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