]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/lowering.rs
5ef278207ed5e8a9f78fb0890bc35bf1199dae22
[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 hir;
44 use hir::map::{Definitions, DefKey, REGULAR_SPACE};
45 use hir::map::definitions::DefPathData;
46 use hir::def_id::{DefIndex, DefId, CRATE_DEF_INDEX};
47 use hir::def::{Def, PathResolution};
48 use rustc_data_structures::indexed_vec::IndexVec;
49 use session::Session;
50 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
51
52 use std::collections::BTreeMap;
53 use std::fmt::Debug;
54 use std::iter;
55 use std::mem;
56
57 use syntax::attr;
58 use syntax::ast::*;
59 use syntax::errors;
60 use syntax::ext::hygiene::{Mark, SyntaxContext};
61 use syntax::ptr::P;
62 use syntax::codemap::{self, respan, Spanned};
63 use syntax::std_inject;
64 use syntax::symbol::{Symbol, keywords};
65 use syntax::util::small_vector::SmallVector;
66 use syntax::visit::{self, Visitor};
67 use syntax_pos::Span;
68
69 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
70
71 pub struct LoweringContext<'a> {
72     crate_root: Option<&'static str>,
73     // Use to assign ids to hir nodes that do not directly correspond to an ast node
74     sess: &'a Session,
75     // As we walk the AST we must keep track of the current 'parent' def id (in
76     // the form of a DefIndex) so that if we create a new node which introduces
77     // a definition, then we can properly create the def id.
78     parent_def: Option<DefIndex>,
79     resolver: &'a mut Resolver,
80     name_map: FxHashMap<Ident, Name>,
81
82     /// The items being lowered are collected here.
83     items: BTreeMap<NodeId, hir::Item>,
84
85     trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
86     impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
87     bodies: BTreeMap<hir::BodyId, hir::Body>,
88     exported_macros: Vec<hir::MacroDef>,
89
90     trait_impls: BTreeMap<DefId, Vec<NodeId>>,
91     trait_default_impl: BTreeMap<DefId, NodeId>,
92
93     catch_scopes: Vec<NodeId>,
94     loop_scopes: Vec<NodeId>,
95     is_in_loop_condition: bool,
96
97     type_def_lifetime_params: DefIdMap<usize>,
98
99     current_hir_id_owner: Vec<(DefIndex, u32)>,
100     item_local_id_counters: NodeMap<u32>,
101     node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
102 }
103
104 pub trait Resolver {
105     // Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc.
106     fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool);
107
108     // Obtain the resolution for a node id
109     fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
110
111     // We must keep the set of definitions up to date as we add nodes that weren't in the AST.
112     // This should only return `None` during testing.
113     fn definitions(&mut self) -> &mut Definitions;
114 }
115
116 pub fn lower_crate(sess: &Session,
117                    krate: &Crate,
118                    resolver: &mut Resolver)
119                    -> hir::Crate {
120     // We're constructing the HIR here; we don't care what we will
121     // read, since we haven't even constructed the *input* to
122     // incr. comp. yet.
123     let _ignore = sess.dep_graph.in_ignore();
124
125     LoweringContext {
126         crate_root: std_inject::injected_crate_name(krate),
127         sess: sess,
128         parent_def: None,
129         resolver: resolver,
130         name_map: FxHashMap(),
131         items: BTreeMap::new(),
132         trait_items: BTreeMap::new(),
133         impl_items: BTreeMap::new(),
134         bodies: BTreeMap::new(),
135         trait_impls: BTreeMap::new(),
136         trait_default_impl: BTreeMap::new(),
137         exported_macros: Vec::new(),
138         catch_scopes: Vec::new(),
139         loop_scopes: Vec::new(),
140         is_in_loop_condition: false,
141         type_def_lifetime_params: DefIdMap(),
142         current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
143         item_local_id_counters: NodeMap(),
144         node_id_to_hir_id: IndexVec::new(),
145     }.lower_crate(krate)
146 }
147
148 #[derive(Copy, Clone, PartialEq, Eq)]
149 enum ParamMode {
150     /// Any path in a type context.
151     Explicit,
152     /// The `module::Type` in `module::Type::method` in an expression.
153     Optional
154 }
155
156 impl<'a> LoweringContext<'a> {
157     fn lower_crate(mut self, c: &Crate) -> hir::Crate {
158         /// Full-crate AST visitor that inserts into a fresh
159         /// `LoweringContext` any information that may be
160         /// needed from arbitrary locations in the crate.
161         /// E.g. The number of lifetime generic parameters
162         /// declared for every type and trait definition.
163         struct MiscCollector<'lcx, 'interner: 'lcx> {
164             lctx: &'lcx mut LoweringContext<'interner>,
165         }
166
167         impl<'lcx, 'interner> Visitor<'lcx> for MiscCollector<'lcx, 'interner> {
168             fn visit_item(&mut self, item: &'lcx Item) {
169                 self.lctx.allocate_hir_id_counter(item.id, item);
170
171                 match item.node {
172                     ItemKind::Struct(_, ref generics) |
173                     ItemKind::Union(_, ref generics) |
174                     ItemKind::Enum(_, ref generics) |
175                     ItemKind::Ty(_, ref generics) |
176                     ItemKind::Trait(_, ref generics, ..) => {
177                         let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
178                         let count = generics.lifetimes.len();
179                         self.lctx.type_def_lifetime_params.insert(def_id, count);
180                     }
181                     _ => {}
182                 }
183                 visit::walk_item(self, item);
184             }
185
186             fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
187                 self.lctx.allocate_hir_id_counter(item.id, item);
188                 visit::walk_trait_item(self, item);
189             }
190
191             fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
192                 self.lctx.allocate_hir_id_counter(item.id, item);
193                 visit::walk_impl_item(self, item);
194             }
195         }
196
197         struct ItemLowerer<'lcx, 'interner: 'lcx> {
198             lctx: &'lcx mut LoweringContext<'interner>,
199         }
200
201         impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
202             fn visit_item(&mut self, item: &'lcx Item) {
203                 let mut item_lowered = true;
204                 self.lctx.with_hir_id_owner(item.id, |lctx| {
205                     if let Some(hir_item) = lctx.lower_item(item) {
206                         lctx.items.insert(item.id, hir_item);
207                     } else {
208                         item_lowered = false;
209                     }
210                 });
211
212                 if item_lowered {
213                     visit::walk_item(self, item);
214                 }
215             }
216
217             fn visit_trait_item(&mut self, item: &'lcx TraitItem) {
218                 self.lctx.with_hir_id_owner(item.id, |lctx| {
219                     let id = hir::TraitItemId { node_id: item.id };
220                     let hir_item = lctx.lower_trait_item(item);
221                     lctx.trait_items.insert(id, hir_item);
222                 });
223
224                 visit::walk_trait_item(self, item);
225             }
226
227             fn visit_impl_item(&mut self, item: &'lcx ImplItem) {
228                 self.lctx.with_hir_id_owner(item.id, |lctx| {
229                     let id = hir::ImplItemId { node_id: item.id };
230                     let hir_item = lctx.lower_impl_item(item);
231                     lctx.impl_items.insert(id, hir_item);
232                 });
233                 visit::walk_impl_item(self, item);
234             }
235         }
236
237         self.lower_node_id(CRATE_NODE_ID);
238         debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
239
240         visit::walk_crate(&mut MiscCollector { lctx: &mut self }, c);
241         visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
242
243         let module = self.lower_mod(&c.module);
244         let attrs = self.lower_attrs(&c.attrs);
245         let body_ids = body_ids(&self.bodies);
246
247         self.resolver
248             .definitions()
249             .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
250
251         hir::Crate {
252             module: module,
253             attrs: attrs,
254             span: c.span,
255             exported_macros: hir::HirVec::from(self.exported_macros),
256             items: self.items,
257             trait_items: self.trait_items,
258             impl_items: self.impl_items,
259             bodies: self.bodies,
260             body_ids: body_ids,
261             trait_impls: self.trait_impls,
262             trait_default_impl: self.trait_default_impl,
263         }
264     }
265
266     fn allocate_hir_id_counter<T: Debug>(&mut self,
267                                          owner: NodeId,
268                                          debug: &T) {
269         if self.item_local_id_counters.insert(owner, 0).is_some() {
270             bug!("Tried to allocate item_local_id_counter for {:?} twice", debug);
271         }
272         // Always allocate the first HirId for the owner itself
273         self.lower_node_id_with_owner(owner, owner);
274     }
275
276     fn lower_node_id_generic<F>(&mut self,
277                                 ast_node_id: NodeId,
278                                 alloc_hir_id: F)
279                                 -> NodeId
280         where F: FnOnce(&mut Self) -> hir::HirId
281     {
282         if ast_node_id == DUMMY_NODE_ID {
283             return ast_node_id;
284         }
285
286         let min_size = ast_node_id.as_usize() + 1;
287
288         if min_size > self.node_id_to_hir_id.len() {
289             self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
290         }
291
292         if self.node_id_to_hir_id[ast_node_id] == hir::DUMMY_HIR_ID {
293             // Generate a new HirId
294             self.node_id_to_hir_id[ast_node_id] = alloc_hir_id(self);
295         }
296
297         ast_node_id
298     }
299
300     fn with_hir_id_owner<F>(&mut self, owner: NodeId, f: F)
301         where F: FnOnce(&mut Self)
302     {
303         let counter = self.item_local_id_counters
304                           .insert(owner, HIR_ID_COUNTER_LOCKED)
305                           .unwrap();
306         let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
307         self.current_hir_id_owner.push((def_index, counter));
308         f(self);
309         let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
310
311         debug_assert!(def_index == new_def_index);
312         debug_assert!(new_counter >= counter);
313
314         let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap();
315         debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
316     }
317
318     /// This method allocates a new HirId for the given NodeId and stores it in
319     /// the LoweringContext's NodeId => HirId map.
320     /// Take care not to call this method if the resulting HirId is then not
321     /// actually used in the HIR, as that would trigger an assertion in the
322     /// HirIdValidator later on, which makes sure that all NodeIds got mapped
323     /// properly. Calling the method twice with the same NodeId is fine though.
324     fn lower_node_id(&mut self, ast_node_id: NodeId) -> NodeId {
325         self.lower_node_id_generic(ast_node_id, |this| {
326             let &mut (def_index, ref mut local_id_counter) = this.current_hir_id_owner
327                                                                  .last_mut()
328                                                                  .unwrap();
329             let local_id = *local_id_counter;
330             *local_id_counter += 1;
331             hir::HirId {
332                 owner: def_index,
333                 local_id: hir::ItemLocalId(local_id),
334             }
335         })
336     }
337
338     fn lower_node_id_with_owner(&mut self,
339                                 ast_node_id: NodeId,
340                                 owner: NodeId)
341                                 -> NodeId {
342         self.lower_node_id_generic(ast_node_id, |this| {
343             let local_id_counter = this.item_local_id_counters
344                                        .get_mut(&owner)
345                                        .unwrap();
346             let local_id = *local_id_counter;
347
348             // We want to be sure not to modify the counter in the map while it
349             // is also on the stack. Otherwise we'll get lost updates when writing
350             // back from the stack to the map.
351             debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
352
353             *local_id_counter += 1;
354             let def_index = this.resolver.definitions().opt_def_index(owner).unwrap();
355
356             hir::HirId {
357                 owner: def_index,
358                 local_id: hir::ItemLocalId(local_id),
359             }
360         })
361     }
362
363     fn record_body(&mut self, value: hir::Expr, decl: Option<&FnDecl>)
364                    -> hir::BodyId {
365         let body = hir::Body {
366             arguments: decl.map_or(hir_vec![], |decl| {
367                 decl.inputs.iter().map(|x| self.lower_arg(x)).collect()
368             }),
369             value: value
370         };
371         let id = body.id();
372         self.bodies.insert(id, body);
373         id
374     }
375
376     fn next_id(&mut self) -> NodeId {
377         self.lower_node_id(self.sess.next_node_id())
378     }
379
380     fn expect_full_def(&mut self, id: NodeId) -> Def {
381         self.resolver.get_resolution(id).map_or(Def::Err, |pr| {
382             if pr.unresolved_segments() != 0 {
383                 bug!("path not fully resolved: {:?}", pr);
384             }
385             pr.base_def()
386         })
387     }
388
389     fn diagnostic(&self) -> &errors::Handler {
390         self.sess.diagnostic()
391     }
392
393     fn str_to_ident(&self, s: &'static str) -> Name {
394         Symbol::gensym(s)
395     }
396
397     fn allow_internal_unstable(&self, reason: &'static str, mut span: Span) -> Span {
398         let mark = Mark::fresh(Mark::root());
399         mark.set_expn_info(codemap::ExpnInfo {
400             call_site: span,
401             callee: codemap::NameAndSpan {
402                 format: codemap::CompilerDesugaring(Symbol::intern(reason)),
403                 span: Some(span),
404                 allow_internal_unstable: true,
405             },
406         });
407         span.ctxt = SyntaxContext::empty().apply_mark(mark);
408         span
409     }
410
411     fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
412         where F: FnOnce(&mut LoweringContext) -> T
413     {
414         let len = self.catch_scopes.len();
415         self.catch_scopes.push(catch_id);
416
417         let result = f(self);
418         assert_eq!(len + 1, self.catch_scopes.len(),
419             "catch scopes should be added and removed in stack order");
420
421         self.catch_scopes.pop().unwrap();
422
423         result
424     }
425
426     fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
427         where F: FnOnce(&mut LoweringContext) -> T
428     {
429         // We're no longer in the base loop's condition; we're in another loop.
430         let was_in_loop_condition = self.is_in_loop_condition;
431         self.is_in_loop_condition = false;
432
433         let len = self.loop_scopes.len();
434         self.loop_scopes.push(loop_id);
435
436         let result = f(self);
437         assert_eq!(len + 1, self.loop_scopes.len(),
438             "Loop scopes should be added and removed in stack order");
439
440         self.loop_scopes.pop().unwrap();
441
442         self.is_in_loop_condition = was_in_loop_condition;
443
444         result
445     }
446
447     fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
448         where F: FnOnce(&mut LoweringContext) -> T
449     {
450         let was_in_loop_condition = self.is_in_loop_condition;
451         self.is_in_loop_condition = true;
452
453         let result = f(self);
454
455         self.is_in_loop_condition = was_in_loop_condition;
456
457         result
458     }
459
460     fn with_new_scopes<T, F>(&mut self, f: F) -> T
461         where F: FnOnce(&mut LoweringContext) -> T
462     {
463         let was_in_loop_condition = self.is_in_loop_condition;
464         self.is_in_loop_condition = false;
465
466         let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
467         let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
468         let result = f(self);
469         self.catch_scopes = catch_scopes;
470         self.loop_scopes = loop_scopes;
471
472         self.is_in_loop_condition = was_in_loop_condition;
473
474         result
475     }
476
477     fn with_parent_def<T, F>(&mut self, parent_id: NodeId, f: F) -> T
478         where F: FnOnce(&mut LoweringContext) -> T
479     {
480         let old_def = self.parent_def;
481         self.parent_def = {
482             let defs = self.resolver.definitions();
483             Some(defs.opt_def_index(parent_id).unwrap())
484         };
485
486         let result = f(self);
487
488         self.parent_def = old_def;
489         result
490     }
491
492     fn def_key(&mut self, id: DefId) -> DefKey {
493         if id.is_local() {
494             self.resolver.definitions().def_key(id.index)
495         } else {
496             self.sess.cstore.def_key(id)
497         }
498     }
499
500     fn lower_ident(&mut self, ident: Ident) -> Name {
501         let ident = ident.modern();
502         if ident.ctxt == SyntaxContext::empty() {
503             return ident.name;
504         }
505         *self.name_map.entry(ident).or_insert_with(|| Symbol::from_ident(ident))
506     }
507
508     fn lower_opt_sp_ident(&mut self, o_id: Option<Spanned<Ident>>) -> Option<Spanned<Name>> {
509         o_id.map(|sp_ident| respan(sp_ident.span, sp_ident.node.name))
510     }
511
512     fn lower_loop_destination(&mut self, destination: Option<(NodeId, Spanned<Ident>)>)
513         -> hir::Destination
514     {
515         match destination {
516             Some((id, label_ident)) => {
517                 let target = if let Def::Label(loop_id) = self.expect_full_def(id) {
518                     hir::LoopIdResult::Ok(self.lower_node_id(loop_id))
519                 } else {
520                     hir::LoopIdResult::Err(hir::LoopIdError::UnresolvedLabel)
521                 };
522                 hir::Destination {
523                     ident: Some(label_ident),
524                     target_id: hir::ScopeTarget::Loop(target),
525                 }
526             },
527             None => {
528                 let loop_id = self.loop_scopes
529                                   .last()
530                                   .map(|innermost_loop_id| *innermost_loop_id);
531
532                 hir::Destination {
533                     ident: None,
534                     target_id: hir::ScopeTarget::Loop(
535                         loop_id.map(|id| Ok(self.lower_node_id(id)))
536                                .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
537                                .into())
538                 }
539             }
540         }
541     }
542
543     fn lower_attrs(&mut self, attrs: &Vec<Attribute>) -> hir::HirVec<Attribute> {
544         attrs.clone().into()
545     }
546
547     fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
548         hir::Arm {
549             attrs: self.lower_attrs(&arm.attrs),
550             pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
551             guard: arm.guard.as_ref().map(|ref x| P(self.lower_expr(x))),
552             body: P(self.lower_expr(&arm.body)),
553         }
554     }
555
556     fn lower_ty_binding(&mut self, b: &TypeBinding) -> hir::TypeBinding {
557         hir::TypeBinding {
558             id: self.lower_node_id(b.id),
559             name: self.lower_ident(b.ident),
560             ty: self.lower_ty(&b.ty),
561             span: b.span,
562         }
563     }
564
565     fn lower_ty(&mut self, t: &Ty) -> P<hir::Ty> {
566         let kind = match t.node {
567             TyKind::Infer => hir::TyInfer,
568             TyKind::Err => hir::TyErr,
569             TyKind::Slice(ref ty) => hir::TySlice(self.lower_ty(ty)),
570             TyKind::Ptr(ref mt) => hir::TyPtr(self.lower_mt(mt)),
571             TyKind::Rptr(ref region, ref mt) => {
572                 let span = Span { hi: t.span.lo, ..t.span };
573                 let lifetime = match *region {
574                     Some(ref lt) => self.lower_lifetime(lt),
575                     None => self.elided_lifetime(span)
576                 };
577                 hir::TyRptr(lifetime, self.lower_mt(mt))
578             }
579             TyKind::BareFn(ref f) => {
580                 hir::TyBareFn(P(hir::BareFnTy {
581                     lifetimes: self.lower_lifetime_defs(&f.lifetimes),
582                     unsafety: self.lower_unsafety(f.unsafety),
583                     abi: f.abi,
584                     decl: self.lower_fn_decl(&f.decl),
585                 }))
586             }
587             TyKind::Never => hir::TyNever,
588             TyKind::Tup(ref tys) => {
589                 hir::TyTup(tys.iter().map(|ty| self.lower_ty(ty)).collect())
590             }
591             TyKind::Paren(ref ty) => {
592                 return self.lower_ty(ty);
593             }
594             TyKind::Path(ref qself, ref path) => {
595                 let id = self.lower_node_id(t.id);
596                 let qpath = self.lower_qpath(t.id, qself, path, ParamMode::Explicit);
597                 return self.ty_path(id, t.span, qpath);
598             }
599             TyKind::ImplicitSelf => {
600                 hir::TyPath(hir::QPath::Resolved(None, P(hir::Path {
601                     def: self.expect_full_def(t.id),
602                     segments: hir_vec![hir::PathSegment {
603                         name: keywords::SelfType.name(),
604                         parameters: hir::PathParameters::none()
605                     }],
606                     span: t.span,
607                 })))
608             }
609             TyKind::Array(ref ty, ref length) => {
610                 let length = self.lower_expr(length);
611                 hir::TyArray(self.lower_ty(ty),
612                              self.record_body(length, None))
613             }
614             TyKind::Typeof(ref expr) => {
615                 let expr = self.lower_expr(expr);
616                 hir::TyTypeof(self.record_body(expr, None))
617             }
618             TyKind::TraitObject(ref bounds) => {
619                 let mut lifetime_bound = None;
620                 let bounds = bounds.iter().filter_map(|bound| {
621                     match *bound {
622                         TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
623                             Some(self.lower_poly_trait_ref(ty))
624                         }
625                         TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
626                         RegionTyParamBound(ref lifetime) => {
627                             if lifetime_bound.is_none() {
628                                 lifetime_bound = Some(self.lower_lifetime(lifetime));
629                             }
630                             None
631                         }
632                     }
633                 }).collect();
634                 let lifetime_bound = lifetime_bound.unwrap_or_else(|| {
635                     self.elided_lifetime(t.span)
636                 });
637                 hir::TyTraitObject(bounds, lifetime_bound)
638             }
639             TyKind::ImplTrait(ref bounds) => {
640                 hir::TyImplTrait(self.lower_bounds(bounds))
641             }
642             TyKind::Mac(_) => panic!("TyMac should have been expanded by now."),
643         };
644
645         P(hir::Ty {
646             id: self.lower_node_id(t.id),
647             node: kind,
648             span: t.span,
649         })
650     }
651
652     fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
653         hir::ForeignMod {
654             abi: fm.abi,
655             items: fm.items.iter().map(|x| self.lower_foreign_item(x)).collect(),
656         }
657     }
658
659     fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
660         P(hir::GlobalAsm {
661             asm: ga.asm,
662             ctxt: ga.ctxt,
663         })
664     }
665
666     fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
667         Spanned {
668             node: hir::Variant_ {
669                 name: v.node.name.name,
670                 attrs: self.lower_attrs(&v.node.attrs),
671                 data: self.lower_variant_data(&v.node.data),
672                 disr_expr: v.node.disr_expr.as_ref().map(|e| {
673                     let e = self.lower_expr(e);
674                     self.record_body(e, None)
675                 }),
676             },
677             span: v.span,
678         }
679     }
680
681     fn lower_qpath(&mut self,
682                    id: NodeId,
683                    qself: &Option<QSelf>,
684                    p: &Path,
685                    param_mode: ParamMode)
686                    -> hir::QPath {
687         let qself_position = qself.as_ref().map(|q| q.position);
688         let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty));
689
690         let resolution = self.resolver.get_resolution(id)
691                                       .unwrap_or(PathResolution::new(Def::Err));
692
693         let proj_start = p.segments.len() - resolution.unresolved_segments();
694         let path = P(hir::Path {
695             def: resolution.base_def(),
696             segments: p.segments[..proj_start].iter().enumerate().map(|(i, segment)| {
697                 let param_mode = match (qself_position, param_mode) {
698                     (Some(j), ParamMode::Optional) if i < j => {
699                         // This segment is part of the trait path in a
700                         // qualified path - one of `a`, `b` or `Trait`
701                         // in `<X as a::b::Trait>::T::U::method`.
702                         ParamMode::Explicit
703                     }
704                     _ => param_mode
705                 };
706
707                 // Figure out if this is a type/trait segment,
708                 // which may need lifetime elision performed.
709                 let parent_def_id = |this: &mut Self, def_id: DefId| {
710                     DefId {
711                         krate: def_id.krate,
712                         index: this.def_key(def_id).parent.expect("missing parent")
713                     }
714                 };
715                 let type_def_id = match resolution.base_def() {
716                     Def::AssociatedTy(def_id) if i + 2 == proj_start => {
717                         Some(parent_def_id(self, def_id))
718                     }
719                     Def::Variant(def_id) if i + 1 == proj_start => {
720                         Some(parent_def_id(self, def_id))
721                     }
722                     Def::Struct(def_id) |
723                     Def::Union(def_id) |
724                     Def::Enum(def_id) |
725                     Def::TyAlias(def_id) |
726                     Def::Trait(def_id) if i + 1 == proj_start => Some(def_id),
727                     _ => None
728                 };
729
730                 let num_lifetimes = type_def_id.map_or(0, |def_id| {
731                     if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
732                         return n;
733                     }
734                     assert!(!def_id.is_local());
735                     let n = self.sess.cstore.item_generics_cloned(def_id).regions.len();
736                     self.type_def_lifetime_params.insert(def_id, n);
737                     n
738                 });
739                 self.lower_path_segment(p.span, segment, param_mode, num_lifetimes)
740             }).collect(),
741             span: p.span,
742         });
743
744         // Simple case, either no projections, or only fully-qualified.
745         // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
746         if resolution.unresolved_segments() == 0 {
747             return hir::QPath::Resolved(qself, path);
748         }
749
750         // Create the innermost type that we're projecting from.
751         let mut ty = if path.segments.is_empty() {
752             // If the base path is empty that means there exists a
753             // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
754             qself.expect("missing QSelf for <T>::...")
755         } else {
756             // Otherwise, the base path is an implicit `Self` type path,
757             // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
758             // `<I as Iterator>::Item::default`.
759             let new_id = self.next_id();
760             self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))
761         };
762
763         // Anything after the base path are associated "extensions",
764         // out of which all but the last one are associated types,
765         // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
766         // * base path is `std::vec::Vec<T>`
767         // * "extensions" are `IntoIter`, `Item` and `clone`
768         // * type nodes are:
769         //   1. `std::vec::Vec<T>` (created above)
770         //   2. `<std::vec::Vec<T>>::IntoIter`
771         //   3. `<<std::vec::Vec<T>>::IntoIter>::Item`
772         // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
773         for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
774             let segment = P(self.lower_path_segment(p.span, segment, param_mode, 0));
775             let qpath = hir::QPath::TypeRelative(ty, segment);
776
777             // It's finished, return the extension of the right node type.
778             if i == p.segments.len() - 1 {
779                 return qpath;
780             }
781
782             // Wrap the associated extension in another type node.
783             let new_id = self.next_id();
784             ty = self.ty_path(new_id, p.span, qpath);
785         }
786
787         // Should've returned in the for loop above.
788         span_bug!(p.span, "lower_qpath: no final extension segment in {}..{}",
789                   proj_start, p.segments.len())
790     }
791
792     fn lower_path_extra(&mut self,
793                         id: NodeId,
794                         p: &Path,
795                         name: Option<Name>,
796                         param_mode: ParamMode,
797                         defaults_to_global: bool)
798                         -> hir::Path {
799         let mut segments = p.segments.iter();
800         if defaults_to_global && p.is_global() {
801             segments.next();
802         }
803
804         hir::Path {
805             def: self.expect_full_def(id),
806             segments: segments.map(|segment| {
807                 self.lower_path_segment(p.span, segment, param_mode, 0)
808             }).chain(name.map(|name| {
809                 hir::PathSegment {
810                     name: name,
811                     parameters: hir::PathParameters::none()
812                 }
813             })).collect(),
814             span: p.span,
815         }
816     }
817
818     fn lower_path(&mut self,
819                   id: NodeId,
820                   p: &Path,
821                   param_mode: ParamMode,
822                   defaults_to_global: bool)
823                   -> hir::Path {
824         self.lower_path_extra(id, p, None, param_mode, defaults_to_global)
825     }
826
827     fn lower_path_segment(&mut self,
828                           path_span: Span,
829                           segment: &PathSegment,
830                           param_mode: ParamMode,
831                           expected_lifetimes: usize)
832                           -> hir::PathSegment {
833         let mut parameters = if let Some(ref parameters) = segment.parameters {
834             match **parameters {
835                 PathParameters::AngleBracketed(ref data) => {
836                     let data = self.lower_angle_bracketed_parameter_data(data, param_mode);
837                     hir::AngleBracketedParameters(data)
838                 }
839                 PathParameters::Parenthesized(ref data) => {
840                     hir::ParenthesizedParameters(self.lower_parenthesized_parameter_data(data))
841                 }
842             }
843         } else {
844             let data = self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode);
845             hir::AngleBracketedParameters(data)
846         };
847
848         if let hir::AngleBracketedParameters(ref mut data) = parameters {
849             if data.lifetimes.is_empty() {
850                 data.lifetimes = (0..expected_lifetimes).map(|_| {
851                     self.elided_lifetime(path_span)
852                 }).collect();
853             }
854         }
855
856         hir::PathSegment {
857             name: self.lower_ident(segment.identifier),
858             parameters: parameters,
859         }
860     }
861
862     fn lower_angle_bracketed_parameter_data(&mut self,
863                                             data: &AngleBracketedParameterData,
864                                             param_mode: ParamMode)
865                                             -> hir::AngleBracketedParameterData {
866         let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
867         hir::AngleBracketedParameterData {
868             lifetimes: self.lower_lifetimes(lifetimes),
869             types: types.iter().map(|ty| self.lower_ty(ty)).collect(),
870             infer_types: types.is_empty() && param_mode == ParamMode::Optional,
871             bindings: bindings.iter().map(|b| self.lower_ty_binding(b)).collect(),
872         }
873     }
874
875     fn lower_parenthesized_parameter_data(&mut self,
876                                           data: &ParenthesizedParameterData)
877                                           -> hir::ParenthesizedParameterData {
878         let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
879         hir::ParenthesizedParameterData {
880             inputs: inputs.iter().map(|ty| self.lower_ty(ty)).collect(),
881             output: output.as_ref().map(|ty| self.lower_ty(ty)),
882             span: span,
883         }
884     }
885
886     fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
887         P(hir::Local {
888             id: self.lower_node_id(l.id),
889             ty: l.ty.as_ref().map(|t| self.lower_ty(t)),
890             pat: self.lower_pat(&l.pat),
891             init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
892             span: l.span,
893             attrs: l.attrs.clone(),
894         })
895     }
896
897     fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
898         match m {
899             Mutability::Mutable => hir::MutMutable,
900             Mutability::Immutable => hir::MutImmutable,
901         }
902     }
903
904     fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
905         hir::Arg {
906             id: self.lower_node_id(arg.id),
907             pat: self.lower_pat(&arg.pat),
908         }
909     }
910
911     fn lower_fn_args_to_names(&mut self, decl: &FnDecl)
912                               -> hir::HirVec<Spanned<Name>> {
913         decl.inputs.iter().map(|arg| {
914             match arg.pat.node {
915                 PatKind::Ident(_, ident, None) => {
916                     respan(ident.span, ident.node.name)
917                 }
918                 _ => respan(arg.pat.span, keywords::Invalid.name()),
919             }
920         }).collect()
921     }
922
923     fn lower_fn_decl(&mut self, decl: &FnDecl) -> P<hir::FnDecl> {
924         P(hir::FnDecl {
925             inputs: decl.inputs.iter().map(|arg| self.lower_ty(&arg.ty)).collect(),
926             output: match decl.output {
927                 FunctionRetTy::Ty(ref ty) => hir::Return(self.lower_ty(ty)),
928                 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
929             },
930             variadic: decl.variadic,
931             has_implicit_self: decl.inputs.get(0).map_or(false, |arg| {
932                 match arg.ty.node {
933                     TyKind::ImplicitSelf => true,
934                     TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
935                     _ => false
936                 }
937             })
938         })
939     }
940
941     fn lower_ty_param_bound(&mut self, tpb: &TyParamBound) -> hir::TyParamBound {
942         match *tpb {
943             TraitTyParamBound(ref ty, modifier) => {
944                 hir::TraitTyParamBound(self.lower_poly_trait_ref(ty),
945                                        self.lower_trait_bound_modifier(modifier))
946             }
947             RegionTyParamBound(ref lifetime) => {
948                 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
949             }
950         }
951     }
952
953     fn lower_ty_param(&mut self, tp: &TyParam, add_bounds: &[TyParamBound]) -> hir::TyParam {
954         let mut name = self.lower_ident(tp.ident);
955
956         // Don't expose `Self` (recovered "keyword used as ident" parse error).
957         // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
958         // Instead, use gensym("Self") to create a distinct name that looks the same.
959         if name == keywords::SelfType.name() {
960             name = Symbol::gensym("Self");
961         }
962
963         let mut bounds = self.lower_bounds(&tp.bounds);
964         if !add_bounds.is_empty() {
965             bounds = bounds.into_iter().chain(self.lower_bounds(add_bounds).into_iter()).collect();
966         }
967
968         hir::TyParam {
969             id: self.lower_node_id(tp.id),
970             name: name,
971             bounds: bounds,
972             default: tp.default.as_ref().map(|x| self.lower_ty(x)),
973             span: tp.span,
974             pure_wrt_drop: tp.attrs.iter().any(|attr| attr.check_name("may_dangle")),
975         }
976     }
977
978     fn lower_ty_params(&mut self, tps: &Vec<TyParam>, add_bounds: &NodeMap<Vec<TyParamBound>>)
979                        -> hir::HirVec<hir::TyParam> {
980         tps.iter().map(|tp| {
981             self.lower_ty_param(tp, add_bounds.get(&tp.id).map_or(&[][..], |x| &x))
982         }).collect()
983     }
984
985     fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
986         hir::Lifetime {
987             id: self.lower_node_id(l.id),
988             name: self.lower_ident(l.ident),
989             span: l.span,
990         }
991     }
992
993     fn lower_lifetime_def(&mut self, l: &LifetimeDef) -> hir::LifetimeDef {
994         hir::LifetimeDef {
995             lifetime: self.lower_lifetime(&l.lifetime),
996             bounds: self.lower_lifetimes(&l.bounds),
997             pure_wrt_drop: l.attrs.iter().any(|attr| attr.check_name("may_dangle")),
998         }
999     }
1000
1001     fn lower_lifetimes(&mut self, lts: &Vec<Lifetime>) -> hir::HirVec<hir::Lifetime> {
1002         lts.iter().map(|l| self.lower_lifetime(l)).collect()
1003     }
1004
1005     fn lower_lifetime_defs(&mut self, lts: &Vec<LifetimeDef>) -> hir::HirVec<hir::LifetimeDef> {
1006         lts.iter().map(|l| self.lower_lifetime_def(l)).collect()
1007     }
1008
1009     fn lower_generics(&mut self, g: &Generics) -> hir::Generics {
1010         // Collect `?Trait` bounds in where clause and move them to parameter definitions.
1011         let mut add_bounds = NodeMap();
1012         for pred in &g.where_clause.predicates {
1013             if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
1014                 'next_bound: for bound in &bound_pred.bounds {
1015                     if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
1016                         let report_error = |this: &mut Self| {
1017                             this.diagnostic().span_err(bound_pred.bounded_ty.span,
1018                                                        "`?Trait` bounds are only permitted at the \
1019                                                         point where a type parameter is declared");
1020                         };
1021                         // Check if the where clause type is a plain type parameter.
1022                         match bound_pred.bounded_ty.node {
1023                             TyKind::Path(None, ref path)
1024                                     if path.segments.len() == 1 &&
1025                                        bound_pred.bound_lifetimes.is_empty() => {
1026                                 if let Some(Def::TyParam(def_id)) =
1027                                         self.resolver.get_resolution(bound_pred.bounded_ty.id)
1028                                                      .map(|d| d.base_def()) {
1029                                     if let Some(node_id) =
1030                                             self.resolver.definitions().as_local_node_id(def_id) {
1031                                         for ty_param in &g.ty_params {
1032                                             if node_id == ty_param.id {
1033                                                 add_bounds.entry(ty_param.id).or_insert(Vec::new())
1034                                                                             .push(bound.clone());
1035                                                 continue 'next_bound;
1036                                             }
1037                                         }
1038                                     }
1039                                 }
1040                                 report_error(self)
1041                             }
1042                             _ => report_error(self)
1043                         }
1044                     }
1045                 }
1046             }
1047         }
1048
1049         hir::Generics {
1050             ty_params: self.lower_ty_params(&g.ty_params, &add_bounds),
1051             lifetimes: self.lower_lifetime_defs(&g.lifetimes),
1052             where_clause: self.lower_where_clause(&g.where_clause),
1053             span: g.span,
1054         }
1055     }
1056
1057     fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
1058         hir::WhereClause {
1059             id: self.lower_node_id(wc.id),
1060             predicates: wc.predicates
1061                           .iter()
1062                           .map(|predicate| self.lower_where_predicate(predicate))
1063                           .collect(),
1064         }
1065     }
1066
1067     fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
1068         match *pred {
1069             WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
1070                                                                 ref bounded_ty,
1071                                                                 ref bounds,
1072                                                                 span}) => {
1073                 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1074                     bound_lifetimes: self.lower_lifetime_defs(bound_lifetimes),
1075                     bounded_ty: self.lower_ty(bounded_ty),
1076                     bounds: bounds.iter().filter_map(|bound| match *bound {
1077                         // Ignore `?Trait` bounds, they were copied into type parameters already.
1078                         TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
1079                         _ => Some(self.lower_ty_param_bound(bound))
1080                     }).collect(),
1081                     span: span,
1082                 })
1083             }
1084             WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
1085                                                                   ref bounds,
1086                                                                   span}) => {
1087                 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1088                     span: span,
1089                     lifetime: self.lower_lifetime(lifetime),
1090                     bounds: bounds.iter().map(|bound| self.lower_lifetime(bound)).collect(),
1091                 })
1092             }
1093             WherePredicate::EqPredicate(WhereEqPredicate{ id,
1094                                                           ref lhs_ty,
1095                                                           ref rhs_ty,
1096                                                           span}) => {
1097                 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1098                     id: self.lower_node_id(id),
1099                     lhs_ty: self.lower_ty(lhs_ty),
1100                     rhs_ty: self.lower_ty(rhs_ty),
1101                     span: span,
1102                 })
1103             }
1104         }
1105     }
1106
1107     fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
1108         match *vdata {
1109             VariantData::Struct(ref fields, id) => {
1110                 hir::VariantData::Struct(fields.iter()
1111                                                .enumerate()
1112                                                .map(|f| self.lower_struct_field(f))
1113                                                .collect(),
1114                                          self.lower_node_id(id))
1115             }
1116             VariantData::Tuple(ref fields, id) => {
1117                 hir::VariantData::Tuple(fields.iter()
1118                                               .enumerate()
1119                                               .map(|f| self.lower_struct_field(f))
1120                                               .collect(),
1121                                         self.lower_node_id(id))
1122             }
1123             VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id)),
1124         }
1125     }
1126
1127     fn lower_trait_ref(&mut self, p: &TraitRef) -> hir::TraitRef {
1128         let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit) {
1129             hir::QPath::Resolved(None, path) => path.and_then(|path| path),
1130             qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath)
1131         };
1132         hir::TraitRef {
1133             path: path,
1134             ref_id: self.lower_node_id(p.ref_id),
1135         }
1136     }
1137
1138     fn lower_poly_trait_ref(&mut self, p: &PolyTraitRef) -> hir::PolyTraitRef {
1139         hir::PolyTraitRef {
1140             bound_lifetimes: self.lower_lifetime_defs(&p.bound_lifetimes),
1141             trait_ref: self.lower_trait_ref(&p.trait_ref),
1142             span: p.span,
1143         }
1144     }
1145
1146     fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
1147         hir::StructField {
1148             span: f.span,
1149             id: self.lower_node_id(f.id),
1150             name: self.lower_ident(match f.ident {
1151                 Some(ident) => ident,
1152                 // FIXME(jseyfried) positional field hygiene
1153                 None => Ident { name: Symbol::intern(&index.to_string()), ctxt: f.span.ctxt },
1154             }),
1155             vis: self.lower_visibility(&f.vis, None),
1156             ty: self.lower_ty(&f.ty),
1157             attrs: self.lower_attrs(&f.attrs),
1158         }
1159     }
1160
1161     fn lower_field(&mut self, f: &Field) -> hir::Field {
1162         hir::Field {
1163             name: respan(f.ident.span, self.lower_ident(f.ident.node)),
1164             expr: P(self.lower_expr(&f.expr)),
1165             span: f.span,
1166             is_shorthand: f.is_shorthand,
1167         }
1168     }
1169
1170     fn lower_mt(&mut self, mt: &MutTy) -> hir::MutTy {
1171         hir::MutTy {
1172             ty: self.lower_ty(&mt.ty),
1173             mutbl: self.lower_mutability(mt.mutbl),
1174         }
1175     }
1176
1177     fn lower_bounds(&mut self, bounds: &[TyParamBound]) -> hir::TyParamBounds {
1178         bounds.iter().map(|bound| self.lower_ty_param_bound(bound)).collect()
1179     }
1180
1181     fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
1182         let mut expr = None;
1183
1184         let mut stmts = vec![];
1185
1186         for (index, stmt) in b.stmts.iter().enumerate() {
1187             if index == b.stmts.len() - 1 {
1188                 if let StmtKind::Expr(ref e) = stmt.node {
1189                     expr = Some(P(self.lower_expr(e)));
1190                 } else {
1191                     stmts.extend(self.lower_stmt(stmt));
1192                 }
1193             } else {
1194                 stmts.extend(self.lower_stmt(stmt));
1195             }
1196         }
1197
1198         P(hir::Block {
1199             id: self.lower_node_id(b.id),
1200             stmts: stmts.into(),
1201             expr: expr,
1202             rules: self.lower_block_check_mode(&b.rules),
1203             span: b.span,
1204             targeted_by_break: targeted_by_break,
1205         })
1206     }
1207
1208     fn lower_item_kind(&mut self,
1209                        id: NodeId,
1210                        name: &mut Name,
1211                        attrs: &hir::HirVec<Attribute>,
1212                        vis: &mut hir::Visibility,
1213                        i: &ItemKind)
1214                        -> hir::Item_ {
1215         match *i {
1216             ItemKind::ExternCrate(string) => hir::ItemExternCrate(string),
1217             ItemKind::Use(ref view_path) => {
1218                 let path = match view_path.node {
1219                     ViewPathSimple(_, ref path) => path,
1220                     ViewPathGlob(ref path) => path,
1221                     ViewPathList(ref path, ref path_list_idents) => {
1222                         for &Spanned { node: ref import, span } in path_list_idents {
1223                             // `use a::{self as x, b as y};` lowers to
1224                             // `use a as x; use a::b as y;`
1225                             let mut ident = import.name;
1226                             let suffix = if ident.name == keywords::SelfValue.name() {
1227                                 if let Some(last) = path.segments.last() {
1228                                     ident = last.identifier;
1229                                 }
1230                                 None
1231                             } else {
1232                                 Some(ident.name)
1233                             };
1234
1235                             let mut path = self.lower_path_extra(import.id, path, suffix,
1236                                                                  ParamMode::Explicit, true);
1237                             path.span = span;
1238
1239                             self.allocate_hir_id_counter(import.id, import);
1240                             self.with_hir_id_owner(import.id, |this| {
1241                                 let vis = match *vis {
1242                                     hir::Visibility::Public => hir::Visibility::Public,
1243                                     hir::Visibility::Crate => hir::Visibility::Crate,
1244                                     hir::Visibility::Inherited => hir::Visibility::Inherited,
1245                                     hir::Visibility::Restricted { ref path, id: _ } => {
1246                                         hir::Visibility::Restricted {
1247                                             path: path.clone(),
1248                                             // We are allocating a new NodeId here
1249                                             id: this.next_id(),
1250                                         }
1251                                     }
1252                                 };
1253
1254                                 this.items.insert(import.id, hir::Item {
1255                                     id: import.id,
1256                                     name: import.rename.unwrap_or(ident).name,
1257                                     attrs: attrs.clone(),
1258                                     node: hir::ItemUse(P(path), hir::UseKind::Single),
1259                                     vis: vis,
1260                                     span: span,
1261                                 });
1262                             });
1263                         }
1264                         path
1265                     }
1266                 };
1267                 let path = P(self.lower_path(id, path, ParamMode::Explicit, true));
1268                 let kind = match view_path.node {
1269                     ViewPathSimple(ident, _) => {
1270                         *name = ident.name;
1271                         hir::UseKind::Single
1272                     }
1273                     ViewPathGlob(_) => {
1274                         hir::UseKind::Glob
1275                     }
1276                     ViewPathList(..) => {
1277                         // Privatize the degenerate import base, used only to check
1278                         // the stability of `use a::{};`, to avoid it showing up as
1279                         // a reexport by accident when `pub`, e.g. in documentation.
1280                         *vis = hir::Inherited;
1281                         hir::UseKind::ListStem
1282                     }
1283                 };
1284                 hir::ItemUse(path, kind)
1285             }
1286             ItemKind::Static(ref t, m, ref e) => {
1287                 let value = self.lower_expr(e);
1288                 hir::ItemStatic(self.lower_ty(t),
1289                                 self.lower_mutability(m),
1290                                 self.record_body(value, None))
1291             }
1292             ItemKind::Const(ref t, ref e) => {
1293                 let value = self.lower_expr(e);
1294                 hir::ItemConst(self.lower_ty(t),
1295                                self.record_body(value, None))
1296             }
1297             ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
1298                 self.with_new_scopes(|this| {
1299                     let body = this.lower_block(body, false);
1300                     let body = this.expr_block(body, ThinVec::new());
1301                     let body_id = this.record_body(body, Some(decl));
1302                     hir::ItemFn(this.lower_fn_decl(decl),
1303                                               this.lower_unsafety(unsafety),
1304                                               this.lower_constness(constness),
1305                                               abi,
1306                                               this.lower_generics(generics),
1307                                               body_id)
1308                 })
1309             }
1310             ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
1311             ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
1312             ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
1313             ItemKind::Ty(ref t, ref generics) => {
1314                 hir::ItemTy(self.lower_ty(t), self.lower_generics(generics))
1315             }
1316             ItemKind::Enum(ref enum_definition, ref generics) => {
1317                 hir::ItemEnum(hir::EnumDef {
1318                                   variants: enum_definition.variants
1319                                                            .iter()
1320                                                            .map(|x| self.lower_variant(x))
1321                                                            .collect(),
1322                               },
1323                               self.lower_generics(generics))
1324             }
1325             ItemKind::Struct(ref struct_def, ref generics) => {
1326                 let struct_def = self.lower_variant_data(struct_def);
1327                 hir::ItemStruct(struct_def, self.lower_generics(generics))
1328             }
1329             ItemKind::Union(ref vdata, ref generics) => {
1330                 let vdata = self.lower_variant_data(vdata);
1331                 hir::ItemUnion(vdata, self.lower_generics(generics))
1332             }
1333             ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1334                 let trait_ref = self.lower_trait_ref(trait_ref);
1335
1336                 if let Def::Trait(def_id) = trait_ref.path.def {
1337                     self.trait_default_impl.insert(def_id, id);
1338                 }
1339
1340                 hir::ItemDefaultImpl(self.lower_unsafety(unsafety),
1341                                      trait_ref)
1342             }
1343             ItemKind::Impl(unsafety,
1344                            polarity,
1345                            defaultness,
1346                            ref generics,
1347                            ref ifce,
1348                            ref ty,
1349                            ref impl_items) => {
1350                 let new_impl_items = impl_items.iter()
1351                                                .map(|item| self.lower_impl_item_ref(item))
1352                                                .collect();
1353                 let ifce = ifce.as_ref().map(|trait_ref| self.lower_trait_ref(trait_ref));
1354
1355                 if let Some(ref trait_ref) = ifce {
1356                     if let Def::Trait(def_id) = trait_ref.path.def {
1357                         self.trait_impls.entry(def_id).or_insert(vec![]).push(id);
1358                     }
1359                 }
1360
1361                 hir::ItemImpl(self.lower_unsafety(unsafety),
1362                               self.lower_impl_polarity(polarity),
1363                               self.lower_defaultness(defaultness, true /* [1] */),
1364                               self.lower_generics(generics),
1365                               ifce,
1366                               self.lower_ty(ty),
1367                               new_impl_items)
1368             }
1369             ItemKind::Trait(unsafety, ref generics, ref bounds, ref items) => {
1370                 let bounds = self.lower_bounds(bounds);
1371                 let items = items.iter().map(|item| self.lower_trait_item_ref(item)).collect();
1372                 hir::ItemTrait(self.lower_unsafety(unsafety),
1373                                self.lower_generics(generics),
1374                                bounds,
1375                                items)
1376             }
1377             ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
1378         }
1379
1380         // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
1381         //     not cause an assertion failure inside the `lower_defaultness` function
1382     }
1383
1384     fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
1385         self.with_parent_def(i.id, |this| {
1386             hir::TraitItem {
1387                 id: this.lower_node_id(i.id),
1388                 name: this.lower_ident(i.ident),
1389                 attrs: this.lower_attrs(&i.attrs),
1390                 node: match i.node {
1391                     TraitItemKind::Const(ref ty, ref default) => {
1392                         hir::TraitItemKind::Const(this.lower_ty(ty),
1393                                                   default.as_ref().map(|x| {
1394                             let value = this.lower_expr(x);
1395                             this.record_body(value, None)
1396                         }))
1397                     }
1398                     TraitItemKind::Method(ref sig, None) => {
1399                         let names = this.lower_fn_args_to_names(&sig.decl);
1400                         hir::TraitItemKind::Method(this.lower_method_sig(sig),
1401                                                    hir::TraitMethod::Required(names))
1402                     }
1403                     TraitItemKind::Method(ref sig, Some(ref body)) => {
1404                         let body = this.lower_block(body, false);
1405                         let expr = this.expr_block(body, ThinVec::new());
1406                         let body_id = this.record_body(expr, Some(&sig.decl));
1407                         hir::TraitItemKind::Method(this.lower_method_sig(sig),
1408                                                    hir::TraitMethod::Provided(body_id))
1409                     }
1410                     TraitItemKind::Type(ref bounds, ref default) => {
1411                         hir::TraitItemKind::Type(this.lower_bounds(bounds),
1412                                                  default.as_ref().map(|x| this.lower_ty(x)))
1413                     }
1414                     TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
1415                 },
1416                 span: i.span,
1417             }
1418         })
1419     }
1420
1421     fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
1422         let (kind, has_default) = match i.node {
1423             TraitItemKind::Const(_, ref default) => {
1424                 (hir::AssociatedItemKind::Const, default.is_some())
1425             }
1426             TraitItemKind::Type(_, ref default) => {
1427                 (hir::AssociatedItemKind::Type, default.is_some())
1428             }
1429             TraitItemKind::Method(ref sig, ref default) => {
1430                 (hir::AssociatedItemKind::Method {
1431                     has_self: sig.decl.has_self(),
1432                  }, default.is_some())
1433             }
1434             TraitItemKind::Macro(..) => unimplemented!(),
1435         };
1436         hir::TraitItemRef {
1437             id: hir::TraitItemId { node_id: i.id },
1438             name: self.lower_ident(i.ident),
1439             span: i.span,
1440             defaultness: self.lower_defaultness(Defaultness::Default, has_default),
1441             kind: kind,
1442         }
1443     }
1444
1445     fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
1446         self.with_parent_def(i.id, |this| {
1447             hir::ImplItem {
1448                 id: this.lower_node_id(i.id),
1449                 name: this.lower_ident(i.ident),
1450                 attrs: this.lower_attrs(&i.attrs),
1451                 vis: this.lower_visibility(&i.vis, None),
1452                 defaultness: this.lower_defaultness(i.defaultness, true /* [1] */),
1453                 node: match i.node {
1454                     ImplItemKind::Const(ref ty, ref expr) => {
1455                         let value = this.lower_expr(expr);
1456                         let body_id = this.record_body(value, None);
1457                         hir::ImplItemKind::Const(this.lower_ty(ty), body_id)
1458                     }
1459                     ImplItemKind::Method(ref sig, ref body) => {
1460                         let body = this.lower_block(body, false);
1461                         let expr = this.expr_block(body, ThinVec::new());
1462                         let body_id = this.record_body(expr, Some(&sig.decl));
1463                         hir::ImplItemKind::Method(this.lower_method_sig(sig), body_id)
1464                     }
1465                     ImplItemKind::Type(ref ty) => hir::ImplItemKind::Type(this.lower_ty(ty)),
1466                     ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
1467                 },
1468                 span: i.span,
1469             }
1470         })
1471
1472         // [1] since `default impl` is not yet implemented, this is always true in impls
1473     }
1474
1475     fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
1476         hir::ImplItemRef {
1477             id: hir::ImplItemId { node_id: i.id },
1478             name: self.lower_ident(i.ident),
1479             span: i.span,
1480             vis: self.lower_visibility(&i.vis, Some(i.id)),
1481             defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
1482             kind: match i.node {
1483                 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
1484                 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
1485                 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
1486                     has_self: sig.decl.has_self(),
1487                 },
1488                 ImplItemKind::Macro(..) => unimplemented!(),
1489             },
1490         }
1491
1492         // [1] since `default impl` is not yet implemented, this is always true in impls
1493     }
1494
1495     fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
1496         hir::Mod {
1497             inner: m.inner,
1498             item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
1499         }
1500     }
1501
1502     fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
1503         match i.node {
1504             ItemKind::Use(ref view_path) => {
1505                 if let ViewPathList(_, ref imports) = view_path.node {
1506                     return iter::once(i.id).chain(imports.iter().map(|import| import.node.id))
1507                         .map(|id| hir::ItemId { id: id }).collect();
1508                 }
1509             }
1510             ItemKind::MacroDef(..) => return SmallVector::new(),
1511             _ => {}
1512         }
1513         SmallVector::one(hir::ItemId { id: i.id })
1514     }
1515
1516     pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
1517         let mut name = i.ident.name;
1518         let mut vis = self.lower_visibility(&i.vis, None);
1519         let attrs = self.lower_attrs(&i.attrs);
1520         if let ItemKind::MacroDef(ref def) = i.node {
1521             if !def.legacy || i.attrs.iter().any(|attr| attr.path == "macro_export") {
1522                 self.exported_macros.push(hir::MacroDef {
1523                     name: name,
1524                     vis: vis,
1525                     attrs: attrs,
1526                     id: i.id,
1527                     span: i.span,
1528                     body: def.stream(),
1529                     legacy: def.legacy,
1530                 });
1531             }
1532             return None;
1533         }
1534
1535         let node = self.with_parent_def(i.id, |this| {
1536             this.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node)
1537         });
1538
1539         Some(hir::Item {
1540             id: self.lower_node_id(i.id),
1541             name: name,
1542             attrs: attrs,
1543             node: node,
1544             vis: vis,
1545             span: i.span,
1546         })
1547     }
1548
1549     fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
1550         self.with_parent_def(i.id, |this| {
1551             hir::ForeignItem {
1552                 id: this.lower_node_id(i.id),
1553                 name: i.ident.name,
1554                 attrs: this.lower_attrs(&i.attrs),
1555                 node: match i.node {
1556                     ForeignItemKind::Fn(ref fdec, ref generics) => {
1557                         hir::ForeignItemFn(this.lower_fn_decl(fdec),
1558                                            this.lower_fn_args_to_names(fdec),
1559                                            this.lower_generics(generics))
1560                     }
1561                     ForeignItemKind::Static(ref t, m) => {
1562                         hir::ForeignItemStatic(this.lower_ty(t), m)
1563                     }
1564                 },
1565                 vis: this.lower_visibility(&i.vis, None),
1566                 span: i.span,
1567             }
1568         })
1569     }
1570
1571     fn lower_method_sig(&mut self, sig: &MethodSig) -> hir::MethodSig {
1572         hir::MethodSig {
1573             generics: self.lower_generics(&sig.generics),
1574             abi: sig.abi,
1575             unsafety: self.lower_unsafety(sig.unsafety),
1576             constness: self.lower_constness(sig.constness),
1577             decl: self.lower_fn_decl(&sig.decl),
1578         }
1579     }
1580
1581     fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
1582         match u {
1583             Unsafety::Unsafe => hir::Unsafety::Unsafe,
1584             Unsafety::Normal => hir::Unsafety::Normal,
1585         }
1586     }
1587
1588     fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
1589         match c.node {
1590             Constness::Const => hir::Constness::Const,
1591             Constness::NotConst => hir::Constness::NotConst,
1592         }
1593     }
1594
1595     fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
1596         match u {
1597             UnOp::Deref => hir::UnDeref,
1598             UnOp::Not => hir::UnNot,
1599             UnOp::Neg => hir::UnNeg,
1600         }
1601     }
1602
1603     fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
1604         Spanned {
1605             node: match b.node {
1606                 BinOpKind::Add => hir::BiAdd,
1607                 BinOpKind::Sub => hir::BiSub,
1608                 BinOpKind::Mul => hir::BiMul,
1609                 BinOpKind::Div => hir::BiDiv,
1610                 BinOpKind::Rem => hir::BiRem,
1611                 BinOpKind::And => hir::BiAnd,
1612                 BinOpKind::Or => hir::BiOr,
1613                 BinOpKind::BitXor => hir::BiBitXor,
1614                 BinOpKind::BitAnd => hir::BiBitAnd,
1615                 BinOpKind::BitOr => hir::BiBitOr,
1616                 BinOpKind::Shl => hir::BiShl,
1617                 BinOpKind::Shr => hir::BiShr,
1618                 BinOpKind::Eq => hir::BiEq,
1619                 BinOpKind::Lt => hir::BiLt,
1620                 BinOpKind::Le => hir::BiLe,
1621                 BinOpKind::Ne => hir::BiNe,
1622                 BinOpKind::Ge => hir::BiGe,
1623                 BinOpKind::Gt => hir::BiGt,
1624             },
1625             span: b.span,
1626         }
1627     }
1628
1629     fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
1630         P(hir::Pat {
1631             id: self.lower_node_id(p.id),
1632             node: match p.node {
1633                 PatKind::Wild => hir::PatKind::Wild,
1634                 PatKind::Ident(ref binding_mode, pth1, ref sub) => {
1635                     self.with_parent_def(p.id, |this| {
1636                         match this.resolver.get_resolution(p.id).map(|d| d.base_def()) {
1637                             // `None` can occur in body-less function signatures
1638                             def @ None | def @ Some(Def::Local(_)) => {
1639                                 let def_id = def.map(|d| d.def_id()).unwrap_or_else(|| {
1640                                     this.resolver.definitions().local_def_id(p.id)
1641                                 });
1642                                 hir::PatKind::Binding(this.lower_binding_mode(binding_mode),
1643                                                       def_id,
1644                                                       respan(pth1.span, pth1.node.name),
1645                                                       sub.as_ref().map(|x| this.lower_pat(x)))
1646                             }
1647                             Some(def) => {
1648                                 hir::PatKind::Path(hir::QPath::Resolved(None, P(hir::Path {
1649                                     span: pth1.span,
1650                                     def: def,
1651                                     segments: hir_vec![
1652                                         hir::PathSegment::from_name(pth1.node.name)
1653                                     ],
1654                                 })))
1655                             }
1656                         }
1657                     })
1658                 }
1659                 PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
1660                 PatKind::TupleStruct(ref path, ref pats, ddpos) => {
1661                     let qpath = self.lower_qpath(p.id, &None, path, ParamMode::Optional);
1662                     hir::PatKind::TupleStruct(qpath,
1663                                               pats.iter().map(|x| self.lower_pat(x)).collect(),
1664                                               ddpos)
1665                 }
1666                 PatKind::Path(ref qself, ref path) => {
1667                     hir::PatKind::Path(self.lower_qpath(p.id, qself, path, ParamMode::Optional))
1668                 }
1669                 PatKind::Struct(ref path, ref fields, etc) => {
1670                     let qpath = self.lower_qpath(p.id, &None, path, ParamMode::Optional);
1671
1672                     let fs = fields.iter()
1673                                    .map(|f| {
1674                                        Spanned {
1675                                            span: f.span,
1676                                            node: hir::FieldPat {
1677                                                name: self.lower_ident(f.node.ident),
1678                                                pat: self.lower_pat(&f.node.pat),
1679                                                is_shorthand: f.node.is_shorthand,
1680                                            },
1681                                        }
1682                                    })
1683                                    .collect();
1684                     hir::PatKind::Struct(qpath, fs, etc)
1685                 }
1686                 PatKind::Tuple(ref elts, ddpos) => {
1687                     hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
1688                 }
1689                 PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
1690                 PatKind::Ref(ref inner, mutbl) => {
1691                     hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
1692                 }
1693                 PatKind::Range(ref e1, ref e2, ref end) => {
1694                     hir::PatKind::Range(P(self.lower_expr(e1)),
1695                                         P(self.lower_expr(e2)),
1696                                         self.lower_range_end(end))
1697                 }
1698                 PatKind::Slice(ref before, ref slice, ref after) => {
1699                     hir::PatKind::Slice(before.iter().map(|x| self.lower_pat(x)).collect(),
1700                                 slice.as_ref().map(|x| self.lower_pat(x)),
1701                                 after.iter().map(|x| self.lower_pat(x)).collect())
1702                 }
1703                 PatKind::Mac(_) => panic!("Shouldn't exist here"),
1704             },
1705             span: p.span,
1706         })
1707     }
1708
1709     fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
1710         match *e {
1711             RangeEnd::Included => hir::RangeEnd::Included,
1712             RangeEnd::Excluded => hir::RangeEnd::Excluded,
1713         }
1714     }
1715
1716     fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
1717         let kind = match e.node {
1718             // Issue #22181:
1719             // Eventually a desugaring for `box EXPR`
1720             // (similar to the desugaring above for `in PLACE BLOCK`)
1721             // should go here, desugaring
1722             //
1723             // to:
1724             //
1725             // let mut place = BoxPlace::make_place();
1726             // let raw_place = Place::pointer(&mut place);
1727             // let value = $value;
1728             // unsafe {
1729             //     ::std::ptr::write(raw_place, value);
1730             //     Boxed::finalize(place)
1731             // }
1732             //
1733             // But for now there are type-inference issues doing that.
1734             ExprKind::Box(ref inner) => {
1735                 hir::ExprBox(P(self.lower_expr(inner)))
1736             }
1737
1738             // Desugar ExprBox: `in (PLACE) EXPR`
1739             ExprKind::InPlace(ref placer, ref value_expr) => {
1740                 // to:
1741                 //
1742                 // let p = PLACE;
1743                 // let mut place = Placer::make_place(p);
1744                 // let raw_place = Place::pointer(&mut place);
1745                 // push_unsafe!({
1746                 //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1747                 //     InPlace::finalize(place)
1748                 // })
1749                 let placer_expr = P(self.lower_expr(placer));
1750                 let value_expr = P(self.lower_expr(value_expr));
1751
1752                 let placer_ident = self.str_to_ident("placer");
1753                 let place_ident = self.str_to_ident("place");
1754                 let p_ptr_ident = self.str_to_ident("p_ptr");
1755
1756                 let make_place = ["ops", "Placer", "make_place"];
1757                 let place_pointer = ["ops", "Place", "pointer"];
1758                 let move_val_init = ["intrinsics", "move_val_init"];
1759                 let inplace_finalize = ["ops", "InPlace", "finalize"];
1760
1761                 let unstable_span = self.allow_internal_unstable("<-", e.span);
1762                 let make_call = |this: &mut LoweringContext, p, args| {
1763                     let path = P(this.expr_std_path(unstable_span, p, ThinVec::new()));
1764                     P(this.expr_call(e.span, path, args))
1765                 };
1766
1767                 let mk_stmt_let = |this: &mut LoweringContext, bind, expr| {
1768                     this.stmt_let(e.span, false, bind, expr)
1769                 };
1770
1771                 let mk_stmt_let_mut = |this: &mut LoweringContext, bind, expr| {
1772                     this.stmt_let(e.span, true, bind, expr)
1773                 };
1774
1775                 // let placer = <placer_expr> ;
1776                 let (s1, placer_binding) = {
1777                     mk_stmt_let(self, placer_ident, placer_expr)
1778                 };
1779
1780                 // let mut place = Placer::make_place(placer);
1781                 let (s2, place_binding) = {
1782                     let placer = self.expr_ident(e.span, placer_ident, placer_binding);
1783                     let call = make_call(self, &make_place, hir_vec![placer]);
1784                     mk_stmt_let_mut(self, place_ident, call)
1785                 };
1786
1787                 // let p_ptr = Place::pointer(&mut place);
1788                 let (s3, p_ptr_binding) = {
1789                     let agent = P(self.expr_ident(e.span, place_ident, place_binding));
1790                     let args = hir_vec![self.expr_mut_addr_of(e.span, agent)];
1791                     let call = make_call(self, &place_pointer, args);
1792                     mk_stmt_let(self, p_ptr_ident, call)
1793                 };
1794
1795                 // pop_unsafe!(EXPR));
1796                 let pop_unsafe_expr = {
1797                     self.signal_block_expr(hir_vec![],
1798                                            value_expr,
1799                                            e.span,
1800                                            hir::PopUnsafeBlock(hir::CompilerGenerated),
1801                                            ThinVec::new())
1802                 };
1803
1804                 // push_unsafe!({
1805                 //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1806                 //     InPlace::finalize(place)
1807                 // })
1808                 let expr = {
1809                     let ptr = self.expr_ident(e.span, p_ptr_ident, p_ptr_binding);
1810                     let call_move_val_init =
1811                         hir::StmtSemi(
1812                             make_call(self, &move_val_init, hir_vec![ptr, pop_unsafe_expr]),
1813                             self.next_id());
1814                     let call_move_val_init = respan(e.span, call_move_val_init);
1815
1816                     let place = self.expr_ident(e.span, place_ident, place_binding);
1817                     let call = make_call(self, &inplace_finalize, hir_vec![place]);
1818                     P(self.signal_block_expr(hir_vec![call_move_val_init],
1819                                              call,
1820                                              e.span,
1821                                              hir::PushUnsafeBlock(hir::CompilerGenerated),
1822                                              ThinVec::new()))
1823                 };
1824
1825                 let block = self.block_all(e.span, hir_vec![s1, s2, s3], Some(expr));
1826                 hir::ExprBlock(P(block))
1827             }
1828
1829             ExprKind::Array(ref exprs) => {
1830                 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
1831             }
1832             ExprKind::Repeat(ref expr, ref count) => {
1833                 let expr = P(self.lower_expr(expr));
1834                 let count = self.lower_expr(count);
1835                 hir::ExprRepeat(expr, self.record_body(count, None))
1836             }
1837             ExprKind::Tup(ref elts) => {
1838                 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
1839             }
1840             ExprKind::Call(ref f, ref args) => {
1841                 let f = P(self.lower_expr(f));
1842                 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
1843             }
1844             ExprKind::MethodCall(i, ref tps, ref args) => {
1845                 let tps = tps.iter().map(|x| self.lower_ty(x)).collect();
1846                 let args = args.iter().map(|x| self.lower_expr(x)).collect();
1847                 hir::ExprMethodCall(respan(i.span, self.lower_ident(i.node)), tps, args)
1848             }
1849             ExprKind::Binary(binop, ref lhs, ref rhs) => {
1850                 let binop = self.lower_binop(binop);
1851                 let lhs = P(self.lower_expr(lhs));
1852                 let rhs = P(self.lower_expr(rhs));
1853                 hir::ExprBinary(binop, lhs, rhs)
1854             }
1855             ExprKind::Unary(op, ref ohs) => {
1856                 let op = self.lower_unop(op);
1857                 let ohs = P(self.lower_expr(ohs));
1858                 hir::ExprUnary(op, ohs)
1859             }
1860             ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
1861             ExprKind::Cast(ref expr, ref ty) => {
1862                 let expr = P(self.lower_expr(expr));
1863                 hir::ExprCast(expr, self.lower_ty(ty))
1864             }
1865             ExprKind::Type(ref expr, ref ty) => {
1866                 let expr = P(self.lower_expr(expr));
1867                 hir::ExprType(expr, self.lower_ty(ty))
1868             }
1869             ExprKind::AddrOf(m, ref ohs) => {
1870                 let m = self.lower_mutability(m);
1871                 let ohs = P(self.lower_expr(ohs));
1872                 hir::ExprAddrOf(m, ohs)
1873             }
1874             // More complicated than you might expect because the else branch
1875             // might be `if let`.
1876             ExprKind::If(ref cond, ref blk, ref else_opt) => {
1877                 let else_opt = else_opt.as_ref().map(|els| {
1878                     match els.node {
1879                         ExprKind::IfLet(..) => {
1880                             // wrap the if-let expr in a block
1881                             let span = els.span;
1882                             let els = P(self.lower_expr(els));
1883                             let id = self.next_id();
1884                             let blk = P(hir::Block {
1885                                 stmts: hir_vec![],
1886                                 expr: Some(els),
1887                                 id: id,
1888                                 rules: hir::DefaultBlock,
1889                                 span: span,
1890                                 targeted_by_break: false,
1891                             });
1892                             P(self.expr_block(blk, ThinVec::new()))
1893                         }
1894                         _ => P(self.lower_expr(els)),
1895                     }
1896                 });
1897
1898                 let then_blk = self.lower_block(blk, false);
1899                 let then_expr = self.expr_block(then_blk, ThinVec::new());
1900
1901                 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
1902             }
1903             ExprKind::While(ref cond, ref body, opt_ident) => {
1904                 self.with_loop_scope(e.id, |this|
1905                     hir::ExprWhile(
1906                         this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
1907                         this.lower_block(body, false),
1908                         this.lower_opt_sp_ident(opt_ident)))
1909             }
1910             ExprKind::Loop(ref body, opt_ident) => {
1911                 self.with_loop_scope(e.id, |this|
1912                     hir::ExprLoop(this.lower_block(body, false),
1913                                   this.lower_opt_sp_ident(opt_ident),
1914                                   hir::LoopSource::Loop))
1915             }
1916             ExprKind::Catch(ref body) => {
1917                 self.with_catch_scope(body.id, |this|
1918                     hir::ExprBlock(this.lower_block(body, true)))
1919             }
1920             ExprKind::Match(ref expr, ref arms) => {
1921                 hir::ExprMatch(P(self.lower_expr(expr)),
1922                                arms.iter().map(|x| self.lower_arm(x)).collect(),
1923                                hir::MatchSource::Normal)
1924             }
1925             ExprKind::Closure(capture_clause, ref decl, ref body, fn_decl_span) => {
1926                 self.with_new_scopes(|this| {
1927                     this.with_parent_def(e.id, |this| {
1928                         let expr = this.lower_expr(body);
1929                         hir::ExprClosure(this.lower_capture_clause(capture_clause),
1930                                          this.lower_fn_decl(decl),
1931                                          this.record_body(expr, Some(decl)),
1932                                          fn_decl_span)
1933                     })
1934                 })
1935             }
1936             ExprKind::Block(ref blk) => hir::ExprBlock(self.lower_block(blk, false)),
1937             ExprKind::Assign(ref el, ref er) => {
1938                 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
1939             }
1940             ExprKind::AssignOp(op, ref el, ref er) => {
1941                 hir::ExprAssignOp(self.lower_binop(op),
1942                                   P(self.lower_expr(el)),
1943                                   P(self.lower_expr(er)))
1944             }
1945             ExprKind::Field(ref el, ident) => {
1946                 hir::ExprField(P(self.lower_expr(el)),
1947                                respan(ident.span, self.lower_ident(ident.node)))
1948             }
1949             ExprKind::TupField(ref el, ident) => {
1950                 hir::ExprTupField(P(self.lower_expr(el)), ident)
1951             }
1952             ExprKind::Index(ref el, ref er) => {
1953                 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
1954             }
1955             ExprKind::Range(ref e1, ref e2, lims) => {
1956                 use syntax::ast::RangeLimits::*;
1957
1958                 let path = match (e1, e2, lims) {
1959                     (&None, &None, HalfOpen) => "RangeFull",
1960                     (&Some(..), &None, HalfOpen) => "RangeFrom",
1961                     (&None, &Some(..), HalfOpen) => "RangeTo",
1962                     (&Some(..), &Some(..), HalfOpen) => "Range",
1963                     (&None, &Some(..), Closed) => "RangeToInclusive",
1964                     (&Some(..), &Some(..), Closed) => "RangeInclusive",
1965                     (_, &None, Closed) =>
1966                         panic!(self.diagnostic().span_fatal(
1967                             e.span, "inclusive range with no end")),
1968                 };
1969
1970                 let fields =
1971                     e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e)))
1972                     .map(|(s, e)| {
1973                         let expr = P(self.lower_expr(&e));
1974                         let unstable_span = self.allow_internal_unstable("...", e.span);
1975                         self.field(Symbol::intern(s), expr, unstable_span)
1976                     }).collect::<P<[hir::Field]>>();
1977
1978                 let is_unit = fields.is_empty();
1979                 let unstable_span = self.allow_internal_unstable("...", e.span);
1980                 let struct_path =
1981                     iter::once("ops").chain(iter::once(path))
1982                     .collect::<Vec<_>>();
1983                 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
1984                 let struct_path = hir::QPath::Resolved(None, P(struct_path));
1985
1986                 return hir::Expr {
1987                     id: self.lower_node_id(e.id),
1988                     node: if is_unit {
1989                         hir::ExprPath(struct_path)
1990                     } else {
1991                         hir::ExprStruct(struct_path, fields, None)
1992                     },
1993                     span: unstable_span,
1994                     attrs: e.attrs.clone(),
1995                 };
1996             }
1997             ExprKind::Path(ref qself, ref path) => {
1998                 hir::ExprPath(self.lower_qpath(e.id, qself, path, ParamMode::Optional))
1999             }
2000             ExprKind::Break(opt_ident, ref opt_expr) => {
2001                 let label_result = if self.is_in_loop_condition && opt_ident.is_none() {
2002                     hir::Destination {
2003                         ident: opt_ident,
2004                         target_id: hir::ScopeTarget::Loop(
2005                                 Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into()),
2006                     }
2007                 } else {
2008                     self.lower_loop_destination(opt_ident.map(|ident| (e.id, ident)))
2009                 };
2010                 hir::ExprBreak(
2011                         label_result,
2012                         opt_expr.as_ref().map(|x| P(self.lower_expr(x))))
2013             }
2014             ExprKind::Continue(opt_ident) =>
2015                 hir::ExprAgain(
2016                     if self.is_in_loop_condition && opt_ident.is_none() {
2017                         hir::Destination {
2018                             ident: opt_ident,
2019                             target_id: hir::ScopeTarget::Loop(Err(
2020                                 hir::LoopIdError::UnlabeledCfInWhileCondition).into()),
2021                         }
2022                     } else {
2023                         self.lower_loop_destination(opt_ident.map( |ident| (e.id, ident)))
2024                     }),
2025             ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
2026             ExprKind::InlineAsm(ref asm) => {
2027                 let hir_asm = hir::InlineAsm {
2028                     inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
2029                     outputs: asm.outputs.iter().map(|out| {
2030                         hir::InlineAsmOutput {
2031                             constraint: out.constraint.clone(),
2032                             is_rw: out.is_rw,
2033                             is_indirect: out.is_indirect,
2034                         }
2035                     }).collect(),
2036                     asm: asm.asm.clone(),
2037                     asm_str_style: asm.asm_str_style,
2038                     clobbers: asm.clobbers.clone().into(),
2039                     volatile: asm.volatile,
2040                     alignstack: asm.alignstack,
2041                     dialect: asm.dialect,
2042                     ctxt: asm.ctxt,
2043                 };
2044                 let outputs =
2045                     asm.outputs.iter().map(|out| self.lower_expr(&out.expr)).collect();
2046                 let inputs =
2047                     asm.inputs.iter().map(|&(_, ref input)| self.lower_expr(input)).collect();
2048                 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
2049             }
2050             ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
2051                 hir::ExprStruct(self.lower_qpath(e.id, &None, path, ParamMode::Optional),
2052                                 fields.iter().map(|x| self.lower_field(x)).collect(),
2053                                 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))))
2054             }
2055             ExprKind::Paren(ref ex) => {
2056                 let mut ex = self.lower_expr(ex);
2057                 // include parens in span, but only if it is a super-span.
2058                 if e.span.contains(ex.span) {
2059                     ex.span = e.span;
2060                 }
2061                 // merge attributes into the inner expression.
2062                 let mut attrs = e.attrs.clone();
2063                 attrs.extend::<Vec<_>>(ex.attrs.into());
2064                 ex.attrs = attrs;
2065                 return ex;
2066             }
2067
2068             // Desugar ExprIfLet
2069             // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
2070             ExprKind::IfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
2071                 // to:
2072                 //
2073                 //   match <sub_expr> {
2074                 //     <pat> => <body>,
2075                 //     _ => [<else_opt> | ()]
2076                 //   }
2077
2078                 let mut arms = vec![];
2079
2080                 // `<pat> => <body>`
2081                 {
2082                     let body = self.lower_block(body, false);
2083                     let body_expr = P(self.expr_block(body, ThinVec::new()));
2084                     let pat = self.lower_pat(pat);
2085                     arms.push(self.arm(hir_vec![pat], body_expr));
2086                 }
2087
2088                 // _ => [<else_opt>|()]
2089                 {
2090                     let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
2091                     let wildcard_pattern = self.pat_wild(e.span);
2092                     let body = if let Some(else_expr) = wildcard_arm {
2093                         P(self.lower_expr(else_expr))
2094                     } else {
2095                         self.expr_tuple(e.span, hir_vec![])
2096                     };
2097                     arms.push(self.arm(hir_vec![wildcard_pattern], body));
2098                 }
2099
2100                 let contains_else_clause = else_opt.is_some();
2101
2102                 let sub_expr = P(self.lower_expr(sub_expr));
2103
2104                 hir::ExprMatch(
2105                     sub_expr,
2106                     arms.into(),
2107                     hir::MatchSource::IfLetDesugar {
2108                         contains_else_clause: contains_else_clause,
2109                     })
2110             }
2111
2112             // Desugar ExprWhileLet
2113             // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
2114             ExprKind::WhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
2115                 // to:
2116                 //
2117                 //   [opt_ident]: loop {
2118                 //     match <sub_expr> {
2119                 //       <pat> => <body>,
2120                 //       _ => break
2121                 //     }
2122                 //   }
2123
2124                 // Note that the block AND the condition are evaluated in the loop scope.
2125                 // This is done to allow `break` from inside the condition of the loop.
2126                 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| (
2127                     this.lower_block(body, false),
2128                     this.expr_break(e.span, ThinVec::new()),
2129                     this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
2130                 ));
2131
2132                 // `<pat> => <body>`
2133                 let pat_arm = {
2134                     let body_expr = P(self.expr_block(body, ThinVec::new()));
2135                     let pat = self.lower_pat(pat);
2136                     self.arm(hir_vec![pat], body_expr)
2137                 };
2138
2139                 // `_ => break`
2140                 let break_arm = {
2141                     let pat_under = self.pat_wild(e.span);
2142                     self.arm(hir_vec![pat_under], break_expr)
2143                 };
2144
2145                 // `match <sub_expr> { ... }`
2146                 let arms = hir_vec![pat_arm, break_arm];
2147                 let match_expr = self.expr(e.span,
2148                                            hir::ExprMatch(sub_expr,
2149                                                           arms,
2150                                                           hir::MatchSource::WhileLetDesugar),
2151                                            ThinVec::new());
2152
2153                 // `[opt_ident]: loop { ... }`
2154                 let loop_block = P(self.block_expr(P(match_expr)));
2155                 let loop_expr = hir::ExprLoop(loop_block, self.lower_opt_sp_ident(opt_ident),
2156                                               hir::LoopSource::WhileLet);
2157                 // add attributes to the outer returned expr node
2158                 loop_expr
2159             }
2160
2161             // Desugar ExprForLoop
2162             // From: `[opt_ident]: for <pat> in <head> <body>`
2163             ExprKind::ForLoop(ref pat, ref head, ref body, opt_ident) => {
2164                 // to:
2165                 //
2166                 //   {
2167                 //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
2168                 //       mut iter => {
2169                 //         [opt_ident]: loop {
2170                 //           match ::std::iter::Iterator::next(&mut iter) {
2171                 //             ::std::option::Option::Some(<pat>) => <body>,
2172                 //             ::std::option::Option::None => break
2173                 //           }
2174                 //         }
2175                 //       }
2176                 //     };
2177                 //     result
2178                 //   }
2179
2180                 // expand <head>
2181                 let head = self.lower_expr(head);
2182
2183                 let iter = self.str_to_ident("iter");
2184
2185                 // `::std::option::Option::Some(<pat>) => <body>`
2186                 let pat_arm = {
2187                     let body_block = self.with_loop_scope(e.id,
2188                                                           |this| this.lower_block(body, false));
2189                     let body_expr = P(self.expr_block(body_block, ThinVec::new()));
2190                     let pat = self.lower_pat(pat);
2191                     let some_pat = self.pat_some(e.span, pat);
2192
2193                     self.arm(hir_vec![some_pat], body_expr)
2194                 };
2195
2196                 // `::std::option::Option::None => break`
2197                 let break_arm = {
2198                     let break_expr = self.with_loop_scope(e.id, |this|
2199                         this.expr_break(e.span, ThinVec::new()));
2200                     let pat = self.pat_none(e.span);
2201                     self.arm(hir_vec![pat], break_expr)
2202                 };
2203
2204                 // `mut iter`
2205                 let iter_pat = self.pat_ident_binding_mode(e.span, iter,
2206                                                            hir::BindByValue(hir::MutMutable));
2207
2208                 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
2209                 let match_expr = {
2210                     let iter = P(self.expr_ident(e.span, iter, iter_pat.id));
2211                     let ref_mut_iter = self.expr_mut_addr_of(e.span, iter);
2212                     let next_path = &["iter", "Iterator", "next"];
2213                     let next_path = P(self.expr_std_path(e.span, next_path, ThinVec::new()));
2214                     let next_expr = P(self.expr_call(e.span, next_path,
2215                                       hir_vec![ref_mut_iter]));
2216                     let arms = hir_vec![pat_arm, break_arm];
2217
2218                     P(self.expr(e.span,
2219                                 hir::ExprMatch(next_expr, arms,
2220                                                hir::MatchSource::ForLoopDesugar),
2221                                 ThinVec::new()))
2222                 };
2223
2224                 // `[opt_ident]: loop { ... }`
2225                 let loop_block = P(self.block_expr(match_expr));
2226                 let loop_expr = hir::ExprLoop(loop_block, self.lower_opt_sp_ident(opt_ident),
2227                                               hir::LoopSource::ForLoop);
2228                 let loop_expr = P(hir::Expr {
2229                     id: self.lower_node_id(e.id),
2230                     node: loop_expr,
2231                     span: e.span,
2232                     attrs: ThinVec::new(),
2233                 });
2234
2235                 // `mut iter => { ... }`
2236                 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
2237
2238                 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
2239                 let into_iter_expr = {
2240                     let into_iter_path = &["iter", "IntoIterator", "into_iter"];
2241                     let into_iter = P(self.expr_std_path(e.span, into_iter_path,
2242                                                          ThinVec::new()));
2243                     P(self.expr_call(e.span, into_iter, hir_vec![head]))
2244                 };
2245
2246                 let match_expr = P(self.expr_match(e.span,
2247                                                    into_iter_expr,
2248                                                    hir_vec![iter_arm],
2249                                                    hir::MatchSource::ForLoopDesugar));
2250
2251                 // `{ let _result = ...; _result }`
2252                 // underscore prevents an unused_variables lint if the head diverges
2253                 let result_ident = self.str_to_ident("_result");
2254                 let (let_stmt, let_stmt_binding) =
2255                     self.stmt_let(e.span, false, result_ident, match_expr);
2256
2257                 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
2258                 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
2259                 // add the attributes to the outer returned expr node
2260                 return self.expr_block(block, e.attrs.clone());
2261             }
2262
2263             // Desugar ExprKind::Try
2264             // From: `<expr>?`
2265             ExprKind::Try(ref sub_expr) => {
2266                 // to:
2267                 //
2268                 // match Carrier::translate(<expr>) {
2269                 //     Ok(val) => #[allow(unreachable_code)] val,
2270                 //     Err(err) => #[allow(unreachable_code)]
2271                 //                 // If there is an enclosing `catch {...}`
2272                 //                 break 'catch_target Carrier::from_error(From::from(err)),
2273                 //                 // Otherwise
2274                 //                 return Carrier::from_error(From::from(err)),
2275                 // }
2276
2277                 let unstable_span = self.allow_internal_unstable("?", e.span);
2278
2279                 // Carrier::translate(<expr>)
2280                 let discr = {
2281                     // expand <expr>
2282                     let sub_expr = self.lower_expr(sub_expr);
2283
2284                     let path = &["ops", "Carrier", "translate"];
2285                     let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
2286                     P(self.expr_call(e.span, path, hir_vec![sub_expr]))
2287                 };
2288
2289                 // #[allow(unreachable_code)]
2290                 let attr = {
2291                     // allow(unreachable_code)
2292                     let allow = {
2293                         let allow_ident = self.str_to_ident("allow");
2294                         let uc_ident = self.str_to_ident("unreachable_code");
2295                         let uc_meta_item = attr::mk_spanned_word_item(e.span, uc_ident);
2296                         let uc_nested = NestedMetaItemKind::MetaItem(uc_meta_item);
2297                         let uc_spanned = respan(e.span, uc_nested);
2298                         attr::mk_spanned_list_item(e.span, allow_ident, vec![uc_spanned])
2299                     };
2300                     attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
2301                 };
2302                 let attrs = vec![attr];
2303
2304                 // Ok(val) => #[allow(unreachable_code)] val,
2305                 let ok_arm = {
2306                     let val_ident = self.str_to_ident("val");
2307                     let val_pat = self.pat_ident(e.span, val_ident);
2308                     let val_expr = P(self.expr_ident_with_attrs(e.span,
2309                                                                 val_ident,
2310                                                                 val_pat.id,
2311                                                                 ThinVec::from(attrs.clone())));
2312                     let ok_pat = self.pat_ok(e.span, val_pat);
2313
2314                     self.arm(hir_vec![ok_pat], val_expr)
2315                 };
2316
2317                 // Err(err) => #[allow(unreachable_code)]
2318                 //             return Carrier::from_error(From::from(err)),
2319                 let err_arm = {
2320                     let err_ident = self.str_to_ident("err");
2321                     let err_local = self.pat_ident(e.span, err_ident);
2322                     let from_expr = {
2323                         let path = &["convert", "From", "from"];
2324                         let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
2325                         let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
2326
2327                         self.expr_call(e.span, from, hir_vec![err_expr])
2328                     };
2329                     let from_err_expr = {
2330                         let path = &["ops", "Carrier", "from_error"];
2331                         let from_err = P(self.expr_std_path(unstable_span, path,
2332                                                             ThinVec::new()));
2333                         P(self.expr_call(e.span, from_err, hir_vec![from_expr]))
2334                     };
2335
2336                     let thin_attrs = ThinVec::from(attrs);
2337                     let catch_scope = self.catch_scopes.last().map(|x| *x);
2338                     let ret_expr = if let Some(catch_node) = catch_scope {
2339                         P(self.expr(
2340                             e.span,
2341                             hir::ExprBreak(
2342                                 hir::Destination {
2343                                     ident: None,
2344                                     target_id: hir::ScopeTarget::Block(catch_node),
2345                                 },
2346                                 Some(from_err_expr)
2347                             ),
2348                             thin_attrs))
2349                     } else {
2350                         P(self.expr(e.span,
2351                                     hir::Expr_::ExprRet(Some(from_err_expr)),
2352                                     thin_attrs))
2353                     };
2354
2355
2356                     let err_pat = self.pat_err(e.span, err_local);
2357                     self.arm(hir_vec![err_pat], ret_expr)
2358                 };
2359
2360                 hir::ExprMatch(discr,
2361                                hir_vec![err_arm, ok_arm],
2362                                hir::MatchSource::TryDesugar)
2363             }
2364
2365             ExprKind::Mac(_) => panic!("Shouldn't exist here"),
2366         };
2367
2368         hir::Expr {
2369             id: self.lower_node_id(e.id),
2370             node: kind,
2371             span: e.span,
2372             attrs: e.attrs.clone(),
2373         }
2374     }
2375
2376     fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
2377         SmallVector::one(match s.node {
2378             StmtKind::Local(ref l) => Spanned {
2379                 node: hir::StmtDecl(P(Spanned {
2380                     node: hir::DeclLocal(self.lower_local(l)),
2381                     span: s.span,
2382                 }), self.lower_node_id(s.id)),
2383                 span: s.span,
2384             },
2385             StmtKind::Item(ref it) => {
2386                 // Can only use the ID once.
2387                 let mut id = Some(s.id);
2388                 return self.lower_item_id(it).into_iter().map(|item_id| Spanned {
2389                     node: hir::StmtDecl(P(Spanned {
2390                         node: hir::DeclItem(item_id),
2391                         span: s.span,
2392                     }), id.take()
2393                           .map(|id| self.lower_node_id(id))
2394                           .unwrap_or_else(|| self.next_id())),
2395                     span: s.span,
2396                 }).collect();
2397             }
2398             StmtKind::Expr(ref e) => {
2399                 Spanned {
2400                     node: hir::StmtExpr(P(self.lower_expr(e)),
2401                                           self.lower_node_id(s.id)),
2402                     span: s.span,
2403                 }
2404             }
2405             StmtKind::Semi(ref e) => {
2406                 Spanned {
2407                     node: hir::StmtSemi(P(self.lower_expr(e)),
2408                                           self.lower_node_id(s.id)),
2409                     span: s.span,
2410                 }
2411             }
2412             StmtKind::Mac(..) => panic!("Shouldn't exist here"),
2413         })
2414     }
2415
2416     fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
2417         match c {
2418             CaptureBy::Value => hir::CaptureByValue,
2419             CaptureBy::Ref => hir::CaptureByRef,
2420         }
2421     }
2422
2423     /// If an `explicit_owner` is given, this method allocates the `HirId` in
2424     /// the address space of that item instead of the item currently being
2425     /// lowered. This can happen during `lower_impl_item_ref()` where we need to
2426     /// lower a `Visibility` value although we haven't lowered the owning
2427     /// `ImplItem` in question yet.
2428     fn lower_visibility(&mut self,
2429                         v: &Visibility,
2430                         explicit_owner: Option<NodeId>)
2431                         -> hir::Visibility {
2432         match *v {
2433             Visibility::Public => hir::Public,
2434             Visibility::Crate(_) => hir::Visibility::Crate,
2435             Visibility::Restricted { ref path, id } => {
2436                 hir::Visibility::Restricted {
2437                     path: P(self.lower_path(id, path, ParamMode::Explicit, true)),
2438                     id: if let Some(owner) = explicit_owner {
2439                         self.lower_node_id_with_owner(id, owner)
2440                     } else {
2441                         self.lower_node_id(id)
2442                     }
2443                 }
2444             }
2445             Visibility::Inherited => hir::Inherited,
2446         }
2447     }
2448
2449     fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
2450         match d {
2451             Defaultness::Default => hir::Defaultness::Default { has_value: has_value },
2452             Defaultness::Final => {
2453                 assert!(has_value);
2454                 hir::Defaultness::Final
2455             }
2456         }
2457     }
2458
2459     fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
2460         match *b {
2461             BlockCheckMode::Default => hir::DefaultBlock,
2462             BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
2463         }
2464     }
2465
2466     fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingMode {
2467         match *b {
2468             BindingMode::ByRef(m) => hir::BindByRef(self.lower_mutability(m)),
2469             BindingMode::ByValue(m) => hir::BindByValue(self.lower_mutability(m)),
2470         }
2471     }
2472
2473     fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2474         match u {
2475             CompilerGenerated => hir::CompilerGenerated,
2476             UserProvided => hir::UserProvided,
2477         }
2478     }
2479
2480     fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
2481         match i {
2482             ImplPolarity::Positive => hir::ImplPolarity::Positive,
2483             ImplPolarity::Negative => hir::ImplPolarity::Negative,
2484         }
2485     }
2486
2487     fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2488         match f {
2489             TraitBoundModifier::None => hir::TraitBoundModifier::None,
2490             TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
2491         }
2492     }
2493
2494     // Helper methods for building HIR.
2495
2496     fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
2497         hir::Arm {
2498             attrs: hir_vec![],
2499             pats: pats,
2500             guard: None,
2501             body: expr,
2502         }
2503     }
2504
2505     fn field(&mut self, name: Name, expr: P<hir::Expr>, span: Span) -> hir::Field {
2506         hir::Field {
2507             name: Spanned {
2508                 node: name,
2509                 span: span,
2510             },
2511             span: span,
2512             expr: expr,
2513             is_shorthand: false,
2514         }
2515     }
2516
2517     fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
2518         let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
2519         P(self.expr(span, expr_break, attrs))
2520     }
2521
2522     fn expr_call(&mut self, span: Span, e: P<hir::Expr>, args: hir::HirVec<hir::Expr>)
2523                  -> hir::Expr {
2524         self.expr(span, hir::ExprCall(e, args), ThinVec::new())
2525     }
2526
2527     fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
2528         self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
2529     }
2530
2531     fn expr_ident_with_attrs(&mut self, span: Span,
2532                                         id: Name,
2533                                         binding: NodeId,
2534                                         attrs: ThinVec<Attribute>) -> hir::Expr {
2535         let def = {
2536             let defs = self.resolver.definitions();
2537             Def::Local(defs.local_def_id(binding))
2538         };
2539
2540         let expr_path = hir::ExprPath(hir::QPath::Resolved(None, P(hir::Path {
2541             span: span,
2542             def: def,
2543             segments: hir_vec![hir::PathSegment::from_name(id)],
2544         })));
2545
2546         self.expr(span, expr_path, attrs)
2547     }
2548
2549     fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
2550         self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
2551     }
2552
2553     fn expr_std_path(&mut self,
2554                      span: Span,
2555                      components: &[&str],
2556                      attrs: ThinVec<Attribute>)
2557                      -> hir::Expr {
2558         let path = self.std_path(span, components, true);
2559         self.expr(span, hir::ExprPath(hir::QPath::Resolved(None, P(path))), attrs)
2560     }
2561
2562     fn expr_match(&mut self,
2563                   span: Span,
2564                   arg: P<hir::Expr>,
2565                   arms: hir::HirVec<hir::Arm>,
2566                   source: hir::MatchSource)
2567                   -> hir::Expr {
2568         self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
2569     }
2570
2571     fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
2572         self.expr(b.span, hir::ExprBlock(b), attrs)
2573     }
2574
2575     fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
2576         P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
2577     }
2578
2579     fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
2580         hir::Expr {
2581             id: self.next_id(),
2582             node: node,
2583             span: span,
2584             attrs: attrs,
2585         }
2586     }
2587
2588     fn stmt_let(&mut self, sp: Span, mutbl: bool, ident: Name, ex: P<hir::Expr>)
2589                 -> (hir::Stmt, NodeId) {
2590         let pat = if mutbl {
2591             self.pat_ident_binding_mode(sp, ident, hir::BindByValue(hir::MutMutable))
2592         } else {
2593             self.pat_ident(sp, ident)
2594         };
2595         let pat_id = pat.id;
2596         let local = P(hir::Local {
2597             pat: pat,
2598             ty: None,
2599             init: Some(ex),
2600             id: self.next_id(),
2601             span: sp,
2602             attrs: ThinVec::new(),
2603         });
2604         let decl = respan(sp, hir::DeclLocal(local));
2605         (respan(sp, hir::StmtDecl(P(decl), self.next_id())), pat_id)
2606     }
2607
2608     fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
2609         self.block_all(expr.span, hir::HirVec::new(), Some(expr))
2610     }
2611
2612     fn block_all(&mut self, span: Span, stmts: hir::HirVec<hir::Stmt>, expr: Option<P<hir::Expr>>)
2613                  -> hir::Block {
2614         hir::Block {
2615             stmts: stmts,
2616             expr: expr,
2617             id: self.next_id(),
2618             rules: hir::DefaultBlock,
2619             span: span,
2620             targeted_by_break: false,
2621         }
2622     }
2623
2624     fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
2625         self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
2626     }
2627
2628     fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
2629         self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
2630     }
2631
2632     fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
2633         self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
2634     }
2635
2636     fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
2637         self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
2638     }
2639
2640     fn pat_std_enum(&mut self,
2641                     span: Span,
2642                     components: &[&str],
2643                     subpats: hir::HirVec<P<hir::Pat>>)
2644                     -> P<hir::Pat> {
2645         let path = self.std_path(span, components, true);
2646         let qpath = hir::QPath::Resolved(None, P(path));
2647         let pt = if subpats.is_empty() {
2648             hir::PatKind::Path(qpath)
2649         } else {
2650             hir::PatKind::TupleStruct(qpath, subpats, None)
2651         };
2652         self.pat(span, pt)
2653     }
2654
2655     fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
2656         self.pat_ident_binding_mode(span, name, hir::BindByValue(hir::MutImmutable))
2657     }
2658
2659     fn pat_ident_binding_mode(&mut self, span: Span, name: Name, bm: hir::BindingMode)
2660                               -> P<hir::Pat> {
2661         let id = self.next_id();
2662         let parent_def = self.parent_def.unwrap();
2663         let def_id = {
2664             let defs = self.resolver.definitions();
2665             let def_path_data = DefPathData::Binding(name.as_str());
2666             let def_index = defs
2667                 .create_def_with_parent(parent_def, id, def_path_data, REGULAR_SPACE, Mark::root());
2668             DefId::local(def_index)
2669         };
2670
2671         P(hir::Pat {
2672             id: id,
2673             node: hir::PatKind::Binding(bm,
2674                                         def_id,
2675                                         Spanned {
2676                                             span: span,
2677                                             node: name,
2678                                         },
2679                                         None),
2680             span: span,
2681         })
2682     }
2683
2684     fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
2685         self.pat(span, hir::PatKind::Wild)
2686     }
2687
2688     fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
2689         P(hir::Pat {
2690             id: self.next_id(),
2691             node: pat,
2692             span: span,
2693         })
2694     }
2695
2696     /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
2697     /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
2698     /// The path is also resolved according to `is_value`.
2699     fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
2700         let mut path = hir::Path {
2701             span: span,
2702             def: Def::Err,
2703             segments: iter::once(keywords::CrateRoot.name()).chain({
2704                 self.crate_root.into_iter().chain(components.iter().cloned()).map(Symbol::intern)
2705             }).map(hir::PathSegment::from_name).collect(),
2706         };
2707
2708         self.resolver.resolve_hir_path(&mut path, is_value);
2709         path
2710     }
2711
2712     fn signal_block_expr(&mut self,
2713                          stmts: hir::HirVec<hir::Stmt>,
2714                          expr: P<hir::Expr>,
2715                          span: Span,
2716                          rule: hir::BlockCheckMode,
2717                          attrs: ThinVec<Attribute>)
2718                          -> hir::Expr {
2719         let id = self.next_id();
2720         let block = P(hir::Block {
2721             rules: rule,
2722             span: span,
2723             id: id,
2724             stmts: stmts,
2725             expr: Some(expr),
2726             targeted_by_break: false,
2727         });
2728         self.expr_block(block, attrs)
2729     }
2730
2731     fn ty_path(&mut self, id: NodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
2732         let mut id = id;
2733         let node = match qpath {
2734             hir::QPath::Resolved(None, path) => {
2735                 // Turn trait object paths into `TyTraitObject` instead.
2736                 if let Def::Trait(_) = path.def {
2737                     let principal = hir::PolyTraitRef {
2738                         bound_lifetimes: hir_vec![],
2739                         trait_ref: hir::TraitRef {
2740                             path: path.and_then(|path| path),
2741                             ref_id: id,
2742                         },
2743                         span,
2744                     };
2745
2746                     // The original ID is taken by the `PolyTraitRef`,
2747                     // so the `Ty` itself needs a different one.
2748                     id = self.next_id();
2749
2750                     hir::TyTraitObject(hir_vec![principal], self.elided_lifetime(span))
2751                 } else {
2752                     hir::TyPath(hir::QPath::Resolved(None, path))
2753                 }
2754             }
2755             _ => hir::TyPath(qpath)
2756         };
2757         P(hir::Ty { id, node, span })
2758     }
2759
2760     fn elided_lifetime(&mut self, span: Span) -> hir::Lifetime {
2761         hir::Lifetime {
2762             id: self.next_id(),
2763             span: span,
2764             name: keywords::Invalid.name()
2765         }
2766     }
2767 }
2768
2769 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
2770     // Sorting by span ensures that we get things in order within a
2771     // file, and also puts the files in a sensible order.
2772     let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
2773     body_ids.sort_by_key(|b| bodies[b].value.span);
2774     body_ids
2775 }