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