]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/lowering.rs
Auto merge of #54778 - scottmcm:stabilize-ihle, r=pnkfelix
[rust.git] / src / librustc / hir / lowering.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Lowers the AST to the HIR.
12 //!
13 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
14 //! much like a fold. Where lowering involves a bit more work things get more
15 //! interesting and there are some invariants you should know about. These mostly
16 //! concern spans and ids.
17 //!
18 //! Spans are assigned to AST nodes during parsing and then are modified during
19 //! expansion to indicate the origin of a node and the process it went through
20 //! being expanded. Ids are assigned to AST nodes just before lowering.
21 //!
22 //! For the simpler lowering steps, ids and spans should be preserved. Unlike
23 //! expansion we do not preserve the process of lowering in the spans, so spans
24 //! should not be modified here. When creating a new node (as opposed to
25 //! 'folding' an existing one), then you create a new id using `next_id()`.
26 //!
27 //! You must ensure that ids are unique. That means that you should only use the
28 //! id from an AST node in a single HIR node (you can assume that AST node ids
29 //! are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
30 //! If you do, you must then set the new node's id to a fresh one.
31 //!
32 //! Spans are used for error messages and for tools to map semantics back to
33 //! source code. It is therefore not as important with spans as ids to be strict
34 //! about use (you can't break the compiler by screwing up a span). Obviously, a
35 //! HIR node can only have a single span. But multiple nodes can have the same
36 //! span and spans don't need to be kept in order, etc. Where code is preserved
37 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
38 //! new it is probably best to give a span for the whole AST node being lowered.
39 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
40 //! get confused if the spans from leaf AST nodes occur in multiple places
41 //! in the HIR, especially for multiple identifiers.
42
43 use dep_graph::DepGraph;
44 use hir::{self, ParamName};
45 use hir::HirVec;
46 use hir::map::{DefKey, DefPathData, Definitions};
47 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
48 use hir::def::{Def, PathResolution, PerNS};
49 use hir::GenericArg;
50 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
51                     ELIDED_LIFETIMES_IN_PATHS};
52 use middle::cstore::CrateStore;
53 use rustc_data_structures::fx::FxHashSet;
54 use rustc_data_structures::indexed_vec::IndexVec;
55 use rustc_data_structures::thin_vec::ThinVec;
56 use session::Session;
57 use session::config::nightly_options;
58 use util::common::FN_OUTPUT_NAME;
59 use util::nodemap::{DefIdMap, NodeMap};
60
61 use std::collections::BTreeMap;
62 use std::fmt::Debug;
63 use std::mem;
64 use smallvec::SmallVec;
65 use syntax::attr;
66 use syntax::ast;
67 use syntax::ast::*;
68 use syntax::errors;
69 use syntax::ext::hygiene::{Mark, SyntaxContext};
70 use syntax::feature_gate::{emit_feature_err, GateIssue};
71 use syntax::print::pprust;
72 use syntax::ptr::P;
73 use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
74 use syntax::std_inject;
75 use syntax::symbol::{keywords, Symbol};
76 use syntax::tokenstream::{Delimited, TokenStream, TokenTree};
77 use syntax::parse::token::Token;
78 use syntax::visit::{self, Visitor};
79 use syntax_pos::{Span, MultiSpan};
80
81 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
82
83 pub struct LoweringContext<'a> {
84     crate_root: Option<&'static str>,
85
86     // Use to assign ids to hir nodes that do not directly correspond to an ast node
87     sess: &'a Session,
88
89     cstore: &'a dyn CrateStore,
90
91     resolver: &'a mut dyn Resolver,
92
93     /// The items being lowered are collected here.
94     items: BTreeMap<NodeId, hir::Item>,
95
96     trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
97     impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
98     bodies: BTreeMap<hir::BodyId, hir::Body>,
99     exported_macros: Vec<hir::MacroDef>,
100
101     trait_impls: BTreeMap<DefId, Vec<NodeId>>,
102     trait_auto_impl: BTreeMap<DefId, NodeId>,
103
104     is_generator: bool,
105
106     catch_scopes: Vec<NodeId>,
107     loop_scopes: Vec<NodeId>,
108     is_in_loop_condition: bool,
109     is_in_trait_impl: bool,
110
111     /// What to do when we encounter either an "anonymous lifetime
112     /// reference". The term "anonymous" is meant to encompass both
113     /// `'_` lifetimes as well as fully elided cases where nothing is
114     /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
115     anonymous_lifetime_mode: AnonymousLifetimeMode,
116
117     // Used to create lifetime definitions from in-band lifetime usages.
118     // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
119     // When a named lifetime is encountered in a function or impl header and
120     // has not been defined
121     // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
122     // to this list. The results of this list are then added to the list of
123     // lifetime definitions in the corresponding impl or function generics.
124     lifetimes_to_define: Vec<(Span, ParamName)>,
125
126     // Whether or not in-band lifetimes are being collected. This is used to
127     // indicate whether or not we're in a place where new lifetimes will result
128     // in in-band lifetime definitions, such a function or an impl header,
129     // including implicit lifetimes from `impl_header_lifetime_elision`.
130     is_collecting_in_band_lifetimes: bool,
131
132     // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
133     // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
134     // against this list to see if it is already in-scope, or if a definition
135     // needs to be created for it.
136     in_scope_lifetimes: Vec<Ident>,
137
138     type_def_lifetime_params: DefIdMap<usize>,
139
140     current_hir_id_owner: Vec<(DefIndex, u32)>,
141     item_local_id_counters: NodeMap<u32>,
142     node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
143 }
144
145 pub trait Resolver {
146     /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
147     fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
148
149     /// Obtain the resolution for a node id
150     fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
151
152     /// Obtain the possible resolutions for the given `use` statement.
153     fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>>;
154
155     /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
156     /// This should only return `None` during testing.
157     fn definitions(&mut self) -> &mut Definitions;
158
159     /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
160     /// it based on `is_value`.
161     fn resolve_str_path(
162         &mut self,
163         span: Span,
164         crate_root: Option<&str>,
165         components: &[&str],
166         params: Option<P<hir::GenericArgs>>,
167         is_value: bool,
168     ) -> hir::Path;
169 }
170
171 #[derive(Debug)]
172 enum ImplTraitContext<'a> {
173     /// Treat `impl Trait` as shorthand for a new universal generic parameter.
174     /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
175     /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
176     ///
177     /// Newly generated parameters should be inserted into the given `Vec`.
178     Universal(&'a mut Vec<hir::GenericParam>),
179
180     /// Treat `impl Trait` as shorthand for a new existential parameter.
181     /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
182     /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
183     ///
184     /// We optionally store a `DefId` for the parent item here so we can look up necessary
185     /// information later. It is `None` when no information about the context should be stored,
186     /// e.g. for consts and statics.
187     Existential(Option<DefId>),
188
189     /// `impl Trait` is not accepted in this position.
190     Disallowed(ImplTraitPosition),
191 }
192
193 /// Position in which `impl Trait` is disallowed. Used for error reporting.
194 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
195 enum ImplTraitPosition {
196     Binding,
197     Other,
198 }
199
200 impl<'a> ImplTraitContext<'a> {
201     #[inline]
202     fn disallowed() -> Self {
203         ImplTraitContext::Disallowed(ImplTraitPosition::Other)
204     }
205
206     fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
207         use self::ImplTraitContext::*;
208         match self {
209             Universal(params) => Universal(params),
210             Existential(did) => Existential(*did),
211             Disallowed(pos) => Disallowed(*pos),
212         }
213     }
214 }
215
216 pub fn lower_crate(
217     sess: &Session,
218     cstore: &dyn CrateStore,
219     dep_graph: &DepGraph,
220     krate: &Crate,
221     resolver: &mut dyn Resolver,
222 ) -> hir::Crate {
223     // We're constructing the HIR here; we don't care what we will
224     // read, since we haven't even constructed the *input* to
225     // incr. comp. yet.
226     dep_graph.assert_ignored();
227
228     LoweringContext {
229         crate_root: std_inject::injected_crate_name(),
230         sess,
231         cstore,
232         resolver,
233         items: BTreeMap::new(),
234         trait_items: BTreeMap::new(),
235         impl_items: BTreeMap::new(),
236         bodies: BTreeMap::new(),
237         trait_impls: BTreeMap::new(),
238         trait_auto_impl: BTreeMap::new(),
239         exported_macros: Vec::new(),
240         catch_scopes: Vec::new(),
241         loop_scopes: Vec::new(),
242         is_in_loop_condition: false,
243         anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
244         type_def_lifetime_params: DefIdMap(),
245         current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
246         item_local_id_counters: NodeMap(),
247         node_id_to_hir_id: IndexVec::new(),
248         is_generator: false,
249         is_in_trait_impl: false,
250         lifetimes_to_define: Vec::new(),
251         is_collecting_in_band_lifetimes: false,
252         in_scope_lifetimes: Vec::new(),
253     }.lower_crate(krate)
254 }
255
256 #[derive(Copy, Clone, PartialEq)]
257 enum ParamMode {
258     /// Any path in a type context.
259     Explicit,
260     /// The `module::Type` in `module::Type::method` in an expression.
261     Optional,
262 }
263
264 #[derive(Debug)]
265 struct LoweredNodeId {
266     node_id: NodeId,
267     hir_id: hir::HirId,
268 }
269
270 enum ParenthesizedGenericArgs {
271     Ok,
272     Warn,
273     Err,
274 }
275
276 /// What to do when we encounter an **anonymous** lifetime
277 /// reference. Anonymous lifetime references come in two flavors.  You
278 /// have implicit, or fully elided, references to lifetimes, like the
279 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
280 /// or `Ref<'_, T>`.  These often behave the same, but not always:
281 ///
282 /// - certain usages of implicit references are deprecated, like
283 ///   `Ref<T>`, and we sometimes just give hard errors in those cases
284 ///   as well.
285 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
286 ///   the same as `Box<dyn Foo + '_>`.
287 ///
288 /// We describe the effects of the various modes in terms of three cases:
289 ///
290 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
291 ///   of a `&` (e.g., the missing lifetime in something like `&T`)
292 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
293 ///   there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
294 ///   elided bounds follow special rules. Note that this only covers
295 ///   cases where *nothing* is written; the `'_` in `Box<dyn Foo +
296 ///   '_>` is a case of "modern" elision.
297 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
298 ///   parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
299 ///   non-deprecated equivalent.
300 ///
301 /// Currently, the handling of lifetime elision is somewhat spread out
302 /// between HIR lowering and -- as described below -- the
303 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
304 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
305 /// everything into HIR lowering.
306 #[derive(Copy, Clone)]
307 enum AnonymousLifetimeMode {
308     /// For **Modern** cases, create a new anonymous region parameter
309     /// and reference that.
310     ///
311     /// For **Dyn Bound** cases, pass responsibility to
312     /// `resolve_lifetime` code.
313     ///
314     /// For **Deprecated** cases, report an error.
315     CreateParameter,
316
317     /// Give a hard error when either `&` or `'_` is written. Used to
318     /// rule out things like `where T: Foo<'_>`. Does not imply an
319     /// error on default object bounds (e.g., `Box<dyn Foo>`).
320     ReportError,
321
322     /// Pass responsibility to `resolve_lifetime` code for all cases.
323     PassThrough,
324 }
325
326 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[hir::ItemId; 1]> }
327
328 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
329     fn visit_ty(&mut self, ty: &'a Ty) {
330         match ty.node {
331             | TyKind::Typeof(_)
332             | TyKind::BareFn(_)
333             => return,
334
335             TyKind::ImplTrait(id, _) => self.ids.push(hir::ItemId { id }),
336             _ => {},
337         }
338         visit::walk_ty(self, ty);
339     }
340
341     fn visit_path_segment(
342         &mut self,
343         path_span: Span,
344         path_segment: &'v PathSegment,
345     ) {
346         if let Some(ref p) = path_segment.args {
347             if let GenericArgs::Parenthesized(_) = **p {
348                 return;
349             }
350         }
351         visit::walk_path_segment(self, path_span, path_segment)
352     }
353 }
354
355 impl<'a> LoweringContext<'a> {
356     fn lower_crate(mut self, c: &Crate) -> hir::Crate {
357         /// Full-crate AST visitor that inserts into a fresh
358         /// `LoweringContext` any information that may be
359         /// needed from arbitrary locations in the crate.
360         /// E.g. The number of lifetime generic parameters
361         /// declared for every type and trait definition.
362         struct MiscCollector<'lcx, 'interner: 'lcx> {
363             lctx: &'lcx mut LoweringContext<'interner>,
364         }
365
366         impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
367             fn visit_item(&mut self, item: &'lcx Item) {
368                 self.lctx.allocate_hir_id_counter(item.id, item);
369
370                 match item.node {
371                     ItemKind::Struct(_, ref generics)
372                     | ItemKind::Union(_, ref generics)
373                     | ItemKind::Enum(_, ref generics)
374                     | ItemKind::Ty(_, ref generics)
375                     | ItemKind::Existential(_, ref generics)
376                     | ItemKind::Trait(_, _, ref generics, ..) => {
377                         let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
378                         let count = generics
379                             .params
380                             .iter()
381                             .filter(|param| match param.kind {
382                                 ast::GenericParamKind::Lifetime { .. } => true,
383                                 _ => false,
384                             })
385                             .count();
386                         self.lctx.type_def_lifetime_params.insert(def_id, count);
387                     }
388                     _ => {}
389                 }
390                 visit::walk_item(self, item);
391             }
392
393             fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
394                 self.lctx.allocate_hir_id_counter(item.id, item);
395                 visit::walk_trait_item(self, item);
396             }
397
398             fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
399                 self.lctx.allocate_hir_id_counter(item.id, item);
400                 visit::walk_impl_item(self, item);
401             }
402         }
403
404         struct ItemLowerer<'lcx, 'interner: 'lcx> {
405             lctx: &'lcx mut LoweringContext<'interner>,
406         }
407
408         impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
409             fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
410             where
411                 F: FnOnce(&mut Self),
412             {
413                 let old = self.lctx.is_in_trait_impl;
414                 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
415                     false
416                 } else {
417                     true
418                 };
419                 f(self);
420                 self.lctx.is_in_trait_impl = old;
421             }
422         }
423
424         impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
425             fn visit_item(&mut self, item: &'lcx Item) {
426                 let mut item_lowered = true;
427                 self.lctx.with_hir_id_owner(item.id, |lctx| {
428                     if let Some(hir_item) = lctx.lower_item(item) {
429                         lctx.items.insert(item.id, hir_item);
430                     } else {
431                         item_lowered = false;
432                     }
433                 });
434
435                 if item_lowered {
436                     let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
437                         hir::ItemKind::Impl(_, _, _, ref generics, ..)
438                         | hir::ItemKind::Trait(_, _, ref generics, ..) => {
439                             generics.params.clone()
440                         }
441                         _ => HirVec::new(),
442                     };
443
444                     self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
445                         let this = &mut ItemLowerer { lctx: this };
446                         if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
447                             this.with_trait_impl_ref(opt_trait_ref, |this| {
448                                 visit::walk_item(this, item)
449                             });
450                         } else {
451                             visit::walk_item(this, item);
452                         }
453                     });
454                 }
455             }
456
457             fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
458                 self.lctx.with_hir_id_owner(item.id, |lctx| {
459                     let id = hir::TraitItemId { node_id: item.id };
460                     let hir_item = lctx.lower_trait_item(item);
461                     lctx.trait_items.insert(id, hir_item);
462                 });
463
464                 visit::walk_trait_item(self, item);
465             }
466
467             fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
468                 self.lctx.with_hir_id_owner(item.id, |lctx| {
469                     let id = hir::ImplItemId { node_id: item.id };
470                     let hir_item = lctx.lower_impl_item(item);
471                     lctx.impl_items.insert(id, hir_item);
472                 });
473                 visit::walk_impl_item(self, item);
474             }
475         }
476
477         self.lower_node_id(CRATE_NODE_ID);
478         debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
479
480         visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
481         visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
482
483         let module = self.lower_mod(&c.module);
484         let attrs = self.lower_attrs(&c.attrs);
485         let body_ids = body_ids(&self.bodies);
486
487         self.resolver
488             .definitions()
489             .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
490
491         hir::Crate {
492             module,
493             attrs,
494             span: c.span,
495             exported_macros: hir::HirVec::from(self.exported_macros),
496             items: self.items,
497             trait_items: self.trait_items,
498             impl_items: self.impl_items,
499             bodies: self.bodies,
500             body_ids,
501             trait_impls: self.trait_impls,
502             trait_auto_impl: self.trait_auto_impl,
503         }
504     }
505
506     fn allocate_hir_id_counter<T: Debug>(&mut self, owner: NodeId, debug: &T) -> LoweredNodeId {
507         if self.item_local_id_counters.insert(owner, 0).is_some() {
508             bug!(
509                 "Tried to allocate item_local_id_counter for {:?} twice",
510                 debug
511             );
512         }
513         // Always allocate the first HirId for the owner itself
514         self.lower_node_id_with_owner(owner, owner)
515     }
516
517     fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> LoweredNodeId
518     where
519         F: FnOnce(&mut Self) -> hir::HirId,
520     {
521         if ast_node_id == DUMMY_NODE_ID {
522             return LoweredNodeId {
523                 node_id: DUMMY_NODE_ID,
524                 hir_id: hir::DUMMY_HIR_ID,
525             };
526         }
527
528         let min_size = ast_node_id.as_usize() + 1;
529
530         if min_size > self.node_id_to_hir_id.len() {
531             self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
532         }
533
534         let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
535
536         if existing_hir_id == hir::DUMMY_HIR_ID {
537             // Generate a new HirId
538             let hir_id = alloc_hir_id(self);
539             self.node_id_to_hir_id[ast_node_id] = hir_id;
540             LoweredNodeId {
541                 node_id: ast_node_id,
542                 hir_id,
543             }
544         } else {
545             LoweredNodeId {
546                 node_id: ast_node_id,
547                 hir_id: existing_hir_id,
548             }
549         }
550     }
551
552     fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
553     where
554         F: FnOnce(&mut Self) -> T,
555     {
556         let counter = self.item_local_id_counters
557             .insert(owner, HIR_ID_COUNTER_LOCKED)
558             .unwrap_or_else(|| panic!("No item_local_id_counters entry for {:?}", owner));
559         let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
560         self.current_hir_id_owner.push((def_index, counter));
561         let ret = f(self);
562         let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
563
564         debug_assert!(def_index == new_def_index);
565         debug_assert!(new_counter >= counter);
566
567         let prev = self.item_local_id_counters
568             .insert(owner, new_counter)
569             .unwrap();
570         debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
571         ret
572     }
573
574     /// This method allocates a new HirId for the given NodeId and stores it in
575     /// the LoweringContext's NodeId => HirId map.
576     /// Take care not to call this method if the resulting HirId is then not
577     /// actually used in the HIR, as that would trigger an assertion in the
578     /// HirIdValidator later on, which makes sure that all NodeIds got mapped
579     /// properly. Calling the method twice with the same NodeId is fine though.
580     fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
581         self.lower_node_id_generic(ast_node_id, |this| {
582             let &mut (def_index, ref mut local_id_counter) =
583                 this.current_hir_id_owner.last_mut().unwrap();
584             let local_id = *local_id_counter;
585             *local_id_counter += 1;
586             hir::HirId {
587                 owner: def_index,
588                 local_id: hir::ItemLocalId(local_id),
589             }
590         })
591     }
592
593     fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> LoweredNodeId {
594         self.lower_node_id_generic(ast_node_id, |this| {
595             let local_id_counter = this
596                 .item_local_id_counters
597                 .get_mut(&owner)
598                 .expect("called lower_node_id_with_owner before allocate_hir_id_counter");
599             let local_id = *local_id_counter;
600
601             // We want to be sure not to modify the counter in the map while it
602             // is also on the stack. Otherwise we'll get lost updates when writing
603             // back from the stack to the map.
604             debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
605
606             *local_id_counter += 1;
607             let def_index = this
608                 .resolver
609                 .definitions()
610                 .opt_def_index(owner)
611                 .expect("You forgot to call `create_def_with_parent` or are lowering node ids \
612                          that do not belong to the current owner");
613
614             hir::HirId {
615                 owner: def_index,
616                 local_id: hir::ItemLocalId(local_id),
617             }
618         })
619     }
620
621     fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>) -> hir::BodyId {
622         let body = hir::Body {
623             arguments: decl.map_or(hir_vec![], |decl| {
624                 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
625             }),
626             is_generator: self.is_generator,
627             value,
628         };
629         let id = body.id();
630         self.bodies.insert(id, body);
631         id
632     }
633
634     fn next_id(&mut self) -> LoweredNodeId {
635         self.lower_node_id(self.sess.next_node_id())
636     }
637
638     fn expect_full_def(&mut self, id: NodeId) -> Def {
639         self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
640             if pr.unresolved_segments() != 0 {
641                 bug!("path not fully resolved: {:?}", pr);
642             }
643             pr.base_def()
644         })
645     }
646
647     fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def> {
648         self.resolver.get_import(id).present_items().map(|pr| {
649             if pr.unresolved_segments() != 0 {
650                 bug!("path not fully resolved: {:?}", pr);
651             }
652             pr.base_def()
653         })
654     }
655
656     fn diagnostic(&self) -> &errors::Handler {
657         self.sess.diagnostic()
658     }
659
660     fn str_to_ident(&self, s: &'static str) -> Ident {
661         Ident::with_empty_ctxt(Symbol::gensym(s))
662     }
663
664     fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span {
665         let mark = Mark::fresh(Mark::root());
666         mark.set_expn_info(source_map::ExpnInfo {
667             call_site: span,
668             def_site: Some(span),
669             format: source_map::CompilerDesugaring(reason),
670             allow_internal_unstable: true,
671             allow_internal_unsafe: false,
672             local_inner_macros: false,
673             edition: source_map::hygiene::default_edition(),
674         });
675         span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
676     }
677
678     fn with_anonymous_lifetime_mode<R>(
679         &mut self,
680         anonymous_lifetime_mode: AnonymousLifetimeMode,
681         op: impl FnOnce(&mut Self) -> R,
682     ) -> R {
683         let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
684         self.anonymous_lifetime_mode = anonymous_lifetime_mode;
685         let result = op(self);
686         self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
687         result
688     }
689
690     /// Creates a new hir::GenericParam for every new lifetime and
691     /// type parameter encountered while evaluating `f`. Definitions
692     /// are created with the parent provided. If no `parent_id` is
693     /// provided, no definitions will be returned.
694     ///
695     /// Presuming that in-band lifetimes are enabled, then
696     /// `self.anonymous_lifetime_mode` will be updated to match the
697     /// argument while `f` is running (and restored afterwards).
698     fn collect_in_band_defs<T, F>(
699         &mut self,
700         parent_id: DefId,
701         anonymous_lifetime_mode: AnonymousLifetimeMode,
702         f: F,
703     ) -> (Vec<hir::GenericParam>, T)
704     where
705         F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
706     {
707         assert!(!self.is_collecting_in_band_lifetimes);
708         assert!(self.lifetimes_to_define.is_empty());
709         let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
710
711         self.anonymous_lifetime_mode = anonymous_lifetime_mode;
712         self.is_collecting_in_band_lifetimes = true;
713
714         let (in_band_ty_params, res) = f(self);
715
716         self.is_collecting_in_band_lifetimes = false;
717         self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
718
719         let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
720
721         let params = lifetimes_to_define
722             .into_iter()
723             .map(|(span, hir_name)| {
724                 let def_node_id = self.next_id().node_id;
725
726                 // Get the name we'll use to make the def-path. Note
727                 // that collisions are ok here and this shouldn't
728                 // really show up for end-user.
729                 let (str_name, kind) = match hir_name {
730                     ParamName::Plain(ident) => (
731                         ident.as_interned_str(),
732                         hir::LifetimeParamKind::InBand,
733                     ),
734                     ParamName::Fresh(_) => (
735                         keywords::UnderscoreLifetime.name().as_interned_str(),
736                         hir::LifetimeParamKind::Elided,
737                     ),
738                     ParamName::Error => (
739                         keywords::UnderscoreLifetime.name().as_interned_str(),
740                         hir::LifetimeParamKind::Error,
741                     ),
742                 };
743
744                 // Add a definition for the in-band lifetime def
745                 self.resolver.definitions().create_def_with_parent(
746                     parent_id.index,
747                     def_node_id,
748                     DefPathData::LifetimeParam(str_name),
749                     DefIndexAddressSpace::High,
750                     Mark::root(),
751                     span,
752                 );
753
754                 hir::GenericParam {
755                     id: def_node_id,
756                     name: hir_name,
757                     attrs: hir_vec![],
758                     bounds: hir_vec![],
759                     span,
760                     pure_wrt_drop: false,
761                     kind: hir::GenericParamKind::Lifetime { kind }
762                 }
763             })
764             .chain(in_band_ty_params.into_iter())
765             .collect();
766
767         (params, res)
768     }
769
770     /// When there is a reference to some lifetime `'a`, and in-band
771     /// lifetimes are enabled, then we want to push that lifetime into
772     /// the vector of names to define later. In that case, it will get
773     /// added to the appropriate generics.
774     fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
775         if !self.is_collecting_in_band_lifetimes {
776             return;
777         }
778
779         if !self.sess.features_untracked().in_band_lifetimes {
780             return;
781         }
782
783         if self.in_scope_lifetimes.contains(&ident.modern()) {
784             return;
785         }
786
787         let hir_name = ParamName::Plain(ident);
788
789         if self.lifetimes_to_define.iter()
790                                    .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
791             return;
792         }
793
794         self.lifetimes_to_define.push((ident.span, hir_name));
795     }
796
797     /// When we have either an elided or `'_` lifetime in an impl
798     /// header, we convert it to an in-band lifetime.
799     fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
800         assert!(self.is_collecting_in_band_lifetimes);
801         let index = self.lifetimes_to_define.len();
802         let hir_name = ParamName::Fresh(index);
803         self.lifetimes_to_define.push((span, hir_name));
804         hir_name
805     }
806
807     // Evaluates `f` with the lifetimes in `params` in-scope.
808     // This is used to track which lifetimes have already been defined, and
809     // which are new in-band lifetimes that need to have a definition created
810     // for them.
811     fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
812     where
813         F: FnOnce(&mut LoweringContext<'_>) -> T,
814     {
815         let old_len = self.in_scope_lifetimes.len();
816         let lt_def_names = params.iter().filter_map(|param| match param.kind {
817             GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
818             _ => None,
819         });
820         self.in_scope_lifetimes.extend(lt_def_names);
821
822         let res = f(self);
823
824         self.in_scope_lifetimes.truncate(old_len);
825         res
826     }
827
828     // Same as the method above, but accepts `hir::GenericParam`s
829     // instead of `ast::GenericParam`s.
830     // This should only be used with generics that have already had their
831     // in-band lifetimes added. In practice, this means that this function is
832     // only used when lowering a child item of a trait or impl.
833     fn with_parent_impl_lifetime_defs<T, F>(&mut self,
834         params: &HirVec<hir::GenericParam>,
835         f: F
836     ) -> T where
837         F: FnOnce(&mut LoweringContext<'_>) -> T,
838     {
839         let old_len = self.in_scope_lifetimes.len();
840         let lt_def_names = params.iter().filter_map(|param| match param.kind {
841             hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
842             _ => None,
843         });
844         self.in_scope_lifetimes.extend(lt_def_names);
845
846         let res = f(self);
847
848         self.in_scope_lifetimes.truncate(old_len);
849         res
850     }
851
852     /// Appends in-band lifetime defs and argument-position `impl
853     /// Trait` defs to the existing set of generics.
854     ///
855     /// Presuming that in-band lifetimes are enabled, then
856     /// `self.anonymous_lifetime_mode` will be updated to match the
857     /// argument while `f` is running (and restored afterwards).
858     fn add_in_band_defs<F, T>(
859         &mut self,
860         generics: &Generics,
861         parent_id: DefId,
862         anonymous_lifetime_mode: AnonymousLifetimeMode,
863         f: F,
864     ) -> (hir::Generics, T)
865     where
866         F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
867     {
868         let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
869             &generics.params,
870             |this| {
871                 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
872                     let mut params = Vec::new();
873                     let generics = this.lower_generics(
874                         generics,
875                         ImplTraitContext::Universal(&mut params),
876                     );
877                     let res = f(this, &mut params);
878                     (params, (generics, res))
879                 })
880             },
881         );
882
883         lowered_generics.params = lowered_generics
884             .params
885             .iter()
886             .cloned()
887             .chain(in_band_defs)
888             .collect();
889
890         (lowered_generics, res)
891     }
892
893     fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
894     where
895         F: FnOnce(&mut LoweringContext<'_>) -> T,
896     {
897         let len = self.catch_scopes.len();
898         self.catch_scopes.push(catch_id);
899
900         let result = f(self);
901         assert_eq!(
902             len + 1,
903             self.catch_scopes.len(),
904             "catch scopes should be added and removed in stack order"
905         );
906
907         self.catch_scopes.pop().unwrap();
908
909         result
910     }
911
912     fn make_async_expr(
913         &mut self,
914         capture_clause: CaptureBy,
915         closure_node_id: NodeId,
916         ret_ty: Option<&Ty>,
917         body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
918     ) -> hir::ExprKind {
919         let prev_is_generator = mem::replace(&mut self.is_generator, true);
920         let body_expr = body(self);
921         let span = body_expr.span;
922         let output = match ret_ty {
923             Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
924             None => FunctionRetTy::Default(span),
925         };
926         let decl = FnDecl {
927             inputs: vec![],
928             output,
929             variadic: false
930         };
931         let body_id = self.record_body(body_expr, Some(&decl));
932         self.is_generator = prev_is_generator;
933
934         let capture_clause = self.lower_capture_clause(capture_clause);
935         let closure_hir_id = self.lower_node_id(closure_node_id).hir_id;
936         let decl = self.lower_fn_decl(&decl, None, /* impl trait allowed */ false, None);
937         let generator = hir::Expr {
938             id: closure_node_id,
939             hir_id: closure_hir_id,
940             node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
941                 Some(hir::GeneratorMovability::Static)),
942             span,
943             attrs: ThinVec::new(),
944         };
945
946         let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::Async, span);
947         let gen_future = self.expr_std_path(
948             unstable_span, &["future", "from_generator"], None, ThinVec::new());
949         hir::ExprKind::Call(P(gen_future), hir_vec![generator])
950     }
951
952     fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
953     where
954         F: FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
955     {
956         let prev = mem::replace(&mut self.is_generator, false);
957         let result = f(self);
958         let r = self.record_body(result, decl);
959         self.is_generator = prev;
960         return r;
961     }
962
963     fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
964     where
965         F: FnOnce(&mut LoweringContext<'_>) -> T,
966     {
967         // We're no longer in the base loop's condition; we're in another loop.
968         let was_in_loop_condition = self.is_in_loop_condition;
969         self.is_in_loop_condition = false;
970
971         let len = self.loop_scopes.len();
972         self.loop_scopes.push(loop_id);
973
974         let result = f(self);
975         assert_eq!(
976             len + 1,
977             self.loop_scopes.len(),
978             "Loop scopes should be added and removed in stack order"
979         );
980
981         self.loop_scopes.pop().unwrap();
982
983         self.is_in_loop_condition = was_in_loop_condition;
984
985         result
986     }
987
988     fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
989     where
990         F: FnOnce(&mut LoweringContext<'_>) -> T,
991     {
992         let was_in_loop_condition = self.is_in_loop_condition;
993         self.is_in_loop_condition = true;
994
995         let result = f(self);
996
997         self.is_in_loop_condition = was_in_loop_condition;
998
999         result
1000     }
1001
1002     fn with_new_scopes<T, F>(&mut self, f: F) -> T
1003     where
1004         F: FnOnce(&mut LoweringContext<'_>) -> T,
1005     {
1006         let was_in_loop_condition = self.is_in_loop_condition;
1007         self.is_in_loop_condition = false;
1008
1009         let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
1010         let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
1011         let ret = f(self);
1012         self.catch_scopes = catch_scopes;
1013         self.loop_scopes = loop_scopes;
1014
1015         self.is_in_loop_condition = was_in_loop_condition;
1016
1017         ret
1018     }
1019
1020     fn def_key(&mut self, id: DefId) -> DefKey {
1021         if id.is_local() {
1022             self.resolver.definitions().def_key(id.index)
1023         } else {
1024             self.cstore.def_key(id)
1025         }
1026     }
1027
1028     fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1029         label.map(|label| hir::Label {
1030             ident: label.ident,
1031         })
1032     }
1033
1034     fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1035         let target_id = match destination {
1036             Some((id, _)) => {
1037                 if let Def::Label(loop_id) = self.expect_full_def(id) {
1038                     Ok(self.lower_node_id(loop_id).node_id)
1039                 } else {
1040                     Err(hir::LoopIdError::UnresolvedLabel)
1041                 }
1042             }
1043             None => {
1044                 self.loop_scopes
1045                     .last()
1046                     .cloned()
1047                     .map(|id| Ok(self.lower_node_id(id).node_id))
1048                     .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1049                     .into()
1050             }
1051         };
1052         hir::Destination {
1053             label: self.lower_label(destination.map(|(_, label)| label)),
1054             target_id,
1055         }
1056     }
1057
1058     fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1059         attrs
1060             .iter()
1061             .map(|a| self.lower_attr(a))
1062             .collect::<Vec<_>>()
1063             .into()
1064     }
1065
1066     fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1067         Attribute {
1068             id: attr.id,
1069             style: attr.style,
1070             path: attr.path.clone(),
1071             tokens: self.lower_token_stream(attr.tokens.clone()),
1072             is_sugared_doc: attr.is_sugared_doc,
1073             span: attr.span,
1074         }
1075     }
1076
1077     fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1078         tokens
1079             .into_trees()
1080             .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1081             .collect()
1082     }
1083
1084     fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1085         match tree {
1086             TokenTree::Token(span, token) => self.lower_token(token, span),
1087             TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
1088                 span,
1089                 Delimited {
1090                     delim: delimited.delim,
1091                     tts: self.lower_token_stream(delimited.tts.into()).into(),
1092                 },
1093             ).into(),
1094         }
1095     }
1096
1097     fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
1098         match token {
1099             Token::Interpolated(_) => {}
1100             other => return TokenTree::Token(span, other).into(),
1101         }
1102
1103         let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
1104         self.lower_token_stream(tts)
1105     }
1106
1107     fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1108         hir::Arm {
1109             attrs: self.lower_attrs(&arm.attrs),
1110             pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1111             guard: match arm.guard {
1112                 Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1113                 _ => None,
1114             },
1115             body: P(self.lower_expr(&arm.body)),
1116         }
1117     }
1118
1119     fn lower_ty_binding(&mut self, b: &TypeBinding,
1120                         itctx: ImplTraitContext<'_>) -> hir::TypeBinding {
1121         hir::TypeBinding {
1122             id: self.lower_node_id(b.id).node_id,
1123             ident: b.ident,
1124             ty: self.lower_ty(&b.ty, itctx),
1125             span: b.span,
1126         }
1127     }
1128
1129     fn lower_generic_arg(&mut self,
1130                         arg: &ast::GenericArg,
1131                         itctx: ImplTraitContext<'_>)
1132                         -> hir::GenericArg {
1133         match arg {
1134             ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(&lt)),
1135             ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1136         }
1137     }
1138
1139     fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1140         P(self.lower_ty_direct(t, itctx))
1141     }
1142
1143     fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1144         let kind = match t.node {
1145             TyKind::Infer => hir::TyKind::Infer,
1146             TyKind::Err => hir::TyKind::Err,
1147             TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1148             TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1149             TyKind::Rptr(ref region, ref mt) => {
1150                 let span = t.span.shrink_to_lo();
1151                 let lifetime = match *region {
1152                     Some(ref lt) => self.lower_lifetime(lt),
1153                     None => self.elided_ref_lifetime(span),
1154                 };
1155                 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1156             }
1157             TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1158                 &f.generic_params,
1159                 |this| {
1160                     this.with_anonymous_lifetime_mode(
1161                         AnonymousLifetimeMode::PassThrough,
1162                         |this| {
1163                             hir::TyKind::BareFn(P(hir::BareFnTy {
1164                                 generic_params: this.lower_generic_params(
1165                                     &f.generic_params,
1166                                     &NodeMap(),
1167                                     ImplTraitContext::disallowed(),
1168                                 ),
1169                                 unsafety: this.lower_unsafety(f.unsafety),
1170                                 abi: f.abi,
1171                                 decl: this.lower_fn_decl(&f.decl, None, false, None),
1172                                 arg_names: this.lower_fn_args_to_names(&f.decl),
1173                             }))
1174                         },
1175                     )
1176                 },
1177             ),
1178             TyKind::Never => hir::TyKind::Never,
1179             TyKind::Tup(ref tys) => {
1180                 hir::TyKind::Tup(tys.iter().map(|ty| {
1181                     self.lower_ty_direct(ty, itctx.reborrow())
1182                 }).collect())
1183             }
1184             TyKind::Paren(ref ty) => {
1185                 return self.lower_ty_direct(ty, itctx);
1186             }
1187             TyKind::Path(ref qself, ref path) => {
1188                 let id = self.lower_node_id(t.id);
1189                 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
1190                 let ty = self.ty_path(id, t.span, qpath);
1191                 if let hir::TyKind::TraitObject(..) = ty.node {
1192                     self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1193                 }
1194                 return ty;
1195             }
1196             TyKind::ImplicitSelf => hir::TyKind::Path(hir::QPath::Resolved(
1197                 None,
1198                 P(hir::Path {
1199                     def: self.expect_full_def(t.id),
1200                     segments: hir_vec![hir::PathSegment::from_ident(keywords::SelfType.ident())],
1201                     span: t.span,
1202                 }),
1203             )),
1204             TyKind::Array(ref ty, ref length) => {
1205                 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1206             }
1207             TyKind::Typeof(ref expr) => {
1208                 hir::TyKind::Typeof(self.lower_anon_const(expr))
1209             }
1210             TyKind::TraitObject(ref bounds, kind) => {
1211                 let mut lifetime_bound = None;
1212                 let bounds = bounds
1213                     .iter()
1214                     .filter_map(|bound| match *bound {
1215                         GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1216                             Some(self.lower_poly_trait_ref(ty, itctx.reborrow()))
1217                         }
1218                         GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1219                         GenericBound::Outlives(ref lifetime) => {
1220                             if lifetime_bound.is_none() {
1221                                 lifetime_bound = Some(self.lower_lifetime(lifetime));
1222                             }
1223                             None
1224                         }
1225                     })
1226                     .collect();
1227                 let lifetime_bound =
1228                     lifetime_bound.unwrap_or_else(|| self.elided_dyn_bound(t.span));
1229                 if kind != TraitObjectSyntax::Dyn {
1230                     self.maybe_lint_bare_trait(t.span, t.id, false);
1231                 }
1232                 hir::TyKind::TraitObject(bounds, lifetime_bound)
1233             }
1234             TyKind::ImplTrait(def_node_id, ref bounds) => {
1235                 let span = t.span;
1236                 match itctx {
1237                     ImplTraitContext::Existential(fn_def_id) => {
1238                         self.lower_existential_impl_trait(
1239                             span, fn_def_id, def_node_id,
1240                             |this| this.lower_param_bounds(bounds, itctx),
1241                         )
1242                     }
1243                     ImplTraitContext::Universal(in_band_ty_params) => {
1244                         self.lower_node_id(def_node_id);
1245                         // Add a definition for the in-band Param
1246                         let def_index = self
1247                             .resolver
1248                             .definitions()
1249                             .opt_def_index(def_node_id)
1250                             .unwrap();
1251
1252                         let hir_bounds = self.lower_param_bounds(
1253                             bounds,
1254                             ImplTraitContext::Universal(in_band_ty_params),
1255                         );
1256                         // Set the name to `impl Bound1 + Bound2`
1257                         let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1258                         in_band_ty_params.push(hir::GenericParam {
1259                             id: def_node_id,
1260                             name: ParamName::Plain(ident),
1261                             pure_wrt_drop: false,
1262                             attrs: hir_vec![],
1263                             bounds: hir_bounds,
1264                             span,
1265                             kind: hir::GenericParamKind::Type {
1266                                 default: None,
1267                                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1268                             }
1269                         });
1270
1271                         hir::TyKind::Path(hir::QPath::Resolved(
1272                             None,
1273                             P(hir::Path {
1274                                 span,
1275                                 def: Def::TyParam(DefId::local(def_index)),
1276                                 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1277                             }),
1278                         ))
1279                     }
1280                     ImplTraitContext::Disallowed(pos) => {
1281                         let allowed_in = if self.sess.features_untracked()
1282                                                 .impl_trait_in_bindings {
1283                             "bindings or function and inherent method return types"
1284                         } else {
1285                             "function and inherent method return types"
1286                         };
1287                         let mut err = struct_span_err!(
1288                             self.sess,
1289                             t.span,
1290                             E0562,
1291                             "`impl Trait` not allowed outside of {}",
1292                             allowed_in,
1293                         );
1294                         if pos == ImplTraitPosition::Binding &&
1295                             nightly_options::is_nightly_build() {
1296                             help!(err,
1297                                   "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1298                                    to enable");
1299                         }
1300                         err.emit();
1301                         hir::TyKind::Err
1302                     }
1303                 }
1304             }
1305             TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1306         };
1307
1308         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1309         hir::Ty {
1310             id: node_id,
1311             node: kind,
1312             span: t.span,
1313             hir_id,
1314         }
1315     }
1316
1317     fn lower_existential_impl_trait(
1318         &mut self,
1319         span: Span,
1320         fn_def_id: Option<DefId>,
1321         exist_ty_node_id: NodeId,
1322         lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1323     ) -> hir::TyKind {
1324         // Make sure we know that some funky desugaring has been going on here.
1325         // This is a first: there is code in other places like for loop
1326         // desugaring that explicitly states that we don't want to track that.
1327         // Not tracking it makes lints in rustc and clippy very fragile as
1328         // frequently opened issues show.
1329         let exist_ty_span = self.allow_internal_unstable(
1330             CompilerDesugaringKind::ExistentialReturnType,
1331             span,
1332         );
1333
1334         let exist_ty_def_index = self
1335             .resolver
1336             .definitions()
1337             .opt_def_index(exist_ty_node_id)
1338             .unwrap();
1339
1340         self.allocate_hir_id_counter(exist_ty_node_id, &"existential impl trait");
1341
1342         let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1343
1344         let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1345             exist_ty_node_id,
1346             exist_ty_def_index,
1347             &hir_bounds,
1348         );
1349
1350         self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1351             let exist_ty_item_kind = hir::ItemKind::Existential(hir::ExistTy {
1352                 generics: hir::Generics {
1353                     params: lifetime_defs,
1354                     where_clause: hir::WhereClause {
1355                         id: lctx.next_id().node_id,
1356                         predicates: Vec::new().into(),
1357                     },
1358                     span,
1359                 },
1360                 bounds: hir_bounds,
1361                 impl_trait_fn: fn_def_id,
1362             });
1363             let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
1364             // Generate an `existential type Foo: Trait;` declaration
1365             trace!("creating existential type with id {:#?}", exist_ty_id);
1366
1367             trace!("exist ty def index: {:#?}", exist_ty_def_index);
1368             let exist_ty_item = hir::Item {
1369                 id: exist_ty_id.node_id,
1370                 hir_id: exist_ty_id.hir_id,
1371                 name: keywords::Invalid.name(),
1372                 attrs: Default::default(),
1373                 node: exist_ty_item_kind,
1374                 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1375                 span: exist_ty_span,
1376             };
1377
1378             // Insert the item into the global list. This usually happens
1379             // automatically for all AST items. But this existential type item
1380             // does not actually exist in the AST.
1381             lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
1382
1383             // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
1384             hir::TyKind::Def(hir::ItemId { id: exist_ty_id.node_id }, lifetimes)
1385         })
1386     }
1387
1388     fn lifetimes_from_impl_trait_bounds(
1389         &mut self,
1390         exist_ty_id: NodeId,
1391         parent_index: DefIndex,
1392         bounds: &hir::GenericBounds,
1393     ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1394         // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1395         // appear in the bounds, excluding lifetimes that are created within the bounds.
1396         // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1397         struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1398             context: &'r mut LoweringContext<'a>,
1399             parent: DefIndex,
1400             exist_ty_id: NodeId,
1401             collect_elided_lifetimes: bool,
1402             currently_bound_lifetimes: Vec<hir::LifetimeName>,
1403             already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1404             output_lifetimes: Vec<hir::GenericArg>,
1405             output_lifetime_params: Vec<hir::GenericParam>,
1406         }
1407
1408         impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1409             fn nested_visit_map<'this>(
1410                 &'this mut self,
1411             ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1412                 hir::intravisit::NestedVisitorMap::None
1413             }
1414
1415             fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1416                 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1417                 if parameters.parenthesized {
1418                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1419                     self.collect_elided_lifetimes = false;
1420                     hir::intravisit::walk_generic_args(self, span, parameters);
1421                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1422                 } else {
1423                     hir::intravisit::walk_generic_args(self, span, parameters);
1424                 }
1425             }
1426
1427             fn visit_ty(&mut self, t: &'v hir::Ty) {
1428                 // Don't collect elided lifetimes used inside of `fn()` syntax
1429                 if let hir::TyKind::BareFn(_) = t.node {
1430                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1431                     self.collect_elided_lifetimes = false;
1432
1433                     // Record the "stack height" of `for<'a>` lifetime bindings
1434                     // to be able to later fully undo their introduction.
1435                     let old_len = self.currently_bound_lifetimes.len();
1436                     hir::intravisit::walk_ty(self, t);
1437                     self.currently_bound_lifetimes.truncate(old_len);
1438
1439                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1440                 } else {
1441                     hir::intravisit::walk_ty(self, t)
1442                 }
1443             }
1444
1445             fn visit_poly_trait_ref(
1446                 &mut self,
1447                 trait_ref: &'v hir::PolyTraitRef,
1448                 modifier: hir::TraitBoundModifier,
1449             ) {
1450                 // Record the "stack height" of `for<'a>` lifetime bindings
1451                 // to be able to later fully undo their introduction.
1452                 let old_len = self.currently_bound_lifetimes.len();
1453                 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1454                 self.currently_bound_lifetimes.truncate(old_len);
1455             }
1456
1457             fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1458                 // Record the introduction of 'a in `for<'a> ...`
1459                 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1460                     // Introduce lifetimes one at a time so that we can handle
1461                     // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1462                     let lt_name = hir::LifetimeName::Param(param.name);
1463                     self.currently_bound_lifetimes.push(lt_name);
1464                 }
1465
1466                 hir::intravisit::walk_generic_param(self, param);
1467             }
1468
1469             fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1470                 let name = match lifetime.name {
1471                     hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1472                         if self.collect_elided_lifetimes {
1473                             // Use `'_` for both implicit and underscore lifetimes in
1474                             // `abstract type Foo<'_>: SomeTrait<'_>;`
1475                             hir::LifetimeName::Underscore
1476                         } else {
1477                             return;
1478                         }
1479                     }
1480                     hir::LifetimeName::Param(_) => lifetime.name,
1481                     hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1482                 };
1483
1484                 if !self.currently_bound_lifetimes.contains(&name)
1485                     && !self.already_defined_lifetimes.contains(&name) {
1486                     self.already_defined_lifetimes.insert(name);
1487
1488                     self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1489                         id: self.context.next_id().node_id,
1490                         span: lifetime.span,
1491                         name,
1492                     }));
1493
1494                     // We need to manually create the ids here, because the
1495                     // definitions will go into the explicit `existential type`
1496                     // declaration and thus need to have their owner set to that item
1497                     let def_node_id = self.context.sess.next_node_id();
1498                     let _ = self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1499                     self.context.resolver.definitions().create_def_with_parent(
1500                         self.parent,
1501                         def_node_id,
1502                         DefPathData::LifetimeParam(name.ident().as_interned_str()),
1503                         DefIndexAddressSpace::High,
1504                         Mark::root(),
1505                         lifetime.span,
1506                     );
1507
1508                     let (name, kind) = match name {
1509                         hir::LifetimeName::Underscore => (
1510                             hir::ParamName::Plain(keywords::UnderscoreLifetime.ident()),
1511                             hir::LifetimeParamKind::Elided,
1512                         ),
1513                         hir::LifetimeName::Param(param_name) => (
1514                             param_name,
1515                             hir::LifetimeParamKind::Explicit,
1516                         ),
1517                         _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
1518                     };
1519
1520                     self.output_lifetime_params.push(hir::GenericParam {
1521                         id: def_node_id,
1522                         name,
1523                         span: lifetime.span,
1524                         pure_wrt_drop: false,
1525                         attrs: hir_vec![],
1526                         bounds: hir_vec![],
1527                         kind: hir::GenericParamKind::Lifetime { kind }
1528                     });
1529                 }
1530             }
1531         }
1532
1533         let mut lifetime_collector = ImplTraitLifetimeCollector {
1534             context: self,
1535             parent: parent_index,
1536             exist_ty_id,
1537             collect_elided_lifetimes: true,
1538             currently_bound_lifetimes: Vec::new(),
1539             already_defined_lifetimes: FxHashSet::default(),
1540             output_lifetimes: Vec::new(),
1541             output_lifetime_params: Vec::new(),
1542         };
1543
1544         for bound in bounds {
1545             hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1546         }
1547
1548         (
1549             lifetime_collector.output_lifetimes.into(),
1550             lifetime_collector.output_lifetime_params.into(),
1551         )
1552     }
1553
1554     fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1555         hir::ForeignMod {
1556             abi: fm.abi,
1557             items: fm.items
1558                 .iter()
1559                 .map(|x| self.lower_foreign_item(x))
1560                 .collect(),
1561         }
1562     }
1563
1564     fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1565         P(hir::GlobalAsm {
1566             asm: ga.asm,
1567             ctxt: ga.ctxt,
1568         })
1569     }
1570
1571     fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1572         Spanned {
1573             node: hir::VariantKind {
1574                 name: v.node.ident.name,
1575                 attrs: self.lower_attrs(&v.node.attrs),
1576                 data: self.lower_variant_data(&v.node.data),
1577                 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1578             },
1579             span: v.span,
1580         }
1581     }
1582
1583     fn lower_qpath(
1584         &mut self,
1585         id: NodeId,
1586         qself: &Option<QSelf>,
1587         p: &Path,
1588         param_mode: ParamMode,
1589         mut itctx: ImplTraitContext<'_>,
1590     ) -> hir::QPath {
1591         let qself_position = qself.as_ref().map(|q| q.position);
1592         let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1593
1594         let resolution = self.resolver
1595             .get_resolution(id)
1596             .unwrap_or_else(|| PathResolution::new(Def::Err));
1597
1598         let proj_start = p.segments.len() - resolution.unresolved_segments();
1599         let path = P(hir::Path {
1600             def: resolution.base_def(),
1601             segments: p.segments[..proj_start]
1602                 .iter()
1603                 .enumerate()
1604                 .map(|(i, segment)| {
1605                     let param_mode = match (qself_position, param_mode) {
1606                         (Some(j), ParamMode::Optional) if i < j => {
1607                             // This segment is part of the trait path in a
1608                             // qualified path - one of `a`, `b` or `Trait`
1609                             // in `<X as a::b::Trait>::T::U::method`.
1610                             ParamMode::Explicit
1611                         }
1612                         _ => param_mode,
1613                     };
1614
1615                     // Figure out if this is a type/trait segment,
1616                     // which may need lifetime elision performed.
1617                     let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1618                         krate: def_id.krate,
1619                         index: this.def_key(def_id).parent.expect("missing parent"),
1620                     };
1621                     let type_def_id = match resolution.base_def() {
1622                         Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1623                             Some(parent_def_id(self, def_id))
1624                         }
1625                         Def::Variant(def_id) if i + 1 == proj_start => {
1626                             Some(parent_def_id(self, def_id))
1627                         }
1628                         Def::Struct(def_id)
1629                         | Def::Union(def_id)
1630                         | Def::Enum(def_id)
1631                         | Def::TyAlias(def_id)
1632                         | Def::Trait(def_id) if i + 1 == proj_start =>
1633                         {
1634                             Some(def_id)
1635                         }
1636                         _ => None,
1637                     };
1638                     let parenthesized_generic_args = match resolution.base_def() {
1639                         // `a::b::Trait(Args)`
1640                         Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1641                         // `a::b::Trait(Args)::TraitItem`
1642                         Def::Method(..) | Def::AssociatedConst(..) | Def::AssociatedTy(..)
1643                             if i + 2 == proj_start =>
1644                         {
1645                             ParenthesizedGenericArgs::Ok
1646                         }
1647                         // Avoid duplicated errors
1648                         Def::Err => ParenthesizedGenericArgs::Ok,
1649                         // An error
1650                         Def::Struct(..)
1651                         | Def::Enum(..)
1652                         | Def::Union(..)
1653                         | Def::TyAlias(..)
1654                         | Def::Variant(..) if i + 1 == proj_start =>
1655                         {
1656                             ParenthesizedGenericArgs::Err
1657                         }
1658                         // A warning for now, for compatibility reasons
1659                         _ => ParenthesizedGenericArgs::Warn,
1660                     };
1661
1662                     let num_lifetimes = type_def_id.map_or(0, |def_id| {
1663                         if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1664                             return n;
1665                         }
1666                         assert!(!def_id.is_local());
1667                         let item_generics =
1668                             self.cstore.item_generics_cloned_untracked(def_id, self.sess);
1669                         let n = item_generics.own_counts().lifetimes;
1670                         self.type_def_lifetime_params.insert(def_id, n);
1671                         n
1672                     });
1673                     self.lower_path_segment(
1674                         p.span,
1675                         segment,
1676                         param_mode,
1677                         num_lifetimes,
1678                         parenthesized_generic_args,
1679                         itctx.reborrow(),
1680                     )
1681                 })
1682                 .collect(),
1683             span: p.span,
1684         });
1685
1686         // Simple case, either no projections, or only fully-qualified.
1687         // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1688         if resolution.unresolved_segments() == 0 {
1689             return hir::QPath::Resolved(qself, path);
1690         }
1691
1692         // Create the innermost type that we're projecting from.
1693         let mut ty = if path.segments.is_empty() {
1694             // If the base path is empty that means there exists a
1695             // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1696             qself.expect("missing QSelf for <T>::...")
1697         } else {
1698             // Otherwise, the base path is an implicit `Self` type path,
1699             // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1700             // `<I as Iterator>::Item::default`.
1701             let new_id = self.next_id();
1702             P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1703         };
1704
1705         // Anything after the base path are associated "extensions",
1706         // out of which all but the last one are associated types,
1707         // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1708         // * base path is `std::vec::Vec<T>`
1709         // * "extensions" are `IntoIter`, `Item` and `clone`
1710         // * type nodes are:
1711         //   1. `std::vec::Vec<T>` (created above)
1712         //   2. `<std::vec::Vec<T>>::IntoIter`
1713         //   3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1714         // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1715         for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1716             let segment = P(self.lower_path_segment(
1717                 p.span,
1718                 segment,
1719                 param_mode,
1720                 0,
1721                 ParenthesizedGenericArgs::Warn,
1722                 itctx.reborrow(),
1723             ));
1724             let qpath = hir::QPath::TypeRelative(ty, segment);
1725
1726             // It's finished, return the extension of the right node type.
1727             if i == p.segments.len() - 1 {
1728                 return qpath;
1729             }
1730
1731             // Wrap the associated extension in another type node.
1732             let new_id = self.next_id();
1733             ty = P(self.ty_path(new_id, p.span, qpath));
1734         }
1735
1736         // Should've returned in the for loop above.
1737         span_bug!(
1738             p.span,
1739             "lower_qpath: no final extension segment in {}..{}",
1740             proj_start,
1741             p.segments.len()
1742         )
1743     }
1744
1745     fn lower_path_extra(
1746         &mut self,
1747         def: Def,
1748         p: &Path,
1749         ident: Option<Ident>,
1750         param_mode: ParamMode,
1751     ) -> hir::Path {
1752         hir::Path {
1753             def,
1754             segments: p.segments
1755                 .iter()
1756                 .map(|segment| {
1757                     self.lower_path_segment(
1758                         p.span,
1759                         segment,
1760                         param_mode,
1761                         0,
1762                         ParenthesizedGenericArgs::Err,
1763                         ImplTraitContext::disallowed(),
1764                     )
1765                 })
1766                 .chain(ident.map(|ident| hir::PathSegment::from_ident(ident)))
1767                 .collect(),
1768             span: p.span,
1769         }
1770     }
1771
1772     fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1773         let def = self.expect_full_def(id);
1774         self.lower_path_extra(def, p, None, param_mode)
1775     }
1776
1777     fn lower_path_segment(
1778         &mut self,
1779         path_span: Span,
1780         segment: &PathSegment,
1781         param_mode: ParamMode,
1782         expected_lifetimes: usize,
1783         parenthesized_generic_args: ParenthesizedGenericArgs,
1784         itctx: ImplTraitContext<'_>,
1785     ) -> hir::PathSegment {
1786         let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
1787             let msg = "parenthesized parameters may only be used with a trait";
1788             match **generic_args {
1789                 GenericArgs::AngleBracketed(ref data) => {
1790                     self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1791                 }
1792                 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1793                     ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1794                     ParenthesizedGenericArgs::Warn => {
1795                         self.sess.buffer_lint(
1796                             PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1797                             CRATE_NODE_ID,
1798                             data.span,
1799                             msg.into(),
1800                         );
1801                         (hir::GenericArgs::none(), true)
1802                     }
1803                     ParenthesizedGenericArgs::Err => {
1804                         struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1805                             .span_label(data.span, "only traits may use parentheses")
1806                             .emit();
1807                         (hir::GenericArgs::none(), true)
1808                     }
1809                 },
1810             }
1811         } else {
1812             self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1813         };
1814
1815         let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1816             GenericArg::Lifetime(_) => true,
1817             _ => false,
1818         });
1819         let first_generic_span = generic_args.args.iter().map(|a| a.span())
1820             .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1821         if !generic_args.parenthesized && !has_lifetimes {
1822             generic_args.args =
1823                 self.elided_path_lifetimes(path_span, expected_lifetimes)
1824                     .into_iter()
1825                     .map(|lt| GenericArg::Lifetime(lt))
1826                     .chain(generic_args.args.into_iter())
1827                 .collect();
1828             if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1829                 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1830                 let no_ty_args = generic_args.args.len() == expected_lifetimes;
1831                 let no_bindings = generic_args.bindings.is_empty();
1832                 let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
1833                     // If there are no (non-implicit) generic args or associated-type
1834                     // bindings, our suggestion includes the angle brackets
1835                     (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1836                 } else {
1837                     // Otherwise—sorry, this is kind of gross—we need to infer the
1838                     // place to splice in the `'_, ` from the generics that do exist
1839                     let first_generic_span = first_generic_span
1840                         .expect("already checked that type args or bindings exist");
1841                     (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1842                 };
1843                 self.sess.buffer_lint_with_diagnostic(
1844                     ELIDED_LIFETIMES_IN_PATHS,
1845                     CRATE_NODE_ID,
1846                     path_span,
1847                     "hidden lifetime parameters in types are deprecated",
1848                     builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1849                         expected_lifetimes, path_span, incl_angl_brckt, insertion_span, suggestion
1850                     )
1851                 );
1852             }
1853         }
1854
1855         hir::PathSegment::new(
1856             segment.ident,
1857             generic_args,
1858             infer_types,
1859         )
1860     }
1861
1862     fn lower_angle_bracketed_parameter_data(
1863         &mut self,
1864         data: &AngleBracketedArgs,
1865         param_mode: ParamMode,
1866         mut itctx: ImplTraitContext<'_>,
1867     ) -> (hir::GenericArgs, bool) {
1868         let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1869         let has_types = args.iter().any(|arg| match arg {
1870             ast::GenericArg::Type(_) => true,
1871             _ => false,
1872         });
1873         (hir::GenericArgs {
1874             args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
1875             bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx.reborrow())).collect(),
1876             parenthesized: false,
1877         },
1878         !has_types && param_mode == ParamMode::Optional)
1879     }
1880
1881     fn lower_parenthesized_parameter_data(
1882         &mut self,
1883         data: &ParenthesisedArgs,
1884     ) -> (hir::GenericArgs, bool) {
1885         // Switch to `PassThrough` mode for anonymous lifetimes: this
1886         // means that we permit things like `&Ref<T>`, where `Ref` has
1887         // a hidden lifetime parameter. This is needed for backwards
1888         // compatibility, even in contexts like an impl header where
1889         // we generally don't permit such things (see #51008).
1890         self.with_anonymous_lifetime_mode(
1891             AnonymousLifetimeMode::PassThrough,
1892             |this| {
1893                 let &ParenthesisedArgs { ref inputs, ref output, span } = data;
1894                 let inputs = inputs
1895                     .iter()
1896                     .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
1897                     .collect();
1898                 let mk_tup = |this: &mut Self, tys, span| {
1899                     let LoweredNodeId { node_id, hir_id } = this.next_id();
1900                     hir::Ty { node: hir::TyKind::Tup(tys), id: node_id, hir_id, span }
1901                 };
1902
1903                 (
1904                     hir::GenericArgs {
1905                         args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1906                         bindings: hir_vec![
1907                             hir::TypeBinding {
1908                                 id: this.next_id().node_id,
1909                                 ident: Ident::from_str(FN_OUTPUT_NAME),
1910                                 ty: output
1911                                     .as_ref()
1912                                     .map(|ty| this.lower_ty(&ty, ImplTraitContext::disallowed()))
1913                                     .unwrap_or_else(|| P(mk_tup(this, hir::HirVec::new(), span))),
1914                                 span: output.as_ref().map_or(span, |ty| ty.span),
1915                             }
1916                         ],
1917                         parenthesized: true,
1918                     },
1919                     false,
1920                 )
1921             }
1922         )
1923     }
1924
1925     fn lower_local(&mut self, l: &Local) -> (P<hir::Local>, SmallVec<[hir::ItemId; 1]>) {
1926         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1927         let mut ids = SmallVec::<[hir::ItemId; 1]>::new();
1928         if self.sess.features_untracked().impl_trait_in_bindings {
1929             if let Some(ref ty) = l.ty {
1930                 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1931                 visitor.visit_ty(ty);
1932             }
1933         }
1934         let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
1935         (P(hir::Local {
1936             id: node_id,
1937             hir_id,
1938             ty: l.ty
1939                 .as_ref()
1940                 .map(|t| self.lower_ty(t,
1941                     if self.sess.features_untracked().impl_trait_in_bindings {
1942                         ImplTraitContext::Existential(Some(parent_def_id))
1943                     } else {
1944                         ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
1945                     }
1946                 )),
1947             pat: self.lower_pat(&l.pat),
1948             init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1949             span: l.span,
1950             attrs: l.attrs.clone(),
1951             source: hir::LocalSource::Normal,
1952         }), ids)
1953     }
1954
1955     fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1956         match m {
1957             Mutability::Mutable => hir::MutMutable,
1958             Mutability::Immutable => hir::MutImmutable,
1959         }
1960     }
1961
1962     fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1963         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1964         hir::Arg {
1965             id: node_id,
1966             hir_id,
1967             pat: self.lower_pat(&arg.pat),
1968         }
1969     }
1970
1971     fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
1972         decl.inputs
1973             .iter()
1974             .map(|arg| match arg.pat.node {
1975                 PatKind::Ident(_, ident, _) => ident,
1976                 _ => Ident::new(keywords::Invalid.name(), arg.pat.span),
1977             })
1978             .collect()
1979     }
1980
1981     // Lowers a function declaration.
1982     //
1983     // decl: the unlowered (ast) function declaration.
1984     // fn_def_id: if `Some`, impl Trait arguments are lowered into generic parameters on the
1985     //      given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1986     //      make_ret_async is also `Some`.
1987     // impl_trait_return_allow: determines whether impl Trait can be used in return position.
1988     //      This guards against trait declarations and implementations where impl Trait is
1989     //      disallowed.
1990     // make_ret_async: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1991     //      return type. This is used for `async fn` declarations. The `NodeId` is the id of the
1992     //      return type impl Trait item.
1993     fn lower_fn_decl(
1994         &mut self,
1995         decl: &FnDecl,
1996         mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
1997         impl_trait_return_allow: bool,
1998         make_ret_async: Option<NodeId>,
1999     ) -> P<hir::FnDecl> {
2000         let inputs = decl.inputs
2001             .iter()
2002             .map(|arg| {
2003                 if let Some((_, ref mut ibty)) = in_band_ty_params {
2004                     self.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2005                 } else {
2006                     self.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2007                 }
2008             })
2009             .collect::<HirVec<_>>();
2010
2011         let output = if let Some(ret_id) = make_ret_async {
2012             self.lower_async_fn_ret_ty(
2013                 &inputs,
2014                 &decl.output,
2015                 in_band_ty_params.expect("make_ret_async but no fn_def_id").0,
2016                 ret_id,
2017             )
2018         } else {
2019             match decl.output {
2020                 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2021                     Some((def_id, _)) if impl_trait_return_allow => {
2022                         hir::Return(self.lower_ty(ty,
2023                             ImplTraitContext::Existential(Some(def_id))))
2024                     }
2025                     _ => {
2026                         hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2027                     }
2028                 },
2029                 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2030             }
2031         };
2032
2033         P(hir::FnDecl {
2034             inputs,
2035             output,
2036             variadic: decl.variadic,
2037             implicit_self: decl.inputs.get(0).map_or(
2038                 hir::ImplicitSelfKind::None,
2039                 |arg| {
2040                     let is_mutable_pat = match arg.pat.node {
2041                         PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2042                         PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2043                             mt == Mutability::Mutable,
2044                         _ => false,
2045                     };
2046
2047                     match arg.ty.node {
2048                         TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2049                         TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2050                         // Given we are only considering `ImplicitSelf` types, we needn't consider
2051                         // the case where we have a mutable pattern to a reference as that would
2052                         // no longer be an `ImplicitSelf`.
2053                         TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2054                             mt.mutbl == ast::Mutability::Mutable =>
2055                                 hir::ImplicitSelfKind::MutRef,
2056                         TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2057                             hir::ImplicitSelfKind::ImmRef,
2058                         _ => hir::ImplicitSelfKind::None,
2059                     }
2060                 },
2061             ),
2062         })
2063     }
2064
2065     // Transform `-> T` into `-> impl Future<Output = T>` for `async fn`
2066     //
2067     // fn_span: the span of the async function declaration. Used for error reporting.
2068     // inputs: lowered types of arguments to the function. Used to collect lifetimes.
2069     // output: unlowered output type (`T` in `-> T`)
2070     // fn_def_id: DefId of the parent function. Used to create child impl trait definition.
2071     fn lower_async_fn_ret_ty(
2072         &mut self,
2073         inputs: &[hir::Ty],
2074         output: &FunctionRetTy,
2075         fn_def_id: DefId,
2076         return_impl_trait_id: NodeId,
2077     ) -> hir::FunctionRetTy {
2078         // Get lifetimes used in the input arguments to the function. Our output type must also
2079         // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
2080         // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
2081         // is a subset of the other. We really want some new lifetime that is a subset of all input
2082         // lifetimes, but that doesn't exist at the moment.
2083
2084         struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
2085             context: &'r mut LoweringContext<'a>,
2086             // Lifetimes bound by HRTB
2087             currently_bound_lifetimes: Vec<hir::LifetimeName>,
2088             // Whether to count elided lifetimes.
2089             // Disabled inside of `Fn` or `fn` syntax.
2090             collect_elided_lifetimes: bool,
2091             // The lifetime found.
2092             // Multiple different or elided lifetimes cannot appear in async fn for now.
2093             output_lifetime: Option<(hir::LifetimeName, Span)>,
2094         }
2095
2096         impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for AsyncFnLifetimeCollector<'r, 'a> {
2097             fn nested_visit_map<'this>(
2098                 &'this mut self,
2099             ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
2100                 hir::intravisit::NestedVisitorMap::None
2101             }
2102
2103             fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
2104                 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2105                 if parameters.parenthesized {
2106                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2107                     self.collect_elided_lifetimes = false;
2108                     hir::intravisit::walk_generic_args(self, span, parameters);
2109                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2110                 } else {
2111                     hir::intravisit::walk_generic_args(self, span, parameters);
2112                 }
2113             }
2114
2115             fn visit_ty(&mut self, t: &'v hir::Ty) {
2116                 // Don't collect elided lifetimes used inside of `fn()` syntax
2117                 if let &hir::TyKind::BareFn(_) = &t.node {
2118                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2119                     self.collect_elided_lifetimes = false;
2120
2121                     // Record the "stack height" of `for<'a>` lifetime bindings
2122                     // to be able to later fully undo their introduction.
2123                     let old_len = self.currently_bound_lifetimes.len();
2124                     hir::intravisit::walk_ty(self, t);
2125                     self.currently_bound_lifetimes.truncate(old_len);
2126
2127                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2128                 } else {
2129                     hir::intravisit::walk_ty(self, t);
2130                 }
2131             }
2132
2133             fn visit_poly_trait_ref(
2134                 &mut self,
2135                 trait_ref: &'v hir::PolyTraitRef,
2136                 modifier: hir::TraitBoundModifier,
2137             ) {
2138                 // Record the "stack height" of `for<'a>` lifetime bindings
2139                 // to be able to later fully undo their introduction.
2140                 let old_len = self.currently_bound_lifetimes.len();
2141                 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2142                 self.currently_bound_lifetimes.truncate(old_len);
2143             }
2144
2145             fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
2146                  // Record the introduction of 'a in `for<'a> ...`
2147                 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2148                     // Introduce lifetimes one at a time so that we can handle
2149                     // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
2150                     let lt_name = hir::LifetimeName::Param(param.name);
2151                     self.currently_bound_lifetimes.push(lt_name);
2152                 }
2153
2154                 hir::intravisit::walk_generic_param(self, param);
2155             }
2156
2157             fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2158                 let name = match lifetime.name {
2159                     hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2160                         if self.collect_elided_lifetimes {
2161                             // Use `'_` for both implicit and underscore lifetimes in
2162                             // `abstract type Foo<'_>: SomeTrait<'_>;`
2163                             hir::LifetimeName::Underscore
2164                         } else {
2165                             return;
2166                         }
2167                     }
2168                     hir::LifetimeName::Param(_) => lifetime.name,
2169                     hir::LifetimeName::Error | hir::LifetimeName::Static => return,
2170                 };
2171
2172                 if !self.currently_bound_lifetimes.contains(&name) {
2173                     if let Some((current_lt_name, current_lt_span)) = self.output_lifetime {
2174                         // We don't currently have a reliable way to desugar `async fn` with
2175                         // multiple potentially unrelated input lifetimes into
2176                         // `-> impl Trait + 'lt`, so we report an error in this case.
2177                         if current_lt_name != name {
2178                             struct_span_err!(
2179                                 self.context.sess,
2180                                 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2181                                 E0709,
2182                                 "multiple different lifetimes used in arguments of `async fn`",
2183                             )
2184                                 .span_label(current_lt_span, "first lifetime here")
2185                                 .span_label(lifetime.span, "different lifetime here")
2186                                 .help("`async fn` can only accept borrowed values \
2187                                       with identical lifetimes")
2188                                 .emit()
2189                         } else if current_lt_name.is_elided() && name.is_elided() {
2190                             struct_span_err!(
2191                                 self.context.sess,
2192                                 MultiSpan::from_spans(vec![current_lt_span, lifetime.span]),
2193                                 E0707,
2194                                 "multiple elided lifetimes used in arguments of `async fn`",
2195                             )
2196                                 .span_label(current_lt_span, "first lifetime here")
2197                                 .span_label(lifetime.span, "different lifetime here")
2198                                 .help("consider giving these arguments named lifetimes")
2199                                 .emit()
2200                         }
2201                     } else {
2202                         self.output_lifetime = Some((name, lifetime.span));
2203                     }
2204                 }
2205             }
2206         }
2207
2208         let bound_lifetime = {
2209             let mut lifetime_collector = AsyncFnLifetimeCollector {
2210                 context: self,
2211                 currently_bound_lifetimes: Vec::new(),
2212                 collect_elided_lifetimes: true,
2213                 output_lifetime: None,
2214             };
2215
2216             for arg in inputs {
2217                 hir::intravisit::walk_ty(&mut lifetime_collector, arg);
2218             }
2219             lifetime_collector.output_lifetime
2220         };
2221
2222         let span = match output {
2223             FunctionRetTy::Ty(ty) => ty.span,
2224             FunctionRetTy::Default(span) => *span,
2225         };
2226
2227         let impl_trait_ty = self.lower_existential_impl_trait(
2228             span, Some(fn_def_id), return_impl_trait_id, |this| {
2229             let output_ty = match output {
2230                 FunctionRetTy::Ty(ty) => {
2231                     this.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2232                 }
2233                 FunctionRetTy::Default(span) => {
2234                     let LoweredNodeId { node_id, hir_id } = this.next_id();
2235                     P(hir::Ty {
2236                         id: node_id,
2237                         hir_id: hir_id,
2238                         node: hir::TyKind::Tup(hir_vec![]),
2239                         span: *span,
2240                     })
2241                 }
2242             };
2243
2244             // "<Output = T>"
2245             let future_params = P(hir::GenericArgs {
2246                 args: hir_vec![],
2247                 bindings: hir_vec![hir::TypeBinding {
2248                     ident: Ident::from_str(FN_OUTPUT_NAME),
2249                     ty: output_ty,
2250                     id: this.next_id().node_id,
2251                     span,
2252                 }],
2253                 parenthesized: false,
2254             });
2255
2256             let future_path =
2257                 this.std_path(span, &["future", "Future"], Some(future_params), false);
2258
2259             let LoweredNodeId { node_id, hir_id } = this.next_id();
2260             let mut bounds = vec![
2261                 hir::GenericBound::Trait(
2262                     hir::PolyTraitRef {
2263                         trait_ref: hir::TraitRef {
2264                             path: future_path,
2265                             ref_id: node_id,
2266                             hir_ref_id: hir_id,
2267                         },
2268                         bound_generic_params: hir_vec![],
2269                         span,
2270                     },
2271                     hir::TraitBoundModifier::None
2272                 ),
2273             ];
2274
2275             if let Some((name, span)) = bound_lifetime {
2276                 bounds.push(hir::GenericBound::Outlives(
2277                     hir::Lifetime { id: this.next_id().node_id, name, span }));
2278             }
2279
2280             hir::HirVec::from(bounds)
2281         });
2282
2283         let LoweredNodeId { node_id, hir_id } = self.next_id();
2284         let impl_trait_ty = P(hir::Ty {
2285             id: node_id,
2286             node: impl_trait_ty,
2287             span,
2288             hir_id,
2289         });
2290
2291         hir::FunctionRetTy::Return(impl_trait_ty)
2292     }
2293
2294     fn lower_param_bound(
2295         &mut self,
2296         tpb: &GenericBound,
2297         itctx: ImplTraitContext<'_>,
2298     ) -> hir::GenericBound {
2299         match *tpb {
2300             GenericBound::Trait(ref ty, modifier) => {
2301                 hir::GenericBound::Trait(
2302                     self.lower_poly_trait_ref(ty, itctx),
2303                     self.lower_trait_bound_modifier(modifier),
2304                 )
2305             }
2306             GenericBound::Outlives(ref lifetime) => {
2307                 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2308             }
2309         }
2310     }
2311
2312     fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2313         let span = l.ident.span;
2314         match l.ident {
2315             ident if ident.name == keywords::StaticLifetime.name() =>
2316                 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2317             ident if ident.name == keywords::UnderscoreLifetime.name() =>
2318                 match self.anonymous_lifetime_mode {
2319                     AnonymousLifetimeMode::CreateParameter => {
2320                         let fresh_name = self.collect_fresh_in_band_lifetime(span);
2321                         self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2322                     }
2323
2324                     AnonymousLifetimeMode::PassThrough => {
2325                         self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2326                     }
2327
2328                     AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2329                 },
2330             ident => {
2331                 self.maybe_collect_in_band_lifetime(ident);
2332                 let param_name = ParamName::Plain(ident);
2333                 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2334             }
2335         }
2336     }
2337
2338     fn new_named_lifetime(
2339         &mut self,
2340         id: NodeId,
2341         span: Span,
2342         name: hir::LifetimeName,
2343     ) -> hir::Lifetime {
2344         hir::Lifetime {
2345             id: self.lower_node_id(id).node_id,
2346             span,
2347             name: name,
2348         }
2349     }
2350
2351     fn lower_generic_params(
2352         &mut self,
2353         params: &[GenericParam],
2354         add_bounds: &NodeMap<Vec<GenericBound>>,
2355         mut itctx: ImplTraitContext<'_>,
2356     ) -> hir::HirVec<hir::GenericParam> {
2357         params.iter().map(|param| {
2358             self.lower_generic_param(param, add_bounds, itctx.reborrow())
2359         }).collect()
2360     }
2361
2362     fn lower_generic_param(&mut self,
2363                            param: &GenericParam,
2364                            add_bounds: &NodeMap<Vec<GenericBound>>,
2365                            mut itctx: ImplTraitContext<'_>)
2366                            -> hir::GenericParam {
2367         let mut bounds = self.with_anonymous_lifetime_mode(
2368             AnonymousLifetimeMode::ReportError,
2369             |this| this.lower_param_bounds(&param.bounds, itctx.reborrow()),
2370         );
2371
2372         match param.kind {
2373             GenericParamKind::Lifetime => {
2374                 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2375                 self.is_collecting_in_band_lifetimes = false;
2376
2377                 let lt = self.with_anonymous_lifetime_mode(
2378                     AnonymousLifetimeMode::ReportError,
2379                     |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2380                 );
2381                 let param_name = match lt.name {
2382                     hir::LifetimeName::Param(param_name) => param_name,
2383                     hir::LifetimeName::Implicit
2384                         | hir::LifetimeName::Underscore
2385                         | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2386                     hir::LifetimeName::Error => ParamName::Error,
2387                 };
2388                 let param = hir::GenericParam {
2389                     id: lt.id,
2390                     name: param_name,
2391                     span: lt.span,
2392                     pure_wrt_drop: attr::contains_name(&param.attrs, "may_dangle"),
2393                     attrs: self.lower_attrs(&param.attrs),
2394                     bounds,
2395                     kind: hir::GenericParamKind::Lifetime {
2396                         kind: hir::LifetimeParamKind::Explicit,
2397                     }
2398                 };
2399
2400                 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2401
2402                 param
2403             }
2404             GenericParamKind::Type { ref default, .. } => {
2405                 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2406                 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2407                 // Instead, use gensym("Self") to create a distinct name that looks the same.
2408                 let ident = if param.ident.name == keywords::SelfType.name() {
2409                     param.ident.gensym()
2410                 } else {
2411                     param.ident
2412                 };
2413
2414                 let add_bounds = add_bounds.get(&param.id).map_or(&[][..], |x| &x);
2415                 if !add_bounds.is_empty() {
2416                     let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2417                     bounds = bounds.into_iter()
2418                                    .chain(params)
2419                                    .collect();
2420                 }
2421
2422                 hir::GenericParam {
2423                     id: self.lower_node_id(param.id).node_id,
2424                     name: hir::ParamName::Plain(ident),
2425                     pure_wrt_drop: attr::contains_name(&param.attrs, "may_dangle"),
2426                     attrs: self.lower_attrs(&param.attrs),
2427                     bounds,
2428                     span: ident.span,
2429                     kind: hir::GenericParamKind::Type {
2430                         default: default.as_ref().map(|x| {
2431                             self.lower_ty(x, ImplTraitContext::disallowed())
2432                         }),
2433                         synthetic: param.attrs.iter()
2434                                               .filter(|attr| attr.check_name("rustc_synthetic"))
2435                                               .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2436                                               .next(),
2437                     }
2438                 }
2439             }
2440         }
2441     }
2442
2443     fn lower_generics(
2444         &mut self,
2445         generics: &Generics,
2446         itctx: ImplTraitContext<'_>)
2447         -> hir::Generics
2448     {
2449         // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2450         // FIXME: This could probably be done with less rightward drift. Also looks like two control
2451         //        paths where report_error is called are also the only paths that advance to after
2452         //        the match statement, so the error reporting could probably just be moved there.
2453         let mut add_bounds: NodeMap<Vec<_>> = NodeMap();
2454         for pred in &generics.where_clause.predicates {
2455             if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2456                 'next_bound: for bound in &bound_pred.bounds {
2457                     if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2458                         let report_error = |this: &mut Self| {
2459                             this.diagnostic().span_err(
2460                                 bound_pred.bounded_ty.span,
2461                                 "`?Trait` bounds are only permitted at the \
2462                                  point where a type parameter is declared",
2463                             );
2464                         };
2465                         // Check if the where clause type is a plain type parameter.
2466                         match bound_pred.bounded_ty.node {
2467                             TyKind::Path(None, ref path)
2468                                 if path.segments.len() == 1
2469                                     && bound_pred.bound_generic_params.is_empty() =>
2470                             {
2471                                 if let Some(Def::TyParam(def_id)) = self.resolver
2472                                     .get_resolution(bound_pred.bounded_ty.id)
2473                                     .map(|d| d.base_def())
2474                                 {
2475                                     if let Some(node_id) =
2476                                         self.resolver.definitions().as_local_node_id(def_id)
2477                                     {
2478                                         for param in &generics.params {
2479                                             match param.kind {
2480                                                 GenericParamKind::Type { .. } => {
2481                                                     if node_id == param.id {
2482                                                         add_bounds.entry(param.id)
2483                                                             .or_default()
2484                                                             .push(bound.clone());
2485                                                         continue 'next_bound;
2486                                                     }
2487                                                 }
2488                                                 _ => {}
2489                                             }
2490                                         }
2491                                     }
2492                                 }
2493                                 report_error(self)
2494                             }
2495                             _ => report_error(self),
2496                         }
2497                     }
2498                 }
2499             }
2500         }
2501
2502         hir::Generics {
2503             params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2504             where_clause: self.lower_where_clause(&generics.where_clause),
2505             span: generics.span,
2506         }
2507     }
2508
2509     fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2510         self.with_anonymous_lifetime_mode(
2511             AnonymousLifetimeMode::ReportError,
2512             |this| {
2513                 hir::WhereClause {
2514                     id: this.lower_node_id(wc.id).node_id,
2515                     predicates: wc.predicates
2516                         .iter()
2517                         .map(|predicate| this.lower_where_predicate(predicate))
2518                         .collect(),
2519                 }
2520             },
2521         )
2522     }
2523
2524     fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2525         match *pred {
2526             WherePredicate::BoundPredicate(WhereBoundPredicate {
2527                 ref bound_generic_params,
2528                 ref bounded_ty,
2529                 ref bounds,
2530                 span,
2531             }) => {
2532                 self.with_in_scope_lifetime_defs(
2533                     &bound_generic_params,
2534                     |this| {
2535                         hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2536                             bound_generic_params: this.lower_generic_params(
2537                                 bound_generic_params,
2538                                 &NodeMap(),
2539                                 ImplTraitContext::disallowed(),
2540                             ),
2541                             bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
2542                             bounds: bounds
2543                                 .iter()
2544                                 .filter_map(|bound| match *bound {
2545                                     // Ignore `?Trait` bounds.
2546                                     // Tthey were copied into type parameters already.
2547                                     GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
2548                                     _ => Some(this.lower_param_bound(
2549                                         bound,
2550                                         ImplTraitContext::disallowed(),
2551                                     )),
2552                                 })
2553                                 .collect(),
2554                             span,
2555                         })
2556                     },
2557                 )
2558             }
2559             WherePredicate::RegionPredicate(WhereRegionPredicate {
2560                 ref lifetime,
2561                 ref bounds,
2562                 span,
2563             }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2564                 span,
2565                 lifetime: self.lower_lifetime(lifetime),
2566                 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2567             }),
2568             WherePredicate::EqPredicate(WhereEqPredicate {
2569                 id,
2570                 ref lhs_ty,
2571                 ref rhs_ty,
2572                 span,
2573             }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2574                 id: self.lower_node_id(id).node_id,
2575                 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
2576                 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
2577                 span,
2578             }),
2579         }
2580     }
2581
2582     fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2583         match *vdata {
2584             VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2585                 fields
2586                     .iter()
2587                     .enumerate()
2588                     .map(|f| self.lower_struct_field(f))
2589                     .collect(),
2590                 self.lower_node_id(id).node_id,
2591             ),
2592             VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2593                 fields
2594                     .iter()
2595                     .enumerate()
2596                     .map(|f| self.lower_struct_field(f))
2597                     .collect(),
2598                 self.lower_node_id(id).node_id,
2599             ),
2600             VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2601         }
2602     }
2603
2604     fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2605         let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2606             hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2607             qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2608         };
2609         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.ref_id);
2610         hir::TraitRef {
2611             path,
2612             ref_id: node_id,
2613             hir_ref_id: hir_id,
2614         }
2615     }
2616
2617     fn lower_poly_trait_ref(
2618         &mut self,
2619         p: &PolyTraitRef,
2620         mut itctx: ImplTraitContext<'_>,
2621     ) -> hir::PolyTraitRef {
2622         let bound_generic_params =
2623             self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx.reborrow());
2624         let trait_ref = self.with_parent_impl_lifetime_defs(
2625             &bound_generic_params,
2626             |this| this.lower_trait_ref(&p.trait_ref, itctx),
2627         );
2628
2629         hir::PolyTraitRef {
2630             bound_generic_params,
2631             trait_ref,
2632             span: p.span,
2633         }
2634     }
2635
2636     fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2637         hir::StructField {
2638             span: f.span,
2639             id: self.lower_node_id(f.id).node_id,
2640             ident: match f.ident {
2641                 Some(ident) => ident,
2642                 // FIXME(jseyfried) positional field hygiene
2643                 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2644             },
2645             vis: self.lower_visibility(&f.vis, None),
2646             ty: self.lower_ty(&f.ty, ImplTraitContext::disallowed()),
2647             attrs: self.lower_attrs(&f.attrs),
2648         }
2649     }
2650
2651     fn lower_field(&mut self, f: &Field) -> hir::Field {
2652         hir::Field {
2653             id: self.next_id().node_id,
2654             ident: f.ident,
2655             expr: P(self.lower_expr(&f.expr)),
2656             span: f.span,
2657             is_shorthand: f.is_shorthand,
2658         }
2659     }
2660
2661     fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2662         hir::MutTy {
2663             ty: self.lower_ty(&mt.ty, itctx),
2664             mutbl: self.lower_mutability(mt.mutbl),
2665         }
2666     }
2667
2668     fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2669         -> hir::GenericBounds {
2670         bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2671     }
2672
2673     fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2674         let mut expr = None;
2675
2676         let mut stmts = vec![];
2677
2678         for (index, stmt) in b.stmts.iter().enumerate() {
2679             if index == b.stmts.len() - 1 {
2680                 if let StmtKind::Expr(ref e) = stmt.node {
2681                     expr = Some(P(self.lower_expr(e)));
2682                 } else {
2683                     stmts.extend(self.lower_stmt(stmt));
2684                 }
2685             } else {
2686                 stmts.extend(self.lower_stmt(stmt));
2687             }
2688         }
2689
2690         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2691
2692         P(hir::Block {
2693             id: node_id,
2694             hir_id,
2695             stmts: stmts.into(),
2696             expr,
2697             rules: self.lower_block_check_mode(&b.rules),
2698             span: b.span,
2699             targeted_by_break,
2700             recovered: b.recovered,
2701         })
2702     }
2703
2704     fn lower_async_body(
2705         &mut self,
2706         decl: &FnDecl,
2707         asyncness: IsAsync,
2708         body: &Block,
2709     ) -> hir::BodyId {
2710         self.lower_body(Some(decl), |this| {
2711             if let IsAsync::Async { closure_id, .. } = asyncness {
2712                 let async_expr = this.make_async_expr(
2713                     CaptureBy::Value, closure_id, None,
2714                     |this| {
2715                         let body = this.lower_block(body, false);
2716                         this.expr_block(body, ThinVec::new())
2717                     });
2718                 this.expr(body.span, async_expr, ThinVec::new())
2719             } else {
2720                 let body = this.lower_block(body, false);
2721                 this.expr_block(body, ThinVec::new())
2722             }
2723         })
2724     }
2725
2726     fn lower_item_kind(
2727         &mut self,
2728         id: NodeId,
2729         name: &mut Name,
2730         attrs: &hir::HirVec<Attribute>,
2731         vis: &mut hir::Visibility,
2732         i: &ItemKind,
2733     ) -> hir::ItemKind {
2734         match *i {
2735             ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
2736             ItemKind::Use(ref use_tree) => {
2737                 // Start with an empty prefix
2738                 let prefix = Path {
2739                     segments: vec![],
2740                     span: use_tree.span,
2741                 };
2742
2743                 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2744             }
2745             ItemKind::Static(ref t, m, ref e) => {
2746                 let value = self.lower_body(None, |this| this.lower_expr(e));
2747                 hir::ItemKind::Static(
2748                     self.lower_ty(
2749                         t,
2750                         if self.sess.features_untracked().impl_trait_in_bindings {
2751                             ImplTraitContext::Existential(None)
2752                         } else {
2753                             ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2754                         }
2755                     ),
2756                     self.lower_mutability(m),
2757                     value,
2758                 )
2759             }
2760             ItemKind::Const(ref t, ref e) => {
2761                 let value = self.lower_body(None, |this| this.lower_expr(e));
2762                 hir::ItemKind::Const(
2763                     self.lower_ty(
2764                         t,
2765                         if self.sess.features_untracked().impl_trait_in_bindings {
2766                             ImplTraitContext::Existential(None)
2767                         } else {
2768                             ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2769                         }
2770                     ),
2771                     value
2772                 )
2773             }
2774             ItemKind::Fn(ref decl, header, ref generics, ref body) => {
2775                 let fn_def_id = self.resolver.definitions().local_def_id(id);
2776                 self.with_new_scopes(|this| {
2777                     // Note: we don't need to change the return type from `T` to
2778                     // `impl Future<Output = T>` here because lower_body
2779                     // only cares about the input argument patterns in the function
2780                     // declaration (decl), not the return types.
2781                     let body_id = this.lower_async_body(decl, header.asyncness, body);
2782
2783                     let (generics, fn_decl) = this.add_in_band_defs(
2784                         generics,
2785                         fn_def_id,
2786                         AnonymousLifetimeMode::PassThrough,
2787                         |this, idty| this.lower_fn_decl(
2788                             decl,
2789                             Some((fn_def_id, idty)),
2790                             true,
2791                             header.asyncness.opt_return_id()
2792                         ),
2793                     );
2794
2795                     hir::ItemKind::Fn(
2796                         fn_decl,
2797                         this.lower_fn_header(header),
2798                         generics,
2799                         body_id,
2800                     )
2801                 })
2802             }
2803             ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
2804             ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
2805             ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
2806             ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
2807                 self.lower_ty(t, ImplTraitContext::disallowed()),
2808                 self.lower_generics(generics, ImplTraitContext::disallowed()),
2809             ),
2810             ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(hir::ExistTy {
2811                 generics: self.lower_generics(generics, ImplTraitContext::disallowed()),
2812                 bounds: self.lower_param_bounds(b, ImplTraitContext::disallowed()),
2813                 impl_trait_fn: None,
2814             }),
2815             ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum(
2816                 hir::EnumDef {
2817                     variants: enum_definition
2818                         .variants
2819                         .iter()
2820                         .map(|x| self.lower_variant(x))
2821                         .collect(),
2822                 },
2823                 self.lower_generics(generics, ImplTraitContext::disallowed()),
2824             ),
2825             ItemKind::Struct(ref struct_def, ref generics) => {
2826                 let struct_def = self.lower_variant_data(struct_def);
2827                 hir::ItemKind::Struct(
2828                     struct_def,
2829                     self.lower_generics(generics, ImplTraitContext::disallowed()),
2830                 )
2831             }
2832             ItemKind::Union(ref vdata, ref generics) => {
2833                 let vdata = self.lower_variant_data(vdata);
2834                 hir::ItemKind::Union(
2835                     vdata,
2836                     self.lower_generics(generics, ImplTraitContext::disallowed()),
2837                 )
2838             }
2839             ItemKind::Impl(
2840                 unsafety,
2841                 polarity,
2842                 defaultness,
2843                 ref ast_generics,
2844                 ref trait_ref,
2845                 ref ty,
2846                 ref impl_items,
2847             ) => {
2848                 let def_id = self.resolver.definitions().local_def_id(id);
2849
2850                 // Lower the "impl header" first. This ordering is important
2851                 // for in-band lifetimes! Consider `'a` here:
2852                 //
2853                 //     impl Foo<'a> for u32 {
2854                 //         fn method(&'a self) { .. }
2855                 //     }
2856                 //
2857                 // Because we start by lowering the `Foo<'a> for u32`
2858                 // part, we will add `'a` to the list of generics on
2859                 // the impl. When we then encounter it later in the
2860                 // method, it will not be considered an in-band
2861                 // lifetime to be added, but rather a reference to a
2862                 // parent lifetime.
2863                 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2864                     ast_generics,
2865                     def_id,
2866                     AnonymousLifetimeMode::CreateParameter,
2867                     |this, _| {
2868                         let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2869                             this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
2870                         });
2871
2872                         if let Some(ref trait_ref) = trait_ref {
2873                             if let Def::Trait(def_id) = trait_ref.path.def {
2874                                 this.trait_impls.entry(def_id).or_default().push(id);
2875                             }
2876                         }
2877
2878                         let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
2879
2880                         (trait_ref, lowered_ty)
2881                     },
2882                 );
2883
2884                 let new_impl_items = self.with_in_scope_lifetime_defs(
2885                     &ast_generics.params,
2886                     |this| {
2887                         impl_items
2888                             .iter()
2889                             .map(|item| this.lower_impl_item_ref(item))
2890                             .collect()
2891                     },
2892                 );
2893
2894                 hir::ItemKind::Impl(
2895                     self.lower_unsafety(unsafety),
2896                     self.lower_impl_polarity(polarity),
2897                     self.lower_defaultness(defaultness, true /* [1] */),
2898                     generics,
2899                     trait_ref,
2900                     lowered_ty,
2901                     new_impl_items,
2902                 )
2903             }
2904             ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2905                 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
2906                 let items = items
2907                     .iter()
2908                     .map(|item| self.lower_trait_item_ref(item))
2909                     .collect();
2910                 hir::ItemKind::Trait(
2911                     self.lower_is_auto(is_auto),
2912                     self.lower_unsafety(unsafety),
2913                     self.lower_generics(generics, ImplTraitContext::disallowed()),
2914                     bounds,
2915                     items,
2916                 )
2917             }
2918             ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
2919                 self.lower_generics(generics, ImplTraitContext::disallowed()),
2920                 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
2921             ),
2922             ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2923         }
2924
2925         // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2926         //     not cause an assertion failure inside the `lower_defaultness` function
2927     }
2928
2929     fn lower_use_tree(
2930         &mut self,
2931         tree: &UseTree,
2932         prefix: &Path,
2933         id: NodeId,
2934         vis: &mut hir::Visibility,
2935         name: &mut Name,
2936         attrs: &hir::HirVec<Attribute>,
2937     ) -> hir::ItemKind {
2938         let path = &tree.prefix;
2939
2940         match tree.kind {
2941             UseTreeKind::Simple(rename, id1, id2) => {
2942                 *name = tree.ident().name;
2943
2944                 // First apply the prefix to the path
2945                 let mut path = Path {
2946                     segments: prefix
2947                         .segments
2948                         .iter()
2949                         .chain(path.segments.iter())
2950                         .cloned()
2951                         .collect(),
2952                     span: path.span,
2953                 };
2954
2955                 // Correctly resolve `self` imports
2956                 if path.segments.len() > 1
2957                     && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2958                 {
2959                     let _ = path.segments.pop();
2960                     if rename.is_none() {
2961                         *name = path.segments.last().unwrap().ident.name;
2962                     }
2963                 }
2964
2965                 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2966                 let mut defs = self.expect_full_def_from_use(id);
2967                 // we want to return *something* from this function, so hang onto the first item
2968                 // for later
2969                 let ret_def = defs.next().unwrap_or(Def::Err);
2970
2971                 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2972                     let vis = vis.clone();
2973                     let name = name.clone();
2974                     let span = path.span;
2975                     self.resolver.definitions().create_def_with_parent(
2976                         parent_def_index,
2977                         new_node_id,
2978                         DefPathData::Misc,
2979                         DefIndexAddressSpace::High,
2980                         Mark::root(),
2981                         span);
2982                     self.allocate_hir_id_counter(new_node_id, &path);
2983
2984                     self.with_hir_id_owner(new_node_id, |this| {
2985                         let new_id = this.lower_node_id(new_node_id);
2986                         let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2987                         let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
2988                         let vis_kind = match vis.node {
2989                             hir::VisibilityKind::Public => hir::VisibilityKind::Public,
2990                             hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
2991                             hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
2992                             hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
2993                                 let id = this.next_id();
2994                                 hir::VisibilityKind::Restricted {
2995                                     path: path.clone(),
2996                                     // We are allocating a new NodeId here
2997                                     id: id.node_id,
2998                                     hir_id: id.hir_id,
2999                                 }
3000                             }
3001                         };
3002                         let vis = respan(vis.span, vis_kind);
3003
3004                         this.items.insert(
3005                             new_id.node_id,
3006                             hir::Item {
3007                                 id: new_id.node_id,
3008                                 hir_id: new_id.hir_id,
3009                                 name: name,
3010                                 attrs: attrs.clone(),
3011                                 node: item,
3012                                 vis,
3013                                 span,
3014                             },
3015                         );
3016                     });
3017                 }
3018
3019                 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
3020                 hir::ItemKind::Use(path, hir::UseKind::Single)
3021             }
3022             UseTreeKind::Glob => {
3023                 let path = P(self.lower_path(
3024                     id,
3025                     &Path {
3026                         segments: prefix
3027                             .segments
3028                             .iter()
3029                             .chain(path.segments.iter())
3030                             .cloned()
3031                             .collect(),
3032                         span: path.span,
3033                     },
3034                     ParamMode::Explicit,
3035                 ));
3036                 hir::ItemKind::Use(path, hir::UseKind::Glob)
3037             }
3038             UseTreeKind::Nested(ref trees) => {
3039                 let prefix = Path {
3040                     segments: prefix
3041                         .segments
3042                         .iter()
3043                         .chain(path.segments.iter())
3044                         .cloned()
3045                         .collect(),
3046                     span: prefix.span.to(path.span),
3047                 };
3048
3049                 // Add all the nested PathListItems in the HIR
3050                 for &(ref use_tree, id) in trees {
3051                     self.allocate_hir_id_counter(id, &use_tree);
3052                     let LoweredNodeId {
3053                         node_id: new_id,
3054                         hir_id: new_hir_id,
3055                     } = self.lower_node_id(id);
3056
3057                     let mut vis = vis.clone();
3058                     let mut name = name.clone();
3059                     let item =
3060                         self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
3061
3062                     self.with_hir_id_owner(new_id, |this| {
3063                         let vis_kind = match vis.node {
3064                             hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3065                             hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3066                             hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3067                             hir::VisibilityKind::Restricted { ref path, id: _, hir_id: _ } => {
3068                                 let id = this.next_id();
3069                                 hir::VisibilityKind::Restricted {
3070                                     path: path.clone(),
3071                                     // We are allocating a new NodeId here
3072                                     id: id.node_id,
3073                                     hir_id: id.hir_id,
3074                                 }
3075                             }
3076                         };
3077                         let vis = respan(vis.span, vis_kind);
3078
3079                         this.items.insert(
3080                             new_id,
3081                             hir::Item {
3082                                 id: new_id,
3083                                 hir_id: new_hir_id,
3084                                 name: name,
3085                                 attrs: attrs.clone(),
3086                                 node: item,
3087                                 vis,
3088                                 span: use_tree.span,
3089                             },
3090                         );
3091                     });
3092                 }
3093
3094                 // Privatize the degenerate import base, used only to check
3095                 // the stability of `use a::{};`, to avoid it showing up as
3096                 // a re-export by accident when `pub`, e.g. in documentation.
3097                 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
3098                 *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3099                 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3100             }
3101         }
3102     }
3103
3104     fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3105         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3106         let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
3107
3108         let (generics, node) = match i.node {
3109             TraitItemKind::Const(ref ty, ref default) => (
3110                 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3111                 hir::TraitItemKind::Const(
3112                     self.lower_ty(ty, ImplTraitContext::disallowed()),
3113                     default
3114                         .as_ref()
3115                         .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
3116                 ),
3117             ),
3118             TraitItemKind::Method(ref sig, None) => {
3119                 let names = self.lower_fn_args_to_names(&sig.decl);
3120                 let (generics, sig) = self.lower_method_sig(
3121                     &i.generics,
3122                     sig,
3123                     trait_item_def_id,
3124                     false,
3125                     None,
3126                 );
3127                 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3128             }
3129             TraitItemKind::Method(ref sig, Some(ref body)) => {
3130                 let body_id = self.lower_body(Some(&sig.decl), |this| {
3131                     let body = this.lower_block(body, false);
3132                     this.expr_block(body, ThinVec::new())
3133                 });
3134                 let (generics, sig) = self.lower_method_sig(
3135                     &i.generics,
3136                     sig,
3137                     trait_item_def_id,
3138                     false,
3139                     None,
3140                 );
3141                 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3142             }
3143             TraitItemKind::Type(ref bounds, ref default) => (
3144                 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3145                 hir::TraitItemKind::Type(
3146                     self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3147                     default
3148                         .as_ref()
3149                         .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3150                 ),
3151             ),
3152             TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3153         };
3154
3155         hir::TraitItem {
3156             id: node_id,
3157             hir_id,
3158             ident: i.ident,
3159             attrs: self.lower_attrs(&i.attrs),
3160             generics,
3161             node,
3162             span: i.span,
3163         }
3164     }
3165
3166     fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3167         let (kind, has_default) = match i.node {
3168             TraitItemKind::Const(_, ref default) => {
3169                 (hir::AssociatedItemKind::Const, default.is_some())
3170             }
3171             TraitItemKind::Type(_, ref default) => {
3172                 (hir::AssociatedItemKind::Type, default.is_some())
3173             }
3174             TraitItemKind::Method(ref sig, ref default) => (
3175                 hir::AssociatedItemKind::Method {
3176                     has_self: sig.decl.has_self(),
3177                 },
3178                 default.is_some(),
3179             ),
3180             TraitItemKind::Macro(..) => unimplemented!(),
3181         };
3182         hir::TraitItemRef {
3183             id: hir::TraitItemId { node_id: i.id },
3184             ident: i.ident,
3185             span: i.span,
3186             defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3187             kind,
3188         }
3189     }
3190
3191     fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3192         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3193         let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
3194
3195         let (generics, node) = match i.node {
3196             ImplItemKind::Const(ref ty, ref expr) => {
3197                 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
3198                 (
3199                     self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3200                     hir::ImplItemKind::Const(
3201                         self.lower_ty(ty, ImplTraitContext::disallowed()),
3202                         body_id,
3203                     ),
3204                 )
3205             }
3206             ImplItemKind::Method(ref sig, ref body) => {
3207                 let body_id = self.lower_async_body(&sig.decl, sig.header.asyncness, body);
3208                 let impl_trait_return_allow = !self.is_in_trait_impl;
3209                 let (generics, sig) = self.lower_method_sig(
3210                     &i.generics,
3211                     sig,
3212                     impl_item_def_id,
3213                     impl_trait_return_allow,
3214                     sig.header.asyncness.opt_return_id(),
3215                 );
3216                 (generics, hir::ImplItemKind::Method(sig, body_id))
3217             }
3218             ImplItemKind::Type(ref ty) => (
3219                 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3220                 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3221             ),
3222             ImplItemKind::Existential(ref bounds) => (
3223                 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3224                 hir::ImplItemKind::Existential(
3225                     self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3226                 ),
3227             ),
3228             ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
3229         };
3230
3231         hir::ImplItem {
3232             id: node_id,
3233             hir_id,
3234             ident: i.ident,
3235             attrs: self.lower_attrs(&i.attrs),
3236             generics,
3237             vis: self.lower_visibility(&i.vis, None),
3238             defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3239             node,
3240             span: i.span,
3241         }
3242
3243         // [1] since `default impl` is not yet implemented, this is always true in impls
3244     }
3245
3246     fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3247         hir::ImplItemRef {
3248             id: hir::ImplItemId { node_id: i.id },
3249             ident: i.ident,
3250             span: i.span,
3251             vis: self.lower_visibility(&i.vis, Some(i.id)),
3252             defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3253             kind: match i.node {
3254                 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
3255                 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
3256                 ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential,
3257                 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
3258                     has_self: sig.decl.has_self(),
3259                 },
3260                 ImplItemKind::Macro(..) => unimplemented!(),
3261             },
3262         }
3263
3264         // [1] since `default impl` is not yet implemented, this is always true in impls
3265     }
3266
3267     fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3268         hir::Mod {
3269             inner: m.inner,
3270             item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3271         }
3272     }
3273
3274     fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3275         match i.node {
3276             ItemKind::Use(ref use_tree) => {
3277                 let mut vec = smallvec![hir::ItemId { id: i.id }];
3278                 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3279                 vec
3280             }
3281             ItemKind::MacroDef(..) => SmallVec::new(),
3282             ItemKind::Fn(..) |
3283             ItemKind::Impl(.., None, _, _) => smallvec![hir::ItemId { id: i.id }],
3284             ItemKind::Static(ref ty, ..) => {
3285                 let mut ids = smallvec![hir::ItemId { id: i.id }];
3286                 if self.sess.features_untracked().impl_trait_in_bindings {
3287                     let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3288                     visitor.visit_ty(ty);
3289                 }
3290                 ids
3291             },
3292             ItemKind::Const(ref ty, ..) => {
3293                 let mut ids = smallvec![hir::ItemId { id: i.id }];
3294                 if self.sess.features_untracked().impl_trait_in_bindings {
3295                     let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3296                     visitor.visit_ty(ty);
3297                 }
3298                 ids
3299             },
3300             _ => smallvec![hir::ItemId { id: i.id }],
3301         }
3302     }
3303
3304     fn lower_item_id_use_tree(&mut self,
3305                               tree: &UseTree,
3306                               base_id: NodeId,
3307                               vec: &mut SmallVec<[hir::ItemId; 1]>)
3308     {
3309         match tree.kind {
3310             UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3311                 vec.push(hir::ItemId { id });
3312                 self.lower_item_id_use_tree(nested, id, vec);
3313             },
3314             UseTreeKind::Glob => {}
3315             UseTreeKind::Simple(_, id1, id2) => {
3316                 for (_, &id) in self.expect_full_def_from_use(base_id)
3317                                     .skip(1)
3318                                     .zip([id1, id2].iter())
3319                 {
3320                     vec.push(hir::ItemId { id });
3321                 }
3322             },
3323         }
3324     }
3325
3326     pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
3327         let mut name = i.ident.name;
3328         let mut vis = self.lower_visibility(&i.vis, None);
3329         let attrs = self.lower_attrs(&i.attrs);
3330         if let ItemKind::MacroDef(ref def) = i.node {
3331             if !def.legacy || attr::contains_name(&i.attrs, "macro_export") ||
3332                               attr::contains_name(&i.attrs, "rustc_doc_only_macro") {
3333                 let body = self.lower_token_stream(def.stream());
3334                 self.exported_macros.push(hir::MacroDef {
3335                     name,
3336                     vis,
3337                     attrs,
3338                     id: i.id,
3339                     span: i.span,
3340                     body,
3341                     legacy: def.legacy,
3342                 });
3343             }
3344             return None;
3345         }
3346
3347         let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
3348
3349         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
3350
3351         Some(hir::Item {
3352             id: node_id,
3353             hir_id,
3354             name,
3355             attrs,
3356             node,
3357             vis,
3358             span: i.span,
3359         })
3360     }
3361
3362     fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
3363         let node_id = self.lower_node_id(i.id).node_id;
3364         let def_id = self.resolver.definitions().local_def_id(node_id);
3365         hir::ForeignItem {
3366             id: node_id,
3367             name: i.ident.name,
3368             attrs: self.lower_attrs(&i.attrs),
3369             node: match i.node {
3370                 ForeignItemKind::Fn(ref fdec, ref generics) => {
3371                     let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
3372                         generics,
3373                         def_id,
3374                         AnonymousLifetimeMode::PassThrough,
3375                         |this, _| {
3376                             (
3377                                 // Disallow impl Trait in foreign items
3378                                 this.lower_fn_decl(fdec, None, false, None),
3379                                 this.lower_fn_args_to_names(fdec),
3380                             )
3381                         },
3382                     );
3383
3384                     hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
3385                 }
3386                 ForeignItemKind::Static(ref t, m) => {
3387                     hir::ForeignItemKind::Static(
3388                         self.lower_ty(t, ImplTraitContext::disallowed()), m)
3389                 }
3390                 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
3391                 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
3392             },
3393             vis: self.lower_visibility(&i.vis, None),
3394             span: i.span,
3395         }
3396     }
3397
3398     fn lower_method_sig(
3399         &mut self,
3400         generics: &Generics,
3401         sig: &MethodSig,
3402         fn_def_id: DefId,
3403         impl_trait_return_allow: bool,
3404         is_async: Option<NodeId>,
3405     ) -> (hir::Generics, hir::MethodSig) {
3406         let header = self.lower_fn_header(sig.header);
3407         let (generics, decl) = self.add_in_band_defs(
3408             generics,
3409             fn_def_id,
3410             AnonymousLifetimeMode::PassThrough,
3411             |this, idty| this.lower_fn_decl(
3412                 &sig.decl,
3413                 Some((fn_def_id, idty)),
3414                 impl_trait_return_allow,
3415                 is_async,
3416             ),
3417         );
3418         (generics, hir::MethodSig { header, decl })
3419     }
3420
3421     fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
3422         match a {
3423             IsAuto::Yes => hir::IsAuto::Yes,
3424             IsAuto::No => hir::IsAuto::No,
3425         }
3426     }
3427
3428     fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
3429         hir::FnHeader {
3430             unsafety: self.lower_unsafety(h.unsafety),
3431             asyncness: self.lower_asyncness(h.asyncness),
3432             constness: self.lower_constness(h.constness),
3433             abi: h.abi,
3434         }
3435     }
3436
3437     fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
3438         match u {
3439             Unsafety::Unsafe => hir::Unsafety::Unsafe,
3440             Unsafety::Normal => hir::Unsafety::Normal,
3441         }
3442     }
3443
3444     fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
3445         match c.node {
3446             Constness::Const => hir::Constness::Const,
3447             Constness::NotConst => hir::Constness::NotConst,
3448         }
3449     }
3450
3451     fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
3452         match a {
3453             IsAsync::Async { .. } => hir::IsAsync::Async,
3454             IsAsync::NotAsync => hir::IsAsync::NotAsync,
3455         }
3456     }
3457
3458     fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
3459         match u {
3460             UnOp::Deref => hir::UnDeref,
3461             UnOp::Not => hir::UnNot,
3462             UnOp::Neg => hir::UnNeg,
3463         }
3464     }
3465
3466     fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
3467         Spanned {
3468             node: match b.node {
3469                 BinOpKind::Add => hir::BinOpKind::Add,
3470                 BinOpKind::Sub => hir::BinOpKind::Sub,
3471                 BinOpKind::Mul => hir::BinOpKind::Mul,
3472                 BinOpKind::Div => hir::BinOpKind::Div,
3473                 BinOpKind::Rem => hir::BinOpKind::Rem,
3474                 BinOpKind::And => hir::BinOpKind::And,
3475                 BinOpKind::Or => hir::BinOpKind::Or,
3476                 BinOpKind::BitXor => hir::BinOpKind::BitXor,
3477                 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
3478                 BinOpKind::BitOr => hir::BinOpKind::BitOr,
3479                 BinOpKind::Shl => hir::BinOpKind::Shl,
3480                 BinOpKind::Shr => hir::BinOpKind::Shr,
3481                 BinOpKind::Eq => hir::BinOpKind::Eq,
3482                 BinOpKind::Lt => hir::BinOpKind::Lt,
3483                 BinOpKind::Le => hir::BinOpKind::Le,
3484                 BinOpKind::Ne => hir::BinOpKind::Ne,
3485                 BinOpKind::Ge => hir::BinOpKind::Ge,
3486                 BinOpKind::Gt => hir::BinOpKind::Gt,
3487             },
3488             span: b.span,
3489         }
3490     }
3491
3492     fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
3493         let node = match p.node {
3494             PatKind::Wild => hir::PatKind::Wild,
3495             PatKind::Ident(ref binding_mode, ident, ref sub) => {
3496                 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3497                     // `None` can occur in body-less function signatures
3498                     def @ None | def @ Some(Def::Local(_)) => {
3499                         let canonical_id = match def {
3500                             Some(Def::Local(id)) => id,
3501                             _ => p.id,
3502                         };
3503                         hir::PatKind::Binding(
3504                             self.lower_binding_mode(binding_mode),
3505                             canonical_id,
3506                             ident,
3507                             sub.as_ref().map(|x| self.lower_pat(x)),
3508                         )
3509                     }
3510                     Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3511                         None,
3512                         P(hir::Path {
3513                             span: ident.span,
3514                             def,
3515                             segments: hir_vec![hir::PathSegment::from_ident(ident)],
3516                         }),
3517                     )),
3518                 }
3519             }
3520             PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3521             PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3522                 let qpath = self.lower_qpath(
3523                     p.id,
3524                     &None,
3525                     path,
3526                     ParamMode::Optional,
3527                     ImplTraitContext::disallowed(),
3528                 );
3529                 self.check_self_struct_ctor_feature(&qpath);
3530                 hir::PatKind::TupleStruct(
3531                     qpath,
3532                     pats.iter().map(|x| self.lower_pat(x)).collect(),
3533                     ddpos,
3534                 )
3535             }
3536             PatKind::Path(ref qself, ref path) => {
3537                 let qpath = self.lower_qpath(
3538                     p.id,
3539                     qself,
3540                     path,
3541                     ParamMode::Optional,
3542                     ImplTraitContext::disallowed(),
3543                 );
3544                 self.check_self_struct_ctor_feature(&qpath);
3545                 hir::PatKind::Path(qpath)
3546             }
3547             PatKind::Struct(ref path, ref fields, etc) => {
3548                 let qpath = self.lower_qpath(
3549                     p.id,
3550                     &None,
3551                     path,
3552                     ParamMode::Optional,
3553                     ImplTraitContext::disallowed(),
3554                 );
3555
3556                 let fs = fields
3557                     .iter()
3558                     .map(|f| Spanned {
3559                         span: f.span,
3560                         node: hir::FieldPat {
3561                             id: self.next_id().node_id,
3562                             ident: f.node.ident,
3563                             pat: self.lower_pat(&f.node.pat),
3564                             is_shorthand: f.node.is_shorthand,
3565                         },
3566                     })
3567                     .collect();
3568                 hir::PatKind::Struct(qpath, fs, etc)
3569             }
3570             PatKind::Tuple(ref elts, ddpos) => {
3571                 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3572             }
3573             PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3574             PatKind::Ref(ref inner, mutbl) => {
3575                 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3576             }
3577             PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
3578                 P(self.lower_expr(e1)),
3579                 P(self.lower_expr(e2)),
3580                 self.lower_range_end(end),
3581             ),
3582             PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3583                 before.iter().map(|x| self.lower_pat(x)).collect(),
3584                 slice.as_ref().map(|x| self.lower_pat(x)),
3585                 after.iter().map(|x| self.lower_pat(x)).collect(),
3586             ),
3587             PatKind::Paren(ref inner) => return self.lower_pat(inner),
3588             PatKind::Mac(_) => panic!("Shouldn't exist here"),
3589         };
3590
3591         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3592         P(hir::Pat {
3593             id: node_id,
3594             hir_id,
3595             node,
3596             span: p.span,
3597         })
3598     }
3599
3600     fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3601         match *e {
3602             RangeEnd::Included(_) => hir::RangeEnd::Included,
3603             RangeEnd::Excluded => hir::RangeEnd::Excluded,
3604         }
3605     }
3606
3607     fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3608         self.with_new_scopes(|this| {
3609             let LoweredNodeId { node_id, hir_id } = this.lower_node_id(c.id);
3610             hir::AnonConst {
3611                 id: node_id,
3612                 hir_id,
3613                 body: this.lower_body(None, |this| this.lower_expr(&c.value)),
3614             }
3615         })
3616     }
3617
3618     fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3619         let kind = match e.node {
3620             ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
3621             ExprKind::ObsoleteInPlace(..) => {
3622                 self.sess.abort_if_errors();
3623                 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3624             }
3625             ExprKind::Array(ref exprs) => {
3626                 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
3627             }
3628             ExprKind::Repeat(ref expr, ref count) => {
3629                 let expr = P(self.lower_expr(expr));
3630                 let count = self.lower_anon_const(count);
3631                 hir::ExprKind::Repeat(expr, count)
3632             }
3633             ExprKind::Tup(ref elts) => {
3634                 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
3635             }
3636             ExprKind::Call(ref f, ref args) => {
3637                 let f = P(self.lower_expr(f));
3638                 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
3639             }
3640             ExprKind::MethodCall(ref seg, ref args) => {
3641                 let hir_seg = self.lower_path_segment(
3642                     e.span,
3643                     seg,
3644                     ParamMode::Optional,
3645                     0,
3646                     ParenthesizedGenericArgs::Err,
3647                     ImplTraitContext::disallowed(),
3648                 );
3649                 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3650                 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
3651             }
3652             ExprKind::Binary(binop, ref lhs, ref rhs) => {
3653                 let binop = self.lower_binop(binop);
3654                 let lhs = P(self.lower_expr(lhs));
3655                 let rhs = P(self.lower_expr(rhs));
3656                 hir::ExprKind::Binary(binop, lhs, rhs)
3657             }
3658             ExprKind::Unary(op, ref ohs) => {
3659                 let op = self.lower_unop(op);
3660                 let ohs = P(self.lower_expr(ohs));
3661                 hir::ExprKind::Unary(op, ohs)
3662             }
3663             ExprKind::Lit(ref l) => hir::ExprKind::Lit(P((**l).clone())),
3664             ExprKind::Cast(ref expr, ref ty) => {
3665                 let expr = P(self.lower_expr(expr));
3666                 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3667             }
3668             ExprKind::Type(ref expr, ref ty) => {
3669                 let expr = P(self.lower_expr(expr));
3670                 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
3671             }
3672             ExprKind::AddrOf(m, ref ohs) => {
3673                 let m = self.lower_mutability(m);
3674                 let ohs = P(self.lower_expr(ohs));
3675                 hir::ExprKind::AddrOf(m, ohs)
3676             }
3677             // More complicated than you might expect because the else branch
3678             // might be `if let`.
3679             ExprKind::If(ref cond, ref blk, ref else_opt) => {
3680                 let else_opt = else_opt.as_ref().map(|els| {
3681                     match els.node {
3682                         ExprKind::IfLet(..) => {
3683                             // wrap the if-let expr in a block
3684                             let span = els.span;
3685                             let els = P(self.lower_expr(els));
3686                             let LoweredNodeId { node_id, hir_id } = self.next_id();
3687                             let blk = P(hir::Block {
3688                                 stmts: hir_vec![],
3689                                 expr: Some(els),
3690                                 id: node_id,
3691                                 hir_id,
3692                                 rules: hir::DefaultBlock,
3693                                 span,
3694                                 targeted_by_break: false,
3695                                 recovered: blk.recovered,
3696                             });
3697                             P(self.expr_block(blk, ThinVec::new()))
3698                         }
3699                         _ => P(self.lower_expr(els)),
3700                     }
3701                 });
3702
3703                 let then_blk = self.lower_block(blk, false);
3704                 let then_expr = self.expr_block(then_blk, ThinVec::new());
3705
3706                 hir::ExprKind::If(P(self.lower_expr(cond)), P(then_expr), else_opt)
3707             }
3708             ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3709                 hir::ExprKind::While(
3710                     this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3711                     this.lower_block(body, false),
3712                     this.lower_label(opt_label),
3713                 )
3714             }),
3715             ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3716                 hir::ExprKind::Loop(
3717                     this.lower_block(body, false),
3718                     this.lower_label(opt_label),
3719                     hir::LoopSource::Loop,
3720                 )
3721             }),
3722             ExprKind::TryBlock(ref body) => {
3723                 self.with_catch_scope(body.id, |this| {
3724                     let unstable_span =
3725                         this.allow_internal_unstable(CompilerDesugaringKind::TryBlock, body.span);
3726                     let mut block = this.lower_block(body, true).into_inner();
3727                     let tail = block.expr.take().map_or_else(
3728                         || {
3729                             let LoweredNodeId { node_id, hir_id } = this.next_id();
3730                             let span = this.sess.source_map().end_point(unstable_span);
3731                             hir::Expr {
3732                                 id: node_id,
3733                                 span,
3734                                 node: hir::ExprKind::Tup(hir_vec![]),
3735                                 attrs: ThinVec::new(),
3736                                 hir_id,
3737                             }
3738                         },
3739                         |x: P<hir::Expr>| x.into_inner(),
3740                     );
3741                     block.expr = Some(this.wrap_in_try_constructor(
3742                         "from_ok", tail, unstable_span));
3743                     hir::ExprKind::Block(P(block), None)
3744                 })
3745             }
3746             ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
3747                 P(self.lower_expr(expr)),
3748                 arms.iter().map(|x| self.lower_arm(x)).collect(),
3749                 hir::MatchSource::Normal,
3750             ),
3751             ExprKind::Async(capture_clause, closure_node_id, ref block) => {
3752                 self.make_async_expr(capture_clause, closure_node_id, None, |this| {
3753                     this.with_new_scopes(|this| {
3754                         let block = this.lower_block(block, false);
3755                         this.expr_block(block, ThinVec::new())
3756                     })
3757                 })
3758             }
3759             ExprKind::Closure(
3760                 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
3761             ) => {
3762                 if let IsAsync::Async { closure_id, .. } = asyncness {
3763                     let outer_decl = FnDecl {
3764                         inputs: decl.inputs.clone(),
3765                         output: FunctionRetTy::Default(fn_decl_span),
3766                         variadic: false,
3767                     };
3768                     // We need to lower the declaration outside the new scope, because we
3769                     // have to conserve the state of being inside a loop condition for the
3770                     // closure argument types.
3771                     let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
3772
3773                     self.with_new_scopes(|this| {
3774                         // FIXME(cramertj) allow `async` non-`move` closures with
3775                         if capture_clause == CaptureBy::Ref &&
3776                             !decl.inputs.is_empty()
3777                         {
3778                             struct_span_err!(
3779                                 this.sess,
3780                                 fn_decl_span,
3781                                 E0708,
3782                                 "`async` non-`move` closures with arguments \
3783                                 are not currently supported",
3784                             )
3785                                 .help("consider using `let` statements to manually capture \
3786                                         variables by reference before entering an \
3787                                         `async move` closure")
3788                                 .emit();
3789                         }
3790
3791                         // Transform `async |x: u8| -> X { ... }` into
3792                         // `|x: u8| future_from_generator(|| -> X { ... })`
3793                         let body_id = this.lower_body(Some(&outer_decl), |this| {
3794                             let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
3795                                 Some(&**ty)
3796                             } else { None };
3797                             let async_body = this.make_async_expr(
3798                                 capture_clause, closure_id, async_ret_ty,
3799                                 |this| {
3800                                     this.with_new_scopes(|this| this.lower_expr(body))
3801                                 });
3802                             this.expr(fn_decl_span, async_body, ThinVec::new())
3803                         });
3804                         hir::ExprKind::Closure(
3805                             this.lower_capture_clause(capture_clause),
3806                             fn_decl,
3807                             body_id,
3808                             fn_decl_span,
3809                             None,
3810                         )
3811                     })
3812                 } else {
3813                     // Lower outside new scope to preserve `is_in_loop_condition`.
3814                     let fn_decl = self.lower_fn_decl(decl, None, false, None);
3815
3816                     self.with_new_scopes(|this| {
3817                         let mut is_generator = false;
3818                         let body_id = this.lower_body(Some(decl), |this| {
3819                             let e = this.lower_expr(body);
3820                             is_generator = this.is_generator;
3821                             e
3822                         });
3823                         let generator_option = if is_generator {
3824                             if !decl.inputs.is_empty() {
3825                                 span_err!(
3826                                     this.sess,
3827                                     fn_decl_span,
3828                                     E0628,
3829                                     "generators cannot have explicit arguments"
3830                                 );
3831                                 this.sess.abort_if_errors();
3832                             }
3833                             Some(match movability {
3834                                 Movability::Movable => hir::GeneratorMovability::Movable,
3835                                 Movability::Static => hir::GeneratorMovability::Static,
3836                             })
3837                         } else {
3838                             if movability == Movability::Static {
3839                                 span_err!(
3840                                     this.sess,
3841                                     fn_decl_span,
3842                                     E0697,
3843                                     "closures cannot be static"
3844                                 );
3845                             }
3846                             None
3847                         };
3848                         hir::ExprKind::Closure(
3849                             this.lower_capture_clause(capture_clause),
3850                             fn_decl,
3851                             body_id,
3852                             fn_decl_span,
3853                             generator_option,
3854                         )
3855                     })
3856                 }
3857             }
3858             ExprKind::Block(ref blk, opt_label) => {
3859                 hir::ExprKind::Block(self.lower_block(blk,
3860                                                       opt_label.is_some()),
3861                                                       self.lower_label(opt_label))
3862             }
3863             ExprKind::Assign(ref el, ref er) => {
3864                 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3865             }
3866             ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
3867                 self.lower_binop(op),
3868                 P(self.lower_expr(el)),
3869                 P(self.lower_expr(er)),
3870             ),
3871             ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
3872             ExprKind::Index(ref el, ref er) => {
3873                 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
3874             }
3875             // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3876             ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3877                 let id = self.next_id();
3878                 let e1 = self.lower_expr(e1);
3879                 let e2 = self.lower_expr(e2);
3880                 let ty_path = P(self.std_path(e.span, &["ops", "RangeInclusive"], None, false));
3881                 let ty = P(self.ty_path(id, e.span, hir::QPath::Resolved(None, ty_path)));
3882                 let new_seg = P(hir::PathSegment::from_ident(Ident::from_str("new")));
3883                 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3884                 let new = P(self.expr(e.span, hir::ExprKind::Path(new_path), ThinVec::new()));
3885                 hir::ExprKind::Call(new, hir_vec![e1, e2])
3886             }
3887             ExprKind::Range(ref e1, ref e2, lims) => {
3888                 use syntax::ast::RangeLimits::*;
3889
3890                 let path = match (e1, e2, lims) {
3891                     (&None, &None, HalfOpen) => "RangeFull",
3892                     (&Some(..), &None, HalfOpen) => "RangeFrom",
3893                     (&None, &Some(..), HalfOpen) => "RangeTo",
3894                     (&Some(..), &Some(..), HalfOpen) => "Range",
3895                     (&None, &Some(..), Closed) => "RangeToInclusive",
3896                     (&Some(..), &Some(..), Closed) => unreachable!(),
3897                     (_, &None, Closed) => self.diagnostic()
3898                         .span_fatal(e.span, "inclusive range with no end")
3899                         .raise(),
3900                 };
3901
3902                 let fields = e1.iter()
3903                     .map(|e| ("start", e))
3904                     .chain(e2.iter().map(|e| ("end", e)))
3905                     .map(|(s, e)| {
3906                         let expr = P(self.lower_expr(&e));
3907                         let ident = Ident::new(Symbol::intern(s), e.span);
3908                         self.field(ident, expr, e.span)
3909                     })
3910                     .collect::<P<[hir::Field]>>();
3911
3912                 let is_unit = fields.is_empty();
3913                 let struct_path = ["ops", path];
3914                 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
3915                 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3916
3917                 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3918
3919                 return hir::Expr {
3920                     id: node_id,
3921                     hir_id,
3922                     node: if is_unit {
3923                         hir::ExprKind::Path(struct_path)
3924                     } else {
3925                         hir::ExprKind::Struct(struct_path, fields, None)
3926                     },
3927                     span: e.span,
3928                     attrs: e.attrs.clone(),
3929                 };
3930             }
3931             ExprKind::Path(ref qself, ref path) => {
3932                 let qpath = self.lower_qpath(
3933                     e.id,
3934                     qself,
3935                     path,
3936                     ParamMode::Optional,
3937                     ImplTraitContext::disallowed(),
3938                 );
3939                 self.check_self_struct_ctor_feature(&qpath);
3940                 hir::ExprKind::Path(qpath)
3941             }
3942             ExprKind::Break(opt_label, ref opt_expr) => {
3943                 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3944                     hir::Destination {
3945                         label: None,
3946                         target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3947                     }
3948                 } else {
3949                     self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3950                 };
3951                 hir::ExprKind::Break(
3952                     destination,
3953                     opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3954                 )
3955             }
3956             ExprKind::Continue(opt_label) => {
3957                 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
3958                     hir::Destination {
3959                         label: None,
3960                         target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3961                     }
3962                 } else {
3963                     self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3964                 })
3965             }
3966             ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
3967             ExprKind::InlineAsm(ref asm) => {
3968                 let hir_asm = hir::InlineAsm {
3969                     inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3970                     outputs: asm.outputs
3971                         .iter()
3972                         .map(|out| hir::InlineAsmOutput {
3973                             constraint: out.constraint.clone(),
3974                             is_rw: out.is_rw,
3975                             is_indirect: out.is_indirect,
3976                             span: out.expr.span,
3977                         })
3978                         .collect(),
3979                     asm: asm.asm.clone(),
3980                     asm_str_style: asm.asm_str_style,
3981                     clobbers: asm.clobbers.clone().into(),
3982                     volatile: asm.volatile,
3983                     alignstack: asm.alignstack,
3984                     dialect: asm.dialect,
3985                     ctxt: asm.ctxt,
3986                 };
3987                 let outputs = asm.outputs
3988                     .iter()
3989                     .map(|out| self.lower_expr(&out.expr))
3990                     .collect();
3991                 let inputs = asm.inputs
3992                     .iter()
3993                     .map(|&(_, ref input)| self.lower_expr(input))
3994                     .collect();
3995                 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
3996             }
3997             ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
3998                 self.lower_qpath(
3999                     e.id,
4000                     &None,
4001                     path,
4002                     ParamMode::Optional,
4003                     ImplTraitContext::disallowed(),
4004                 ),
4005                 fields.iter().map(|x| self.lower_field(x)).collect(),
4006                 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4007             ),
4008             ExprKind::Paren(ref ex) => {
4009                 let mut ex = self.lower_expr(ex);
4010                 // include parens in span, but only if it is a super-span.
4011                 if e.span.contains(ex.span) {
4012                     ex.span = e.span;
4013                 }
4014                 // merge attributes into the inner expression.
4015                 let mut attrs = e.attrs.clone();
4016                 attrs.extend::<Vec<_>>(ex.attrs.into());
4017                 ex.attrs = attrs;
4018                 return ex;
4019             }
4020
4021             ExprKind::Yield(ref opt_expr) => {
4022                 self.is_generator = true;
4023                 let expr = opt_expr
4024                     .as_ref()
4025                     .map(|x| self.lower_expr(x))
4026                     .unwrap_or_else(||
4027                     self.expr(e.span, hir::ExprKind::Tup(hir_vec![]), ThinVec::new())
4028                 );
4029                 hir::ExprKind::Yield(P(expr))
4030             }
4031
4032             // Desugar ExprIfLet
4033             // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
4034             ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
4035                 // to:
4036                 //
4037                 //   match <sub_expr> {
4038                 //     <pat> => <body>,
4039                 //     _ => [<else_opt> | ()]
4040                 //   }
4041
4042                 let mut arms = vec![];
4043
4044                 // `<pat> => <body>`
4045                 {
4046                     let body = self.lower_block(body, false);
4047                     let body_expr = P(self.expr_block(body, ThinVec::new()));
4048                     let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4049                     arms.push(self.arm(pats, body_expr));
4050                 }
4051
4052                 // _ => [<else_opt>|()]
4053                 {
4054                     let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
4055                     let wildcard_pattern = self.pat_wild(e.span);
4056                     let body = if let Some(else_expr) = wildcard_arm {
4057                         P(self.lower_expr(else_expr))
4058                     } else {
4059                         self.expr_tuple(e.span, hir_vec![])
4060                     };
4061                     arms.push(self.arm(hir_vec![wildcard_pattern], body));
4062                 }
4063
4064                 let contains_else_clause = else_opt.is_some();
4065
4066                 let sub_expr = P(self.lower_expr(sub_expr));
4067
4068                 hir::ExprKind::Match(
4069                     sub_expr,
4070                     arms.into(),
4071                     hir::MatchSource::IfLetDesugar {
4072                         contains_else_clause,
4073                     },
4074                 )
4075             }
4076
4077             // Desugar ExprWhileLet
4078             // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4079             ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
4080                 // to:
4081                 //
4082                 //   [opt_ident]: loop {
4083                 //     match <sub_expr> {
4084                 //       <pat> => <body>,
4085                 //       _ => break
4086                 //     }
4087                 //   }
4088
4089                 // Note that the block AND the condition are evaluated in the loop scope.
4090                 // This is done to allow `break` from inside the condition of the loop.
4091                 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4092                     (
4093                         this.lower_block(body, false),
4094                         this.expr_break(e.span, ThinVec::new()),
4095                         this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4096                     )
4097                 });
4098
4099                 // `<pat> => <body>`
4100                 let pat_arm = {
4101                     let body_expr = P(self.expr_block(body, ThinVec::new()));
4102                     let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4103                     self.arm(pats, body_expr)
4104                 };
4105
4106                 // `_ => break`
4107                 let break_arm = {
4108                     let pat_under = self.pat_wild(e.span);
4109                     self.arm(hir_vec![pat_under], break_expr)
4110                 };
4111
4112                 // `match <sub_expr> { ... }`
4113                 let arms = hir_vec![pat_arm, break_arm];
4114                 let match_expr = self.expr(
4115                     sub_expr.span,
4116                     hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4117                     ThinVec::new(),
4118                 );
4119
4120                 // `[opt_ident]: loop { ... }`
4121                 let loop_block = P(self.block_expr(P(match_expr)));
4122                 let loop_expr = hir::ExprKind::Loop(
4123                     loop_block,
4124                     self.lower_label(opt_label),
4125                     hir::LoopSource::WhileLet,
4126                 );
4127                 // add attributes to the outer returned expr node
4128                 loop_expr
4129             }
4130
4131             // Desugar ExprForLoop
4132             // From: `[opt_ident]: for <pat> in <head> <body>`
4133             ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4134                 // to:
4135                 //
4136                 //   {
4137                 //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4138                 //       mut iter => {
4139                 //         [opt_ident]: loop {
4140                 //           let mut __next;
4141                 //           match ::std::iter::Iterator::next(&mut iter) {
4142                 //             ::std::option::Option::Some(val) => __next = val,
4143                 //             ::std::option::Option::None => break
4144                 //           };
4145                 //           let <pat> = __next;
4146                 //           StmtKind::Expr(<body>);
4147                 //         }
4148                 //       }
4149                 //     };
4150                 //     result
4151                 //   }
4152
4153                 // expand <head>
4154                 let head = self.lower_expr(head);
4155                 let head_sp = head.span;
4156                 let desugared_span = self.allow_internal_unstable(
4157                     CompilerDesugaringKind::ForLoop,
4158                     head_sp,
4159                 );
4160
4161                 let iter = self.str_to_ident("iter");
4162
4163                 let next_ident = self.str_to_ident("__next");
4164                 let next_pat = self.pat_ident_binding_mode(
4165                     desugared_span,
4166                     next_ident,
4167                     hir::BindingAnnotation::Mutable,
4168                 );
4169
4170                 // `::std::option::Option::Some(val) => next = val`
4171                 let pat_arm = {
4172                     let val_ident = self.str_to_ident("val");
4173                     let val_pat = self.pat_ident(pat.span, val_ident);
4174                     let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
4175                     let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
4176                     let assign = P(self.expr(
4177                         pat.span,
4178                         hir::ExprKind::Assign(next_expr, val_expr),
4179                         ThinVec::new(),
4180                     ));
4181                     let some_pat = self.pat_some(pat.span, val_pat);
4182                     self.arm(hir_vec![some_pat], assign)
4183                 };
4184
4185                 // `::std::option::Option::None => break`
4186                 let break_arm = {
4187                     let break_expr =
4188                         self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4189                     let pat = self.pat_none(e.span);
4190                     self.arm(hir_vec![pat], break_expr)
4191                 };
4192
4193                 // `mut iter`
4194                 let iter_pat = self.pat_ident_binding_mode(
4195                     desugared_span,
4196                     iter,
4197                     hir::BindingAnnotation::Mutable
4198                 );
4199
4200                 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4201                 let match_expr = {
4202                     let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
4203                     let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4204                     let next_path = &["iter", "Iterator", "next"];
4205                     let next_path = P(self.expr_std_path(head_sp, next_path, None, ThinVec::new()));
4206                     let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
4207                     let arms = hir_vec![pat_arm, break_arm];
4208
4209                     P(self.expr(
4210                         head_sp,
4211                         hir::ExprKind::Match(
4212                             next_expr,
4213                             arms,
4214                             hir::MatchSource::ForLoopDesugar
4215                         ),
4216                         ThinVec::new(),
4217                     ))
4218                 };
4219                 let match_stmt = respan(
4220                     head_sp,
4221                     hir::StmtKind::Expr(match_expr, self.next_id().node_id)
4222                 );
4223
4224                 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
4225
4226                 // `let mut __next`
4227                 let next_let = self.stmt_let_pat(
4228                     desugared_span,
4229                     None,
4230                     next_pat,
4231                     hir::LocalSource::ForLoopDesugar,
4232                 );
4233
4234                 // `let <pat> = __next`
4235                 let pat = self.lower_pat(pat);
4236                 let pat_let = self.stmt_let_pat(
4237                     head_sp,
4238                     Some(next_expr),
4239                     pat,
4240                     hir::LocalSource::ForLoopDesugar,
4241                 );
4242
4243                 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4244                 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4245                 let body_stmt = respan(
4246                     body.span,
4247                     hir::StmtKind::Expr(body_expr, self.next_id().node_id)
4248                 );
4249
4250                 let loop_block = P(self.block_all(
4251                     e.span,
4252                     hir_vec![next_let, match_stmt, pat_let, body_stmt],
4253                     None,
4254                 ));
4255
4256                 // `[opt_ident]: loop { ... }`
4257                 let loop_expr = hir::ExprKind::Loop(
4258                     loop_block,
4259                     self.lower_label(opt_label),
4260                     hir::LoopSource::ForLoop,
4261                 );
4262                 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4263                 let loop_expr = P(hir::Expr {
4264                     id: node_id,
4265                     hir_id,
4266                     node: loop_expr,
4267                     span: e.span,
4268                     attrs: ThinVec::new(),
4269                 });
4270
4271                 // `mut iter => { ... }`
4272                 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4273
4274                 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4275                 let into_iter_expr = {
4276                     let into_iter_path = &["iter", "IntoIterator", "into_iter"];
4277                     let into_iter = P(self.expr_std_path(
4278                             head_sp, into_iter_path, None, ThinVec::new()));
4279                     P(self.expr_call(head_sp, into_iter, hir_vec![head]))
4280                 };
4281
4282                 let match_expr = P(self.expr_match(
4283                     head_sp,
4284                     into_iter_expr,
4285                     hir_vec![iter_arm],
4286                     hir::MatchSource::ForLoopDesugar,
4287                 ));
4288
4289                 // `{ let _result = ...; _result }`
4290                 // underscore prevents an unused_variables lint if the head diverges
4291                 let result_ident = self.str_to_ident("_result");
4292                 let (let_stmt, let_stmt_binding) =
4293                     self.stmt_let(e.span, false, result_ident, match_expr);
4294
4295                 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
4296                 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
4297                 // add the attributes to the outer returned expr node
4298                 return self.expr_block(block, e.attrs.clone());
4299             }
4300
4301             // Desugar ExprKind::Try
4302             // From: `<expr>?`
4303             ExprKind::Try(ref sub_expr) => {
4304                 // to:
4305                 //
4306                 // match Try::into_result(<expr>) {
4307                 //     Ok(val) => #[allow(unreachable_code)] val,
4308                 //     Err(err) => #[allow(unreachable_code)]
4309                 //                 // If there is an enclosing `catch {...}`
4310                 //                 break 'catch_target Try::from_error(From::from(err)),
4311                 //                 // Otherwise
4312                 //                 return Try::from_error(From::from(err)),
4313                 // }
4314
4315                 let unstable_span =
4316                     self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
4317
4318                 // Try::into_result(<expr>)
4319                 let discr = {
4320                     // expand <expr>
4321                     let sub_expr = self.lower_expr(sub_expr);
4322
4323                     let path = &["ops", "Try", "into_result"];
4324                     let path = P(self.expr_std_path(
4325                             unstable_span, path, None, ThinVec::new()));
4326                     P(self.expr_call(e.span, path, hir_vec![sub_expr]))
4327                 };
4328
4329                 // #[allow(unreachable_code)]
4330                 let attr = {
4331                     // allow(unreachable_code)
4332                     let allow = {
4333                         let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
4334                         let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
4335                         let uc_nested = attr::mk_nested_word_item(uc_ident);
4336                         attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
4337                     };
4338                     attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
4339                 };
4340                 let attrs = vec![attr];
4341
4342                 // Ok(val) => #[allow(unreachable_code)] val,
4343                 let ok_arm = {
4344                     let val_ident = self.str_to_ident("val");
4345                     let val_pat = self.pat_ident(e.span, val_ident);
4346                     let val_expr = P(self.expr_ident_with_attrs(
4347                         e.span,
4348                         val_ident,
4349                         val_pat.id,
4350                         ThinVec::from(attrs.clone()),
4351                     ));
4352                     let ok_pat = self.pat_ok(e.span, val_pat);
4353
4354                     self.arm(hir_vec![ok_pat], val_expr)
4355                 };
4356
4357                 // Err(err) => #[allow(unreachable_code)]
4358                 //             return Try::from_error(From::from(err)),
4359                 let err_arm = {
4360                     let err_ident = self.str_to_ident("err");
4361                     let err_local = self.pat_ident(e.span, err_ident);
4362                     let from_expr = {
4363                         let path = &["convert", "From", "from"];
4364                         let from = P(self.expr_std_path(
4365                                 e.span, path, None, ThinVec::new()));
4366                         let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
4367
4368                         self.expr_call(e.span, from, hir_vec![err_expr])
4369                     };
4370                     let from_err_expr =
4371                         self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
4372                     let thin_attrs = ThinVec::from(attrs);
4373                     let catch_scope = self.catch_scopes.last().map(|x| *x);
4374                     let ret_expr = if let Some(catch_node) = catch_scope {
4375                         P(self.expr(
4376                             e.span,
4377                             hir::ExprKind::Break(
4378                                 hir::Destination {
4379                                     label: None,
4380                                     target_id: Ok(catch_node),
4381                                 },
4382                                 Some(from_err_expr),
4383                             ),
4384                             thin_attrs,
4385                         ))
4386                     } else {
4387                         P(self.expr(e.span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
4388                     };
4389
4390                     let err_pat = self.pat_err(e.span, err_local);
4391                     self.arm(hir_vec![err_pat], ret_expr)
4392                 };
4393
4394                 hir::ExprKind::Match(
4395                     discr,
4396                     hir_vec![err_arm, ok_arm],
4397                     hir::MatchSource::TryDesugar,
4398                 )
4399             }
4400
4401             ExprKind::Mac(_) => panic!("Shouldn't exist here"),
4402         };
4403
4404         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
4405
4406         hir::Expr {
4407             id: node_id,
4408             hir_id,
4409             node: kind,
4410             span: e.span,
4411             attrs: e.attrs.clone(),
4412         }
4413     }
4414
4415     fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
4416         smallvec![match s.node {
4417             StmtKind::Local(ref l) => {
4418                 let (l, item_ids) = self.lower_local(l);
4419                 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
4420                     .into_iter()
4421                     .map(|item_id| Spanned {
4422                         node: hir::StmtKind::Decl(
4423                             P(Spanned {
4424                                 node: hir::DeclKind::Item(item_id),
4425                                 span: s.span,
4426                             }),
4427                             self.next_id().node_id,
4428                         ),
4429                         span: s.span,
4430                     })
4431                     .collect();
4432                 ids.push(Spanned {
4433                     node: hir::StmtKind::Decl(
4434                         P(Spanned {
4435                             node: hir::DeclKind::Local(l),
4436                             span: s.span,
4437                         }),
4438                         self.lower_node_id(s.id).node_id,
4439                     ),
4440                     span: s.span,
4441                 });
4442                 return ids;
4443             },
4444             StmtKind::Item(ref it) => {
4445                 // Can only use the ID once.
4446                 let mut id = Some(s.id);
4447                 return self.lower_item_id(it)
4448                     .into_iter()
4449                     .map(|item_id| Spanned {
4450                         node: hir::StmtKind::Decl(
4451                             P(Spanned {
4452                                 node: hir::DeclKind::Item(item_id),
4453                                 span: s.span,
4454                             }),
4455                             id.take()
4456                               .map(|id| self.lower_node_id(id).node_id)
4457                               .unwrap_or_else(|| self.next_id().node_id),
4458                         ),
4459                         span: s.span,
4460                     })
4461                     .collect();
4462             }
4463             StmtKind::Expr(ref e) => Spanned {
4464                 node: hir::StmtKind::Expr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4465                 span: s.span,
4466             },
4467             StmtKind::Semi(ref e) => Spanned {
4468                 node: hir::StmtKind::Semi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
4469                 span: s.span,
4470             },
4471             StmtKind::Mac(..) => panic!("Shouldn't exist here"),
4472         }]
4473     }
4474
4475     fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
4476         match c {
4477             CaptureBy::Value => hir::CaptureByValue,
4478             CaptureBy::Ref => hir::CaptureByRef,
4479         }
4480     }
4481
4482     /// If an `explicit_owner` is given, this method allocates the `HirId` in
4483     /// the address space of that item instead of the item currently being
4484     /// lowered. This can happen during `lower_impl_item_ref()` where we need to
4485     /// lower a `Visibility` value although we haven't lowered the owning
4486     /// `ImplItem` in question yet.
4487     fn lower_visibility(
4488         &mut self,
4489         v: &Visibility,
4490         explicit_owner: Option<NodeId>,
4491     ) -> hir::Visibility {
4492         let node = match v.node {
4493             VisibilityKind::Public => hir::VisibilityKind::Public,
4494             VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
4495             VisibilityKind::Restricted { ref path, id } => {
4496                 let lowered_id = if let Some(owner) = explicit_owner {
4497                     self.lower_node_id_with_owner(id, owner)
4498                 } else {
4499                     self.lower_node_id(id)
4500                 };
4501                 hir::VisibilityKind::Restricted {
4502                     path: P(self.lower_path(id, path, ParamMode::Explicit)),
4503                     id: lowered_id.node_id,
4504                     hir_id: lowered_id.hir_id,
4505                 }
4506             },
4507             VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
4508         };
4509         respan(v.span, node)
4510     }
4511
4512     fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
4513         match d {
4514             Defaultness::Default => hir::Defaultness::Default {
4515                 has_value: has_value,
4516             },
4517             Defaultness::Final => {
4518                 assert!(has_value);
4519                 hir::Defaultness::Final
4520             }
4521         }
4522     }
4523
4524     fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
4525         match *b {
4526             BlockCheckMode::Default => hir::DefaultBlock,
4527             BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
4528         }
4529     }
4530
4531     fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
4532         match *b {
4533             BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
4534             BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
4535             BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
4536             BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
4537         }
4538     }
4539
4540     fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
4541         match u {
4542             CompilerGenerated => hir::CompilerGenerated,
4543             UserProvided => hir::UserProvided,
4544         }
4545     }
4546
4547     fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
4548         match i {
4549             ImplPolarity::Positive => hir::ImplPolarity::Positive,
4550             ImplPolarity::Negative => hir::ImplPolarity::Negative,
4551         }
4552     }
4553
4554     fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
4555         match f {
4556             TraitBoundModifier::None => hir::TraitBoundModifier::None,
4557             TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
4558         }
4559     }
4560
4561     // Helper methods for building HIR.
4562
4563     fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
4564         hir::Arm {
4565             attrs: hir_vec![],
4566             pats,
4567             guard: None,
4568             body: expr,
4569         }
4570     }
4571
4572     fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
4573         hir::Field {
4574             id: self.next_id().node_id,
4575             ident,
4576             span,
4577             expr,
4578             is_shorthand: false,
4579         }
4580     }
4581
4582     fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
4583         let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
4584         P(self.expr(span, expr_break, attrs))
4585     }
4586
4587     fn expr_call(
4588         &mut self,
4589         span: Span,
4590         e: P<hir::Expr>,
4591         args: hir::HirVec<hir::Expr>,
4592     ) -> hir::Expr {
4593         self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
4594     }
4595
4596     fn expr_ident(&mut self, span: Span, ident: Ident, binding: NodeId) -> hir::Expr {
4597         self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
4598     }
4599
4600     fn expr_ident_with_attrs(
4601         &mut self,
4602         span: Span,
4603         ident: Ident,
4604         binding: NodeId,
4605         attrs: ThinVec<Attribute>,
4606     ) -> hir::Expr {
4607         let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
4608             None,
4609             P(hir::Path {
4610                 span,
4611                 def: Def::Local(binding),
4612                 segments: hir_vec![hir::PathSegment::from_ident(ident)],
4613             }),
4614         ));
4615
4616         self.expr(span, expr_path, attrs)
4617     }
4618
4619     fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4620         self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
4621     }
4622
4623     fn expr_std_path(
4624         &mut self,
4625         span: Span,
4626         components: &[&str],
4627         params: Option<P<hir::GenericArgs>>,
4628         attrs: ThinVec<Attribute>,
4629     ) -> hir::Expr {
4630         let path = self.std_path(span, components, params, true);
4631         self.expr(
4632             span,
4633             hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
4634             attrs,
4635         )
4636     }
4637
4638     fn expr_match(
4639         &mut self,
4640         span: Span,
4641         arg: P<hir::Expr>,
4642         arms: hir::HirVec<hir::Arm>,
4643         source: hir::MatchSource,
4644     ) -> hir::Expr {
4645         self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
4646     }
4647
4648     fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4649         self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
4650     }
4651
4652     fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4653         P(self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()))
4654     }
4655
4656     fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
4657         let LoweredNodeId { node_id, hir_id } = self.next_id();
4658         hir::Expr {
4659             id: node_id,
4660             hir_id,
4661             node,
4662             span,
4663             attrs,
4664         }
4665     }
4666
4667     fn stmt_let_pat(
4668         &mut self,
4669         sp: Span,
4670         ex: Option<P<hir::Expr>>,
4671         pat: P<hir::Pat>,
4672         source: hir::LocalSource,
4673     ) -> hir::Stmt {
4674         let LoweredNodeId { node_id, hir_id } = self.next_id();
4675
4676         let local = P(hir::Local {
4677             pat,
4678             ty: None,
4679             init: ex,
4680             id: node_id,
4681             hir_id,
4682             span: sp,
4683             attrs: ThinVec::new(),
4684             source,
4685         });
4686         let decl = respan(sp, hir::DeclKind::Local(local));
4687         respan(sp, hir::StmtKind::Decl(P(decl), self.next_id().node_id))
4688     }
4689
4690     fn stmt_let(
4691         &mut self,
4692         sp: Span,
4693         mutbl: bool,
4694         ident: Ident,
4695         ex: P<hir::Expr>,
4696     ) -> (hir::Stmt, NodeId) {
4697         let pat = if mutbl {
4698             self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4699         } else {
4700             self.pat_ident(sp, ident)
4701         };
4702         let pat_id = pat.id;
4703         (
4704             self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4705             pat_id,
4706         )
4707     }
4708
4709     fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4710         self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4711     }
4712
4713     fn block_all(
4714         &mut self,
4715         span: Span,
4716         stmts: hir::HirVec<hir::Stmt>,
4717         expr: Option<P<hir::Expr>>,
4718     ) -> hir::Block {
4719         let LoweredNodeId { node_id, hir_id } = self.next_id();
4720
4721         hir::Block {
4722             stmts,
4723             expr,
4724             id: node_id,
4725             hir_id,
4726             rules: hir::DefaultBlock,
4727             span,
4728             targeted_by_break: false,
4729             recovered: false,
4730         }
4731     }
4732
4733     fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4734         self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4735     }
4736
4737     fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4738         self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4739     }
4740
4741     fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4742         self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4743     }
4744
4745     fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4746         self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4747     }
4748
4749     fn pat_std_enum(
4750         &mut self,
4751         span: Span,
4752         components: &[&str],
4753         subpats: hir::HirVec<P<hir::Pat>>,
4754     ) -> P<hir::Pat> {
4755         let path = self.std_path(span, components, None, true);
4756         let qpath = hir::QPath::Resolved(None, P(path));
4757         let pt = if subpats.is_empty() {
4758             hir::PatKind::Path(qpath)
4759         } else {
4760             hir::PatKind::TupleStruct(qpath, subpats, None)
4761         };
4762         self.pat(span, pt)
4763     }
4764
4765     fn pat_ident(&mut self, span: Span, ident: Ident) -> P<hir::Pat> {
4766         self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
4767     }
4768
4769     fn pat_ident_binding_mode(
4770         &mut self,
4771         span: Span,
4772         ident: Ident,
4773         bm: hir::BindingAnnotation,
4774     ) -> P<hir::Pat> {
4775         let LoweredNodeId { node_id, hir_id } = self.next_id();
4776
4777         P(hir::Pat {
4778             id: node_id,
4779             hir_id,
4780             node: hir::PatKind::Binding(bm, node_id, ident.with_span_pos(span), None),
4781             span,
4782         })
4783     }
4784
4785     fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4786         self.pat(span, hir::PatKind::Wild)
4787     }
4788
4789     fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4790         let LoweredNodeId { node_id, hir_id } = self.next_id();
4791         P(hir::Pat {
4792             id: node_id,
4793             hir_id,
4794             node: pat,
4795             span,
4796         })
4797     }
4798
4799     /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4800     /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4801     /// The path is also resolved according to `is_value`.
4802     fn std_path(
4803         &mut self,
4804         span: Span,
4805         components: &[&str],
4806         params: Option<P<hir::GenericArgs>>,
4807         is_value: bool
4808     ) -> hir::Path {
4809         self.resolver
4810             .resolve_str_path(span, self.crate_root, components, params, is_value)
4811     }
4812
4813     fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> hir::Ty {
4814         let mut id = id;
4815         let node = match qpath {
4816             hir::QPath::Resolved(None, path) => {
4817                 // Turn trait object paths into `TyKind::TraitObject` instead.
4818                 if let Def::Trait(_) = path.def {
4819                     let principal = hir::PolyTraitRef {
4820                         bound_generic_params: hir::HirVec::new(),
4821                         trait_ref: hir::TraitRef {
4822                             path: path.and_then(|path| path),
4823                             ref_id: id.node_id,
4824                             hir_ref_id: id.hir_id,
4825                         },
4826                         span,
4827                     };
4828
4829                     // The original ID is taken by the `PolyTraitRef`,
4830                     // so the `Ty` itself needs a different one.
4831                     id = self.next_id();
4832                     hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4833                 } else {
4834                     hir::TyKind::Path(hir::QPath::Resolved(None, path))
4835                 }
4836             }
4837             _ => hir::TyKind::Path(qpath),
4838         };
4839         hir::Ty {
4840             id: id.node_id,
4841             hir_id: id.hir_id,
4842             node,
4843             span,
4844         }
4845     }
4846
4847     /// Invoked to create the lifetime argument for a type `&T`
4848     /// with no explicit lifetime.
4849     fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4850         match self.anonymous_lifetime_mode {
4851             // Intercept when we are in an impl header and introduce an in-band lifetime.
4852             // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4853             // `'f`.
4854             AnonymousLifetimeMode::CreateParameter => {
4855                 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4856                 hir::Lifetime {
4857                     id: self.next_id().node_id,
4858                     span,
4859                     name: hir::LifetimeName::Param(fresh_name),
4860                 }
4861             }
4862
4863             AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
4864
4865             AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4866         }
4867     }
4868
4869     /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
4870     /// return a "error lifetime".
4871     fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
4872         let (id, msg, label) = match id {
4873             Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
4874
4875             None => (
4876                 self.next_id().node_id,
4877                 "`&` without an explicit lifetime name cannot be used here",
4878                 "explicit lifetime name needed here",
4879             ),
4880         };
4881
4882         let mut err = struct_span_err!(
4883             self.sess,
4884             span,
4885             E0637,
4886             "{}",
4887             msg,
4888         );
4889         err.span_label(span, label);
4890         err.emit();
4891
4892         self.new_named_lifetime(id, span, hir::LifetimeName::Error)
4893     }
4894
4895     /// Invoked to create the lifetime argument(s) for a path like
4896     /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4897     /// sorts of cases are deprecated. This may therefore report a warning or an
4898     /// error, depending on the mode.
4899     fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4900         match self.anonymous_lifetime_mode {
4901             // NB. We intentionally ignore the create-parameter mode here
4902             // and instead "pass through" to resolve-lifetimes, which will then
4903             // report an error. This is because we don't want to support
4904             // impl elision for deprecated forms like
4905             //
4906             //     impl Foo for std::cell::Ref<u32> // note lack of '_
4907             AnonymousLifetimeMode::CreateParameter => {}
4908
4909             AnonymousLifetimeMode::ReportError => {
4910                 return (0..count)
4911                     .map(|_| self.new_error_lifetime(None, span))
4912                     .collect();
4913             }
4914
4915             // This is the normal case.
4916             AnonymousLifetimeMode::PassThrough => {}
4917         }
4918
4919         (0..count)
4920             .map(|_| self.new_implicit_lifetime(span))
4921             .collect()
4922     }
4923
4924     /// Invoked to create the lifetime argument(s) for an elided trait object
4925     /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4926     /// when the bound is written, even if it is written with `'_` like in
4927     /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4928     fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4929         match self.anonymous_lifetime_mode {
4930             // NB. We intentionally ignore the create-parameter mode here.
4931             // and instead "pass through" to resolve-lifetimes, which will apply
4932             // the object-lifetime-defaulting rules. Elided object lifetime defaults
4933             // do not act like other elided lifetimes. In other words, given this:
4934             //
4935             //     impl Foo for Box<dyn Debug>
4936             //
4937             // we do not introduce a fresh `'_` to serve as the bound, but instead
4938             // ultimately translate to the equivalent of:
4939             //
4940             //     impl Foo for Box<dyn Debug + 'static>
4941             //
4942             // `resolve_lifetime` has the code to make that happen.
4943             AnonymousLifetimeMode::CreateParameter => {}
4944
4945             AnonymousLifetimeMode::ReportError => {
4946                 // ReportError applies to explicit use of `'_`.
4947             }
4948
4949             // This is the normal case.
4950             AnonymousLifetimeMode::PassThrough => {}
4951         }
4952
4953         self.new_implicit_lifetime(span)
4954     }
4955
4956     fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4957         hir::Lifetime {
4958             id: self.next_id().node_id,
4959             span,
4960             name: hir::LifetimeName::Implicit,
4961         }
4962     }
4963
4964     fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4965         self.sess.buffer_lint_with_diagnostic(
4966             builtin::BARE_TRAIT_OBJECTS,
4967             id,
4968             span,
4969             "trait objects without an explicit `dyn` are deprecated",
4970             builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4971         )
4972     }
4973
4974     fn wrap_in_try_constructor(
4975         &mut self,
4976         method: &'static str,
4977         e: hir::Expr,
4978         unstable_span: Span,
4979     ) -> P<hir::Expr> {
4980         let path = &["ops", "Try", method];
4981         let from_err = P(self.expr_std_path(unstable_span, path, None,
4982                                             ThinVec::new()));
4983         P(self.expr_call(e.span, from_err, hir_vec![e]))
4984     }
4985
4986     fn check_self_struct_ctor_feature(&self, qp: &hir::QPath) {
4987         if let hir::QPath::Resolved(_, ref p) = qp {
4988             if p.segments.len() == 1 &&
4989                p.segments[0].ident.name == keywords::SelfType.name() &&
4990                !self.sess.features_untracked().self_struct_ctor {
4991                 emit_feature_err(&self.sess.parse_sess, "self_struct_ctor",
4992                                  p.span, GateIssue::Language,
4993                                  "`Self` struct constructors are unstable");
4994             }
4995         }
4996     }
4997 }
4998
4999 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5000     // Sorting by span ensures that we get things in order within a
5001     // file, and also puts the files in a sensible order.
5002     let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5003     body_ids.sort_by_key(|b| bodies[b].value.span);
5004     body_ids
5005 }