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