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