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