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