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