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