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