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