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