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