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