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