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