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