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