]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/lowering.rs
Merge branch 'no-stderr-sink' of https://github.com/Zoxc/rust into rollup
[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;
45 use hir::HirVec;
46 use hir::map::{Definitions, DefKey, DefPathData};
47 use hir::def_id::{DefIndex, DefId, CRATE_DEF_INDEX, DefIndexAddressSpace};
48 use hir::def::{Def, PathResolution};
49 use lint::builtin::PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES;
50 use middle::cstore::CrateStore;
51 use rustc_data_structures::indexed_vec::IndexVec;
52 use session::Session;
53 use util::common::FN_OUTPUT_NAME;
54 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
55
56 use std::collections::{BTreeMap, HashSet};
57 use std::fmt::Debug;
58 use std::iter;
59 use std::mem;
60 use syntax::attr;
61 use syntax::ast::*;
62 use syntax::errors;
63 use syntax::ext::hygiene::{Mark, SyntaxContext};
64 use syntax::print::pprust;
65 use syntax::ptr::P;
66 use syntax::codemap::{self, respan, Spanned, CompilerDesugaringKind};
67 use syntax::std_inject;
68 use syntax::symbol::{Symbol, keywords};
69 use syntax::tokenstream::{TokenStream, TokenTree, Delimited};
70 use syntax::parse::token::Token;
71 use syntax::util::small_vector::SmallVector;
72 use syntax::visit::{self, Visitor};
73 use syntax_pos::Span;
74
75 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
76
77 pub struct LoweringContext<'a> {
78     crate_root: Option<&'static str>,
79
80     // Use to assign ids to hir nodes that do not directly correspond to an ast node
81     sess: &'a Session,
82
83     cstore: &'a CrateStore,
84
85     // As we walk the AST we must keep track of the current 'parent' def id (in
86     // the form of a DefIndex) so that if we create a new node which introduces
87     // a definition, then we can properly create the def id.
88     parent_def: Option<DefIndex>,
89     resolver: &'a mut Resolver,
90     name_map: FxHashMap<Ident, Name>,
91
92     /// The items being lowered are collected here.
93     items: BTreeMap<NodeId, hir::Item>,
94
95     trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
96     impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
97     bodies: BTreeMap<hir::BodyId, hir::Body>,
98     exported_macros: Vec<hir::MacroDef>,
99
100     trait_impls: BTreeMap<DefId, Vec<NodeId>>,
101     trait_auto_impl: BTreeMap<DefId, NodeId>,
102
103     is_generator: bool,
104
105     catch_scopes: Vec<NodeId>,
106     loop_scopes: Vec<NodeId>,
107     is_in_loop_condition: bool,
108     is_in_trait_impl: bool,
109
110     // This is a list of in-band type definitions being generated by
111     // Argument-position `impl Trait`.
112     // When traversing a signature such as `fn foo(x: impl Trait)`,
113     // we record `impl Trait` as a new type parameter, then later
114     // add it on to `foo`s generics.
115     in_band_ty_params: Vec<hir::TyParam>,
116
117     // Used to create lifetime definitions from in-band lifetime usages.
118     // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
119     // When a named lifetime is encountered in a function or impl header and
120     // has not been defined
121     // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
122     // to this list. The results of this list are then added to the list of
123     // lifetime definitions in the corresponding impl or function generics.
124     lifetimes_to_define: Vec<(Span, Name)>,
125     // Whether or not in-band lifetimes are being collected. This is used to
126     // indicate whether or not we're in a place where new lifetimes will result
127     // in in-band lifetime definitions, such a function or an impl header.
128     // This will always be false unless the `in_band_lifetimes` feature is
129     // enabled.
130     is_collecting_in_band_lifetimes: bool,
131     // Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
132     // When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
133     // against this list to see if it is already in-scope, or if a definition
134     // needs to be created for it.
135     in_scope_lifetimes: Vec<Name>,
136
137     type_def_lifetime_params: DefIdMap<usize>,
138
139     current_hir_id_owner: Vec<(DefIndex, u32)>,
140     item_local_id_counters: NodeMap<u32>,
141     node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
142 }
143
144 pub trait Resolver {
145     /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
146     fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
147
148     /// Obtain the resolution for a node id
149     fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
150
151     /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
152     /// This should only return `None` during testing.
153     fn definitions(&mut self) -> &mut Definitions;
154
155     /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
156     /// it based on `is_value`.
157     fn resolve_str_path(&mut self, span: Span, crate_root: Option<&str>,
158                 components: &[&str], is_value: bool) -> hir::Path;
159 }
160
161 #[derive(Clone, Copy, Debug)]
162 enum ImplTraitContext {
163     /// Treat `impl Trait` as shorthand for a new universal generic parameter.
164     /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
165     /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
166     ///
167     /// We store a DefId here so we can look up necessary information later
168     Universal(DefId),
169
170     /// Treat `impl Trait` as shorthand for a new universal existential parameter.
171     /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
172     /// equivalent to a fresh existential parameter like `abstract type T; fn foo() -> T`.
173     Existential,
174
175     /// `impl Trait` is not accepted in this position.
176     Disallowed,
177 }
178
179 pub fn lower_crate(sess: &Session,
180                    cstore: &CrateStore,
181                    dep_graph: &DepGraph,
182                    krate: &Crate,
183                    resolver: &mut Resolver)
184                    -> hir::Crate {
185     // We're constructing the HIR here; we don't care what we will
186     // read, since we haven't even constructed the *input* to
187     // incr. comp. yet.
188     dep_graph.assert_ignored();
189
190     LoweringContext {
191         crate_root: std_inject::injected_crate_name(),
192         sess,
193         cstore,
194         parent_def: None,
195         resolver,
196         name_map: FxHashMap(),
197         items: BTreeMap::new(),
198         trait_items: BTreeMap::new(),
199         impl_items: BTreeMap::new(),
200         bodies: BTreeMap::new(),
201         trait_impls: BTreeMap::new(),
202         trait_auto_impl: BTreeMap::new(),
203         exported_macros: Vec::new(),
204         catch_scopes: Vec::new(),
205         loop_scopes: Vec::new(),
206         is_in_loop_condition: false,
207         type_def_lifetime_params: DefIdMap(),
208         current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
209         item_local_id_counters: NodeMap(),
210         node_id_to_hir_id: IndexVec::new(),
211         is_generator: false,
212         is_in_trait_impl: false,
213         in_band_ty_params: Vec::new(),
214         lifetimes_to_define: Vec::new(),
215         is_collecting_in_band_lifetimes: false,
216         in_scope_lifetimes: Vec::new(),
217     }.lower_crate(krate)
218 }
219
220 #[derive(Copy, Clone, PartialEq, Eq)]
221 enum ParamMode {
222     /// Any path in a type context.
223     Explicit,
224     /// The `module::Type` in `module::Type::method` in an expression.
225     Optional
226 }
227
228 struct LoweredNodeId {
229     node_id: NodeId,
230     hir_id: hir::HirId,
231 }
232
233 enum ParenthesizedGenericArgs {
234     Ok,
235     Warn,
236     Err,
237 }
238
239 impl<'a> LoweringContext<'a> {
240     fn lower_crate(mut self, c: &Crate) -> hir::Crate {
241         /// Full-crate AST visitor that inserts into a fresh
242         /// `LoweringContext` any information that may be
243         /// needed from arbitrary locations in the crate.
244         /// E.g. The number of lifetime generic parameters
245         /// declared for every type and trait definition.
246         struct MiscCollector<'lcx, 'interner: 'lcx> {
247             lctx: &'lcx mut LoweringContext<'interner>,
248         }
249
250         impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
251             fn visit_item(&mut self, item: &'lcx Item) {
252                 self.lctx.allocate_hir_id_counter(item.id, item);
253
254                 match item.node {
255                     ItemKind::Struct(_, ref generics) |
256                     ItemKind::Union(_, ref generics) |
257                     ItemKind::Enum(_, ref generics) |
258                     ItemKind::Ty(_, ref generics) |
259                     ItemKind::Trait(_, _, ref generics, ..) => {
260                         let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
261                         let count = generics.params.iter()
262                             .filter(|param| param.is_lifetime_param())
263                             .count();
264                         self.lctx.type_def_lifetime_params.insert(def_id, count);
265                     }
266                     _ => {}
267                 }
268                 visit::walk_item(self, item);
269             }
270
271             fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
272                 self.lctx.allocate_hir_id_counter(item.id, item);
273                 visit::walk_trait_item(self, item);
274             }
275
276             fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
277                 self.lctx.allocate_hir_id_counter(item.id, item);
278                 visit::walk_impl_item(self, item);
279             }
280         }
281
282         struct ItemLowerer<'lcx, 'interner: 'lcx> {
283             lctx: &'lcx mut LoweringContext<'interner>,
284         }
285
286         impl<'lcx, 'interner> ItemLowerer<'lcx, 'interner> {
287             fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
288                 where F: FnOnce(&mut Self)
289             {
290                 let old = self.lctx.is_in_trait_impl;
291                 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
292                     false
293                 } else {
294                     true
295                 };
296                 f(self);
297                 self.lctx.is_in_trait_impl = old;
298             }
299         }
300
301         impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
302             fn visit_item(&mut self, item: &'lcx Item) {
303                 let mut item_lowered = true;
304                 self.lctx.with_hir_id_owner(item.id, |lctx| {
305                     if let Some(hir_item) = lctx.lower_item(item) {
306                         lctx.items.insert(item.id, hir_item);
307                     } else {
308                         item_lowered = false;
309                     }
310                 });
311
312                 if item_lowered {
313                     let item_lifetimes = match self.lctx.items.get(&item.id).unwrap().node {
314                         hir::Item_::ItemImpl(_,_,_,ref generics,..) |
315                         hir::Item_::ItemTrait(_,_,ref generics,..) =>
316                             generics.lifetimes().cloned().collect::<Vec<_>>(),
317                         _ => Vec::new(),
318                     };
319
320                     self.lctx.with_parent_impl_lifetime_defs(&item_lifetimes, |this| {
321                         let this = &mut ItemLowerer { lctx: this };
322                         if let ItemKind::Impl(_,_,_,_,ref opt_trait_ref,_,_) = item.node {
323                             this.with_trait_impl_ref(opt_trait_ref, |this| {
324                                 visit::walk_item(this, item)
325                             });
326                         } else {
327                             visit::walk_item(this, item);
328                         }
329                     });
330                 }
331             }
332
333             fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
334                 self.lctx.with_hir_id_owner(item.id, |lctx| {
335                     let id = hir::TraitItemId { node_id: item.id };
336                     let hir_item = lctx.lower_trait_item(item);
337                     lctx.trait_items.insert(id, hir_item);
338                 });
339
340                 visit::walk_trait_item(self, item);
341             }
342
343             fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
344                 self.lctx.with_hir_id_owner(item.id, |lctx| {
345                     let id = hir::ImplItemId { node_id: item.id };
346                     let hir_item = lctx.lower_impl_item(item);
347                     lctx.impl_items.insert(id, hir_item);
348                 });
349                 visit::walk_impl_item(self, item);
350             }
351         }
352
353         self.lower_node_id(CRATE_NODE_ID);
354         debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
355
356         visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
357         visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
358
359         let module = self.lower_mod(&c.module);
360         let attrs = self.lower_attrs(&c.attrs);
361         let body_ids = body_ids(&self.bodies);
362
363         self.resolver
364             .definitions()
365             .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
366
367         hir::Crate {
368             module,
369             attrs,
370             span: c.span,
371             exported_macros: hir::HirVec::from(self.exported_macros),
372             items: self.items,
373             trait_items: self.trait_items,
374             impl_items: self.impl_items,
375             bodies: self.bodies,
376             body_ids,
377             trait_impls: self.trait_impls,
378             trait_auto_impl: self.trait_auto_impl,
379         }
380     }
381
382     fn allocate_hir_id_counter<T: Debug>(&mut self,
383                                          owner: NodeId,
384                                          debug: &T) {
385         if self.item_local_id_counters.insert(owner, 0).is_some() {
386             bug!("Tried to allocate item_local_id_counter for {:?} twice", debug);
387         }
388         // Always allocate the first HirId for the owner itself
389         self.lower_node_id_with_owner(owner, owner);
390     }
391
392     fn lower_node_id_generic<F>(&mut self,
393                                 ast_node_id: NodeId,
394                                 alloc_hir_id: F)
395                                 -> LoweredNodeId
396         where F: FnOnce(&mut Self) -> hir::HirId
397     {
398         if ast_node_id == DUMMY_NODE_ID {
399             return LoweredNodeId {
400                 node_id: DUMMY_NODE_ID,
401                 hir_id: hir::DUMMY_HIR_ID,
402             }
403         }
404
405         let min_size = ast_node_id.as_usize() + 1;
406
407         if min_size > self.node_id_to_hir_id.len() {
408             self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
409         }
410
411         let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
412
413         if existing_hir_id == hir::DUMMY_HIR_ID {
414             // Generate a new HirId
415             let hir_id = alloc_hir_id(self);
416             self.node_id_to_hir_id[ast_node_id] = hir_id;
417             LoweredNodeId {
418                 node_id: ast_node_id,
419                 hir_id,
420             }
421         } else {
422             LoweredNodeId {
423                 node_id: ast_node_id,
424                 hir_id: existing_hir_id,
425             }
426         }
427     }
428
429     fn with_hir_id_owner<F>(&mut self, owner: NodeId, f: F)
430         where F: FnOnce(&mut Self)
431     {
432         let counter = self.item_local_id_counters
433                           .insert(owner, HIR_ID_COUNTER_LOCKED)
434                           .unwrap();
435         let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
436         self.current_hir_id_owner.push((def_index, counter));
437         f(self);
438         let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
439
440         debug_assert!(def_index == new_def_index);
441         debug_assert!(new_counter >= counter);
442
443         let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap();
444         debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
445     }
446
447     /// This method allocates a new HirId for the given NodeId and stores it in
448     /// the LoweringContext's NodeId => HirId map.
449     /// Take care not to call this method if the resulting HirId is then not
450     /// actually used in the HIR, as that would trigger an assertion in the
451     /// HirIdValidator later on, which makes sure that all NodeIds got mapped
452     /// properly. Calling the method twice with the same NodeId is fine though.
453     fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
454         self.lower_node_id_generic(ast_node_id, |this| {
455             let &mut (def_index, ref mut local_id_counter) = this.current_hir_id_owner
456                                                                  .last_mut()
457                                                                  .unwrap();
458             let local_id = *local_id_counter;
459             *local_id_counter += 1;
460             hir::HirId {
461                 owner: def_index,
462                 local_id: hir::ItemLocalId(local_id),
463             }
464         })
465     }
466
467     fn lower_node_id_with_owner(&mut self,
468                                 ast_node_id: NodeId,
469                                 owner: NodeId)
470                                 -> LoweredNodeId {
471         self.lower_node_id_generic(ast_node_id, |this| {
472             let local_id_counter = this.item_local_id_counters
473                                        .get_mut(&owner)
474                                        .unwrap();
475             let local_id = *local_id_counter;
476
477             // We want to be sure not to modify the counter in the map while it
478             // is also on the stack. Otherwise we'll get lost updates when writing
479             // back from the stack to the map.
480             debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
481
482             *local_id_counter += 1;
483             let def_index = this.resolver.definitions().opt_def_index(owner).unwrap();
484
485             hir::HirId {
486                 owner: def_index,
487                 local_id: hir::ItemLocalId(local_id),
488             }
489         })
490     }
491
492     fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>)
493                    -> hir::BodyId {
494         let body = hir::Body {
495             arguments: decl.map_or(hir_vec![], |decl| {
496                 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
497             }),
498             is_generator: self.is_generator,
499             value,
500         };
501         let id = body.id();
502         self.bodies.insert(id, body);
503         id
504     }
505
506     fn next_id(&mut self) -> LoweredNodeId {
507         self.lower_node_id(self.sess.next_node_id())
508     }
509
510     fn expect_full_def(&mut self, id: NodeId) -> Def {
511         self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
512             if pr.unresolved_segments() != 0 {
513                 bug!("path not fully resolved: {:?}", pr);
514             }
515             pr.base_def()
516         })
517     }
518
519     fn diagnostic(&self) -> &errors::Handler {
520         self.sess.diagnostic()
521     }
522
523     fn str_to_ident(&self, s: &'static str) -> Name {
524         Symbol::gensym(s)
525     }
526
527     fn allow_internal_unstable(&self, reason: CompilerDesugaringKind, span: Span) -> Span
528     {
529         let mark = Mark::fresh(Mark::root());
530         mark.set_expn_info(codemap::ExpnInfo {
531             call_site: span,
532             callee: codemap::NameAndSpan {
533                 format: codemap::CompilerDesugaring(reason),
534                 span: Some(span),
535                 allow_internal_unstable: true,
536                 allow_internal_unsafe: false,
537             },
538         });
539         span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
540     }
541
542     // Creates a new hir::GenericParam for every new lifetime and type parameter
543     // encountered while evaluating `f`. Definitions are created with the parent
544     // provided. If no `parent_id` is provided, no definitions will be returned.
545     fn collect_in_band_defs<T, F>(
546         &mut self,
547         parent_id: Option<DefId>,
548         f: F
549     ) -> (Vec<hir::GenericParam>, T) where F: FnOnce(&mut LoweringContext) -> T
550     {
551         assert!(!self.is_collecting_in_band_lifetimes);
552         assert!(self.lifetimes_to_define.is_empty());
553         self.is_collecting_in_band_lifetimes = self.sess.features.borrow().in_band_lifetimes;
554
555         assert!(self.in_band_ty_params.is_empty());
556
557         let res = f(self);
558
559         self.is_collecting_in_band_lifetimes = false;
560
561         let in_band_ty_params = self.in_band_ty_params.split_off(0);
562         let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
563
564         let mut params = match parent_id {
565             Some(parent_id) => lifetimes_to_define.into_iter().map(|(span, name)| {
566                     let def_node_id = self.next_id().node_id;
567
568                     // Add a definition for the in-band lifetime def
569                     self.resolver.definitions().create_def_with_parent(
570                         parent_id.index,
571                         def_node_id,
572                         DefPathData::LifetimeDef(name.as_str()),
573                         DefIndexAddressSpace::High,
574                         Mark::root()
575                     );
576
577                     hir::GenericParam::Lifetime(hir::LifetimeDef {
578                         lifetime: hir::Lifetime {
579                             id: def_node_id,
580                             span,
581                             name: hir::LifetimeName::Name(name),
582                         },
583                         bounds: Vec::new().into(),
584                         pure_wrt_drop: false,
585                         in_band: true,
586                     })
587                 }).collect(),
588             None => Vec::new(),
589         };
590
591         params.extend(in_band_ty_params.into_iter().map(|tp| hir::GenericParam::Type(tp)));
592
593         (params, res)
594     }
595
596     // Evaluates `f` with the lifetimes in `lt_defs` in-scope.
597     // This is used to track which lifetimes have already been defined, and
598     // which are new in-band lifetimes that need to have a definition created
599     // for them.
600     fn with_in_scope_lifetime_defs<T, F>(
601         &mut self,
602         lt_defs: &[LifetimeDef],
603         f: F
604     ) -> T where F: FnOnce(&mut LoweringContext) -> T
605     {
606         let old_len = self.in_scope_lifetimes.len();
607         let lt_def_names = lt_defs.iter().map(|lt_def| lt_def.lifetime.ident.name);
608         self.in_scope_lifetimes.extend(lt_def_names);
609
610         let res = f(self);
611
612         self.in_scope_lifetimes.truncate(old_len);
613         res
614     }
615
616     // Same as the method above, but accepts `hir::LifetimeDef`s
617     // instead of `ast::LifetimeDef`s.
618     // This should only be used with generics that have already had their
619     // in-band lifetimes added. In practice, this means that this function is
620     // only used when lowering a child item of a trait or impl.
621     fn with_parent_impl_lifetime_defs<T, F>(
622         &mut self,
623         lt_defs: &[hir::LifetimeDef],
624         f: F
625     ) -> T where F: FnOnce(&mut LoweringContext) -> T
626     {
627         let old_len = self.in_scope_lifetimes.len();
628         let lt_def_names = lt_defs.iter().map(|lt_def| lt_def.lifetime.name.name());
629         self.in_scope_lifetimes.extend(lt_def_names);
630
631         let res = f(self);
632
633         self.in_scope_lifetimes.truncate(old_len);
634         res
635     }
636
637     // Appends in-band lifetime defs and argument-position `impl Trait` defs
638     // to the existing set of generics.
639     fn add_in_band_defs<F, T>(
640         &mut self,
641         generics: &Generics,
642         parent_id: Option<DefId>,
643         f: F
644     ) -> (hir::Generics, T)
645         where F: FnOnce(&mut LoweringContext) -> T
646     {
647         let (in_band_defs, (mut lowered_generics, res)) =
648             self.with_in_scope_lifetime_defs(
649                 &generics.params
650                     .iter()
651                     .filter_map(|p| match *p {
652                         GenericParam::Lifetime(ref ld) => Some(ld.clone()),
653                         _ => None,
654                     })
655                     .collect::<Vec<_>>(),
656                 |this| {
657                     this.collect_in_band_defs(parent_id, |this| {
658                         (this.lower_generics(generics), f(this))
659                     })
660                 }
661             );
662
663         lowered_generics.params =
664             lowered_generics.params.iter().cloned().chain(in_band_defs).collect();
665
666         (lowered_generics, res)
667     }
668
669     fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
670         where F: FnOnce(&mut LoweringContext) -> T
671     {
672         let len = self.catch_scopes.len();
673         self.catch_scopes.push(catch_id);
674
675         let result = f(self);
676         assert_eq!(len + 1, self.catch_scopes.len(),
677             "catch scopes should be added and removed in stack order");
678
679         self.catch_scopes.pop().unwrap();
680
681         result
682     }
683
684     fn lower_body<F>(&mut self, decl: Option<&FnDecl>, f: F) -> hir::BodyId
685         where F: FnOnce(&mut LoweringContext) -> hir::Expr
686     {
687         let prev = mem::replace(&mut self.is_generator, false);
688         let result = f(self);
689         let r = self.record_body(result, decl);
690         self.is_generator = prev;
691         return r
692     }
693
694     fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
695         where F: FnOnce(&mut LoweringContext) -> T
696     {
697         // We're no longer in the base loop's condition; we're in another loop.
698         let was_in_loop_condition = self.is_in_loop_condition;
699         self.is_in_loop_condition = false;
700
701         let len = self.loop_scopes.len();
702         self.loop_scopes.push(loop_id);
703
704         let result = f(self);
705         assert_eq!(len + 1, self.loop_scopes.len(),
706             "Loop scopes should be added and removed in stack order");
707
708         self.loop_scopes.pop().unwrap();
709
710         self.is_in_loop_condition = was_in_loop_condition;
711
712         result
713     }
714
715     fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
716         where F: FnOnce(&mut LoweringContext) -> T
717     {
718         let was_in_loop_condition = self.is_in_loop_condition;
719         self.is_in_loop_condition = true;
720
721         let result = f(self);
722
723         self.is_in_loop_condition = was_in_loop_condition;
724
725         result
726     }
727
728     fn with_new_scopes<T, F>(&mut self, f: F) -> T
729         where F: FnOnce(&mut LoweringContext) -> T
730     {
731         let was_in_loop_condition = self.is_in_loop_condition;
732         self.is_in_loop_condition = false;
733
734         let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
735         let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
736         let result = f(self);
737         self.catch_scopes = catch_scopes;
738         self.loop_scopes = loop_scopes;
739
740         self.is_in_loop_condition = was_in_loop_condition;
741
742         result
743     }
744
745     fn with_parent_def<T, F>(&mut self, parent_id: NodeId, f: F) -> T
746         where F: FnOnce(&mut LoweringContext) -> T
747     {
748         let old_def = self.parent_def;
749         self.parent_def = {
750             let defs = self.resolver.definitions();
751             Some(defs.opt_def_index(parent_id).unwrap())
752         };
753
754         let result = f(self);
755
756         self.parent_def = old_def;
757         result
758     }
759
760     fn def_key(&mut self, id: DefId) -> DefKey {
761         if id.is_local() {
762             self.resolver.definitions().def_key(id.index)
763         } else {
764             self.cstore.def_key(id)
765         }
766     }
767
768     fn lower_ident(&mut self, ident: Ident) -> Name {
769         let ident = ident.modern();
770         if ident.ctxt == SyntaxContext::empty() {
771             return ident.name;
772         }
773         *self.name_map.entry(ident).or_insert_with(|| Symbol::from_ident(ident))
774     }
775
776     fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
777         label.map(|label| hir::Label { name: label.ident.name, span: label.span })
778     }
779
780     fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>)
781         -> hir::Destination
782     {
783         match destination {
784             Some((id, label)) => {
785                 let target = if let Def::Label(loop_id) = self.expect_full_def(id) {
786                     hir::LoopIdResult::Ok(self.lower_node_id(loop_id).node_id)
787                 } else {
788                     hir::LoopIdResult::Err(hir::LoopIdError::UnresolvedLabel)
789                 };
790                 hir::Destination {
791                     label: self.lower_label(Some(label)),
792                     target_id: hir::ScopeTarget::Loop(target),
793                 }
794             },
795             None => {
796                 let loop_id = self.loop_scopes
797                                   .last()
798                                   .map(|innermost_loop_id| *innermost_loop_id);
799
800                 hir::Destination {
801                     label: None,
802                     target_id: hir::ScopeTarget::Loop(
803                         loop_id.map(|id| Ok(self.lower_node_id(id).node_id))
804                                .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
805                                .into())
806                 }
807             }
808         }
809     }
810
811     fn lower_attrs(&mut self, attrs: &Vec<Attribute>) -> hir::HirVec<Attribute> {
812         attrs.iter().map(|a| self.lower_attr(a)).collect::<Vec<_>>().into()
813     }
814
815     fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
816         Attribute {
817             id: attr.id,
818             style: attr.style,
819             path: attr.path.clone(),
820             tokens: self.lower_token_stream(attr.tokens.clone()),
821             is_sugared_doc: attr.is_sugared_doc,
822             span: attr.span,
823         }
824     }
825
826     fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
827         tokens.into_trees()
828             .flat_map(|tree| self.lower_token_tree(tree).into_trees())
829             .collect()
830     }
831
832     fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
833         match tree {
834             TokenTree::Token(span, token) => {
835                 self.lower_token(token, span)
836             }
837             TokenTree::Delimited(span, delimited) => {
838                 TokenTree::Delimited(span, Delimited {
839                     delim: delimited.delim,
840                     tts: self.lower_token_stream(delimited.tts.into()).into(),
841                 }).into()
842             }
843         }
844     }
845
846     fn lower_token(&mut self, token: Token, span: Span) -> TokenStream {
847         match token {
848             Token::Interpolated(_) => {}
849             other => return TokenTree::Token(span, other).into(),
850         }
851
852         let tts = token.interpolated_to_tokenstream(&self.sess.parse_sess, span);
853         self.lower_token_stream(tts)
854     }
855
856     fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
857         hir::Arm {
858             attrs: self.lower_attrs(&arm.attrs),
859             pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
860             guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
861             body: P(self.lower_expr(&arm.body)),
862         }
863     }
864
865     fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir::TypeBinding {
866         hir::TypeBinding {
867             id: self.lower_node_id(b.id).node_id,
868             name: self.lower_ident(b.ident),
869             ty: self.lower_ty(&b.ty, itctx),
870             span: b.span,
871         }
872     }
873
874     fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
875         let kind = match t.node {
876             TyKind::Infer => hir::TyInfer,
877             TyKind::Err => hir::TyErr,
878             TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty, itctx)),
879             TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt, itctx)),
880             TyKind::Rptr(ref region, ref mt) => {
881                 let span = t.span.with_hi(t.span.lo());
882                 let lifetime = match *region {
883                     Some(ref lt) => self.lower_lifetime(lt),
884                     None => self.elided_lifetime(span)
885                 };
886                 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
887             }
888             TyKind::BareFn(ref f) => {
889                 self.with_in_scope_lifetime_defs(
890                     &f.generic_params
891                         .iter()
892                         .filter_map(|p| match *p {
893                             GenericParam::Lifetime(ref ld) => Some(ld.clone()),
894                             _ => None,
895                         })
896                         .collect::<Vec<_>>(),
897                     |this| hir::TyBareFn(P(hir::BareFnTy {
898                         generic_params: this.lower_generic_params(&f.generic_params, &NodeMap()),
899                         unsafety: this.lower_unsafety(f.unsafety),
900                         abi: f.abi,
901                         decl: this.lower_fn_decl(&f.decl, None, false),
902                         arg_names: this.lower_fn_args_to_names(&f.decl),
903                     })))
904             }
905             TyKind::Never => hir::TyNever,
906             TyKind::Tup(ref tys) => {
907                 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty, itctx)).collect())
908             }
909             TyKind::Paren(ref ty) => {
910                 return self.lower_ty(ty, itctx);
911             }
912             TyKind::Path(ref qself, ref path) => {
913                 let id = self.lower_node_id(t.id);
914                 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit, itctx);
915                 return self.ty_path(id, t.span, qpath);
916             }
917             TyKind::ImplicitSelf => {
918                 hir::TyPath(hir::QPath::Resolved(None, P(hir::Path {
919                     def: self.expect_full_def(t.id),
920                     segments: hir_vec![
921                         hir::PathSegment::from_name(keywords::SelfType.name())
922                     ],
923                     span: t.span,
924                 })))
925             }
926             TyKind::Array(ref ty, ref length) => {
927                 let length = self.lower_body(None, |this| this.lower_expr(length));
928                 hir::TyArray(self.lower_ty(ty, itctx), length)
929             }
930             TyKind::Typeof(ref expr) => {
931                 let expr = self.lower_body(None, |this| this.lower_expr(expr));
932                 hir::TyTypeof(expr)
933             }
934             TyKind::TraitObject(ref bounds, ..) => {
935                 let mut lifetime_bound = None;
936                 let bounds = bounds.iter().filter_map(|bound| {
937                     match *bound {
938                         TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
939                             Some(self.lower_poly_trait_ref(ty, itctx))
940                         }
941                         TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
942                         RegionTyParamBound(ref lifetime) => {
943                             if lifetime_bound.is_none() {
944                                 lifetime_bound = Some(self.lower_lifetime(lifetime));
945                             }
946                             None
947                         }
948                     }
949                 }).collect();
950                 let lifetime_bound = lifetime_bound.unwrap_or_else(|| {
951                     self.elided_lifetime(t.span)
952                 });
953                 hir::TyTraitObject(bounds, lifetime_bound)
954             }
955             TyKind::ImplTrait(ref bounds) => {
956                 use syntax::feature_gate::{emit_feature_err, GateIssue};
957                 let span = t.span;
958                 match itctx {
959                     ImplTraitContext::Existential => {
960                         let has_feature = self.sess.features.borrow().conservative_impl_trait;
961                         if !t.span.allows_unstable() && !has_feature {
962                             emit_feature_err(&self.sess.parse_sess, "conservative_impl_trait",
963                                              t.span, GateIssue::Language,
964                                              "`impl Trait` in return position is experimental");
965                         }
966                         let def_index = self.resolver.definitions().opt_def_index(t.id).unwrap();
967                         let hir_bounds = self.lower_bounds(bounds, itctx);
968                         let (lifetimes, lifetime_defs) =
969                             self.lifetimes_from_impl_trait_bounds(def_index, &hir_bounds);
970
971                         hir::TyImplTraitExistential(hir::ExistTy {
972                             generics: hir::Generics {
973                                 params: lifetime_defs,
974                                 where_clause: hir::WhereClause {
975                                     id: self.next_id().node_id,
976                                     predicates: Vec::new().into(),
977                                 },
978                                 span,
979                             },
980                             bounds: hir_bounds,
981                         }, lifetimes)
982                     },
983                     ImplTraitContext::Universal(def_id) => {
984                         let has_feature = self.sess.features.borrow().universal_impl_trait;
985                         if !t.span.allows_unstable() && !has_feature {
986                             emit_feature_err(&self.sess.parse_sess, "universal_impl_trait",
987                                              t.span, GateIssue::Language,
988                                              "`impl Trait` in argument position is experimental");
989                         }
990
991                         let def_node_id = self.next_id().node_id;
992
993                         // Add a definition for the in-band TyParam
994                         let def_index = self.resolver.definitions().create_def_with_parent(
995                             def_id.index,
996                             def_node_id,
997                             DefPathData::ImplTrait,
998                             DefIndexAddressSpace::High,
999                             Mark::root()
1000                         );
1001
1002                         let hir_bounds = self.lower_bounds(bounds, itctx);
1003                         // Set the name to `impl Bound1 + Bound2`
1004                         let name = Symbol::intern(&pprust::ty_to_string(t));
1005                         self.in_band_ty_params.push(hir::TyParam {
1006                             name,
1007                             id: def_node_id,
1008                             bounds: hir_bounds,
1009                             default: None,
1010                             span,
1011                             pure_wrt_drop: false,
1012                             synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1013                         });
1014
1015                         hir::TyPath(hir::QPath::Resolved(None, P(hir::Path {
1016                             span,
1017                             def: Def::TyParam(DefId::local(def_index)),
1018                             segments: hir_vec![hir::PathSegment::from_name(name)],
1019                         })))
1020                     },
1021                     ImplTraitContext::Disallowed => {
1022                         span_err!(self.sess, t.span, E0562,
1023                                   "`impl Trait` not allowed outside of function \
1024                                   and inherent method return types");
1025                         hir::TyErr
1026                     }
1027                 }
1028             }
1029             TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
1030         };
1031
1032         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(t.id);
1033         P(hir::Ty {
1034             id: node_id,
1035             node: kind,
1036             span: t.span,
1037             hir_id,
1038         })
1039     }
1040
1041     fn lifetimes_from_impl_trait_bounds(
1042         &mut self,
1043         parent_index: DefIndex,
1044         bounds: &hir::TyParamBounds
1045     ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
1046
1047         // This visitor walks over impl trait bounds and creates defs for all lifetimes which
1048         // appear in the bounds, excluding lifetimes that are created within the bounds.
1049         // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
1050         struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
1051             context: &'r mut LoweringContext<'a>,
1052             parent: DefIndex,
1053             collect_elided_lifetimes: bool,
1054             currently_bound_lifetimes: Vec<hir::LifetimeName>,
1055             already_defined_lifetimes: HashSet<hir::LifetimeName>,
1056             output_lifetimes: Vec<hir::Lifetime>,
1057             output_lifetime_params: Vec<hir::GenericParam>,
1058         }
1059
1060         impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1061             fn nested_visit_map<'this>(&'this mut self)
1062                 -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1063                 hir::intravisit::NestedVisitorMap::None
1064             }
1065
1066             fn visit_path_parameters(&mut self, span: Span, parameters: &'v hir::PathParameters) {
1067                 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1068                 if parameters.parenthesized {
1069                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1070                     self.collect_elided_lifetimes = false;
1071                     hir::intravisit::walk_path_parameters(self, span, parameters);
1072                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1073                 } else {
1074                     hir::intravisit::walk_path_parameters(self, span, parameters);
1075                 }
1076             }
1077
1078             fn visit_ty(&mut self, t: &'v hir::Ty) {
1079                 // Don't collect elided lifetimes used inside of `fn()` syntax
1080                 if let &hir::Ty_::TyBareFn(_) = &t.node {
1081                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1082                     self.collect_elided_lifetimes = false;
1083                     hir::intravisit::walk_ty(self, t);
1084                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1085                 } else {
1086                     hir::intravisit::walk_ty(self, t);
1087                 }
1088             }
1089
1090             fn visit_poly_trait_ref(&mut self,
1091                                     polytr: &'v hir::PolyTraitRef,
1092                                     _: hir::TraitBoundModifier) {
1093                 let old_len = self.currently_bound_lifetimes.len();
1094
1095                 // Record the introduction of 'a in `for<'a> ...`
1096                 for param in &polytr.bound_generic_params {
1097                     if let hir::GenericParam::Lifetime(ref lt_def) = *param {
1098                         // Introduce lifetimes one at a time so that we can handle
1099                         // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
1100                         self.currently_bound_lifetimes.push(lt_def.lifetime.name);
1101
1102                         // Visit the lifetime bounds
1103                         for lt_bound in &lt_def.bounds {
1104                             self.visit_lifetime(&lt_bound);
1105                         }
1106                     }
1107                 }
1108
1109                 hir::intravisit::walk_trait_ref(self, &polytr.trait_ref);
1110
1111                 self.currently_bound_lifetimes.truncate(old_len);
1112             }
1113
1114             fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1115                 let name = match lifetime.name {
1116                     hir::LifetimeName::Implicit |
1117                     hir::LifetimeName::Underscore =>
1118                         if self.collect_elided_lifetimes {
1119                             // Use `'_` for both implicit and underscore lifetimes in
1120                             // `abstract type Foo<'_>: SomeTrait<'_>;`
1121                             hir::LifetimeName::Underscore
1122                         } else {
1123                             return
1124                         }
1125                     name @ hir::LifetimeName::Name(_) => name,
1126                     hir::LifetimeName::Static => return,
1127                 };
1128
1129                 if !self.currently_bound_lifetimes.contains(&name) &&
1130                    !self.already_defined_lifetimes.contains(&name)
1131                 {
1132                     self.already_defined_lifetimes.insert(name);
1133
1134                     self.output_lifetimes.push(hir::Lifetime {
1135                         id: self.context.next_id().node_id,
1136                         span: lifetime.span,
1137                         name,
1138                     });
1139
1140                     let def_node_id = self.context.next_id().node_id;
1141                     self.context.resolver.definitions().create_def_with_parent(
1142                         self.parent,
1143                         def_node_id,
1144                         DefPathData::LifetimeDef(name.name().as_str()),
1145                         DefIndexAddressSpace::High,
1146                         Mark::root()
1147                     );
1148                     let def_lifetime = hir::Lifetime {
1149                         id: def_node_id,
1150                         span: lifetime.span,
1151                         name: name,
1152                     };
1153                     self.output_lifetime_params.push(hir::GenericParam::Lifetime(hir::LifetimeDef {
1154                         lifetime: def_lifetime,
1155                         bounds: Vec::new().into(),
1156                         pure_wrt_drop: false,
1157                         in_band: false,
1158                     }));
1159                 }
1160             }
1161         }
1162
1163         let mut lifetime_collector = ImplTraitLifetimeCollector {
1164             context: self,
1165             parent: parent_index,
1166             collect_elided_lifetimes: true,
1167             currently_bound_lifetimes: Vec::new(),
1168             already_defined_lifetimes: HashSet::new(),
1169             output_lifetimes: Vec::new(),
1170             output_lifetime_params: Vec::new(),
1171         };
1172
1173         for bound in bounds {
1174             hir::intravisit::walk_ty_param_bound(&mut lifetime_collector, &bound);
1175         }
1176
1177         (
1178             lifetime_collector.output_lifetimes.into(),
1179             lifetime_collector.output_lifetime_params.into()
1180         )
1181     }
1182
1183     fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1184         hir::ForeignMod {
1185             abi: fm.abi,
1186             items: fm.items.iter().map(|x| self.lower_foreign_item(x)).collect(),
1187         }
1188     }
1189
1190     fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1191         P(hir::GlobalAsm {
1192             asm: ga.asm,
1193             ctxt: ga.ctxt,
1194         })
1195     }
1196
1197     fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1198         Spanned {
1199             node: hir::Variant_ {
1200                 name: v.node.name.name,
1201                 attrs: self.lower_attrs(&v.node.attrs),
1202                 data: self.lower_variant_data(&v.node.data),
1203                 disr_expr: v.node.disr_expr.as_ref().map(|e| {
1204                     self.lower_body(None, |this| this.lower_expr(e))
1205                 }),
1206             },
1207             span: v.span,
1208         }
1209     }
1210
1211     fn lower_qpath(&mut self,
1212                    id: NodeId,
1213                    qself: &Option<QSelf>,
1214                    p: &Path,
1215                    param_mode: ParamMode,
1216                    itctx: ImplTraitContext)
1217                    -> hir::QPath {
1218         let qself_position = qself.as_ref().map(|q| q.position);
1219         let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx));
1220
1221         let resolution = self.resolver.get_resolution(id)
1222                                       .unwrap_or(PathResolution::new(Def::Err));
1223
1224         let proj_start = p.segments.len() - resolution.unresolved_segments();
1225         let path = P(hir::Path {
1226             def: resolution.base_def(),
1227             segments: p.segments[..proj_start].iter().enumerate().map(|(i, segment)| {
1228                 let param_mode = match (qself_position, param_mode) {
1229                     (Some(j), ParamMode::Optional) if i < j => {
1230                         // This segment is part of the trait path in a
1231                         // qualified path - one of `a`, `b` or `Trait`
1232                         // in `<X as a::b::Trait>::T::U::method`.
1233                         ParamMode::Explicit
1234                     }
1235                     _ => param_mode
1236                 };
1237
1238                 // Figure out if this is a type/trait segment,
1239                 // which may need lifetime elision performed.
1240                 let parent_def_id = |this: &mut Self, def_id: DefId| {
1241                     DefId {
1242                         krate: def_id.krate,
1243                         index: this.def_key(def_id).parent.expect("missing parent")
1244                     }
1245                 };
1246                 let type_def_id = match resolution.base_def() {
1247                     Def::AssociatedTy(def_id) if i + 2 == proj_start => {
1248                         Some(parent_def_id(self, def_id))
1249                     }
1250                     Def::Variant(def_id) if i + 1 == proj_start => {
1251                         Some(parent_def_id(self, def_id))
1252                     }
1253                     Def::Struct(def_id) |
1254                     Def::Union(def_id) |
1255                     Def::Enum(def_id) |
1256                     Def::TyAlias(def_id) |
1257                     Def::Trait(def_id) if i + 1 == proj_start => Some(def_id),
1258                     _ => None
1259                 };
1260                 let parenthesized_generic_args = match resolution.base_def() {
1261                     // `a::b::Trait(Args)`
1262                     Def::Trait(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1263                     // `a::b::Trait(Args)::TraitItem`
1264                     Def::Method(..) |
1265                     Def::AssociatedConst(..) |
1266                     Def::AssociatedTy(..) if i + 2 == proj_start => ParenthesizedGenericArgs::Ok,
1267                     // Avoid duplicated errors
1268                     Def::Err => ParenthesizedGenericArgs::Ok,
1269                     // An error
1270                     Def::Struct(..) | Def::Enum(..) | Def::Union(..) | Def::TyAlias(..) |
1271                     Def::Variant(..) if i + 1 == proj_start => ParenthesizedGenericArgs::Err,
1272                     // A warning for now, for compatibility reasons
1273                     _ => ParenthesizedGenericArgs::Warn,
1274                 };
1275
1276                 let num_lifetimes = type_def_id.map_or(0, |def_id| {
1277                     if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1278                         return n;
1279                     }
1280                     assert!(!def_id.is_local());
1281                     let n = self.cstore
1282                                 .item_generics_cloned_untracked(def_id, self.sess)
1283                                 .regions
1284                                 .len();
1285                     self.type_def_lifetime_params.insert(def_id, n);
1286                     n
1287                 });
1288                 self.lower_path_segment(p.span, segment, param_mode, num_lifetimes,
1289                                         parenthesized_generic_args, itctx)
1290             }).collect(),
1291             span: p.span,
1292         });
1293
1294         // Simple case, either no projections, or only fully-qualified.
1295         // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
1296         if resolution.unresolved_segments() == 0 {
1297             return hir::QPath::Resolved(qself, path);
1298         }
1299
1300         // Create the innermost type that we're projecting from.
1301         let mut ty = if path.segments.is_empty() {
1302             // If the base path is empty that means there exists a
1303             // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
1304             qself.expect("missing QSelf for <T>::...")
1305         } else {
1306             // Otherwise, the base path is an implicit `Self` type path,
1307             // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1308             // `<I as Iterator>::Item::default`.
1309             let new_id = self.next_id();
1310             self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
1311         };
1312
1313         // Anything after the base path are associated "extensions",
1314         // out of which all but the last one are associated types,
1315         // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1316         // * base path is `std::vec::Vec<T>`
1317         // * "extensions" are `IntoIter`, `Item` and `clone`
1318         // * type nodes are:
1319         //   1. `std::vec::Vec<T>` (created above)
1320         //   2. `<std::vec::Vec<T>>::IntoIter`
1321         //   3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1322         // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1323         for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1324             let segment = P(self.lower_path_segment(p.span, segment, param_mode, 0,
1325                                                     ParenthesizedGenericArgs::Warn,
1326                                                     itctx));
1327             let qpath = hir::QPath::TypeRelative(ty, segment);
1328
1329             // It's finished, return the extension of the right node type.
1330             if i == p.segments.len() - 1 {
1331                 return qpath;
1332             }
1333
1334             // Wrap the associated extension in another type node.
1335             let new_id = self.next_id();
1336             ty = self.ty_path(new_id, p.span, qpath);
1337         }
1338
1339         // Should've returned in the for loop above.
1340         span_bug!(p.span, "lower_qpath: no final extension segment in {}..{}",
1341                   proj_start, p.segments.len())
1342     }
1343
1344     fn lower_path_extra(&mut self,
1345                         id: NodeId,
1346                         p: &Path,
1347                         name: Option<Name>,
1348                         param_mode: ParamMode,
1349                         defaults_to_global: bool)
1350                         -> hir::Path {
1351         let mut segments = p.segments.iter();
1352         if defaults_to_global && p.is_global() {
1353             segments.next();
1354         }
1355
1356         hir::Path {
1357             def: self.expect_full_def(id),
1358             segments: segments.map(|segment| {
1359                 self.lower_path_segment(p.span, segment, param_mode, 0,
1360                                         ParenthesizedGenericArgs::Err,
1361                                         ImplTraitContext::Disallowed)
1362             }).chain(name.map(|name| hir::PathSegment::from_name(name)))
1363               .collect(),
1364             span: p.span,
1365         }
1366     }
1367
1368     fn lower_path(&mut self,
1369                   id: NodeId,
1370                   p: &Path,
1371                   param_mode: ParamMode,
1372                   defaults_to_global: bool)
1373                   -> hir::Path {
1374         self.lower_path_extra(id, p, None, param_mode, defaults_to_global)
1375     }
1376
1377     fn lower_path_segment(&mut self,
1378                           path_span: Span,
1379                           segment: &PathSegment,
1380                           param_mode: ParamMode,
1381                           expected_lifetimes: usize,
1382                           parenthesized_generic_args: ParenthesizedGenericArgs,
1383                           itctx: ImplTraitContext)
1384                           -> hir::PathSegment {
1385         let (mut parameters, infer_types) = if let Some(ref parameters) = segment.parameters {
1386             let msg = "parenthesized parameters may only be used with a trait";
1387             match **parameters {
1388                 PathParameters::AngleBracketed(ref data) => {
1389                     self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1390                 }
1391                 PathParameters::Parenthesized(ref data) => match parenthesized_generic_args {
1392                     ParenthesizedGenericArgs::Ok =>
1393                         self.lower_parenthesized_parameter_data(data),
1394                     ParenthesizedGenericArgs::Warn => {
1395                         self.sess.buffer_lint(PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1396                                               CRATE_NODE_ID, data.span, msg.into());
1397                         (hir::PathParameters::none(), true)
1398                     }
1399                     ParenthesizedGenericArgs::Err => {
1400                         struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1401                             .span_label(data.span, "only traits may use parentheses").emit();
1402                         (hir::PathParameters::none(), true)
1403                     }
1404                 }
1405             }
1406         } else {
1407             self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1408         };
1409
1410         if !parameters.parenthesized && parameters.lifetimes.is_empty() {
1411             parameters.lifetimes = (0..expected_lifetimes).map(|_| {
1412                 self.elided_lifetime(path_span)
1413             }).collect();
1414         }
1415
1416         hir::PathSegment::new(
1417             self.lower_ident(segment.identifier),
1418             parameters,
1419             infer_types
1420         )
1421     }
1422
1423     fn lower_angle_bracketed_parameter_data(&mut self,
1424                                             data: &AngleBracketedParameterData,
1425                                             param_mode: ParamMode,
1426                                             itctx: ImplTraitContext)
1427                                             -> (hir::PathParameters, bool) {
1428         let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings, .. } = data;
1429         (hir::PathParameters {
1430             lifetimes: self.lower_lifetimes(lifetimes),
1431             types: types.iter().map(|ty| self.lower_ty(ty, itctx)).collect(),
1432             bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
1433             parenthesized: false,
1434         }, types.is_empty() && param_mode == ParamMode::Optional)
1435     }
1436
1437     fn lower_parenthesized_parameter_data(&mut self,
1438                                           data: &ParenthesizedParameterData)
1439                                           -> (hir::PathParameters, bool) {
1440         const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1441         let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
1442         let inputs = inputs.iter().map(|ty| self.lower_ty(ty, DISALLOWED)).collect();
1443         let mk_tup = |this: &mut Self, tys, span| {
1444             let LoweredNodeId { node_id, hir_id } = this.next_id();
1445             P(hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span })
1446         };
1447
1448         (hir::PathParameters {
1449             lifetimes: hir::HirVec::new(),
1450             types: hir_vec![mk_tup(self, inputs, span)],
1451             bindings: hir_vec![hir::TypeBinding {
1452                 id: self.next_id().node_id,
1453                 name: Symbol::intern(FN_OUTPUT_NAME),
1454                 ty: output.as_ref().map(|ty| self.lower_ty(&ty, DISALLOWED))
1455                                    .unwrap_or_else(|| mk_tup(self, hir::HirVec::new(), span)),
1456                 span: output.as_ref().map_or(span, |ty| ty.span),
1457             }],
1458             parenthesized: true,
1459         }, false)
1460     }
1461
1462     fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1463         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1464         P(hir::Local {
1465             id: node_id,
1466             hir_id,
1467             ty: l.ty.as_ref().map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1468             pat: self.lower_pat(&l.pat),
1469             init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1470             span: l.span,
1471             attrs: l.attrs.clone(),
1472             source: hir::LocalSource::Normal,
1473         })
1474     }
1475
1476     fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1477         match m {
1478             Mutability::Mutable => hir::MutMutable,
1479             Mutability::Immutable => hir::MutImmutable,
1480         }
1481     }
1482
1483     fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1484         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1485         hir::Arg {
1486             id: node_id,
1487             hir_id,
1488             pat: self.lower_pat(&arg.pat),
1489         }
1490     }
1491
1492     fn lower_fn_args_to_names(&mut self, decl: &FnDecl)
1493                               -> hir::HirVec<Spanned<Name>> {
1494         decl.inputs.iter().map(|arg| {
1495             match arg.pat.node {
1496                 PatKind::Ident(_, ident, None) => {
1497                     respan(ident.span, ident.node.name)
1498                 }
1499                 _ => respan(arg.pat.span, keywords::Invalid.name()),
1500             }
1501         }).collect()
1502     }
1503
1504
1505     fn lower_fn_decl(&mut self,
1506                      decl: &FnDecl,
1507                      fn_def_id: Option<DefId>,
1508                      impl_trait_return_allow: bool)
1509                      -> P<hir::FnDecl> {
1510         // NOTE: The two last parameters here have to do with impl Trait. If fn_def_id is Some,
1511         //       then impl Trait arguments are lowered into generic parameters on the given
1512         //       fn_def_id, otherwise impl Trait is disallowed. (for now)
1513         //
1514         //       Furthermore, if impl_trait_return_allow is true, then impl Trait may be used in
1515         //       return positions as well. This guards against trait declarations and their impls
1516         //       where impl Trait is disallowed. (again for now)
1517         P(hir::FnDecl {
1518             inputs: decl.inputs.iter()
1519                 .map(|arg| if let Some(def_id) = fn_def_id {
1520                     self.lower_ty(&arg.ty, ImplTraitContext::Universal(def_id))
1521                 } else {
1522                     self.lower_ty(&arg.ty, ImplTraitContext::Disallowed)
1523                 }).collect(),
1524             output: match decl.output {
1525                 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1526                     Some(_) if impl_trait_return_allow =>
1527                         hir::Return(self.lower_ty(ty, ImplTraitContext::Existential)),
1528                     _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1529                 },
1530                 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1531             },
1532             variadic: decl.variadic,
1533             has_implicit_self: decl.inputs.get(0).map_or(false, |arg| {
1534                 match arg.ty.node {
1535                     TyKind::ImplicitSelf => true,
1536                     TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1537                     _ => false
1538                 }
1539             })
1540         })
1541     }
1542
1543     fn lower_ty_param_bound(&mut self, tpb: &TyParamBound, itctx: ImplTraitContext)
1544                             -> hir::TyParamBound {
1545         match *tpb {
1546             TraitTyParamBound(ref ty, modifier) => {
1547                 hir::TraitTyParamBound(self.lower_poly_trait_ref(ty, itctx),
1548                                        self.lower_trait_bound_modifier(modifier))
1549             }
1550             RegionTyParamBound(ref lifetime) => {
1551                 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
1552             }
1553         }
1554     }
1555
1556     fn lower_ty_param(&mut self, tp: &TyParam, add_bounds: &[TyParamBound]) -> hir::TyParam {
1557         let mut name = self.lower_ident(tp.ident);
1558
1559         // Don't expose `Self` (recovered "keyword used as ident" parse error).
1560         // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
1561         // Instead, use gensym("Self") to create a distinct name that looks the same.
1562         if name == keywords::SelfType.name() {
1563             name = Symbol::gensym("Self");
1564         }
1565
1566         let itctx = ImplTraitContext::Universal(self.resolver.definitions().local_def_id(tp.id));
1567         let mut bounds = self.lower_bounds(&tp.bounds, itctx);
1568         if !add_bounds.is_empty() {
1569             bounds = bounds.into_iter().chain(
1570                 self.lower_bounds(add_bounds, itctx).into_iter()
1571             ).collect();
1572         }
1573
1574         hir::TyParam {
1575             id: self.lower_node_id(tp.id).node_id,
1576             name,
1577             bounds,
1578             default: tp.default.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
1579             span: tp.span,
1580             pure_wrt_drop: attr::contains_name(&tp.attrs, "may_dangle"),
1581             synthetic: tp.attrs.iter()
1582                                .filter(|attr| attr.check_name("rustc_synthetic"))
1583                                .map(|_| hir::SyntheticTyParamKind::ImplTrait)
1584                                .nth(0),
1585         }
1586     }
1587
1588     fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1589         let name = match self.lower_ident(l.ident) {
1590             x if x == "'_" => hir::LifetimeName::Underscore,
1591             x if x == "'static" => hir::LifetimeName::Static,
1592             name => {
1593                 if  self.is_collecting_in_band_lifetimes &&
1594                     !self.in_scope_lifetimes.contains(&name) &&
1595                     self.lifetimes_to_define.iter()
1596                         .find(|&&(_, lt_name)| lt_name == name)
1597                         .is_none()
1598                 {
1599                     self.lifetimes_to_define.push((l.span, name));
1600                 }
1601
1602                 hir::LifetimeName::Name(name)
1603             }
1604         };
1605
1606         hir::Lifetime {
1607             id: self.lower_node_id(l.id).node_id,
1608             name,
1609             span: l.span,
1610         }
1611     }
1612
1613     fn lower_lifetime_def(&mut self, l: &LifetimeDef) -> hir::LifetimeDef {
1614         let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1615         self.is_collecting_in_band_lifetimes = false;
1616
1617         let def = hir::LifetimeDef {
1618             lifetime: self.lower_lifetime(&l.lifetime),
1619             bounds: self.lower_lifetimes(&l.bounds),
1620             pure_wrt_drop: attr::contains_name(&l.attrs, "may_dangle"),
1621             in_band: false,
1622         };
1623
1624         self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1625
1626         def
1627     }
1628
1629     fn lower_lifetimes(&mut self, lts: &Vec<Lifetime>) -> hir::HirVec<hir::Lifetime> {
1630         lts.iter().map(|l| self.lower_lifetime(l)).collect()
1631     }
1632
1633     fn lower_generic_params(
1634         &mut self,
1635         params: &Vec<GenericParam>,
1636         add_bounds: &NodeMap<Vec<TyParamBound>>,
1637     ) -> hir::HirVec<hir::GenericParam> {
1638         params.iter()
1639             .map(|param| match *param {
1640                 GenericParam::Lifetime(ref lifetime_def) => {
1641                     hir::GenericParam::Lifetime(self.lower_lifetime_def(lifetime_def))
1642                 }
1643                 GenericParam::Type(ref ty_param) => {
1644                     hir::GenericParam::Type(self.lower_ty_param(
1645                         ty_param,
1646                         add_bounds.get(&ty_param.id).map_or(&[][..], |x| &x)
1647                     ))
1648                 }
1649             })
1650             .collect()
1651     }
1652
1653     fn lower_generics(&mut self, g: &Generics) -> hir::Generics {
1654         // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1655         // FIXME: This could probably be done with less rightward drift. Also looks like two control
1656         //        paths where report_error is called are also the only paths that advance to after
1657         //        the match statement, so the error reporting could probably just be moved there.
1658         let mut add_bounds = NodeMap();
1659         for pred in &g.where_clause.predicates {
1660             if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1661                 'next_bound: for bound in &bound_pred.bounds {
1662                     if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
1663                         let report_error = |this: &mut Self| {
1664                             this.diagnostic().span_err(bound_pred.bounded_ty.span,
1665                                                        "`?Trait` bounds are only permitted at the \
1666                                                         point where a type parameter is declared");
1667                         };
1668                         // Check if the where clause type is a plain type parameter.
1669                         match bound_pred.bounded_ty.node {
1670                             TyKind::Path(None, ref path)
1671                                     if path.segments.len() == 1 &&
1672                                        bound_pred.bound_generic_params.is_empty() => {
1673                                 if let Some(Def::TyParam(def_id)) =
1674                                         self.resolver.get_resolution(bound_pred.bounded_ty.id)
1675                                                      .map(|d| d.base_def()) {
1676                                     if let Some(node_id) =
1677                                             self.resolver.definitions().as_local_node_id(def_id) {
1678                                         for param in &g.params {
1679                                             if let GenericParam::Type(ref ty_param) = *param {
1680                                                 if node_id == ty_param.id {
1681                                                     add_bounds.entry(ty_param.id)
1682                                                         .or_insert(Vec::new())
1683                                                         .push(bound.clone());
1684                                                     continue 'next_bound;
1685                                                 }
1686                                             }
1687                                         }
1688                                     }
1689                                 }
1690                                 report_error(self)
1691                             }
1692                             _ => report_error(self)
1693                         }
1694                     }
1695                 }
1696             }
1697         }
1698
1699         hir::Generics {
1700             params: self.lower_generic_params(&g.params, &add_bounds),
1701             where_clause: self.lower_where_clause(&g.where_clause),
1702             span: g.span,
1703         }
1704     }
1705
1706     fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
1707         hir::WhereClause {
1708             id: self.lower_node_id(wc.id).node_id,
1709             predicates: wc.predicates
1710                           .iter()
1711                           .map(|predicate| self.lower_where_predicate(predicate))
1712                           .collect(),
1713         }
1714     }
1715
1716     fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
1717         match *pred {
1718             WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_generic_params,
1719                                                                 ref bounded_ty,
1720                                                                 ref bounds,
1721                                                                 span}) => {
1722                 self.with_in_scope_lifetime_defs(
1723                     &bound_generic_params.iter()
1724                         .filter_map(|p| match *p {
1725                             GenericParam::Lifetime(ref ld) => Some(ld.clone()),
1726                             _ => None,
1727                         })
1728                         .collect::<Vec<_>>(),
1729                     |this| {
1730                         hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1731                             bound_generic_params:
1732                                 this.lower_generic_params(bound_generic_params, &NodeMap()),
1733                             bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
1734                             bounds: bounds.iter().filter_map(|bound| match *bound {
1735                                 // Ignore `?Trait` bounds.
1736                                 // Tthey were copied into type parameters already.
1737                                 TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
1738                                 _ => Some(this.lower_ty_param_bound(
1739                                         bound, ImplTraitContext::Disallowed))
1740                             }).collect(),
1741                             span,
1742                         })
1743                     }
1744                 )
1745             }
1746             WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
1747                                                                   ref bounds,
1748                                                                   span}) => {
1749                 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1750                     span,
1751                     lifetime: self.lower_lifetime(lifetime),
1752                     bounds: bounds.iter().map(|bound| self.lower_lifetime(bound)).collect(),
1753                 })
1754             }
1755             WherePredicate::EqPredicate(WhereEqPredicate{ id,
1756                                                           ref lhs_ty,
1757                                                           ref rhs_ty,
1758                                                           span}) => {
1759                 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1760                     id: self.lower_node_id(id).node_id,
1761                     lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
1762                     rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
1763                     span,
1764                 })
1765             }
1766         }
1767     }
1768
1769     fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
1770         match *vdata {
1771             VariantData::Struct(ref fields, id) => {
1772                 hir::VariantData::Struct(fields.iter()
1773                                                .enumerate()
1774                                                .map(|f| self.lower_struct_field(f))
1775                                                .collect(),
1776                                          self.lower_node_id(id).node_id)
1777             }
1778             VariantData::Tuple(ref fields, id) => {
1779                 hir::VariantData::Tuple(fields.iter()
1780                                               .enumerate()
1781                                               .map(|f| self.lower_struct_field(f))
1782                                               .collect(),
1783                                         self.lower_node_id(id).node_id)
1784             }
1785             VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
1786         }
1787     }
1788
1789     fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
1790         let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
1791             hir::QPath::Resolved(None, path) => path.and_then(|path| path),
1792             qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath)
1793         };
1794         hir::TraitRef {
1795             path,
1796             ref_id: self.lower_node_id(p.ref_id).node_id,
1797         }
1798     }
1799
1800     fn lower_poly_trait_ref(&mut self,
1801                             p: &PolyTraitRef,
1802                             itctx: ImplTraitContext)
1803                             -> hir::PolyTraitRef {
1804         let bound_generic_params = self.lower_generic_params(&p.bound_generic_params, &NodeMap());
1805         let trait_ref = self.with_parent_impl_lifetime_defs(
1806             &bound_generic_params.iter()
1807                 .filter_map(|p| match *p {
1808                     hir::GenericParam::Lifetime(ref ld) => Some(ld.clone()),
1809                     _ => None,
1810                 })
1811                 .collect::<Vec<_>>(),
1812             |this| this.lower_trait_ref(&p.trait_ref, itctx),
1813         );
1814
1815         hir::PolyTraitRef {
1816             bound_generic_params,
1817             trait_ref,
1818             span: p.span,
1819         }
1820     }
1821
1822     fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
1823         hir::StructField {
1824             span: f.span,
1825             id: self.lower_node_id(f.id).node_id,
1826             name: self.lower_ident(match f.ident {
1827                 Some(ident) => ident,
1828                 // FIXME(jseyfried) positional field hygiene
1829                 None => Ident { name: Symbol::intern(&index.to_string()), ctxt: f.span.ctxt() },
1830             }),
1831             vis: self.lower_visibility(&f.vis, None),
1832             ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
1833             attrs: self.lower_attrs(&f.attrs),
1834         }
1835     }
1836
1837     fn lower_field(&mut self, f: &Field) -> hir::Field {
1838         hir::Field {
1839             name: respan(f.ident.span, self.lower_ident(f.ident.node)),
1840             expr: P(self.lower_expr(&f.expr)),
1841             span: f.span,
1842             is_shorthand: f.is_shorthand,
1843         }
1844     }
1845
1846     fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
1847         hir::MutTy {
1848             ty: self.lower_ty(&mt.ty, itctx),
1849             mutbl: self.lower_mutability(mt.mutbl),
1850         }
1851     }
1852
1853     fn lower_bounds(&mut self, bounds: &[TyParamBound], itctx: ImplTraitContext)
1854                     -> hir::TyParamBounds {
1855         bounds.iter().map(|bound| self.lower_ty_param_bound(bound, itctx)).collect()
1856     }
1857
1858     fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
1859         let mut expr = None;
1860
1861         let mut stmts = vec![];
1862
1863         for (index, stmt) in b.stmts.iter().enumerate() {
1864             if index == b.stmts.len() - 1 {
1865                 if let StmtKind::Expr(ref e) = stmt.node {
1866                     expr = Some(P(self.lower_expr(e)));
1867                 } else {
1868                     stmts.extend(self.lower_stmt(stmt));
1869                 }
1870             } else {
1871                 stmts.extend(self.lower_stmt(stmt));
1872             }
1873         }
1874
1875         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
1876
1877         P(hir::Block {
1878             id: node_id,
1879             hir_id,
1880             stmts: stmts.into(),
1881             expr,
1882             rules: self.lower_block_check_mode(&b.rules),
1883             span: b.span,
1884             targeted_by_break,
1885             recovered: b.recovered,
1886         })
1887     }
1888
1889     fn lower_item_kind(&mut self,
1890                        id: NodeId,
1891                        name: &mut Name,
1892                        attrs: &hir::HirVec<Attribute>,
1893                        vis: &mut hir::Visibility,
1894                        i: &ItemKind)
1895                        -> hir::Item_ {
1896         match *i {
1897             ItemKind::ExternCrate(string) => hir::ItemExternCrate(string),
1898             ItemKind::Use(ref use_tree) => {
1899                 // Start with an empty prefix
1900                 let prefix = Path {
1901                     segments: vec![],
1902                     span: use_tree.span,
1903                 };
1904
1905                 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
1906             }
1907             ItemKind::Static(ref t, m, ref e) => {
1908                 let value = self.lower_body(None, |this| this.lower_expr(e));
1909                 hir::ItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed),
1910                                 self.lower_mutability(m),
1911                                 value)
1912             }
1913             ItemKind::Const(ref t, ref e) => {
1914                 let value = self.lower_body(None, |this| this.lower_expr(e));
1915                 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
1916             }
1917             ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
1918                 let fn_def_id = self.resolver.definitions().opt_local_def_id(id);
1919                 self.with_new_scopes(|this| {
1920                     let body_id = this.lower_body(Some(decl), |this| {
1921                         let body = this.lower_block(body, false);
1922                         this.expr_block(body, ThinVec::new())
1923                     });
1924                     let (generics, fn_decl) =
1925                         this.add_in_band_defs(generics, fn_def_id, |this|
1926                             this.lower_fn_decl(decl, fn_def_id, true));
1927
1928                     hir::ItemFn(fn_decl,
1929                                 this.lower_unsafety(unsafety),
1930                                 this.lower_constness(constness),
1931                                 abi,
1932                                 generics,
1933                                 body_id)
1934                 })
1935             }
1936             ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
1937             ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
1938             ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
1939             ItemKind::Ty(ref t, ref generics) => {
1940                 hir::ItemTy(self.lower_ty(t, ImplTraitContext::Disallowed),
1941                             self.lower_generics(generics))
1942             }
1943             ItemKind::Enum(ref enum_definition, ref generics) => {
1944                 hir::ItemEnum(hir::EnumDef {
1945                                   variants: enum_definition.variants
1946                                                            .iter()
1947                                                            .map(|x| self.lower_variant(x))
1948                                                            .collect(),
1949                               },
1950                               self.lower_generics(generics))
1951             }
1952             ItemKind::Struct(ref struct_def, ref generics) => {
1953                 let struct_def = self.lower_variant_data(struct_def);
1954                 hir::ItemStruct(struct_def, self.lower_generics(generics))
1955             }
1956             ItemKind::Union(ref vdata, ref generics) => {
1957                 let vdata = self.lower_variant_data(vdata);
1958                 hir::ItemUnion(vdata, self.lower_generics(generics))
1959             }
1960             ItemKind::Impl(unsafety,
1961                            polarity,
1962                            defaultness,
1963                            ref ast_generics,
1964                            ref ifce,
1965                            ref ty,
1966                            ref impl_items) => {
1967                 let def_id = self.resolver.definitions().opt_local_def_id(id);
1968                 let (generics, (ifce, lowered_ty)) =
1969                     self.add_in_band_defs(ast_generics, def_id, |this| {
1970                         let ifce = ifce.as_ref().map(|trait_ref| {
1971                             this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
1972                         });
1973
1974                         if let Some(ref trait_ref) = ifce {
1975                             if let Def::Trait(def_id) = trait_ref.path.def {
1976                                 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
1977                             }
1978                         }
1979
1980                         let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
1981
1982                         (ifce, lowered_ty)
1983                     });
1984
1985                 let new_impl_items = self.with_in_scope_lifetime_defs(
1986                     &ast_generics.params
1987                         .iter()
1988                         .filter_map(|p| match *p {
1989                             GenericParam::Lifetime(ref ld) => Some(ld.clone()),
1990                             _ => None,
1991                         })
1992                         .collect::<Vec<_>>(),
1993                     |this| {
1994                         impl_items.iter()
1995                             .map(|item| this.lower_impl_item_ref(item))
1996                             .collect()
1997                     }
1998                 );
1999
2000
2001                 hir::ItemImpl(self.lower_unsafety(unsafety),
2002                               self.lower_impl_polarity(polarity),
2003                               self.lower_defaultness(defaultness, true /* [1] */),
2004                               generics,
2005                               ifce,
2006                               lowered_ty,
2007                               new_impl_items)
2008             }
2009             ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2010                 let bounds = self.lower_bounds(bounds, ImplTraitContext::Disallowed);
2011                 let items = items.iter().map(|item| self.lower_trait_item_ref(item)).collect();
2012                 hir::ItemTrait(self.lower_is_auto(is_auto),
2013                                self.lower_unsafety(unsafety),
2014                                self.lower_generics(generics),
2015                                bounds,
2016                                items)
2017             }
2018             ItemKind::TraitAlias(ref generics, ref bounds) => {
2019                 hir::ItemTraitAlias(self.lower_generics(generics),
2020                                     self.lower_bounds(bounds, ImplTraitContext::Disallowed))
2021             }
2022             ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2023         }
2024
2025         // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2026         //     not cause an assertion failure inside the `lower_defaultness` function
2027     }
2028
2029     fn lower_use_tree(&mut self,
2030                        tree: &UseTree,
2031                        prefix: &Path,
2032                        id: NodeId,
2033                        vis: &mut hir::Visibility,
2034                        name: &mut Name,
2035                        attrs: &hir::HirVec<Attribute>)
2036                        -> hir::Item_ {
2037         let path = &tree.prefix;
2038
2039         match tree.kind {
2040             UseTreeKind::Simple(ident) => {
2041                 *name = ident.name;
2042
2043                 // First apply the prefix to the path
2044                 let mut path = Path {
2045                     segments: prefix.segments
2046                         .iter()
2047                         .chain(path.segments.iter())
2048                         .cloned()
2049                         .collect(),
2050                     span: path.span
2051                 };
2052
2053                 // Correctly resolve `self` imports
2054                 if path.segments.len() > 1 &&
2055                    path.segments.last().unwrap().identifier.name == keywords::SelfValue.name() {
2056                     let _ = path.segments.pop();
2057                     if ident.name == keywords::SelfValue.name() {
2058                         *name = path.segments.last().unwrap().identifier.name;
2059                     }
2060                 }
2061
2062                 let path = P(self.lower_path(id, &path, ParamMode::Explicit, true));
2063                 hir::ItemUse(path, hir::UseKind::Single)
2064             }
2065             UseTreeKind::Glob => {
2066                 let path = P(self.lower_path(id, &Path {
2067                     segments: prefix.segments
2068                         .iter()
2069                         .chain(path.segments.iter())
2070                         .cloned()
2071                         .collect(),
2072                     span: path.span,
2073                 }, ParamMode::Explicit, true));
2074                 hir::ItemUse(path, hir::UseKind::Glob)
2075             }
2076             UseTreeKind::Nested(ref trees) => {
2077                 let prefix = Path {
2078                     segments: prefix.segments
2079                         .iter()
2080                         .chain(path.segments.iter())
2081                         .cloned()
2082                         .collect(),
2083                     span: prefix.span.to(path.span),
2084                 };
2085
2086                 // Add all the nested PathListItems in the HIR
2087                 for &(ref use_tree, id) in trees {
2088                     self.allocate_hir_id_counter(id, &use_tree);
2089                     let LoweredNodeId {
2090                         node_id: new_id,
2091                         hir_id: new_hir_id,
2092                     } = self.lower_node_id(id);
2093
2094                     let mut vis = vis.clone();
2095                     let mut name = name.clone();
2096                     let item = self.lower_use_tree(
2097                         use_tree, &prefix, new_id, &mut vis, &mut name, &attrs,
2098                     );
2099
2100                     self.with_hir_id_owner(new_id, |this| {
2101                         let vis = match vis {
2102                             hir::Visibility::Public => hir::Visibility::Public,
2103                             hir::Visibility::Crate => hir::Visibility::Crate,
2104                             hir::Visibility::Inherited => hir::Visibility::Inherited,
2105                             hir::Visibility::Restricted { ref path, id: _  } => {
2106                                 hir::Visibility::Restricted {
2107                                     path: path.clone(),
2108                                     // We are allocating a new NodeId here
2109                                     id: this.next_id().node_id,
2110                                 }
2111                             }
2112                         };
2113
2114                         this.items.insert(new_id, hir::Item {
2115                             id: new_id,
2116                             hir_id: new_hir_id,
2117                             name: name,
2118                             attrs: attrs.clone(),
2119                             node: item,
2120                             vis,
2121                             span: use_tree.span,
2122                         });
2123                     });
2124                 }
2125
2126                 // Privatize the degenerate import base, used only to check
2127                 // the stability of `use a::{};`, to avoid it showing up as
2128                 // a re-export by accident when `pub`, e.g. in documentation.
2129                 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit, true));
2130                 *vis = hir::Inherited;
2131                 hir::ItemUse(path, hir::UseKind::ListStem)
2132             }
2133         }
2134     }
2135
2136     fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2137         self.with_parent_def(i.id, |this| {
2138             let LoweredNodeId { node_id, hir_id } = this.lower_node_id(i.id);
2139             let fn_def_id = this.resolver.definitions().opt_local_def_id(node_id);
2140
2141             let (generics, node) = match i.node {
2142                 TraitItemKind::Const(ref ty, ref default) => {
2143                     (
2144                         this.lower_generics(&i.generics),
2145                         hir::TraitItemKind::Const(
2146                             this.lower_ty(ty, ImplTraitContext::Disallowed),
2147                             default.as_ref().map(|x| {
2148                                 this.lower_body(None, |this| this.lower_expr(x))
2149                             }))
2150                     )
2151                 }
2152                 TraitItemKind::Method(ref sig, None) => {
2153                     let names = this.lower_fn_args_to_names(&sig.decl);
2154                     this.add_in_band_defs(&i.generics, fn_def_id, |this|
2155                         hir::TraitItemKind::Method(
2156                             this.lower_method_sig(sig, fn_def_id, false),
2157                             hir::TraitMethod::Required(names)))
2158                 }
2159                 TraitItemKind::Method(ref sig, Some(ref body)) => {
2160                     let body_id = this.lower_body(Some(&sig.decl), |this| {
2161                         let body = this.lower_block(body, false);
2162                         this.expr_block(body, ThinVec::new())
2163                     });
2164
2165                     this.add_in_band_defs(&i.generics, fn_def_id, |this|
2166                         hir::TraitItemKind::Method(
2167                             this.lower_method_sig(sig, fn_def_id, false),
2168                            hir::TraitMethod::Provided(body_id)))
2169                 }
2170                 TraitItemKind::Type(ref bounds, ref default) => {
2171                     (
2172                         this.lower_generics(&i.generics),
2173                         hir::TraitItemKind::Type(
2174                             this.lower_bounds(bounds, ImplTraitContext::Disallowed),
2175                             default.as_ref().map(|x| {
2176                                 this.lower_ty(x, ImplTraitContext::Disallowed)
2177                             }))
2178                     )
2179                 }
2180                 TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2181             };
2182
2183             hir::TraitItem {
2184                 id: node_id,
2185                 hir_id,
2186                 name: this.lower_ident(i.ident),
2187                 attrs: this.lower_attrs(&i.attrs),
2188                 generics,
2189                 node,
2190                 span: i.span,
2191             }
2192         })
2193     }
2194
2195     fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2196         let (kind, has_default) = match i.node {
2197             TraitItemKind::Const(_, ref default) => {
2198                 (hir::AssociatedItemKind::Const, default.is_some())
2199             }
2200             TraitItemKind::Type(_, ref default) => {
2201                 (hir::AssociatedItemKind::Type, default.is_some())
2202             }
2203             TraitItemKind::Method(ref sig, ref default) => {
2204                 (hir::AssociatedItemKind::Method {
2205                     has_self: sig.decl.has_self(),
2206                  }, default.is_some())
2207             }
2208             TraitItemKind::Macro(..) => unimplemented!(),
2209         };
2210         hir::TraitItemRef {
2211             id: hir::TraitItemId { node_id: i.id },
2212             name: self.lower_ident(i.ident),
2213             span: i.span,
2214             defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2215             kind,
2216         }
2217     }
2218
2219     fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2220         self.with_parent_def(i.id, |this| {
2221             let LoweredNodeId { node_id, hir_id } = this.lower_node_id(i.id);
2222             let fn_def_id = this.resolver.definitions().opt_local_def_id(node_id);
2223
2224             let (generics, node) = match i.node {
2225                 ImplItemKind::Const(ref ty, ref expr) => {
2226                     let body_id = this.lower_body(None, |this| this.lower_expr(expr));
2227                     (
2228                         this.lower_generics(&i.generics),
2229                         hir::ImplItemKind::Const(
2230                             this.lower_ty(ty, ImplTraitContext::Disallowed),
2231                             body_id
2232                         )
2233                     )
2234                 }
2235                 ImplItemKind::Method(ref sig, ref body) => {
2236                     let body_id = this.lower_body(Some(&sig.decl), |this| {
2237                         let body = this.lower_block(body, false);
2238                         this.expr_block(body, ThinVec::new())
2239                     });
2240                     let impl_trait_return_allow = !this.is_in_trait_impl;
2241
2242                     this.add_in_band_defs(&i.generics, fn_def_id, |this|
2243                         hir::ImplItemKind::Method(
2244                             this.lower_method_sig(sig, fn_def_id, impl_trait_return_allow),
2245                             body_id))
2246                 }
2247                 ImplItemKind::Type(ref ty) => (
2248                     this.lower_generics(&i.generics),
2249                     hir::ImplItemKind::Type(
2250                         this.lower_ty(ty, ImplTraitContext::Disallowed)),
2251                 ),
2252                 ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2253             };
2254
2255             hir::ImplItem {
2256                 id: node_id,
2257                 hir_id,
2258                 name: this.lower_ident(i.ident),
2259                 attrs: this.lower_attrs(&i.attrs),
2260                 generics,
2261                 vis: this.lower_visibility(&i.vis, None),
2262                 defaultness: this.lower_defaultness(i.defaultness, true /* [1] */),
2263                 node,
2264                 span: i.span,
2265             }
2266         })
2267
2268         // [1] since `default impl` is not yet implemented, this is always true in impls
2269     }
2270
2271     fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
2272         hir::ImplItemRef {
2273             id: hir::ImplItemId { node_id: i.id },
2274             name: self.lower_ident(i.ident),
2275             span: i.span,
2276             vis: self.lower_visibility(&i.vis, Some(i.id)),
2277             defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2278             kind: match i.node {
2279                 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
2280                 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
2281                 ImplItemKind::Method(ref sig, _) => {
2282                     hir::AssociatedItemKind::Method {
2283                         has_self: sig.decl.has_self(),
2284                     }
2285                 },
2286                 ImplItemKind::Macro(..) => unimplemented!(),
2287             },
2288         }
2289
2290         // [1] since `default impl` is not yet implemented, this is always true in impls
2291     }
2292
2293     fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
2294         hir::Mod {
2295             inner: m.inner,
2296             item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
2297         }
2298     }
2299
2300     fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
2301         match i.node {
2302             ItemKind::Use(ref use_tree) => {
2303                 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
2304                 self.lower_item_id_use_tree(use_tree, &mut vec);
2305                 return vec;
2306             }
2307             ItemKind::MacroDef(..) => return SmallVector::new(),
2308             _ => {}
2309         }
2310         SmallVector::one(hir::ItemId { id: i.id })
2311     }
2312
2313     fn lower_item_id_use_tree(&self, tree: &UseTree, vec: &mut SmallVector<hir::ItemId>) {
2314         match tree.kind {
2315             UseTreeKind::Nested(ref nested_vec) => {
2316                 for &(ref nested, id) in nested_vec {
2317                     vec.push(hir::ItemId { id, });
2318                     self.lower_item_id_use_tree(nested, vec);
2319                 }
2320             }
2321             UseTreeKind::Glob => {}
2322             UseTreeKind::Simple(..) => {}
2323         }
2324     }
2325
2326     pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
2327         let mut name = i.ident.name;
2328         let mut vis = self.lower_visibility(&i.vis, None);
2329         let attrs = self.lower_attrs(&i.attrs);
2330         if let ItemKind::MacroDef(ref def) = i.node {
2331             if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
2332                 let body = self.lower_token_stream(def.stream());
2333                 self.exported_macros.push(hir::MacroDef {
2334                     name,
2335                     vis,
2336                     attrs,
2337                     id: i.id,
2338                     span: i.span,
2339                     body,
2340                     legacy: def.legacy,
2341                 });
2342             }
2343             return None;
2344         }
2345
2346         let node = self.with_parent_def(i.id, |this| {
2347             this.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node)
2348         });
2349
2350         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2351
2352         Some(hir::Item {
2353             id: node_id,
2354             hir_id,
2355             name,
2356             attrs,
2357             node,
2358             vis,
2359             span: i.span,
2360         })
2361     }
2362
2363     fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
2364         self.with_parent_def(i.id, |this| {
2365             let node_id = this.lower_node_id(i.id).node_id;
2366             let def_id = this.resolver.definitions().local_def_id(node_id);
2367             hir::ForeignItem {
2368                 id: node_id,
2369                 name: i.ident.name,
2370                 attrs: this.lower_attrs(&i.attrs),
2371                 node: match i.node {
2372                     ForeignItemKind::Fn(ref fdec, ref generics) => {
2373                         // Disallow impl Trait in foreign items
2374                         let (generics, (fn_dec, fn_args)) =
2375                             this.add_in_band_defs(
2376                                 generics,
2377                                 Some(def_id),
2378                                 |this| (
2379                                     this.lower_fn_decl(fdec, None, false),
2380                                     this.lower_fn_args_to_names(fdec)
2381                                 )
2382                             );
2383
2384                         hir::ForeignItemFn(fn_dec, fn_args, generics)
2385                     }
2386                     ForeignItemKind::Static(ref t, m) => {
2387                         hir::ForeignItemStatic(this.lower_ty(t, ImplTraitContext::Disallowed), m)
2388                     }
2389                     ForeignItemKind::Ty => {
2390                         hir::ForeignItemType
2391                     }
2392                 },
2393                 vis: this.lower_visibility(&i.vis, None),
2394                 span: i.span,
2395             }
2396         })
2397     }
2398
2399     fn lower_method_sig(&mut self,
2400                         sig: &MethodSig,
2401                         fn_def_id: Option<DefId>,
2402                         impl_trait_return_allow: bool)
2403                         -> hir::MethodSig {
2404         hir::MethodSig {
2405             abi: sig.abi,
2406             unsafety: self.lower_unsafety(sig.unsafety),
2407             constness: self.lower_constness(sig.constness),
2408             decl: self.lower_fn_decl(&sig.decl, fn_def_id, impl_trait_return_allow),
2409         }
2410     }
2411
2412     fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
2413         match a {
2414             IsAuto::Yes => hir::IsAuto::Yes,
2415             IsAuto::No => hir::IsAuto::No,
2416         }
2417     }
2418
2419     fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
2420         match u {
2421             Unsafety::Unsafe => hir::Unsafety::Unsafe,
2422             Unsafety::Normal => hir::Unsafety::Normal,
2423         }
2424     }
2425
2426     fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
2427         match c.node {
2428             Constness::Const => hir::Constness::Const,
2429             Constness::NotConst => hir::Constness::NotConst,
2430         }
2431     }
2432
2433     fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
2434         match u {
2435             UnOp::Deref => hir::UnDeref,
2436             UnOp::Not => hir::UnNot,
2437             UnOp::Neg => hir::UnNeg,
2438         }
2439     }
2440
2441     fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
2442         Spanned {
2443             node: match b.node {
2444                 BinOpKind::Add => hir::BiAdd,
2445                 BinOpKind::Sub => hir::BiSub,
2446                 BinOpKind::Mul => hir::BiMul,
2447                 BinOpKind::Div => hir::BiDiv,
2448                 BinOpKind::Rem => hir::BiRem,
2449                 BinOpKind::And => hir::BiAnd,
2450                 BinOpKind::Or => hir::BiOr,
2451                 BinOpKind::BitXor => hir::BiBitXor,
2452                 BinOpKind::BitAnd => hir::BiBitAnd,
2453                 BinOpKind::BitOr => hir::BiBitOr,
2454                 BinOpKind::Shl => hir::BiShl,
2455                 BinOpKind::Shr => hir::BiShr,
2456                 BinOpKind::Eq => hir::BiEq,
2457                 BinOpKind::Lt => hir::BiLt,
2458                 BinOpKind::Le => hir::BiLe,
2459                 BinOpKind::Ne => hir::BiNe,
2460                 BinOpKind::Ge => hir::BiGe,
2461                 BinOpKind::Gt => hir::BiGt,
2462             },
2463             span: b.span,
2464         }
2465     }
2466
2467     fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2468         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
2469
2470         P(hir::Pat {
2471             id: node_id,
2472             hir_id,
2473             node: match p.node {
2474                 PatKind::Wild => hir::PatKind::Wild,
2475                 PatKind::Ident(ref binding_mode, pth1, ref sub) => {
2476                     match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
2477                         // `None` can occur in body-less function signatures
2478                         def @ None | def @ Some(Def::Local(_)) => {
2479                             let canonical_id = match def {
2480                                 Some(Def::Local(id)) => id,
2481                                 _ => p.id
2482                             };
2483                             hir::PatKind::Binding(self.lower_binding_mode(binding_mode),
2484                                                   canonical_id,
2485                                                   respan(pth1.span, pth1.node.name),
2486                                                   sub.as_ref().map(|x| self.lower_pat(x)))
2487                         }
2488                         Some(def) => {
2489                             hir::PatKind::Path(hir::QPath::Resolved(None, P(hir::Path {
2490                                 span: pth1.span,
2491                                 def,
2492                                 segments: hir_vec![
2493                                     hir::PathSegment::from_name(pth1.node.name)
2494                                 ],
2495                             })))
2496                         }
2497                     }
2498                 }
2499                 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
2500                 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
2501                     let qpath = self.lower_qpath(p.id, &None, path, ParamMode::Optional,
2502                                                  ImplTraitContext::Disallowed);
2503                     hir::PatKind::TupleStruct(qpath,
2504                                               pats.iter().map(|x| self.lower_pat(x)).collect(),
2505                                               ddpos)
2506                 }
2507                 PatKind::Path(ref qself, ref path) => {
2508                     hir::PatKind::Path(self.lower_qpath(p.id, qself, path, ParamMode::Optional,
2509                                                         ImplTraitContext::Disallowed))
2510                 }
2511                 PatKind::Struct(ref path, ref fields, etc) => {
2512                     let qpath = self.lower_qpath(p.id, &None, path, ParamMode::Optional,
2513                                                  ImplTraitContext::Disallowed);
2514
2515                     let fs = fields.iter()
2516                                    .map(|f| {
2517                                        Spanned {
2518                                            span: f.span,
2519                                            node: hir::FieldPat {
2520                                                name: self.lower_ident(f.node.ident),
2521                                                pat: self.lower_pat(&f.node.pat),
2522                                                is_shorthand: f.node.is_shorthand,
2523                                            },
2524                                        }
2525                                    })
2526                                    .collect();
2527                     hir::PatKind::Struct(qpath, fs, etc)
2528                 }
2529                 PatKind::Tuple(ref elts, ddpos) => {
2530                     hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
2531                 }
2532                 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
2533                 PatKind::Ref(ref inner, mutbl) => {
2534                     hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
2535                 }
2536                 PatKind::Range(ref e1, ref e2, ref end) => {
2537                     hir::PatKind::Range(P(self.lower_expr(e1)),
2538                                         P(self.lower_expr(e2)),
2539                                         self.lower_range_end(end))
2540                 }
2541                 PatKind::Slice(ref before, ref slice, ref after) => {
2542                     hir::PatKind::Slice(before.iter().map(|x| self.lower_pat(x)).collect(),
2543                                 slice.as_ref().map(|x| self.lower_pat(x)),
2544                                 after.iter().map(|x| self.lower_pat(x)).collect())
2545                 }
2546                 PatKind::Mac(_) => panic!("Shouldn't exist here"),
2547             },
2548             span: p.span,
2549         })
2550     }
2551
2552     fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
2553         match *e {
2554             RangeEnd::Included(_) => hir::RangeEnd::Included,
2555             RangeEnd::Excluded => hir::RangeEnd::Excluded,
2556         }
2557     }
2558
2559     fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
2560         let kind = match e.node {
2561             // Issue #22181:
2562             // Eventually a desugaring for `box EXPR`
2563             // (similar to the desugaring above for `in PLACE BLOCK`)
2564             // should go here, desugaring
2565             //
2566             // to:
2567             //
2568             // let mut place = BoxPlace::make_place();
2569             // let raw_place = Place::pointer(&mut place);
2570             // let value = $value;
2571             // unsafe {
2572             //     ::std::ptr::write(raw_place, value);
2573             //     Boxed::finalize(place)
2574             // }
2575             //
2576             // But for now there are type-inference issues doing that.
2577             ExprKind::Box(ref inner) => {
2578                 hir::ExprBox(P(self.lower_expr(inner)))
2579             }
2580
2581             // Desugar ExprBox: `in (PLACE) EXPR`
2582             ExprKind::InPlace(ref placer, ref value_expr) => {
2583                 // to:
2584                 //
2585                 // let p = PLACE;
2586                 // let mut place = Placer::make_place(p);
2587                 // let raw_place = Place::pointer(&mut place);
2588                 // push_unsafe!({
2589                 //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
2590                 //     InPlace::finalize(place)
2591                 // })
2592                 let placer_expr = P(self.lower_expr(placer));
2593                 let value_expr = P(self.lower_expr(value_expr));
2594
2595                 let placer_ident = self.str_to_ident("placer");
2596                 let place_ident = self.str_to_ident("place");
2597                 let p_ptr_ident = self.str_to_ident("p_ptr");
2598
2599                 let make_place = ["ops", "Placer", "make_place"];
2600                 let place_pointer = ["ops", "Place", "pointer"];
2601                 let move_val_init = ["intrinsics", "move_val_init"];
2602                 let inplace_finalize = ["ops", "InPlace", "finalize"];
2603
2604                 let unstable_span =
2605                     self.allow_internal_unstable(CompilerDesugaringKind::BackArrow, e.span);
2606                 let make_call = |this: &mut LoweringContext, p, args| {
2607                     let path = P(this.expr_std_path(unstable_span, p, ThinVec::new()));
2608                     P(this.expr_call(e.span, path, args))
2609                 };
2610
2611                 let mk_stmt_let = |this: &mut LoweringContext, bind, expr| {
2612                     this.stmt_let(e.span, false, bind, expr)
2613                 };
2614
2615                 let mk_stmt_let_mut = |this: &mut LoweringContext, bind, expr| {
2616                     this.stmt_let(e.span, true, bind, expr)
2617                 };
2618
2619                 // let placer = <placer_expr> ;
2620                 let (s1, placer_binding) = {
2621                     mk_stmt_let(self, placer_ident, placer_expr)
2622                 };
2623
2624                 // let mut place = Placer::make_place(placer);
2625                 let (s2, place_binding) = {
2626                     let placer = self.expr_ident(e.span, placer_ident, placer_binding);
2627                     let call = make_call(self, &make_place, hir_vec![placer]);
2628                     mk_stmt_let_mut(self, place_ident, call)
2629                 };
2630
2631                 // let p_ptr = Place::pointer(&mut place);
2632                 let (s3, p_ptr_binding) = {
2633                     let agent = P(self.expr_ident(e.span, place_ident, place_binding));
2634                     let args = hir_vec![self.expr_mut_addr_of(e.span, agent)];
2635                     let call = make_call(self, &place_pointer, args);
2636                     mk_stmt_let(self, p_ptr_ident, call)
2637                 };
2638
2639                 // pop_unsafe!(EXPR));
2640                 let pop_unsafe_expr = {
2641                     self.signal_block_expr(hir_vec![],
2642                                            value_expr,
2643                                            e.span,
2644                                            hir::PopUnsafeBlock(hir::CompilerGenerated),
2645                                            ThinVec::new())
2646                 };
2647
2648                 // push_unsafe!({
2649                 //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
2650                 //     InPlace::finalize(place)
2651                 // })
2652                 let expr = {
2653                     let ptr = self.expr_ident(e.span, p_ptr_ident, p_ptr_binding);
2654                     let call_move_val_init =
2655                         hir::StmtSemi(
2656                             make_call(self, &move_val_init, hir_vec![ptr, pop_unsafe_expr]),
2657                             self.next_id().node_id);
2658                     let call_move_val_init = respan(e.span, call_move_val_init);
2659
2660                     let place = self.expr_ident(e.span, place_ident, place_binding);
2661                     let call = make_call(self, &inplace_finalize, hir_vec![place]);
2662                     P(self.signal_block_expr(hir_vec![call_move_val_init],
2663                                              call,
2664                                              e.span,
2665                                              hir::PushUnsafeBlock(hir::CompilerGenerated),
2666                                              ThinVec::new()))
2667                 };
2668
2669                 let block = self.block_all(e.span, hir_vec![s1, s2, s3], Some(expr));
2670                 hir::ExprBlock(P(block))
2671             }
2672
2673             ExprKind::Array(ref exprs) => {
2674                 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
2675             }
2676             ExprKind::Repeat(ref expr, ref count) => {
2677                 let expr = P(self.lower_expr(expr));
2678                 let count = self.lower_body(None, |this| this.lower_expr(count));
2679                 hir::ExprRepeat(expr, count)
2680             }
2681             ExprKind::Tup(ref elts) => {
2682                 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
2683             }
2684             ExprKind::Call(ref f, ref args) => {
2685                 let f = P(self.lower_expr(f));
2686                 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
2687             }
2688             ExprKind::MethodCall(ref seg, ref args) => {
2689                 let hir_seg = self.lower_path_segment(e.span, seg, ParamMode::Optional, 0,
2690                                                       ParenthesizedGenericArgs::Err,
2691                                                       ImplTraitContext::Disallowed);
2692                 let args = args.iter().map(|x| self.lower_expr(x)).collect();
2693                 hir::ExprMethodCall(hir_seg, seg.span, args)
2694             }
2695             ExprKind::Binary(binop, ref lhs, ref rhs) => {
2696                 let binop = self.lower_binop(binop);
2697                 let lhs = P(self.lower_expr(lhs));
2698                 let rhs = P(self.lower_expr(rhs));
2699                 hir::ExprBinary(binop, lhs, rhs)
2700             }
2701             ExprKind::Unary(op, ref ohs) => {
2702                 let op = self.lower_unop(op);
2703                 let ohs = P(self.lower_expr(ohs));
2704                 hir::ExprUnary(op, ohs)
2705             }
2706             ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
2707             ExprKind::Cast(ref expr, ref ty) => {
2708                 let expr = P(self.lower_expr(expr));
2709                 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
2710             }
2711             ExprKind::Type(ref expr, ref ty) => {
2712                 let expr = P(self.lower_expr(expr));
2713                 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
2714             }
2715             ExprKind::AddrOf(m, ref ohs) => {
2716                 let m = self.lower_mutability(m);
2717                 let ohs = P(self.lower_expr(ohs));
2718                 hir::ExprAddrOf(m, ohs)
2719             }
2720             // More complicated than you might expect because the else branch
2721             // might be `if let`.
2722             ExprKind::If(ref cond, ref blk, ref else_opt) => {
2723                 let else_opt = else_opt.as_ref().map(|els| {
2724                     match els.node {
2725                         ExprKind::IfLet(..) => {
2726                             // wrap the if-let expr in a block
2727                             let span = els.span;
2728                             let els = P(self.lower_expr(els));
2729                             let LoweredNodeId {
2730                                 node_id,
2731                                 hir_id,
2732                             } = self.next_id();
2733                             let blk = P(hir::Block {
2734                                 stmts: hir_vec![],
2735                                 expr: Some(els),
2736                                 id: node_id,
2737                                 hir_id,
2738                                 rules: hir::DefaultBlock,
2739                                 span,
2740                                 targeted_by_break: false,
2741                                 recovered: blk.recovered,
2742                             });
2743                             P(self.expr_block(blk, ThinVec::new()))
2744                         }
2745                         _ => P(self.lower_expr(els)),
2746                     }
2747                 });
2748
2749                 let then_blk = self.lower_block(blk, false);
2750                 let then_expr = self.expr_block(then_blk, ThinVec::new());
2751
2752                 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
2753             }
2754             ExprKind::While(ref cond, ref body, opt_label) => {
2755                 self.with_loop_scope(e.id, |this|
2756                     hir::ExprWhile(
2757                         this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
2758                         this.lower_block(body, false),
2759                         this.lower_label(opt_label)))
2760             }
2761             ExprKind::Loop(ref body, opt_label) => {
2762                 self.with_loop_scope(e.id, |this|
2763                     hir::ExprLoop(this.lower_block(body, false),
2764                                   this.lower_label(opt_label),
2765                                   hir::LoopSource::Loop))
2766             }
2767             ExprKind::Catch(ref body) => {
2768                 self.with_catch_scope(body.id, |this|
2769                     hir::ExprBlock(this.lower_block(body, true)))
2770             }
2771             ExprKind::Match(ref expr, ref arms) => {
2772                 hir::ExprMatch(P(self.lower_expr(expr)),
2773                                arms.iter().map(|x| self.lower_arm(x)).collect(),
2774                                hir::MatchSource::Normal)
2775             }
2776             ExprKind::Closure(capture_clause, movability, ref decl, ref body, fn_decl_span) => {
2777                 self.with_new_scopes(|this| {
2778                     this.with_parent_def(e.id, |this| {
2779                         let mut is_generator = false;
2780                         let body_id = this.lower_body(Some(decl), |this| {
2781                             let e = this.lower_expr(body);
2782                             is_generator = this.is_generator;
2783                             e
2784                         });
2785                         let generator_option = if is_generator {
2786                             if !decl.inputs.is_empty() {
2787                                 span_err!(this.sess, fn_decl_span, E0628,
2788                                         "generators cannot have explicit arguments");
2789                                 this.sess.abort_if_errors();
2790                             }
2791                             Some(match movability {
2792                                 Movability::Movable => hir::GeneratorMovability::Movable,
2793                                 Movability::Static => hir::GeneratorMovability::Static,
2794                             })
2795                         } else {
2796                             if movability == Movability::Static {
2797                                 span_err!(this.sess, fn_decl_span, E0906,
2798                                         "closures cannot be static");
2799                             }
2800                             None
2801                         };
2802                         hir::ExprClosure(this.lower_capture_clause(capture_clause),
2803                                          this.lower_fn_decl(decl, None, false),
2804                                          body_id,
2805                                          fn_decl_span,
2806                                          generator_option)
2807                     })
2808                 })
2809             }
2810             ExprKind::Block(ref blk) => hir::ExprBlock(self.lower_block(blk, false)),
2811             ExprKind::Assign(ref el, ref er) => {
2812                 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
2813             }
2814             ExprKind::AssignOp(op, ref el, ref er) => {
2815                 hir::ExprAssignOp(self.lower_binop(op),
2816                                   P(self.lower_expr(el)),
2817                                   P(self.lower_expr(er)))
2818             }
2819             ExprKind::Field(ref el, ident) => {
2820                 hir::ExprField(P(self.lower_expr(el)),
2821                                respan(ident.span, self.lower_ident(ident.node)))
2822             }
2823             ExprKind::TupField(ref el, ident) => {
2824                 hir::ExprTupField(P(self.lower_expr(el)), ident)
2825             }
2826             ExprKind::Index(ref el, ref er) => {
2827                 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
2828             }
2829             ExprKind::Range(ref e1, ref e2, lims) => {
2830                 use syntax::ast::RangeLimits::*;
2831
2832                 let path = match (e1, e2, lims) {
2833                     (&None, &None, HalfOpen) => "RangeFull",
2834                     (&Some(..), &None, HalfOpen) => "RangeFrom",
2835                     (&None, &Some(..), HalfOpen) => "RangeTo",
2836                     (&Some(..), &Some(..), HalfOpen) => "Range",
2837                     (&None, &Some(..), Closed) => "RangeToInclusive",
2838                     (&Some(..), &Some(..), Closed) => "RangeInclusive",
2839                     (_, &None, Closed) =>
2840                         self.diagnostic().span_fatal(
2841                             e.span, "inclusive range with no end").raise(),
2842                 };
2843
2844                 let fields =
2845                     e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e)))
2846                     .map(|(s, e)| {
2847                         let expr = P(self.lower_expr(&e));
2848                         let unstable_span =
2849                             self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
2850                         self.field(Symbol::intern(s), expr, unstable_span)
2851                     }).collect::<P<[hir::Field]>>();
2852
2853                 let is_unit = fields.is_empty();
2854                 let unstable_span =
2855                     self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
2856                 let struct_path =
2857                     iter::once("ops").chain(iter::once(path))
2858                     .collect::<Vec<_>>();
2859                 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
2860                 let struct_path = hir::QPath::Resolved(None, P(struct_path));
2861
2862                 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
2863
2864                 return hir::Expr {
2865                     id: node_id,
2866                     hir_id,
2867                     node: if is_unit {
2868                         hir::ExprPath(struct_path)
2869                     } else {
2870                         hir::ExprStruct(struct_path, fields, None)
2871                     },
2872                     span: unstable_span,
2873                     attrs: e.attrs.clone(),
2874                 };
2875             }
2876             ExprKind::Path(ref qself, ref path) => {
2877                 hir::ExprPath(self.lower_qpath(e.id, qself, path, ParamMode::Optional,
2878                                                ImplTraitContext::Disallowed))
2879             }
2880             ExprKind::Break(opt_label, ref opt_expr) => {
2881                 let destination = if self.is_in_loop_condition && opt_label.is_none() {
2882                     hir::Destination {
2883                         label: None,
2884                         target_id: hir::ScopeTarget::Loop(
2885                                 Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into()),
2886                     }
2887                 } else {
2888                     self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
2889                 };
2890                 hir::ExprBreak(
2891                         destination,
2892                         opt_expr.as_ref().map(|x| P(self.lower_expr(x))))
2893             }
2894             ExprKind::Continue(opt_label) =>
2895                 hir::ExprAgain(
2896                     if self.is_in_loop_condition && opt_label.is_none() {
2897                         hir::Destination {
2898                             label: None,
2899                             target_id: hir::ScopeTarget::Loop(Err(
2900                                 hir::LoopIdError::UnlabeledCfInWhileCondition).into()),
2901                         }
2902                     } else {
2903                         self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
2904                     }),
2905             ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
2906             ExprKind::InlineAsm(ref asm) => {
2907                 let hir_asm = hir::InlineAsm {
2908                     inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
2909                     outputs: asm.outputs.iter().map(|out| {
2910                         hir::InlineAsmOutput {
2911                             constraint: out.constraint.clone(),
2912                             is_rw: out.is_rw,
2913                             is_indirect: out.is_indirect,
2914                         }
2915                     }).collect(),
2916                     asm: asm.asm.clone(),
2917                     asm_str_style: asm.asm_str_style,
2918                     clobbers: asm.clobbers.clone().into(),
2919                     volatile: asm.volatile,
2920                     alignstack: asm.alignstack,
2921                     dialect: asm.dialect,
2922                     ctxt: asm.ctxt,
2923                 };
2924                 let outputs =
2925                     asm.outputs.iter().map(|out| self.lower_expr(&out.expr)).collect();
2926                 let inputs =
2927                     asm.inputs.iter().map(|&(_, ref input)| self.lower_expr(input)).collect();
2928                 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
2929             }
2930             ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
2931                 hir::ExprStruct(self.lower_qpath(e.id, &None, path, ParamMode::Optional,
2932                                                  ImplTraitContext::Disallowed),
2933                                 fields.iter().map(|x| self.lower_field(x)).collect(),
2934                                 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))))
2935             }
2936             ExprKind::Paren(ref ex) => {
2937                 let mut ex = self.lower_expr(ex);
2938                 // include parens in span, but only if it is a super-span.
2939                 if e.span.contains(ex.span) {
2940                     ex.span = e.span;
2941                 }
2942                 // merge attributes into the inner expression.
2943                 let mut attrs = e.attrs.clone();
2944                 attrs.extend::<Vec<_>>(ex.attrs.into());
2945                 ex.attrs = attrs;
2946                 return ex;
2947             }
2948
2949             ExprKind::Yield(ref opt_expr) => {
2950                 self.is_generator = true;
2951                 let expr = opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| {
2952                     self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new())
2953                 });
2954                 hir::ExprYield(P(expr))
2955             }
2956
2957             // Desugar ExprIfLet
2958             // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
2959             ExprKind::IfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
2960                 // to:
2961                 //
2962                 //   match <sub_expr> {
2963                 //     <pat> => <body>,
2964                 //     _ => [<else_opt> | ()]
2965                 //   }
2966
2967                 let mut arms = vec![];
2968
2969                 // `<pat> => <body>`
2970                 {
2971                     let body = self.lower_block(body, false);
2972                     let body_expr = P(self.expr_block(body, ThinVec::new()));
2973                     let pat = self.lower_pat(pat);
2974                     arms.push(self.arm(hir_vec![pat], body_expr));
2975                 }
2976
2977                 // _ => [<else_opt>|()]
2978                 {
2979                     let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
2980                     let wildcard_pattern = self.pat_wild(e.span);
2981                     let body = if let Some(else_expr) = wildcard_arm {
2982                         P(self.lower_expr(else_expr))
2983                     } else {
2984                         self.expr_tuple(e.span, hir_vec![])
2985                     };
2986                     arms.push(self.arm(hir_vec![wildcard_pattern], body));
2987                 }
2988
2989                 let contains_else_clause = else_opt.is_some();
2990
2991                 let sub_expr = P(self.lower_expr(sub_expr));
2992
2993                 hir::ExprMatch(
2994                     sub_expr,
2995                     arms.into(),
2996                     hir::MatchSource::IfLetDesugar {
2997                         contains_else_clause,
2998                     })
2999             }
3000
3001             // Desugar ExprWhileLet
3002             // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3003             ExprKind::WhileLet(ref pat, ref sub_expr, ref body, opt_label) => {
3004                 // to:
3005                 //
3006                 //   [opt_ident]: loop {
3007                 //     match <sub_expr> {
3008                 //       <pat> => <body>,
3009                 //       _ => break
3010                 //     }
3011                 //   }
3012
3013                 // Note that the block AND the condition are evaluated in the loop scope.
3014                 // This is done to allow `break` from inside the condition of the loop.
3015                 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| (
3016                     this.lower_block(body, false),
3017                     this.expr_break(e.span, ThinVec::new()),
3018                     this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3019                 ));
3020
3021                 // `<pat> => <body>`
3022                 let pat_arm = {
3023                     let body_expr = P(self.expr_block(body, ThinVec::new()));
3024                     let pat = self.lower_pat(pat);
3025                     self.arm(hir_vec![pat], body_expr)
3026                 };
3027
3028                 // `_ => break`
3029                 let break_arm = {
3030                     let pat_under = self.pat_wild(e.span);
3031                     self.arm(hir_vec![pat_under], break_expr)
3032                 };
3033
3034                 // `match <sub_expr> { ... }`
3035                 let arms = hir_vec![pat_arm, break_arm];
3036                 let match_expr = self.expr(e.span,
3037                                            hir::ExprMatch(sub_expr,
3038                                                           arms,
3039                                                           hir::MatchSource::WhileLetDesugar),
3040                                            ThinVec::new());
3041
3042                 // `[opt_ident]: loop { ... }`
3043                 let loop_block = P(self.block_expr(P(match_expr)));
3044                 let loop_expr = hir::ExprLoop(loop_block, self.lower_label(opt_label),
3045                                               hir::LoopSource::WhileLet);
3046                 // add attributes to the outer returned expr node
3047                 loop_expr
3048             }
3049
3050             // Desugar ExprForLoop
3051             // From: `[opt_ident]: for <pat> in <head> <body>`
3052             ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3053                 // to:
3054                 //
3055                 //   {
3056                 //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3057                 //       mut iter => {
3058                 //         [opt_ident]: loop {
3059                 //           let mut __next;
3060                 //           match ::std::iter::Iterator::next(&mut iter) {
3061                 //             ::std::option::Option::Some(val) => __next = val,
3062                 //             ::std::option::Option::None => break
3063                 //           };
3064                 //           let <pat> = __next;
3065                 //           StmtExpr(<body>);
3066                 //         }
3067                 //       }
3068                 //     };
3069                 //     result
3070                 //   }
3071
3072                 // expand <head>
3073                 let head = self.lower_expr(head);
3074
3075                 let iter = self.str_to_ident("iter");
3076
3077                 let next_ident = self.str_to_ident("__next");
3078                 let next_pat = self.pat_ident_binding_mode(e.span,
3079                                                            next_ident,
3080                                                            hir::BindingAnnotation::Mutable);
3081
3082                 // `::std::option::Option::Some(val) => next = val`
3083                 let pat_arm = {
3084                     let val_ident = self.str_to_ident("val");
3085                     let val_pat = self.pat_ident(e.span, val_ident);
3086                     let val_expr = P(self.expr_ident(e.span, val_ident, val_pat.id));
3087                     let next_expr = P(self.expr_ident(e.span, next_ident, next_pat.id));
3088                     let assign = P(self.expr(e.span,
3089                                              hir::ExprAssign(next_expr, val_expr),
3090                                              ThinVec::new()));
3091                     let some_pat = self.pat_some(e.span, val_pat);
3092                     self.arm(hir_vec![some_pat], assign)
3093                 };
3094
3095                 // `::std::option::Option::None => break`
3096                 let break_arm = {
3097                     let break_expr = self.with_loop_scope(e.id, |this|
3098                         this.expr_break(e.span, ThinVec::new()));
3099                     let pat = self.pat_none(e.span);
3100                     self.arm(hir_vec![pat], break_expr)
3101                 };
3102
3103                 // `mut iter`
3104                 let iter_pat = self.pat_ident_binding_mode(e.span,
3105                                                            iter,
3106                                                            hir::BindingAnnotation::Mutable);
3107
3108                 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3109                 let match_expr = {
3110                     let iter = P(self.expr_ident(e.span, iter, iter_pat.id));
3111                     let ref_mut_iter = self.expr_mut_addr_of(e.span, iter);
3112                     let next_path = &["iter", "Iterator", "next"];
3113                     let next_path = P(self.expr_std_path(e.span, next_path, ThinVec::new()));
3114                     let next_expr = P(self.expr_call(e.span, next_path,
3115                                       hir_vec![ref_mut_iter]));
3116                     let arms = hir_vec![pat_arm, break_arm];
3117
3118                     P(self.expr(e.span,
3119                                 hir::ExprMatch(next_expr, arms,
3120                                                hir::MatchSource::ForLoopDesugar),
3121                                 ThinVec::new()))
3122                 };
3123                 let match_stmt = respan(e.span, hir::StmtExpr(match_expr, self.next_id().node_id));
3124
3125                 let next_expr = P(self.expr_ident(e.span, next_ident, next_pat.id));
3126
3127                 // `let mut __next`
3128                 let next_let = self.stmt_let_pat(e.span,
3129                     None,
3130                     next_pat,
3131                     hir::LocalSource::ForLoopDesugar);
3132
3133                 // `let <pat> = __next`
3134                 let pat = self.lower_pat(pat);
3135                 let pat_let = self.stmt_let_pat(e.span,
3136                     Some(next_expr),
3137                     pat,
3138                     hir::LocalSource::ForLoopDesugar);
3139
3140                 let body_block = self.with_loop_scope(e.id,
3141                                                         |this| this.lower_block(body, false));
3142                 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
3143                 let body_stmt = respan(e.span, hir::StmtExpr(body_expr, self.next_id().node_id));
3144
3145                 let loop_block = P(self.block_all(e.span,
3146                                                   hir_vec![next_let,
3147                                                            match_stmt,
3148                                                            pat_let,
3149                                                            body_stmt],
3150                                                   None));
3151
3152                 // `[opt_ident]: loop { ... }`
3153                 let loop_expr = hir::ExprLoop(loop_block, self.lower_label(opt_label),
3154                                               hir::LoopSource::ForLoop);
3155                 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3156                 let loop_expr = P(hir::Expr {
3157                     id: node_id,
3158                     hir_id,
3159                     node: loop_expr,
3160                     span: e.span,
3161                     attrs: ThinVec::new(),
3162                 });
3163
3164                 // `mut iter => { ... }`
3165                 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
3166
3167                 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
3168                 let into_iter_expr = {
3169                     let into_iter_path = &["iter", "IntoIterator", "into_iter"];
3170                     let into_iter = P(self.expr_std_path(e.span, into_iter_path,
3171                                                          ThinVec::new()));
3172                     P(self.expr_call(e.span, into_iter, hir_vec![head]))
3173                 };
3174
3175                 let match_expr = P(self.expr_match(e.span,
3176                                                    into_iter_expr,
3177                                                    hir_vec![iter_arm],
3178                                                    hir::MatchSource::ForLoopDesugar));
3179
3180                 // `{ let _result = ...; _result }`
3181                 // underscore prevents an unused_variables lint if the head diverges
3182                 let result_ident = self.str_to_ident("_result");
3183                 let (let_stmt, let_stmt_binding) =
3184                     self.stmt_let(e.span, false, result_ident, match_expr);
3185
3186                 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
3187                 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
3188                 // add the attributes to the outer returned expr node
3189                 return self.expr_block(block, e.attrs.clone());
3190             }
3191
3192             // Desugar ExprKind::Try
3193             // From: `<expr>?`
3194             ExprKind::Try(ref sub_expr) => {
3195                 // to:
3196                 //
3197                 // match Try::into_result(<expr>) {
3198                 //     Ok(val) => #[allow(unreachable_code)] val,
3199                 //     Err(err) => #[allow(unreachable_code)]
3200                 //                 // If there is an enclosing `catch {...}`
3201                 //                 break 'catch_target Try::from_error(From::from(err)),
3202                 //                 // Otherwise
3203                 //                 return Try::from_error(From::from(err)),
3204                 // }
3205
3206                 let unstable_span =
3207                     self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
3208
3209                 // Try::into_result(<expr>)
3210                 let discr = {
3211                     // expand <expr>
3212                     let sub_expr = self.lower_expr(sub_expr);
3213
3214                     let path = &["ops", "Try", "into_result"];
3215                     let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
3216                     P(self.expr_call(e.span, path, hir_vec![sub_expr]))
3217                 };
3218
3219                 // #[allow(unreachable_code)]
3220                 let attr = {
3221                     // allow(unreachable_code)
3222                     let allow = {
3223                         let allow_ident = self.str_to_ident("allow");
3224                         let uc_ident = self.str_to_ident("unreachable_code");
3225                         let uc_meta_item = attr::mk_spanned_word_item(e.span, uc_ident);
3226                         let uc_nested = NestedMetaItemKind::MetaItem(uc_meta_item);
3227                         let uc_spanned = respan(e.span, uc_nested);
3228                         attr::mk_spanned_list_item(e.span, allow_ident, vec![uc_spanned])
3229                     };
3230                     attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
3231                 };
3232                 let attrs = vec![attr];
3233
3234                 // Ok(val) => #[allow(unreachable_code)] val,
3235                 let ok_arm = {
3236                     let val_ident = self.str_to_ident("val");
3237                     let val_pat = self.pat_ident(e.span, val_ident);
3238                     let val_expr = P(self.expr_ident_with_attrs(e.span,
3239                                                                 val_ident,
3240                                                                 val_pat.id,
3241                                                                 ThinVec::from(attrs.clone())));
3242                     let ok_pat = self.pat_ok(e.span, val_pat);
3243
3244                     self.arm(hir_vec![ok_pat], val_expr)
3245                 };
3246
3247                 // Err(err) => #[allow(unreachable_code)]
3248                 //             return Try::from_error(From::from(err)),
3249                 let err_arm = {
3250                     let err_ident = self.str_to_ident("err");
3251                     let err_local = self.pat_ident(e.span, err_ident);
3252                     let from_expr = {
3253                         let path = &["convert", "From", "from"];
3254                         let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
3255                         let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
3256
3257                         self.expr_call(e.span, from, hir_vec![err_expr])
3258                     };
3259                     let from_err_expr = {
3260                         let path = &["ops", "Try", "from_error"];
3261                         let from_err = P(self.expr_std_path(unstable_span, path,
3262                                                             ThinVec::new()));
3263                         P(self.expr_call(e.span, from_err, hir_vec![from_expr]))
3264                     };
3265
3266                     let thin_attrs = ThinVec::from(attrs);
3267                     let catch_scope = self.catch_scopes.last().map(|x| *x);
3268                     let ret_expr = if let Some(catch_node) = catch_scope {
3269                         P(self.expr(
3270                             e.span,
3271                             hir::ExprBreak(
3272                                 hir::Destination {
3273                                     label: None,
3274                                     target_id: hir::ScopeTarget::Block(catch_node),
3275                                 },
3276                                 Some(from_err_expr)
3277                             ),
3278                             thin_attrs))
3279                     } else {
3280                         P(self.expr(e.span,
3281                                     hir::Expr_::ExprRet(Some(from_err_expr)),
3282                                     thin_attrs))
3283                     };
3284
3285
3286                     let err_pat = self.pat_err(e.span, err_local);
3287                     self.arm(hir_vec![err_pat], ret_expr)
3288                 };
3289
3290                 hir::ExprMatch(discr,
3291                                hir_vec![err_arm, ok_arm],
3292                                hir::MatchSource::TryDesugar)
3293             }
3294
3295             ExprKind::Mac(_) => panic!("Shouldn't exist here"),
3296         };
3297
3298         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3299
3300         hir::Expr {
3301             id: node_id,
3302             hir_id,
3303             node: kind,
3304             span: e.span,
3305             attrs: e.attrs.clone(),
3306         }
3307     }
3308
3309     fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
3310         SmallVector::one(match s.node {
3311             StmtKind::Local(ref l) => Spanned {
3312                 node: hir::StmtDecl(P(Spanned {
3313                     node: hir::DeclLocal(self.lower_local(l)),
3314                     span: s.span,
3315                 }), self.lower_node_id(s.id).node_id),
3316                 span: s.span,
3317             },
3318             StmtKind::Item(ref it) => {
3319                 // Can only use the ID once.
3320                 let mut id = Some(s.id);
3321                 return self.lower_item_id(it).into_iter().map(|item_id| Spanned {
3322                     node: hir::StmtDecl(P(Spanned {
3323                         node: hir::DeclItem(item_id),
3324                         span: s.span,
3325                     }), id.take()
3326                           .map(|id| self.lower_node_id(id).node_id)
3327                           .unwrap_or_else(|| self.next_id().node_id)),
3328                     span: s.span,
3329                 }).collect();
3330             }
3331             StmtKind::Expr(ref e) => {
3332                 Spanned {
3333                     node: hir::StmtExpr(P(self.lower_expr(e)),
3334                                           self.lower_node_id(s.id).node_id),
3335                     span: s.span,
3336                 }
3337             }
3338             StmtKind::Semi(ref e) => {
3339                 Spanned {
3340                     node: hir::StmtSemi(P(self.lower_expr(e)),
3341                                           self.lower_node_id(s.id).node_id),
3342                     span: s.span,
3343                 }
3344             }
3345             StmtKind::Mac(..) => panic!("Shouldn't exist here"),
3346         })
3347     }
3348
3349     fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
3350         match c {
3351             CaptureBy::Value => hir::CaptureByValue,
3352             CaptureBy::Ref => hir::CaptureByRef,
3353         }
3354     }
3355
3356     /// If an `explicit_owner` is given, this method allocates the `HirId` in
3357     /// the address space of that item instead of the item currently being
3358     /// lowered. This can happen during `lower_impl_item_ref()` where we need to
3359     /// lower a `Visibility` value although we haven't lowered the owning
3360     /// `ImplItem` in question yet.
3361     fn lower_visibility(&mut self,
3362                         v: &Visibility,
3363                         explicit_owner: Option<NodeId>)
3364                         -> hir::Visibility {
3365         match *v {
3366             Visibility::Public => hir::Public,
3367             Visibility::Crate(..) => hir::Visibility::Crate,
3368             Visibility::Restricted { ref path, id } => {
3369                 hir::Visibility::Restricted {
3370                     path: P(self.lower_path(id, path, ParamMode::Explicit, true)),
3371                     id: if let Some(owner) = explicit_owner {
3372                         self.lower_node_id_with_owner(id, owner).node_id
3373                     } else {
3374                         self.lower_node_id(id).node_id
3375                     }
3376                 }
3377             }
3378             Visibility::Inherited => hir::Inherited,
3379         }
3380     }
3381
3382     fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
3383         match d {
3384             Defaultness::Default => hir::Defaultness::Default { has_value: has_value },
3385             Defaultness::Final => {
3386                 assert!(has_value);
3387                 hir::Defaultness::Final
3388             }
3389         }
3390     }
3391
3392     fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3393         match *b {
3394             BlockCheckMode::Default => hir::DefaultBlock,
3395             BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3396         }
3397     }
3398
3399     fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3400         match *b {
3401             BindingMode::ByValue(Mutability::Immutable) =>
3402                 hir::BindingAnnotation::Unannotated,
3403             BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3404             BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3405             BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3406         }
3407     }
3408
3409     fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3410         match u {
3411             CompilerGenerated => hir::CompilerGenerated,
3412             UserProvided => hir::UserProvided,
3413         }
3414     }
3415
3416     fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
3417         match i {
3418             ImplPolarity::Positive => hir::ImplPolarity::Positive,
3419             ImplPolarity::Negative => hir::ImplPolarity::Negative,
3420         }
3421     }
3422
3423     fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3424         match f {
3425             TraitBoundModifier::None => hir::TraitBoundModifier::None,
3426             TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3427         }
3428     }
3429
3430     // Helper methods for building HIR.
3431
3432     fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
3433         hir::Arm {
3434             attrs: hir_vec![],
3435             pats,
3436             guard: None,
3437             body: expr,
3438         }
3439     }
3440
3441     fn field(&mut self, name: Name, expr: P<hir::Expr>, span: Span) -> hir::Field {
3442         hir::Field {
3443             name: Spanned {
3444                 node: name,
3445                 span,
3446             },
3447             span,
3448             expr,
3449             is_shorthand: false,
3450         }
3451     }
3452
3453     fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
3454         let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
3455         P(self.expr(span, expr_break, attrs))
3456     }
3457
3458     fn expr_call(&mut self, span: Span, e: P<hir::Expr>, args: hir::HirVec<hir::Expr>)
3459                  -> hir::Expr {
3460         self.expr(span, hir::ExprCall(e, args), ThinVec::new())
3461     }
3462
3463     fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
3464         self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
3465     }
3466
3467     fn expr_ident_with_attrs(&mut self, span: Span,
3468                                         id: Name,
3469                                         binding: NodeId,
3470                                         attrs: ThinVec<Attribute>) -> hir::Expr {
3471         let expr_path = hir::ExprPath(hir::QPath::Resolved(None, P(hir::Path {
3472             span,
3473             def: Def::Local(binding),
3474             segments: hir_vec![hir::PathSegment::from_name(id)],
3475         })));
3476
3477         self.expr(span, expr_path, attrs)
3478     }
3479
3480     fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
3481         self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
3482     }
3483
3484     fn expr_std_path(&mut self,
3485                      span: Span,
3486                      components: &[&str],
3487                      attrs: ThinVec<Attribute>)
3488                      -> hir::Expr {
3489         let path = self.std_path(span, components, true);
3490         self.expr(span, hir::ExprPath(hir::QPath::Resolved(None, P(path))), attrs)
3491     }
3492
3493     fn expr_match(&mut self,
3494                   span: Span,
3495                   arg: P<hir::Expr>,
3496                   arms: hir::HirVec<hir::Arm>,
3497                   source: hir::MatchSource)
3498                   -> hir::Expr {
3499         self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
3500     }
3501
3502     fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
3503         self.expr(b.span, hir::ExprBlock(b), attrs)
3504     }
3505
3506     fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
3507         P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
3508     }
3509
3510     fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
3511         let LoweredNodeId { node_id, hir_id } = self.next_id();
3512         hir::Expr {
3513             id: node_id,
3514             hir_id,
3515             node,
3516             span,
3517             attrs,
3518         }
3519     }
3520
3521     fn stmt_let_pat(&mut self,
3522                     sp: Span,
3523                     ex: Option<P<hir::Expr>>,
3524                     pat: P<hir::Pat>,
3525                     source: hir::LocalSource)
3526                     -> hir::Stmt {
3527         let LoweredNodeId { node_id, hir_id } = self.next_id();
3528
3529         let local = P(hir::Local {
3530             pat,
3531             ty: None,
3532             init: ex,
3533             id: node_id,
3534             hir_id,
3535             span: sp,
3536             attrs: ThinVec::new(),
3537             source,
3538         });
3539         let decl = respan(sp, hir::DeclLocal(local));
3540         respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
3541     }
3542
3543     fn stmt_let(&mut self, sp: Span, mutbl: bool, ident: Name, ex: P<hir::Expr>)
3544                 -> (hir::Stmt, NodeId) {
3545         let pat = if mutbl {
3546             self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
3547         } else {
3548             self.pat_ident(sp, ident)
3549         };
3550         let pat_id = pat.id;
3551         (self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal), pat_id)
3552     }
3553
3554     fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
3555         self.block_all(expr.span, hir::HirVec::new(), Some(expr))
3556     }
3557
3558     fn block_all(&mut self, span: Span, stmts: hir::HirVec<hir::Stmt>, expr: Option<P<hir::Expr>>)
3559                  -> hir::Block {
3560         let LoweredNodeId { node_id, hir_id } = self.next_id();
3561
3562         hir::Block {
3563             stmts,
3564             expr,
3565             id: node_id,
3566             hir_id,
3567             rules: hir::DefaultBlock,
3568             span,
3569             targeted_by_break: false,
3570             recovered: false,
3571         }
3572     }
3573
3574     fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3575         self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
3576     }
3577
3578     fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3579         self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
3580     }
3581
3582     fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3583         self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
3584     }
3585
3586     fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
3587         self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
3588     }
3589
3590     fn pat_std_enum(&mut self,
3591                     span: Span,
3592                     components: &[&str],
3593                     subpats: hir::HirVec<P<hir::Pat>>)
3594                     -> P<hir::Pat> {
3595         let path = self.std_path(span, components, true);
3596         let qpath = hir::QPath::Resolved(None, P(path));
3597         let pt = if subpats.is_empty() {
3598             hir::PatKind::Path(qpath)
3599         } else {
3600             hir::PatKind::TupleStruct(qpath, subpats, None)
3601         };
3602         self.pat(span, pt)
3603     }
3604
3605     fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
3606         self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
3607     }
3608
3609     fn pat_ident_binding_mode(&mut self, span: Span, name: Name, bm: hir::BindingAnnotation)
3610                               -> P<hir::Pat> {
3611         let LoweredNodeId { node_id, hir_id } = self.next_id();
3612
3613         P(hir::Pat {
3614             id: node_id,
3615             hir_id,
3616             node: hir::PatKind::Binding(bm,
3617                                         node_id,
3618                                         Spanned {
3619                                             span,
3620                                             node: name,
3621                                         },
3622                                         None),
3623             span,
3624         })
3625     }
3626
3627     fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
3628         self.pat(span, hir::PatKind::Wild)
3629     }
3630
3631     fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
3632         let LoweredNodeId { node_id, hir_id } = self.next_id();
3633         P(hir::Pat {
3634             id: node_id,
3635             hir_id,
3636             node: pat,
3637             span,
3638         })
3639     }
3640
3641     /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
3642     /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
3643     /// The path is also resolved according to `is_value`.
3644     fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
3645         self.resolver.resolve_str_path(span, self.crate_root, components, is_value)
3646     }
3647
3648     fn signal_block_expr(&mut self,
3649                          stmts: hir::HirVec<hir::Stmt>,
3650                          expr: P<hir::Expr>,
3651                          span: Span,
3652                          rule: hir::BlockCheckMode,
3653                          attrs: ThinVec<Attribute>)
3654                          -> hir::Expr {
3655         let LoweredNodeId { node_id, hir_id } = self.next_id();
3656
3657         let block = P(hir::Block {
3658             rules: rule,
3659             span,
3660             id: node_id,
3661             hir_id,
3662             stmts,
3663             expr: Some(expr),
3664             targeted_by_break: false,
3665             recovered: false,
3666         });
3667         self.expr_block(block, attrs)
3668     }
3669
3670     fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
3671         let mut id = id;
3672         let node = match qpath {
3673             hir::QPath::Resolved(None, path) => {
3674                 // Turn trait object paths into `TyTraitObject` instead.
3675                 if let Def::Trait(_) = path.def {
3676                     let principal = hir::PolyTraitRef {
3677                         bound_generic_params: hir::HirVec::new(),
3678                         trait_ref: hir::TraitRef {
3679                             path: path.and_then(|path| path),
3680                             ref_id: id.node_id,
3681                         },
3682                         span,
3683                     };
3684
3685                     // The original ID is taken by the `PolyTraitRef`,
3686                     // so the `Ty` itself needs a different one.
3687                     id = self.next_id();
3688
3689                     hir::TyTraitObject(hir_vec![principal], self.elided_lifetime(span))
3690                 } else {
3691                     hir::TyPath(hir::QPath::Resolved(None, path))
3692                 }
3693             }
3694             _ => hir::TyPath(qpath)
3695         };
3696         P(hir::Ty { id: id.node_id, hir_id: id.hir_id, node, span })
3697     }
3698
3699     fn elided_lifetime(&mut self, span: Span) -> hir::Lifetime {
3700         hir::Lifetime {
3701             id: self.next_id().node_id,
3702             span,
3703             name: hir::LifetimeName::Implicit,
3704         }
3705     }
3706 }
3707
3708 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
3709     // Sorting by span ensures that we get things in order within a
3710     // file, and also puts the files in a sensible order.
3711     let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
3712     body_ids.sort_by_key(|b| bodies[b].value.span);
3713     body_ids
3714 }