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