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