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