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