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