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