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