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