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