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