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