]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/lowering.rs
Auto merge of #32005 - vegai:31686, r=Manishearth
[rust.git] / src / librustc_front / 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 // Lowering must be reproducable (the compiler only lowers once, but tools and
33 // custom lints may lower an AST node to a HIR node to interact with the
34 // compiler). The most interesting bit of this is ids - if you lower an AST node
35 // and create new HIR nodes with fresh ids, when re-lowering the same node, you
36 // must ensure you get the same ids! To do this, we keep track of the next id
37 // when we translate a node which requires new ids. By checking this cache and
38 // using node ids starting with the cached id, we ensure ids are reproducible.
39 // To use this system, you just need to hold on to a CachedIdSetter object
40 // whilst lowering. This is an RAII object that takes care of setting and
41 // restoring the cached id, etc.
42 //
43 // This whole system relies on node ids being incremented one at a time and
44 // all increments being for lowering. This means that you should not call any
45 // non-lowering function which will use new node ids.
46 //
47 // We must also cache gensym'ed Idents to ensure that we get the same Ident
48 // every time we lower a node with gensym'ed names. One consequence of this is
49 // that you can only gensym a name once in a lowering (you don't need to worry
50 // about nested lowering though). That's because we cache based on the name and
51 // the currently cached node id, which is unique per lowered node.
52 //
53 // Spans are used for error messages and for tools to map semantics back to
54 // source code. It is therefore not as important with spans as ids to be strict
55 // about use (you can't break the compiler by screwing up a span). Obviously, a
56 // HIR node can only have a single span. But multiple nodes can have the same
57 // span and spans don't need to be kept in order, etc. Where code is preserved
58 // by lowering, it should have the same span as in the AST. Where HIR nodes are
59 // new it is probably best to give a span for the whole AST node being lowered.
60 // All nodes should have real spans, don't use dummy spans. Tools are likely to
61 // get confused if the spans from leaf AST nodes occur in multiple places
62 // in the HIR, especially for multiple identifiers.
63
64 use hir;
65
66 use std::collections::BTreeMap;
67 use std::collections::HashMap;
68 use syntax::ast::*;
69 use syntax::attr::{ThinAttributes, ThinAttributesExt};
70 use syntax::ext::mtwt;
71 use syntax::ptr::P;
72 use syntax::codemap::{respan, Spanned, Span};
73 use syntax::parse::token;
74 use syntax::std_inject;
75 use syntax::visit::{self, Visitor};
76
77 use std::cell::{Cell, RefCell};
78
79 pub struct LoweringContext<'a> {
80     crate_root: Option<&'static str>,
81     // Map AST ids to ids used for expanded nodes.
82     id_cache: RefCell<HashMap<NodeId, NodeId>>,
83     // Use if there are no cached ids for the current node.
84     id_assigner: &'a NodeIdAssigner,
85     // 0 == no cached id. Must be incremented to align with previous id
86     // incrementing.
87     cached_id: Cell<u32>,
88     // Keep track of gensym'ed idents.
89     gensym_cache: RefCell<HashMap<(NodeId, &'static str), hir::Ident>>,
90     // A copy of cached_id, but is also set to an id while a node is lowered for
91     // the first time.
92     gensym_key: Cell<u32>,
93 }
94
95 impl<'a, 'hir> LoweringContext<'a> {
96     pub fn new(id_assigner: &'a NodeIdAssigner, c: Option<&Crate>) -> LoweringContext<'a> {
97         let crate_root = c.and_then(|c| {
98             if std_inject::no_core(c) {
99                 None
100             } else if std_inject::no_std(c) {
101                 Some("core")
102             } else {
103                 Some("std")
104             }
105         });
106
107         LoweringContext {
108             crate_root: crate_root,
109             id_cache: RefCell::new(HashMap::new()),
110             id_assigner: id_assigner,
111             cached_id: Cell::new(0),
112             gensym_cache: RefCell::new(HashMap::new()),
113             gensym_key: Cell::new(0),
114         }
115     }
116
117     fn next_id(&self) -> NodeId {
118         let cached_id = self.cached_id.get();
119         if cached_id == 0 {
120             return self.id_assigner.next_node_id();
121         }
122
123         self.cached_id.set(cached_id + 1);
124         cached_id
125     }
126
127     fn str_to_ident(&self, s: &'static str) -> hir::Ident {
128         let gensym_key = self.gensym_key.get();
129         if gensym_key == 0 {
130             return hir::Ident::from_name(token::gensym(s));
131         }
132
133         let cached = self.gensym_cache.borrow().contains_key(&(gensym_key, s));
134         if cached {
135             self.gensym_cache.borrow()[&(gensym_key, s)]
136         } else {
137             let result = hir::Ident::from_name(token::gensym(s));
138             self.gensym_cache.borrow_mut().insert((gensym_key, s), result);
139             result
140         }
141     }
142 }
143
144 // Utility fn for setting and unsetting the cached id.
145 fn cache_ids<'a, OP, R>(lctx: &LoweringContext, expr_id: NodeId, op: OP) -> R
146     where OP: FnOnce(&LoweringContext) -> R
147 {
148     // Only reset the id if it was previously 0, i.e., was not cached.
149     // If it was cached, we are in a nested node, but our id count will
150     // still count towards the parent's count.
151     let reset_cached_id = lctx.cached_id.get() == 0;
152     // We always reset gensym_key so that if we use the same name in a nested
153     // node and after that node, they get different values.
154     let old_gensym_key = lctx.gensym_key.get();
155
156     {
157         let id_cache: &mut HashMap<_, _> = &mut lctx.id_cache.borrow_mut();
158
159         if id_cache.contains_key(&expr_id) {
160             let cached_id = lctx.cached_id.get();
161             if cached_id == 0 {
162                 // We're entering a node where we need to track ids, but are not
163                 // yet tracking.
164                 lctx.cached_id.set(id_cache[&expr_id]);
165             } else {
166                 // We're already tracking - check that the tracked id is the same
167                 // as the expected id.
168                 assert!(cached_id == id_cache[&expr_id], "id mismatch");
169             }
170             lctx.gensym_key.set(id_cache[&expr_id]);
171         } else {
172             // We've never lowered this node before, remember it for next time.
173             let next_id = lctx.id_assigner.peek_node_id();
174             id_cache.insert(expr_id, next_id);
175             lctx.gensym_key.set(next_id);
176             // self.cached_id is not set when we lower a node for the first time,
177             // only on re-lowering.
178         }
179     }
180
181     let result = op(lctx);
182
183     if reset_cached_id {
184         lctx.cached_id.set(0);
185     }
186     lctx.gensym_key.set(old_gensym_key);
187
188     result
189 }
190
191 pub fn lower_ident(_lctx: &LoweringContext, ident: Ident) -> hir::Ident {
192     hir::Ident {
193         name: mtwt::resolve(ident),
194         unhygienic_name: ident.name,
195     }
196 }
197
198 pub fn lower_attrs(_lctx: &LoweringContext, attrs: &Vec<Attribute>) -> hir::HirVec<Attribute> {
199     attrs.clone().into()
200 }
201
202 pub fn lower_view_path(lctx: &LoweringContext, view_path: &ViewPath) -> P<hir::ViewPath> {
203     P(Spanned {
204         node: match view_path.node {
205             ViewPathSimple(ident, ref path) => {
206                 hir::ViewPathSimple(ident.name, lower_path(lctx, path))
207             }
208             ViewPathGlob(ref path) => {
209                 hir::ViewPathGlob(lower_path(lctx, path))
210             }
211             ViewPathList(ref path, ref path_list_idents) => {
212                 hir::ViewPathList(lower_path(lctx, path),
213                                   path_list_idents.iter()
214                                                   .map(lower_path_list_item)
215                                                   .collect())
216             }
217         },
218         span: view_path.span,
219     })
220 }
221
222 fn lower_path_list_item(path_list_ident: &PathListItem) -> hir::PathListItem {
223     Spanned {
224         node: match path_list_ident.node {
225             PathListItemKind::Ident { id, name, rename } => hir::PathListIdent {
226                 id: id,
227                 name: name.name,
228                 rename: rename.map(|x| x.name),
229             },
230             PathListItemKind::Mod { id, rename } => hir::PathListMod {
231                 id: id,
232                 rename: rename.map(|x| x.name),
233             },
234         },
235         span: path_list_ident.span,
236     }
237 }
238
239 pub fn lower_arm(lctx: &LoweringContext, arm: &Arm) -> hir::Arm {
240     hir::Arm {
241         attrs: lower_attrs(lctx, &arm.attrs),
242         pats: arm.pats.iter().map(|x| lower_pat(lctx, x)).collect(),
243         guard: arm.guard.as_ref().map(|ref x| lower_expr(lctx, x)),
244         body: lower_expr(lctx, &arm.body),
245     }
246 }
247
248 pub fn lower_decl(lctx: &LoweringContext, d: &Decl) -> P<hir::Decl> {
249     match d.node {
250         DeclKind::Local(ref l) => P(Spanned {
251             node: hir::DeclLocal(lower_local(lctx, l)),
252             span: d.span,
253         }),
254         DeclKind::Item(ref it) => P(Spanned {
255             node: hir::DeclItem(lower_item_id(lctx, it)),
256             span: d.span,
257         }),
258     }
259 }
260
261 pub fn lower_ty_binding(lctx: &LoweringContext, b: &TypeBinding) -> hir::TypeBinding {
262     hir::TypeBinding {
263         id: b.id,
264         name: b.ident.name,
265         ty: lower_ty(lctx, &b.ty),
266         span: b.span,
267     }
268 }
269
270 pub fn lower_ty(lctx: &LoweringContext, t: &Ty) -> P<hir::Ty> {
271     use syntax::ast::TyKind::*;
272     P(hir::Ty {
273         id: t.id,
274         node: match t.node {
275             Infer => hir::TyInfer,
276             Vec(ref ty) => hir::TyVec(lower_ty(lctx, ty)),
277             Ptr(ref mt) => hir::TyPtr(lower_mt(lctx, mt)),
278             Rptr(ref region, ref mt) => {
279                 hir::TyRptr(lower_opt_lifetime(lctx, region), lower_mt(lctx, mt))
280             }
281             BareFn(ref f) => {
282                 hir::TyBareFn(P(hir::BareFnTy {
283                     lifetimes: lower_lifetime_defs(lctx, &f.lifetimes),
284                     unsafety: lower_unsafety(lctx, f.unsafety),
285                     abi: f.abi,
286                     decl: lower_fn_decl(lctx, &f.decl),
287                 }))
288             }
289             Tup(ref tys) => hir::TyTup(tys.iter().map(|ty| lower_ty(lctx, ty)).collect()),
290             Paren(ref ty) => {
291                 return lower_ty(lctx, ty);
292             }
293             Path(ref qself, ref path) => {
294                 let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
295                     hir::QSelf {
296                         ty: lower_ty(lctx, ty),
297                         position: position,
298                     }
299                 });
300                 hir::TyPath(qself, lower_path(lctx, path))
301             }
302             ObjectSum(ref ty, ref bounds) => {
303                 hir::TyObjectSum(lower_ty(lctx, ty), lower_bounds(lctx, bounds))
304             }
305             FixedLengthVec(ref ty, ref e) => {
306                 hir::TyFixedLengthVec(lower_ty(lctx, ty), lower_expr(lctx, e))
307             }
308             Typeof(ref expr) => {
309                 hir::TyTypeof(lower_expr(lctx, expr))
310             }
311             PolyTraitRef(ref bounds) => {
312                 hir::TyPolyTraitRef(bounds.iter().map(|b| lower_ty_param_bound(lctx, b)).collect())
313             }
314             Mac(_) => panic!("TyMac should have been expanded by now."),
315         },
316         span: t.span,
317     })
318 }
319
320 pub fn lower_foreign_mod(lctx: &LoweringContext, fm: &ForeignMod) -> hir::ForeignMod {
321     hir::ForeignMod {
322         abi: fm.abi,
323         items: fm.items.iter().map(|x| lower_foreign_item(lctx, x)).collect(),
324     }
325 }
326
327 pub fn lower_variant(lctx: &LoweringContext, v: &Variant) -> hir::Variant {
328     Spanned {
329         node: hir::Variant_ {
330             name: v.node.name.name,
331             attrs: lower_attrs(lctx, &v.node.attrs),
332             data: lower_variant_data(lctx, &v.node.data),
333             disr_expr: v.node.disr_expr.as_ref().map(|e| lower_expr(lctx, e)),
334         },
335         span: v.span,
336     }
337 }
338
339 // Path segments are usually unhygienic, hygienic path segments can occur only in
340 // identifier-like paths originating from `ExprPath`.
341 // Make life simpler for rustc_resolve by renaming only such segments.
342 pub fn lower_path_full(lctx: &LoweringContext, p: &Path, maybe_hygienic: bool) -> hir::Path {
343     let maybe_hygienic = maybe_hygienic && !p.global && p.segments.len() == 1;
344     hir::Path {
345         global: p.global,
346         segments: p.segments
347                    .iter()
348                    .map(|&PathSegment { identifier, ref parameters }| {
349                        hir::PathSegment {
350                            identifier: if maybe_hygienic {
351                                lower_ident(lctx, identifier)
352                            } else {
353                                hir::Ident::from_name(identifier.name)
354                            },
355                            parameters: lower_path_parameters(lctx, parameters),
356                        }
357                    })
358                    .collect(),
359         span: p.span,
360     }
361 }
362
363 pub fn lower_path(lctx: &LoweringContext, p: &Path) -> hir::Path {
364     lower_path_full(lctx, p, false)
365 }
366
367 pub fn lower_path_parameters(lctx: &LoweringContext,
368                              path_parameters: &PathParameters)
369                              -> hir::PathParameters {
370     match *path_parameters {
371         PathParameters::AngleBracketed(ref data) =>
372             hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(lctx, data)),
373         PathParameters::Parenthesized(ref data) =>
374             hir::ParenthesizedParameters(lower_parenthesized_parameter_data(lctx, data)),
375     }
376 }
377
378 pub fn lower_angle_bracketed_parameter_data(lctx: &LoweringContext,
379                                             data: &AngleBracketedParameterData)
380                                             -> hir::AngleBracketedParameterData {
381     let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
382     hir::AngleBracketedParameterData {
383         lifetimes: lower_lifetimes(lctx, lifetimes),
384         types: types.iter().map(|ty| lower_ty(lctx, ty)).collect(),
385         bindings: bindings.iter().map(|b| lower_ty_binding(lctx, b)).collect(),
386     }
387 }
388
389 pub fn lower_parenthesized_parameter_data(lctx: &LoweringContext,
390                                           data: &ParenthesizedParameterData)
391                                           -> hir::ParenthesizedParameterData {
392     let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
393     hir::ParenthesizedParameterData {
394         inputs: inputs.iter().map(|ty| lower_ty(lctx, ty)).collect(),
395         output: output.as_ref().map(|ty| lower_ty(lctx, ty)),
396         span: span,
397     }
398 }
399
400 pub fn lower_local(lctx: &LoweringContext, l: &Local) -> P<hir::Local> {
401     P(hir::Local {
402         id: l.id,
403         ty: l.ty.as_ref().map(|t| lower_ty(lctx, t)),
404         pat: lower_pat(lctx, &l.pat),
405         init: l.init.as_ref().map(|e| lower_expr(lctx, e)),
406         span: l.span,
407         attrs: l.attrs.clone(),
408     })
409 }
410
411 pub fn lower_explicit_self_underscore(lctx: &LoweringContext,
412                                       es: &SelfKind)
413                                       -> hir::ExplicitSelf_ {
414     match *es {
415         SelfKind::Static => hir::SelfStatic,
416         SelfKind::Value(v) => hir::SelfValue(v.name),
417         SelfKind::Region(ref lifetime, m, ident) => {
418             hir::SelfRegion(lower_opt_lifetime(lctx, lifetime),
419                             lower_mutability(lctx, m),
420                             ident.name)
421         }
422         SelfKind::Explicit(ref typ, ident) => {
423             hir::SelfExplicit(lower_ty(lctx, typ), ident.name)
424         }
425     }
426 }
427
428 pub fn lower_mutability(_lctx: &LoweringContext, m: Mutability) -> hir::Mutability {
429     match m {
430         Mutability::Mutable => hir::MutMutable,
431         Mutability::Immutable => hir::MutImmutable,
432     }
433 }
434
435 pub fn lower_explicit_self(lctx: &LoweringContext, s: &ExplicitSelf) -> hir::ExplicitSelf {
436     Spanned {
437         node: lower_explicit_self_underscore(lctx, &s.node),
438         span: s.span,
439     }
440 }
441
442 pub fn lower_arg(lctx: &LoweringContext, arg: &Arg) -> hir::Arg {
443     hir::Arg {
444         id: arg.id,
445         pat: lower_pat(lctx, &arg.pat),
446         ty: lower_ty(lctx, &arg.ty),
447     }
448 }
449
450 pub fn lower_fn_decl(lctx: &LoweringContext, decl: &FnDecl) -> P<hir::FnDecl> {
451     P(hir::FnDecl {
452         inputs: decl.inputs.iter().map(|x| lower_arg(lctx, x)).collect(),
453         output: match decl.output {
454             FunctionRetTy::Ty(ref ty) => hir::Return(lower_ty(lctx, ty)),
455             FunctionRetTy::Default(span) => hir::DefaultReturn(span),
456             FunctionRetTy::None(span) => hir::NoReturn(span),
457         },
458         variadic: decl.variadic,
459     })
460 }
461
462 pub fn lower_ty_param_bound(lctx: &LoweringContext, tpb: &TyParamBound) -> hir::TyParamBound {
463     match *tpb {
464         TraitTyParamBound(ref ty, modifier) => {
465             hir::TraitTyParamBound(lower_poly_trait_ref(lctx, ty),
466                                    lower_trait_bound_modifier(lctx, modifier))
467         }
468         RegionTyParamBound(ref lifetime) => {
469             hir::RegionTyParamBound(lower_lifetime(lctx, lifetime))
470         }
471     }
472 }
473
474 pub fn lower_ty_param(lctx: &LoweringContext, tp: &TyParam) -> hir::TyParam {
475     hir::TyParam {
476         id: tp.id,
477         name: tp.ident.name,
478         bounds: lower_bounds(lctx, &tp.bounds),
479         default: tp.default.as_ref().map(|x| lower_ty(lctx, x)),
480         span: tp.span,
481     }
482 }
483
484 pub fn lower_ty_params(lctx: &LoweringContext,
485                        tps: &P<[TyParam]>)
486                        -> hir::HirVec<hir::TyParam> {
487     tps.iter().map(|tp| lower_ty_param(lctx, tp)).collect()
488 }
489
490 pub fn lower_lifetime(_lctx: &LoweringContext, l: &Lifetime) -> hir::Lifetime {
491     hir::Lifetime {
492         id: l.id,
493         name: l.name,
494         span: l.span,
495     }
496 }
497
498 pub fn lower_lifetime_def(lctx: &LoweringContext, l: &LifetimeDef) -> hir::LifetimeDef {
499     hir::LifetimeDef {
500         lifetime: lower_lifetime(lctx, &l.lifetime),
501         bounds: lower_lifetimes(lctx, &l.bounds),
502     }
503 }
504
505 pub fn lower_lifetimes(lctx: &LoweringContext, lts: &Vec<Lifetime>) -> hir::HirVec<hir::Lifetime> {
506     lts.iter().map(|l| lower_lifetime(lctx, l)).collect()
507 }
508
509 pub fn lower_lifetime_defs(lctx: &LoweringContext,
510                            lts: &Vec<LifetimeDef>)
511                            -> hir::HirVec<hir::LifetimeDef> {
512     lts.iter().map(|l| lower_lifetime_def(lctx, l)).collect()
513 }
514
515 pub fn lower_opt_lifetime(lctx: &LoweringContext,
516                           o_lt: &Option<Lifetime>)
517                           -> Option<hir::Lifetime> {
518     o_lt.as_ref().map(|lt| lower_lifetime(lctx, lt))
519 }
520
521 pub fn lower_generics(lctx: &LoweringContext, g: &Generics) -> hir::Generics {
522     hir::Generics {
523         ty_params: lower_ty_params(lctx, &g.ty_params),
524         lifetimes: lower_lifetime_defs(lctx, &g.lifetimes),
525         where_clause: lower_where_clause(lctx, &g.where_clause),
526     }
527 }
528
529 pub fn lower_where_clause(lctx: &LoweringContext, wc: &WhereClause) -> hir::WhereClause {
530     hir::WhereClause {
531         id: wc.id,
532         predicates: wc.predicates
533                       .iter()
534                       .map(|predicate| lower_where_predicate(lctx, predicate))
535                       .collect(),
536     }
537 }
538
539 pub fn lower_where_predicate(lctx: &LoweringContext,
540                              pred: &WherePredicate)
541                              -> hir::WherePredicate {
542     match *pred {
543         WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
544                                                             ref bounded_ty,
545                                                             ref bounds,
546                                                             span}) => {
547             hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
548                 bound_lifetimes: lower_lifetime_defs(lctx, bound_lifetimes),
549                 bounded_ty: lower_ty(lctx, bounded_ty),
550                 bounds: bounds.iter().map(|x| lower_ty_param_bound(lctx, x)).collect(),
551                 span: span,
552             })
553         }
554         WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
555                                                               ref bounds,
556                                                               span}) => {
557             hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
558                 span: span,
559                 lifetime: lower_lifetime(lctx, lifetime),
560                 bounds: bounds.iter().map(|bound| lower_lifetime(lctx, bound)).collect(),
561             })
562         }
563         WherePredicate::EqPredicate(WhereEqPredicate{ id,
564                                                       ref path,
565                                                       ref ty,
566                                                       span}) => {
567             hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
568                 id: id,
569                 path: lower_path(lctx, path),
570                 ty: lower_ty(lctx, ty),
571                 span: span,
572             })
573         }
574     }
575 }
576
577 pub fn lower_variant_data(lctx: &LoweringContext, vdata: &VariantData) -> hir::VariantData {
578     match *vdata {
579         VariantData::Struct(ref fields, id) => {
580             hir::VariantData::Struct(fields.iter()
581                                            .enumerate()
582                                            .map(|f| lower_struct_field(lctx, f))
583                                            .collect(),
584                                      id)
585         }
586         VariantData::Tuple(ref fields, id) => {
587             hir::VariantData::Tuple(fields.iter()
588                                           .enumerate()
589                                           .map(|f| lower_struct_field(lctx, f))
590                                           .collect(),
591                                     id)
592         }
593         VariantData::Unit(id) => hir::VariantData::Unit(id),
594     }
595 }
596
597 pub fn lower_trait_ref(lctx: &LoweringContext, p: &TraitRef) -> hir::TraitRef {
598     hir::TraitRef {
599         path: lower_path(lctx, &p.path),
600         ref_id: p.ref_id,
601     }
602 }
603
604 pub fn lower_poly_trait_ref(lctx: &LoweringContext, p: &PolyTraitRef) -> hir::PolyTraitRef {
605     hir::PolyTraitRef {
606         bound_lifetimes: lower_lifetime_defs(lctx, &p.bound_lifetimes),
607         trait_ref: lower_trait_ref(lctx, &p.trait_ref),
608         span: p.span,
609     }
610 }
611
612 pub fn lower_struct_field(lctx: &LoweringContext,
613                           (index, f): (usize, &StructField))
614                           -> hir::StructField {
615     hir::StructField {
616         span: f.span,
617         id: f.node.id,
618         name: f.node.ident().map(|ident| ident.name)
619                             .unwrap_or(token::intern(&index.to_string())),
620         vis: lower_visibility(lctx, f.node.kind.visibility()),
621         ty: lower_ty(lctx, &f.node.ty),
622         attrs: lower_attrs(lctx, &f.node.attrs),
623     }
624 }
625
626 pub fn lower_field(lctx: &LoweringContext, f: &Field) -> hir::Field {
627     hir::Field {
628         name: respan(f.ident.span, f.ident.node.name),
629         expr: lower_expr(lctx, &f.expr),
630         span: f.span,
631     }
632 }
633
634 pub fn lower_mt(lctx: &LoweringContext, mt: &MutTy) -> hir::MutTy {
635     hir::MutTy {
636         ty: lower_ty(lctx, &mt.ty),
637         mutbl: lower_mutability(lctx, mt.mutbl),
638     }
639 }
640
641 pub fn lower_opt_bounds(lctx: &LoweringContext,
642                         b: &Option<TyParamBounds>)
643                         -> Option<hir::TyParamBounds> {
644     b.as_ref().map(|ref bounds| lower_bounds(lctx, bounds))
645 }
646
647 fn lower_bounds(lctx: &LoweringContext, bounds: &TyParamBounds) -> hir::TyParamBounds {
648     bounds.iter().map(|bound| lower_ty_param_bound(lctx, bound)).collect()
649 }
650
651 pub fn lower_block(lctx: &LoweringContext, b: &Block) -> P<hir::Block> {
652     P(hir::Block {
653         id: b.id,
654         stmts: b.stmts.iter().map(|s| lower_stmt(lctx, s)).collect(),
655         expr: b.expr.as_ref().map(|ref x| lower_expr(lctx, x)),
656         rules: lower_block_check_mode(lctx, &b.rules),
657         span: b.span,
658     })
659 }
660
661 pub fn lower_item_kind(lctx: &LoweringContext, i: &ItemKind) -> hir::Item_ {
662     match *i {
663         ItemKind::ExternCrate(string) => hir::ItemExternCrate(string),
664         ItemKind::Use(ref view_path) => {
665             hir::ItemUse(lower_view_path(lctx, view_path))
666         }
667         ItemKind::Static(ref t, m, ref e) => {
668             hir::ItemStatic(lower_ty(lctx, t),
669                             lower_mutability(lctx, m),
670                             lower_expr(lctx, e))
671         }
672         ItemKind::Const(ref t, ref e) => {
673             hir::ItemConst(lower_ty(lctx, t), lower_expr(lctx, e))
674         }
675         ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
676             hir::ItemFn(lower_fn_decl(lctx, decl),
677                         lower_unsafety(lctx, unsafety),
678                         lower_constness(lctx, constness),
679                         abi,
680                         lower_generics(lctx, generics),
681                         lower_block(lctx, body))
682         }
683         ItemKind::Mod(ref m) => hir::ItemMod(lower_mod(lctx, m)),
684         ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(lctx, nm)),
685         ItemKind::Ty(ref t, ref generics) => {
686             hir::ItemTy(lower_ty(lctx, t), lower_generics(lctx, generics))
687         }
688         ItemKind::Enum(ref enum_definition, ref generics) => {
689             hir::ItemEnum(hir::EnumDef {
690                               variants: enum_definition.variants
691                                                        .iter()
692                                                        .map(|x| lower_variant(lctx, x))
693                                                        .collect(),
694                           },
695                           lower_generics(lctx, generics))
696         }
697         ItemKind::Struct(ref struct_def, ref generics) => {
698             let struct_def = lower_variant_data(lctx, struct_def);
699             hir::ItemStruct(struct_def, lower_generics(lctx, generics))
700         }
701         ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
702             hir::ItemDefaultImpl(lower_unsafety(lctx, unsafety),
703                                  lower_trait_ref(lctx, trait_ref))
704         }
705         ItemKind::Impl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
706             let new_impl_items = impl_items.iter()
707                                            .map(|item| lower_impl_item(lctx, item))
708                                            .collect();
709             let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(lctx, trait_ref));
710             hir::ItemImpl(lower_unsafety(lctx, unsafety),
711                           lower_impl_polarity(lctx, polarity),
712                           lower_generics(lctx, generics),
713                           ifce,
714                           lower_ty(lctx, ty),
715                           new_impl_items)
716         }
717         ItemKind::Trait(unsafety, ref generics, ref bounds, ref items) => {
718             let bounds = lower_bounds(lctx, bounds);
719             let items = items.iter().map(|item| lower_trait_item(lctx, item)).collect();
720             hir::ItemTrait(lower_unsafety(lctx, unsafety),
721                            lower_generics(lctx, generics),
722                            bounds,
723                            items)
724         }
725         ItemKind::Mac(_) => panic!("Shouldn't still be around"),
726     }
727 }
728
729 pub fn lower_trait_item(lctx: &LoweringContext, i: &TraitItem) -> hir::TraitItem {
730     hir::TraitItem {
731         id: i.id,
732         name: i.ident.name,
733         attrs: lower_attrs(lctx, &i.attrs),
734         node: match i.node {
735             TraitItemKind::Const(ref ty, ref default) => {
736                 hir::ConstTraitItem(lower_ty(lctx, ty),
737                                     default.as_ref().map(|x| lower_expr(lctx, x)))
738             }
739             TraitItemKind::Method(ref sig, ref body) => {
740                 hir::MethodTraitItem(lower_method_sig(lctx, sig),
741                                      body.as_ref().map(|x| lower_block(lctx, x)))
742             }
743             TraitItemKind::Type(ref bounds, ref default) => {
744                 hir::TypeTraitItem(lower_bounds(lctx, bounds),
745                                    default.as_ref().map(|x| lower_ty(lctx, x)))
746             }
747         },
748         span: i.span,
749     }
750 }
751
752 pub fn lower_impl_item(lctx: &LoweringContext, i: &ImplItem) -> hir::ImplItem {
753     hir::ImplItem {
754         id: i.id,
755         name: i.ident.name,
756         attrs: lower_attrs(lctx, &i.attrs),
757         vis: lower_visibility(lctx, i.vis),
758         node: match i.node {
759             ImplItemKind::Const(ref ty, ref expr) => {
760                 hir::ImplItemKind::Const(lower_ty(lctx, ty), lower_expr(lctx, expr))
761             }
762             ImplItemKind::Method(ref sig, ref body) => {
763                 hir::ImplItemKind::Method(lower_method_sig(lctx, sig), lower_block(lctx, body))
764             }
765             ImplItemKind::Type(ref ty) => hir::ImplItemKind::Type(lower_ty(lctx, ty)),
766             ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
767         },
768         span: i.span,
769     }
770 }
771
772 pub fn lower_mod(lctx: &LoweringContext, m: &Mod) -> hir::Mod {
773     hir::Mod {
774         inner: m.inner,
775         item_ids: m.items.iter().map(|x| lower_item_id(lctx, x)).collect(),
776     }
777 }
778
779 struct ItemLowerer<'lcx, 'interner: 'lcx> {
780     items: BTreeMap<NodeId, hir::Item>,
781     lctx: &'lcx LoweringContext<'interner>,
782 }
783
784 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
785     fn visit_item(&mut self, item: &'lcx Item) {
786         self.items.insert(item.id, lower_item(self.lctx, item));
787         visit::walk_item(self, item);
788     }
789 }
790
791 pub fn lower_crate(lctx: &LoweringContext, c: &Crate) -> hir::Crate {
792     let items = {
793         let mut item_lowerer = ItemLowerer { items: BTreeMap::new(), lctx: lctx };
794         visit::walk_crate(&mut item_lowerer, c);
795         item_lowerer.items
796     };
797
798     hir::Crate {
799         module: lower_mod(lctx, &c.module),
800         attrs: lower_attrs(lctx, &c.attrs),
801         config: c.config.clone().into(),
802         span: c.span,
803         exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(lctx, m)).collect(),
804         items: items,
805     }
806 }
807
808 pub fn lower_macro_def(lctx: &LoweringContext, m: &MacroDef) -> hir::MacroDef {
809     hir::MacroDef {
810         name: m.ident.name,
811         attrs: lower_attrs(lctx, &m.attrs),
812         id: m.id,
813         span: m.span,
814         imported_from: m.imported_from.map(|x| x.name),
815         export: m.export,
816         use_locally: m.use_locally,
817         allow_internal_unstable: m.allow_internal_unstable,
818         body: m.body.clone().into(),
819     }
820 }
821
822 pub fn lower_item_id(_lctx: &LoweringContext, i: &Item) -> hir::ItemId {
823     hir::ItemId { id: i.id }
824 }
825
826 pub fn lower_item(lctx: &LoweringContext, i: &Item) -> hir::Item {
827     let node = lower_item_kind(lctx, &i.node);
828
829     hir::Item {
830         id: i.id,
831         name: i.ident.name,
832         attrs: lower_attrs(lctx, &i.attrs),
833         node: node,
834         vis: lower_visibility(lctx, i.vis),
835         span: i.span,
836     }
837 }
838
839 pub fn lower_foreign_item(lctx: &LoweringContext, i: &ForeignItem) -> hir::ForeignItem {
840     hir::ForeignItem {
841         id: i.id,
842         name: i.ident.name,
843         attrs: lower_attrs(lctx, &i.attrs),
844         node: match i.node {
845             ForeignItemKind::Fn(ref fdec, ref generics) => {
846                 hir::ForeignItemFn(lower_fn_decl(lctx, fdec), lower_generics(lctx, generics))
847             }
848             ForeignItemKind::Static(ref t, m) => {
849                 hir::ForeignItemStatic(lower_ty(lctx, t), m)
850             }
851         },
852         vis: lower_visibility(lctx, i.vis),
853         span: i.span,
854     }
855 }
856
857 pub fn lower_method_sig(lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig {
858     hir::MethodSig {
859         generics: lower_generics(lctx, &sig.generics),
860         abi: sig.abi,
861         explicit_self: lower_explicit_self(lctx, &sig.explicit_self),
862         unsafety: lower_unsafety(lctx, sig.unsafety),
863         constness: lower_constness(lctx, sig.constness),
864         decl: lower_fn_decl(lctx, &sig.decl),
865     }
866 }
867
868 pub fn lower_unsafety(_lctx: &LoweringContext, u: Unsafety) -> hir::Unsafety {
869     match u {
870         Unsafety::Unsafe => hir::Unsafety::Unsafe,
871         Unsafety::Normal => hir::Unsafety::Normal,
872     }
873 }
874
875 pub fn lower_constness(_lctx: &LoweringContext, c: Constness) -> hir::Constness {
876     match c {
877         Constness::Const => hir::Constness::Const,
878         Constness::NotConst => hir::Constness::NotConst,
879     }
880 }
881
882 pub fn lower_unop(_lctx: &LoweringContext, u: UnOp) -> hir::UnOp {
883     match u {
884         UnOp::Deref => hir::UnDeref,
885         UnOp::Not => hir::UnNot,
886         UnOp::Neg => hir::UnNeg,
887     }
888 }
889
890 pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp {
891     Spanned {
892         node: match b.node {
893             BinOpKind::Add => hir::BiAdd,
894             BinOpKind::Sub => hir::BiSub,
895             BinOpKind::Mul => hir::BiMul,
896             BinOpKind::Div => hir::BiDiv,
897             BinOpKind::Rem => hir::BiRem,
898             BinOpKind::And => hir::BiAnd,
899             BinOpKind::Or => hir::BiOr,
900             BinOpKind::BitXor => hir::BiBitXor,
901             BinOpKind::BitAnd => hir::BiBitAnd,
902             BinOpKind::BitOr => hir::BiBitOr,
903             BinOpKind::Shl => hir::BiShl,
904             BinOpKind::Shr => hir::BiShr,
905             BinOpKind::Eq => hir::BiEq,
906             BinOpKind::Lt => hir::BiLt,
907             BinOpKind::Le => hir::BiLe,
908             BinOpKind::Ne => hir::BiNe,
909             BinOpKind::Ge => hir::BiGe,
910             BinOpKind::Gt => hir::BiGt,
911         },
912         span: b.span,
913     }
914 }
915
916 pub fn lower_pat(lctx: &LoweringContext, p: &Pat) -> P<hir::Pat> {
917     P(hir::Pat {
918         id: p.id,
919         node: match p.node {
920             PatKind::Wild => hir::PatKind::Wild,
921             PatKind::Ident(ref binding_mode, pth1, ref sub) => {
922                 hir::PatKind::Ident(lower_binding_mode(lctx, binding_mode),
923                               respan(pth1.span, lower_ident(lctx, pth1.node)),
924                               sub.as_ref().map(|x| lower_pat(lctx, x)))
925             }
926             PatKind::Lit(ref e) => hir::PatKind::Lit(lower_expr(lctx, e)),
927             PatKind::TupleStruct(ref pth, ref pats) => {
928                 hir::PatKind::TupleStruct(lower_path(lctx, pth),
929                              pats.as_ref()
930                                  .map(|pats| pats.iter().map(|x| lower_pat(lctx, x)).collect()))
931             }
932             PatKind::Path(ref pth) => {
933                 hir::PatKind::Path(lower_path(lctx, pth))
934             }
935             PatKind::QPath(ref qself, ref pth) => {
936                 let qself = hir::QSelf {
937                     ty: lower_ty(lctx, &qself.ty),
938                     position: qself.position,
939                 };
940                 hir::PatKind::QPath(qself, lower_path(lctx, pth))
941             }
942             PatKind::Struct(ref pth, ref fields, etc) => {
943                 let pth = lower_path(lctx, pth);
944                 let fs = fields.iter()
945                                .map(|f| {
946                                    Spanned {
947                                        span: f.span,
948                                        node: hir::FieldPat {
949                                            name: f.node.ident.name,
950                                            pat: lower_pat(lctx, &f.node.pat),
951                                            is_shorthand: f.node.is_shorthand,
952                                        },
953                                    }
954                                })
955                                .collect();
956                 hir::PatKind::Struct(pth, fs, etc)
957             }
958             PatKind::Tup(ref elts) => {
959                 hir::PatKind::Tup(elts.iter().map(|x| lower_pat(lctx, x)).collect())
960             }
961             PatKind::Box(ref inner) => hir::PatKind::Box(lower_pat(lctx, inner)),
962             PatKind::Ref(ref inner, mutbl) => {
963                 hir::PatKind::Ref(lower_pat(lctx, inner), lower_mutability(lctx, mutbl))
964             }
965             PatKind::Range(ref e1, ref e2) => {
966                 hir::PatKind::Range(lower_expr(lctx, e1), lower_expr(lctx, e2))
967             }
968             PatKind::Vec(ref before, ref slice, ref after) => {
969                 hir::PatKind::Vec(before.iter().map(|x| lower_pat(lctx, x)).collect(),
970                             slice.as_ref().map(|x| lower_pat(lctx, x)),
971                             after.iter().map(|x| lower_pat(lctx, x)).collect())
972             }
973             PatKind::Mac(_) => panic!("Shouldn't exist here"),
974         },
975         span: p.span,
976     })
977 }
978
979 pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
980     P(hir::Expr {
981         id: e.id,
982         node: match e.node {
983             // Issue #22181:
984             // Eventually a desugaring for `box EXPR`
985             // (similar to the desugaring above for `in PLACE BLOCK`)
986             // should go here, desugaring
987             //
988             // to:
989             //
990             // let mut place = BoxPlace::make_place();
991             // let raw_place = Place::pointer(&mut place);
992             // let value = $value;
993             // unsafe {
994             //     ::std::ptr::write(raw_place, value);
995             //     Boxed::finalize(place)
996             // }
997             //
998             // But for now there are type-inference issues doing that.
999             ExprKind::Box(ref e) => {
1000                 hir::ExprBox(lower_expr(lctx, e))
1001             }
1002
1003             // Desugar ExprBox: `in (PLACE) EXPR`
1004             ExprKind::InPlace(ref placer, ref value_expr) => {
1005                 // to:
1006                 //
1007                 // let p = PLACE;
1008                 // let mut place = Placer::make_place(p);
1009                 // let raw_place = Place::pointer(&mut place);
1010                 // push_unsafe!({
1011                 //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1012                 //     InPlace::finalize(place)
1013                 // })
1014                 return cache_ids(lctx, e.id, |lctx| {
1015                     let placer_expr = lower_expr(lctx, placer);
1016                     let value_expr = lower_expr(lctx, value_expr);
1017
1018                     let placer_ident = lctx.str_to_ident("placer");
1019                     let place_ident = lctx.str_to_ident("place");
1020                     let p_ptr_ident = lctx.str_to_ident("p_ptr");
1021
1022                     let make_place = ["ops", "Placer", "make_place"];
1023                     let place_pointer = ["ops", "Place", "pointer"];
1024                     let move_val_init = ["intrinsics", "move_val_init"];
1025                     let inplace_finalize = ["ops", "InPlace", "finalize"];
1026
1027                     let make_call = |lctx: &LoweringContext, p, args| {
1028                         let path = core_path(lctx, e.span, p);
1029                         let path = expr_path(lctx, path, None);
1030                         expr_call(lctx, e.span, path, args, None)
1031                     };
1032
1033                     let mk_stmt_let = |lctx: &LoweringContext, bind, expr| {
1034                         stmt_let(lctx, e.span, false, bind, expr, None)
1035                     };
1036
1037                     let mk_stmt_let_mut = |lctx: &LoweringContext, bind, expr| {
1038                         stmt_let(lctx, e.span, true, bind, expr, None)
1039                     };
1040
1041                     // let placer = <placer_expr> ;
1042                     let s1 = {
1043                         let placer_expr = signal_block_expr(lctx,
1044                                                             hir_vec![],
1045                                                             placer_expr,
1046                                                             e.span,
1047                                                             hir::PopUnstableBlock,
1048                                                             None);
1049                         mk_stmt_let(lctx, placer_ident, placer_expr)
1050                     };
1051
1052                     // let mut place = Placer::make_place(placer);
1053                     let s2 = {
1054                         let placer = expr_ident(lctx, e.span, placer_ident, None);
1055                         let call = make_call(lctx, &make_place, hir_vec![placer]);
1056                         mk_stmt_let_mut(lctx, place_ident, call)
1057                     };
1058
1059                     // let p_ptr = Place::pointer(&mut place);
1060                     let s3 = {
1061                         let agent = expr_ident(lctx, e.span, place_ident, None);
1062                         let args = hir_vec![expr_mut_addr_of(lctx, e.span, agent, None)];
1063                         let call = make_call(lctx, &place_pointer, args);
1064                         mk_stmt_let(lctx, p_ptr_ident, call)
1065                     };
1066
1067                     // pop_unsafe!(EXPR));
1068                     let pop_unsafe_expr = {
1069                         let value_expr = signal_block_expr(lctx,
1070                                                            hir_vec![],
1071                                                            value_expr,
1072                                                            e.span,
1073                                                            hir::PopUnstableBlock,
1074                                                            None);
1075                         signal_block_expr(lctx,
1076                                           hir_vec![],
1077                                           value_expr,
1078                                           e.span,
1079                                           hir::PopUnsafeBlock(hir::CompilerGenerated), None)
1080                     };
1081
1082                     // push_unsafe!({
1083                     //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1084                     //     InPlace::finalize(place)
1085                     // })
1086                     let expr = {
1087                         let ptr = expr_ident(lctx, e.span, p_ptr_ident, None);
1088                         let call_move_val_init =
1089                             hir::StmtSemi(
1090                                 make_call(lctx, &move_val_init, hir_vec![ptr, pop_unsafe_expr]),
1091                                 lctx.next_id());
1092                         let call_move_val_init = respan(e.span, call_move_val_init);
1093
1094                         let place = expr_ident(lctx, e.span, place_ident, None);
1095                         let call = make_call(lctx, &inplace_finalize, hir_vec![place]);
1096                         signal_block_expr(lctx,
1097                                           hir_vec![call_move_val_init],
1098                                           call,
1099                                           e.span,
1100                                           hir::PushUnsafeBlock(hir::CompilerGenerated), None)
1101                     };
1102
1103                     signal_block_expr(lctx,
1104                                       hir_vec![s1, s2, s3],
1105                                       expr,
1106                                       e.span,
1107                                       hir::PushUnstableBlock,
1108                                       e.attrs.clone())
1109                 });
1110             }
1111
1112             ExprKind::Vec(ref exprs) => {
1113                 hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect())
1114             }
1115             ExprKind::Repeat(ref expr, ref count) => {
1116                 let expr = lower_expr(lctx, expr);
1117                 let count = lower_expr(lctx, count);
1118                 hir::ExprRepeat(expr, count)
1119             }
1120             ExprKind::Tup(ref elts) => {
1121                 hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect())
1122             }
1123             ExprKind::Call(ref f, ref args) => {
1124                 let f = lower_expr(lctx, f);
1125                 hir::ExprCall(f, args.iter().map(|x| lower_expr(lctx, x)).collect())
1126             }
1127             ExprKind::MethodCall(i, ref tps, ref args) => {
1128                 let tps = tps.iter().map(|x| lower_ty(lctx, x)).collect();
1129                 let args = args.iter().map(|x| lower_expr(lctx, x)).collect();
1130                 hir::ExprMethodCall(respan(i.span, i.node.name), tps, args)
1131             }
1132             ExprKind::Binary(binop, ref lhs, ref rhs) => {
1133                 let binop = lower_binop(lctx, binop);
1134                 let lhs = lower_expr(lctx, lhs);
1135                 let rhs = lower_expr(lctx, rhs);
1136                 hir::ExprBinary(binop, lhs, rhs)
1137             }
1138             ExprKind::Unary(op, ref ohs) => {
1139                 let op = lower_unop(lctx, op);
1140                 let ohs = lower_expr(lctx, ohs);
1141                 hir::ExprUnary(op, ohs)
1142             }
1143             ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
1144             ExprKind::Cast(ref expr, ref ty) => {
1145                 let expr = lower_expr(lctx, expr);
1146                 hir::ExprCast(expr, lower_ty(lctx, ty))
1147             }
1148             ExprKind::Type(ref expr, ref ty) => {
1149                 let expr = lower_expr(lctx, expr);
1150                 hir::ExprType(expr, lower_ty(lctx, ty))
1151             }
1152             ExprKind::AddrOf(m, ref ohs) => {
1153                 let m = lower_mutability(lctx, m);
1154                 let ohs = lower_expr(lctx, ohs);
1155                 hir::ExprAddrOf(m, ohs)
1156             }
1157             // More complicated than you might expect because the else branch
1158             // might be `if let`.
1159             ExprKind::If(ref cond, ref blk, ref else_opt) => {
1160                 let else_opt = else_opt.as_ref().map(|els| {
1161                     match els.node {
1162                         ExprKind::IfLet(..) => {
1163                             cache_ids(lctx, e.id, |lctx| {
1164                                 // wrap the if-let expr in a block
1165                                 let span = els.span;
1166                                 let els = lower_expr(lctx, els);
1167                                 let id = lctx.next_id();
1168                                 let blk = P(hir::Block {
1169                                     stmts: hir_vec![],
1170                                     expr: Some(els),
1171                                     id: id,
1172                                     rules: hir::DefaultBlock,
1173                                     span: span,
1174                                 });
1175                                 expr_block(lctx, blk, None)
1176                             })
1177                         }
1178                         _ => lower_expr(lctx, els),
1179                     }
1180                 });
1181
1182                 hir::ExprIf(lower_expr(lctx, cond), lower_block(lctx, blk), else_opt)
1183             }
1184             ExprKind::While(ref cond, ref body, opt_ident) => {
1185                 hir::ExprWhile(lower_expr(lctx, cond), lower_block(lctx, body),
1186                                opt_ident.map(|ident| lower_ident(lctx, ident)))
1187             }
1188             ExprKind::Loop(ref body, opt_ident) => {
1189                 hir::ExprLoop(lower_block(lctx, body),
1190                               opt_ident.map(|ident| lower_ident(lctx, ident)))
1191             }
1192             ExprKind::Match(ref expr, ref arms) => {
1193                 hir::ExprMatch(lower_expr(lctx, expr),
1194                                arms.iter().map(|x| lower_arm(lctx, x)).collect(),
1195                                hir::MatchSource::Normal)
1196             }
1197             ExprKind::Closure(capture_clause, ref decl, ref body) => {
1198                 hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
1199                                  lower_fn_decl(lctx, decl),
1200                                  lower_block(lctx, body))
1201             }
1202             ExprKind::Block(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
1203             ExprKind::Assign(ref el, ref er) => {
1204                 hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
1205             }
1206             ExprKind::AssignOp(op, ref el, ref er) => {
1207                 hir::ExprAssignOp(lower_binop(lctx, op),
1208                                   lower_expr(lctx, el),
1209                                   lower_expr(lctx, er))
1210             }
1211             ExprKind::Field(ref el, ident) => {
1212                 hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name))
1213             }
1214             ExprKind::TupField(ref el, ident) => {
1215                 hir::ExprTupField(lower_expr(lctx, el), ident)
1216             }
1217             ExprKind::Index(ref el, ref er) => {
1218                 hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
1219             }
1220             ExprKind::Range(ref e1, ref e2) => {
1221                 hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)),
1222                                e2.as_ref().map(|x| lower_expr(lctx, x)))
1223             }
1224             ExprKind::Path(ref qself, ref path) => {
1225                 let hir_qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
1226                     hir::QSelf {
1227                         ty: lower_ty(lctx, ty),
1228                         position: position,
1229                     }
1230                 });
1231                 hir::ExprPath(hir_qself, lower_path_full(lctx, path, qself.is_none()))
1232             }
1233             ExprKind::Break(opt_ident) => hir::ExprBreak(opt_ident.map(|sp_ident| {
1234                 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1235             })),
1236             ExprKind::Again(opt_ident) => hir::ExprAgain(opt_ident.map(|sp_ident| {
1237                 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1238             })),
1239             ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
1240             ExprKind::InlineAsm(InlineAsm {
1241                     ref inputs,
1242                     ref outputs,
1243                     ref asm,
1244                     asm_str_style,
1245                     ref clobbers,
1246                     volatile,
1247                     alignstack,
1248                     dialect,
1249                     expn_id,
1250                 }) => hir::ExprInlineAsm(hir::InlineAsm {
1251                 inputs: inputs.iter()
1252                               .map(|&(ref c, ref input)| (c.clone(), lower_expr(lctx, input)))
1253                               .collect(),
1254                 outputs: outputs.iter()
1255                                 .map(|out| {
1256                                     hir::InlineAsmOutput {
1257                                         constraint: out.constraint.clone(),
1258                                         expr: lower_expr(lctx, &out.expr),
1259                                         is_rw: out.is_rw,
1260                                         is_indirect: out.is_indirect,
1261                                     }
1262                                 })
1263                                 .collect(),
1264                 asm: asm.clone(),
1265                 asm_str_style: asm_str_style,
1266                 clobbers: clobbers.clone().into(),
1267                 volatile: volatile,
1268                 alignstack: alignstack,
1269                 dialect: dialect,
1270                 expn_id: expn_id,
1271             }),
1272             ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
1273                 hir::ExprStruct(lower_path(lctx, path),
1274                                 fields.iter().map(|x| lower_field(lctx, x)).collect(),
1275                                 maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
1276             }
1277             ExprKind::Paren(ref ex) => {
1278                 // merge attributes into the inner expression.
1279                 return lower_expr(lctx, ex).map(|mut ex| {
1280                     ex.attrs.update(|attrs| {
1281                         attrs.prepend(e.attrs.clone())
1282                     });
1283                     ex
1284                 });
1285             }
1286
1287             // Desugar ExprIfLet
1288             // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
1289             ExprKind::IfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
1290                 // to:
1291                 //
1292                 //   match <sub_expr> {
1293                 //     <pat> => <body>,
1294                 //     [_ if <else_opt_if_cond> => <else_opt_if_body>,]
1295                 //     _ => [<else_opt> | ()]
1296                 //   }
1297
1298                 return cache_ids(lctx, e.id, |lctx| {
1299                     // `<pat> => <body>`
1300                     let pat_arm = {
1301                         let body = lower_block(lctx, body);
1302                         let body_expr = expr_block(lctx, body, None);
1303                         arm(hir_vec![lower_pat(lctx, pat)], body_expr)
1304                     };
1305
1306                     // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
1307                     let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e));
1308                     let else_if_arms = {
1309                         let mut arms = vec![];
1310                         loop {
1311                             let else_opt_continue = else_opt.and_then(|els| {
1312                                 els.and_then(|els| {
1313                                     match els.node {
1314                                         // else if
1315                                         hir::ExprIf(cond, then, else_opt) => {
1316                                             let pat_under = pat_wild(lctx, e.span);
1317                                             arms.push(hir::Arm {
1318                                                 attrs: hir_vec![],
1319                                                 pats: hir_vec![pat_under],
1320                                                 guard: Some(cond),
1321                                                 body: expr_block(lctx, then, None),
1322                                             });
1323                                             else_opt.map(|else_opt| (else_opt, true))
1324                                         }
1325                                         _ => Some((P(els), false)),
1326                                     }
1327                                 })
1328                             });
1329                             match else_opt_continue {
1330                                 Some((e, true)) => {
1331                                     else_opt = Some(e);
1332                                 }
1333                                 Some((e, false)) => {
1334                                     else_opt = Some(e);
1335                                     break;
1336                                 }
1337                                 None => {
1338                                     else_opt = None;
1339                                     break;
1340                                 }
1341                             }
1342                         }
1343                         arms
1344                     };
1345
1346                     let contains_else_clause = else_opt.is_some();
1347
1348                     // `_ => [<else_opt> | ()]`
1349                     let else_arm = {
1350                         let pat_under = pat_wild(lctx, e.span);
1351                         let else_expr =
1352                             else_opt.unwrap_or_else(
1353                                 || expr_tuple(lctx, e.span, hir_vec![], None));
1354                         arm(hir_vec![pat_under], else_expr)
1355                     };
1356
1357                     let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
1358                     arms.push(pat_arm);
1359                     arms.extend(else_if_arms);
1360                     arms.push(else_arm);
1361
1362                     let sub_expr = lower_expr(lctx, sub_expr);
1363                     // add attributes to the outer returned expr node
1364                     expr(lctx,
1365                          e.span,
1366                          hir::ExprMatch(sub_expr,
1367                                         arms.into(),
1368                                         hir::MatchSource::IfLetDesugar {
1369                                             contains_else_clause: contains_else_clause,
1370                                         }),
1371                          e.attrs.clone())
1372                 });
1373             }
1374
1375             // Desugar ExprWhileLet
1376             // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
1377             ExprKind::WhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
1378                 // to:
1379                 //
1380                 //   [opt_ident]: loop {
1381                 //     match <sub_expr> {
1382                 //       <pat> => <body>,
1383                 //       _ => break
1384                 //     }
1385                 //   }
1386
1387                 return cache_ids(lctx, e.id, |lctx| {
1388                     // `<pat> => <body>`
1389                     let pat_arm = {
1390                         let body = lower_block(lctx, body);
1391                         let body_expr = expr_block(lctx, body, None);
1392                         arm(hir_vec![lower_pat(lctx, pat)], body_expr)
1393                     };
1394
1395                     // `_ => break`
1396                     let break_arm = {
1397                         let pat_under = pat_wild(lctx, e.span);
1398                         let break_expr = expr_break(lctx, e.span, None);
1399                         arm(hir_vec![pat_under], break_expr)
1400                     };
1401
1402                     // `match <sub_expr> { ... }`
1403                     let arms = hir_vec![pat_arm, break_arm];
1404                     let sub_expr = lower_expr(lctx, sub_expr);
1405                     let match_expr = expr(lctx,
1406                                           e.span,
1407                                           hir::ExprMatch(sub_expr,
1408                                                          arms,
1409                                                          hir::MatchSource::WhileLetDesugar),
1410                                           None);
1411
1412                     // `[opt_ident]: loop { ... }`
1413                     let loop_block = block_expr(lctx, match_expr);
1414                     let loop_expr = hir::ExprLoop(loop_block,
1415                                                   opt_ident.map(|ident| lower_ident(lctx, ident)));
1416                     // add attributes to the outer returned expr node
1417                     expr(lctx, e.span, loop_expr, e.attrs.clone())
1418                 });
1419             }
1420
1421             // Desugar ExprForLoop
1422             // From: `[opt_ident]: for <pat> in <head> <body>`
1423             ExprKind::ForLoop(ref pat, ref head, ref body, opt_ident) => {
1424                 // to:
1425                 //
1426                 //   {
1427                 //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1428                 //       mut iter => {
1429                 //         [opt_ident]: loop {
1430                 //           match ::std::iter::Iterator::next(&mut iter) {
1431                 //             ::std::option::Option::Some(<pat>) => <body>,
1432                 //             ::std::option::Option::None => break
1433                 //           }
1434                 //         }
1435                 //       }
1436                 //     };
1437                 //     result
1438                 //   }
1439
1440                 return cache_ids(lctx, e.id, |lctx| {
1441                     // expand <head>
1442                     let head = lower_expr(lctx, head);
1443
1444                     let iter = lctx.str_to_ident("iter");
1445
1446                     // `::std::option::Option::Some(<pat>) => <body>`
1447                     let pat_arm = {
1448                         let body_block = lower_block(lctx, body);
1449                         let body_span = body_block.span;
1450                         let body_expr = P(hir::Expr {
1451                             id: lctx.next_id(),
1452                             node: hir::ExprBlock(body_block),
1453                             span: body_span,
1454                             attrs: None,
1455                         });
1456                         let pat = lower_pat(lctx, pat);
1457                         let some_pat = pat_some(lctx, e.span, pat);
1458
1459                         arm(hir_vec![some_pat], body_expr)
1460                     };
1461
1462                     // `::std::option::Option::None => break`
1463                     let break_arm = {
1464                         let break_expr = expr_break(lctx, e.span, None);
1465
1466                         arm(hir_vec![pat_none(lctx, e.span)], break_expr)
1467                     };
1468
1469                     // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1470                     let match_expr = {
1471                         let next_path = {
1472                             let strs = std_path(lctx, &["iter", "Iterator", "next"]);
1473
1474                             path_global(e.span, strs)
1475                         };
1476                         let iter = expr_ident(lctx, e.span, iter, None);
1477                         let ref_mut_iter = expr_mut_addr_of(lctx, e.span, iter, None);
1478                         let next_path = expr_path(lctx, next_path, None);
1479                         let next_expr = expr_call(lctx,
1480                                                   e.span,
1481                                                   next_path,
1482                                                   hir_vec![ref_mut_iter],
1483                                                   None);
1484                         let arms = hir_vec![pat_arm, break_arm];
1485
1486                         expr(lctx,
1487                              e.span,
1488                              hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
1489                              None)
1490                     };
1491
1492                     // `[opt_ident]: loop { ... }`
1493                     let loop_block = block_expr(lctx, match_expr);
1494                     let loop_expr = hir::ExprLoop(loop_block,
1495                                                   opt_ident.map(|ident| lower_ident(lctx, ident)));
1496                     let loop_expr = expr(lctx, e.span, loop_expr, None);
1497
1498                     // `mut iter => { ... }`
1499                     let iter_arm = {
1500                         let iter_pat = pat_ident_binding_mode(lctx,
1501                                                               e.span,
1502                                                               iter,
1503                                                               hir::BindByValue(hir::MutMutable));
1504                         arm(hir_vec![iter_pat], loop_expr)
1505                     };
1506
1507                     // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1508                     let into_iter_expr = {
1509                         let into_iter_path = {
1510                             let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
1511
1512                             path_global(e.span, strs)
1513                         };
1514
1515                         let into_iter = expr_path(lctx, into_iter_path, None);
1516                         expr_call(lctx, e.span, into_iter, hir_vec![head], None)
1517                     };
1518
1519                     let match_expr = expr_match(lctx,
1520                                                 e.span,
1521                                                 into_iter_expr,
1522                                                 hir_vec![iter_arm],
1523                                                 hir::MatchSource::ForLoopDesugar,
1524                                                 None);
1525
1526                     // `{ let _result = ...; _result }`
1527                     // underscore prevents an unused_variables lint if the head diverges
1528                     let result_ident = lctx.str_to_ident("_result");
1529                     let let_stmt = stmt_let(lctx, e.span, false, result_ident, match_expr, None);
1530                     let result = expr_ident(lctx, e.span, result_ident, None);
1531                     let block = block_all(lctx, e.span, hir_vec![let_stmt], Some(result));
1532                     // add the attributes to the outer returned expr node
1533                     expr_block(lctx, block, e.attrs.clone())
1534                 });
1535             }
1536
1537             ExprKind::Mac(_) => panic!("Shouldn't exist here"),
1538         },
1539         span: e.span,
1540         attrs: e.attrs.clone(),
1541     })
1542 }
1543
1544 pub fn lower_stmt(lctx: &LoweringContext, s: &Stmt) -> hir::Stmt {
1545     match s.node {
1546         StmtKind::Decl(ref d, id) => {
1547             Spanned {
1548                 node: hir::StmtDecl(lower_decl(lctx, d), id),
1549                 span: s.span,
1550             }
1551         }
1552         StmtKind::Expr(ref e, id) => {
1553             Spanned {
1554                 node: hir::StmtExpr(lower_expr(lctx, e), id),
1555                 span: s.span,
1556             }
1557         }
1558         StmtKind::Semi(ref e, id) => {
1559             Spanned {
1560                 node: hir::StmtSemi(lower_expr(lctx, e), id),
1561                 span: s.span,
1562             }
1563         }
1564         StmtKind::Mac(..) => panic!("Shouldn't exist here"),
1565     }
1566 }
1567
1568 pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureBy) -> hir::CaptureClause {
1569     match c {
1570         CaptureBy::Value => hir::CaptureByValue,
1571         CaptureBy::Ref => hir::CaptureByRef,
1572     }
1573 }
1574
1575 pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1576     match v {
1577         Visibility::Public => hir::Public,
1578         Visibility::Inherited => hir::Inherited,
1579     }
1580 }
1581
1582 pub fn lower_block_check_mode(lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1583     match *b {
1584         BlockCheckMode::Default => hir::DefaultBlock,
1585         BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(lower_unsafe_source(lctx, u)),
1586     }
1587 }
1588
1589 pub fn lower_binding_mode(lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1590     match *b {
1591         BindingMode::ByRef(m) => hir::BindByRef(lower_mutability(lctx, m)),
1592         BindingMode::ByValue(m) => hir::BindByValue(lower_mutability(lctx, m)),
1593     }
1594 }
1595
1596 pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1597     match u {
1598         CompilerGenerated => hir::CompilerGenerated,
1599         UserProvided => hir::UserProvided,
1600     }
1601 }
1602
1603 pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1604     match i {
1605         ImplPolarity::Positive => hir::ImplPolarity::Positive,
1606         ImplPolarity::Negative => hir::ImplPolarity::Negative,
1607     }
1608 }
1609
1610 pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
1611                                   f: TraitBoundModifier)
1612                                   -> hir::TraitBoundModifier {
1613     match f {
1614         TraitBoundModifier::None => hir::TraitBoundModifier::None,
1615         TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
1616     }
1617 }
1618
1619 // Helper methods for building HIR.
1620
1621 fn arm(pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1622     hir::Arm {
1623         attrs: hir_vec![],
1624         pats: pats,
1625         guard: None,
1626         body: expr,
1627     }
1628 }
1629
1630 fn expr_break(lctx: &LoweringContext, span: Span,
1631               attrs: ThinAttributes) -> P<hir::Expr> {
1632     expr(lctx, span, hir::ExprBreak(None), attrs)
1633 }
1634
1635 fn expr_call(lctx: &LoweringContext,
1636              span: Span,
1637              e: P<hir::Expr>,
1638              args: hir::HirVec<P<hir::Expr>>,
1639              attrs: ThinAttributes)
1640              -> P<hir::Expr> {
1641     expr(lctx, span, hir::ExprCall(e, args), attrs)
1642 }
1643
1644 fn expr_ident(lctx: &LoweringContext, span: Span, id: hir::Ident,
1645               attrs: ThinAttributes) -> P<hir::Expr> {
1646     expr_path(lctx, path_ident(span, id), attrs)
1647 }
1648
1649 fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>,
1650                     attrs: ThinAttributes) -> P<hir::Expr> {
1651     expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e), attrs)
1652 }
1653
1654 fn expr_path(lctx: &LoweringContext, path: hir::Path,
1655              attrs: ThinAttributes) -> P<hir::Expr> {
1656     expr(lctx, path.span, hir::ExprPath(None, path), attrs)
1657 }
1658
1659 fn expr_match(lctx: &LoweringContext,
1660               span: Span,
1661               arg: P<hir::Expr>,
1662               arms: hir::HirVec<hir::Arm>,
1663               source: hir::MatchSource,
1664               attrs: ThinAttributes)
1665               -> P<hir::Expr> {
1666     expr(lctx, span, hir::ExprMatch(arg, arms, source), attrs)
1667 }
1668
1669 fn expr_block(lctx: &LoweringContext, b: P<hir::Block>,
1670               attrs: ThinAttributes) -> P<hir::Expr> {
1671     expr(lctx, b.span, hir::ExprBlock(b), attrs)
1672 }
1673
1674 fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: hir::HirVec<P<hir::Expr>>,
1675               attrs: ThinAttributes) -> P<hir::Expr> {
1676     expr(lctx, sp, hir::ExprTup(exprs), attrs)
1677 }
1678
1679 fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_,
1680         attrs: ThinAttributes) -> P<hir::Expr> {
1681     P(hir::Expr {
1682         id: lctx.next_id(),
1683         node: node,
1684         span: span,
1685         attrs: attrs,
1686     })
1687 }
1688
1689 fn stmt_let(lctx: &LoweringContext,
1690             sp: Span,
1691             mutbl: bool,
1692             ident: hir::Ident,
1693             ex: P<hir::Expr>,
1694             attrs: ThinAttributes)
1695             -> hir::Stmt {
1696     let pat = if mutbl {
1697         pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
1698     } else {
1699         pat_ident(lctx, sp, ident)
1700     };
1701     let local = P(hir::Local {
1702         pat: pat,
1703         ty: None,
1704         init: Some(ex),
1705         id: lctx.next_id(),
1706         span: sp,
1707         attrs: attrs,
1708     });
1709     let decl = respan(sp, hir::DeclLocal(local));
1710     respan(sp, hir::StmtDecl(P(decl), lctx.next_id()))
1711 }
1712
1713 fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
1714     block_all(lctx, expr.span, hir::HirVec::new(), Some(expr))
1715 }
1716
1717 fn block_all(lctx: &LoweringContext,
1718              span: Span,
1719              stmts: hir::HirVec<hir::Stmt>,
1720              expr: Option<P<hir::Expr>>)
1721              -> P<hir::Block> {
1722     P(hir::Block {
1723         stmts: stmts,
1724         expr: expr,
1725         id: lctx.next_id(),
1726         rules: hir::DefaultBlock,
1727         span: span,
1728     })
1729 }
1730
1731 fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1732     let some = std_path(lctx, &["option", "Option", "Some"]);
1733     let path = path_global(span, some);
1734     pat_enum(lctx, span, path, hir_vec![pat])
1735 }
1736
1737 fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1738     let none = std_path(lctx, &["option", "Option", "None"]);
1739     let path = path_global(span, none);
1740     pat_enum(lctx, span, path, hir_vec![])
1741 }
1742
1743 fn pat_enum(lctx: &LoweringContext,
1744             span: Span,
1745             path: hir::Path,
1746             subpats: hir::HirVec<P<hir::Pat>>)
1747             -> P<hir::Pat> {
1748     let pt = if subpats.is_empty() {
1749         hir::PatKind::Path(path)
1750     } else {
1751         hir::PatKind::TupleStruct(path, Some(subpats))
1752     };
1753     pat(lctx, span, pt)
1754 }
1755
1756 fn pat_ident(lctx: &LoweringContext, span: Span, ident: hir::Ident) -> P<hir::Pat> {
1757     pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
1758 }
1759
1760 fn pat_ident_binding_mode(lctx: &LoweringContext,
1761                           span: Span,
1762                           ident: hir::Ident,
1763                           bm: hir::BindingMode)
1764                           -> P<hir::Pat> {
1765     let pat_ident = hir::PatKind::Ident(bm,
1766                                   Spanned {
1767                                       span: span,
1768                                       node: ident,
1769                                   },
1770                                   None);
1771     pat(lctx, span, pat_ident)
1772 }
1773
1774 fn pat_wild(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1775     pat(lctx, span, hir::PatKind::Wild)
1776 }
1777
1778 fn pat(lctx: &LoweringContext, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
1779     P(hir::Pat {
1780         id: lctx.next_id(),
1781         node: pat,
1782         span: span,
1783     })
1784 }
1785
1786 fn path_ident(span: Span, id: hir::Ident) -> hir::Path {
1787     path(span, vec![id])
1788 }
1789
1790 fn path(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1791     path_all(span, false, strs, hir::HirVec::new(), hir::HirVec::new(), hir::HirVec::new())
1792 }
1793
1794 fn path_global(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1795     path_all(span, true, strs, hir::HirVec::new(), hir::HirVec::new(), hir::HirVec::new())
1796 }
1797
1798 fn path_all(sp: Span,
1799             global: bool,
1800             mut idents: Vec<hir::Ident>,
1801             lifetimes: hir::HirVec<hir::Lifetime>,
1802             types: hir::HirVec<P<hir::Ty>>,
1803             bindings: hir::HirVec<hir::TypeBinding>)
1804             -> hir::Path {
1805     let last_identifier = idents.pop().unwrap();
1806     let mut segments: Vec<hir::PathSegment> = idents.into_iter()
1807                                                     .map(|ident| {
1808                                                         hir::PathSegment {
1809                                                             identifier: ident,
1810                                                             parameters: hir::PathParameters::none(),
1811                                                         }
1812                                                     })
1813                                                     .collect();
1814     segments.push(hir::PathSegment {
1815         identifier: last_identifier,
1816         parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1817             lifetimes: lifetimes,
1818             types: types,
1819             bindings: bindings,
1820         }),
1821     });
1822     hir::Path {
1823         span: sp,
1824         global: global,
1825         segments: segments.into(),
1826     }
1827 }
1828
1829 fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<hir::Ident> {
1830     let mut v = Vec::new();
1831     if let Some(s) = lctx.crate_root {
1832         v.push(hir::Ident::from_name(token::intern(s)));
1833     }
1834     v.extend(components.iter().map(|s| hir::Ident::from_name(token::intern(s))));
1835     return v;
1836 }
1837
1838 // Given suffix ["b","c","d"], returns path `::std::b::c::d` when
1839 // `fld.cx.use_std`, and `::core::b::c::d` otherwise.
1840 fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Path {
1841     let idents = std_path(lctx, components);
1842     path_global(span, idents)
1843 }
1844
1845 fn signal_block_expr(lctx: &LoweringContext,
1846                      stmts: hir::HirVec<hir::Stmt>,
1847                      expr: P<hir::Expr>,
1848                      span: Span,
1849                      rule: hir::BlockCheckMode,
1850                      attrs: ThinAttributes)
1851                      -> P<hir::Expr> {
1852     let id = lctx.next_id();
1853     expr_block(lctx,
1854                P(hir::Block {
1855                    rules: rule,
1856                    span: span,
1857                    id: id,
1858                    stmts: stmts,
1859                    expr: Some(expr),
1860                }),
1861                attrs)
1862 }
1863
1864
1865
1866 #[cfg(test)]
1867 mod test {
1868     use super::*;
1869     use syntax::ast::{self, NodeId, NodeIdAssigner};
1870     use syntax::{parse, codemap};
1871     use syntax::fold::Folder;
1872     use std::cell::Cell;
1873
1874     struct MockAssigner {
1875         next_id: Cell<NodeId>,
1876     }
1877
1878     impl MockAssigner {
1879         fn new() -> MockAssigner {
1880             MockAssigner { next_id: Cell::new(0) }
1881         }
1882     }
1883
1884     trait FakeExtCtxt {
1885         fn call_site(&self) -> codemap::Span;
1886         fn cfg(&self) -> ast::CrateConfig;
1887         fn ident_of(&self, st: &str) -> ast::Ident;
1888         fn name_of(&self, st: &str) -> ast::Name;
1889         fn parse_sess(&self) -> &parse::ParseSess;
1890     }
1891
1892     impl FakeExtCtxt for parse::ParseSess {
1893         fn call_site(&self) -> codemap::Span {
1894             codemap::Span {
1895                 lo: codemap::BytePos(0),
1896                 hi: codemap::BytePos(0),
1897                 expn_id: codemap::NO_EXPANSION,
1898             }
1899         }
1900         fn cfg(&self) -> ast::CrateConfig {
1901             Vec::new()
1902         }
1903         fn ident_of(&self, st: &str) -> ast::Ident {
1904             parse::token::str_to_ident(st)
1905         }
1906         fn name_of(&self, st: &str) -> ast::Name {
1907             parse::token::intern(st)
1908         }
1909         fn parse_sess(&self) -> &parse::ParseSess {
1910             self
1911         }
1912     }
1913
1914     impl NodeIdAssigner for MockAssigner {
1915         fn next_node_id(&self) -> NodeId {
1916             let result = self.next_id.get();
1917             self.next_id.set(result + 1);
1918             result
1919         }
1920
1921         fn peek_node_id(&self) -> NodeId {
1922             self.next_id.get()
1923         }
1924     }
1925
1926     impl Folder for MockAssigner {
1927         fn new_id(&mut self, old_id: NodeId) -> NodeId {
1928             assert_eq!(old_id, ast::DUMMY_NODE_ID);
1929             self.next_node_id()
1930         }
1931     }
1932
1933     #[test]
1934     fn test_preserves_ids() {
1935         let cx = parse::ParseSess::new();
1936         let mut assigner = MockAssigner::new();
1937
1938         let ast_if_let = quote_expr!(&cx,
1939                                      if let Some(foo) = baz {
1940                                          bar(foo);
1941                                      });
1942         let ast_if_let = assigner.fold_expr(ast_if_let);
1943         let ast_while_let = quote_expr!(&cx,
1944                                         while let Some(foo) = baz {
1945                                             bar(foo);
1946                                         });
1947         let ast_while_let = assigner.fold_expr(ast_while_let);
1948         let ast_for = quote_expr!(&cx,
1949                                   for i in 0..10 {
1950                                       for j in 0..10 {
1951                                           foo(i, j);
1952                                       }
1953                                   });
1954         let ast_for = assigner.fold_expr(ast_for);
1955         let ast_in = quote_expr!(&cx, in HEAP { foo() });
1956         let ast_in = assigner.fold_expr(ast_in);
1957
1958         let lctx = LoweringContext::new(&assigner, None);
1959         let hir1 = lower_expr(&lctx, &ast_if_let);
1960         let hir2 = lower_expr(&lctx, &ast_if_let);
1961         assert!(hir1 == hir2);
1962
1963         let hir1 = lower_expr(&lctx, &ast_while_let);
1964         let hir2 = lower_expr(&lctx, &ast_while_let);
1965         assert!(hir1 == hir2);
1966
1967         let hir1 = lower_expr(&lctx, &ast_for);
1968         let hir2 = lower_expr(&lctx, &ast_for);
1969         assert!(hir1 == hir2);
1970
1971         let hir1 = lower_expr(&lctx, &ast_in);
1972         let hir2 = lower_expr(&lctx, &ast_in);
1973         assert!(hir1 == hir2);
1974     }
1975 }