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