]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/lowering.rs
Handle Attributes in arena.
[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>,
101     impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
102     bodies: BTreeMap<hir::BodyId, hir::Body>,
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> for ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1583             fn nested_visit_map<'this>(
1584                 &'this mut self,
1585             ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1586                 hir::intravisit::NestedVisitorMap::None
1587             }
1588
1589             fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1590                 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1591                 if parameters.parenthesized {
1592                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1593                     self.collect_elided_lifetimes = false;
1594                     hir::intravisit::walk_generic_args(self, span, parameters);
1595                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1596                 } else {
1597                     hir::intravisit::walk_generic_args(self, span, parameters);
1598                 }
1599             }
1600
1601             fn visit_ty(&mut self, t: &'v hir::Ty) {
1602                 // Don't collect elided lifetimes used inside of `fn()` syntax.
1603                 if let hir::TyKind::BareFn(_) = t.kind {
1604                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1605                     self.collect_elided_lifetimes = false;
1606
1607                     // Record the "stack height" of `for<'a>` lifetime bindings
1608                     // to be able to later fully undo their introduction.
1609                     let old_len = self.currently_bound_lifetimes.len();
1610                     hir::intravisit::walk_ty(self, t);
1611                     self.currently_bound_lifetimes.truncate(old_len);
1612
1613                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1614                 } else {
1615                     hir::intravisit::walk_ty(self, t)
1616                 }
1617             }
1618
1619             fn visit_poly_trait_ref(
1620                 &mut self,
1621                 trait_ref: &'v hir::PolyTraitRef,
1622                 modifier: hir::TraitBoundModifier,
1623             ) {
1624                 // Record the "stack height" of `for<'a>` lifetime bindings
1625                 // to be able to later fully undo their introduction.
1626                 let old_len = self.currently_bound_lifetimes.len();
1627                 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1628                 self.currently_bound_lifetimes.truncate(old_len);
1629             }
1630
1631             fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1632                 // Record the introduction of 'a in `for<'a> ...`.
1633                 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1634                     // Introduce lifetimes one at a time so that we can handle
1635                     // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1636                     let lt_name = hir::LifetimeName::Param(param.name);
1637                     self.currently_bound_lifetimes.push(lt_name);
1638                 }
1639
1640                 hir::intravisit::walk_generic_param(self, param);
1641             }
1642
1643             fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1644                 let name = match lifetime.name {
1645                     hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1646                         if self.collect_elided_lifetimes {
1647                             // Use `'_` for both implicit and underscore lifetimes in
1648                             // `type Foo<'_> = impl SomeTrait<'_>;`.
1649                             hir::LifetimeName::Underscore
1650                         } else {
1651                             return;
1652                         }
1653                     }
1654                     hir::LifetimeName::Param(_) => lifetime.name,
1655
1656                     // Refers to some other lifetime that is "in
1657                     // scope" within the type.
1658                     hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1659
1660                     hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1661                 };
1662
1663                 if !self.currently_bound_lifetimes.contains(&name)
1664                     && !self.already_defined_lifetimes.contains(&name) {
1665                     self.already_defined_lifetimes.insert(name);
1666
1667                     self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1668                         hir_id: self.context.next_id(),
1669                         span: lifetime.span,
1670                         name,
1671                     }));
1672
1673                     let def_node_id = self.context.resolver.next_node_id();
1674                     let hir_id =
1675                         self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
1676                     self.context.resolver.definitions().create_def_with_parent(
1677                         self.parent,
1678                         def_node_id,
1679                         DefPathData::LifetimeNs(name.ident().name),
1680                         ExpnId::root(),
1681                         lifetime.span);
1682
1683                     let (name, kind) = match name {
1684                         hir::LifetimeName::Underscore => (
1685                             hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1686                             hir::LifetimeParamKind::Elided,
1687                         ),
1688                         hir::LifetimeName::Param(param_name) => (
1689                             param_name,
1690                             hir::LifetimeParamKind::Explicit,
1691                         ),
1692                         _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1693                     };
1694
1695                     self.output_lifetime_params.push(hir::GenericParam {
1696                         hir_id,
1697                         name,
1698                         span: lifetime.span,
1699                         pure_wrt_drop: false,
1700                         attrs: hir_vec![],
1701                         bounds: hir_vec![],
1702                         kind: hir::GenericParamKind::Lifetime { kind }
1703                     });
1704                 }
1705             }
1706         }
1707
1708         let mut lifetime_collector = ImplTraitLifetimeCollector {
1709             context: self,
1710             parent: parent_index,
1711             opaque_ty_id,
1712             collect_elided_lifetimes: true,
1713             currently_bound_lifetimes: Vec::new(),
1714             already_defined_lifetimes: FxHashSet::default(),
1715             output_lifetimes: Vec::new(),
1716             output_lifetime_params: Vec::new(),
1717         };
1718
1719         for bound in bounds {
1720             hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1721         }
1722
1723         (
1724             lifetime_collector.output_lifetimes.into(),
1725             lifetime_collector.output_lifetime_params.into(),
1726         )
1727     }
1728
1729     fn lower_qpath(
1730         &mut self,
1731         id: NodeId,
1732         qself: &Option<QSelf>,
1733         p: &Path,
1734         param_mode: ParamMode,
1735         mut itctx: ImplTraitContext<'_>,
1736     ) -> hir::QPath {
1737         let qself_position = qself.as_ref().map(|q| q.position);
1738         let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1739
1740         let partial_res = self.resolver
1741             .get_partial_res(id)
1742             .unwrap_or_else(|| PartialRes::new(Res::Err));
1743
1744         let proj_start = p.segments.len() - partial_res.unresolved_segments();
1745         let path = P(hir::Path {
1746             res: self.lower_res(partial_res.base_res()),
1747             segments: p.segments[..proj_start]
1748                 .iter()
1749                 .enumerate()
1750                 .map(|(i, segment)| {
1751                     let param_mode = match (qself_position, param_mode) {
1752                         (Some(j), ParamMode::Optional) if i < j => {
1753                             // This segment is part of the trait path in a
1754                             // qualified path - one of `a`, `b` or `Trait`
1755                             // in `<X as a::b::Trait>::T::U::method`.
1756                             ParamMode::Explicit
1757                         }
1758                         _ => param_mode,
1759                     };
1760
1761                     // Figure out if this is a type/trait segment,
1762                     // which may need lifetime elision performed.
1763                     let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1764                         krate: def_id.krate,
1765                         index: this.def_key(def_id).parent.expect("missing parent"),
1766                     };
1767                     let type_def_id = match partial_res.base_res() {
1768                         Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
1769                             Some(parent_def_id(self, def_id))
1770                         }
1771                         Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1772                             Some(parent_def_id(self, def_id))
1773                         }
1774                         Res::Def(DefKind::Struct, def_id)
1775                         | Res::Def(DefKind::Union, def_id)
1776                         | Res::Def(DefKind::Enum, def_id)
1777                         | Res::Def(DefKind::TyAlias, def_id)
1778                         | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
1779                         {
1780                             Some(def_id)
1781                         }
1782                         _ => None,
1783                     };
1784                     let parenthesized_generic_args = match partial_res.base_res() {
1785                         // `a::b::Trait(Args)`
1786                         Res::Def(DefKind::Trait, _) if i + 1 == proj_start => {
1787                             ParenthesizedGenericArgs::Ok
1788                         }
1789                         // `a::b::Trait(Args)::TraitItem`
1790                         Res::Def(DefKind::Method, _) |
1791                         Res::Def(DefKind::AssocConst, _) |
1792                         Res::Def(DefKind::AssocTy, _) if i + 2 == proj_start => {
1793                             ParenthesizedGenericArgs::Ok
1794                         }
1795                         // Avoid duplicated errors.
1796                         Res::Err => ParenthesizedGenericArgs::Ok,
1797                         // An error
1798                         _ => ParenthesizedGenericArgs::Err,
1799                     };
1800
1801                     let num_lifetimes = type_def_id.map_or(0, |def_id| {
1802                         if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1803                             return n;
1804                         }
1805                         assert!(!def_id.is_local());
1806                         let item_generics = self.resolver.cstore()
1807                             .item_generics_cloned_untracked(def_id, self.sess);
1808                         let n = item_generics.own_counts().lifetimes;
1809                         self.type_def_lifetime_params.insert(def_id, n);
1810                         n
1811                     });
1812                     self.lower_path_segment(
1813                         p.span,
1814                         segment,
1815                         param_mode,
1816                         num_lifetimes,
1817                         parenthesized_generic_args,
1818                         itctx.reborrow(),
1819                         None,
1820                     )
1821                 })
1822                 .collect(),
1823             span: p.span,
1824         });
1825
1826         // Simple case, either no projections, or only fully-qualified.
1827         // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1828         if partial_res.unresolved_segments() == 0 {
1829             return hir::QPath::Resolved(qself, path);
1830         }
1831
1832         // Create the innermost type that we're projecting from.
1833         let mut ty = if path.segments.is_empty() {
1834             // If the base path is empty that means there exists a
1835             // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1836             qself.expect("missing QSelf for <T>::...")
1837         } else {
1838             // Otherwise, the base path is an implicit `Self` type path,
1839             // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1840             // `<I as Iterator>::Item::default`.
1841             let new_id = self.next_id();
1842             P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1843         };
1844
1845         // Anything after the base path are associated "extensions",
1846         // out of which all but the last one are associated types,
1847         // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1848         // * base path is `std::vec::Vec<T>`
1849         // * "extensions" are `IntoIter`, `Item` and `clone`
1850         // * type nodes are:
1851         //   1. `std::vec::Vec<T>` (created above)
1852         //   2. `<std::vec::Vec<T>>::IntoIter`
1853         //   3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1854         // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1855         for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1856             let segment = P(self.lower_path_segment(
1857                 p.span,
1858                 segment,
1859                 param_mode,
1860                 0,
1861                 ParenthesizedGenericArgs::Err,
1862                 itctx.reborrow(),
1863                 None,
1864             ));
1865             let qpath = hir::QPath::TypeRelative(ty, segment);
1866
1867             // It's finished, return the extension of the right node type.
1868             if i == p.segments.len() - 1 {
1869                 return qpath;
1870             }
1871
1872             // Wrap the associated extension in another type node.
1873             let new_id = self.next_id();
1874             ty = P(self.ty_path(new_id, p.span, qpath));
1875         }
1876
1877         // We should've returned in the for loop above.
1878         span_bug!(
1879             p.span,
1880             "lower_qpath: no final extension segment in {}..{}",
1881             proj_start,
1882             p.segments.len()
1883         )
1884     }
1885
1886     fn lower_path_extra(
1887         &mut self,
1888         res: Res,
1889         p: &Path,
1890         param_mode: ParamMode,
1891         explicit_owner: Option<NodeId>,
1892     ) -> hir::Path {
1893         hir::Path {
1894             res,
1895             segments: p.segments
1896                 .iter()
1897                 .map(|segment| {
1898                     self.lower_path_segment(
1899                         p.span,
1900                         segment,
1901                         param_mode,
1902                         0,
1903                         ParenthesizedGenericArgs::Err,
1904                         ImplTraitContext::disallowed(),
1905                         explicit_owner,
1906                     )
1907                 })
1908                 .collect(),
1909             span: p.span,
1910         }
1911     }
1912
1913     fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1914         let res = self.expect_full_res(id);
1915         let res = self.lower_res(res);
1916         self.lower_path_extra(res, p, param_mode, None)
1917     }
1918
1919     fn lower_path_segment(
1920         &mut self,
1921         path_span: Span,
1922         segment: &PathSegment,
1923         param_mode: ParamMode,
1924         expected_lifetimes: usize,
1925         parenthesized_generic_args: ParenthesizedGenericArgs,
1926         itctx: ImplTraitContext<'_>,
1927         explicit_owner: Option<NodeId>,
1928     ) -> hir::PathSegment {
1929         let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
1930             let msg = "parenthesized type parameters may only be used with a `Fn` trait";
1931             match **generic_args {
1932                 GenericArgs::AngleBracketed(ref data) => {
1933                     self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1934                 }
1935                 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1936                     ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1937                     ParenthesizedGenericArgs::Err => {
1938                         let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
1939                         err.span_label(data.span, "only `Fn` traits may use parentheses");
1940                         if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
1941                             // Do not suggest going from `Trait()` to `Trait<>`
1942                             if data.inputs.len() > 0 {
1943                                 if let Some(split) = snippet.find('(') {
1944                                     let trait_name = &snippet[0..split];
1945                                     let args = &snippet[split + 1 .. snippet.len() - 1];
1946                                     err.span_suggestion(
1947                                         data.span,
1948                                         "use angle brackets instead",
1949                                         format!("{}<{}>", trait_name, args),
1950                                         Applicability::MaybeIncorrect,
1951                                     );
1952                                 }
1953                             }
1954                         };
1955                         err.emit();
1956                         (
1957                             self.lower_angle_bracketed_parameter_data(
1958                                 &data.as_angle_bracketed_args(),
1959                                 param_mode,
1960                                 itctx
1961                             ).0,
1962                             false,
1963                         )
1964                     }
1965                 },
1966             }
1967         } else {
1968             self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1969         };
1970
1971         let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1972             GenericArg::Lifetime(_) => true,
1973             _ => false,
1974         });
1975         let first_generic_span = generic_args.args.iter().map(|a| a.span())
1976             .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1977         if !generic_args.parenthesized && !has_lifetimes {
1978             generic_args.args =
1979                 self.elided_path_lifetimes(path_span, expected_lifetimes)
1980                     .into_iter()
1981                     .map(|lt| GenericArg::Lifetime(lt))
1982                     .chain(generic_args.args.into_iter())
1983                 .collect();
1984             if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1985                 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1986                 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
1987                 let no_bindings = generic_args.bindings.is_empty();
1988                 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
1989                     // If there are no (non-implicit) generic args or associated type
1990                     // bindings, our suggestion includes the angle brackets.
1991                     (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1992                 } else {
1993                     // Otherwise (sorry, this is kind of gross) we need to infer the
1994                     // place to splice in the `'_, ` from the generics that do exist.
1995                     let first_generic_span = first_generic_span
1996                         .expect("already checked that non-lifetime args or bindings exist");
1997                     (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1998                 };
1999                 match self.anonymous_lifetime_mode {
2000                     // In create-parameter mode we error here because we don't want to support
2001                     // deprecated impl elision in new features like impl elision and `async fn`,
2002                     // both of which work using the `CreateParameter` mode:
2003                     //
2004                     //     impl Foo for std::cell::Ref<u32> // note lack of '_
2005                     //     async fn foo(_: std::cell::Ref<u32>) { ... }
2006                     AnonymousLifetimeMode::CreateParameter => {
2007                         let mut err = struct_span_err!(
2008                             self.sess,
2009                             path_span,
2010                             E0726,
2011                             "implicit elided lifetime not allowed here"
2012                         );
2013                         crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
2014                             &self.sess,
2015                             &mut err,
2016                             expected_lifetimes,
2017                             path_span,
2018                             incl_angl_brckt,
2019                             insertion_sp,
2020                             suggestion,
2021                         );
2022                         err.emit();
2023                     }
2024                     AnonymousLifetimeMode::PassThrough |
2025                     AnonymousLifetimeMode::ReportError => {
2026                         self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2027                             ELIDED_LIFETIMES_IN_PATHS,
2028                             CRATE_NODE_ID,
2029                             path_span,
2030                             "hidden lifetime parameters in types are deprecated",
2031                             builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
2032                                 expected_lifetimes,
2033                                 path_span,
2034                                 incl_angl_brckt,
2035                                 insertion_sp,
2036                                 suggestion,
2037                             )
2038                         );
2039                     }
2040                 }
2041             }
2042         }
2043
2044         let res = self.expect_full_res(segment.id);
2045         let id = if let Some(owner) = explicit_owner {
2046             self.lower_node_id_with_owner(segment.id, owner)
2047         } else {
2048             self.lower_node_id(segment.id)
2049         };
2050         debug!(
2051             "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2052             segment.ident, segment.id, id,
2053         );
2054
2055         hir::PathSegment::new(
2056             segment.ident,
2057             Some(id),
2058             Some(self.lower_res(res)),
2059             generic_args,
2060             infer_args,
2061         )
2062     }
2063
2064     fn lower_angle_bracketed_parameter_data(
2065         &mut self,
2066         data: &AngleBracketedArgs,
2067         param_mode: ParamMode,
2068         mut itctx: ImplTraitContext<'_>,
2069     ) -> (hir::GenericArgs, bool) {
2070         let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
2071         let has_non_lt_args = args.iter().any(|arg| match arg {
2072             ast::GenericArg::Lifetime(_) => false,
2073             ast::GenericArg::Type(_) => true,
2074             ast::GenericArg::Const(_) => true,
2075         });
2076         (
2077             hir::GenericArgs {
2078                 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2079                 bindings: constraints.iter()
2080                     .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow()))
2081                     .collect(),
2082                 parenthesized: false,
2083             },
2084             !has_non_lt_args && param_mode == ParamMode::Optional
2085         )
2086     }
2087
2088     fn lower_parenthesized_parameter_data(
2089         &mut self,
2090         data: &ParenthesizedArgs,
2091     ) -> (hir::GenericArgs, bool) {
2092         // Switch to `PassThrough` mode for anonymous lifetimes; this
2093         // means that we permit things like `&Ref<T>`, where `Ref` has
2094         // a hidden lifetime parameter. This is needed for backwards
2095         // compatibility, even in contexts like an impl header where
2096         // we generally don't permit such things (see #51008).
2097         self.with_anonymous_lifetime_mode(
2098             AnonymousLifetimeMode::PassThrough,
2099             |this| {
2100                 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2101                 let inputs = inputs
2102                     .iter()
2103                     .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2104                     .collect();
2105                 let output_ty = match output {
2106                     FunctionRetTy::Ty(ty) => this.lower_ty(&ty, ImplTraitContext::disallowed()),
2107                     FunctionRetTy::Default(_) => P(this.ty_tup(span, hir::HirVec::new())),
2108                 };
2109                 let args = hir_vec![GenericArg::Type(this.ty_tup(span, inputs))];
2110                 let binding = hir::TypeBinding {
2111                     hir_id: this.next_id(),
2112                     ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2113                     span: output_ty.span,
2114                     kind: hir::TypeBindingKind::Equality { ty: output_ty },
2115                 };
2116                 (
2117                     hir::GenericArgs { args, bindings: hir_vec![binding], parenthesized: true },
2118                     false,
2119                 )
2120             }
2121         )
2122     }
2123
2124     fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2125         let mut ids = SmallVec::<[NodeId; 1]>::new();
2126         if self.sess.features_untracked().impl_trait_in_bindings {
2127             if let Some(ref ty) = l.ty {
2128                 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2129                 visitor.visit_ty(ty);
2130             }
2131         }
2132         let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2133         (hir::Local {
2134             hir_id: self.lower_node_id(l.id),
2135             ty: l.ty
2136                 .as_ref()
2137                 .map(|t| self.lower_ty(t,
2138                     if self.sess.features_untracked().impl_trait_in_bindings {
2139                         ImplTraitContext::OpaqueTy(Some(parent_def_id))
2140                     } else {
2141                         ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2142                     }
2143                 )),
2144             pat: self.lower_pat(&l.pat),
2145             init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2146             span: l.span,
2147             attrs: l.attrs.clone(),
2148             source: hir::LocalSource::Normal,
2149         }, ids)
2150     }
2151
2152     fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2153         // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
2154         // as they are not explicit in HIR/Ty function signatures.
2155         // (instead, the `c_variadic` flag is set to `true`)
2156         let mut inputs = &decl.inputs[..];
2157         if decl.c_variadic() {
2158             inputs = &inputs[..inputs.len() - 1];
2159         }
2160         inputs
2161             .iter()
2162             .map(|param| match param.pat.kind {
2163                 PatKind::Ident(_, ident, _) => ident,
2164                 _ => Ident::new(kw::Invalid, param.pat.span),
2165             })
2166             .collect()
2167     }
2168
2169     // Lowers a function declaration.
2170     //
2171     // `decl`: the unlowered (AST) function declaration.
2172     // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
2173     //      given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2174     //      `make_ret_async` is also `Some`.
2175     // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
2176     //      This guards against trait declarations and implementations where `impl Trait` is
2177     //      disallowed.
2178     // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2179     //      return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
2180     //      return type `impl Trait` item.
2181     fn lower_fn_decl(
2182         &mut self,
2183         decl: &FnDecl,
2184         mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2185         impl_trait_return_allow: bool,
2186         make_ret_async: Option<NodeId>,
2187     ) -> P<hir::FnDecl> {
2188         debug!("lower_fn_decl(\
2189             fn_decl: {:?}, \
2190             in_band_ty_params: {:?}, \
2191             impl_trait_return_allow: {}, \
2192             make_ret_async: {:?})",
2193             decl,
2194             in_band_ty_params,
2195             impl_trait_return_allow,
2196             make_ret_async,
2197         );
2198         let lt_mode = if make_ret_async.is_some() {
2199             // In `async fn`, argument-position elided lifetimes
2200             // must be transformed into fresh generic parameters so that
2201             // they can be applied to the opaque `impl Trait` return type.
2202             AnonymousLifetimeMode::CreateParameter
2203         } else {
2204             self.anonymous_lifetime_mode
2205         };
2206
2207         let c_variadic = decl.c_variadic();
2208
2209         // Remember how many lifetimes were already around so that we can
2210         // only look at the lifetime parameters introduced by the arguments.
2211         let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2212             // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
2213             // as they are not explicit in HIR/Ty function signatures.
2214             // (instead, the `c_variadic` flag is set to `true`)
2215             let mut inputs = &decl.inputs[..];
2216             if c_variadic {
2217                 inputs = &inputs[..inputs.len() - 1];
2218             }
2219             inputs
2220                 .iter()
2221                 .map(|param| {
2222                     if let Some((_, ibty)) = &mut in_band_ty_params {
2223                         this.lower_ty_direct(&param.ty, ImplTraitContext::Universal(ibty))
2224                     } else {
2225                         this.lower_ty_direct(&param.ty, ImplTraitContext::disallowed())
2226                     }
2227                 })
2228                 .collect::<HirVec<_>>()
2229         });
2230
2231         let output = if let Some(ret_id) = make_ret_async {
2232             self.lower_async_fn_ret_ty(
2233                 &decl.output,
2234                 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
2235                 ret_id,
2236             )
2237         } else {
2238             match decl.output {
2239                 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2240                     Some((def_id, _)) if impl_trait_return_allow => {
2241                         hir::Return(self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(def_id))))
2242                     }
2243                     _ => {
2244                         hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2245                     }
2246                 },
2247                 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2248             }
2249         };
2250
2251         P(hir::FnDecl {
2252             inputs,
2253             output,
2254             c_variadic,
2255             implicit_self: decl.inputs.get(0).map_or(
2256                 hir::ImplicitSelfKind::None,
2257                 |arg| {
2258                     let is_mutable_pat = match arg.pat.kind {
2259                         PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2260                         PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2261                             mt == Mutability::Mut,
2262                         _ => false,
2263                     };
2264
2265                     match arg.ty.kind {
2266                         TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2267                         TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2268                         // Given we are only considering `ImplicitSelf` types, we needn't consider
2269                         // the case where we have a mutable pattern to a reference as that would
2270                         // no longer be an `ImplicitSelf`.
2271                         TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() &&
2272                             mt.mutbl == ast::Mutability::Mut =>
2273                                 hir::ImplicitSelfKind::MutRef,
2274                         TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() =>
2275                             hir::ImplicitSelfKind::ImmRef,
2276                         _ => hir::ImplicitSelfKind::None,
2277                     }
2278                 },
2279             ),
2280         })
2281     }
2282
2283     // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
2284     // combined with the following definition of `OpaqueTy`:
2285     //
2286     //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
2287     //
2288     // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
2289     // `output`: unlowered output type (`T` in `-> T`)
2290     // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
2291     // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
2292     // `elided_lt_replacement`: replacement for elided lifetimes in the return type
2293     fn lower_async_fn_ret_ty(
2294         &mut self,
2295         output: &FunctionRetTy,
2296         fn_def_id: DefId,
2297         opaque_ty_node_id: NodeId,
2298     ) -> hir::FunctionRetTy {
2299         debug!(
2300             "lower_async_fn_ret_ty(\
2301              output={:?}, \
2302              fn_def_id={:?}, \
2303              opaque_ty_node_id={:?})",
2304             output, fn_def_id, opaque_ty_node_id,
2305         );
2306
2307         let span = output.span();
2308
2309         let opaque_ty_span = self.mark_span_with_reason(
2310             DesugaringKind::Async,
2311             span,
2312             None,
2313         );
2314
2315         let opaque_ty_def_index = self
2316             .resolver
2317             .definitions()
2318             .opt_def_index(opaque_ty_node_id)
2319             .unwrap();
2320
2321         self.allocate_hir_id_counter(opaque_ty_node_id);
2322
2323         // When we create the opaque type for this async fn, it is going to have
2324         // to capture all the lifetimes involved in the signature (including in the
2325         // return type). This is done by introducing lifetime parameters for:
2326         //
2327         // - all the explicitly declared lifetimes from the impl and function itself;
2328         // - all the elided lifetimes in the fn arguments;
2329         // - all the elided lifetimes in the return type.
2330         //
2331         // So for example in this snippet:
2332         //
2333         // ```rust
2334         // impl<'a> Foo<'a> {
2335         //   async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
2336         //   //               ^ '0                       ^ '1     ^ '2
2337         //   // elided lifetimes used below
2338         //   }
2339         // }
2340         // ```
2341         //
2342         // we would create an opaque type like:
2343         //
2344         // ```
2345         // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
2346         // ```
2347         //
2348         // and we would then desugar `bar` to the equivalent of:
2349         //
2350         // ```rust
2351         // impl<'a> Foo<'a> {
2352         //   fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
2353         // }
2354         // ```
2355         //
2356         // Note that the final parameter to `Bar` is `'_`, not `'2` --
2357         // this is because the elided lifetimes from the return type
2358         // should be figured out using the ordinary elision rules, and
2359         // this desugaring achieves that.
2360         //
2361         // The variable `input_lifetimes_count` tracks the number of
2362         // lifetime parameters to the opaque type *not counting* those
2363         // lifetimes elided in the return type. This includes those
2364         // that are explicitly declared (`in_scope_lifetimes`) and
2365         // those elided lifetimes we found in the arguments (current
2366         // content of `lifetimes_to_define`). Next, we will process
2367         // the return type, which will cause `lifetimes_to_define` to
2368         // grow.
2369         let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
2370
2371         let (opaque_ty_id, lifetime_params) = self.with_hir_id_owner(opaque_ty_node_id, |this| {
2372             // We have to be careful to get elision right here. The
2373             // idea is that we create a lifetime parameter for each
2374             // lifetime in the return type.  So, given a return type
2375             // like `async fn foo(..) -> &[&u32]`, we lower to `impl
2376             // Future<Output = &'1 [ &'2 u32 ]>`.
2377             //
2378             // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
2379             // hence the elision takes place at the fn site.
2380             let future_bound = this.with_anonymous_lifetime_mode(
2381                 AnonymousLifetimeMode::CreateParameter,
2382                 |this| this.lower_async_fn_output_type_to_future_bound(
2383                     output,
2384                     fn_def_id,
2385                     span,
2386                 ),
2387             );
2388
2389             debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
2390
2391             // Calculate all the lifetimes that should be captured
2392             // by the opaque type. This should include all in-scope
2393             // lifetime parameters, including those defined in-band.
2394             //
2395             // Note: this must be done after lowering the output type,
2396             // as the output type may introduce new in-band lifetimes.
2397             let lifetime_params: Vec<(Span, ParamName)> =
2398                 this.in_scope_lifetimes
2399                     .iter().cloned()
2400                     .map(|name| (name.ident().span, name))
2401                     .chain(this.lifetimes_to_define.iter().cloned())
2402                     .collect();
2403
2404             debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
2405             debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
2406             debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
2407
2408             let generic_params =
2409                 lifetime_params
2410                     .iter().cloned()
2411                     .map(|(span, hir_name)| {
2412                         this.lifetime_to_generic_param(span, hir_name, opaque_ty_def_index)
2413                     })
2414                     .collect();
2415
2416             let opaque_ty_item = hir::OpaqueTy {
2417                 generics: hir::Generics {
2418                     params: generic_params,
2419                     where_clause: hir::WhereClause {
2420                         predicates: hir_vec![],
2421                         span,
2422                     },
2423                     span,
2424                 },
2425                 bounds: hir_vec![future_bound],
2426                 impl_trait_fn: Some(fn_def_id),
2427                 origin: hir::OpaqueTyOrigin::AsyncFn,
2428             };
2429
2430             trace!("exist ty from async fn def index: {:#?}", opaque_ty_def_index);
2431             let opaque_ty_id = this.generate_opaque_type(
2432                 opaque_ty_node_id,
2433                 opaque_ty_item,
2434                 span,
2435                 opaque_ty_span,
2436             );
2437
2438             (opaque_ty_id, lifetime_params)
2439         });
2440
2441         // As documented above on the variable
2442         // `input_lifetimes_count`, we need to create the lifetime
2443         // arguments to our opaque type. Continuing with our example,
2444         // we're creating the type arguments for the return type:
2445         //
2446         // ```
2447         // Bar<'a, 'b, '0, '1, '_>
2448         // ```
2449         //
2450         // For the "input" lifetime parameters, we wish to create
2451         // references to the parameters themselves, including the
2452         // "implicit" ones created from parameter types (`'a`, `'b`,
2453         // '`0`, `'1`).
2454         //
2455         // For the "output" lifetime parameters, we just want to
2456         // generate `'_`.
2457         let mut generic_args: Vec<_> =
2458             lifetime_params[..input_lifetimes_count]
2459             .iter()
2460             .map(|&(span, hir_name)| {
2461                 // Input lifetime like `'a` or `'1`:
2462                 GenericArg::Lifetime(hir::Lifetime {
2463                     hir_id: self.next_id(),
2464                     span,
2465                     name: hir::LifetimeName::Param(hir_name),
2466                 })
2467             })
2468             .collect();
2469         generic_args.extend(
2470             lifetime_params[input_lifetimes_count..]
2471             .iter()
2472             .map(|&(span, _)| {
2473                 // Output lifetime like `'_`.
2474                 GenericArg::Lifetime(hir::Lifetime {
2475                     hir_id: self.next_id(),
2476                     span,
2477                     name: hir::LifetimeName::Implicit,
2478                 })
2479             })
2480         );
2481
2482         // Create the `Foo<...>` reference itself. Note that the `type
2483         // Foo = impl Trait` is, internally, created as a child of the
2484         // async fn, so the *type parameters* are inherited.  It's
2485         // only the lifetime parameters that we must supply.
2486         let opaque_ty_ref = hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, generic_args.into());
2487         let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2488         hir::FunctionRetTy::Return(P(opaque_ty))
2489     }
2490
2491     /// Transforms `-> T` into `Future<Output = T>`
2492     fn lower_async_fn_output_type_to_future_bound(
2493         &mut self,
2494         output: &FunctionRetTy,
2495         fn_def_id: DefId,
2496         span: Span,
2497     ) -> hir::GenericBound {
2498         // Compute the `T` in `Future<Output = T>` from the return type.
2499         let output_ty = match output {
2500             FunctionRetTy::Ty(ty) => self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(fn_def_id))),
2501             FunctionRetTy::Default(ret_ty_span) => P(self.ty_tup(*ret_ty_span, hir_vec![])),
2502         };
2503
2504         // "<Output = T>"
2505         let future_params = P(hir::GenericArgs {
2506             args: hir_vec![],
2507             bindings: hir_vec![hir::TypeBinding {
2508                 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2509                 kind: hir::TypeBindingKind::Equality {
2510                     ty: output_ty,
2511                 },
2512                 hir_id: self.next_id(),
2513                 span,
2514             }],
2515             parenthesized: false,
2516         });
2517
2518         // ::std::future::Future<future_params>
2519         let future_path =
2520             P(self.std_path(span, &[sym::future, sym::Future], Some(future_params), false));
2521
2522         hir::GenericBound::Trait(
2523             hir::PolyTraitRef {
2524                 trait_ref: hir::TraitRef {
2525                     path: future_path,
2526                     hir_ref_id: self.next_id(),
2527                 },
2528                 bound_generic_params: hir_vec![],
2529                 span,
2530             },
2531             hir::TraitBoundModifier::None,
2532         )
2533     }
2534
2535     fn lower_param_bound(
2536         &mut self,
2537         tpb: &GenericBound,
2538         itctx: ImplTraitContext<'_>,
2539     ) -> hir::GenericBound {
2540         match *tpb {
2541             GenericBound::Trait(ref ty, modifier) => {
2542                 hir::GenericBound::Trait(
2543                     self.lower_poly_trait_ref(ty, itctx),
2544                     self.lower_trait_bound_modifier(modifier),
2545                 )
2546             }
2547             GenericBound::Outlives(ref lifetime) => {
2548                 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2549             }
2550         }
2551     }
2552
2553     fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2554         let span = l.ident.span;
2555         match l.ident {
2556             ident if ident.name == kw::StaticLifetime =>
2557                 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2558             ident if ident.name == kw::UnderscoreLifetime =>
2559                 match self.anonymous_lifetime_mode {
2560                     AnonymousLifetimeMode::CreateParameter => {
2561                         let fresh_name = self.collect_fresh_in_band_lifetime(span);
2562                         self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2563                     }
2564
2565                     AnonymousLifetimeMode::PassThrough => {
2566                         self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2567                     }
2568
2569                     AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2570                 },
2571             ident => {
2572                 self.maybe_collect_in_band_lifetime(ident);
2573                 let param_name = ParamName::Plain(ident);
2574                 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2575             }
2576         }
2577     }
2578
2579     fn new_named_lifetime(
2580         &mut self,
2581         id: NodeId,
2582         span: Span,
2583         name: hir::LifetimeName,
2584     ) -> hir::Lifetime {
2585         hir::Lifetime {
2586             hir_id: self.lower_node_id(id),
2587             span,
2588             name,
2589         }
2590     }
2591
2592     fn lower_generic_params(
2593         &mut self,
2594         params: &[GenericParam],
2595         add_bounds: &NodeMap<Vec<GenericBound>>,
2596         mut itctx: ImplTraitContext<'_>,
2597     ) -> hir::HirVec<hir::GenericParam> {
2598         params.iter().map(|param| {
2599             self.lower_generic_param(param, add_bounds, itctx.reborrow())
2600         }).collect()
2601     }
2602
2603     fn lower_generic_param(&mut self,
2604                            param: &GenericParam,
2605                            add_bounds: &NodeMap<Vec<GenericBound>>,
2606                            mut itctx: ImplTraitContext<'_>)
2607                            -> hir::GenericParam {
2608         let mut bounds = self.with_anonymous_lifetime_mode(
2609             AnonymousLifetimeMode::ReportError,
2610             |this| this.lower_param_bounds(&param.bounds, itctx.reborrow()),
2611         );
2612
2613         let (name, kind) = match param.kind {
2614             GenericParamKind::Lifetime => {
2615                 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2616                 self.is_collecting_in_band_lifetimes = false;
2617
2618                 let lt = self.with_anonymous_lifetime_mode(
2619                     AnonymousLifetimeMode::ReportError,
2620                     |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2621                 );
2622                 let param_name = match lt.name {
2623                     hir::LifetimeName::Param(param_name) => param_name,
2624                     hir::LifetimeName::Implicit
2625                         | hir::LifetimeName::Underscore
2626                         | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2627                     hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2628                         span_bug!(
2629                             param.ident.span,
2630                             "object-lifetime-default should not occur here",
2631                         );
2632                     }
2633                     hir::LifetimeName::Error => ParamName::Error,
2634                 };
2635
2636                 let kind = hir::GenericParamKind::Lifetime {
2637                     kind: hir::LifetimeParamKind::Explicit
2638                 };
2639
2640                 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2641
2642                 (param_name, kind)
2643             }
2644             GenericParamKind::Type { ref default, .. } => {
2645                 let add_bounds = add_bounds.get(&param.id).map_or(&[][..], |x| &x);
2646                 if !add_bounds.is_empty() {
2647                     let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2648                     bounds = bounds.into_iter()
2649                                    .chain(params)
2650                                    .collect();
2651                 }
2652
2653                 let kind = hir::GenericParamKind::Type {
2654                     default: default.as_ref().map(|x| {
2655                         self.lower_ty(x, ImplTraitContext::OpaqueTy(None))
2656                     }),
2657                     synthetic: param.attrs.iter()
2658                                           .filter(|attr| attr.check_name(sym::rustc_synthetic))
2659                                           .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2660                                           .next(),
2661                 };
2662
2663                 (hir::ParamName::Plain(param.ident), kind)
2664             }
2665             GenericParamKind::Const { ref ty } => {
2666                 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2667                     ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2668                 })
2669             }
2670         };
2671
2672         hir::GenericParam {
2673             hir_id: self.lower_node_id(param.id),
2674             name,
2675             span: param.ident.span,
2676             pure_wrt_drop: attr::contains_name(&param.attrs, sym::may_dangle),
2677             attrs: self.lower_attrs(&param.attrs),
2678             bounds,
2679             kind,
2680         }
2681     }
2682
2683     fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2684         let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2685             hir::QPath::Resolved(None, path) => path,
2686             qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2687         };
2688         hir::TraitRef {
2689             path,
2690             hir_ref_id: self.lower_node_id(p.ref_id),
2691         }
2692     }
2693
2694     fn lower_poly_trait_ref(
2695         &mut self,
2696         p: &PolyTraitRef,
2697         mut itctx: ImplTraitContext<'_>,
2698     ) -> hir::PolyTraitRef {
2699         let bound_generic_params = self.lower_generic_params(
2700             &p.bound_generic_params,
2701             &NodeMap::default(),
2702             itctx.reborrow(),
2703         );
2704         let trait_ref = self.with_in_scope_lifetime_defs(
2705             &p.bound_generic_params,
2706             |this| this.lower_trait_ref(&p.trait_ref, itctx),
2707         );
2708
2709         hir::PolyTraitRef {
2710             bound_generic_params,
2711             trait_ref,
2712             span: p.span,
2713         }
2714     }
2715
2716     fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2717         hir::MutTy {
2718             ty: self.lower_ty(&mt.ty, itctx),
2719             mutbl: mt.mutbl,
2720         }
2721     }
2722
2723     fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2724                           -> hir::GenericBounds {
2725         bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2726     }
2727
2728     fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2729         let mut stmts = vec![];
2730         let mut expr = None;
2731
2732         for (index, stmt) in b.stmts.iter().enumerate() {
2733             if index == b.stmts.len() - 1 {
2734                 if let StmtKind::Expr(ref e) = stmt.kind {
2735                     expr = Some(P(self.lower_expr(e)));
2736                 } else {
2737                     stmts.extend(self.lower_stmt(stmt));
2738                 }
2739             } else {
2740                 stmts.extend(self.lower_stmt(stmt));
2741             }
2742         }
2743
2744         P(hir::Block {
2745             hir_id: self.lower_node_id(b.id),
2746             stmts: stmts.into(),
2747             expr,
2748             rules: self.lower_block_check_mode(&b.rules),
2749             span: b.span,
2750             targeted_by_break,
2751         })
2752     }
2753
2754     /// Lowers a block directly to an expression, presuming that it
2755     /// has no attributes and is not targeted by a `break`.
2756     fn lower_block_expr(&mut self, b: &Block) -> hir::Expr {
2757         let block = self.lower_block(b, false);
2758         self.expr_block(block, AttrVec::new())
2759     }
2760
2761     fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2762         let node = match p.kind {
2763             PatKind::Wild => hir::PatKind::Wild,
2764             PatKind::Ident(ref binding_mode, ident, ref sub) => {
2765                 let lower_sub = |this: &mut Self| sub.as_ref().map(|s| this.lower_pat(&*s));
2766                 let node = self.lower_pat_ident(p, binding_mode, ident, lower_sub);
2767                 node
2768             }
2769             PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
2770             PatKind::TupleStruct(ref path, ref pats) => {
2771                 let qpath = self.lower_qpath(
2772                     p.id,
2773                     &None,
2774                     path,
2775                     ParamMode::Optional,
2776                     ImplTraitContext::disallowed(),
2777                 );
2778                 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple struct");
2779                 hir::PatKind::TupleStruct(qpath, pats, ddpos)
2780             }
2781             PatKind::Or(ref pats) => {
2782                 hir::PatKind::Or(pats.iter().map(|x| self.lower_pat(x)).collect())
2783             }
2784             PatKind::Path(ref qself, ref path) => {
2785                 let qpath = self.lower_qpath(
2786                     p.id,
2787                     qself,
2788                     path,
2789                     ParamMode::Optional,
2790                     ImplTraitContext::disallowed(),
2791                 );
2792                 hir::PatKind::Path(qpath)
2793             }
2794             PatKind::Struct(ref path, ref fields, etc) => {
2795                 let qpath = self.lower_qpath(
2796                     p.id,
2797                     &None,
2798                     path,
2799                     ParamMode::Optional,
2800                     ImplTraitContext::disallowed(),
2801                 );
2802
2803                 let fs = fields
2804                     .iter()
2805                     .map(|f| hir::FieldPat {
2806                         hir_id: self.next_id(),
2807                         ident: f.ident,
2808                         pat: self.lower_pat(&f.pat),
2809                         is_shorthand: f.is_shorthand,
2810                         span: f.span,
2811                     })
2812                     .collect();
2813                 hir::PatKind::Struct(qpath, fs, etc)
2814             }
2815             PatKind::Tuple(ref pats) => {
2816                 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple");
2817                 hir::PatKind::Tuple(pats, ddpos)
2818             }
2819             PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
2820             PatKind::Ref(ref inner, mutbl) => {
2821                 hir::PatKind::Ref(self.lower_pat(inner), mutbl)
2822             }
2823             PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
2824                 P(self.lower_expr(e1)),
2825                 P(self.lower_expr(e2)),
2826                 self.lower_range_end(end),
2827             ),
2828             PatKind::Slice(ref pats) => self.lower_pat_slice(pats),
2829             PatKind::Rest => {
2830                 // If we reach here the `..` pattern is not semantically allowed.
2831                 self.ban_illegal_rest_pat(p.span)
2832             }
2833             PatKind::Paren(ref inner) => return self.lower_pat(inner),
2834             PatKind::Mac(_) => panic!("Shouldn't exist here"),
2835         };
2836
2837         self.pat_with_node_id_of(p, node)
2838     }
2839
2840     fn lower_pat_tuple(
2841         &mut self,
2842         pats: &[AstP<Pat>],
2843         ctx: &str,
2844     ) -> (HirVec<P<hir::Pat>>, Option<usize>) {
2845         let mut elems = Vec::with_capacity(pats.len());
2846         let mut rest = None;
2847
2848         let mut iter = pats.iter().enumerate();
2849         for (idx, pat) in iter.by_ref() {
2850             // Interpret the first `..` pattern as a sub-tuple pattern.
2851             // Note that unlike for slice patterns,
2852             // where `xs @ ..` is a legal sub-slice pattern,
2853             // it is not a legal sub-tuple pattern.
2854             if pat.is_rest() {
2855                 rest = Some((idx, pat.span));
2856                 break;
2857             }
2858             // It was not a sub-tuple pattern so lower it normally.
2859             elems.push(self.lower_pat(pat));
2860         }
2861
2862         for (_, pat) in iter {
2863             // There was a previous sub-tuple pattern; make sure we don't allow more...
2864             if pat.is_rest() {
2865                 // ...but there was one again, so error.
2866                 self.ban_extra_rest_pat(pat.span, rest.unwrap().1, ctx);
2867             } else {
2868                 elems.push(self.lower_pat(pat));
2869             }
2870         }
2871
2872         (elems.into(), rest.map(|(ddpos, _)| ddpos))
2873     }
2874
2875     /// Lower a slice pattern of form `[pat_0, ..., pat_n]` into
2876     /// `hir::PatKind::Slice(before, slice, after)`.
2877     ///
2878     /// When encountering `($binding_mode $ident @)? ..` (`slice`),
2879     /// this is interpreted as a sub-slice pattern semantically.
2880     /// Patterns that follow, which are not like `slice` -- or an error occurs, are in `after`.
2881     fn lower_pat_slice(&mut self, pats: &[AstP<Pat>]) -> hir::PatKind {
2882         let mut before = Vec::new();
2883         let mut after = Vec::new();
2884         let mut slice = None;
2885         let mut prev_rest_span = None;
2886
2887         let mut iter = pats.iter();
2888         // Lower all the patterns until the first occurence of a sub-slice pattern.
2889         for pat in iter.by_ref() {
2890             match pat.kind {
2891                 // Found a sub-slice pattern `..`. Record, lower it to `_`, and stop here.
2892                 PatKind::Rest => {
2893                     prev_rest_span = Some(pat.span);
2894                     slice = Some(self.pat_wild_with_node_id_of(pat));
2895                     break;
2896                 },
2897                 // Found a sub-slice pattern `$binding_mode $ident @ ..`.
2898                 // Record, lower it to `$binding_mode $ident @ _`, and stop here.
2899                 PatKind::Ident(ref bm, ident, Some(ref sub)) if sub.is_rest() => {
2900                     prev_rest_span = Some(sub.span);
2901                     let lower_sub = |this: &mut Self| Some(this.pat_wild_with_node_id_of(sub));
2902                     let node = self.lower_pat_ident(pat, bm, ident, lower_sub);
2903                     slice = Some(self.pat_with_node_id_of(pat, node));
2904                     break;
2905                 },
2906                 // It was not a subslice pattern so lower it normally.
2907                 _ => before.push(self.lower_pat(pat)),
2908             }
2909         }
2910
2911         // Lower all the patterns after the first sub-slice pattern.
2912         for pat in iter {
2913             // There was a previous subslice pattern; make sure we don't allow more.
2914             let rest_span = match pat.kind {
2915                 PatKind::Rest => Some(pat.span),
2916                 PatKind::Ident(.., Some(ref sub)) if sub.is_rest() => {
2917                     // The `HirValidator` is merciless; add a `_` pattern to avoid ICEs.
2918                     after.push(self.pat_wild_with_node_id_of(pat));
2919                     Some(sub.span)
2920                 },
2921                 _ => None,
2922             };
2923             if let Some(rest_span) = rest_span {
2924                 // We have e.g., `[a, .., b, ..]`. That's no good, error!
2925                 self.ban_extra_rest_pat(rest_span, prev_rest_span.unwrap(), "slice");
2926             } else {
2927                 // Lower the pattern normally.
2928                 after.push(self.lower_pat(pat));
2929             }
2930         }
2931
2932         hir::PatKind::Slice(before.into(), slice, after.into())
2933     }
2934
2935     fn lower_pat_ident(
2936         &mut self,
2937         p: &Pat,
2938         binding_mode: &BindingMode,
2939         ident: Ident,
2940         lower_sub: impl FnOnce(&mut Self) -> Option<P<hir::Pat>>,
2941     ) -> hir::PatKind {
2942         match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
2943             // `None` can occur in body-less function signatures
2944             res @ None | res @ Some(Res::Local(_)) => {
2945                 let canonical_id = match res {
2946                     Some(Res::Local(id)) => id,
2947                     _ => p.id,
2948                 };
2949
2950                 hir::PatKind::Binding(
2951                     self.lower_binding_mode(binding_mode),
2952                     self.lower_node_id(canonical_id),
2953                     ident,
2954                     lower_sub(self),
2955                 )
2956             }
2957             Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
2958                 None,
2959                 P(hir::Path {
2960                     span: ident.span,
2961                     res: self.lower_res(res),
2962                     segments: hir_vec![hir::PathSegment::from_ident(ident)],
2963                 }),
2964             )),
2965         }
2966     }
2967
2968     fn pat_wild_with_node_id_of(&mut self, p: &Pat) -> P<hir::Pat> {
2969         self.pat_with_node_id_of(p, hir::PatKind::Wild)
2970     }
2971
2972     /// Construct a `Pat` with the `HirId` of `p.id` lowered.
2973     fn pat_with_node_id_of(&mut self, p: &Pat, kind: hir::PatKind) -> P<hir::Pat> {
2974         P(hir::Pat {
2975             hir_id: self.lower_node_id(p.id),
2976             kind,
2977             span: p.span,
2978         })
2979     }
2980
2981     /// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern.
2982     fn ban_extra_rest_pat(&self, sp: Span, prev_sp: Span, ctx: &str) {
2983         self.diagnostic()
2984             .struct_span_err(sp, &format!("`..` can only be used once per {} pattern", ctx))
2985             .span_label(sp, &format!("can only be used once per {} pattern", ctx))
2986             .span_label(prev_sp, "previously used here")
2987             .emit();
2988     }
2989
2990     /// Used to ban the `..` pattern in places it shouldn't be semantically.
2991     fn ban_illegal_rest_pat(&self, sp: Span) -> hir::PatKind {
2992         self.diagnostic()
2993             .struct_span_err(sp, "`..` patterns are not allowed here")
2994             .note("only allowed in tuple, tuple struct, and slice patterns")
2995             .emit();
2996
2997         // We're not in a list context so `..` can be reasonably treated
2998         // as `_` because it should always be valid and roughly matches the
2999         // intent of `..` (notice that the rest of a single slot is that slot).
3000         hir::PatKind::Wild
3001     }
3002
3003     fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3004         match *e {
3005             RangeEnd::Included(_) => hir::RangeEnd::Included,
3006             RangeEnd::Excluded => hir::RangeEnd::Excluded,
3007         }
3008     }
3009
3010     fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3011         self.with_new_scopes(|this| {
3012             hir::AnonConst {
3013                 hir_id: this.lower_node_id(c.id),
3014                 body: this.lower_const_body(c.value.span, Some(&c.value)),
3015             }
3016         })
3017     }
3018
3019     fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
3020         let kind = match s.kind {
3021             StmtKind::Local(ref l) => {
3022                 let (l, item_ids) = self.lower_local(l);
3023                 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
3024                     .into_iter()
3025                     .map(|item_id| {
3026                         let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
3027                         self.stmt(s.span, hir::StmtKind::Item(item_id))
3028                     })
3029                     .collect();
3030                 ids.push({
3031                     hir::Stmt {
3032                         hir_id: self.lower_node_id(s.id),
3033                         kind: hir::StmtKind::Local(P(l)),
3034                         span: s.span,
3035                     }
3036                 });
3037                 return ids;
3038             },
3039             StmtKind::Item(ref it) => {
3040                 // Can only use the ID once.
3041                 let mut id = Some(s.id);
3042                 return self.lower_item_id(it)
3043                     .into_iter()
3044                     .map(|item_id| {
3045                         let hir_id = id.take()
3046                           .map(|id| self.lower_node_id(id))
3047                           .unwrap_or_else(|| self.next_id());
3048
3049                         hir::Stmt {
3050                             hir_id,
3051                             kind: hir::StmtKind::Item(item_id),
3052                             span: s.span,
3053                         }
3054                     })
3055                     .collect();
3056             }
3057             StmtKind::Expr(ref e) => hir::StmtKind::Expr(P(self.lower_expr(e))),
3058             StmtKind::Semi(ref e) => hir::StmtKind::Semi(P(self.lower_expr(e))),
3059             StmtKind::Mac(..) => panic!("shouldn't exist here"),
3060         };
3061         smallvec![hir::Stmt {
3062             hir_id: self.lower_node_id(s.id),
3063             kind,
3064             span: s.span,
3065         }]
3066     }
3067
3068     fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3069         match *b {
3070             BlockCheckMode::Default => hir::DefaultBlock,
3071             BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3072         }
3073     }
3074
3075     fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3076         match *b {
3077             BindingMode::ByValue(Mutability::Not) => hir::BindingAnnotation::Unannotated,
3078             BindingMode::ByRef(Mutability::Not) => hir::BindingAnnotation::Ref,
3079             BindingMode::ByValue(Mutability::Mut) => hir::BindingAnnotation::Mutable,
3080             BindingMode::ByRef(Mutability::Mut) => hir::BindingAnnotation::RefMut,
3081         }
3082     }
3083
3084     fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3085         match u {
3086             CompilerGenerated => hir::CompilerGenerated,
3087             UserProvided => hir::UserProvided,
3088         }
3089     }
3090
3091     fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3092         match f {
3093             TraitBoundModifier::None => hir::TraitBoundModifier::None,
3094             TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3095         }
3096     }
3097
3098     // Helper methods for building HIR.
3099
3100     fn stmt(&mut self, span: Span, kind: hir::StmtKind) -> hir::Stmt {
3101         hir::Stmt { span, kind, hir_id: self.next_id() }
3102     }
3103
3104     fn stmt_expr(&mut self, span: Span, expr: hir::Expr) -> hir::Stmt {
3105         self.stmt(span, hir::StmtKind::Expr(P(expr)))
3106     }
3107
3108     fn stmt_let_pat(
3109         &mut self,
3110         attrs: AttrVec,
3111         span: Span,
3112         init: Option<P<hir::Expr>>,
3113         pat: P<hir::Pat>,
3114         source: hir::LocalSource,
3115     ) -> hir::Stmt {
3116         let local = hir::Local {
3117             attrs,
3118             hir_id: self.next_id(),
3119             init,
3120             pat,
3121             source,
3122             span,
3123             ty: None,
3124         };
3125         self.stmt(span, hir::StmtKind::Local(P(local)))
3126     }
3127
3128     fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
3129         self.block_all(expr.span, hir::HirVec::new(), Some(expr))
3130     }
3131
3132     fn block_all(
3133         &mut self,
3134         span: Span,
3135         stmts: hir::HirVec<hir::Stmt>,
3136         expr: Option<P<hir::Expr>>,
3137     ) -> hir::Block {
3138         hir::Block {
3139             stmts,
3140             expr,
3141             hir_id: self.next_id(),
3142             rules: hir::DefaultBlock,
3143             span,
3144             targeted_by_break: false,
3145         }
3146     }
3147
3148     /// Constructs a `true` or `false` literal pattern.
3149     fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
3150         let expr = self.expr_bool(span, val);
3151         self.pat(span, hir::PatKind::Lit(P(expr)))
3152     }
3153
3154     fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3155         self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
3156     }
3157
3158     fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3159         self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
3160     }
3161
3162     fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3163         self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
3164     }
3165
3166     fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
3167         self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
3168     }
3169
3170     fn pat_std_enum(
3171         &mut self,
3172         span: Span,
3173         components: &[Symbol],
3174         subpats: hir::HirVec<P<hir::Pat>>,
3175     ) -> P<hir::Pat> {
3176         let path = self.std_path(span, components, None, true);
3177         let qpath = hir::QPath::Resolved(None, P(path));
3178         let pt = if subpats.is_empty() {
3179             hir::PatKind::Path(qpath)
3180         } else {
3181             hir::PatKind::TupleStruct(qpath, subpats, None)
3182         };
3183         self.pat(span, pt)
3184     }
3185
3186     fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
3187         self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
3188     }
3189
3190     fn pat_ident_binding_mode(
3191         &mut self,
3192         span: Span,
3193         ident: Ident,
3194         bm: hir::BindingAnnotation,
3195     ) -> (P<hir::Pat>, hir::HirId) {
3196         let hir_id = self.next_id();
3197
3198         (
3199             P(hir::Pat {
3200                 hir_id,
3201                 kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
3202                 span,
3203             }),
3204             hir_id
3205         )
3206     }
3207
3208     fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
3209         self.pat(span, hir::PatKind::Wild)
3210     }
3211
3212     fn pat(&mut self, span: Span, kind: hir::PatKind) -> P<hir::Pat> {
3213         P(hir::Pat {
3214             hir_id: self.next_id(),
3215             kind,
3216             span,
3217         })
3218     }
3219
3220     /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
3221     /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
3222     /// The path is also resolved according to `is_value`.
3223     fn std_path(
3224         &mut self,
3225         span: Span,
3226         components: &[Symbol],
3227         params: Option<P<hir::GenericArgs>>,
3228         is_value: bool,
3229     ) -> hir::Path {
3230         let ns = if is_value { Namespace::ValueNS } else { Namespace::TypeNS };
3231         let (path, res) = self.resolver.resolve_str_path(span, self.crate_root, components, ns);
3232
3233         let mut segments: Vec<_> = path.segments.iter().map(|segment| {
3234             let res = self.expect_full_res(segment.id);
3235             hir::PathSegment {
3236                 ident: segment.ident,
3237                 hir_id: Some(self.lower_node_id(segment.id)),
3238                 res: Some(self.lower_res(res)),
3239                 infer_args: true,
3240                 args: None,
3241             }
3242         }).collect();
3243         segments.last_mut().unwrap().args = params;
3244
3245         hir::Path {
3246             span,
3247             res: res.map_id(|_| panic!("unexpected `NodeId`")),
3248             segments: segments.into(),
3249         }
3250     }
3251
3252     fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
3253         let kind = match qpath {
3254             hir::QPath::Resolved(None, path) => {
3255                 // Turn trait object paths into `TyKind::TraitObject` instead.
3256                 match path.res {
3257                     Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
3258                         let principal = hir::PolyTraitRef {
3259                             bound_generic_params: hir::HirVec::new(),
3260                             trait_ref: hir::TraitRef {
3261                                 path,
3262                                 hir_ref_id: hir_id,
3263                             },
3264                             span,
3265                         };
3266
3267                         // The original ID is taken by the `PolyTraitRef`,
3268                         // so the `Ty` itself needs a different one.
3269                         hir_id = self.next_id();
3270                         hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
3271                     }
3272                     _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
3273                 }
3274             }
3275             _ => hir::TyKind::Path(qpath),
3276         };
3277
3278         hir::Ty {
3279             hir_id,
3280             kind,
3281             span,
3282         }
3283     }
3284
3285     /// Invoked to create the lifetime argument for a type `&T`
3286     /// with no explicit lifetime.
3287     fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
3288         match self.anonymous_lifetime_mode {
3289             // Intercept when we are in an impl header or async fn and introduce an in-band
3290             // lifetime.
3291             // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
3292             // `'f`.
3293             AnonymousLifetimeMode::CreateParameter => {
3294                 let fresh_name = self.collect_fresh_in_band_lifetime(span);
3295                 hir::Lifetime {
3296                     hir_id: self.next_id(),
3297                     span,
3298                     name: hir::LifetimeName::Param(fresh_name),
3299                 }
3300             }
3301
3302             AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
3303
3304             AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
3305         }
3306     }
3307
3308     /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
3309     /// return a "error lifetime".
3310     fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
3311         let (id, msg, label) = match id {
3312             Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
3313
3314             None => (
3315                 self.resolver.next_node_id(),
3316                 "`&` without an explicit lifetime name cannot be used here",
3317                 "explicit lifetime name needed here",
3318             ),
3319         };
3320
3321         let mut err = struct_span_err!(
3322             self.sess,
3323             span,
3324             E0637,
3325             "{}",
3326             msg,
3327         );
3328         err.span_label(span, label);
3329         err.emit();
3330
3331         self.new_named_lifetime(id, span, hir::LifetimeName::Error)
3332     }
3333
3334     /// Invoked to create the lifetime argument(s) for a path like
3335     /// `std::cell::Ref<T>`; note that implicit lifetimes in these
3336     /// sorts of cases are deprecated. This may therefore report a warning or an
3337     /// error, depending on the mode.
3338     fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
3339         (0..count)
3340             .map(|_| self.elided_path_lifetime(span))
3341             .collect()
3342     }
3343
3344     fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
3345         match self.anonymous_lifetime_mode {
3346             AnonymousLifetimeMode::CreateParameter => {
3347                 // We should have emitted E0726 when processing this path above
3348                 self.sess.delay_span_bug(
3349                     span,
3350                     "expected 'implicit elided lifetime not allowed' error",
3351                 );
3352                 let id = self.resolver.next_node_id();
3353                 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
3354             }
3355             // `PassThrough` is the normal case.
3356             // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
3357             // is unsuitable here, as these can occur from missing lifetime parameters in a
3358             // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
3359             // lifetime. Instead, we simply create an implicit lifetime, which will be checked
3360             // later, at which point a suitable error will be emitted.
3361           | AnonymousLifetimeMode::PassThrough
3362           | AnonymousLifetimeMode::ReportError => self.new_implicit_lifetime(span),
3363         }
3364     }
3365
3366     /// Invoked to create the lifetime argument(s) for an elided trait object
3367     /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
3368     /// when the bound is written, even if it is written with `'_` like in
3369     /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
3370     fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
3371         match self.anonymous_lifetime_mode {
3372             // NB. We intentionally ignore the create-parameter mode here.
3373             // and instead "pass through" to resolve-lifetimes, which will apply
3374             // the object-lifetime-defaulting rules. Elided object lifetime defaults
3375             // do not act like other elided lifetimes. In other words, given this:
3376             //
3377             //     impl Foo for Box<dyn Debug>
3378             //
3379             // we do not introduce a fresh `'_` to serve as the bound, but instead
3380             // ultimately translate to the equivalent of:
3381             //
3382             //     impl Foo for Box<dyn Debug + 'static>
3383             //
3384             // `resolve_lifetime` has the code to make that happen.
3385             AnonymousLifetimeMode::CreateParameter => {}
3386
3387             AnonymousLifetimeMode::ReportError => {
3388                 // ReportError applies to explicit use of `'_`.
3389             }
3390
3391             // This is the normal case.
3392             AnonymousLifetimeMode::PassThrough => {}
3393         }
3394
3395         let r = hir::Lifetime {
3396             hir_id: self.next_id(),
3397             span,
3398             name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
3399         };
3400         debug!("elided_dyn_bound: r={:?}", r);
3401         r
3402     }
3403
3404     fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
3405         hir::Lifetime {
3406             hir_id: self.next_id(),
3407             span,
3408             name: hir::LifetimeName::Implicit,
3409         }
3410     }
3411
3412     fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
3413         // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
3414         // call site which do not have a macro backtrace. See #61963.
3415         let is_macro_callsite = self.sess.source_map()
3416             .span_to_snippet(span)
3417             .map(|snippet| snippet.starts_with("#["))
3418             .unwrap_or(true);
3419         if !is_macro_callsite {
3420             self.resolver.lint_buffer().buffer_lint_with_diagnostic(
3421                 builtin::BARE_TRAIT_OBJECTS,
3422                 id,
3423                 span,
3424                 "trait objects without an explicit `dyn` are deprecated",
3425                 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
3426             )
3427         }
3428     }
3429 }
3430
3431 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
3432     // Sorting by span ensures that we get things in order within a
3433     // file, and also puts the files in a sensible order.
3434     let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
3435     body_ids.sort_by_key(|b| bodies[b].value.span);
3436     body_ids
3437 }
3438
3439 /// Checks if the specified expression is a built-in range literal.
3440 /// (See: `LoweringContext::lower_expr()`).
3441 pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
3442     use hir::{Path, QPath, ExprKind, TyKind};
3443
3444     // Returns whether the given path represents a (desugared) range,
3445     // either in std or core, i.e. has either a `::std::ops::Range` or
3446     // `::core::ops::Range` prefix.
3447     fn is_range_path(path: &Path) -> bool {
3448         let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
3449         let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
3450
3451         // "{{root}}" is the equivalent of `::` prefix in `Path`.
3452         if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
3453             (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
3454         } else {
3455             false
3456         }
3457     };
3458
3459     // Check whether a span corresponding to a range expression is a
3460     // range literal, rather than an explicit struct or `new()` call.
3461     fn is_lit(sess: &Session, span: &Span) -> bool {
3462         let source_map = sess.source_map();
3463         let end_point = source_map.end_point(*span);
3464
3465         if let Ok(end_string) = source_map.span_to_snippet(end_point) {
3466             !(end_string.ends_with("}") || end_string.ends_with(")"))
3467         } else {
3468             false
3469         }
3470     };
3471
3472     match expr.kind {
3473         // All built-in range literals but `..=` and `..` desugar to `Struct`s.
3474         ExprKind::Struct(ref qpath, _, _) => {
3475             if let QPath::Resolved(None, ref path) = **qpath {
3476                 return is_range_path(&path) && is_lit(sess, &expr.span);
3477             }
3478         }
3479
3480         // `..` desugars to its struct path.
3481         ExprKind::Path(QPath::Resolved(None, ref path)) => {
3482             return is_range_path(&path) && is_lit(sess, &expr.span);
3483         }
3484
3485         // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
3486         ExprKind::Call(ref func, _) => {
3487             if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
3488                 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
3489                     let new_call = segment.ident.name == sym::new;
3490                     return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;
3491                 }
3492             }
3493         }
3494
3495         _ => {}
3496     }
3497
3498     false
3499 }