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