1 //! Lowers the AST to the HIR.
3 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
4 //! much like a fold. Where lowering involves a bit more work things get more
5 //! interesting and there are some invariants you should know about. These mostly
6 //! concern spans and IDs.
8 //! Spans are assigned to AST nodes during parsing and then are modified during
9 //! expansion to indicate the origin of a node and the process it went through
10 //! being expanded. IDs are assigned to AST nodes just before lowering.
12 //! For the simpler lowering steps, IDs and spans should be preserved. Unlike
13 //! expansion we do not preserve the process of lowering in the spans, so spans
14 //! should not be modified here. When creating a new node (as opposed to
15 //! 'folding' an existing one), then you create a new ID using `next_id()`.
17 //! You must ensure that IDs are unique. That means that you should only use the
18 //! ID from an AST node in a single HIR node (you can assume that AST node-IDs
19 //! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
20 //! If you do, you must then set the new node's ID to a fresh one.
22 //! Spans are used for error messages and for tools to map semantics back to
23 //! source code. It is therefore not as important with spans as IDs to be strict
24 //! about use (you can't break the compiler by screwing up a span). Obviously, a
25 //! HIR node can only have a single span. But multiple nodes can have the same
26 //! span and spans don't need to be kept in order, etc. Where code is preserved
27 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
28 //! new it is probably best to give a span for the whole AST node being lowered.
29 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
30 //! get confused if the spans from leaf AST nodes occur in multiple places
31 //! in the HIR, especially for multiple identifiers.
33 #![feature(array_value_iter)]
34 #![feature(crate_visibility_modifier)]
36 use rustc::arena::Arena;
37 use rustc::dep_graph::DepGraph;
38 use rustc::hir::map::definitions::{DefKey, DefPathData, Definitions};
39 use rustc::hir::map::Map;
40 use rustc::{bug, span_bug};
41 use rustc_data_structures::captures::Captures;
42 use rustc_data_structures::fx::FxHashSet;
43 use rustc_data_structures::sync::Lrc;
44 use rustc_error_codes::*;
45 use rustc_errors::struct_span_err;
47 use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
48 use rustc_hir::def_id::{DefId, DefIdMap, DefIndex, CRATE_DEF_INDEX};
49 use rustc_hir::intravisit;
50 use rustc_hir::{ConstArg, GenericArg, ParamName};
51 use rustc_index::vec::IndexVec;
52 use rustc_session::config::nightly_options;
53 use rustc_session::lint::{builtin, BuiltinLintDiagnostics, LintBuffer};
54 use rustc_session::node_id::NodeMap;
55 use rustc_session::Session;
56 use rustc_span::hygiene::ExpnId;
57 use rustc_span::source_map::{respan, DesugaringKind, ExpnData, ExpnKind};
58 use rustc_span::symbol::{kw, sym, Symbol};
63 use syntax::print::pprust;
64 use syntax::sess::ParseSess;
65 use syntax::token::{self, Nonterminal, Token};
66 use syntax::tokenstream::{TokenStream, TokenTree};
67 use syntax::visit::{self, Visitor};
68 use syntax::walk_list;
70 use log::{debug, trace};
71 use smallvec::{smallvec, SmallVec};
72 use std::collections::BTreeMap;
75 macro_rules! arena_vec {
76 ($this:expr; $($x:expr),*) => ({
78 $this.arena.alloc_from_iter(std::array::IntoIter::new(a))
87 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
89 struct LoweringContext<'a, 'hir: 'a> {
90 crate_root: Option<Symbol>,
92 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
95 resolver: &'a mut dyn Resolver,
97 /// HACK(Centril): there is a cyclic dependency between the parser and lowering
98 /// if we don't have this function pointer. To avoid that dependency so that
99 /// librustc is independent of the parser, we use dynamic dispatch here.
100 nt_to_tokenstream: NtToTokenstream,
102 /// Used to allocate HIR nodes
103 arena: &'hir Arena<'hir>,
105 /// The items being lowered are collected here.
106 items: BTreeMap<hir::HirId, hir::Item<'hir>>,
108 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem<'hir>>,
109 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem<'hir>>,
110 bodies: BTreeMap<hir::BodyId, hir::Body<'hir>>,
111 exported_macros: Vec<hir::MacroDef<'hir>>,
112 non_exported_macro_attrs: Vec<ast::Attribute>,
114 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
116 modules: BTreeMap<hir::HirId, hir::ModuleItems>,
118 generator_kind: Option<hir::GeneratorKind>,
120 /// Used to get the current `fn`'s def span to point to when using `await`
121 /// outside of an `async fn`.
122 current_item: Option<Span>,
124 catch_scopes: Vec<NodeId>,
125 loop_scopes: Vec<NodeId>,
126 is_in_loop_condition: bool,
127 is_in_trait_impl: bool,
128 is_in_dyn_type: bool,
130 /// What to do when we encounter either an "anonymous lifetime
131 /// reference". The term "anonymous" is meant to encompass both
132 /// `'_` lifetimes as well as fully elided cases where nothing is
133 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
134 anonymous_lifetime_mode: AnonymousLifetimeMode,
136 /// Used to create lifetime definitions from in-band lifetime usages.
137 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
138 /// When a named lifetime is encountered in a function or impl header and
139 /// has not been defined
140 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
141 /// to this list. The results of this list are then added to the list of
142 /// lifetime definitions in the corresponding impl or function generics.
143 lifetimes_to_define: Vec<(Span, ParamName)>,
145 /// `true` if in-band lifetimes are being collected. This is used to
146 /// indicate whether or not we're in a place where new lifetimes will result
147 /// in in-band lifetime definitions, such a function or an impl header,
148 /// including implicit lifetimes from `impl_header_lifetime_elision`.
149 is_collecting_in_band_lifetimes: bool,
151 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
152 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
153 /// against this list to see if it is already in-scope, or if a definition
154 /// needs to be created for it.
156 /// We always store a `modern()` version of the param-name in this
158 in_scope_lifetimes: Vec<ParamName>,
160 current_module: hir::HirId,
162 type_def_lifetime_params: DefIdMap<usize>,
164 current_hir_id_owner: Vec<(DefIndex, u32)>,
165 item_local_id_counters: NodeMap<u32>,
166 node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
168 allow_try_trait: Option<Lrc<[Symbol]>>,
169 allow_gen_future: Option<Lrc<[Symbol]>>,
173 fn def_key(&mut self, id: DefId) -> DefKey;
175 fn item_generics_num_lifetimes(&self, def: DefId, sess: &Session) -> usize;
177 /// Obtains resolution for a `NodeId` with a single resolution.
178 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
180 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
181 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
183 /// Obtains resolution for a label with the given `NodeId`.
184 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
186 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
187 /// This should only return `None` during testing.
188 fn definitions(&mut self) -> &mut Definitions;
190 /// Given suffix `["b", "c", "d"]`, creates an AST path for `[::crate_root]::b::c::d` and
191 /// resolves it based on `is_value`.
195 crate_root: Option<Symbol>,
196 components: &[Symbol],
198 ) -> (ast::Path, Res<NodeId>);
200 fn lint_buffer(&mut self) -> &mut LintBuffer;
202 fn next_node_id(&mut self) -> NodeId;
205 type NtToTokenstream = fn(&Nonterminal, &ParseSess, Span) -> TokenStream;
207 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
208 /// and if so, what meaning it has.
210 enum ImplTraitContext<'b, 'a> {
211 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
212 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
213 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
215 /// Newly generated parameters should be inserted into the given `Vec`.
216 Universal(&'b mut Vec<hir::GenericParam<'a>>),
218 /// Treat `impl Trait` as shorthand for a new opaque type.
219 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
220 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
222 /// We optionally store a `DefId` for the parent item here so we can look up necessary
223 /// information later. It is `None` when no information about the context should be stored
224 /// (e.g., for consts and statics).
225 OpaqueTy(Option<DefId> /* fn def-ID */),
227 /// `impl Trait` is not accepted in this position.
228 Disallowed(ImplTraitPosition),
231 /// Position in which `impl Trait` is disallowed.
232 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
233 enum ImplTraitPosition {
234 /// Disallowed in `let` / `const` / `static` bindings.
237 /// All other posiitons.
241 impl<'a> ImplTraitContext<'_, 'a> {
243 fn disallowed() -> Self {
244 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
247 fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
248 use self::ImplTraitContext::*;
250 Universal(params) => Universal(params),
251 OpaqueTy(fn_def_id) => OpaqueTy(*fn_def_id),
252 Disallowed(pos) => Disallowed(*pos),
257 pub fn lower_crate<'a, 'hir>(
259 dep_graph: &'a DepGraph,
261 resolver: &'a mut dyn Resolver,
262 nt_to_tokenstream: NtToTokenstream,
263 arena: &'hir Arena<'hir>,
264 ) -> hir::Crate<'hir> {
265 // We're constructing the HIR here; we don't care what we will
266 // read, since we haven't even constructed the *input* to
268 dep_graph.assert_ignored();
270 let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
273 crate_root: sess.parse_sess.injected_crate_name.try_get().copied(),
278 items: BTreeMap::new(),
279 trait_items: BTreeMap::new(),
280 impl_items: BTreeMap::new(),
281 bodies: BTreeMap::new(),
282 trait_impls: BTreeMap::new(),
283 modules: BTreeMap::new(),
284 exported_macros: Vec::new(),
285 non_exported_macro_attrs: Vec::new(),
286 catch_scopes: Vec::new(),
287 loop_scopes: Vec::new(),
288 is_in_loop_condition: false,
289 is_in_trait_impl: false,
290 is_in_dyn_type: false,
291 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
292 type_def_lifetime_params: Default::default(),
293 current_module: hir::CRATE_HIR_ID,
294 current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
295 item_local_id_counters: Default::default(),
296 node_id_to_hir_id: IndexVec::new(),
297 generator_kind: None,
299 lifetimes_to_define: Vec::new(),
300 is_collecting_in_band_lifetimes: false,
301 in_scope_lifetimes: Vec::new(),
302 allow_try_trait: Some([sym::try_trait][..].into()),
303 allow_gen_future: Some([sym::gen_future][..].into()),
308 #[derive(Copy, Clone, PartialEq)]
310 /// Any path in a type context.
312 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
314 /// The `module::Type` in `module::Type::method` in an expression.
318 enum ParenthesizedGenericArgs {
323 /// What to do when we encounter an **anonymous** lifetime
324 /// reference. Anonymous lifetime references come in two flavors. You
325 /// have implicit, or fully elided, references to lifetimes, like the
326 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
327 /// or `Ref<'_, T>`. These often behave the same, but not always:
329 /// - certain usages of implicit references are deprecated, like
330 /// `Ref<T>`, and we sometimes just give hard errors in those cases
332 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
333 /// the same as `Box<dyn Foo + '_>`.
335 /// We describe the effects of the various modes in terms of three cases:
337 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
338 /// of a `&` (e.g., the missing lifetime in something like `&T`)
339 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
340 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
341 /// elided bounds follow special rules. Note that this only covers
342 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
343 /// '_>` is a case of "modern" elision.
344 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
345 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
346 /// non-deprecated equivalent.
348 /// Currently, the handling of lifetime elision is somewhat spread out
349 /// between HIR lowering and -- as described below -- the
350 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
351 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
352 /// everything into HIR lowering.
353 #[derive(Copy, Clone, Debug)]
354 enum AnonymousLifetimeMode {
355 /// For **Modern** cases, create a new anonymous region parameter
356 /// and reference that.
358 /// For **Dyn Bound** cases, pass responsibility to
359 /// `resolve_lifetime` code.
361 /// For **Deprecated** cases, report an error.
364 /// Give a hard error when either `&` or `'_` is written. Used to
365 /// rule out things like `where T: Foo<'_>`. Does not imply an
366 /// error on default object bounds (e.g., `Box<dyn Foo>`).
369 /// Pass responsibility to `resolve_lifetime` code for all cases.
373 struct ImplTraitTypeIdVisitor<'a> {
374 ids: &'a mut SmallVec<[NodeId; 1]>,
377 impl Visitor<'_> for ImplTraitTypeIdVisitor<'_> {
378 fn visit_ty(&mut self, ty: &Ty) {
380 TyKind::Typeof(_) | TyKind::BareFn(_) => return,
382 TyKind::ImplTrait(id, _) => self.ids.push(id),
385 visit::walk_ty(self, ty);
388 fn visit_path_segment(&mut self, path_span: Span, path_segment: &PathSegment) {
389 if let Some(ref p) = path_segment.args {
390 if let GenericArgs::Parenthesized(_) = **p {
394 visit::walk_path_segment(self, path_span, path_segment)
398 impl<'a, 'hir> LoweringContext<'a, 'hir> {
399 fn lower_crate(mut self, c: &Crate) -> hir::Crate<'hir> {
400 /// Full-crate AST visitor that inserts into a fresh
401 /// `LoweringContext` any information that may be
402 /// needed from arbitrary locations in the crate,
403 /// e.g., the number of lifetime generic parameters
404 /// declared for every type and trait definition.
405 struct MiscCollector<'tcx, 'lowering, 'hir> {
406 lctx: &'tcx mut LoweringContext<'lowering, 'hir>,
407 hir_id_owner: Option<NodeId>,
410 impl MiscCollector<'_, '_, '_> {
411 fn allocate_use_tree_hir_id_counters(&mut self, tree: &UseTree, owner: DefIndex) {
413 UseTreeKind::Simple(_, id1, id2) => {
414 for &id in &[id1, id2] {
415 self.lctx.resolver.definitions().create_def_with_parent(
422 self.lctx.allocate_hir_id_counter(id);
425 UseTreeKind::Glob => (),
426 UseTreeKind::Nested(ref trees) => {
427 for &(ref use_tree, id) in trees {
428 let hir_id = self.lctx.allocate_hir_id_counter(id);
429 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
435 fn with_hir_id_owner<T>(
437 owner: Option<NodeId>,
438 f: impl FnOnce(&mut Self) -> T,
440 let old = mem::replace(&mut self.hir_id_owner, owner);
442 self.hir_id_owner = old;
447 impl<'tcx> Visitor<'tcx> for MiscCollector<'tcx, '_, '_> {
448 fn visit_pat(&mut self, p: &'tcx Pat) {
449 if let PatKind::Paren(..) | PatKind::Rest = p.kind {
450 // Doesn't generate a HIR node
451 } else if let Some(owner) = self.hir_id_owner {
452 self.lctx.lower_node_id_with_owner(p.id, owner);
455 visit::walk_pat(self, p)
458 fn visit_item(&mut self, item: &'tcx Item) {
459 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
462 ItemKind::Struct(_, ref generics)
463 | ItemKind::Union(_, ref generics)
464 | ItemKind::Enum(_, ref generics)
465 | ItemKind::TyAlias(_, ref generics)
466 | ItemKind::Trait(_, _, ref generics, ..) => {
467 let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
471 .filter(|param| match param.kind {
472 ast::GenericParamKind::Lifetime { .. } => true,
476 self.lctx.type_def_lifetime_params.insert(def_id, count);
478 ItemKind::Use(ref use_tree) => {
479 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
484 self.with_hir_id_owner(Some(item.id), |this| {
485 visit::walk_item(this, item);
489 fn visit_trait_item(&mut self, item: &'tcx AssocItem) {
490 self.lctx.allocate_hir_id_counter(item.id);
493 AssocItemKind::Fn(_, None) => {
494 // Ignore patterns in trait methods without bodies
495 self.with_hir_id_owner(None, |this| visit::walk_trait_item(this, item));
497 _ => self.with_hir_id_owner(Some(item.id), |this| {
498 visit::walk_trait_item(this, item);
503 fn visit_impl_item(&mut self, item: &'tcx AssocItem) {
504 self.lctx.allocate_hir_id_counter(item.id);
505 self.with_hir_id_owner(Some(item.id), |this| {
506 visit::walk_impl_item(this, item);
510 fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) {
511 // Ignore patterns in foreign items
512 self.with_hir_id_owner(None, |this| visit::walk_foreign_item(this, i));
515 fn visit_ty(&mut self, t: &'tcx Ty) {
517 // Mirrors the case in visit::walk_ty
518 TyKind::BareFn(ref f) => {
519 walk_list!(self, visit_generic_param, &f.generic_params);
520 // Mirrors visit::walk_fn_decl
521 for parameter in &f.decl.inputs {
522 // We don't lower the ids of argument patterns
523 self.with_hir_id_owner(None, |this| {
524 this.visit_pat(¶meter.pat);
526 self.visit_ty(¶meter.ty)
528 self.visit_fn_ret_ty(&f.decl.output)
530 _ => visit::walk_ty(self, t),
535 self.lower_node_id(CRATE_NODE_ID);
536 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
538 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
539 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
541 let module = self.lower_mod(&c.module);
542 let attrs = self.lower_attrs(&c.attrs);
543 let body_ids = body_ids(&self.bodies);
545 self.resolver.definitions().init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
551 exported_macros: self.arena.alloc_from_iter(self.exported_macros),
552 non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs),
554 trait_items: self.trait_items,
555 impl_items: self.impl_items,
558 trait_impls: self.trait_impls,
559 modules: self.modules,
563 fn insert_item(&mut self, item: hir::Item<'hir>) {
564 let id = item.hir_id;
565 // FIXME: Use `debug_asset-rt`.
566 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
567 self.items.insert(id, item);
568 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
571 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
572 // Set up the counter if needed.
573 self.item_local_id_counters.entry(owner).or_insert(0);
574 // Always allocate the first `HirId` for the owner itself.
575 let lowered = self.lower_node_id_with_owner(owner, owner);
576 debug_assert_eq!(lowered.local_id.as_u32(), 0);
580 fn lower_node_id_generic(
583 alloc_hir_id: impl FnOnce(&mut Self) -> hir::HirId,
585 if ast_node_id == DUMMY_NODE_ID {
586 return hir::DUMMY_HIR_ID;
589 let min_size = ast_node_id.as_usize() + 1;
591 if min_size > self.node_id_to_hir_id.len() {
592 self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
595 let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
597 if existing_hir_id == hir::DUMMY_HIR_ID {
598 // Generate a new `HirId`.
599 let hir_id = alloc_hir_id(self);
600 self.node_id_to_hir_id[ast_node_id] = hir_id;
608 fn with_hir_id_owner<T>(&mut self, owner: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
610 .item_local_id_counters
611 .insert(owner, HIR_ID_COUNTER_LOCKED)
612 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
613 let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
614 self.current_hir_id_owner.push((def_index, counter));
616 let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
618 debug_assert!(def_index == new_def_index);
619 debug_assert!(new_counter >= counter);
621 let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap();
622 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
626 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
627 /// the `LoweringContext`'s `NodeId => HirId` map.
628 /// Take care not to call this method if the resulting `HirId` is then not
629 /// actually used in the HIR, as that would trigger an assertion in the
630 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
631 /// properly. Calling the method twice with the same `NodeId` is fine though.
632 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
633 self.lower_node_id_generic(ast_node_id, |this| {
634 let &mut (def_index, ref mut local_id_counter) =
635 this.current_hir_id_owner.last_mut().unwrap();
636 let local_id = *local_id_counter;
637 *local_id_counter += 1;
638 hir::HirId { owner: def_index, local_id: hir::ItemLocalId::from_u32(local_id) }
642 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
643 self.lower_node_id_generic(ast_node_id, |this| {
644 let local_id_counter = this
645 .item_local_id_counters
647 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
648 let local_id = *local_id_counter;
650 // We want to be sure not to modify the counter in the map while it
651 // is also on the stack. Otherwise we'll get lost updates when writing
652 // back from the stack to the map.
653 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
655 *local_id_counter += 1;
656 let def_index = this.resolver.definitions().opt_def_index(owner).expect(
657 "you forgot to call `create_def_with_parent` or are lowering node-IDs \
658 that do not belong to the current owner",
661 hir::HirId { owner: def_index, local_id: hir::ItemLocalId::from_u32(local_id) }
665 fn next_id(&mut self) -> hir::HirId {
666 let node_id = self.resolver.next_node_id();
667 self.lower_node_id(node_id)
670 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
672 self.lower_node_id_generic(id, |_| {
673 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
678 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
679 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
680 if pr.unresolved_segments() != 0 {
681 bug!("path not fully resolved: {:?}", pr);
687 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
688 self.resolver.get_import_res(id).present_items()
691 fn diagnostic(&self) -> &rustc_errors::Handler {
692 self.sess.diagnostic()
695 /// Reuses the span but adds information like the kind of the desugaring and features that are
696 /// allowed inside this span.
697 fn mark_span_with_reason(
699 reason: DesugaringKind,
701 allow_internal_unstable: Option<Lrc<[Symbol]>>,
703 span.fresh_expansion(ExpnData {
704 allow_internal_unstable,
705 ..ExpnData::default(ExpnKind::Desugaring(reason), span, self.sess.edition())
709 fn with_anonymous_lifetime_mode<R>(
711 anonymous_lifetime_mode: AnonymousLifetimeMode,
712 op: impl FnOnce(&mut Self) -> R,
715 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
716 anonymous_lifetime_mode,
718 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
719 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
720 let result = op(self);
721 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
723 "with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
724 old_anonymous_lifetime_mode
729 /// Creates a new `hir::GenericParam` for every new lifetime and
730 /// type parameter encountered while evaluating `f`. Definitions
731 /// are created with the parent provided. If no `parent_id` is
732 /// provided, no definitions will be returned.
734 /// Presuming that in-band lifetimes are enabled, then
735 /// `self.anonymous_lifetime_mode` will be updated to match the
736 /// parameter while `f` is running (and restored afterwards).
737 fn collect_in_band_defs<T>(
740 anonymous_lifetime_mode: AnonymousLifetimeMode,
741 f: impl FnOnce(&mut Self) -> (Vec<hir::GenericParam<'hir>>, T),
742 ) -> (Vec<hir::GenericParam<'hir>>, T) {
743 assert!(!self.is_collecting_in_band_lifetimes);
744 assert!(self.lifetimes_to_define.is_empty());
745 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
747 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
748 self.is_collecting_in_band_lifetimes = true;
750 let (in_band_ty_params, res) = f(self);
752 self.is_collecting_in_band_lifetimes = false;
753 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
755 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
757 let params = lifetimes_to_define
759 .map(|(span, hir_name)| self.lifetime_to_generic_param(span, hir_name, parent_id.index))
760 .chain(in_band_ty_params.into_iter())
766 /// Converts a lifetime into a new generic parameter.
767 fn lifetime_to_generic_param(
771 parent_index: DefIndex,
772 ) -> hir::GenericParam<'hir> {
773 let node_id = self.resolver.next_node_id();
775 // Get the name we'll use to make the def-path. Note
776 // that collisions are ok here and this shouldn't
777 // really show up for end-user.
778 let (str_name, kind) = match hir_name {
779 ParamName::Plain(ident) => (ident.name, hir::LifetimeParamKind::InBand),
780 ParamName::Fresh(_) => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Elided),
781 ParamName::Error => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Error),
784 // Add a definition for the in-band lifetime def.
785 self.resolver.definitions().create_def_with_parent(
788 DefPathData::LifetimeNs(str_name),
794 hir_id: self.lower_node_id(node_id),
799 pure_wrt_drop: false,
800 kind: hir::GenericParamKind::Lifetime { kind },
804 /// When there is a reference to some lifetime `'a`, and in-band
805 /// lifetimes are enabled, then we want to push that lifetime into
806 /// the vector of names to define later. In that case, it will get
807 /// added to the appropriate generics.
808 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
809 if !self.is_collecting_in_band_lifetimes {
813 if !self.sess.features_untracked().in_band_lifetimes {
817 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.modern())) {
821 let hir_name = ParamName::Plain(ident);
823 if self.lifetimes_to_define.iter().any(|(_, lt_name)| lt_name.modern() == hir_name.modern())
828 self.lifetimes_to_define.push((ident.span, hir_name));
831 /// When we have either an elided or `'_` lifetime in an impl
832 /// header, we convert it to an in-band lifetime.
833 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
834 assert!(self.is_collecting_in_band_lifetimes);
835 let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
836 let hir_name = ParamName::Fresh(index);
837 self.lifetimes_to_define.push((span, hir_name));
841 // Evaluates `f` with the lifetimes in `params` in-scope.
842 // This is used to track which lifetimes have already been defined, and
843 // which are new in-band lifetimes that need to have a definition created
845 fn with_in_scope_lifetime_defs<T>(
847 params: &[GenericParam],
848 f: impl FnOnce(&mut Self) -> T,
850 let old_len = self.in_scope_lifetimes.len();
851 let lt_def_names = params.iter().filter_map(|param| match param.kind {
852 GenericParamKind::Lifetime { .. } => Some(ParamName::Plain(param.ident.modern())),
855 self.in_scope_lifetimes.extend(lt_def_names);
859 self.in_scope_lifetimes.truncate(old_len);
863 /// Appends in-band lifetime defs and argument-position `impl
864 /// Trait` defs to the existing set of generics.
866 /// Presuming that in-band lifetimes are enabled, then
867 /// `self.anonymous_lifetime_mode` will be updated to match the
868 /// parameter while `f` is running (and restored afterwards).
869 fn add_in_band_defs<T>(
873 anonymous_lifetime_mode: AnonymousLifetimeMode,
874 f: impl FnOnce(&mut Self, &mut Vec<hir::GenericParam<'hir>>) -> T,
875 ) -> (hir::Generics<'hir>, T) {
876 let (in_band_defs, (mut lowered_generics, res)) =
877 self.with_in_scope_lifetime_defs(&generics.params, |this| {
878 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
879 let mut params = Vec::new();
880 // Note: it is necessary to lower generics *before* calling `f`.
881 // When lowering `async fn`, there's a final step when lowering
882 // the return type that assumes that all in-scope lifetimes have
883 // already been added to either `in_scope_lifetimes` or
884 // `lifetimes_to_define`. If we swapped the order of these two,
885 // in-band-lifetimes introduced by generics or where-clauses
886 // wouldn't have been added yet.
888 this.lower_generics_mut(generics, ImplTraitContext::Universal(&mut params));
889 let res = f(this, &mut params);
890 (params, (generics, res))
894 let mut lowered_params: Vec<_> =
895 lowered_generics.params.into_iter().chain(in_band_defs).collect();
897 // FIXME(const_generics): the compiler doesn't always cope with
898 // unsorted generic parameters at the moment, so we make sure
899 // that they're ordered correctly here for now. (When we chain
900 // the `in_band_defs`, we might make the order unsorted.)
901 lowered_params.sort_by_key(|param| match param.kind {
902 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
903 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
904 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
907 lowered_generics.params = lowered_params.into();
909 let lowered_generics = lowered_generics.into_generics(self.arena);
910 (lowered_generics, res)
913 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
914 let was_in_dyn_type = self.is_in_dyn_type;
915 self.is_in_dyn_type = in_scope;
917 let result = f(self);
919 self.is_in_dyn_type = was_in_dyn_type;
924 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
925 let was_in_loop_condition = self.is_in_loop_condition;
926 self.is_in_loop_condition = false;
928 let catch_scopes = mem::take(&mut self.catch_scopes);
929 let loop_scopes = mem::take(&mut self.loop_scopes);
931 self.catch_scopes = catch_scopes;
932 self.loop_scopes = loop_scopes;
934 self.is_in_loop_condition = was_in_loop_condition;
939 fn lower_attrs(&mut self, attrs: &[Attribute]) -> &'hir [Attribute] {
940 self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)))
943 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
944 // Note that we explicitly do not walk the path. Since we don't really
945 // lower attributes (we use the AST version) there is nowhere to keep
946 // the `HirId`s. We don't actually need HIR version of attributes anyway.
947 let kind = match attr.kind {
948 AttrKind::Normal(ref item) => AttrKind::Normal(AttrItem {
949 path: item.path.clone(),
950 args: self.lower_mac_args(&item.args),
952 AttrKind::DocComment(comment) => AttrKind::DocComment(comment),
955 Attribute { kind, id: attr.id, style: attr.style, span: attr.span }
958 fn lower_mac_args(&mut self, args: &MacArgs) -> MacArgs {
960 MacArgs::Empty => MacArgs::Empty,
961 MacArgs::Delimited(dspan, delim, ref tokens) => {
962 MacArgs::Delimited(dspan, delim, self.lower_token_stream(tokens.clone()))
964 MacArgs::Eq(eq_span, ref tokens) => {
965 MacArgs::Eq(eq_span, self.lower_token_stream(tokens.clone()))
970 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
971 tokens.into_trees().flat_map(|tree| self.lower_token_tree(tree).into_trees()).collect()
974 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
976 TokenTree::Token(token) => self.lower_token(token),
977 TokenTree::Delimited(span, delim, tts) => {
978 TokenTree::Delimited(span, delim, self.lower_token_stream(tts)).into()
983 fn lower_token(&mut self, token: Token) -> TokenStream {
985 token::Interpolated(nt) => {
986 let tts = (self.nt_to_tokenstream)(&nt, &self.sess.parse_sess, token.span);
987 self.lower_token_stream(tts)
989 _ => TokenTree::Token(token).into(),
993 /// Given an associated type constraint like one of these:
996 /// T: Iterator<Item: Debug>
998 /// T: Iterator<Item = Debug>
1002 /// returns a `hir::TypeBinding` representing `Item`.
1003 fn lower_assoc_ty_constraint(
1005 constraint: &AssocTyConstraint,
1006 itctx: ImplTraitContext<'_, 'hir>,
1007 ) -> hir::TypeBinding<'hir> {
1008 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
1010 let kind = match constraint.kind {
1011 AssocTyConstraintKind::Equality { ref ty } => {
1012 hir::TypeBindingKind::Equality { ty: self.lower_ty(ty, itctx) }
1014 AssocTyConstraintKind::Bound { ref bounds } => {
1015 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1016 let (desugar_to_impl_trait, itctx) = match itctx {
1017 // We are in the return position:
1019 // fn foo() -> impl Iterator<Item: Debug>
1023 // fn foo() -> impl Iterator<Item = impl Debug>
1024 ImplTraitContext::OpaqueTy(_) => (true, itctx),
1026 // We are in the argument position, but within a dyn type:
1028 // fn foo(x: dyn Iterator<Item: Debug>)
1032 // fn foo(x: dyn Iterator<Item = impl Debug>)
1033 ImplTraitContext::Universal(_) if self.is_in_dyn_type => (true, itctx),
1035 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1036 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1037 // "impl trait context" to permit `impl Debug` in this position (it desugars
1038 // then to an opaque type).
1040 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1041 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1042 (true, ImplTraitContext::OpaqueTy(None))
1045 // We are in the parameter position, but not within a dyn type:
1047 // fn foo(x: impl Iterator<Item: Debug>)
1049 // so we leave it as is and this gets expanded in astconv to a bound like
1050 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1052 _ => (false, itctx),
1055 if desugar_to_impl_trait {
1056 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1057 // constructing the HIR for `impl bounds...` and then lowering that.
1059 let impl_trait_node_id = self.resolver.next_node_id();
1060 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1061 self.resolver.definitions().create_def_with_parent(
1064 DefPathData::ImplTrait,
1069 self.with_dyn_type_scope(false, |this| {
1070 let node_id = this.resolver.next_node_id();
1071 let ty = this.lower_ty(
1074 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1075 span: constraint.span,
1080 hir::TypeBindingKind::Equality { ty }
1083 // Desugar `AssocTy: Bounds` into a type binding where the
1084 // later desugars into a trait predicate.
1085 let bounds = self.lower_param_bounds(bounds, itctx);
1087 hir::TypeBindingKind::Constraint { bounds }
1093 hir_id: self.lower_node_id(constraint.id),
1094 ident: constraint.ident,
1096 span: constraint.span,
1100 fn lower_generic_arg(
1102 arg: &ast::GenericArg,
1103 itctx: ImplTraitContext<'_, 'hir>,
1104 ) -> hir::GenericArg<'hir> {
1106 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1107 ast::GenericArg::Type(ty) => {
1108 // We parse const arguments as path types as we cannot distiguish them durring
1109 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1110 // type and value namespaces. If we resolved the path in the value namespace, we
1111 // transform it into a generic const argument.
1112 if let TyKind::Path(ref qself, ref path) = ty.kind {
1113 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1114 let res = partial_res.base_res();
1115 if !res.matches_ns(Namespace::TypeNS) {
1117 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1121 // Construct a AnonConst where the expr is the "ty"'s path.
1123 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1124 let node_id = self.resolver.next_node_id();
1126 // Add a definition for the in-band const def.
1127 self.resolver.definitions().create_def_with_parent(
1130 DefPathData::AnonConst,
1135 let path_expr = Expr {
1137 kind: ExprKind::Path(qself.clone(), path.clone()),
1139 attrs: AttrVec::new(),
1142 let ct = self.with_new_scopes(|this| hir::AnonConst {
1143 hir_id: this.lower_node_id(node_id),
1144 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1146 return GenericArg::Const(ConstArg { value: ct, span: ty.span });
1150 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1152 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1153 value: self.lower_anon_const(&ct),
1154 span: ct.value.span,
1159 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1160 self.arena.alloc(self.lower_ty_direct(t, itctx))
1166 qself: &Option<QSelf>,
1168 param_mode: ParamMode,
1169 itctx: ImplTraitContext<'_, 'hir>,
1170 ) -> hir::Ty<'hir> {
1171 let id = self.lower_node_id(t.id);
1172 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1173 let ty = self.ty_path(id, t.span, qpath);
1174 if let hir::TyKind::TraitObject(..) = ty.kind {
1175 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1180 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1181 hir::Ty { hir_id: self.next_id(), kind, span }
1184 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1185 self.ty(span, hir::TyKind::Tup(tys))
1188 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
1189 let kind = match t.kind {
1190 TyKind::Infer => hir::TyKind::Infer,
1191 TyKind::Err => hir::TyKind::Err,
1192 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1193 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1194 TyKind::Rptr(ref region, ref mt) => {
1195 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1196 let lifetime = match *region {
1197 Some(ref lt) => self.lower_lifetime(lt),
1198 None => self.elided_ref_lifetime(span),
1200 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1202 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| {
1203 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
1204 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1205 generic_params: this.lower_generic_params(
1207 &NodeMap::default(),
1208 ImplTraitContext::disallowed(),
1210 unsafety: f.unsafety,
1211 abi: this.lower_extern(f.ext),
1212 decl: this.lower_fn_decl(&f.decl, None, false, None),
1213 param_names: this.lower_fn_params_to_names(&f.decl),
1217 TyKind::Never => hir::TyKind::Never,
1218 TyKind::Tup(ref tys) => {
1219 hir::TyKind::Tup(self.arena.alloc_from_iter(
1220 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1223 TyKind::Paren(ref ty) => {
1224 return self.lower_ty_direct(ty, itctx);
1226 TyKind::Path(ref qself, ref path) => {
1227 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1229 TyKind::ImplicitSelf => {
1230 let res = self.expect_full_res(t.id);
1231 let res = self.lower_res(res);
1232 hir::TyKind::Path(hir::QPath::Resolved(
1234 self.arena.alloc(hir::Path {
1236 segments: arena_vec![self; hir::PathSegment::from_ident(
1237 Ident::with_dummy_span(kw::SelfUpper)
1243 TyKind::Array(ref ty, ref length) => {
1244 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1246 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1247 TyKind::TraitObject(ref bounds, kind) => {
1248 let mut lifetime_bound = None;
1249 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1251 this.arena.alloc_from_iter(bounds.iter().filter_map(
1252 |bound| match *bound {
1253 GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1254 Some(this.lower_poly_trait_ref(ty, itctx.reborrow()))
1256 GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1257 GenericBound::Outlives(ref lifetime) => {
1258 if lifetime_bound.is_none() {
1259 lifetime_bound = Some(this.lower_lifetime(lifetime));
1265 let lifetime_bound =
1266 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1267 (bounds, lifetime_bound)
1269 if kind != TraitObjectSyntax::Dyn {
1270 self.maybe_lint_bare_trait(t.span, t.id, false);
1272 hir::TyKind::TraitObject(bounds, lifetime_bound)
1274 TyKind::ImplTrait(def_node_id, ref bounds) => {
1277 ImplTraitContext::OpaqueTy(fn_def_id) => {
1278 self.lower_opaque_impl_trait(span, fn_def_id, def_node_id, |this| {
1279 this.lower_param_bounds(bounds, itctx)
1282 ImplTraitContext::Universal(in_band_ty_params) => {
1283 // Add a definition for the in-band `Param`.
1285 self.resolver.definitions().opt_def_index(def_node_id).unwrap();
1287 let hir_bounds = self.lower_param_bounds(
1289 ImplTraitContext::Universal(in_band_ty_params),
1291 // Set the name to `impl Bound1 + Bound2`.
1292 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1293 in_band_ty_params.push(hir::GenericParam {
1294 hir_id: self.lower_node_id(def_node_id),
1295 name: ParamName::Plain(ident),
1296 pure_wrt_drop: false,
1300 kind: hir::GenericParamKind::Type {
1302 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1306 hir::TyKind::Path(hir::QPath::Resolved(
1308 self.arena.alloc(hir::Path {
1310 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1311 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1315 ImplTraitContext::Disallowed(pos) => {
1316 let allowed_in = if self.sess.features_untracked().impl_trait_in_bindings {
1317 "bindings or function and inherent method return types"
1319 "function and inherent method return types"
1321 let mut err = struct_span_err!(
1325 "`impl Trait` not allowed outside of {}",
1328 if pos == ImplTraitPosition::Binding && nightly_options::is_nightly_build()
1331 "add `#![feature(impl_trait_in_bindings)]` to the crate \
1332 attributes to enable",
1340 TyKind::Mac(_) => bug!("`TyKind::Mac` should have been expanded by now"),
1341 TyKind::CVarArgs => {
1342 self.sess.delay_span_bug(
1344 "`TyKind::CVarArgs` should have been handled elsewhere",
1350 hir::Ty { kind, span: t.span, hir_id: self.lower_node_id(t.id) }
1353 fn lower_opaque_impl_trait(
1356 fn_def_id: Option<DefId>,
1357 opaque_ty_node_id: NodeId,
1358 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1359 ) -> hir::TyKind<'hir> {
1361 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1362 fn_def_id, opaque_ty_node_id, span,
1365 // Make sure we know that some funky desugaring has been going on here.
1366 // This is a first: there is code in other places like for loop
1367 // desugaring that explicitly states that we don't want to track that.
1368 // Not tracking it makes lints in rustc and clippy very fragile, as
1369 // frequently opened issues show.
1370 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1372 let opaque_ty_def_index =
1373 self.resolver.definitions().opt_def_index(opaque_ty_node_id).unwrap();
1375 self.allocate_hir_id_counter(opaque_ty_node_id);
1377 let hir_bounds = self.with_hir_id_owner(opaque_ty_node_id, lower_bounds);
1379 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1381 opaque_ty_def_index,
1385 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes,);
1387 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs,);
1389 self.with_hir_id_owner(opaque_ty_node_id, move |lctx| {
1390 let opaque_ty_item = hir::OpaqueTy {
1391 generics: hir::Generics {
1392 params: lifetime_defs,
1393 where_clause: hir::WhereClause { predicates: &[], span },
1397 impl_trait_fn: fn_def_id,
1398 origin: hir::OpaqueTyOrigin::FnReturn,
1401 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_index);
1403 lctx.generate_opaque_type(opaque_ty_node_id, opaque_ty_item, span, opaque_ty_span);
1405 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1406 hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, lifetimes)
1410 /// Registers a new opaque type with the proper `NodeId`s and
1411 /// returns the lowered node-ID for the opaque type.
1412 fn generate_opaque_type(
1414 opaque_ty_node_id: NodeId,
1415 opaque_ty_item: hir::OpaqueTy<'hir>,
1417 opaque_ty_span: Span,
1419 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1420 let opaque_ty_id = self.lower_node_id(opaque_ty_node_id);
1421 // Generate an `type Foo = impl Trait;` declaration.
1422 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1423 let opaque_ty_item = hir::Item {
1424 hir_id: opaque_ty_id,
1425 ident: Ident::invalid(),
1426 attrs: Default::default(),
1427 kind: opaque_ty_item_kind,
1428 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1429 span: opaque_ty_span,
1432 // Insert the item into the global item list. This usually happens
1433 // automatically for all AST items. But this opaque type item
1434 // does not actually exist in the AST.
1435 self.insert_item(opaque_ty_item);
1439 fn lifetimes_from_impl_trait_bounds(
1441 opaque_ty_id: NodeId,
1442 parent_index: DefIndex,
1443 bounds: hir::GenericBounds<'hir>,
1444 ) -> (&'hir [hir::GenericArg<'hir>], &'hir [hir::GenericParam<'hir>]) {
1446 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
1447 parent_index={:?}, \
1449 opaque_ty_id, parent_index, bounds,
1452 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1453 // appear in the bounds, excluding lifetimes that are created within the bounds.
1454 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1455 struct ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1456 context: &'r mut LoweringContext<'a, 'hir>,
1458 opaque_ty_id: NodeId,
1459 collect_elided_lifetimes: bool,
1460 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1461 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1462 output_lifetimes: Vec<hir::GenericArg<'hir>>,
1463 output_lifetime_params: Vec<hir::GenericParam<'hir>>,
1466 impl<'r, 'a, 'v, 'hir> intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1469 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<'_, Self::Map> {
1470 intravisit::NestedVisitorMap::None
1473 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) {
1474 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1475 if parameters.parenthesized {
1476 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1477 self.collect_elided_lifetimes = false;
1478 intravisit::walk_generic_args(self, span, parameters);
1479 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1481 intravisit::walk_generic_args(self, span, parameters);
1485 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
1486 // Don't collect elided lifetimes used inside of `fn()` syntax.
1487 if let hir::TyKind::BareFn(_) = t.kind {
1488 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1489 self.collect_elided_lifetimes = false;
1491 // Record the "stack height" of `for<'a>` lifetime bindings
1492 // to be able to later fully undo their introduction.
1493 let old_len = self.currently_bound_lifetimes.len();
1494 intravisit::walk_ty(self, t);
1495 self.currently_bound_lifetimes.truncate(old_len);
1497 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1499 intravisit::walk_ty(self, t)
1503 fn visit_poly_trait_ref(
1505 trait_ref: &'v hir::PolyTraitRef<'v>,
1506 modifier: hir::TraitBoundModifier,
1508 // Record the "stack height" of `for<'a>` lifetime bindings
1509 // to be able to later fully undo their introduction.
1510 let old_len = self.currently_bound_lifetimes.len();
1511 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1512 self.currently_bound_lifetimes.truncate(old_len);
1515 fn visit_generic_param(&mut self, param: &'v hir::GenericParam<'v>) {
1516 // Record the introduction of 'a in `for<'a> ...`.
1517 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1518 // Introduce lifetimes one at a time so that we can handle
1519 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1520 let lt_name = hir::LifetimeName::Param(param.name);
1521 self.currently_bound_lifetimes.push(lt_name);
1524 intravisit::walk_generic_param(self, param);
1527 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1528 let name = match lifetime.name {
1529 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1530 if self.collect_elided_lifetimes {
1531 // Use `'_` for both implicit and underscore lifetimes in
1532 // `type Foo<'_> = impl SomeTrait<'_>;`.
1533 hir::LifetimeName::Underscore
1538 hir::LifetimeName::Param(_) => lifetime.name,
1540 // Refers to some other lifetime that is "in
1541 // scope" within the type.
1542 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1544 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1547 if !self.currently_bound_lifetimes.contains(&name)
1548 && !self.already_defined_lifetimes.contains(&name)
1550 self.already_defined_lifetimes.insert(name);
1552 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1553 hir_id: self.context.next_id(),
1554 span: lifetime.span,
1558 let def_node_id = self.context.resolver.next_node_id();
1560 self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
1561 self.context.resolver.definitions().create_def_with_parent(
1564 DefPathData::LifetimeNs(name.ident().name),
1569 let (name, kind) = match name {
1570 hir::LifetimeName::Underscore => (
1571 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1572 hir::LifetimeParamKind::Elided,
1574 hir::LifetimeName::Param(param_name) => {
1575 (param_name, hir::LifetimeParamKind::Explicit)
1577 _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1580 self.output_lifetime_params.push(hir::GenericParam {
1583 span: lifetime.span,
1584 pure_wrt_drop: false,
1587 kind: hir::GenericParamKind::Lifetime { kind },
1593 let mut lifetime_collector = ImplTraitLifetimeCollector {
1595 parent: parent_index,
1597 collect_elided_lifetimes: true,
1598 currently_bound_lifetimes: Vec::new(),
1599 already_defined_lifetimes: FxHashSet::default(),
1600 output_lifetimes: Vec::new(),
1601 output_lifetime_params: Vec::new(),
1604 for bound in bounds {
1605 intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1608 let ImplTraitLifetimeCollector { output_lifetimes, output_lifetime_params, .. } =
1612 self.arena.alloc_from_iter(output_lifetimes),
1613 self.arena.alloc_from_iter(output_lifetime_params),
1617 fn lower_local(&mut self, l: &Local) -> (hir::Local<'hir>, SmallVec<[NodeId; 1]>) {
1618 let mut ids = SmallVec::<[NodeId; 1]>::new();
1619 if self.sess.features_untracked().impl_trait_in_bindings {
1620 if let Some(ref ty) = l.ty {
1621 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1622 visitor.visit_ty(ty);
1625 let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
1626 let ty = l.ty.as_ref().map(|t| {
1629 if self.sess.features_untracked().impl_trait_in_bindings {
1630 ImplTraitContext::OpaqueTy(Some(parent_def_id))
1632 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
1636 let init = l.init.as_ref().map(|e| self.lower_expr(e));
1639 hir_id: self.lower_node_id(l.id),
1641 pat: self.lower_pat(&l.pat),
1644 attrs: l.attrs.clone(),
1645 source: hir::LocalSource::Normal,
1651 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1652 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1653 // as they are not explicit in HIR/Ty function signatures.
1654 // (instead, the `c_variadic` flag is set to `true`)
1655 let mut inputs = &decl.inputs[..];
1656 if decl.c_variadic() {
1657 inputs = &inputs[..inputs.len() - 1];
1659 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1660 PatKind::Ident(_, ident, _) => ident,
1661 _ => Ident::new(kw::Invalid, param.pat.span),
1665 // Lowers a function declaration.
1667 // `decl`: the unlowered (AST) function declaration.
1668 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1669 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1670 // `make_ret_async` is also `Some`.
1671 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1672 // This guards against trait declarations and implementations where `impl Trait` is
1674 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1675 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1676 // return type `impl Trait` item.
1680 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam<'hir>>)>,
1681 impl_trait_return_allow: bool,
1682 make_ret_async: Option<NodeId>,
1683 ) -> &'hir hir::FnDecl<'hir> {
1687 in_band_ty_params: {:?}, \
1688 impl_trait_return_allow: {}, \
1689 make_ret_async: {:?})",
1690 decl, in_band_ty_params, impl_trait_return_allow, make_ret_async,
1692 let lt_mode = if make_ret_async.is_some() {
1693 // In `async fn`, argument-position elided lifetimes
1694 // must be transformed into fresh generic parameters so that
1695 // they can be applied to the opaque `impl Trait` return type.
1696 AnonymousLifetimeMode::CreateParameter
1698 self.anonymous_lifetime_mode
1701 let c_variadic = decl.c_variadic();
1703 // Remember how many lifetimes were already around so that we can
1704 // only look at the lifetime parameters introduced by the arguments.
1705 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
1706 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1707 // as they are not explicit in HIR/Ty function signatures.
1708 // (instead, the `c_variadic` flag is set to `true`)
1709 let mut inputs = &decl.inputs[..];
1711 inputs = &inputs[..inputs.len() - 1];
1713 this.arena.alloc_from_iter(inputs.iter().map(|param| {
1714 if let Some((_, ibty)) = &mut in_band_ty_params {
1715 this.lower_ty_direct(¶m.ty, ImplTraitContext::Universal(ibty))
1717 this.lower_ty_direct(¶m.ty, ImplTraitContext::disallowed())
1722 let output = if let Some(ret_id) = make_ret_async {
1723 self.lower_async_fn_ret_ty(
1725 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1730 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
1731 Some((def_id, _)) if impl_trait_return_allow => hir::FunctionRetTy::Return(
1732 self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(def_id))),
1734 _ => hir::FunctionRetTy::Return(
1735 self.lower_ty(ty, ImplTraitContext::disallowed()),
1738 FunctionRetTy::Default(span) => hir::FunctionRetTy::DefaultReturn(span),
1742 self.arena.alloc(hir::FnDecl {
1746 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1747 let is_mutable_pat = match arg.pat.kind {
1748 PatKind::Ident(BindingMode::ByValue(mt), _, _)
1749 | PatKind::Ident(BindingMode::ByRef(mt), _, _) => mt == Mutability::Mut,
1754 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1755 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1756 // Given we are only considering `ImplicitSelf` types, we needn't consider
1757 // the case where we have a mutable pattern to a reference as that would
1758 // no longer be an `ImplicitSelf`.
1759 TyKind::Rptr(_, ref mt)
1760 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1762 hir::ImplicitSelfKind::MutRef
1764 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1765 hir::ImplicitSelfKind::ImmRef
1767 _ => hir::ImplicitSelfKind::None,
1773 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1774 // combined with the following definition of `OpaqueTy`:
1776 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1778 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1779 // `output`: unlowered output type (`T` in `-> T`)
1780 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1781 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1782 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1783 fn lower_async_fn_ret_ty(
1785 output: &FunctionRetTy,
1787 opaque_ty_node_id: NodeId,
1788 ) -> hir::FunctionRetTy<'hir> {
1790 "lower_async_fn_ret_ty(\
1793 opaque_ty_node_id={:?})",
1794 output, fn_def_id, opaque_ty_node_id,
1797 let span = output.span();
1799 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1801 let opaque_ty_def_index =
1802 self.resolver.definitions().opt_def_index(opaque_ty_node_id).unwrap();
1804 self.allocate_hir_id_counter(opaque_ty_node_id);
1806 // When we create the opaque type for this async fn, it is going to have
1807 // to capture all the lifetimes involved in the signature (including in the
1808 // return type). This is done by introducing lifetime parameters for:
1810 // - all the explicitly declared lifetimes from the impl and function itself;
1811 // - all the elided lifetimes in the fn arguments;
1812 // - all the elided lifetimes in the return type.
1814 // So for example in this snippet:
1817 // impl<'a> Foo<'a> {
1818 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1819 // // ^ '0 ^ '1 ^ '2
1820 // // elided lifetimes used below
1825 // we would create an opaque type like:
1828 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1831 // and we would then desugar `bar` to the equivalent of:
1834 // impl<'a> Foo<'a> {
1835 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1839 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1840 // this is because the elided lifetimes from the return type
1841 // should be figured out using the ordinary elision rules, and
1842 // this desugaring achieves that.
1844 // The variable `input_lifetimes_count` tracks the number of
1845 // lifetime parameters to the opaque type *not counting* those
1846 // lifetimes elided in the return type. This includes those
1847 // that are explicitly declared (`in_scope_lifetimes`) and
1848 // those elided lifetimes we found in the arguments (current
1849 // content of `lifetimes_to_define`). Next, we will process
1850 // the return type, which will cause `lifetimes_to_define` to
1852 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
1854 let (opaque_ty_id, lifetime_params) = self.with_hir_id_owner(opaque_ty_node_id, |this| {
1855 // We have to be careful to get elision right here. The
1856 // idea is that we create a lifetime parameter for each
1857 // lifetime in the return type. So, given a return type
1858 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1859 // Future<Output = &'1 [ &'2 u32 ]>`.
1861 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1862 // hence the elision takes place at the fn site.
1863 let future_bound = this
1864 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::CreateParameter, |this| {
1865 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
1868 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
1870 // Calculate all the lifetimes that should be captured
1871 // by the opaque type. This should include all in-scope
1872 // lifetime parameters, including those defined in-band.
1874 // Note: this must be done after lowering the output type,
1875 // as the output type may introduce new in-band lifetimes.
1876 let lifetime_params: Vec<(Span, ParamName)> = this
1880 .map(|name| (name.ident().span, name))
1881 .chain(this.lifetimes_to_define.iter().cloned())
1884 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
1885 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
1886 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
1888 let generic_params =
1889 this.arena.alloc_from_iter(lifetime_params.iter().map(|(span, hir_name)| {
1890 this.lifetime_to_generic_param(*span, *hir_name, opaque_ty_def_index)
1893 let opaque_ty_item = hir::OpaqueTy {
1894 generics: hir::Generics {
1895 params: generic_params,
1896 where_clause: hir::WhereClause { predicates: &[], span },
1899 bounds: arena_vec![this; future_bound],
1900 impl_trait_fn: Some(fn_def_id),
1901 origin: hir::OpaqueTyOrigin::AsyncFn,
1904 trace!("exist ty from async fn def index: {:#?}", opaque_ty_def_index);
1906 this.generate_opaque_type(opaque_ty_node_id, opaque_ty_item, span, opaque_ty_span);
1908 (opaque_ty_id, lifetime_params)
1911 // As documented above on the variable
1912 // `input_lifetimes_count`, we need to create the lifetime
1913 // arguments to our opaque type. Continuing with our example,
1914 // we're creating the type arguments for the return type:
1917 // Bar<'a, 'b, '0, '1, '_>
1920 // For the "input" lifetime parameters, we wish to create
1921 // references to the parameters themselves, including the
1922 // "implicit" ones created from parameter types (`'a`, `'b`,
1925 // For the "output" lifetime parameters, we just want to
1927 let mut generic_args: Vec<_> = lifetime_params[..input_lifetimes_count]
1929 .map(|&(span, hir_name)| {
1930 // Input lifetime like `'a` or `'1`:
1931 GenericArg::Lifetime(hir::Lifetime {
1932 hir_id: self.next_id(),
1934 name: hir::LifetimeName::Param(hir_name),
1938 generic_args.extend(lifetime_params[input_lifetimes_count..].iter().map(|&(span, _)|
1939 // Output lifetime like `'_`.
1940 GenericArg::Lifetime(hir::Lifetime {
1941 hir_id: self.next_id(),
1943 name: hir::LifetimeName::Implicit,
1945 let generic_args = self.arena.alloc_from_iter(generic_args);
1947 // Create the `Foo<...>` reference itself. Note that the `type
1948 // Foo = impl Trait` is, internally, created as a child of the
1949 // async fn, so the *type parameters* are inherited. It's
1950 // only the lifetime parameters that we must supply.
1951 let opaque_ty_ref = hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, generic_args);
1952 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1953 hir::FunctionRetTy::Return(self.arena.alloc(opaque_ty))
1956 /// Transforms `-> T` into `Future<Output = T>`
1957 fn lower_async_fn_output_type_to_future_bound(
1959 output: &FunctionRetTy,
1962 ) -> hir::GenericBound<'hir> {
1963 // Compute the `T` in `Future<Output = T>` from the return type.
1964 let output_ty = match output {
1965 FunctionRetTy::Ty(ty) => self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(fn_def_id))),
1966 FunctionRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1970 let future_params = self.arena.alloc(hir::GenericArgs {
1972 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
1973 parenthesized: false,
1976 // ::std::future::Future<future_params>
1978 self.std_path(span, &[sym::future, sym::Future], Some(future_params), false);
1980 hir::GenericBound::Trait(
1982 trait_ref: hir::TraitRef { path: future_path, hir_ref_id: self.next_id() },
1983 bound_generic_params: &[],
1986 hir::TraitBoundModifier::None,
1990 fn lower_param_bound(
1993 itctx: ImplTraitContext<'_, 'hir>,
1994 ) -> hir::GenericBound<'hir> {
1996 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
1997 self.lower_poly_trait_ref(ty, itctx),
1998 self.lower_trait_bound_modifier(modifier),
2000 GenericBound::Outlives(ref lifetime) => {
2001 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2006 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2007 let span = l.ident.span;
2009 ident if ident.name == kw::StaticLifetime => {
2010 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static)
2012 ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode {
2013 AnonymousLifetimeMode::CreateParameter => {
2014 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2015 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2018 AnonymousLifetimeMode::PassThrough => {
2019 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2022 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2025 self.maybe_collect_in_band_lifetime(ident);
2026 let param_name = ParamName::Plain(ident);
2027 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2032 fn new_named_lifetime(
2036 name: hir::LifetimeName,
2037 ) -> hir::Lifetime {
2038 hir::Lifetime { hir_id: self.lower_node_id(id), span, name }
2041 fn lower_generic_params_mut<'s>(
2043 params: &'s [GenericParam],
2044 add_bounds: &'s NodeMap<Vec<GenericBound>>,
2045 mut itctx: ImplTraitContext<'s, 'hir>,
2046 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
2049 .map(move |param| self.lower_generic_param(param, add_bounds, itctx.reborrow()))
2052 fn lower_generic_params(
2054 params: &[GenericParam],
2055 add_bounds: &NodeMap<Vec<GenericBound>>,
2056 itctx: ImplTraitContext<'_, 'hir>,
2057 ) -> &'hir [hir::GenericParam<'hir>] {
2058 self.arena.alloc_from_iter(self.lower_generic_params_mut(params, add_bounds, itctx))
2061 fn lower_generic_param(
2063 param: &GenericParam,
2064 add_bounds: &NodeMap<Vec<GenericBound>>,
2065 mut itctx: ImplTraitContext<'_, 'hir>,
2066 ) -> hir::GenericParam<'hir> {
2067 let mut bounds: Vec<_> = self
2068 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2069 this.lower_param_bounds_mut(¶m.bounds, itctx.reborrow()).collect()
2072 let (name, kind) = match param.kind {
2073 GenericParamKind::Lifetime => {
2074 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2075 self.is_collecting_in_band_lifetimes = false;
2078 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2079 this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident })
2081 let param_name = match lt.name {
2082 hir::LifetimeName::Param(param_name) => param_name,
2083 hir::LifetimeName::Implicit
2084 | hir::LifetimeName::Underscore
2085 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2086 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2089 "object-lifetime-default should not occur here",
2092 hir::LifetimeName::Error => ParamName::Error,
2096 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2098 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2102 GenericParamKind::Type { ref default, .. } => {
2103 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2104 if !add_bounds.is_empty() {
2105 let params = self.lower_param_bounds_mut(add_bounds, itctx.reborrow());
2106 bounds.extend(params);
2109 let kind = hir::GenericParamKind::Type {
2112 .map(|x| self.lower_ty(x, ImplTraitContext::OpaqueTy(None))),
2116 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2117 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2121 (hir::ParamName::Plain(param.ident), kind)
2123 GenericParamKind::Const { ref ty } => {
2125 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2126 this.lower_ty(&ty, ImplTraitContext::disallowed())
2129 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const { ty })
2134 hir_id: self.lower_node_id(param.id),
2136 span: param.ident.span,
2137 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2138 attrs: self.lower_attrs(¶m.attrs),
2139 bounds: self.arena.alloc_from_iter(bounds),
2147 itctx: ImplTraitContext<'_, 'hir>,
2148 ) -> hir::TraitRef<'hir> {
2149 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2150 hir::QPath::Resolved(None, path) => path,
2151 qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2153 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2156 fn lower_poly_trait_ref(
2159 mut itctx: ImplTraitContext<'_, 'hir>,
2160 ) -> hir::PolyTraitRef<'hir> {
2161 if p.trait_ref.constness.is_some() {
2162 self.diagnostic().span_err(p.span, "`?const` on trait bounds is not yet implemented");
2165 let bound_generic_params = self.lower_generic_params(
2166 &p.bound_generic_params,
2167 &NodeMap::default(),
2170 let trait_ref = self.with_in_scope_lifetime_defs(&p.bound_generic_params, |this| {
2171 this.lower_trait_ref(&p.trait_ref, itctx)
2174 hir::PolyTraitRef { bound_generic_params, trait_ref, span: p.span }
2177 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2178 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2181 fn lower_param_bounds(
2183 bounds: &[GenericBound],
2184 itctx: ImplTraitContext<'_, 'hir>,
2185 ) -> hir::GenericBounds<'hir> {
2186 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2189 fn lower_param_bounds_mut<'s>(
2191 bounds: &'s [GenericBound],
2192 mut itctx: ImplTraitContext<'s, 'hir>,
2193 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2194 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2197 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> &'hir hir::Block<'hir> {
2198 self.arena.alloc(self.lower_block_noalloc(b, targeted_by_break))
2201 fn lower_block_noalloc(&mut self, b: &Block, targeted_by_break: bool) -> hir::Block<'hir> {
2202 let mut stmts = vec![];
2203 let mut expr: Option<&'hir _> = None;
2205 for (index, stmt) in b.stmts.iter().enumerate() {
2206 if index == b.stmts.len() - 1 {
2207 if let StmtKind::Expr(ref e) = stmt.kind {
2208 expr = Some(self.lower_expr(e));
2210 stmts.extend(self.lower_stmt(stmt));
2213 stmts.extend(self.lower_stmt(stmt));
2218 hir_id: self.lower_node_id(b.id),
2219 stmts: self.arena.alloc_from_iter(stmts),
2221 rules: self.lower_block_check_mode(&b.rules),
2227 /// Lowers a block directly to an expression, presuming that it
2228 /// has no attributes and is not targeted by a `break`.
2229 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2230 let block = self.lower_block(b, false);
2231 self.expr_block(block, AttrVec::new())
2234 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2235 self.with_new_scopes(|this| hir::AnonConst {
2236 hir_id: this.lower_node_id(c.id),
2237 body: this.lower_const_body(c.value.span, Some(&c.value)),
2241 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt<'hir>; 1]> {
2242 let kind = match s.kind {
2243 StmtKind::Local(ref l) => {
2244 let (l, item_ids) = self.lower_local(l);
2245 let mut ids: SmallVec<[hir::Stmt<'hir>; 1]> = item_ids
2248 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
2249 self.stmt(s.span, hir::StmtKind::Item(item_id))
2254 hir_id: self.lower_node_id(s.id),
2255 kind: hir::StmtKind::Local(self.arena.alloc(l)),
2261 StmtKind::Item(ref it) => {
2262 // Can only use the ID once.
2263 let mut id = Some(s.id);
2270 .map(|id| self.lower_node_id(id))
2271 .unwrap_or_else(|| self.next_id());
2273 hir::Stmt { hir_id, kind: hir::StmtKind::Item(item_id), span: s.span }
2277 StmtKind::Expr(ref e) => hir::StmtKind::Expr(self.lower_expr(e)),
2278 StmtKind::Semi(ref e) => hir::StmtKind::Semi(self.lower_expr(e)),
2279 StmtKind::Mac(..) => panic!("shouldn't exist here"),
2281 smallvec![hir::Stmt { hir_id: self.lower_node_id(s.id), kind, span: s.span }]
2284 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
2286 BlockCheckMode::Default => hir::BlockCheckMode::DefaultBlock,
2287 BlockCheckMode::Unsafe(u) => {
2288 hir::BlockCheckMode::UnsafeBlock(self.lower_unsafe_source(u))
2293 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2295 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2296 UserProvided => hir::UnsafeSource::UserProvided,
2300 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2302 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2303 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
2307 // Helper methods for building HIR.
2309 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2310 hir::Stmt { span, kind, hir_id: self.next_id() }
2313 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2314 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2321 init: Option<&'hir hir::Expr<'hir>>,
2322 pat: &'hir hir::Pat<'hir>,
2323 source: hir::LocalSource,
2324 ) -> hir::Stmt<'hir> {
2325 let local = hir::Local { attrs, hir_id: self.next_id(), init, pat, source, span, ty: None };
2326 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2329 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2330 self.block_all(expr.span, &[], Some(expr))
2336 stmts: &'hir [hir::Stmt<'hir>],
2337 expr: Option<&'hir hir::Expr<'hir>>,
2338 ) -> &'hir hir::Block<'hir> {
2339 let blk = hir::Block {
2342 hir_id: self.next_id(),
2343 rules: hir::BlockCheckMode::DefaultBlock,
2345 targeted_by_break: false,
2347 self.arena.alloc(blk)
2350 /// Constructs a `true` or `false` literal pattern.
2351 fn pat_bool(&mut self, span: Span, val: bool) -> &'hir hir::Pat<'hir> {
2352 let expr = self.expr_bool(span, val);
2353 self.pat(span, hir::PatKind::Lit(expr))
2356 fn pat_ok(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2357 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], arena_vec![self; pat])
2360 fn pat_err(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2361 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], arena_vec![self; pat])
2364 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2365 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], arena_vec![self; pat])
2368 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2369 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], &[])
2375 components: &[Symbol],
2376 subpats: &'hir [&'hir hir::Pat<'hir>],
2377 ) -> &'hir hir::Pat<'hir> {
2378 let path = self.std_path(span, components, None, true);
2379 let qpath = hir::QPath::Resolved(None, path);
2380 let pt = if subpats.is_empty() {
2381 hir::PatKind::Path(qpath)
2383 hir::PatKind::TupleStruct(qpath, subpats, None)
2388 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2389 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2392 fn pat_ident_binding_mode(
2396 bm: hir::BindingAnnotation,
2397 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2398 let hir_id = self.next_id();
2401 self.arena.alloc(hir::Pat {
2403 kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
2410 fn pat_wild(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2411 self.pat(span, hir::PatKind::Wild)
2414 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2415 self.arena.alloc(hir::Pat { hir_id: self.next_id(), kind, span })
2418 /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
2419 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
2420 /// The path is also resolved according to `is_value`.
2424 components: &[Symbol],
2425 params: Option<&'hir hir::GenericArgs<'hir>>,
2427 ) -> &'hir hir::Path<'hir> {
2428 let ns = if is_value { Namespace::ValueNS } else { Namespace::TypeNS };
2429 let (path, res) = self.resolver.resolve_str_path(span, self.crate_root, components, ns);
2431 let mut segments: Vec<_> = path
2435 let res = self.expect_full_res(segment.id);
2437 ident: segment.ident,
2438 hir_id: Some(self.lower_node_id(segment.id)),
2439 res: Some(self.lower_res(res)),
2445 segments.last_mut().unwrap().args = params;
2447 self.arena.alloc(hir::Path {
2449 res: res.map_id(|_| panic!("unexpected `NodeId`")),
2450 segments: self.arena.alloc_from_iter(segments),
2456 mut hir_id: hir::HirId,
2458 qpath: hir::QPath<'hir>,
2459 ) -> hir::Ty<'hir> {
2460 let kind = match qpath {
2461 hir::QPath::Resolved(None, path) => {
2462 // Turn trait object paths into `TyKind::TraitObject` instead.
2464 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
2465 let principal = hir::PolyTraitRef {
2466 bound_generic_params: &[],
2467 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2471 // The original ID is taken by the `PolyTraitRef`,
2472 // so the `Ty` itself needs a different one.
2473 hir_id = self.next_id();
2474 hir::TyKind::TraitObject(
2475 arena_vec![self; principal],
2476 self.elided_dyn_bound(span),
2479 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2482 _ => hir::TyKind::Path(qpath),
2485 hir::Ty { hir_id, kind, span }
2488 /// Invoked to create the lifetime argument for a type `&T`
2489 /// with no explicit lifetime.
2490 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
2491 match self.anonymous_lifetime_mode {
2492 // Intercept when we are in an impl header or async fn and introduce an in-band
2494 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
2496 AnonymousLifetimeMode::CreateParameter => {
2497 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2499 hir_id: self.next_id(),
2501 name: hir::LifetimeName::Param(fresh_name),
2505 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
2507 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
2511 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
2512 /// return a "error lifetime".
2513 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
2514 let (id, msg, label) = match id {
2515 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
2518 self.resolver.next_node_id(),
2519 "`&` without an explicit lifetime name cannot be used here",
2520 "explicit lifetime name needed here",
2524 let mut err = struct_span_err!(self.sess, span, E0637, "{}", msg,);
2525 err.span_label(span, label);
2528 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2531 /// Invoked to create the lifetime argument(s) for a path like
2532 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
2533 /// sorts of cases are deprecated. This may therefore report a warning or an
2534 /// error, depending on the mode.
2535 fn elided_path_lifetimes<'s>(
2539 ) -> impl Iterator<Item = hir::Lifetime> + Captures<'a> + Captures<'s> + Captures<'hir> {
2540 (0..count).map(move |_| self.elided_path_lifetime(span))
2543 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
2544 match self.anonymous_lifetime_mode {
2545 AnonymousLifetimeMode::CreateParameter => {
2546 // We should have emitted E0726 when processing this path above
2548 .delay_span_bug(span, "expected 'implicit elided lifetime not allowed' error");
2549 let id = self.resolver.next_node_id();
2550 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2552 // `PassThrough` is the normal case.
2553 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
2554 // is unsuitable here, as these can occur from missing lifetime parameters in a
2555 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
2556 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
2557 // later, at which point a suitable error will be emitted.
2558 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
2559 self.new_implicit_lifetime(span)
2564 /// Invoked to create the lifetime argument(s) for an elided trait object
2565 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2566 /// when the bound is written, even if it is written with `'_` like in
2567 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2568 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2569 match self.anonymous_lifetime_mode {
2570 // NB. We intentionally ignore the create-parameter mode here.
2571 // and instead "pass through" to resolve-lifetimes, which will apply
2572 // the object-lifetime-defaulting rules. Elided object lifetime defaults
2573 // do not act like other elided lifetimes. In other words, given this:
2575 // impl Foo for Box<dyn Debug>
2577 // we do not introduce a fresh `'_` to serve as the bound, but instead
2578 // ultimately translate to the equivalent of:
2580 // impl Foo for Box<dyn Debug + 'static>
2582 // `resolve_lifetime` has the code to make that happen.
2583 AnonymousLifetimeMode::CreateParameter => {}
2585 AnonymousLifetimeMode::ReportError => {
2586 // ReportError applies to explicit use of `'_`.
2589 // This is the normal case.
2590 AnonymousLifetimeMode::PassThrough => {}
2593 let r = hir::Lifetime {
2594 hir_id: self.next_id(),
2596 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2598 debug!("elided_dyn_bound: r={:?}", r);
2602 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
2603 hir::Lifetime { hir_id: self.next_id(), span, name: hir::LifetimeName::Implicit }
2606 fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
2607 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
2608 // call site which do not have a macro backtrace. See #61963.
2609 let is_macro_callsite = self
2612 .span_to_snippet(span)
2613 .map(|snippet| snippet.starts_with("#["))
2615 if !is_macro_callsite {
2616 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2617 builtin::BARE_TRAIT_OBJECTS,
2620 "trait objects without an explicit `dyn` are deprecated",
2621 BuiltinLintDiagnostics::BareTraitObject(span, is_global),
2627 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body<'_>>) -> Vec<hir::BodyId> {
2628 // Sorting by span ensures that we get things in order within a
2629 // file, and also puts the files in a sensible order.
2630 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
2631 body_ids.sort_by_key(|b| bodies[b].value.span);
2635 /// Helper struct for delayed construction of GenericArgs.
2636 struct GenericArgsCtor<'hir> {
2637 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2638 bindings: &'hir [hir::TypeBinding<'hir>],
2639 parenthesized: bool,
2642 impl<'hir> GenericArgsCtor<'hir> {
2643 fn is_empty(&self) -> bool {
2644 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2647 fn into_generic_args(self, arena: &'hir Arena<'hir>) -> hir::GenericArgs<'hir> {
2649 args: arena.alloc_from_iter(self.args),
2650 bindings: self.bindings,
2651 parenthesized: self.parenthesized,