]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/lib.rs
Rollup merge of #100293 - yanchen4791:add-inline-llvm-option, r=nnethercote
[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, in_binder))]
843     #[inline]
844     fn lower_lifetime_binder<R>(
845         &mut self,
846         binder: NodeId,
847         generic_params: &[GenericParam],
848         in_binder: impl FnOnce(&mut Self, &'hir [hir::GenericParam<'hir>]) -> R,
849     ) -> R {
850         let extra_lifetimes = self.resolver.take_extra_lifetime_params(binder);
851         debug!(?extra_lifetimes);
852         let extra_lifetimes: Vec<_> = extra_lifetimes
853             .into_iter()
854             .filter_map(|(ident, node_id, res)| {
855                 self.lifetime_res_to_generic_param(ident, node_id, res)
856             })
857             .collect();
858
859         let generic_params: Vec<_> = self
860             .lower_generic_params_mut(generic_params)
861             .chain(extra_lifetimes.into_iter())
862             .collect();
863         let generic_params = self.arena.alloc_from_iter(generic_params);
864         debug!(?generic_params);
865
866         in_binder(self, generic_params)
867     }
868
869     fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
870         let was_in_dyn_type = self.is_in_dyn_type;
871         self.is_in_dyn_type = in_scope;
872
873         let result = f(self);
874
875         self.is_in_dyn_type = was_in_dyn_type;
876
877         result
878     }
879
880     fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
881         let was_in_loop_condition = self.is_in_loop_condition;
882         self.is_in_loop_condition = false;
883
884         let catch_scope = self.catch_scope.take();
885         let loop_scope = self.loop_scope.take();
886         let ret = f(self);
887         self.catch_scope = catch_scope;
888         self.loop_scope = loop_scope;
889
890         self.is_in_loop_condition = was_in_loop_condition;
891
892         ret
893     }
894
895     fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
896         if attrs.is_empty() {
897             None
898         } else {
899             debug_assert_eq!(id.owner, self.current_hir_id_owner);
900             let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
901             debug_assert!(!ret.is_empty());
902             self.attrs.insert(id.local_id, ret);
903             Some(ret)
904         }
905     }
906
907     fn lower_attr(&self, attr: &Attribute) -> Attribute {
908         // Note that we explicitly do not walk the path. Since we don't really
909         // lower attributes (we use the AST version) there is nowhere to keep
910         // the `HirId`s. We don't actually need HIR version of attributes anyway.
911         // Tokens are also not needed after macro expansion and parsing.
912         let kind = match attr.kind {
913             AttrKind::Normal(ref normal) => AttrKind::Normal(P(NormalAttr {
914                 item: AttrItem {
915                     path: normal.item.path.clone(),
916                     args: self.lower_mac_args(&normal.item.args),
917                     tokens: None,
918                 },
919                 tokens: None,
920             })),
921             AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
922         };
923
924         Attribute { kind, id: attr.id, style: attr.style, span: self.lower_span(attr.span) }
925     }
926
927     fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
928         debug_assert_eq!(id.owner, self.current_hir_id_owner);
929         debug_assert_eq!(target_id.owner, self.current_hir_id_owner);
930         if let Some(&a) = self.attrs.get(&target_id.local_id) {
931             debug_assert!(!a.is_empty());
932             self.attrs.insert(id.local_id, a);
933         }
934     }
935
936     fn lower_mac_args(&self, args: &MacArgs) -> MacArgs {
937         match *args {
938             MacArgs::Empty => MacArgs::Empty,
939             MacArgs::Delimited(dspan, delim, ref tokens) => {
940                 // This is either a non-key-value attribute, or a `macro_rules!` body.
941                 // We either not have any nonterminals present (in the case of an attribute),
942                 // or have tokens available for all nonterminals in the case of a nested
943                 // `macro_rules`: e.g:
944                 //
945                 // ```rust
946                 // macro_rules! outer {
947                 //     ($e:expr) => {
948                 //         macro_rules! inner {
949                 //             () => { $e }
950                 //         }
951                 //     }
952                 // }
953                 // ```
954                 //
955                 // In both cases, we don't want to synthesize any tokens
956                 MacArgs::Delimited(dspan, delim, tokens.flattened())
957             }
958             // This is an inert key-value attribute - it will never be visible to macros
959             // after it gets lowered to HIR. Therefore, we can extract literals to handle
960             // nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
961             MacArgs::Eq(eq_span, MacArgsEq::Ast(ref expr)) => {
962                 // In valid code the value always ends up as a single literal. Otherwise, a dummy
963                 // literal suffices because the error is handled elsewhere.
964                 let lit = if let ExprKind::Lit(lit) = &expr.kind {
965                     lit.clone()
966                 } else {
967                     Lit {
968                         token_lit: token::Lit::new(token::LitKind::Err, kw::Empty, None),
969                         kind: LitKind::Err,
970                         span: DUMMY_SP,
971                     }
972                 };
973                 MacArgs::Eq(eq_span, MacArgsEq::Hir(lit))
974             }
975             MacArgs::Eq(_, MacArgsEq::Hir(ref lit)) => {
976                 unreachable!("in literal form when lowering mac args eq: {:?}", lit)
977             }
978         }
979     }
980
981     /// Given an associated type constraint like one of these:
982     ///
983     /// ```ignore (illustrative)
984     /// T: Iterator<Item: Debug>
985     ///             ^^^^^^^^^^^
986     /// T: Iterator<Item = Debug>
987     ///             ^^^^^^^^^^^^
988     /// ```
989     ///
990     /// returns a `hir::TypeBinding` representing `Item`.
991     #[instrument(level = "debug", skip(self))]
992     fn lower_assoc_ty_constraint(
993         &mut self,
994         constraint: &AssocConstraint,
995         itctx: &mut ImplTraitContext,
996     ) -> hir::TypeBinding<'hir> {
997         debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
998         // lower generic arguments of identifier in constraint
999         let gen_args = if let Some(ref gen_args) = constraint.gen_args {
1000             let gen_args_ctor = match gen_args {
1001                 GenericArgs::AngleBracketed(ref data) => {
1002                     self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
1003                 }
1004                 GenericArgs::Parenthesized(ref data) => {
1005                     self.emit_bad_parenthesized_trait_in_assoc_ty(data);
1006                     let aba = self.ast_arena.aba.alloc(data.as_angle_bracketed_args());
1007                     self.lower_angle_bracketed_parameter_data(aba, ParamMode::Explicit, itctx).0
1008                 }
1009             };
1010             gen_args_ctor.into_generic_args(self)
1011         } else {
1012             self.arena.alloc(hir::GenericArgs::none())
1013         };
1014         let mut itctx_tait = ImplTraitContext::TypeAliasesOpaqueTy;
1015
1016         let kind = match constraint.kind {
1017             AssocConstraintKind::Equality { ref term } => {
1018                 let term = match term {
1019                     Term::Ty(ref ty) => self.lower_ty(ty, itctx).into(),
1020                     Term::Const(ref c) => self.lower_anon_const(c).into(),
1021                 };
1022                 hir::TypeBindingKind::Equality { term }
1023             }
1024             AssocConstraintKind::Bound { ref bounds } => {
1025                 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1026                 let (desugar_to_impl_trait, itctx) = match itctx {
1027                     // We are in the return position:
1028                     //
1029                     //     fn foo() -> impl Iterator<Item: Debug>
1030                     //
1031                     // so desugar to
1032                     //
1033                     //     fn foo() -> impl Iterator<Item = impl Debug>
1034                     ImplTraitContext::ReturnPositionOpaqueTy { .. }
1035                     | ImplTraitContext::TypeAliasesOpaqueTy { .. } => (true, itctx),
1036
1037                     // We are in the argument position, but within a dyn type:
1038                     //
1039                     //     fn foo(x: dyn Iterator<Item: Debug>)
1040                     //
1041                     // so desugar to
1042                     //
1043                     //     fn foo(x: dyn Iterator<Item = impl Debug>)
1044                     ImplTraitContext::Universal if self.is_in_dyn_type => (true, itctx),
1045
1046                     // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1047                     // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1048                     // "impl trait context" to permit `impl Debug` in this position (it desugars
1049                     // then to an opaque type).
1050                     //
1051                     // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1052                     ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1053                         (true, &mut itctx_tait)
1054                     }
1055
1056                     // We are in the parameter position, but not within a dyn type:
1057                     //
1058                     //     fn foo(x: impl Iterator<Item: Debug>)
1059                     //
1060                     // so we leave it as is and this gets expanded in astconv to a bound like
1061                     // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1062                     // `impl Iterator`.
1063                     _ => (false, itctx),
1064                 };
1065
1066                 if desugar_to_impl_trait {
1067                     // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1068                     // constructing the HIR for `impl bounds...` and then lowering that.
1069
1070                     let parent_def_id = self.current_hir_id_owner;
1071                     let impl_trait_node_id = self.next_node_id();
1072                     self.create_def(parent_def_id, impl_trait_node_id, DefPathData::ImplTrait);
1073
1074                     self.with_dyn_type_scope(false, |this| {
1075                         let node_id = this.next_node_id();
1076                         let ty = this.ast_arena.tys.alloc(Ty {
1077                             id: node_id,
1078                             kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1079                             span: this.lower_span(constraint.span),
1080                             tokens: None,
1081                         });
1082                         let ty = this.lower_ty(ty, itctx);
1083
1084                         hir::TypeBindingKind::Equality { term: ty.into() }
1085                     })
1086                 } else {
1087                     // Desugar `AssocTy: Bounds` into a type binding where the
1088                     // later desugars into a trait predicate.
1089                     let bounds = self.lower_param_bounds(bounds, itctx);
1090
1091                     hir::TypeBindingKind::Constraint { bounds }
1092                 }
1093             }
1094         };
1095
1096         hir::TypeBinding {
1097             hir_id: self.lower_node_id(constraint.id),
1098             ident: self.lower_ident(constraint.ident),
1099             gen_args,
1100             kind,
1101             span: self.lower_span(constraint.span),
1102         }
1103     }
1104
1105     fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1106         // Suggest removing empty parentheses: "Trait()" -> "Trait"
1107         let sub = if data.inputs.is_empty() {
1108             let parentheses_span =
1109                 data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1110             AssocTyParenthesesSub::Empty { parentheses_span }
1111         }
1112         // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1113         else {
1114             // Start of parameters to the 1st argument
1115             let open_param = data.inputs_span.shrink_to_lo().to(data
1116                 .inputs
1117                 .first()
1118                 .unwrap()
1119                 .span
1120                 .shrink_to_lo());
1121             // End of last argument to end of parameters
1122             let close_param =
1123                 data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1124             AssocTyParenthesesSub::NotEmpty { open_param, close_param }
1125         };
1126         self.tcx.sess.emit_err(AssocTyParentheses { span: data.span, sub });
1127     }
1128
1129     #[instrument(level = "debug", skip(self))]
1130     fn lower_generic_arg(
1131         &mut self,
1132         arg: &ast::GenericArg,
1133         itctx: &mut ImplTraitContext,
1134     ) -> hir::GenericArg<'hir> {
1135         match arg {
1136             ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(&lt)),
1137             ast::GenericArg::Type(ty) => {
1138                 match ty.kind {
1139                     TyKind::Infer if self.tcx.features().generic_arg_infer => {
1140                         return GenericArg::Infer(hir::InferArg {
1141                             hir_id: self.lower_node_id(ty.id),
1142                             span: self.lower_span(ty.span),
1143                         });
1144                     }
1145                     // We parse const arguments as path types as we cannot distinguish them during
1146                     // parsing. We try to resolve that ambiguity by attempting resolution in both the
1147                     // type and value namespaces. If we resolved the path in the value namespace, we
1148                     // transform it into a generic const argument.
1149                     TyKind::Path(ref qself, ref path) => {
1150                         if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1151                             let res = partial_res.base_res();
1152                             if !res.matches_ns(Namespace::TypeNS) {
1153                                 debug!(
1154                                     "lower_generic_arg: Lowering type argument as const argument: {:?}",
1155                                     ty,
1156                                 );
1157
1158                                 // Construct an AnonConst where the expr is the "ty"'s path.
1159
1160                                 let parent_def_id = self.current_hir_id_owner;
1161                                 let node_id = self.next_node_id();
1162
1163                                 // Add a definition for the in-band const def.
1164                                 self.create_def(parent_def_id, node_id, DefPathData::AnonConst);
1165
1166                                 let span = self.lower_span(ty.span);
1167                                 let path_expr = Expr {
1168                                     id: ty.id,
1169                                     kind: ExprKind::Path(qself.clone(), path.clone()),
1170                                     span,
1171                                     attrs: AttrVec::new(),
1172                                     tokens: None,
1173                                 };
1174
1175                                 let ct = self.with_new_scopes(|this| hir::AnonConst {
1176                                     hir_id: this.lower_node_id(node_id),
1177                                     body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1178                                 });
1179                                 return GenericArg::Const(ConstArg { value: ct, span });
1180                             }
1181                         }
1182                     }
1183                     _ => {}
1184                 }
1185                 GenericArg::Type(self.lower_ty(&ty, itctx))
1186             }
1187             ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1188                 value: self.lower_anon_const(&ct),
1189                 span: self.lower_span(ct.value.span),
1190             }),
1191         }
1192     }
1193
1194     #[instrument(level = "debug", skip(self))]
1195     fn lower_ty(&mut self, t: &Ty, itctx: &mut ImplTraitContext) -> &'hir hir::Ty<'hir> {
1196         self.arena.alloc(self.lower_ty_direct(t, itctx))
1197     }
1198
1199     fn lower_path_ty(
1200         &mut self,
1201         t: &Ty,
1202         qself: &Option<QSelf>,
1203         path: &Path,
1204         param_mode: ParamMode,
1205         itctx: &mut ImplTraitContext,
1206     ) -> hir::Ty<'hir> {
1207         // Check whether we should interpret this as a bare trait object.
1208         // This check mirrors the one in late resolution.  We only introduce this special case in
1209         // the rare occurrence we need to lower `Fresh` anonymous lifetimes.
1210         // The other cases when a qpath should be opportunistically made a trait object are handled
1211         // by `ty_path`.
1212         if qself.is_none()
1213             && let Some(partial_res) = self.resolver.get_partial_res(t.id)
1214             && partial_res.unresolved_segments() == 0
1215             && let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = partial_res.base_res()
1216         {
1217             let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1218                 let poly_trait_ref = this.ast_arena.ptr.alloc(PolyTraitRef {
1219                     bound_generic_params: vec![],
1220                     trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
1221                     span: t.span
1222                 });
1223                 let bound = this.lower_poly_trait_ref(
1224                     poly_trait_ref,
1225                     itctx,
1226                 );
1227                 let bounds = this.arena.alloc_from_iter([bound]);
1228                 let lifetime_bound = this.elided_dyn_bound(t.span);
1229                 (bounds, lifetime_bound)
1230             });
1231             let kind = hir::TyKind::TraitObject(bounds, &lifetime_bound, TraitObjectSyntax::None);
1232             return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() };
1233         }
1234
1235         let id = self.lower_node_id(t.id);
1236         let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1237         self.ty_path(id, t.span, qpath)
1238     }
1239
1240     fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1241         hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1242     }
1243
1244     fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1245         self.ty(span, hir::TyKind::Tup(tys))
1246     }
1247
1248     fn lower_ty_direct(&mut self, t: &Ty, itctx: &mut ImplTraitContext) -> hir::Ty<'hir> {
1249         let kind = match t.kind {
1250             TyKind::Infer => hir::TyKind::Infer,
1251             TyKind::Err => hir::TyKind::Err,
1252             TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1253             TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1254             TyKind::Rptr(ref region, ref mt) => {
1255                 let region = region.unwrap_or_else(|| {
1256                     let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1257                         self.resolver.get_lifetime_res(t.id)
1258                     {
1259                         debug_assert_eq!(start.plus(1), end);
1260                         start
1261                     } else {
1262                         self.next_node_id()
1263                     };
1264                     let span = self.tcx.sess.source_map().start_point(t.span);
1265                     Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id }
1266                 });
1267                 let lifetime = self.lower_lifetime(&region);
1268                 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1269             }
1270             TyKind::BareFn(ref f) => {
1271                 self.lower_lifetime_binder(t.id, &f.generic_params, |lctx, generic_params| {
1272                     hir::TyKind::BareFn(lctx.arena.alloc(hir::BareFnTy {
1273                         generic_params,
1274                         unsafety: lctx.lower_unsafety(f.unsafety),
1275                         abi: lctx.lower_extern(f.ext),
1276                         decl: lctx.lower_fn_decl(&f.decl, None, t.span, FnDeclKind::Pointer, None),
1277                         param_names: lctx.lower_fn_params_to_names(&f.decl),
1278                     }))
1279                 })
1280             }
1281             TyKind::Never => hir::TyKind::Never,
1282             TyKind::Tup(ref tys) => hir::TyKind::Tup(
1283                 self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty_direct(ty, itctx))),
1284             ),
1285             TyKind::Paren(ref ty) => {
1286                 return self.lower_ty_direct(ty, itctx);
1287             }
1288             TyKind::Path(ref qself, ref path) => {
1289                 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1290             }
1291             TyKind::ImplicitSelf => {
1292                 let hir_id = self.next_id();
1293                 let res = self.expect_full_res(t.id);
1294                 let res = self.lower_res(res);
1295                 hir::TyKind::Path(hir::QPath::Resolved(
1296                     None,
1297                     self.arena.alloc(hir::Path {
1298                         res,
1299                         segments: arena_vec![self; hir::PathSegment::new(
1300                             Ident::with_dummy_span(kw::SelfUpper),
1301                             hir_id,
1302                             res
1303                         )],
1304                         span: self.lower_span(t.span),
1305                     }),
1306                 ))
1307             }
1308             TyKind::Array(ref ty, ref length) => {
1309                 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_array_length(length))
1310             }
1311             TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1312             TyKind::TraitObject(ref bounds, kind) => {
1313                 let mut lifetime_bound = None;
1314                 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1315                     let bounds =
1316                         this.arena.alloc_from_iter(bounds.iter().filter_map(
1317                             |bound| match *bound {
1318                                 GenericBound::Trait(
1319                                     ref ty,
1320                                     TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1321                                 ) => Some(this.lower_poly_trait_ref(ty, itctx)),
1322                                 // `~const ?Bound` will cause an error during AST validation
1323                                 // anyways, so treat it like `?Bound` as compilation proceeds.
1324                                 GenericBound::Trait(
1325                                     _,
1326                                     TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1327                                 ) => None,
1328                                 GenericBound::Outlives(ref lifetime) => {
1329                                     if lifetime_bound.is_none() {
1330                                         lifetime_bound = Some(this.lower_lifetime(lifetime));
1331                                     }
1332                                     None
1333                                 }
1334                             },
1335                         ));
1336                     let lifetime_bound =
1337                         lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1338                     (bounds, lifetime_bound)
1339                 });
1340                 hir::TyKind::TraitObject(bounds, lifetime_bound, kind)
1341             }
1342             TyKind::ImplTrait(def_node_id, ref bounds) => {
1343                 let span = t.span;
1344                 match itctx {
1345                     ImplTraitContext::ReturnPositionOpaqueTy { origin, in_trait } => self
1346                         .lower_opaque_impl_trait(
1347                             span,
1348                             *origin,
1349                             def_node_id,
1350                             bounds,
1351                             *in_trait,
1352                             itctx,
1353                         ),
1354                     ImplTraitContext::TypeAliasesOpaqueTy => self.lower_opaque_impl_trait(
1355                         span,
1356                         hir::OpaqueTyOrigin::TyAlias,
1357                         def_node_id,
1358                         bounds,
1359                         false,
1360                         &mut ImplTraitContext::TypeAliasesOpaqueTy,
1361                     ),
1362                     ImplTraitContext::Universal => {
1363                         let span = t.span;
1364                         let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1365                         let (param, bounds, path) =
1366                             self.lower_generic_and_bounds(def_node_id, span, ident, bounds);
1367                         self.impl_trait_defs.push(param);
1368                         if let Some(bounds) = bounds {
1369                             self.impl_trait_bounds.push(bounds);
1370                         }
1371                         path
1372                     }
1373                     ImplTraitContext::Disallowed(
1374                         position @ (ImplTraitPosition::TraitReturn | ImplTraitPosition::ImplReturn),
1375                     ) => {
1376                         self.tcx
1377                             .sess
1378                             .create_feature_err(
1379                                 MisplacedImplTrait {
1380                                     span: t.span,
1381                                     position: DiagnosticArgFromDisplay(&position),
1382                                 },
1383                                 sym::return_position_impl_trait_in_trait,
1384                             )
1385                             .emit();
1386                         hir::TyKind::Err
1387                     }
1388                     ImplTraitContext::Disallowed(position) => {
1389                         self.tcx.sess.emit_err(MisplacedImplTrait {
1390                             span: t.span,
1391                             position: DiagnosticArgFromDisplay(&position),
1392                         });
1393                         hir::TyKind::Err
1394                     }
1395                 }
1396             }
1397             TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1398             TyKind::CVarArgs => {
1399                 self.tcx.sess.delay_span_bug(
1400                     t.span,
1401                     "`TyKind::CVarArgs` should have been handled elsewhere",
1402                 );
1403                 hir::TyKind::Err
1404             }
1405         };
1406
1407         hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1408     }
1409
1410     /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1411     /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1412     /// HIR type that references the TAIT.
1413     ///
1414     /// Given a function definition like:
1415     ///
1416     /// ```rust
1417     /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1418     ///     x
1419     /// }
1420     /// ```
1421     ///
1422     /// we will create a TAIT definition in the HIR like
1423     ///
1424     /// ```
1425     /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1426     /// ```
1427     ///
1428     /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1429     ///
1430     /// ```rust
1431     /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1432     /// ```
1433     ///
1434     /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1435     /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1436     /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1437     /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1438     /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1439     #[instrument(level = "debug", skip(self), ret)]
1440     fn lower_opaque_impl_trait(
1441         &mut self,
1442         span: Span,
1443         origin: hir::OpaqueTyOrigin,
1444         opaque_ty_node_id: NodeId,
1445         bounds: &GenericBounds,
1446         in_trait: bool,
1447         itctx: &mut ImplTraitContext,
1448     ) -> hir::TyKind<'hir> {
1449         // Make sure we know that some funky desugaring has been going on here.
1450         // This is a first: there is code in other places like for loop
1451         // desugaring that explicitly states that we don't want to track that.
1452         // Not tracking it makes lints in rustc and clippy very fragile, as
1453         // frequently opened issues show.
1454         let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1455
1456         let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1457         debug!(?opaque_ty_def_id);
1458
1459         // Contains the new lifetime definitions created for the TAIT (if any).
1460         let mut collected_lifetimes = Vec::new();
1461
1462         // If this came from a TAIT (as opposed to a function that returns an RPIT), we only want
1463         // to capture the lifetimes that appear in the bounds. So visit the bounds to find out
1464         // exactly which ones those are.
1465         let lifetimes_to_remap = if origin == hir::OpaqueTyOrigin::TyAlias {
1466             // in a TAIT like `type Foo<'a> = impl Foo<'a>`, we don't keep all the lifetime parameters
1467             Vec::new()
1468         } else {
1469             // in fn return position, like the `fn test<'a>() -> impl Debug + 'a` example,
1470             // we only keep the lifetimes that appear in the `impl Debug` itself:
1471             lifetime_collector::lifetimes_in_bounds(&self.resolver, bounds)
1472         };
1473         debug!(?lifetimes_to_remap);
1474
1475         self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1476             let mut new_remapping = FxHashMap::default();
1477
1478             // If this opaque type is only capturing a subset of the lifetimes (those that appear
1479             // in bounds), then create the new lifetime parameters required and create a mapping
1480             // from the old `'a` (on the function) to the new `'a` (on the opaque type).
1481             collected_lifetimes = lctx.create_lifetime_defs(
1482                 opaque_ty_def_id,
1483                 &lifetimes_to_remap,
1484                 &mut new_remapping,
1485             );
1486             debug!(?collected_lifetimes);
1487             debug!(?new_remapping);
1488
1489             // Install the remapping from old to new (if any):
1490             lctx.with_remapping(new_remapping, |lctx| {
1491                 // This creates HIR lifetime definitions as `hir::GenericParam`, in the given
1492                 // example `type TestReturn<'a, T, 'x> = impl Debug + 'x`, it creates a collection
1493                 // containing `&['x]`.
1494                 let lifetime_defs = lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(
1495                     |&(new_node_id, lifetime)| {
1496                         let hir_id = lctx.lower_node_id(new_node_id);
1497                         debug_assert_ne!(lctx.opt_local_def_id(new_node_id), None);
1498
1499                         let (name, kind) = if lifetime.ident.name == kw::UnderscoreLifetime {
1500                             (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
1501                         } else {
1502                             (
1503                                 hir::ParamName::Plain(lifetime.ident),
1504                                 hir::LifetimeParamKind::Explicit,
1505                             )
1506                         };
1507
1508                         hir::GenericParam {
1509                             hir_id,
1510                             name,
1511                             span: lifetime.ident.span,
1512                             pure_wrt_drop: false,
1513                             kind: hir::GenericParamKind::Lifetime { kind },
1514                             colon_span: None,
1515                         }
1516                     },
1517                 ));
1518                 debug!(?lifetime_defs);
1519
1520                 // Then when we lower the param bounds, references to 'a are remapped to 'a1, so we
1521                 // get back Debug + 'a1, which is suitable for use on the TAIT.
1522                 let hir_bounds = lctx.lower_param_bounds(bounds, itctx);
1523                 debug!(?hir_bounds);
1524
1525                 let opaque_ty_item = hir::OpaqueTy {
1526                     generics: self.arena.alloc(hir::Generics {
1527                         params: lifetime_defs,
1528                         predicates: &[],
1529                         has_where_clause_predicates: false,
1530                         where_clause_span: lctx.lower_span(span),
1531                         span: lctx.lower_span(span),
1532                     }),
1533                     bounds: hir_bounds,
1534                     origin,
1535                     in_trait,
1536                 };
1537                 debug!(?opaque_ty_item);
1538
1539                 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1540             })
1541         });
1542
1543         // This creates HIR lifetime arguments as `hir::GenericArg`, in the given example `type
1544         // TestReturn<'a, T, 'x> = impl Debug + 'x`, it creates a collection containing `&['x]`.
1545         let lifetimes =
1546             self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(|(_, lifetime)| {
1547                 let id = self.next_node_id();
1548                 let span = lifetime.ident.span;
1549
1550                 let ident = if lifetime.ident.name == kw::UnderscoreLifetime {
1551                     Ident::with_dummy_span(kw::UnderscoreLifetime)
1552                 } else {
1553                     lifetime.ident
1554                 };
1555
1556                 let l = self.new_named_lifetime(lifetime.id, id, span, ident);
1557                 hir::GenericArg::Lifetime(l)
1558             }));
1559         debug!(?lifetimes);
1560
1561         // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1562         hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes, in_trait)
1563     }
1564
1565     /// Registers a new opaque type with the proper `NodeId`s and
1566     /// returns the lowered node-ID for the opaque type.
1567     fn generate_opaque_type(
1568         &mut self,
1569         opaque_ty_id: LocalDefId,
1570         opaque_ty_item: hir::OpaqueTy<'hir>,
1571         span: Span,
1572         opaque_ty_span: Span,
1573     ) -> hir::OwnerNode<'hir> {
1574         let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1575         // Generate an `type Foo = impl Trait;` declaration.
1576         trace!("registering opaque type with id {:#?}", opaque_ty_id);
1577         let opaque_ty_item = hir::Item {
1578             def_id: opaque_ty_id,
1579             ident: Ident::empty(),
1580             kind: opaque_ty_item_kind,
1581             vis_span: self.lower_span(span.shrink_to_lo()),
1582             span: self.lower_span(opaque_ty_span),
1583         };
1584         hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1585     }
1586
1587     /// Given a `parent_def_id`, a list of `lifetimes_in_bounds and a `remapping` hash to be
1588     /// filled, this function creates new definitions for `Param` and `Fresh` lifetimes, inserts the
1589     /// new definition, adds it to the remapping with the definition of the given lifetime and
1590     /// returns a list of lifetimes to be lowered afterwards.
1591     fn create_lifetime_defs(
1592         &mut self,
1593         parent_def_id: LocalDefId,
1594         lifetimes_in_bounds: &[Lifetime],
1595         remapping: &mut FxHashMap<LocalDefId, LocalDefId>,
1596     ) -> Vec<(NodeId, Lifetime)> {
1597         let mut result = Vec::new();
1598
1599         for lifetime in lifetimes_in_bounds {
1600             let res = self.resolver.get_lifetime_res(lifetime.id).unwrap_or(LifetimeRes::Error);
1601             debug!(?res);
1602
1603             match res {
1604                 LifetimeRes::Param { param: old_def_id, binder: _ } => {
1605                     if remapping.get(&old_def_id).is_none() {
1606                         let node_id = self.next_node_id();
1607
1608                         let new_def_id = self.create_def(
1609                             parent_def_id,
1610                             node_id,
1611                             DefPathData::LifetimeNs(lifetime.ident.name),
1612                         );
1613                         remapping.insert(old_def_id, new_def_id);
1614
1615                         result.push((node_id, *lifetime));
1616                     }
1617                 }
1618
1619                 LifetimeRes::Fresh { param, binder: _ } => {
1620                     debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1621                     if let Some(old_def_id) = self.opt_local_def_id(param) && remapping.get(&old_def_id).is_none() {
1622                         let node_id = self.next_node_id();
1623
1624                         let new_def_id = self.create_def(
1625                             parent_def_id,
1626                             node_id,
1627                             DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1628                         );
1629                         remapping.insert(old_def_id, new_def_id);
1630
1631                         result.push((node_id, *lifetime));
1632                     }
1633                 }
1634
1635                 LifetimeRes::Static | LifetimeRes::Error => {}
1636
1637                 res => {
1638                     let bug_msg = format!(
1639                         "Unexpected lifetime resolution {:?} for {:?} at {:?}",
1640                         res, lifetime.ident, lifetime.ident.span
1641                     );
1642                     span_bug!(lifetime.ident.span, "{}", bug_msg);
1643                 }
1644             }
1645         }
1646
1647         result
1648     }
1649
1650     fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1651         // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1652         // as they are not explicit in HIR/Ty function signatures.
1653         // (instead, the `c_variadic` flag is set to `true`)
1654         let mut inputs = &decl.inputs[..];
1655         if decl.c_variadic() {
1656             inputs = &inputs[..inputs.len() - 1];
1657         }
1658         self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1659             PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1660             _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1661         }))
1662     }
1663
1664     // Lowers a function declaration.
1665     //
1666     // `decl`: the unlowered (AST) function declaration.
1667     // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1668     //      given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1669     //      `make_ret_async` is also `Some`.
1670     // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1671     //      return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1672     //      return type `impl Trait` item, and the `Span` points to the `async` keyword.
1673     #[instrument(level = "debug", skip(self))]
1674     fn lower_fn_decl(
1675         &mut self,
1676         decl: &FnDecl,
1677         fn_node_id: Option<NodeId>,
1678         fn_span: Span,
1679         kind: FnDeclKind,
1680         make_ret_async: Option<(NodeId, Span)>,
1681     ) -> &'hir hir::FnDecl<'hir> {
1682         let c_variadic = decl.c_variadic();
1683
1684         // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1685         // as they are not explicit in HIR/Ty function signatures.
1686         // (instead, the `c_variadic` flag is set to `true`)
1687         let mut inputs = &decl.inputs[..];
1688         if c_variadic {
1689             inputs = &inputs[..inputs.len() - 1];
1690         }
1691         let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1692             if fn_node_id.is_some() {
1693                 self.lower_ty_direct(&param.ty, &mut ImplTraitContext::Universal)
1694             } else {
1695                 self.lower_ty_direct(
1696                     &param.ty,
1697                     &mut ImplTraitContext::Disallowed(match kind {
1698                         FnDeclKind::Fn | FnDeclKind::Inherent => {
1699                             unreachable!("fn should allow in-band lifetimes")
1700                         }
1701                         FnDeclKind::ExternFn => ImplTraitPosition::ExternFnParam,
1702                         FnDeclKind::Closure => ImplTraitPosition::ClosureParam,
1703                         FnDeclKind::Pointer => ImplTraitPosition::PointerParam,
1704                         FnDeclKind::Trait => ImplTraitPosition::TraitParam,
1705                         FnDeclKind::Impl => ImplTraitPosition::ImplParam,
1706                     }),
1707                 )
1708             }
1709         }));
1710
1711         let output = if let Some((ret_id, span)) = make_ret_async {
1712             match kind {
1713                 FnDeclKind::Trait => {
1714                     if !kind.impl_trait_in_trait_allowed(self.tcx) {
1715                         self.tcx
1716                             .sess
1717                             .create_feature_err(
1718                                 TraitFnAsync { fn_span, span },
1719                                 sym::return_position_impl_trait_in_trait,
1720                             )
1721                             .emit();
1722                     }
1723                     self.lower_async_fn_ret_ty(
1724                         &decl.output,
1725                         fn_node_id.expect("`make_ret_async` but no `fn_def_id`"),
1726                         ret_id,
1727                         true,
1728                     )
1729                 }
1730                 _ => {
1731                     if !kind.impl_trait_return_allowed(self.tcx) {
1732                         if kind == FnDeclKind::Impl {
1733                             self.tcx
1734                                 .sess
1735                                 .create_feature_err(
1736                                     TraitFnAsync { fn_span, span },
1737                                     sym::return_position_impl_trait_in_trait,
1738                                 )
1739                                 .emit();
1740                         } else {
1741                             self.tcx.sess.emit_err(TraitFnAsync { fn_span, span });
1742                         }
1743                     }
1744                     self.lower_async_fn_ret_ty(
1745                         &decl.output,
1746                         fn_node_id.expect("`make_ret_async` but no `fn_def_id`"),
1747                         ret_id,
1748                         false,
1749                     )
1750                 }
1751             }
1752         } else {
1753             match decl.output {
1754                 FnRetTy::Ty(ref ty) => {
1755                     let mut context = match fn_node_id {
1756                         Some(fn_node_id) if kind.impl_trait_return_allowed(self.tcx) => {
1757                             let fn_def_id = self.local_def_id(fn_node_id);
1758                             ImplTraitContext::ReturnPositionOpaqueTy {
1759                                 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1760                                 in_trait: false,
1761                             }
1762                         }
1763                         Some(fn_node_id) if kind.impl_trait_in_trait_allowed(self.tcx) => {
1764                             let fn_def_id = self.local_def_id(fn_node_id);
1765                             ImplTraitContext::ReturnPositionOpaqueTy {
1766                                 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1767                                 in_trait: true,
1768                             }
1769                         }
1770                         _ => ImplTraitContext::Disallowed(match kind {
1771                             FnDeclKind::Fn | FnDeclKind::Inherent => {
1772                                 unreachable!("fn should allow in-band lifetimes")
1773                             }
1774                             FnDeclKind::ExternFn => ImplTraitPosition::ExternFnReturn,
1775                             FnDeclKind::Closure => ImplTraitPosition::ClosureReturn,
1776                             FnDeclKind::Pointer => ImplTraitPosition::PointerReturn,
1777                             FnDeclKind::Trait => ImplTraitPosition::TraitReturn,
1778                             FnDeclKind::Impl => ImplTraitPosition::ImplReturn,
1779                         }),
1780                     };
1781                     hir::FnRetTy::Return(self.lower_ty(ty, &mut context))
1782                 }
1783                 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
1784             }
1785         };
1786
1787         self.arena.alloc(hir::FnDecl {
1788             inputs,
1789             output,
1790             c_variadic,
1791             implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1792                 let is_mutable_pat = matches!(
1793                     arg.pat.kind,
1794                     PatKind::Ident(hir::BindingAnnotation(_, Mutability::Mut), ..)
1795                 );
1796
1797                 match arg.ty.kind {
1798                     TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1799                     TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1800                     // Given we are only considering `ImplicitSelf` types, we needn't consider
1801                     // the case where we have a mutable pattern to a reference as that would
1802                     // no longer be an `ImplicitSelf`.
1803                     TyKind::Rptr(_, ref mt)
1804                         if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1805                     {
1806                         hir::ImplicitSelfKind::MutRef
1807                     }
1808                     TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1809                         hir::ImplicitSelfKind::ImmRef
1810                     }
1811                     _ => hir::ImplicitSelfKind::None,
1812                 }
1813             }),
1814         })
1815     }
1816
1817     // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1818     // combined with the following definition of `OpaqueTy`:
1819     //
1820     //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1821     //
1822     // `output`: unlowered output type (`T` in `-> T`)
1823     // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1824     // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1825     #[instrument(level = "debug", skip(self))]
1826     fn lower_async_fn_ret_ty(
1827         &mut self,
1828         output: &FnRetTy,
1829         fn_node_id: NodeId,
1830         opaque_ty_node_id: NodeId,
1831         in_trait: bool,
1832     ) -> hir::FnRetTy<'hir> {
1833         let span = output.span();
1834
1835         let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1836
1837         let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1838         let fn_def_id = self.local_def_id(fn_node_id);
1839
1840         // When we create the opaque type for this async fn, it is going to have
1841         // to capture all the lifetimes involved in the signature (including in the
1842         // return type). This is done by introducing lifetime parameters for:
1843         //
1844         // - all the explicitly declared lifetimes from the impl and function itself;
1845         // - all the elided lifetimes in the fn arguments;
1846         // - all the elided lifetimes in the return type.
1847         //
1848         // So for example in this snippet:
1849         //
1850         // ```rust
1851         // impl<'a> Foo<'a> {
1852         //   async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1853         //   //               ^ '0                       ^ '1     ^ '2
1854         //   // elided lifetimes used below
1855         //   }
1856         // }
1857         // ```
1858         //
1859         // we would create an opaque type like:
1860         //
1861         // ```
1862         // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1863         // ```
1864         //
1865         // and we would then desugar `bar` to the equivalent of:
1866         //
1867         // ```rust
1868         // impl<'a> Foo<'a> {
1869         //   fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1870         // }
1871         // ```
1872         //
1873         // Note that the final parameter to `Bar` is `'_`, not `'2` --
1874         // this is because the elided lifetimes from the return type
1875         // should be figured out using the ordinary elision rules, and
1876         // this desugaring achieves that.
1877
1878         // Calculate all the lifetimes that should be captured
1879         // by the opaque type. This should include all in-scope
1880         // lifetime parameters, including those defined in-band.
1881
1882         // Contains the new lifetime definitions created for the TAIT (if any) generated for the
1883         // return type.
1884         let mut collected_lifetimes = Vec::new();
1885         let mut new_remapping = FxHashMap::default();
1886
1887         let extra_lifetime_params = self.resolver.take_extra_lifetime_params(opaque_ty_node_id);
1888         debug!(?extra_lifetime_params);
1889         for (ident, outer_node_id, outer_res) in extra_lifetime_params {
1890             let outer_def_id = self.local_def_id(outer_node_id);
1891             let inner_node_id = self.next_node_id();
1892
1893             // Add a definition for the in scope lifetime def.
1894             let inner_def_id = self.create_def(
1895                 opaque_ty_def_id,
1896                 inner_node_id,
1897                 DefPathData::LifetimeNs(ident.name),
1898             );
1899             new_remapping.insert(outer_def_id, inner_def_id);
1900
1901             let inner_res = match outer_res {
1902                 // Input lifetime like `'a`:
1903                 LifetimeRes::Param { param, .. } => {
1904                     LifetimeRes::Param { param, binder: fn_node_id }
1905                 }
1906                 // Input lifetime like `'1`:
1907                 LifetimeRes::Fresh { param, .. } => {
1908                     LifetimeRes::Fresh { param, binder: fn_node_id }
1909                 }
1910                 LifetimeRes::Static | LifetimeRes::Error => continue,
1911                 res => {
1912                     panic!(
1913                         "Unexpected lifetime resolution {:?} for {:?} at {:?}",
1914                         res, ident, ident.span
1915                     )
1916                 }
1917             };
1918
1919             let lifetime = Lifetime { id: outer_node_id, ident };
1920             collected_lifetimes.push((inner_node_id, lifetime, Some(inner_res)));
1921         }
1922
1923         debug!(?collected_lifetimes);
1924
1925         // We only want to capture the lifetimes that appear in the bounds. So visit the bounds to
1926         // find out exactly which ones those are.
1927         // in fn return position, like the `fn test<'a>() -> impl Debug + 'a` example,
1928         // we only keep the lifetimes that appear in the `impl Debug` itself:
1929         let lifetimes_to_remap = lifetime_collector::lifetimes_in_ret_ty(&self.resolver, output);
1930         debug!(?lifetimes_to_remap);
1931
1932         self.with_hir_id_owner(opaque_ty_node_id, |this| {
1933             // If this opaque type is only capturing a subset of the lifetimes (those that appear
1934             // in bounds), then create the new lifetime parameters required and create a mapping
1935             // from the old `'a` (on the function) to the new `'a` (on the opaque type).
1936             collected_lifetimes.extend(
1937                 this.create_lifetime_defs(
1938                     opaque_ty_def_id,
1939                     &lifetimes_to_remap,
1940                     &mut new_remapping,
1941                 )
1942                 .into_iter()
1943                 .map(|(new_node_id, lifetime)| (new_node_id, lifetime, None)),
1944             );
1945             debug!(?collected_lifetimes);
1946             debug!(?new_remapping);
1947
1948             // Install the remapping from old to new (if any):
1949             this.with_remapping(new_remapping, |this| {
1950                 // We have to be careful to get elision right here. The
1951                 // idea is that we create a lifetime parameter for each
1952                 // lifetime in the return type.  So, given a return type
1953                 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1954                 // Future<Output = &'1 [ &'2 u32 ]>`.
1955                 //
1956                 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1957                 // hence the elision takes place at the fn site.
1958                 let future_bound = this.lower_async_fn_output_type_to_future_bound(
1959                     output,
1960                     span,
1961                     ImplTraitContext::ReturnPositionOpaqueTy {
1962                         origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1963                         in_trait,
1964                     },
1965                 );
1966
1967                 let generic_params = this.arena.alloc_from_iter(collected_lifetimes.iter().map(
1968                     |&(new_node_id, lifetime, _)| {
1969                         let hir_id = this.lower_node_id(new_node_id);
1970                         debug_assert_ne!(this.opt_local_def_id(new_node_id), None);
1971
1972                         let (name, kind) = if lifetime.ident.name == kw::UnderscoreLifetime {
1973                             (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
1974                         } else {
1975                             (
1976                                 hir::ParamName::Plain(lifetime.ident),
1977                                 hir::LifetimeParamKind::Explicit,
1978                             )
1979                         };
1980
1981                         hir::GenericParam {
1982                             hir_id,
1983                             name,
1984                             span: lifetime.ident.span,
1985                             pure_wrt_drop: false,
1986                             kind: hir::GenericParamKind::Lifetime { kind },
1987                             colon_span: None,
1988                         }
1989                     },
1990                 ));
1991                 debug!("lower_async_fn_ret_ty: generic_params={:#?}", generic_params);
1992
1993                 let opaque_ty_item = hir::OpaqueTy {
1994                     generics: this.arena.alloc(hir::Generics {
1995                         params: generic_params,
1996                         predicates: &[],
1997                         has_where_clause_predicates: false,
1998                         where_clause_span: this.lower_span(span),
1999                         span: this.lower_span(span),
2000                     }),
2001                     bounds: arena_vec![this; future_bound],
2002                     origin: hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
2003                     in_trait,
2004                 };
2005
2006                 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
2007                 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
2008             })
2009         });
2010
2011         // As documented above, we need to create the lifetime
2012         // arguments to our opaque type. Continuing with our example,
2013         // we're creating the type arguments for the return type:
2014         //
2015         // ```
2016         // Bar<'a, 'b, '0, '1, '_>
2017         // ```
2018         //
2019         // For the "input" lifetime parameters, we wish to create
2020         // references to the parameters themselves, including the
2021         // "implicit" ones created from parameter types (`'a`, `'b`,
2022         // '`0`, `'1`).
2023         //
2024         // For the "output" lifetime parameters, we just want to
2025         // generate `'_`.
2026         let generic_args = self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(
2027             |(_, lifetime, res)| {
2028                 let id = self.next_node_id();
2029                 let span = lifetime.ident.span;
2030
2031                 let ident = if lifetime.ident.name == kw::UnderscoreLifetime {
2032                     Ident::with_dummy_span(kw::UnderscoreLifetime)
2033                 } else {
2034                     lifetime.ident
2035                 };
2036
2037                 let res = res.unwrap_or(
2038                     self.resolver.get_lifetime_res(lifetime.id).unwrap_or(LifetimeRes::Error),
2039                 );
2040                 hir::GenericArg::Lifetime(self.new_named_lifetime_with_res(id, span, ident, res))
2041             },
2042         ));
2043
2044         // Create the `Foo<...>` reference itself. Note that the `type
2045         // Foo = impl Trait` is, internally, created as a child of the
2046         // async fn, so the *type parameters* are inherited.  It's
2047         // only the lifetime parameters that we must supply.
2048         let opaque_ty_ref = hir::TyKind::OpaqueDef(
2049             hir::ItemId { def_id: opaque_ty_def_id },
2050             generic_args,
2051             in_trait,
2052         );
2053         let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2054         hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2055     }
2056
2057     /// Transforms `-> T` into `Future<Output = T>`.
2058     fn lower_async_fn_output_type_to_future_bound(
2059         &mut self,
2060         output: &FnRetTy,
2061         span: Span,
2062         mut nested_impl_trait_context: ImplTraitContext,
2063     ) -> hir::GenericBound<'hir> {
2064         // Compute the `T` in `Future<Output = T>` from the return type.
2065         let output_ty = match output {
2066             FnRetTy::Ty(ty) => {
2067                 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2068                 // `impl Future` opaque type that `async fn` implicitly
2069                 // generates.
2070                 self.lower_ty(ty, &mut nested_impl_trait_context)
2071             }
2072             FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2073         };
2074
2075         // "<Output = T>"
2076         let future_args = self.arena.alloc(hir::GenericArgs {
2077             args: &[],
2078             bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
2079             parenthesized: false,
2080             span_ext: DUMMY_SP,
2081         });
2082
2083         hir::GenericBound::LangItemTrait(
2084             // ::std::future::Future<future_params>
2085             hir::LangItem::Future,
2086             self.lower_span(span),
2087             self.next_id(),
2088             future_args,
2089         )
2090     }
2091
2092     #[instrument(level = "trace", skip(self))]
2093     fn lower_param_bound(
2094         &mut self,
2095         tpb: &GenericBound,
2096         itctx: &mut ImplTraitContext,
2097     ) -> hir::GenericBound<'hir> {
2098         match tpb {
2099             GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
2100                 self.lower_poly_trait_ref(p, itctx),
2101                 self.lower_trait_bound_modifier(*modifier),
2102             ),
2103             GenericBound::Outlives(lifetime) => {
2104                 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2105             }
2106         }
2107     }
2108
2109     fn lower_lifetime(&mut self, l: &Lifetime) -> &'hir hir::Lifetime {
2110         let span = self.lower_span(l.ident.span);
2111         let ident = self.lower_ident(l.ident);
2112         self.new_named_lifetime(l.id, l.id, span, ident)
2113     }
2114
2115     #[instrument(level = "debug", skip(self))]
2116     fn new_named_lifetime_with_res(
2117         &mut self,
2118         id: NodeId,
2119         span: Span,
2120         ident: Ident,
2121         res: LifetimeRes,
2122     ) -> &'hir hir::Lifetime {
2123         let name = match res {
2124             LifetimeRes::Param { param, .. } => {
2125                 let p_name = ParamName::Plain(ident);
2126                 let param = self.get_remapped_def_id(param);
2127
2128                 hir::LifetimeName::Param(param, p_name)
2129             }
2130             LifetimeRes::Fresh { param, .. } => {
2131                 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2132                 let param = self.local_def_id(param);
2133
2134                 hir::LifetimeName::Param(param, ParamName::Fresh)
2135             }
2136             LifetimeRes::Infer => hir::LifetimeName::Infer,
2137             LifetimeRes::Static => hir::LifetimeName::Static,
2138             LifetimeRes::Error => hir::LifetimeName::Error,
2139             res => panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span),
2140         };
2141
2142         debug!(?name);
2143         self.arena.alloc(hir::Lifetime {
2144             hir_id: self.lower_node_id(id),
2145             span: self.lower_span(span),
2146             name,
2147         })
2148     }
2149
2150     #[instrument(level = "debug", skip(self))]
2151     fn new_named_lifetime(
2152         &mut self,
2153         id: NodeId,
2154         new_id: NodeId,
2155         span: Span,
2156         ident: Ident,
2157     ) -> &'hir hir::Lifetime {
2158         let res = self.resolver.get_lifetime_res(id).unwrap_or(LifetimeRes::Error);
2159         self.new_named_lifetime_with_res(new_id, span, ident, res)
2160     }
2161
2162     fn lower_generic_params_mut<'s>(
2163         &'s mut self,
2164         params: &'s [GenericParam],
2165     ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
2166         params.iter().map(move |param| self.lower_generic_param(param))
2167     }
2168
2169     fn lower_generic_params(&mut self, params: &[GenericParam]) -> &'hir [hir::GenericParam<'hir>] {
2170         self.arena.alloc_from_iter(self.lower_generic_params_mut(params))
2171     }
2172
2173     #[instrument(level = "trace", skip(self))]
2174     fn lower_generic_param(&mut self, param: &GenericParam) -> hir::GenericParam<'hir> {
2175         let (name, kind) = self.lower_generic_param_kind(param);
2176
2177         let hir_id = self.lower_node_id(param.id);
2178         self.lower_attrs(hir_id, &param.attrs);
2179         hir::GenericParam {
2180             hir_id,
2181             name,
2182             span: self.lower_span(param.span()),
2183             pure_wrt_drop: self.tcx.sess.contains_name(&param.attrs, sym::may_dangle),
2184             kind,
2185             colon_span: param.colon_span.map(|s| self.lower_span(s)),
2186         }
2187     }
2188
2189     fn lower_generic_param_kind(
2190         &mut self,
2191         param: &GenericParam,
2192     ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2193         match param.kind {
2194             GenericParamKind::Lifetime => {
2195                 // AST resolution emitted an error on those parameters, so we lower them using
2196                 // `ParamName::Error`.
2197                 let param_name =
2198                     if let Some(LifetimeRes::Error) = self.resolver.get_lifetime_res(param.id) {
2199                         ParamName::Error
2200                     } else {
2201                         let ident = self.lower_ident(param.ident);
2202                         ParamName::Plain(ident)
2203                     };
2204                 let kind =
2205                     hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2206
2207                 (param_name, kind)
2208             }
2209             GenericParamKind::Type { ref default, .. } => {
2210                 let kind = hir::GenericParamKind::Type {
2211                     default: default.as_ref().map(|x| {
2212                         self.lower_ty(x, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type))
2213                     }),
2214                     synthetic: false,
2215                 };
2216
2217                 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2218             }
2219             GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2220                 let ty =
2221                     self.lower_ty(&ty, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type));
2222                 let default = default.as_ref().map(|def| self.lower_anon_const(def));
2223                 (
2224                     hir::ParamName::Plain(self.lower_ident(param.ident)),
2225                     hir::GenericParamKind::Const { ty, default },
2226                 )
2227             }
2228         }
2229     }
2230
2231     fn lower_trait_ref(
2232         &mut self,
2233         p: &TraitRef,
2234         itctx: &mut ImplTraitContext,
2235     ) -> hir::TraitRef<'hir> {
2236         let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2237             hir::QPath::Resolved(None, path) => path,
2238             qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2239         };
2240         hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2241     }
2242
2243     #[instrument(level = "debug", skip(self))]
2244     fn lower_poly_trait_ref(
2245         &mut self,
2246         p: &PolyTraitRef,
2247         itctx: &mut ImplTraitContext,
2248     ) -> hir::PolyTraitRef<'hir> {
2249         self.lower_lifetime_binder(
2250             p.trait_ref.ref_id,
2251             &p.bound_generic_params,
2252             |lctx, bound_generic_params| {
2253                 let trait_ref = lctx.lower_trait_ref(&p.trait_ref, itctx);
2254                 hir::PolyTraitRef { bound_generic_params, trait_ref, span: lctx.lower_span(p.span) }
2255             },
2256         )
2257     }
2258
2259     fn lower_mt(&mut self, mt: &MutTy, itctx: &mut ImplTraitContext) -> hir::MutTy<'hir> {
2260         hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2261     }
2262
2263     #[instrument(level = "debug", skip(self), ret)]
2264     fn lower_param_bounds(
2265         &mut self,
2266         bounds: &[GenericBound],
2267         itctx: &mut ImplTraitContext,
2268     ) -> hir::GenericBounds<'hir> {
2269         self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2270     }
2271
2272     fn lower_param_bounds_mut<'s, 'b>(
2273         &'s mut self,
2274         bounds: &'s [GenericBound],
2275         itctx: &'b mut ImplTraitContext,
2276     ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> + Captures<'b>
2277     {
2278         bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx))
2279     }
2280
2281     #[instrument(level = "debug", skip(self), ret)]
2282     fn lower_generic_and_bounds(
2283         &mut self,
2284         node_id: NodeId,
2285         span: Span,
2286         ident: Ident,
2287         bounds: &[GenericBound],
2288     ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2289         // Add a definition for the in-band `Param`.
2290         let def_id = self.local_def_id(node_id);
2291
2292         // Set the name to `impl Bound1 + Bound2`.
2293         let param = hir::GenericParam {
2294             hir_id: self.lower_node_id(node_id),
2295             name: ParamName::Plain(self.lower_ident(ident)),
2296             pure_wrt_drop: false,
2297             span: self.lower_span(span),
2298             kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2299             colon_span: None,
2300         };
2301
2302         let preds = self.lower_generic_bound_predicate(
2303             ident,
2304             node_id,
2305             &GenericParamKind::Type { default: None },
2306             bounds,
2307             &mut ImplTraitContext::Universal,
2308             hir::PredicateOrigin::ImplTrait,
2309         );
2310
2311         let hir_id = self.next_id();
2312         let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2313         let ty = hir::TyKind::Path(hir::QPath::Resolved(
2314             None,
2315             self.arena.alloc(hir::Path {
2316                 span: self.lower_span(span),
2317                 res,
2318                 segments:
2319                     arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2320             }),
2321         ));
2322
2323         (param, preds, ty)
2324     }
2325
2326     /// Lowers a block directly to an expression, presuming that it
2327     /// has no attributes and is not targeted by a `break`.
2328     fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2329         let block = self.lower_block(b, false);
2330         self.expr_block(block, AttrVec::new())
2331     }
2332
2333     fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen {
2334         match c.value.kind {
2335             ExprKind::Underscore => {
2336                 if self.tcx.features().generic_arg_infer {
2337                     hir::ArrayLen::Infer(self.lower_node_id(c.id), c.value.span)
2338                 } else {
2339                     feature_err(
2340                         &self.tcx.sess.parse_sess,
2341                         sym::generic_arg_infer,
2342                         c.value.span,
2343                         "using `_` for array lengths is unstable",
2344                     )
2345                     .stash(c.value.span, StashKey::UnderscoreForArrayLengths);
2346                     hir::ArrayLen::Body(self.lower_anon_const(c))
2347                 }
2348             }
2349             _ => hir::ArrayLen::Body(self.lower_anon_const(c)),
2350         }
2351     }
2352
2353     fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2354         self.with_new_scopes(|this| hir::AnonConst {
2355             hir_id: this.lower_node_id(c.id),
2356             body: this.lower_const_body(c.value.span, Some(&c.value)),
2357         })
2358     }
2359
2360     fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2361         match u {
2362             CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2363             UserProvided => hir::UnsafeSource::UserProvided,
2364         }
2365     }
2366
2367     fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2368         match f {
2369             TraitBoundModifier::None => hir::TraitBoundModifier::None,
2370             TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2371
2372             // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2373             // placeholder for compilation to proceed.
2374             TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2375                 hir::TraitBoundModifier::Maybe
2376             }
2377         }
2378     }
2379
2380     // Helper methods for building HIR.
2381
2382     fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2383         hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2384     }
2385
2386     fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2387         self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2388     }
2389
2390     fn stmt_let_pat(
2391         &mut self,
2392         attrs: Option<&'hir [Attribute]>,
2393         span: Span,
2394         init: Option<&'hir hir::Expr<'hir>>,
2395         pat: &'hir hir::Pat<'hir>,
2396         source: hir::LocalSource,
2397     ) -> hir::Stmt<'hir> {
2398         let hir_id = self.next_id();
2399         if let Some(a) = attrs {
2400             debug_assert!(!a.is_empty());
2401             self.attrs.insert(hir_id.local_id, a);
2402         }
2403         let local = hir::Local {
2404             hir_id,
2405             init,
2406             pat,
2407             els: None,
2408             source,
2409             span: self.lower_span(span),
2410             ty: None,
2411         };
2412         self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2413     }
2414
2415     fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2416         self.block_all(expr.span, &[], Some(expr))
2417     }
2418
2419     fn block_all(
2420         &mut self,
2421         span: Span,
2422         stmts: &'hir [hir::Stmt<'hir>],
2423         expr: Option<&'hir hir::Expr<'hir>>,
2424     ) -> &'hir hir::Block<'hir> {
2425         let blk = hir::Block {
2426             stmts,
2427             expr,
2428             hir_id: self.next_id(),
2429             rules: hir::BlockCheckMode::DefaultBlock,
2430             span: self.lower_span(span),
2431             targeted_by_break: false,
2432         };
2433         self.arena.alloc(blk)
2434     }
2435
2436     fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2437         let field = self.single_pat_field(span, pat);
2438         self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field, None)
2439     }
2440
2441     fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2442         let field = self.single_pat_field(span, pat);
2443         self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field, None)
2444     }
2445
2446     fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2447         let field = self.single_pat_field(span, pat);
2448         self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field, None)
2449     }
2450
2451     fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2452         self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[], None)
2453     }
2454
2455     fn single_pat_field(
2456         &mut self,
2457         span: Span,
2458         pat: &'hir hir::Pat<'hir>,
2459     ) -> &'hir [hir::PatField<'hir>] {
2460         let field = hir::PatField {
2461             hir_id: self.next_id(),
2462             ident: Ident::new(sym::integer(0), self.lower_span(span)),
2463             is_shorthand: false,
2464             pat,
2465             span: self.lower_span(span),
2466         };
2467         arena_vec![self; field]
2468     }
2469
2470     fn pat_lang_item_variant(
2471         &mut self,
2472         span: Span,
2473         lang_item: hir::LangItem,
2474         fields: &'hir [hir::PatField<'hir>],
2475         hir_id: Option<hir::HirId>,
2476     ) -> &'hir hir::Pat<'hir> {
2477         let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id);
2478         self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2479     }
2480
2481     fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2482         self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::NONE)
2483     }
2484
2485     fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2486         self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::NONE)
2487     }
2488
2489     fn pat_ident_binding_mode(
2490         &mut self,
2491         span: Span,
2492         ident: Ident,
2493         bm: hir::BindingAnnotation,
2494     ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2495         let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2496         (self.arena.alloc(pat), hir_id)
2497     }
2498
2499     fn pat_ident_binding_mode_mut(
2500         &mut self,
2501         span: Span,
2502         ident: Ident,
2503         bm: hir::BindingAnnotation,
2504     ) -> (hir::Pat<'hir>, hir::HirId) {
2505         let hir_id = self.next_id();
2506
2507         (
2508             hir::Pat {
2509                 hir_id,
2510                 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2511                 span: self.lower_span(span),
2512                 default_binding_modes: true,
2513             },
2514             hir_id,
2515         )
2516     }
2517
2518     fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2519         self.arena.alloc(hir::Pat {
2520             hir_id: self.next_id(),
2521             kind,
2522             span: self.lower_span(span),
2523             default_binding_modes: true,
2524         })
2525     }
2526
2527     fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2528         hir::Pat {
2529             hir_id: self.next_id(),
2530             kind,
2531             span: self.lower_span(span),
2532             default_binding_modes: false,
2533         }
2534     }
2535
2536     fn ty_path(
2537         &mut self,
2538         mut hir_id: hir::HirId,
2539         span: Span,
2540         qpath: hir::QPath<'hir>,
2541     ) -> hir::Ty<'hir> {
2542         let kind = match qpath {
2543             hir::QPath::Resolved(None, path) => {
2544                 // Turn trait object paths into `TyKind::TraitObject` instead.
2545                 match path.res {
2546                     Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2547                         let principal = hir::PolyTraitRef {
2548                             bound_generic_params: &[],
2549                             trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2550                             span: self.lower_span(span),
2551                         };
2552
2553                         // The original ID is taken by the `PolyTraitRef`,
2554                         // so the `Ty` itself needs a different one.
2555                         hir_id = self.next_id();
2556                         hir::TyKind::TraitObject(
2557                             arena_vec![self; principal],
2558                             self.elided_dyn_bound(span),
2559                             TraitObjectSyntax::None,
2560                         )
2561                     }
2562                     _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2563                 }
2564             }
2565             _ => hir::TyKind::Path(qpath),
2566         };
2567
2568         hir::Ty { hir_id, kind, span: self.lower_span(span) }
2569     }
2570
2571     /// Invoked to create the lifetime argument(s) for an elided trait object
2572     /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2573     /// when the bound is written, even if it is written with `'_` like in
2574     /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2575     fn elided_dyn_bound(&mut self, span: Span) -> &'hir hir::Lifetime {
2576         let r = hir::Lifetime {
2577             hir_id: self.next_id(),
2578             span: self.lower_span(span),
2579             name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2580         };
2581         debug!("elided_dyn_bound: r={:?}", r);
2582         self.arena.alloc(r)
2583     }
2584 }
2585
2586 /// Helper struct for delayed construction of GenericArgs.
2587 struct GenericArgsCtor<'hir> {
2588     args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2589     bindings: &'hir [hir::TypeBinding<'hir>],
2590     parenthesized: bool,
2591     span: Span,
2592 }
2593
2594 impl<'hir> GenericArgsCtor<'hir> {
2595     fn is_empty(&self) -> bool {
2596         self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2597     }
2598
2599     fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2600         let ga = hir::GenericArgs {
2601             args: this.arena.alloc_from_iter(self.args),
2602             bindings: self.bindings,
2603             parenthesized: self.parenthesized,
2604             span_ext: this.lower_span(self.span),
2605         };
2606         this.arena.alloc(ga)
2607     }
2608 }