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