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