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