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