]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/lib.rs
Rollup merge of #97236 - cjgillot:recover-lifetime-res, r=jackh726
[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 id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1172                         self.resolver.get_lifetime_res(t.id)
1173                     {
1174                         debug_assert_eq!(start.plus(1), end);
1175                         start
1176                     } else {
1177                         self.resolver.next_node_id()
1178                     };
1179                     let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1180                     Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id }
1181                 });
1182                 let lifetime = self.lower_lifetime(&region);
1183                 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1184             }
1185             TyKind::BareFn(ref f) => self.with_lifetime_binder(t.id, |this| {
1186                 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1187                     generic_params: this.lower_generic_params(&f.generic_params),
1188                     unsafety: this.lower_unsafety(f.unsafety),
1189                     abi: this.lower_extern(f.ext),
1190                     decl: this.lower_fn_decl(&f.decl, None, FnDeclKind::Pointer, None),
1191                     param_names: this.lower_fn_params_to_names(&f.decl),
1192                 }))
1193             }),
1194             TyKind::Never => hir::TyKind::Never,
1195             TyKind::Tup(ref tys) => {
1196                 hir::TyKind::Tup(self.arena.alloc_from_iter(
1197                     tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1198                 ))
1199             }
1200             TyKind::Paren(ref ty) => {
1201                 return self.lower_ty_direct(ty, itctx);
1202             }
1203             TyKind::Path(ref qself, ref path) => {
1204                 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1205             }
1206             TyKind::ImplicitSelf => {
1207                 let res = self.expect_full_res(t.id);
1208                 let res = self.lower_res(res);
1209                 hir::TyKind::Path(hir::QPath::Resolved(
1210                     None,
1211                     self.arena.alloc(hir::Path {
1212                         res,
1213                         segments: arena_vec![self; hir::PathSegment::from_ident(
1214                             Ident::with_dummy_span(kw::SelfUpper)
1215                         )],
1216                         span: self.lower_span(t.span),
1217                     }),
1218                 ))
1219             }
1220             TyKind::Array(ref ty, ref length) => {
1221                 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_array_length(length))
1222             }
1223             TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1224             TyKind::TraitObject(ref bounds, kind) => {
1225                 let mut lifetime_bound = None;
1226                 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1227                     let bounds =
1228                         this.arena.alloc_from_iter(bounds.iter().filter_map(
1229                             |bound| match *bound {
1230                                 GenericBound::Trait(
1231                                     ref ty,
1232                                     TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1233                                 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
1234                                 // `~const ?Bound` will cause an error during AST validation
1235                                 // anyways, so treat it like `?Bound` as compilation proceeds.
1236                                 GenericBound::Trait(
1237                                     _,
1238                                     TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1239                                 ) => None,
1240                                 GenericBound::Outlives(ref lifetime) => {
1241                                     if lifetime_bound.is_none() {
1242                                         lifetime_bound = Some(this.lower_lifetime(lifetime));
1243                                     }
1244                                     None
1245                                 }
1246                             },
1247                         ));
1248                     let lifetime_bound =
1249                         lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1250                     (bounds, lifetime_bound)
1251                 });
1252                 hir::TyKind::TraitObject(bounds, lifetime_bound, kind)
1253             }
1254             TyKind::ImplTrait(def_node_id, ref bounds) => {
1255                 let span = t.span;
1256                 match itctx {
1257                     ImplTraitContext::ReturnPositionOpaqueTy { origin } => self
1258                         .lower_opaque_impl_trait(span, origin, def_node_id, |this| {
1259                             this.lower_param_bounds(bounds, itctx)
1260                         }),
1261                     ImplTraitContext::TypeAliasesOpaqueTy => {
1262                         let nested_itctx = ImplTraitContext::TypeAliasesOpaqueTy;
1263                         self.lower_opaque_impl_trait(
1264                             span,
1265                             hir::OpaqueTyOrigin::TyAlias,
1266                             def_node_id,
1267                             |this| this.lower_param_bounds(bounds, nested_itctx),
1268                         )
1269                     }
1270                     ImplTraitContext::Universal(
1271                         in_band_ty_params,
1272                         in_band_ty_bounds,
1273                         parent_def_id,
1274                     ) => {
1275                         // Add a definition for the in-band `Param`.
1276                         let def_id = self.resolver.local_def_id(def_node_id);
1277
1278                         let hir_bounds = self.lower_param_bounds(
1279                             bounds,
1280                             ImplTraitContext::Universal(
1281                                 in_band_ty_params,
1282                                 in_band_ty_bounds,
1283                                 parent_def_id,
1284                             ),
1285                         );
1286                         // Set the name to `impl Bound1 + Bound2`.
1287                         let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1288                         in_band_ty_params.push(hir::GenericParam {
1289                             hir_id: self.lower_node_id(def_node_id),
1290                             name: ParamName::Plain(self.lower_ident(ident)),
1291                             pure_wrt_drop: false,
1292                             span: self.lower_span(span),
1293                             kind: hir::GenericParamKind::Type { default: None, synthetic: true },
1294                             colon_span: None,
1295                         });
1296                         if let Some(preds) = self.lower_generic_bound_predicate(
1297                             ident,
1298                             def_node_id,
1299                             &GenericParamKind::Type { default: None },
1300                             hir_bounds,
1301                             hir::PredicateOrigin::ImplTrait,
1302                         ) {
1303                             in_band_ty_bounds.push(preds)
1304                         }
1305
1306                         hir::TyKind::Path(hir::QPath::Resolved(
1307                             None,
1308                             self.arena.alloc(hir::Path {
1309                                 span: self.lower_span(span),
1310                                 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
1311                                 segments: arena_vec![self; hir::PathSegment::from_ident(self.lower_ident(ident))],
1312                             }),
1313                         ))
1314                     }
1315                     ImplTraitContext::Disallowed(position) => {
1316                         let mut err = struct_span_err!(
1317                             self.sess,
1318                             t.span,
1319                             E0562,
1320                             "`impl Trait` only allowed in function and inherent method return types, not in {}",
1321                             position
1322                         );
1323                         err.emit();
1324                         hir::TyKind::Err
1325                     }
1326                 }
1327             }
1328             TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1329             TyKind::CVarArgs => {
1330                 self.sess.delay_span_bug(
1331                     t.span,
1332                     "`TyKind::CVarArgs` should have been handled elsewhere",
1333                 );
1334                 hir::TyKind::Err
1335             }
1336         };
1337
1338         hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1339     }
1340
1341     #[tracing::instrument(level = "debug", skip(self, lower_bounds))]
1342     fn lower_opaque_impl_trait(
1343         &mut self,
1344         span: Span,
1345         origin: hir::OpaqueTyOrigin,
1346         opaque_ty_node_id: NodeId,
1347         lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1348     ) -> hir::TyKind<'hir> {
1349         // Make sure we know that some funky desugaring has been going on here.
1350         // This is a first: there is code in other places like for loop
1351         // desugaring that explicitly states that we don't want to track that.
1352         // Not tracking it makes lints in rustc and clippy very fragile, as
1353         // frequently opened issues show.
1354         let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1355
1356         let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1357
1358         let mut collected_lifetimes = FxHashMap::default();
1359         self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1360             let hir_bounds = if origin == hir::OpaqueTyOrigin::TyAlias {
1361                 lower_bounds(lctx)
1362             } else {
1363                 lctx.while_capturing_lifetimes(
1364                     opaque_ty_def_id,
1365                     &mut collected_lifetimes,
1366                     lower_bounds,
1367                 )
1368             };
1369             debug!(?collected_lifetimes);
1370
1371             let lifetime_defs = lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(
1372                 |(_, &(span, p_id, p_name, _))| {
1373                     let hir_id = lctx.lower_node_id(p_id);
1374                     debug_assert_ne!(lctx.resolver.opt_local_def_id(p_id), None);
1375
1376                     let kind = if p_name.ident().name == kw::UnderscoreLifetime {
1377                         hir::LifetimeParamKind::Elided
1378                     } else {
1379                         hir::LifetimeParamKind::Explicit
1380                     };
1381
1382                     hir::GenericParam {
1383                         hir_id,
1384                         name: p_name,
1385                         span,
1386                         pure_wrt_drop: false,
1387                         kind: hir::GenericParamKind::Lifetime { kind },
1388                         colon_span: None,
1389                     }
1390                 },
1391             ));
1392
1393             debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1394
1395             let opaque_ty_item = hir::OpaqueTy {
1396                 generics: self.arena.alloc(hir::Generics {
1397                     params: lifetime_defs,
1398                     predicates: &[],
1399                     has_where_clause: false,
1400                     where_clause_span: lctx.lower_span(span),
1401                     span: lctx.lower_span(span),
1402                 }),
1403                 bounds: hir_bounds,
1404                 origin,
1405             };
1406
1407             trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1408             lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1409         });
1410
1411         let lifetimes = self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(
1412             |(_, (span, _, p_name, res))| {
1413                 let id = self.resolver.next_node_id();
1414                 let ident = Ident::new(p_name.ident().name, span);
1415                 let l = self.new_named_lifetime_with_res(id, span, ident, res);
1416                 hir::GenericArg::Lifetime(l)
1417             },
1418         ));
1419
1420         debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1421
1422         // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1423         hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1424     }
1425
1426     /// Registers a new opaque type with the proper `NodeId`s and
1427     /// returns the lowered node-ID for the opaque type.
1428     fn generate_opaque_type(
1429         &mut self,
1430         opaque_ty_id: LocalDefId,
1431         opaque_ty_item: hir::OpaqueTy<'hir>,
1432         span: Span,
1433         opaque_ty_span: Span,
1434     ) -> hir::OwnerNode<'hir> {
1435         let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1436         // Generate an `type Foo = impl Trait;` declaration.
1437         trace!("registering opaque type with id {:#?}", opaque_ty_id);
1438         let opaque_ty_item = hir::Item {
1439             def_id: opaque_ty_id,
1440             ident: Ident::empty(),
1441             kind: opaque_ty_item_kind,
1442             vis_span: self.lower_span(span.shrink_to_lo()),
1443             span: self.lower_span(opaque_ty_span),
1444         };
1445         hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1446     }
1447
1448     fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1449         // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1450         // as they are not explicit in HIR/Ty function signatures.
1451         // (instead, the `c_variadic` flag is set to `true`)
1452         let mut inputs = &decl.inputs[..];
1453         if decl.c_variadic() {
1454             inputs = &inputs[..inputs.len() - 1];
1455         }
1456         self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1457             PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1458             _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1459         }))
1460     }
1461
1462     // Lowers a function declaration.
1463     //
1464     // `decl`: the unlowered (AST) function declaration.
1465     // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1466     //      given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1467     //      `make_ret_async` is also `Some`.
1468     // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1469     //      This guards against trait declarations and implementations where `impl Trait` is
1470     //      disallowed.
1471     // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1472     //      return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1473     //      return type `impl Trait` item.
1474     fn lower_fn_decl(
1475         &mut self,
1476         decl: &FnDecl,
1477         mut in_band_ty_params: Option<(
1478             NodeId,
1479             &mut Vec<hir::GenericParam<'hir>>,
1480             &mut Vec<hir::WherePredicate<'hir>>,
1481         )>,
1482         kind: FnDeclKind,
1483         make_ret_async: Option<NodeId>,
1484     ) -> &'hir hir::FnDecl<'hir> {
1485         debug!(
1486             "lower_fn_decl(\
1487             fn_decl: {:?}, \
1488             in_band_ty_params: {:?}, \
1489             kind: {:?}, \
1490             make_ret_async: {:?})",
1491             decl, in_band_ty_params, kind, make_ret_async,
1492         );
1493
1494         let c_variadic = decl.c_variadic();
1495
1496         // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1497         // as they are not explicit in HIR/Ty function signatures.
1498         // (instead, the `c_variadic` flag is set to `true`)
1499         let mut inputs = &decl.inputs[..];
1500         if c_variadic {
1501             inputs = &inputs[..inputs.len() - 1];
1502         }
1503         let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1504             if let Some((_, ibty, ibpb)) = &mut in_band_ty_params {
1505                 self.lower_ty_direct(
1506                     &param.ty,
1507                     ImplTraitContext::Universal(ibty, ibpb, self.current_hir_id_owner),
1508                 )
1509             } else {
1510                 self.lower_ty_direct(
1511                     &param.ty,
1512                     ImplTraitContext::Disallowed(match kind {
1513                         FnDeclKind::Fn | FnDeclKind::Inherent => {
1514                             unreachable!("fn should allow in-band lifetimes")
1515                         }
1516                         FnDeclKind::ExternFn => ImplTraitPosition::ExternFnParam,
1517                         FnDeclKind::Closure => ImplTraitPosition::ClosureParam,
1518                         FnDeclKind::Pointer => ImplTraitPosition::PointerParam,
1519                         FnDeclKind::Trait => ImplTraitPosition::TraitParam,
1520                         FnDeclKind::Impl => ImplTraitPosition::ImplParam,
1521                     }),
1522                 )
1523             }
1524         }));
1525
1526         let output = if let Some(ret_id) = make_ret_async {
1527             self.lower_async_fn_ret_ty(
1528                 &decl.output,
1529                 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1530                 ret_id,
1531             )
1532         } else {
1533             match decl.output {
1534                 FnRetTy::Ty(ref ty) => {
1535                     let context = match in_band_ty_params {
1536                         Some((node_id, _, _)) if kind.impl_trait_return_allowed() => {
1537                             let fn_def_id = self.resolver.local_def_id(node_id);
1538                             ImplTraitContext::ReturnPositionOpaqueTy {
1539                                 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1540                             }
1541                         }
1542                         _ => ImplTraitContext::Disallowed(match kind {
1543                             FnDeclKind::Fn | FnDeclKind::Inherent => {
1544                                 unreachable!("fn should allow in-band lifetimes")
1545                             }
1546                             FnDeclKind::ExternFn => ImplTraitPosition::ExternFnReturn,
1547                             FnDeclKind::Closure => ImplTraitPosition::ClosureReturn,
1548                             FnDeclKind::Pointer => ImplTraitPosition::PointerReturn,
1549                             FnDeclKind::Trait => ImplTraitPosition::TraitReturn,
1550                             FnDeclKind::Impl => ImplTraitPosition::ImplReturn,
1551                         }),
1552                     };
1553                     hir::FnRetTy::Return(self.lower_ty(ty, context))
1554                 }
1555                 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
1556             }
1557         };
1558
1559         self.arena.alloc(hir::FnDecl {
1560             inputs,
1561             output,
1562             c_variadic,
1563             implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1564                 use BindingMode::{ByRef, ByValue};
1565                 let is_mutable_pat = matches!(
1566                     arg.pat.kind,
1567                     PatKind::Ident(ByValue(Mutability::Mut) | ByRef(Mutability::Mut), ..)
1568                 );
1569
1570                 match arg.ty.kind {
1571                     TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1572                     TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1573                     // Given we are only considering `ImplicitSelf` types, we needn't consider
1574                     // the case where we have a mutable pattern to a reference as that would
1575                     // no longer be an `ImplicitSelf`.
1576                     TyKind::Rptr(_, ref mt)
1577                         if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1578                     {
1579                         hir::ImplicitSelfKind::MutRef
1580                     }
1581                     TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1582                         hir::ImplicitSelfKind::ImmRef
1583                     }
1584                     _ => hir::ImplicitSelfKind::None,
1585                 }
1586             }),
1587         })
1588     }
1589
1590     // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1591     // combined with the following definition of `OpaqueTy`:
1592     //
1593     //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1594     //
1595     // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1596     // `output`: unlowered output type (`T` in `-> T`)
1597     // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1598     // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1599     // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1600     #[tracing::instrument(level = "debug", skip(self))]
1601     fn lower_async_fn_ret_ty(
1602         &mut self,
1603         output: &FnRetTy,
1604         fn_node_id: NodeId,
1605         opaque_ty_node_id: NodeId,
1606     ) -> hir::FnRetTy<'hir> {
1607         let span = output.span();
1608
1609         let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1610
1611         let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1612         let fn_def_id = self.resolver.local_def_id(fn_node_id);
1613
1614         // When we create the opaque type for this async fn, it is going to have
1615         // to capture all the lifetimes involved in the signature (including in the
1616         // return type). This is done by introducing lifetime parameters for:
1617         //
1618         // - all the explicitly declared lifetimes from the impl and function itself;
1619         // - all the elided lifetimes in the fn arguments;
1620         // - all the elided lifetimes in the return type.
1621         //
1622         // So for example in this snippet:
1623         //
1624         // ```rust
1625         // impl<'a> Foo<'a> {
1626         //   async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1627         //   //               ^ '0                       ^ '1     ^ '2
1628         //   // elided lifetimes used below
1629         //   }
1630         // }
1631         // ```
1632         //
1633         // we would create an opaque type like:
1634         //
1635         // ```
1636         // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1637         // ```
1638         //
1639         // and we would then desugar `bar` to the equivalent of:
1640         //
1641         // ```rust
1642         // impl<'a> Foo<'a> {
1643         //   fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1644         // }
1645         // ```
1646         //
1647         // Note that the final parameter to `Bar` is `'_`, not `'2` --
1648         // this is because the elided lifetimes from the return type
1649         // should be figured out using the ordinary elision rules, and
1650         // this desugaring achieves that.
1651
1652         // Calculate all the lifetimes that should be captured
1653         // by the opaque type. This should include all in-scope
1654         // lifetime parameters, including those defined in-band.
1655
1656         let mut captures = FxHashMap::default();
1657
1658         let extra_lifetime_params = self.resolver.take_extra_lifetime_params(opaque_ty_node_id);
1659         debug!(?extra_lifetime_params);
1660         for (ident, outer_node_id, outer_res) in extra_lifetime_params {
1661             let Ident { name, span } = ident;
1662             let outer_def_id = self.resolver.local_def_id(outer_node_id);
1663             let inner_node_id = self.resolver.next_node_id();
1664
1665             // Add a definition for the in scope lifetime def.
1666             self.resolver.create_def(
1667                 opaque_ty_def_id,
1668                 inner_node_id,
1669                 DefPathData::LifetimeNs(name),
1670                 ExpnId::root(),
1671                 span.with_parent(None),
1672             );
1673
1674             let (p_name, inner_res) = match outer_res {
1675                 // Input lifetime like `'a`:
1676                 LifetimeRes::Param { param, .. } => {
1677                     (hir::ParamName::Plain(ident), LifetimeRes::Param { param, binder: fn_node_id })
1678                 }
1679                 // Input lifetime like `'1`:
1680                 LifetimeRes::Fresh { param, .. } => (
1681                     hir::ParamName::Fresh(outer_def_id),
1682                     LifetimeRes::Fresh { param, binder: fn_node_id },
1683                 ),
1684                 LifetimeRes::Static | LifetimeRes::Error => continue,
1685                 res => {
1686                     panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span)
1687                 }
1688             };
1689
1690             captures.insert(outer_def_id, (span, inner_node_id, p_name, inner_res));
1691         }
1692
1693         debug!(?captures);
1694
1695         self.with_hir_id_owner(opaque_ty_node_id, |this| {
1696             let future_bound =
1697                 this.while_capturing_lifetimes(opaque_ty_def_id, &mut captures, |this| {
1698                     // We have to be careful to get elision right here. The
1699                     // idea is that we create a lifetime parameter for each
1700                     // lifetime in the return type.  So, given a return type
1701                     // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1702                     // Future<Output = &'1 [ &'2 u32 ]>`.
1703                     //
1704                     // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1705                     // hence the elision takes place at the fn site.
1706                     this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
1707                 });
1708             debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
1709             debug!("lower_async_fn_ret_ty: captures={:#?}", captures);
1710
1711             let generic_params =
1712                 this.arena.alloc_from_iter(captures.iter().map(|(_, &(span, p_id, p_name, _))| {
1713                     let hir_id = this.lower_node_id(p_id);
1714                     debug_assert_ne!(this.resolver.opt_local_def_id(p_id), None);
1715
1716                     let kind = if p_name.ident().name == kw::UnderscoreLifetime {
1717                         hir::LifetimeParamKind::Elided
1718                     } else {
1719                         hir::LifetimeParamKind::Explicit
1720                     };
1721
1722                     hir::GenericParam {
1723                         hir_id,
1724                         name: p_name,
1725                         span,
1726                         pure_wrt_drop: false,
1727                         kind: hir::GenericParamKind::Lifetime { kind },
1728                         colon_span: None,
1729                     }
1730                 }));
1731             debug!("lower_async_fn_ret_ty: generic_params={:#?}", generic_params);
1732
1733             let opaque_ty_item = hir::OpaqueTy {
1734                 generics: this.arena.alloc(hir::Generics {
1735                     params: generic_params,
1736                     predicates: &[],
1737                     has_where_clause: false,
1738                     where_clause_span: this.lower_span(span),
1739                     span: this.lower_span(span),
1740                 }),
1741                 bounds: arena_vec![this; future_bound],
1742                 origin: hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
1743             };
1744
1745             trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1746             this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1747         });
1748
1749         // As documented above, we need to create the lifetime
1750         // arguments to our opaque type. Continuing with our example,
1751         // we're creating the type arguments for the return type:
1752         //
1753         // ```
1754         // Bar<'a, 'b, '0, '1, '_>
1755         // ```
1756         //
1757         // For the "input" lifetime parameters, we wish to create
1758         // references to the parameters themselves, including the
1759         // "implicit" ones created from parameter types (`'a`, `'b`,
1760         // '`0`, `'1`).
1761         //
1762         // For the "output" lifetime parameters, we just want to
1763         // generate `'_`.
1764         let generic_args =
1765             self.arena.alloc_from_iter(captures.into_iter().map(|(_, (span, _, p_name, res))| {
1766                 let id = self.resolver.next_node_id();
1767                 let ident = Ident::new(p_name.ident().name, span);
1768                 let l = self.new_named_lifetime_with_res(id, span, ident, res);
1769                 hir::GenericArg::Lifetime(l)
1770             }));
1771
1772         // Create the `Foo<...>` reference itself. Note that the `type
1773         // Foo = impl Trait` is, internally, created as a child of the
1774         // async fn, so the *type parameters* are inherited.  It's
1775         // only the lifetime parameters that we must supply.
1776         let opaque_ty_ref =
1777             hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
1778         let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1779         hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1780     }
1781
1782     /// Transforms `-> T` into `Future<Output = T>`.
1783     fn lower_async_fn_output_type_to_future_bound(
1784         &mut self,
1785         output: &FnRetTy,
1786         fn_def_id: LocalDefId,
1787         span: Span,
1788     ) -> hir::GenericBound<'hir> {
1789         // Compute the `T` in `Future<Output = T>` from the return type.
1790         let output_ty = match output {
1791             FnRetTy::Ty(ty) => {
1792                 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1793                 // `impl Future` opaque type that `async fn` implicitly
1794                 // generates.
1795                 let context = ImplTraitContext::ReturnPositionOpaqueTy {
1796                     origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1797                 };
1798                 self.lower_ty(ty, context)
1799             }
1800             FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1801         };
1802
1803         // "<Output = T>"
1804         let future_args = self.arena.alloc(hir::GenericArgs {
1805             args: &[],
1806             bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
1807             parenthesized: false,
1808             span_ext: DUMMY_SP,
1809         });
1810
1811         hir::GenericBound::LangItemTrait(
1812             // ::std::future::Future<future_params>
1813             hir::LangItem::Future,
1814             self.lower_span(span),
1815             self.next_id(),
1816             future_args,
1817         )
1818     }
1819
1820     fn lower_param_bound(
1821         &mut self,
1822         tpb: &GenericBound,
1823         itctx: ImplTraitContext<'_, 'hir>,
1824     ) -> hir::GenericBound<'hir> {
1825         match tpb {
1826             GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
1827                 self.lower_poly_trait_ref(p, itctx),
1828                 self.lower_trait_bound_modifier(*modifier),
1829             ),
1830             GenericBound::Outlives(lifetime) => {
1831                 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
1832             }
1833         }
1834     }
1835
1836     fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1837         let span = self.lower_span(l.ident.span);
1838         let ident = self.lower_ident(l.ident);
1839         let res = self.resolver.get_lifetime_res(l.id).unwrap_or(LifetimeRes::Error);
1840         self.new_named_lifetime_with_res(l.id, span, ident, res)
1841     }
1842
1843     #[tracing::instrument(level = "debug", skip(self))]
1844     fn new_named_lifetime_with_res(
1845         &mut self,
1846         id: NodeId,
1847         span: Span,
1848         ident: Ident,
1849         res: LifetimeRes,
1850     ) -> hir::Lifetime {
1851         debug!(?self.captured_lifetimes);
1852         let name = match res {
1853             LifetimeRes::Param { param, binder } => {
1854                 debug_assert_ne!(ident.name, kw::UnderscoreLifetime);
1855                 let p_name = ParamName::Plain(ident);
1856                 if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) =
1857                     &mut self.captured_lifetimes
1858                     && !binders_to_ignore.contains(&binder)
1859                 {
1860                     match captures.entry(param) {
1861                         Entry::Occupied(_) => {}
1862                         Entry::Vacant(v) => {
1863                             let p_id = self.resolver.next_node_id();
1864                             self.resolver.create_def(
1865                                 *parent_def_id,
1866                                 p_id,
1867                                 DefPathData::LifetimeNs(p_name.ident().name),
1868                                 ExpnId::root(),
1869                                 span.with_parent(None),
1870                             );
1871
1872                             v.insert((span, p_id, p_name, res));
1873                         }
1874                     }
1875                 }
1876                 hir::LifetimeName::Param(p_name)
1877             }
1878             LifetimeRes::Fresh { mut param, binder } => {
1879                 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1880                 if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) =
1881                     &mut self.captured_lifetimes
1882                     && !binders_to_ignore.contains(&binder)
1883                 {
1884                     match captures.entry(param) {
1885                         Entry::Occupied(o) => param = self.resolver.local_def_id(o.get().1),
1886                         Entry::Vacant(v) => {
1887                             let p_id = self.resolver.next_node_id();
1888                             let p_def_id = self.resolver.create_def(
1889                                 *parent_def_id,
1890                                 p_id,
1891                                 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1892                                 ExpnId::root(),
1893                                 span.with_parent(None),
1894                             );
1895
1896                             let p_name = ParamName::Fresh(param);
1897                             v.insert((span, p_id, p_name, res));
1898                             param = p_def_id;
1899                         }
1900                     }
1901                 }
1902                 let p_name = ParamName::Fresh(param);
1903                 hir::LifetimeName::Param(p_name)
1904             }
1905             LifetimeRes::Anonymous { binder, elided } => {
1906                 let l_name = if elided {
1907                     hir::LifetimeName::Implicit
1908                 } else {
1909                     hir::LifetimeName::Underscore
1910                 };
1911                 if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) =
1912                     &mut self.captured_lifetimes
1913                     && !binders_to_ignore.contains(&binder)
1914                 {
1915                     let p_id = self.resolver.next_node_id();
1916                     let p_def_id = self.resolver.create_def(
1917                         *parent_def_id,
1918                         p_id,
1919                         DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1920                         ExpnId::root(),
1921                         span.with_parent(None),
1922                     );
1923                     let p_name = ParamName::Fresh(p_def_id);
1924                     captures.insert(p_def_id, (span, p_id, p_name, res));
1925                     hir::LifetimeName::Param(p_name)
1926                 } else {
1927                     l_name
1928                 }
1929             }
1930             LifetimeRes::Static => hir::LifetimeName::Static,
1931             LifetimeRes::Error => hir::LifetimeName::Error,
1932             res => panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span),
1933         };
1934         debug!(?self.captured_lifetimes);
1935         hir::Lifetime { hir_id: self.lower_node_id(id), span: self.lower_span(span), name }
1936     }
1937
1938     fn lower_generic_params_mut<'s>(
1939         &'s mut self,
1940         params: &'s [GenericParam],
1941     ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
1942         params.iter().map(move |param| self.lower_generic_param(param))
1943     }
1944
1945     fn lower_generic_params(&mut self, params: &[GenericParam]) -> &'hir [hir::GenericParam<'hir>] {
1946         self.arena.alloc_from_iter(self.lower_generic_params_mut(params))
1947     }
1948
1949     fn lower_generic_param(&mut self, param: &GenericParam) -> hir::GenericParam<'hir> {
1950         let (name, kind) = match param.kind {
1951             GenericParamKind::Lifetime => {
1952                 let param_name = if param.ident.name == kw::StaticLifetime
1953                     || param.ident.name == kw::UnderscoreLifetime
1954                 {
1955                     ParamName::Error
1956                 } else {
1957                     let ident = self.lower_ident(param.ident);
1958                     ParamName::Plain(ident)
1959                 };
1960                 let kind =
1961                     hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
1962
1963                 (param_name, kind)
1964             }
1965             GenericParamKind::Type { ref default, .. } => {
1966                 let kind = hir::GenericParamKind::Type {
1967                     default: default.as_ref().map(|x| {
1968                         self.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
1969                     }),
1970                     synthetic: false,
1971                 };
1972
1973                 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
1974             }
1975             GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1976                 let ty = self.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
1977                 let default = default.as_ref().map(|def| self.lower_anon_const(def));
1978                 (
1979                     hir::ParamName::Plain(self.lower_ident(param.ident)),
1980                     hir::GenericParamKind::Const { ty, default },
1981                 )
1982             }
1983         };
1984         let name = match name {
1985             hir::ParamName::Plain(ident) => hir::ParamName::Plain(self.lower_ident(ident)),
1986             name => name,
1987         };
1988
1989         let hir_id = self.lower_node_id(param.id);
1990         self.lower_attrs(hir_id, &param.attrs);
1991         hir::GenericParam {
1992             hir_id,
1993             name,
1994             span: self.lower_span(param.span()),
1995             pure_wrt_drop: self.sess.contains_name(&param.attrs, sym::may_dangle),
1996             kind,
1997             colon_span: param.colon_span.map(|s| self.lower_span(s)),
1998         }
1999     }
2000
2001     fn lower_trait_ref(
2002         &mut self,
2003         p: &TraitRef,
2004         itctx: ImplTraitContext<'_, 'hir>,
2005     ) -> hir::TraitRef<'hir> {
2006         let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2007             hir::QPath::Resolved(None, path) => path,
2008             qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2009         };
2010         hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2011     }
2012
2013     #[tracing::instrument(level = "debug", skip(self))]
2014     fn lower_poly_trait_ref(
2015         &mut self,
2016         p: &PolyTraitRef,
2017         mut itctx: ImplTraitContext<'_, 'hir>,
2018     ) -> hir::PolyTraitRef<'hir> {
2019         let bound_generic_params = self.lower_generic_params(&p.bound_generic_params);
2020
2021         let trait_ref = self.with_lifetime_binder(p.trait_ref.ref_id, |this| {
2022             this.lower_trait_ref(&p.trait_ref, itctx.reborrow())
2023         });
2024
2025         hir::PolyTraitRef { bound_generic_params, trait_ref, span: self.lower_span(p.span) }
2026     }
2027
2028     fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2029         hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2030     }
2031
2032     fn lower_param_bounds(
2033         &mut self,
2034         bounds: &[GenericBound],
2035         itctx: ImplTraitContext<'_, 'hir>,
2036     ) -> hir::GenericBounds<'hir> {
2037         self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2038     }
2039
2040     fn lower_param_bounds_mut<'s>(
2041         &'s mut self,
2042         bounds: &'s [GenericBound],
2043         mut itctx: ImplTraitContext<'s, 'hir>,
2044     ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2045         bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2046     }
2047
2048     /// Lowers a block directly to an expression, presuming that it
2049     /// has no attributes and is not targeted by a `break`.
2050     fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2051         let block = self.lower_block(b, false);
2052         self.expr_block(block, AttrVec::new())
2053     }
2054
2055     fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen {
2056         match c.value.kind {
2057             ExprKind::Underscore => {
2058                 if self.sess.features_untracked().generic_arg_infer {
2059                     hir::ArrayLen::Infer(self.lower_node_id(c.id), c.value.span)
2060                 } else {
2061                     feature_err(
2062                         &self.sess.parse_sess,
2063                         sym::generic_arg_infer,
2064                         c.value.span,
2065                         "using `_` for array lengths is unstable",
2066                     )
2067                     .emit();
2068                     hir::ArrayLen::Body(self.lower_anon_const(c))
2069                 }
2070             }
2071             _ => hir::ArrayLen::Body(self.lower_anon_const(c)),
2072         }
2073     }
2074
2075     fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2076         self.with_new_scopes(|this| hir::AnonConst {
2077             hir_id: this.lower_node_id(c.id),
2078             body: this.lower_const_body(c.value.span, Some(&c.value)),
2079         })
2080     }
2081
2082     fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2083         match u {
2084             CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2085             UserProvided => hir::UnsafeSource::UserProvided,
2086         }
2087     }
2088
2089     fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2090         match f {
2091             TraitBoundModifier::None => hir::TraitBoundModifier::None,
2092             TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2093
2094             // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2095             // placeholder for compilation to proceed.
2096             TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2097                 hir::TraitBoundModifier::Maybe
2098             }
2099         }
2100     }
2101
2102     // Helper methods for building HIR.
2103
2104     fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2105         hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2106     }
2107
2108     fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2109         self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2110     }
2111
2112     fn stmt_let_pat(
2113         &mut self,
2114         attrs: Option<&'hir [Attribute]>,
2115         span: Span,
2116         init: Option<&'hir hir::Expr<'hir>>,
2117         pat: &'hir hir::Pat<'hir>,
2118         source: hir::LocalSource,
2119     ) -> hir::Stmt<'hir> {
2120         let hir_id = self.next_id();
2121         if let Some(a) = attrs {
2122             debug_assert!(!a.is_empty());
2123             self.attrs.insert(hir_id.local_id, a);
2124         }
2125         let local = hir::Local { hir_id, init, pat, source, span: self.lower_span(span), ty: None };
2126         self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2127     }
2128
2129     fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2130         self.block_all(expr.span, &[], Some(expr))
2131     }
2132
2133     fn block_all(
2134         &mut self,
2135         span: Span,
2136         stmts: &'hir [hir::Stmt<'hir>],
2137         expr: Option<&'hir hir::Expr<'hir>>,
2138     ) -> &'hir hir::Block<'hir> {
2139         let blk = hir::Block {
2140             stmts,
2141             expr,
2142             hir_id: self.next_id(),
2143             rules: hir::BlockCheckMode::DefaultBlock,
2144             span: self.lower_span(span),
2145             targeted_by_break: false,
2146         };
2147         self.arena.alloc(blk)
2148     }
2149
2150     fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2151         let field = self.single_pat_field(span, pat);
2152         self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field, None)
2153     }
2154
2155     fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2156         let field = self.single_pat_field(span, pat);
2157         self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field, None)
2158     }
2159
2160     fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2161         let field = self.single_pat_field(span, pat);
2162         self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field, None)
2163     }
2164
2165     fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2166         self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[], None)
2167     }
2168
2169     fn single_pat_field(
2170         &mut self,
2171         span: Span,
2172         pat: &'hir hir::Pat<'hir>,
2173     ) -> &'hir [hir::PatField<'hir>] {
2174         let field = hir::PatField {
2175             hir_id: self.next_id(),
2176             ident: Ident::new(sym::integer(0), self.lower_span(span)),
2177             is_shorthand: false,
2178             pat,
2179             span: self.lower_span(span),
2180         };
2181         arena_vec![self; field]
2182     }
2183
2184     fn pat_lang_item_variant(
2185         &mut self,
2186         span: Span,
2187         lang_item: hir::LangItem,
2188         fields: &'hir [hir::PatField<'hir>],
2189         hir_id: Option<hir::HirId>,
2190     ) -> &'hir hir::Pat<'hir> {
2191         let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id);
2192         self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2193     }
2194
2195     fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2196         self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2197     }
2198
2199     fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2200         self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::Unannotated)
2201     }
2202
2203     fn pat_ident_binding_mode(
2204         &mut self,
2205         span: Span,
2206         ident: Ident,
2207         bm: hir::BindingAnnotation,
2208     ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2209         let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2210         (self.arena.alloc(pat), hir_id)
2211     }
2212
2213     fn pat_ident_binding_mode_mut(
2214         &mut self,
2215         span: Span,
2216         ident: Ident,
2217         bm: hir::BindingAnnotation,
2218     ) -> (hir::Pat<'hir>, hir::HirId) {
2219         let hir_id = self.next_id();
2220
2221         (
2222             hir::Pat {
2223                 hir_id,
2224                 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2225                 span: self.lower_span(span),
2226                 default_binding_modes: true,
2227             },
2228             hir_id,
2229         )
2230     }
2231
2232     fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2233         self.arena.alloc(hir::Pat {
2234             hir_id: self.next_id(),
2235             kind,
2236             span: self.lower_span(span),
2237             default_binding_modes: true,
2238         })
2239     }
2240
2241     fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2242         hir::Pat {
2243             hir_id: self.next_id(),
2244             kind,
2245             span: self.lower_span(span),
2246             default_binding_modes: false,
2247         }
2248     }
2249
2250     fn ty_path(
2251         &mut self,
2252         mut hir_id: hir::HirId,
2253         span: Span,
2254         qpath: hir::QPath<'hir>,
2255     ) -> hir::Ty<'hir> {
2256         let kind = match qpath {
2257             hir::QPath::Resolved(None, path) => {
2258                 // Turn trait object paths into `TyKind::TraitObject` instead.
2259                 match path.res {
2260                     Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2261                         let principal = hir::PolyTraitRef {
2262                             bound_generic_params: &[],
2263                             trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2264                             span: self.lower_span(span),
2265                         };
2266
2267                         // The original ID is taken by the `PolyTraitRef`,
2268                         // so the `Ty` itself needs a different one.
2269                         hir_id = self.next_id();
2270                         hir::TyKind::TraitObject(
2271                             arena_vec![self; principal],
2272                             self.elided_dyn_bound(span),
2273                             TraitObjectSyntax::None,
2274                         )
2275                     }
2276                     _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2277                 }
2278             }
2279             _ => hir::TyKind::Path(qpath),
2280         };
2281
2282         hir::Ty { hir_id, kind, span: self.lower_span(span) }
2283     }
2284
2285     /// Invoked to create the lifetime argument(s) for an elided trait object
2286     /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2287     /// when the bound is written, even if it is written with `'_` like in
2288     /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2289     fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2290         let r = hir::Lifetime {
2291             hir_id: self.next_id(),
2292             span: self.lower_span(span),
2293             name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2294         };
2295         debug!("elided_dyn_bound: r={:?}", r);
2296         r
2297     }
2298 }
2299
2300 /// Helper struct for delayed construction of GenericArgs.
2301 struct GenericArgsCtor<'hir> {
2302     args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2303     bindings: &'hir [hir::TypeBinding<'hir>],
2304     parenthesized: bool,
2305     span: Span,
2306 }
2307
2308 impl<'hir> GenericArgsCtor<'hir> {
2309     fn is_empty(&self) -> bool {
2310         self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2311     }
2312
2313     fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2314         let ga = hir::GenericArgs {
2315             args: this.arena.alloc_from_iter(self.args),
2316             bindings: self.bindings,
2317             parenthesized: self.parenthesized,
2318             span_ext: this.lower_span(self.span),
2319         };
2320         this.arena.alloc(ga)
2321     }
2322 }