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