]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/lib.rs
Remove `crate` visibility usage in compiler
[rust.git] / compiler / rustc_ast_lowering / src / lib.rs
1 //! Lowers the AST to the HIR.
2 //!
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.
7 //!
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.
11 //!
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), create a new ID using `next_id()`.
16 //!
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.
21 //!
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.
32
33 #![feature(box_patterns)]
34 #![feature(let_chains)]
35 #![feature(let_else)]
36 #![feature(never_type)]
37 #![recursion_limit = "256"]
38 #![allow(rustc::potential_query_instability)]
39
40 use rustc_ast::tokenstream::{CanSynthesizeMissingTokens, TokenStream};
41 use rustc_ast::visit;
42 use rustc_ast::{self as ast, *};
43 use rustc_ast_pretty::pprust;
44 use rustc_data_structures::captures::Captures;
45 use rustc_data_structures::fingerprint::Fingerprint;
46 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
47 use rustc_data_structures::sorted_map::SortedMap;
48 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
49 use rustc_data_structures::sync::Lrc;
50 use rustc_errors::struct_span_err;
51 use rustc_hir as hir;
52 use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
53 use rustc_hir::def_id::{DefId, DefPathHash, LocalDefId, CRATE_DEF_ID};
54 use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
55 use rustc_hir::{ConstArg, GenericArg, ItemLocalId, ParamName, TraitCandidate};
56 use rustc_index::vec::{Idx, IndexVec};
57 use rustc_query_system::ich::StableHashingContext;
58 use rustc_session::parse::feature_err;
59 use rustc_session::utils::{FlattenNonterminals, NtToTokenstream};
60 use rustc_session::Session;
61 use rustc_span::hygiene::{ExpnId, MacroKind};
62 use rustc_span::source_map::DesugaringKind;
63 use rustc_span::symbol::{kw, sym, Ident, Symbol};
64 use rustc_span::{Span, DUMMY_SP};
65
66 use smallvec::SmallVec;
67 use std::collections::hash_map::Entry;
68 use tracing::{debug, trace};
69
70 macro_rules! arena_vec {
71     ($this:expr; $($x:expr),*) => (
72         $this.arena.alloc_from_iter([$($x),*])
73     );
74 }
75
76 mod asm;
77 mod block;
78 mod expr;
79 mod index;
80 mod item;
81 mod pat;
82 mod path;
83
84 rustc_hir::arena_types!(rustc_arena::declare_arena);
85
86 struct LoweringContext<'a, 'hir: 'a> {
87     /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
88     sess: &'a Session,
89
90     resolver: &'a mut dyn ResolverAstLowering,
91
92     /// HACK(Centril): there is a cyclic dependency between the parser and lowering
93     /// if we don't have this function pointer. To avoid that dependency so that
94     /// `rustc_middle` is independent of the parser, we use dynamic dispatch here.
95     nt_to_tokenstream: NtToTokenstream,
96
97     /// Used to allocate HIR nodes.
98     arena: &'hir Arena<'hir>,
99
100     /// Bodies inside the owner being lowered.
101     bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
102     /// Attributes inside the owner being lowered.
103     attrs: SortedMap<hir::ItemLocalId, &'hir [Attribute]>,
104     /// Collect items that were created by lowering the current owner.
105     children: FxHashMap<LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>>,
106
107     generator_kind: Option<hir::GeneratorKind>,
108
109     /// When inside an `async` context, this is the `HirId` of the
110     /// `task_context` local bound to the resume argument of the generator.
111     task_context: Option<hir::HirId>,
112
113     /// Used to get the current `fn`'s def span to point to when using `await`
114     /// outside of an `async fn`.
115     current_item: Option<Span>,
116
117     catch_scope: Option<NodeId>,
118     loop_scope: Option<NodeId>,
119     is_in_loop_condition: bool,
120     is_in_trait_impl: bool,
121     is_in_dyn_type: bool,
122
123     /// Used to handle lifetimes appearing in impl-traits.
124     captured_lifetimes: Option<LifetimeCaptureContext>,
125
126     current_hir_id_owner: LocalDefId,
127     item_local_id_counter: hir::ItemLocalId,
128     local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
129     trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
130
131     /// NodeIds that are lowered inside the current HIR owner.
132     node_id_to_local_id: FxHashMap<NodeId, hir::ItemLocalId>,
133
134     allow_try_trait: Option<Lrc<[Symbol]>>,
135     allow_gen_future: Option<Lrc<[Symbol]>>,
136     allow_into_future: Option<Lrc<[Symbol]>>,
137 }
138
139 /// Resolution for a lifetime appearing in a type.
140 #[derive(Copy, Clone, Debug)]
141 pub enum LifetimeRes {
142     /// Successfully linked the lifetime to a generic parameter.
143     Param {
144         /// Id of the generic parameter that introduced it.
145         param: LocalDefId,
146         /// Id of the introducing place. That can be:
147         /// - an item's id, for the item's generic parameters;
148         /// - a TraitRef's ref_id, identifying the `for<...>` binder;
149         /// - a BareFn type's id;
150         /// - a Path's id when this path has parenthesized generic args.
151         ///
152         /// This information is used for impl-trait lifetime captures, to know when to or not to
153         /// capture any given lifetime.
154         binder: NodeId,
155     },
156     /// Created a generic parameter for an anonymous lifetime.
157     Fresh {
158         /// Id of the generic parameter that introduced it.
159         param: LocalDefId,
160         /// Id of the introducing place. See `Param`.
161         binder: NodeId,
162     },
163     /// This variant is used for anonymous lifetimes that we did not resolve during
164     /// late resolution.  Shifting the work to the HIR lifetime resolver.
165     Anonymous {
166         /// Id of the introducing place. See `Param`.
167         binder: NodeId,
168         /// Whether this lifetime was spelled or elided.
169         elided: bool,
170     },
171     /// Explicit `'static` lifetime.
172     Static,
173     /// Resolution failure.
174     Error,
175     /// HACK: This is used to recover the NodeId of an elided lifetime.
176     ElidedAnchor { start: NodeId, end: NodeId },
177 }
178
179 /// When we lower a lifetime, it is inserted in `captures`, and the resolution is modified so
180 /// to point to the lifetime parameter impl-trait will generate.
181 /// When traversing `for<...>` binders, they are inserted in `binders_to_ignore` so we know *not*
182 /// to rebind the introduced lifetimes.
183 #[derive(Debug)]
184 struct LifetimeCaptureContext {
185     /// parent def_id for new definitions
186     parent_def_id: LocalDefId,
187     /// Set of lifetimes to rebind.
188     captures: FxHashMap<
189         LocalDefId, // original parameter id
190         (
191             Span,        // Span
192             NodeId,      // synthetized parameter id
193             ParamName,   // parameter name
194             LifetimeRes, // original resolution
195         ),
196     >,
197     /// Traversed binders.  The ids in this set should *not* be rebound.
198     binders_to_ignore: FxHashSet<NodeId>,
199 }
200
201 pub trait ResolverAstLowering {
202     fn def_key(&self, id: DefId) -> DefKey;
203
204     fn def_span(&self, id: LocalDefId) -> Span;
205
206     fn item_generics_num_lifetimes(&self, def: DefId) -> usize;
207
208     fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>>;
209
210     /// Obtains resolution for a `NodeId` with a single resolution.
211     fn get_partial_res(&self, id: NodeId) -> Option<PartialRes>;
212
213     /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
214     fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
215
216     /// Obtains resolution for a label with the given `NodeId`.
217     fn get_label_res(&self, id: NodeId) -> Option<NodeId>;
218
219     /// Obtains resolution for a lifetime with the given `NodeId`.
220     fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes>;
221
222     /// Obtain the list of lifetimes parameters to add to an item.
223     fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)>;
224
225     fn create_stable_hashing_context(&self) -> StableHashingContext<'_>;
226
227     fn definitions(&self) -> &Definitions;
228
229     fn next_node_id(&mut self) -> NodeId;
230
231     fn take_trait_map(&mut self, node: NodeId) -> Option<Vec<hir::TraitCandidate>>;
232
233     fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId>;
234
235     fn local_def_id(&self, node: NodeId) -> LocalDefId;
236
237     fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
238
239     fn create_def(
240         &mut self,
241         parent: LocalDefId,
242         node_id: ast::NodeId,
243         data: DefPathData,
244         expn_id: ExpnId,
245         span: Span,
246     ) -> LocalDefId;
247
248     fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind;
249 }
250
251 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
252 /// and if so, what meaning it has.
253 #[derive(Debug)]
254 enum ImplTraitContext<'b, 'a> {
255     /// Treat `impl Trait` as shorthand for a new universal generic parameter.
256     /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
257     /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
258     ///
259     /// Newly generated parameters should be inserted into the given `Vec`.
260     Universal(&'b mut Vec<hir::GenericParam<'a>>, &'b mut Vec<hir::WherePredicate<'a>>, LocalDefId),
261
262     /// Treat `impl Trait` as shorthand for a new opaque type.
263     /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
264     /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
265     ///
266     ReturnPositionOpaqueTy {
267         /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
268         origin: hir::OpaqueTyOrigin,
269     },
270     /// Impl trait in type aliases.
271     TypeAliasesOpaqueTy,
272     /// `impl Trait` is not accepted in this position.
273     Disallowed(ImplTraitPosition),
274 }
275
276 /// Position in which `impl Trait` is disallowed.
277 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
278 enum ImplTraitPosition {
279     Path,
280     Variable,
281     Type,
282     Trait,
283     AsyncBlock,
284     Bound,
285     Generic,
286     ExternFnParam,
287     ClosureParam,
288     PointerParam,
289     FnTraitParam,
290     TraitParam,
291     ImplParam,
292     ExternFnReturn,
293     ClosureReturn,
294     PointerReturn,
295     FnTraitReturn,
296     TraitReturn,
297     ImplReturn,
298 }
299
300 impl<'a> ImplTraitContext<'_, 'a> {
301     fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
302         use self::ImplTraitContext::*;
303         match self {
304             Universal(params, bounds, parent) => Universal(params, bounds, *parent),
305             ReturnPositionOpaqueTy { origin } => ReturnPositionOpaqueTy { origin: *origin },
306             TypeAliasesOpaqueTy => TypeAliasesOpaqueTy,
307             Disallowed(pos) => Disallowed(*pos),
308         }
309     }
310 }
311
312 impl std::fmt::Display for ImplTraitPosition {
313     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314         let name = match self {
315             ImplTraitPosition::Path => "path",
316             ImplTraitPosition::Variable => "variable binding",
317             ImplTraitPosition::Type => "type",
318             ImplTraitPosition::Trait => "trait",
319             ImplTraitPosition::AsyncBlock => "async block",
320             ImplTraitPosition::Bound => "bound",
321             ImplTraitPosition::Generic => "generic",
322             ImplTraitPosition::ExternFnParam => "`extern fn` param",
323             ImplTraitPosition::ClosureParam => "closure param",
324             ImplTraitPosition::PointerParam => "`fn` pointer param",
325             ImplTraitPosition::FnTraitParam => "`Fn` trait param",
326             ImplTraitPosition::TraitParam => "trait method param",
327             ImplTraitPosition::ImplParam => "`impl` method param",
328             ImplTraitPosition::ExternFnReturn => "`extern fn` return",
329             ImplTraitPosition::ClosureReturn => "closure return",
330             ImplTraitPosition::PointerReturn => "`fn` pointer return",
331             ImplTraitPosition::FnTraitReturn => "`Fn` trait return",
332             ImplTraitPosition::TraitReturn => "trait method return",
333             ImplTraitPosition::ImplReturn => "`impl` method return",
334         };
335
336         write!(f, "{}", name)
337     }
338 }
339
340 #[derive(Debug)]
341 enum FnDeclKind {
342     Fn,
343     Inherent,
344     ExternFn,
345     Closure,
346     Pointer,
347     Trait,
348     Impl,
349 }
350
351 impl FnDeclKind {
352     fn impl_trait_return_allowed(&self) -> bool {
353         match self {
354             FnDeclKind::Fn | FnDeclKind::Inherent => true,
355             _ => false,
356         }
357     }
358 }
359
360 #[derive(Copy, Clone)]
361 enum AstOwner<'a> {
362     NonOwner,
363     Crate(&'a ast::Crate),
364     Item(&'a ast::Item),
365     AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
366     ForeignItem(&'a ast::ForeignItem),
367 }
368
369 fn index_crate<'a>(
370     resolver: &dyn ResolverAstLowering,
371     krate: &'a Crate,
372 ) -> IndexVec<LocalDefId, AstOwner<'a>> {
373     let mut indexer = Indexer { resolver, index: IndexVec::new() };
374     indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner);
375     indexer.index[CRATE_DEF_ID] = AstOwner::Crate(krate);
376     visit::walk_crate(&mut indexer, krate);
377     return indexer.index;
378
379     struct Indexer<'s, 'a> {
380         resolver: &'s dyn ResolverAstLowering,
381         index: IndexVec<LocalDefId, AstOwner<'a>>,
382     }
383
384     impl<'a> visit::Visitor<'a> for Indexer<'_, 'a> {
385         fn visit_attribute(&mut self, _: &'a Attribute) {
386             // We do not want to lower expressions that appear in attributes,
387             // as they are not accessible to the rest of the HIR.
388         }
389
390         fn visit_item(&mut self, item: &'a ast::Item) {
391             let def_id = self.resolver.local_def_id(item.id);
392             self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
393             self.index[def_id] = AstOwner::Item(item);
394             visit::walk_item(self, item)
395         }
396
397         fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
398             let def_id = self.resolver.local_def_id(item.id);
399             self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
400             self.index[def_id] = AstOwner::AssocItem(item, ctxt);
401             visit::walk_assoc_item(self, item, ctxt);
402         }
403
404         fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
405             let def_id = self.resolver.local_def_id(item.id);
406             self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
407             self.index[def_id] = AstOwner::ForeignItem(item);
408             visit::walk_foreign_item(self, item);
409         }
410     }
411 }
412
413 /// Compute the hash for the HIR of the full crate.
414 /// This hash will then be part of the crate_hash which is stored in the metadata.
415 fn compute_hir_hash(
416     resolver: &mut dyn ResolverAstLowering,
417     owners: &IndexVec<LocalDefId, hir::MaybeOwner<&hir::OwnerInfo<'_>>>,
418 ) -> Fingerprint {
419     let mut hir_body_nodes: Vec<_> = owners
420         .iter_enumerated()
421         .filter_map(|(def_id, info)| {
422             let info = info.as_owner()?;
423             let def_path_hash = resolver.definitions().def_path_hash(def_id);
424             Some((def_path_hash, info))
425         })
426         .collect();
427     hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
428
429     let mut stable_hasher = StableHasher::new();
430     let mut hcx = resolver.create_stable_hashing_context();
431     hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
432     stable_hasher.finish()
433 }
434
435 pub fn lower_crate<'a, 'hir>(
436     sess: &'a Session,
437     krate: &'a Crate,
438     resolver: &'a mut dyn ResolverAstLowering,
439     nt_to_tokenstream: NtToTokenstream,
440     arena: &'hir Arena<'hir>,
441 ) -> &'hir hir::Crate<'hir> {
442     let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
443
444     let ast_index = index_crate(resolver, krate);
445
446     let mut owners =
447         IndexVec::from_fn_n(|_| hir::MaybeOwner::Phantom, resolver.definitions().def_index_count());
448
449     for def_id in ast_index.indices() {
450         item::ItemLowerer {
451             sess,
452             resolver,
453             nt_to_tokenstream,
454             arena,
455             ast_index: &ast_index,
456             owners: &mut owners,
457         }
458         .lower_node(def_id);
459     }
460
461     let hir_hash = compute_hir_hash(resolver, &owners);
462     let krate = hir::Crate { owners, hir_hash };
463     arena.alloc(krate)
464 }
465
466 #[derive(Copy, Clone, PartialEq)]
467 enum ParamMode {
468     /// Any path in a type context.
469     Explicit,
470     /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
471     ExplicitNamed,
472     /// The `module::Type` in `module::Type::method` in an expression.
473     Optional,
474 }
475
476 enum ParenthesizedGenericArgs {
477     Ok,
478     Err,
479 }
480
481 impl<'a, 'hir> LoweringContext<'a, 'hir> {
482     fn with_hir_id_owner(
483         &mut self,
484         owner: NodeId,
485         f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
486     ) {
487         let def_id = self.resolver.local_def_id(owner);
488
489         let current_attrs = std::mem::take(&mut self.attrs);
490         let current_bodies = std::mem::take(&mut self.bodies);
491         let current_node_ids = std::mem::take(&mut self.node_id_to_local_id);
492         let current_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
493         let current_trait_map = std::mem::take(&mut self.trait_map);
494         let current_owner = std::mem::replace(&mut self.current_hir_id_owner, def_id);
495         let current_local_counter =
496             std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
497
498         // Always allocate the first `HirId` for the owner itself.
499         let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::new(0));
500         debug_assert_eq!(_old, None);
501
502         let item = f(self);
503         debug_assert_eq!(def_id, item.def_id());
504         let info = self.make_owner_info(item);
505
506         self.attrs = current_attrs;
507         self.bodies = current_bodies;
508         self.node_id_to_local_id = current_node_ids;
509         self.local_id_to_def_id = current_id_to_def_id;
510         self.trait_map = current_trait_map;
511         self.current_hir_id_owner = current_owner;
512         self.item_local_id_counter = current_local_counter;
513
514         let _old = self.children.insert(def_id, hir::MaybeOwner::Owner(info));
515         debug_assert!(_old.is_none())
516     }
517
518     fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
519         let attrs = std::mem::take(&mut self.attrs);
520         let mut bodies = std::mem::take(&mut self.bodies);
521         let local_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
522         let trait_map = std::mem::take(&mut self.trait_map);
523
524         #[cfg(debug_assertions)]
525         for (id, attrs) in attrs.iter() {
526             // Verify that we do not store empty slices in the map.
527             if attrs.is_empty() {
528                 panic!("Stored empty attributes for {:?}", id);
529             }
530         }
531
532         bodies.sort_by_key(|(k, _)| *k);
533         let bodies = SortedMap::from_presorted_elements(bodies);
534         let (hash_including_bodies, hash_without_bodies) = self.hash_owner(node, &bodies);
535         let (nodes, parenting) =
536             index::index_hir(self.sess, self.resolver.definitions(), node, &bodies);
537         let nodes = hir::OwnerNodes {
538             hash_including_bodies,
539             hash_without_bodies,
540             nodes,
541             bodies,
542             local_id_to_def_id,
543         };
544         let attrs = {
545             let mut hcx = self.resolver.create_stable_hashing_context();
546             let mut stable_hasher = StableHasher::new();
547             attrs.hash_stable(&mut hcx, &mut stable_hasher);
548             let hash = stable_hasher.finish();
549             hir::AttributeMap { map: attrs, hash }
550         };
551
552         self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map })
553     }
554
555     /// Hash the HIR node twice, one deep and one shallow hash.  This allows to differentiate
556     /// queries which depend on the full HIR tree and those which only depend on the item signature.
557     fn hash_owner(
558         &mut self,
559         node: hir::OwnerNode<'hir>,
560         bodies: &SortedMap<hir::ItemLocalId, &'hir hir::Body<'hir>>,
561     ) -> (Fingerprint, Fingerprint) {
562         let mut hcx = self.resolver.create_stable_hashing_context();
563         let mut stable_hasher = StableHasher::new();
564         hcx.with_hir_bodies(true, node.def_id(), bodies, |hcx| {
565             node.hash_stable(hcx, &mut stable_hasher)
566         });
567         let hash_including_bodies = stable_hasher.finish();
568         let mut stable_hasher = StableHasher::new();
569         hcx.with_hir_bodies(false, node.def_id(), bodies, |hcx| {
570             node.hash_stable(hcx, &mut stable_hasher)
571         });
572         let hash_without_bodies = stable_hasher.finish();
573         (hash_including_bodies, hash_without_bodies)
574     }
575
576     /// This method allocates a new `HirId` for the given `NodeId` and stores it in
577     /// the `LoweringContext`'s `NodeId => HirId` map.
578     /// Take care not to call this method if the resulting `HirId` is then not
579     /// actually used in the HIR, as that would trigger an assertion in the
580     /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
581     /// properly. Calling the method twice with the same `NodeId` is fine though.
582     fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
583         assert_ne!(ast_node_id, DUMMY_NODE_ID);
584
585         match self.node_id_to_local_id.entry(ast_node_id) {
586             Entry::Occupied(o) => {
587                 hir::HirId { owner: self.current_hir_id_owner, local_id: *o.get() }
588             }
589             Entry::Vacant(v) => {
590                 // Generate a new `HirId`.
591                 let owner = self.current_hir_id_owner;
592                 let local_id = self.item_local_id_counter;
593                 let hir_id = hir::HirId { owner, local_id };
594
595                 v.insert(local_id);
596                 self.item_local_id_counter.increment_by(1);
597
598                 assert_ne!(local_id, hir::ItemLocalId::new(0));
599                 if let Some(def_id) = self.resolver.opt_local_def_id(ast_node_id) {
600                     // Do not override a `MaybeOwner::Owner` that may already here.
601                     self.children.entry(def_id).or_insert(hir::MaybeOwner::NonOwner(hir_id));
602                     self.local_id_to_def_id.insert(local_id, def_id);
603                 }
604
605                 if let Some(traits) = self.resolver.take_trait_map(ast_node_id) {
606                     self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
607                 }
608
609                 hir_id
610             }
611         }
612     }
613
614     fn next_id(&mut self) -> hir::HirId {
615         let node_id = self.resolver.next_node_id();
616         self.lower_node_id(node_id)
617     }
618
619     fn lower_res(&mut self, res: Res<NodeId>) -> Res {
620         let res: Result<Res, ()> = res.apply_id(|id| {
621             let owner = self.current_hir_id_owner;
622             let local_id = self.node_id_to_local_id.get(&id).copied().ok_or(())?;
623             Ok(hir::HirId { owner, local_id })
624         });
625         // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
626         // This can happen when trying to lower the return type `x` in erroneous code like
627         //   async fn foo(x: u8) -> x {}
628         // In that case, `x` is lowered as a function parameter, and the return type is lowered as
629         // an opaque type as a synthesized HIR owner.
630         res.unwrap_or(Res::Err)
631     }
632
633     fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
634         self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
635             if pr.unresolved_segments() != 0 {
636                 panic!("path not fully resolved: {:?}", pr);
637             }
638             pr.base_res()
639         })
640     }
641
642     fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
643         self.resolver.get_import_res(id).present_items()
644     }
645
646     fn diagnostic(&self) -> &rustc_errors::Handler {
647         self.sess.diagnostic()
648     }
649
650     /// Reuses the span but adds information like the kind of the desugaring and features that are
651     /// allowed inside this span.
652     fn mark_span_with_reason(
653         &self,
654         reason: DesugaringKind,
655         span: Span,
656         allow_internal_unstable: Option<Lrc<[Symbol]>>,
657     ) -> Span {
658         span.mark_with_reason(
659             allow_internal_unstable,
660             reason,
661             self.sess.edition(),
662             self.resolver.create_stable_hashing_context(),
663         )
664     }
665
666     /// Intercept all spans entering HIR.
667     /// Mark a span as relative to the current owning item.
668     fn lower_span(&self, span: Span) -> Span {
669         if self.sess.opts.debugging_opts.incremental_relative_spans {
670             span.with_parent(Some(self.current_hir_id_owner))
671         } else {
672             // Do not make spans relative when not using incremental compilation.
673             span
674         }
675     }
676
677     fn lower_ident(&self, ident: Ident) -> Ident {
678         Ident::new(ident.name, self.lower_span(ident.span))
679     }
680
681     /// Converts a lifetime into a new generic parameter.
682     fn lifetime_res_to_generic_param(
683         &mut self,
684         ident: Ident,
685         node_id: NodeId,
686         res: LifetimeRes,
687     ) -> Option<hir::GenericParam<'hir>> {
688         let (name, kind) = match res {
689             LifetimeRes::Param { .. } => {
690                 (hir::ParamName::Plain(ident), hir::LifetimeParamKind::Explicit)
691             }
692             LifetimeRes::Fresh { param, .. } => {
693                 (hir::ParamName::Fresh(param), hir::LifetimeParamKind::Elided)
694             }
695             LifetimeRes::Static | LifetimeRes::Error => return None,
696             res => panic!(
697                 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
698                 res, ident, ident.span
699             ),
700         };
701         let hir_id = self.lower_node_id(node_id);
702         Some(hir::GenericParam {
703             hir_id,
704             name,
705             span: self.lower_span(ident.span),
706             pure_wrt_drop: false,
707             kind: hir::GenericParamKind::Lifetime { kind },
708             colon_span: None,
709         })
710     }
711
712     /// Creates a new `hir::GenericParam` for every new `Fresh` lifetime and
713     /// universal `impl Trait` type parameter encountered while evaluating `f`.
714     /// Definitions are created with the provided `parent_def_id`.
715     fn add_implicit_generics<T>(
716         &mut self,
717         generics: &Generics,
718         parent_node_id: NodeId,
719         f: impl FnOnce(
720             &mut Self,
721             &mut Vec<hir::GenericParam<'hir>>,
722             &mut Vec<hir::WherePredicate<'hir>>,
723         ) -> T,
724     ) -> (&'hir hir::Generics<'hir>, T) {
725         let mut impl_trait_defs = Vec::new();
726         let mut impl_trait_bounds = Vec::new();
727         let mut lowered_generics = self.lower_generics_mut(
728             generics,
729             ImplTraitContext::Universal(
730                 &mut impl_trait_defs,
731                 &mut impl_trait_bounds,
732                 self.current_hir_id_owner,
733             ),
734         );
735         let res = f(self, &mut impl_trait_defs, &mut impl_trait_bounds);
736
737         let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
738         lowered_generics.params.extend(
739             extra_lifetimes
740                 .into_iter()
741                 .filter_map(|(ident, node_id, res)| {
742                     self.lifetime_res_to_generic_param(ident, node_id, res)
743                 })
744                 .chain(impl_trait_defs),
745         );
746         lowered_generics.predicates.extend(impl_trait_bounds);
747
748         let lowered_generics = lowered_generics.into_generics(self.arena);
749         (lowered_generics, res)
750     }
751
752     /// Setup lifetime capture for and impl-trait.
753     /// The captures will be added to `captures`.
754     fn while_capturing_lifetimes<T>(
755         &mut self,
756         parent_def_id: LocalDefId,
757         captures: &mut FxHashMap<LocalDefId, (Span, NodeId, ParamName, LifetimeRes)>,
758         f: impl FnOnce(&mut Self) -> T,
759     ) -> T {
760         let lifetime_stash = std::mem::replace(
761             &mut self.captured_lifetimes,
762             Some(LifetimeCaptureContext {
763                 parent_def_id,
764                 captures: std::mem::take(captures),
765                 binders_to_ignore: Default::default(),
766             }),
767         );
768
769         let ret = f(self);
770
771         let ctxt = std::mem::replace(&mut self.captured_lifetimes, lifetime_stash).unwrap();
772         *captures = ctxt.captures;
773
774         ret
775     }
776
777     /// Register a binder to be ignored for lifetime capture.
778     #[tracing::instrument(level = "debug", skip(self, f))]
779     #[inline]
780     fn with_lifetime_binder<T>(&mut self, binder: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
781         if let Some(ctxt) = &mut self.captured_lifetimes {
782             ctxt.binders_to_ignore.insert(binder);
783         }
784         let ret = f(self);
785         if let Some(ctxt) = &mut self.captured_lifetimes {
786             ctxt.binders_to_ignore.remove(&binder);
787         }
788         ret
789     }
790
791     fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
792         let was_in_dyn_type = self.is_in_dyn_type;
793         self.is_in_dyn_type = in_scope;
794
795         let result = f(self);
796
797         self.is_in_dyn_type = was_in_dyn_type;
798
799         result
800     }
801
802     fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
803         let was_in_loop_condition = self.is_in_loop_condition;
804         self.is_in_loop_condition = false;
805
806         let catch_scope = self.catch_scope.take();
807         let loop_scope = self.loop_scope.take();
808         let ret = f(self);
809         self.catch_scope = catch_scope;
810         self.loop_scope = loop_scope;
811
812         self.is_in_loop_condition = was_in_loop_condition;
813
814         ret
815     }
816
817     fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
818         if attrs.is_empty() {
819             None
820         } else {
821             debug_assert_eq!(id.owner, self.current_hir_id_owner);
822             let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
823             debug_assert!(!ret.is_empty());
824             self.attrs.insert(id.local_id, ret);
825             Some(ret)
826         }
827     }
828
829     fn lower_attr(&self, attr: &Attribute) -> Attribute {
830         // Note that we explicitly do not walk the path. Since we don't really
831         // lower attributes (we use the AST version) there is nowhere to keep
832         // the `HirId`s. We don't actually need HIR version of attributes anyway.
833         // Tokens are also not needed after macro expansion and parsing.
834         let kind = match attr.kind {
835             AttrKind::Normal(ref item, _) => AttrKind::Normal(
836                 AttrItem {
837                     path: item.path.clone(),
838                     args: self.lower_mac_args(&item.args),
839                     tokens: None,
840                 },
841                 None,
842             ),
843             AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
844         };
845
846         Attribute { kind, id: attr.id, style: attr.style, span: self.lower_span(attr.span) }
847     }
848
849     fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
850         debug_assert_eq!(id.owner, self.current_hir_id_owner);
851         debug_assert_eq!(target_id.owner, self.current_hir_id_owner);
852         if let Some(&a) = self.attrs.get(&target_id.local_id) {
853             debug_assert!(!a.is_empty());
854             self.attrs.insert(id.local_id, a);
855         }
856     }
857
858     fn lower_mac_args(&self, args: &MacArgs) -> MacArgs {
859         match *args {
860             MacArgs::Empty => MacArgs::Empty,
861             MacArgs::Delimited(dspan, delim, ref tokens) => {
862                 // This is either a non-key-value attribute, or a `macro_rules!` body.
863                 // We either not have any nonterminals present (in the case of an attribute),
864                 // or have tokens available for all nonterminals in the case of a nested
865                 // `macro_rules`: e.g:
866                 //
867                 // ```rust
868                 // macro_rules! outer {
869                 //     ($e:expr) => {
870                 //         macro_rules! inner {
871                 //             () => { $e }
872                 //         }
873                 //     }
874                 // }
875                 // ```
876                 //
877                 // In both cases, we don't want to synthesize any tokens
878                 MacArgs::Delimited(
879                     dspan,
880                     delim,
881                     self.lower_token_stream(tokens.clone(), CanSynthesizeMissingTokens::No),
882                 )
883             }
884             // This is an inert key-value attribute - it will never be visible to macros
885             // after it gets lowered to HIR. Therefore, we can extract literals to handle
886             // nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
887             MacArgs::Eq(eq_span, MacArgsEq::Ast(ref expr)) => {
888                 // In valid code the value always ends up as a single literal. Otherwise, a dummy
889                 // literal suffices because the error is handled elsewhere.
890                 let lit = if let ExprKind::Lit(lit) = &expr.kind {
891                     lit.clone()
892                 } else {
893                     Lit {
894                         token: token::Lit::new(token::LitKind::Err, kw::Empty, None),
895                         kind: LitKind::Err(kw::Empty),
896                         span: DUMMY_SP,
897                     }
898                 };
899                 MacArgs::Eq(eq_span, MacArgsEq::Hir(lit))
900             }
901             MacArgs::Eq(_, MacArgsEq::Hir(ref lit)) => {
902                 unreachable!("in literal form when lowering mac args eq: {:?}", lit)
903             }
904         }
905     }
906
907     fn lower_token_stream(
908         &self,
909         tokens: TokenStream,
910         synthesize_tokens: CanSynthesizeMissingTokens,
911     ) -> TokenStream {
912         FlattenNonterminals {
913             parse_sess: &self.sess.parse_sess,
914             synthesize_tokens,
915             nt_to_tokenstream: self.nt_to_tokenstream,
916         }
917         .process_token_stream(tokens)
918     }
919
920     /// Given an associated type constraint like one of these:
921     ///
922     /// ```ignore (illustrative)
923     /// T: Iterator<Item: Debug>
924     ///             ^^^^^^^^^^^
925     /// T: Iterator<Item = Debug>
926     ///             ^^^^^^^^^^^^
927     /// ```
928     ///
929     /// returns a `hir::TypeBinding` representing `Item`.
930     fn lower_assoc_ty_constraint(
931         &mut self,
932         constraint: &AssocConstraint,
933         mut itctx: ImplTraitContext<'_, 'hir>,
934     ) -> hir::TypeBinding<'hir> {
935         debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
936
937         // lower generic arguments of identifier in constraint
938         let gen_args = if let Some(ref gen_args) = constraint.gen_args {
939             let gen_args_ctor = match gen_args {
940                 GenericArgs::AngleBracketed(ref data) => {
941                     self.lower_angle_bracketed_parameter_data(
942                         data,
943                         ParamMode::Explicit,
944                         itctx.reborrow(),
945                     )
946                     .0
947                 }
948                 GenericArgs::Parenthesized(ref data) => {
949                     let mut err = self.sess.struct_span_err(
950                         gen_args.span(),
951                         "parenthesized generic arguments cannot be used in associated type constraints"
952                     );
953                     // FIXME: try to write a suggestion here
954                     err.emit();
955                     self.lower_angle_bracketed_parameter_data(
956                         &data.as_angle_bracketed_args(),
957                         ParamMode::Explicit,
958                         itctx.reborrow(),
959                     )
960                     .0
961                 }
962             };
963             gen_args_ctor.into_generic_args(self)
964         } else {
965             self.arena.alloc(hir::GenericArgs::none())
966         };
967
968         let kind = match constraint.kind {
969             AssocConstraintKind::Equality { ref term } => {
970                 let term = match term {
971                     Term::Ty(ref ty) => self.lower_ty(ty, itctx).into(),
972                     Term::Const(ref c) => self.lower_anon_const(c).into(),
973                 };
974                 hir::TypeBindingKind::Equality { term }
975             }
976             AssocConstraintKind::Bound { ref bounds } => {
977                 let mut parent_def_id = self.current_hir_id_owner;
978                 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
979                 let (desugar_to_impl_trait, itctx) = match itctx {
980                     // We are in the return position:
981                     //
982                     //     fn foo() -> impl Iterator<Item: Debug>
983                     //
984                     // so desugar to
985                     //
986                     //     fn foo() -> impl Iterator<Item = impl Debug>
987                     ImplTraitContext::ReturnPositionOpaqueTy { .. }
988                     | ImplTraitContext::TypeAliasesOpaqueTy { .. } => (true, itctx),
989
990                     // We are in the argument position, but within a dyn type:
991                     //
992                     //     fn foo(x: dyn Iterator<Item: Debug>)
993                     //
994                     // so desugar to
995                     //
996                     //     fn foo(x: dyn Iterator<Item = impl Debug>)
997                     ImplTraitContext::Universal(_, _, parent) if self.is_in_dyn_type => {
998                         parent_def_id = parent;
999                         (true, itctx)
1000                     }
1001
1002                     // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1003                     // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1004                     // "impl trait context" to permit `impl Debug` in this position (it desugars
1005                     // then to an opaque type).
1006                     //
1007                     // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1008                     ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1009                         (true, ImplTraitContext::TypeAliasesOpaqueTy)
1010                     }
1011
1012                     // We are in the parameter position, but not within a dyn type:
1013                     //
1014                     //     fn foo(x: impl Iterator<Item: Debug>)
1015                     //
1016                     // so we leave it as is and this gets expanded in astconv to a bound like
1017                     // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1018                     // `impl Iterator`.
1019                     _ => (false, itctx),
1020                 };
1021
1022                 if desugar_to_impl_trait {
1023                     // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1024                     // constructing the HIR for `impl bounds...` and then lowering that.
1025
1026                     let impl_trait_node_id = self.resolver.next_node_id();
1027                     self.resolver.create_def(
1028                         parent_def_id,
1029                         impl_trait_node_id,
1030                         DefPathData::ImplTrait,
1031                         ExpnId::root(),
1032                         constraint.span,
1033                     );
1034
1035                     self.with_dyn_type_scope(false, |this| {
1036                         let node_id = this.resolver.next_node_id();
1037                         let ty = this.lower_ty(
1038                             &Ty {
1039                                 id: node_id,
1040                                 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1041                                 span: this.lower_span(constraint.span),
1042                                 tokens: None,
1043                             },
1044                             itctx,
1045                         );
1046
1047                         hir::TypeBindingKind::Equality { term: ty.into() }
1048                     })
1049                 } else {
1050                     // Desugar `AssocTy: Bounds` into a type binding where the
1051                     // later desugars into a trait predicate.
1052                     let bounds = self.lower_param_bounds(bounds, itctx);
1053
1054                     hir::TypeBindingKind::Constraint { bounds }
1055                 }
1056             }
1057         };
1058
1059         hir::TypeBinding {
1060             hir_id: self.lower_node_id(constraint.id),
1061             ident: self.lower_ident(constraint.ident),
1062             gen_args,
1063             kind,
1064             span: self.lower_span(constraint.span),
1065         }
1066     }
1067
1068     fn lower_generic_arg(
1069         &mut self,
1070         arg: &ast::GenericArg,
1071         itctx: ImplTraitContext<'_, 'hir>,
1072     ) -> hir::GenericArg<'hir> {
1073         match arg {
1074             ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(&lt)),
1075             ast::GenericArg::Type(ty) => {
1076                 match ty.kind {
1077                     TyKind::Infer if self.sess.features_untracked().generic_arg_infer => {
1078                         return GenericArg::Infer(hir::InferArg {
1079                             hir_id: self.lower_node_id(ty.id),
1080                             span: self.lower_span(ty.span),
1081                         });
1082                     }
1083                     // We parse const arguments as path types as we cannot distinguish them during
1084                     // parsing. We try to resolve that ambiguity by attempting resolution in both the
1085                     // type and value namespaces. If we resolved the path in the value namespace, we
1086                     // transform it into a generic const argument.
1087                     TyKind::Path(ref qself, ref path) => {
1088                         if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1089                             let res = partial_res.base_res();
1090                             if !res.matches_ns(Namespace::TypeNS) {
1091                                 debug!(
1092                                     "lower_generic_arg: Lowering type argument as const argument: {:?}",
1093                                     ty,
1094                                 );
1095
1096                                 // Construct an AnonConst where the expr is the "ty"'s path.
1097
1098                                 let parent_def_id = self.current_hir_id_owner;
1099                                 let node_id = self.resolver.next_node_id();
1100
1101                                 // Add a definition for the in-band const def.
1102                                 self.resolver.create_def(
1103                                     parent_def_id,
1104                                     node_id,
1105                                     DefPathData::AnonConst,
1106                                     ExpnId::root(),
1107                                     ty.span,
1108                                 );
1109
1110                                 let span = self.lower_span(ty.span);
1111                                 let path_expr = Expr {
1112                                     id: ty.id,
1113                                     kind: ExprKind::Path(qself.clone(), path.clone()),
1114                                     span,
1115                                     attrs: AttrVec::new(),
1116                                     tokens: None,
1117                                 };
1118
1119                                 let ct = self.with_new_scopes(|this| hir::AnonConst {
1120                                     hir_id: this.lower_node_id(node_id),
1121                                     body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1122                                 });
1123                                 return GenericArg::Const(ConstArg { value: ct, span });
1124                             }
1125                         }
1126                     }
1127                     _ => {}
1128                 }
1129                 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1130             }
1131             ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1132                 value: self.lower_anon_const(&ct),
1133                 span: self.lower_span(ct.value.span),
1134             }),
1135         }
1136     }
1137
1138     fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1139         self.arena.alloc(self.lower_ty_direct(t, itctx))
1140     }
1141
1142     fn lower_path_ty(
1143         &mut self,
1144         t: &Ty,
1145         qself: &Option<QSelf>,
1146         path: &Path,
1147         param_mode: ParamMode,
1148         itctx: ImplTraitContext<'_, 'hir>,
1149     ) -> hir::Ty<'hir> {
1150         let id = self.lower_node_id(t.id);
1151         let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1152         self.ty_path(id, t.span, qpath)
1153     }
1154
1155     fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1156         hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1157     }
1158
1159     fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1160         self.ty(span, hir::TyKind::Tup(tys))
1161     }
1162
1163     fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
1164         let kind = match t.kind {
1165             TyKind::Infer => hir::TyKind::Infer,
1166             TyKind::Err => hir::TyKind::Err,
1167             TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1168             TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1169             TyKind::Rptr(ref region, ref mt) => {
1170                 let region = region.unwrap_or_else(|| {
1171                     let Some(LifetimeRes::ElidedAnchor { start, end }) = self.resolver.get_lifetime_res(t.id) else {
1172                         panic!()
1173                     };
1174                     debug_assert_eq!(start.plus(1), end);
1175                     let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1176                     Lifetime {
1177                         ident: Ident::new(kw::UnderscoreLifetime, span),
1178                         id: start,
1179                     }
1180                 });
1181                 let lifetime = self.lower_lifetime(&region);
1182                 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1183             }
1184             TyKind::BareFn(ref f) => self.with_lifetime_binder(t.id, |this| {
1185                 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1186                     generic_params: this.lower_generic_params(&f.generic_params),
1187                     unsafety: this.lower_unsafety(f.unsafety),
1188                     abi: this.lower_extern(f.ext),
1189                     decl: this.lower_fn_decl(&f.decl, None, FnDeclKind::Pointer, None),
1190                     param_names: this.lower_fn_params_to_names(&f.decl),
1191                 }))
1192             }),
1193             TyKind::Never => hir::TyKind::Never,
1194             TyKind::Tup(ref tys) => {
1195                 hir::TyKind::Tup(self.arena.alloc_from_iter(
1196                     tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1197                 ))
1198             }
1199             TyKind::Paren(ref ty) => {
1200                 return self.lower_ty_direct(ty, itctx);
1201             }
1202             TyKind::Path(ref qself, ref path) => {
1203                 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1204             }
1205             TyKind::ImplicitSelf => {
1206                 let res = self.expect_full_res(t.id);
1207                 let res = self.lower_res(res);
1208                 hir::TyKind::Path(hir::QPath::Resolved(
1209                     None,
1210                     self.arena.alloc(hir::Path {
1211                         res,
1212                         segments: arena_vec![self; hir::PathSegment::from_ident(
1213                             Ident::with_dummy_span(kw::SelfUpper)
1214                         )],
1215                         span: self.lower_span(t.span),
1216                     }),
1217                 ))
1218             }
1219             TyKind::Array(ref ty, ref length) => {
1220                 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_array_length(length))
1221             }
1222             TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1223             TyKind::TraitObject(ref bounds, kind) => {
1224                 let mut lifetime_bound = None;
1225                 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1226                     let bounds =
1227                         this.arena.alloc_from_iter(bounds.iter().filter_map(
1228                             |bound| match *bound {
1229                                 GenericBound::Trait(
1230                                     ref ty,
1231                                     TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1232                                 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
1233                                 // `~const ?Bound` will cause an error during AST validation
1234                                 // anyways, so treat it like `?Bound` as compilation proceeds.
1235                                 GenericBound::Trait(
1236                                     _,
1237                                     TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1238                                 ) => None,
1239                                 GenericBound::Outlives(ref lifetime) => {
1240                                     if lifetime_bound.is_none() {
1241                                         lifetime_bound = Some(this.lower_lifetime(lifetime));
1242                                     }
1243                                     None
1244                                 }
1245                             },
1246                         ));
1247                     let lifetime_bound =
1248                         lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1249                     (bounds, lifetime_bound)
1250                 });
1251                 hir::TyKind::TraitObject(bounds, lifetime_bound, kind)
1252             }
1253             TyKind::ImplTrait(def_node_id, ref bounds) => {
1254                 let span = t.span;
1255                 match itctx {
1256                     ImplTraitContext::ReturnPositionOpaqueTy { origin } => self
1257                         .lower_opaque_impl_trait(span, origin, def_node_id, |this| {
1258                             this.lower_param_bounds(bounds, itctx)
1259                         }),
1260                     ImplTraitContext::TypeAliasesOpaqueTy => {
1261                         let nested_itctx = ImplTraitContext::TypeAliasesOpaqueTy;
1262                         self.lower_opaque_impl_trait(
1263                             span,
1264                             hir::OpaqueTyOrigin::TyAlias,
1265                             def_node_id,
1266                             |this| this.lower_param_bounds(bounds, nested_itctx),
1267                         )
1268                     }
1269                     ImplTraitContext::Universal(
1270                         in_band_ty_params,
1271                         in_band_ty_bounds,
1272                         parent_def_id,
1273                     ) => {
1274                         // Add a definition for the in-band `Param`.
1275                         let def_id = self.resolver.local_def_id(def_node_id);
1276
1277                         let hir_bounds = self.lower_param_bounds(
1278                             bounds,
1279                             ImplTraitContext::Universal(
1280                                 in_band_ty_params,
1281                                 in_band_ty_bounds,
1282                                 parent_def_id,
1283                             ),
1284                         );
1285                         // Set the name to `impl Bound1 + Bound2`.
1286                         let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1287                         in_band_ty_params.push(hir::GenericParam {
1288                             hir_id: self.lower_node_id(def_node_id),
1289                             name: ParamName::Plain(self.lower_ident(ident)),
1290                             pure_wrt_drop: false,
1291                             span: self.lower_span(span),
1292                             kind: hir::GenericParamKind::Type { default: None, synthetic: true },
1293                             colon_span: None,
1294                         });
1295                         if let Some(preds) = self.lower_generic_bound_predicate(
1296                             ident,
1297                             def_node_id,
1298                             &GenericParamKind::Type { default: None },
1299                             hir_bounds,
1300                             hir::PredicateOrigin::ImplTrait,
1301                         ) {
1302                             in_band_ty_bounds.push(preds)
1303                         }
1304
1305                         hir::TyKind::Path(hir::QPath::Resolved(
1306                             None,
1307                             self.arena.alloc(hir::Path {
1308                                 span: self.lower_span(span),
1309                                 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
1310                                 segments: arena_vec![self; hir::PathSegment::from_ident(self.lower_ident(ident))],
1311                             }),
1312                         ))
1313                     }
1314                     ImplTraitContext::Disallowed(position) => {
1315                         let mut err = struct_span_err!(
1316                             self.sess,
1317                             t.span,
1318                             E0562,
1319                             "`impl Trait` only allowed in function and inherent method return types, not in {}",
1320                             position
1321                         );
1322                         err.emit();
1323                         hir::TyKind::Err
1324                     }
1325                 }
1326             }
1327             TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1328             TyKind::CVarArgs => {
1329                 self.sess.delay_span_bug(
1330                     t.span,
1331                     "`TyKind::CVarArgs` should have been handled elsewhere",
1332                 );
1333                 hir::TyKind::Err
1334             }
1335         };
1336
1337         hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1338     }
1339
1340     #[tracing::instrument(level = "debug", skip(self, lower_bounds))]
1341     fn lower_opaque_impl_trait(
1342         &mut self,
1343         span: Span,
1344         origin: hir::OpaqueTyOrigin,
1345         opaque_ty_node_id: NodeId,
1346         lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1347     ) -> hir::TyKind<'hir> {
1348         // Make sure we know that some funky desugaring has been going on here.
1349         // This is a first: there is code in other places like for loop
1350         // desugaring that explicitly states that we don't want to track that.
1351         // Not tracking it makes lints in rustc and clippy very fragile, as
1352         // frequently opened issues show.
1353         let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1354
1355         let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1356
1357         let mut collected_lifetimes = FxHashMap::default();
1358         self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1359             let hir_bounds = if origin == hir::OpaqueTyOrigin::TyAlias {
1360                 lower_bounds(lctx)
1361             } else {
1362                 lctx.while_capturing_lifetimes(
1363                     opaque_ty_def_id,
1364                     &mut collected_lifetimes,
1365                     lower_bounds,
1366                 )
1367             };
1368             debug!(?collected_lifetimes);
1369
1370             let lifetime_defs = lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(
1371                 |(_, &(span, p_id, p_name, _))| {
1372                     let hir_id = lctx.lower_node_id(p_id);
1373                     debug_assert_ne!(lctx.resolver.opt_local_def_id(p_id), None);
1374
1375                     let kind = if p_name.ident().name == kw::UnderscoreLifetime {
1376                         hir::LifetimeParamKind::Elided
1377                     } else {
1378                         hir::LifetimeParamKind::Explicit
1379                     };
1380
1381                     hir::GenericParam {
1382                         hir_id,
1383                         name: p_name,
1384                         span,
1385                         pure_wrt_drop: false,
1386                         kind: hir::GenericParamKind::Lifetime { kind },
1387                         colon_span: None,
1388                     }
1389                 },
1390             ));
1391
1392             debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1393
1394             let opaque_ty_item = hir::OpaqueTy {
1395                 generics: self.arena.alloc(hir::Generics {
1396                     params: lifetime_defs,
1397                     predicates: &[],
1398                     has_where_clause: false,
1399                     where_clause_span: lctx.lower_span(span),
1400                     span: lctx.lower_span(span),
1401                 }),
1402                 bounds: hir_bounds,
1403                 origin,
1404             };
1405
1406             trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1407             lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1408         });
1409
1410         let lifetimes = self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(
1411             |(_, (span, _, p_name, res))| {
1412                 let id = self.resolver.next_node_id();
1413                 let ident = Ident::new(p_name.ident().name, span);
1414                 let l = self.new_named_lifetime_with_res(id, span, ident, res);
1415                 hir::GenericArg::Lifetime(l)
1416             },
1417         ));
1418
1419         debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1420
1421         // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1422         hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1423     }
1424
1425     /// Registers a new opaque type with the proper `NodeId`s and
1426     /// returns the lowered node-ID for the opaque type.
1427     fn generate_opaque_type(
1428         &mut self,
1429         opaque_ty_id: LocalDefId,
1430         opaque_ty_item: hir::OpaqueTy<'hir>,
1431         span: Span,
1432         opaque_ty_span: Span,
1433     ) -> hir::OwnerNode<'hir> {
1434         let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1435         // Generate an `type Foo = impl Trait;` declaration.
1436         trace!("registering opaque type with id {:#?}", opaque_ty_id);
1437         let opaque_ty_item = hir::Item {
1438             def_id: opaque_ty_id,
1439             ident: Ident::empty(),
1440             kind: opaque_ty_item_kind,
1441             vis_span: self.lower_span(span.shrink_to_lo()),
1442             span: self.lower_span(opaque_ty_span),
1443         };
1444         hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1445     }
1446
1447     fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1448         // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1449         // as they are not explicit in HIR/Ty function signatures.
1450         // (instead, the `c_variadic` flag is set to `true`)
1451         let mut inputs = &decl.inputs[..];
1452         if decl.c_variadic() {
1453             inputs = &inputs[..inputs.len() - 1];
1454         }
1455         self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1456             PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1457             _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1458         }))
1459     }
1460
1461     // Lowers a function declaration.
1462     //
1463     // `decl`: the unlowered (AST) function declaration.
1464     // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1465     //      given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1466     //      `make_ret_async` is also `Some`.
1467     // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1468     //      This guards against trait declarations and implementations where `impl Trait` is
1469     //      disallowed.
1470     // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1471     //      return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1472     //      return type `impl Trait` item.
1473     fn lower_fn_decl(
1474         &mut self,
1475         decl: &FnDecl,
1476         mut in_band_ty_params: Option<(
1477             NodeId,
1478             &mut Vec<hir::GenericParam<'hir>>,
1479             &mut Vec<hir::WherePredicate<'hir>>,
1480         )>,
1481         kind: FnDeclKind,
1482         make_ret_async: Option<NodeId>,
1483     ) -> &'hir hir::FnDecl<'hir> {
1484         debug!(
1485             "lower_fn_decl(\
1486             fn_decl: {:?}, \
1487             in_band_ty_params: {:?}, \
1488             kind: {:?}, \
1489             make_ret_async: {:?})",
1490             decl, in_band_ty_params, kind, make_ret_async,
1491         );
1492
1493         let c_variadic = decl.c_variadic();
1494
1495         // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1496         // as they are not explicit in HIR/Ty function signatures.
1497         // (instead, the `c_variadic` flag is set to `true`)
1498         let mut inputs = &decl.inputs[..];
1499         if c_variadic {
1500             inputs = &inputs[..inputs.len() - 1];
1501         }
1502         let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1503             if let Some((_, ibty, ibpb)) = &mut in_band_ty_params {
1504                 self.lower_ty_direct(
1505                     &param.ty,
1506                     ImplTraitContext::Universal(ibty, ibpb, self.current_hir_id_owner),
1507                 )
1508             } else {
1509                 self.lower_ty_direct(
1510                     &param.ty,
1511                     ImplTraitContext::Disallowed(match kind {
1512                         FnDeclKind::Fn | FnDeclKind::Inherent => {
1513                             unreachable!("fn should allow in-band lifetimes")
1514                         }
1515                         FnDeclKind::ExternFn => ImplTraitPosition::ExternFnParam,
1516                         FnDeclKind::Closure => ImplTraitPosition::ClosureParam,
1517                         FnDeclKind::Pointer => ImplTraitPosition::PointerParam,
1518                         FnDeclKind::Trait => ImplTraitPosition::TraitParam,
1519                         FnDeclKind::Impl => ImplTraitPosition::ImplParam,
1520                     }),
1521                 )
1522             }
1523         }));
1524
1525         let output = if let Some(ret_id) = make_ret_async {
1526             self.lower_async_fn_ret_ty(
1527                 &decl.output,
1528                 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1529                 ret_id,
1530             )
1531         } else {
1532             match decl.output {
1533                 FnRetTy::Ty(ref ty) => {
1534                     let context = match in_band_ty_params {
1535                         Some((node_id, _, _)) if kind.impl_trait_return_allowed() => {
1536                             let fn_def_id = self.resolver.local_def_id(node_id);
1537                             ImplTraitContext::ReturnPositionOpaqueTy {
1538                                 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1539                             }
1540                         }
1541                         _ => ImplTraitContext::Disallowed(match kind {
1542                             FnDeclKind::Fn | FnDeclKind::Inherent => {
1543                                 unreachable!("fn should allow in-band lifetimes")
1544                             }
1545                             FnDeclKind::ExternFn => ImplTraitPosition::ExternFnReturn,
1546                             FnDeclKind::Closure => ImplTraitPosition::ClosureReturn,
1547                             FnDeclKind::Pointer => ImplTraitPosition::PointerReturn,
1548                             FnDeclKind::Trait => ImplTraitPosition::TraitReturn,
1549                             FnDeclKind::Impl => ImplTraitPosition::ImplReturn,
1550                         }),
1551                     };
1552                     hir::FnRetTy::Return(self.lower_ty(ty, context))
1553                 }
1554                 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
1555             }
1556         };
1557
1558         self.arena.alloc(hir::FnDecl {
1559             inputs,
1560             output,
1561             c_variadic,
1562             implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1563                 use BindingMode::{ByRef, ByValue};
1564                 let is_mutable_pat = matches!(
1565                     arg.pat.kind,
1566                     PatKind::Ident(ByValue(Mutability::Mut) | ByRef(Mutability::Mut), ..)
1567                 );
1568
1569                 match arg.ty.kind {
1570                     TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1571                     TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1572                     // Given we are only considering `ImplicitSelf` types, we needn't consider
1573                     // the case where we have a mutable pattern to a reference as that would
1574                     // no longer be an `ImplicitSelf`.
1575                     TyKind::Rptr(_, ref mt)
1576                         if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1577                     {
1578                         hir::ImplicitSelfKind::MutRef
1579                     }
1580                     TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1581                         hir::ImplicitSelfKind::ImmRef
1582                     }
1583                     _ => hir::ImplicitSelfKind::None,
1584                 }
1585             }),
1586         })
1587     }
1588
1589     // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1590     // combined with the following definition of `OpaqueTy`:
1591     //
1592     //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1593     //
1594     // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1595     // `output`: unlowered output type (`T` in `-> T`)
1596     // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1597     // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1598     // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1599     #[tracing::instrument(level = "debug", skip(self))]
1600     fn lower_async_fn_ret_ty(
1601         &mut self,
1602         output: &FnRetTy,
1603         fn_node_id: NodeId,
1604         opaque_ty_node_id: NodeId,
1605     ) -> hir::FnRetTy<'hir> {
1606         let span = output.span();
1607
1608         let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1609
1610         let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1611         let fn_def_id = self.resolver.local_def_id(fn_node_id);
1612
1613         // When we create the opaque type for this async fn, it is going to have
1614         // to capture all the lifetimes involved in the signature (including in the
1615         // return type). This is done by introducing lifetime parameters for:
1616         //
1617         // - all the explicitly declared lifetimes from the impl and function itself;
1618         // - all the elided lifetimes in the fn arguments;
1619         // - all the elided lifetimes in the return type.
1620         //
1621         // So for example in this snippet:
1622         //
1623         // ```rust
1624         // impl<'a> Foo<'a> {
1625         //   async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1626         //   //               ^ '0                       ^ '1     ^ '2
1627         //   // elided lifetimes used below
1628         //   }
1629         // }
1630         // ```
1631         //
1632         // we would create an opaque type like:
1633         //
1634         // ```
1635         // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1636         // ```
1637         //
1638         // and we would then desugar `bar` to the equivalent of:
1639         //
1640         // ```rust
1641         // impl<'a> Foo<'a> {
1642         //   fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1643         // }
1644         // ```
1645         //
1646         // Note that the final parameter to `Bar` is `'_`, not `'2` --
1647         // this is because the elided lifetimes from the return type
1648         // should be figured out using the ordinary elision rules, and
1649         // this desugaring achieves that.
1650
1651         // Calculate all the lifetimes that should be captured
1652         // by the opaque type. This should include all in-scope
1653         // lifetime parameters, including those defined in-band.
1654
1655         let mut captures = FxHashMap::default();
1656
1657         let extra_lifetime_params = self.resolver.take_extra_lifetime_params(opaque_ty_node_id);
1658         debug!(?extra_lifetime_params);
1659         for (ident, outer_node_id, outer_res) in extra_lifetime_params {
1660             let Ident { name, span } = ident;
1661             let outer_def_id = self.resolver.local_def_id(outer_node_id);
1662             let inner_node_id = self.resolver.next_node_id();
1663
1664             // Add a definition for the in scope lifetime def.
1665             self.resolver.create_def(
1666                 opaque_ty_def_id,
1667                 inner_node_id,
1668                 DefPathData::LifetimeNs(name),
1669                 ExpnId::root(),
1670                 span.with_parent(None),
1671             );
1672
1673             let (p_name, inner_res) = match outer_res {
1674                 // Input lifetime like `'a`:
1675                 LifetimeRes::Param { param, .. } => {
1676                     (hir::ParamName::Plain(ident), LifetimeRes::Param { param, binder: fn_node_id })
1677                 }
1678                 // Input lifetime like `'1`:
1679                 LifetimeRes::Fresh { param, .. } => (
1680                     hir::ParamName::Fresh(outer_def_id),
1681                     LifetimeRes::Fresh { param, binder: fn_node_id },
1682                 ),
1683                 LifetimeRes::Static | LifetimeRes::Error => continue,
1684                 res => {
1685                     panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span)
1686                 }
1687             };
1688
1689             captures.insert(outer_def_id, (span, inner_node_id, p_name, inner_res));
1690         }
1691
1692         debug!(?captures);
1693
1694         self.with_hir_id_owner(opaque_ty_node_id, |this| {
1695             let future_bound =
1696                 this.while_capturing_lifetimes(opaque_ty_def_id, &mut captures, |this| {
1697                     // We have to be careful to get elision right here. The
1698                     // idea is that we create a lifetime parameter for each
1699                     // lifetime in the return type.  So, given a return type
1700                     // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1701                     // Future<Output = &'1 [ &'2 u32 ]>`.
1702                     //
1703                     // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1704                     // hence the elision takes place at the fn site.
1705                     this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
1706                 });
1707             debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
1708             debug!("lower_async_fn_ret_ty: captures={:#?}", captures);
1709
1710             let generic_params =
1711                 this.arena.alloc_from_iter(captures.iter().map(|(_, &(span, p_id, p_name, _))| {
1712                     let hir_id = this.lower_node_id(p_id);
1713                     debug_assert_ne!(this.resolver.opt_local_def_id(p_id), None);
1714
1715                     let kind = if p_name.ident().name == kw::UnderscoreLifetime {
1716                         hir::LifetimeParamKind::Elided
1717                     } else {
1718                         hir::LifetimeParamKind::Explicit
1719                     };
1720
1721                     hir::GenericParam {
1722                         hir_id,
1723                         name: p_name,
1724                         span,
1725                         pure_wrt_drop: false,
1726                         kind: hir::GenericParamKind::Lifetime { kind },
1727                         colon_span: None,
1728                     }
1729                 }));
1730             debug!("lower_async_fn_ret_ty: generic_params={:#?}", generic_params);
1731
1732             let opaque_ty_item = hir::OpaqueTy {
1733                 generics: this.arena.alloc(hir::Generics {
1734                     params: generic_params,
1735                     predicates: &[],
1736                     has_where_clause: false,
1737                     where_clause_span: this.lower_span(span),
1738                     span: this.lower_span(span),
1739                 }),
1740                 bounds: arena_vec![this; future_bound],
1741                 origin: hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
1742             };
1743
1744             trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1745             this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1746         });
1747
1748         // As documented above, we need to create the lifetime
1749         // arguments to our opaque type. Continuing with our example,
1750         // we're creating the type arguments for the return type:
1751         //
1752         // ```
1753         // Bar<'a, 'b, '0, '1, '_>
1754         // ```
1755         //
1756         // For the "input" lifetime parameters, we wish to create
1757         // references to the parameters themselves, including the
1758         // "implicit" ones created from parameter types (`'a`, `'b`,
1759         // '`0`, `'1`).
1760         //
1761         // For the "output" lifetime parameters, we just want to
1762         // generate `'_`.
1763         let generic_args =
1764             self.arena.alloc_from_iter(captures.into_iter().map(|(_, (span, _, p_name, res))| {
1765                 let id = self.resolver.next_node_id();
1766                 let ident = Ident::new(p_name.ident().name, span);
1767                 let l = self.new_named_lifetime_with_res(id, span, ident, res);
1768                 hir::GenericArg::Lifetime(l)
1769             }));
1770
1771         // Create the `Foo<...>` reference itself. Note that the `type
1772         // Foo = impl Trait` is, internally, created as a child of the
1773         // async fn, so the *type parameters* are inherited.  It's
1774         // only the lifetime parameters that we must supply.
1775         let opaque_ty_ref =
1776             hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
1777         let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1778         hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1779     }
1780
1781     /// Transforms `-> T` into `Future<Output = T>`.
1782     fn lower_async_fn_output_type_to_future_bound(
1783         &mut self,
1784         output: &FnRetTy,
1785         fn_def_id: LocalDefId,
1786         span: Span,
1787     ) -> hir::GenericBound<'hir> {
1788         // Compute the `T` in `Future<Output = T>` from the return type.
1789         let output_ty = match output {
1790             FnRetTy::Ty(ty) => {
1791                 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1792                 // `impl Future` opaque type that `async fn` implicitly
1793                 // generates.
1794                 let context = ImplTraitContext::ReturnPositionOpaqueTy {
1795                     origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1796                 };
1797                 self.lower_ty(ty, context)
1798             }
1799             FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1800         };
1801
1802         // "<Output = T>"
1803         let future_args = self.arena.alloc(hir::GenericArgs {
1804             args: &[],
1805             bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
1806             parenthesized: false,
1807             span_ext: DUMMY_SP,
1808         });
1809
1810         hir::GenericBound::LangItemTrait(
1811             // ::std::future::Future<future_params>
1812             hir::LangItem::Future,
1813             self.lower_span(span),
1814             self.next_id(),
1815             future_args,
1816         )
1817     }
1818
1819     fn lower_param_bound(
1820         &mut self,
1821         tpb: &GenericBound,
1822         itctx: ImplTraitContext<'_, 'hir>,
1823     ) -> hir::GenericBound<'hir> {
1824         match tpb {
1825             GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
1826                 self.lower_poly_trait_ref(p, itctx),
1827                 self.lower_trait_bound_modifier(*modifier),
1828             ),
1829             GenericBound::Outlives(lifetime) => {
1830                 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
1831             }
1832         }
1833     }
1834
1835     fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1836         let span = self.lower_span(l.ident.span);
1837         let ident = self.lower_ident(l.ident);
1838         let res = self
1839             .resolver
1840             .get_lifetime_res(l.id)
1841             .unwrap_or_else(|| panic!("Missing resolution for lifetime {:?} at {:?}", l, span));
1842         self.new_named_lifetime_with_res(l.id, span, ident, res)
1843     }
1844
1845     #[tracing::instrument(level = "debug", skip(self))]
1846     fn new_named_lifetime_with_res(
1847         &mut self,
1848         id: NodeId,
1849         span: Span,
1850         ident: Ident,
1851         res: LifetimeRes,
1852     ) -> hir::Lifetime {
1853         debug!(?self.captured_lifetimes);
1854         let name = match res {
1855             LifetimeRes::Param { param, binder } => {
1856                 debug_assert_ne!(ident.name, kw::UnderscoreLifetime);
1857                 let p_name = ParamName::Plain(ident);
1858                 if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) =
1859                     &mut self.captured_lifetimes
1860                     && !binders_to_ignore.contains(&binder)
1861                 {
1862                     match captures.entry(param) {
1863                         Entry::Occupied(_) => {}
1864                         Entry::Vacant(v) => {
1865                             let p_id = self.resolver.next_node_id();
1866                             self.resolver.create_def(
1867                                 *parent_def_id,
1868                                 p_id,
1869                                 DefPathData::LifetimeNs(p_name.ident().name),
1870                                 ExpnId::root(),
1871                                 span.with_parent(None),
1872                             );
1873
1874                             v.insert((span, p_id, p_name, res));
1875                         }
1876                     }
1877                 }
1878                 hir::LifetimeName::Param(p_name)
1879             }
1880             LifetimeRes::Fresh { mut param, binder } => {
1881                 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1882                 if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) =
1883                     &mut self.captured_lifetimes
1884                     && !binders_to_ignore.contains(&binder)
1885                 {
1886                     match captures.entry(param) {
1887                         Entry::Occupied(o) => param = self.resolver.local_def_id(o.get().1),
1888                         Entry::Vacant(v) => {
1889                             let p_id = self.resolver.next_node_id();
1890                             let p_def_id = self.resolver.create_def(
1891                                 *parent_def_id,
1892                                 p_id,
1893                                 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1894                                 ExpnId::root(),
1895                                 span.with_parent(None),
1896                             );
1897
1898                             let p_name = ParamName::Fresh(param);
1899                             v.insert((span, p_id, p_name, res));
1900                             param = p_def_id;
1901                         }
1902                     }
1903                 }
1904                 let p_name = ParamName::Fresh(param);
1905                 hir::LifetimeName::Param(p_name)
1906             }
1907             LifetimeRes::Anonymous { binder, elided } => {
1908                 let l_name = if elided {
1909                     hir::LifetimeName::Implicit
1910                 } else {
1911                     hir::LifetimeName::Underscore
1912                 };
1913                 if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) =
1914                     &mut self.captured_lifetimes
1915                     && !binders_to_ignore.contains(&binder)
1916                 {
1917                     let p_id = self.resolver.next_node_id();
1918                     let p_def_id = self.resolver.create_def(
1919                         *parent_def_id,
1920                         p_id,
1921                         DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1922                         ExpnId::root(),
1923                         span.with_parent(None),
1924                     );
1925                     let p_name = ParamName::Fresh(p_def_id);
1926                     captures.insert(p_def_id, (span, p_id, p_name, res));
1927                     hir::LifetimeName::Param(p_name)
1928                 } else {
1929                     l_name
1930                 }
1931             }
1932             LifetimeRes::Static => hir::LifetimeName::Static,
1933             LifetimeRes::Error => hir::LifetimeName::Error,
1934             res => panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span),
1935         };
1936         debug!(?self.captured_lifetimes);
1937         hir::Lifetime { hir_id: self.lower_node_id(id), span: self.lower_span(span), name }
1938     }
1939
1940     fn lower_generic_params_mut<'s>(
1941         &'s mut self,
1942         params: &'s [GenericParam],
1943     ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
1944         params.iter().map(move |param| self.lower_generic_param(param))
1945     }
1946
1947     fn lower_generic_params(&mut self, params: &[GenericParam]) -> &'hir [hir::GenericParam<'hir>] {
1948         self.arena.alloc_from_iter(self.lower_generic_params_mut(params))
1949     }
1950
1951     fn lower_generic_param(&mut self, param: &GenericParam) -> hir::GenericParam<'hir> {
1952         let (name, kind) = match param.kind {
1953             GenericParamKind::Lifetime => {
1954                 let param_name = if param.ident.name == kw::StaticLifetime
1955                     || param.ident.name == kw::UnderscoreLifetime
1956                 {
1957                     ParamName::Error
1958                 } else {
1959                     let ident = self.lower_ident(param.ident);
1960                     ParamName::Plain(ident)
1961                 };
1962                 let kind =
1963                     hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
1964
1965                 (param_name, kind)
1966             }
1967             GenericParamKind::Type { ref default, .. } => {
1968                 let kind = hir::GenericParamKind::Type {
1969                     default: default.as_ref().map(|x| {
1970                         self.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
1971                     }),
1972                     synthetic: false,
1973                 };
1974
1975                 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
1976             }
1977             GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1978                 let ty = self.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
1979                 let default = default.as_ref().map(|def| self.lower_anon_const(def));
1980                 (
1981                     hir::ParamName::Plain(self.lower_ident(param.ident)),
1982                     hir::GenericParamKind::Const { ty, default },
1983                 )
1984             }
1985         };
1986         let name = match name {
1987             hir::ParamName::Plain(ident) => hir::ParamName::Plain(self.lower_ident(ident)),
1988             name => name,
1989         };
1990
1991         let hir_id = self.lower_node_id(param.id);
1992         self.lower_attrs(hir_id, &param.attrs);
1993         hir::GenericParam {
1994             hir_id,
1995             name,
1996             span: self.lower_span(param.span()),
1997             pure_wrt_drop: self.sess.contains_name(&param.attrs, sym::may_dangle),
1998             kind,
1999             colon_span: param.colon_span.map(|s| self.lower_span(s)),
2000         }
2001     }
2002
2003     fn lower_trait_ref(
2004         &mut self,
2005         p: &TraitRef,
2006         itctx: ImplTraitContext<'_, 'hir>,
2007     ) -> hir::TraitRef<'hir> {
2008         let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2009             hir::QPath::Resolved(None, path) => path,
2010             qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2011         };
2012         hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2013     }
2014
2015     #[tracing::instrument(level = "debug", skip(self))]
2016     fn lower_poly_trait_ref(
2017         &mut self,
2018         p: &PolyTraitRef,
2019         mut itctx: ImplTraitContext<'_, 'hir>,
2020     ) -> hir::PolyTraitRef<'hir> {
2021         let bound_generic_params = self.lower_generic_params(&p.bound_generic_params);
2022
2023         let trait_ref = self.with_lifetime_binder(p.trait_ref.ref_id, |this| {
2024             this.lower_trait_ref(&p.trait_ref, itctx.reborrow())
2025         });
2026
2027         hir::PolyTraitRef { bound_generic_params, trait_ref, span: self.lower_span(p.span) }
2028     }
2029
2030     fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2031         hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2032     }
2033
2034     fn lower_param_bounds(
2035         &mut self,
2036         bounds: &[GenericBound],
2037         itctx: ImplTraitContext<'_, 'hir>,
2038     ) -> hir::GenericBounds<'hir> {
2039         self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2040     }
2041
2042     fn lower_param_bounds_mut<'s>(
2043         &'s mut self,
2044         bounds: &'s [GenericBound],
2045         mut itctx: ImplTraitContext<'s, 'hir>,
2046     ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2047         bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2048     }
2049
2050     /// Lowers a block directly to an expression, presuming that it
2051     /// has no attributes and is not targeted by a `break`.
2052     fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2053         let block = self.lower_block(b, false);
2054         self.expr_block(block, AttrVec::new())
2055     }
2056
2057     fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen {
2058         match c.value.kind {
2059             ExprKind::Underscore => {
2060                 if self.sess.features_untracked().generic_arg_infer {
2061                     hir::ArrayLen::Infer(self.lower_node_id(c.id), c.value.span)
2062                 } else {
2063                     feature_err(
2064                         &self.sess.parse_sess,
2065                         sym::generic_arg_infer,
2066                         c.value.span,
2067                         "using `_` for array lengths is unstable",
2068                     )
2069                     .emit();
2070                     hir::ArrayLen::Body(self.lower_anon_const(c))
2071                 }
2072             }
2073             _ => hir::ArrayLen::Body(self.lower_anon_const(c)),
2074         }
2075     }
2076
2077     fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2078         self.with_new_scopes(|this| hir::AnonConst {
2079             hir_id: this.lower_node_id(c.id),
2080             body: this.lower_const_body(c.value.span, Some(&c.value)),
2081         })
2082     }
2083
2084     fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2085         match u {
2086             CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2087             UserProvided => hir::UnsafeSource::UserProvided,
2088         }
2089     }
2090
2091     fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2092         match f {
2093             TraitBoundModifier::None => hir::TraitBoundModifier::None,
2094             TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2095
2096             // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2097             // placeholder for compilation to proceed.
2098             TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2099                 hir::TraitBoundModifier::Maybe
2100             }
2101         }
2102     }
2103
2104     // Helper methods for building HIR.
2105
2106     fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2107         hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2108     }
2109
2110     fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2111         self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2112     }
2113
2114     fn stmt_let_pat(
2115         &mut self,
2116         attrs: Option<&'hir [Attribute]>,
2117         span: Span,
2118         init: Option<&'hir hir::Expr<'hir>>,
2119         pat: &'hir hir::Pat<'hir>,
2120         source: hir::LocalSource,
2121     ) -> hir::Stmt<'hir> {
2122         let hir_id = self.next_id();
2123         if let Some(a) = attrs {
2124             debug_assert!(!a.is_empty());
2125             self.attrs.insert(hir_id.local_id, a);
2126         }
2127         let local = hir::Local { hir_id, init, pat, source, span: self.lower_span(span), ty: None };
2128         self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2129     }
2130
2131     fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2132         self.block_all(expr.span, &[], Some(expr))
2133     }
2134
2135     fn block_all(
2136         &mut self,
2137         span: Span,
2138         stmts: &'hir [hir::Stmt<'hir>],
2139         expr: Option<&'hir hir::Expr<'hir>>,
2140     ) -> &'hir hir::Block<'hir> {
2141         let blk = hir::Block {
2142             stmts,
2143             expr,
2144             hir_id: self.next_id(),
2145             rules: hir::BlockCheckMode::DefaultBlock,
2146             span: self.lower_span(span),
2147             targeted_by_break: false,
2148         };
2149         self.arena.alloc(blk)
2150     }
2151
2152     fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2153         let field = self.single_pat_field(span, pat);
2154         self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field, None)
2155     }
2156
2157     fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2158         let field = self.single_pat_field(span, pat);
2159         self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field, None)
2160     }
2161
2162     fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2163         let field = self.single_pat_field(span, pat);
2164         self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field, None)
2165     }
2166
2167     fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2168         self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[], None)
2169     }
2170
2171     fn single_pat_field(
2172         &mut self,
2173         span: Span,
2174         pat: &'hir hir::Pat<'hir>,
2175     ) -> &'hir [hir::PatField<'hir>] {
2176         let field = hir::PatField {
2177             hir_id: self.next_id(),
2178             ident: Ident::new(sym::integer(0), self.lower_span(span)),
2179             is_shorthand: false,
2180             pat,
2181             span: self.lower_span(span),
2182         };
2183         arena_vec![self; field]
2184     }
2185
2186     fn pat_lang_item_variant(
2187         &mut self,
2188         span: Span,
2189         lang_item: hir::LangItem,
2190         fields: &'hir [hir::PatField<'hir>],
2191         hir_id: Option<hir::HirId>,
2192     ) -> &'hir hir::Pat<'hir> {
2193         let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id);
2194         self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2195     }
2196
2197     fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2198         self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2199     }
2200
2201     fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2202         self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::Unannotated)
2203     }
2204
2205     fn pat_ident_binding_mode(
2206         &mut self,
2207         span: Span,
2208         ident: Ident,
2209         bm: hir::BindingAnnotation,
2210     ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2211         let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2212         (self.arena.alloc(pat), hir_id)
2213     }
2214
2215     fn pat_ident_binding_mode_mut(
2216         &mut self,
2217         span: Span,
2218         ident: Ident,
2219         bm: hir::BindingAnnotation,
2220     ) -> (hir::Pat<'hir>, hir::HirId) {
2221         let hir_id = self.next_id();
2222
2223         (
2224             hir::Pat {
2225                 hir_id,
2226                 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2227                 span: self.lower_span(span),
2228                 default_binding_modes: true,
2229             },
2230             hir_id,
2231         )
2232     }
2233
2234     fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2235         self.arena.alloc(hir::Pat {
2236             hir_id: self.next_id(),
2237             kind,
2238             span: self.lower_span(span),
2239             default_binding_modes: true,
2240         })
2241     }
2242
2243     fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2244         hir::Pat {
2245             hir_id: self.next_id(),
2246             kind,
2247             span: self.lower_span(span),
2248             default_binding_modes: false,
2249         }
2250     }
2251
2252     fn ty_path(
2253         &mut self,
2254         mut hir_id: hir::HirId,
2255         span: Span,
2256         qpath: hir::QPath<'hir>,
2257     ) -> hir::Ty<'hir> {
2258         let kind = match qpath {
2259             hir::QPath::Resolved(None, path) => {
2260                 // Turn trait object paths into `TyKind::TraitObject` instead.
2261                 match path.res {
2262                     Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2263                         let principal = hir::PolyTraitRef {
2264                             bound_generic_params: &[],
2265                             trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2266                             span: self.lower_span(span),
2267                         };
2268
2269                         // The original ID is taken by the `PolyTraitRef`,
2270                         // so the `Ty` itself needs a different one.
2271                         hir_id = self.next_id();
2272                         hir::TyKind::TraitObject(
2273                             arena_vec![self; principal],
2274                             self.elided_dyn_bound(span),
2275                             TraitObjectSyntax::None,
2276                         )
2277                     }
2278                     _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2279                 }
2280             }
2281             _ => hir::TyKind::Path(qpath),
2282         };
2283
2284         hir::Ty { hir_id, kind, span: self.lower_span(span) }
2285     }
2286
2287     /// Invoked to create the lifetime argument(s) for an elided trait object
2288     /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2289     /// when the bound is written, even if it is written with `'_` like in
2290     /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2291     fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2292         let r = hir::Lifetime {
2293             hir_id: self.next_id(),
2294             span: self.lower_span(span),
2295             name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2296         };
2297         debug!("elided_dyn_bound: r={:?}", r);
2298         r
2299     }
2300 }
2301
2302 /// Helper struct for delayed construction of GenericArgs.
2303 struct GenericArgsCtor<'hir> {
2304     args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2305     bindings: &'hir [hir::TypeBinding<'hir>],
2306     parenthesized: bool,
2307     span: Span,
2308 }
2309
2310 impl<'hir> GenericArgsCtor<'hir> {
2311     fn is_empty(&self) -> bool {
2312         self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2313     }
2314
2315     fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2316         let ga = hir::GenericArgs {
2317             args: this.arena.alloc_from_iter(self.args),
2318             bindings: self.bindings,
2319             parenthesized: self.parenthesized,
2320             span_ext: this.lower_span(self.span),
2321         };
2322         this.arena.alloc(ga)
2323     }
2324 }