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