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