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