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