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