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