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