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