]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/lowering.rs
Use numeric field `Name`s ("0", "1" etc) for positional fields
[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     Spanned {
616         node: hir::StructField_ {
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         span: f.span,
625     }
626 }
627
628 pub fn lower_field(lctx: &LoweringContext, f: &Field) -> hir::Field {
629     hir::Field {
630         name: respan(f.ident.span, f.ident.node.name),
631         expr: lower_expr(lctx, &f.expr),
632         span: f.span,
633     }
634 }
635
636 pub fn lower_mt(lctx: &LoweringContext, mt: &MutTy) -> hir::MutTy {
637     hir::MutTy {
638         ty: lower_ty(lctx, &mt.ty),
639         mutbl: lower_mutability(lctx, mt.mutbl),
640     }
641 }
642
643 pub fn lower_opt_bounds(lctx: &LoweringContext,
644                         b: &Option<TyParamBounds>)
645                         -> Option<hir::TyParamBounds> {
646     b.as_ref().map(|ref bounds| lower_bounds(lctx, bounds))
647 }
648
649 fn lower_bounds(lctx: &LoweringContext, bounds: &TyParamBounds) -> hir::TyParamBounds {
650     bounds.iter().map(|bound| lower_ty_param_bound(lctx, bound)).collect()
651 }
652
653 pub fn lower_block(lctx: &LoweringContext, b: &Block) -> P<hir::Block> {
654     P(hir::Block {
655         id: b.id,
656         stmts: b.stmts.iter().map(|s| lower_stmt(lctx, s)).collect(),
657         expr: b.expr.as_ref().map(|ref x| lower_expr(lctx, x)),
658         rules: lower_block_check_mode(lctx, &b.rules),
659         span: b.span,
660     })
661 }
662
663 pub fn lower_item_kind(lctx: &LoweringContext, i: &ItemKind) -> hir::Item_ {
664     match *i {
665         ItemKind::ExternCrate(string) => hir::ItemExternCrate(string),
666         ItemKind::Use(ref view_path) => {
667             hir::ItemUse(lower_view_path(lctx, view_path))
668         }
669         ItemKind::Static(ref t, m, ref e) => {
670             hir::ItemStatic(lower_ty(lctx, t),
671                             lower_mutability(lctx, m),
672                             lower_expr(lctx, e))
673         }
674         ItemKind::Const(ref t, ref e) => {
675             hir::ItemConst(lower_ty(lctx, t), lower_expr(lctx, e))
676         }
677         ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
678             hir::ItemFn(lower_fn_decl(lctx, decl),
679                         lower_unsafety(lctx, unsafety),
680                         lower_constness(lctx, constness),
681                         abi,
682                         lower_generics(lctx, generics),
683                         lower_block(lctx, body))
684         }
685         ItemKind::Mod(ref m) => hir::ItemMod(lower_mod(lctx, m)),
686         ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(lctx, nm)),
687         ItemKind::Ty(ref t, ref generics) => {
688             hir::ItemTy(lower_ty(lctx, t), lower_generics(lctx, generics))
689         }
690         ItemKind::Enum(ref enum_definition, ref generics) => {
691             hir::ItemEnum(hir::EnumDef {
692                               variants: enum_definition.variants
693                                                        .iter()
694                                                        .map(|x| lower_variant(lctx, x))
695                                                        .collect(),
696                           },
697                           lower_generics(lctx, generics))
698         }
699         ItemKind::Struct(ref struct_def, ref generics) => {
700             let struct_def = lower_variant_data(lctx, struct_def);
701             hir::ItemStruct(struct_def, lower_generics(lctx, generics))
702         }
703         ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
704             hir::ItemDefaultImpl(lower_unsafety(lctx, unsafety),
705                                  lower_trait_ref(lctx, trait_ref))
706         }
707         ItemKind::Impl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
708             let new_impl_items = impl_items.iter()
709                                            .map(|item| lower_impl_item(lctx, item))
710                                            .collect();
711             let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(lctx, trait_ref));
712             hir::ItemImpl(lower_unsafety(lctx, unsafety),
713                           lower_impl_polarity(lctx, polarity),
714                           lower_generics(lctx, generics),
715                           ifce,
716                           lower_ty(lctx, ty),
717                           new_impl_items)
718         }
719         ItemKind::Trait(unsafety, ref generics, ref bounds, ref items) => {
720             let bounds = lower_bounds(lctx, bounds);
721             let items = items.iter().map(|item| lower_trait_item(lctx, item)).collect();
722             hir::ItemTrait(lower_unsafety(lctx, unsafety),
723                            lower_generics(lctx, generics),
724                            bounds,
725                            items)
726         }
727         ItemKind::Mac(_) => panic!("Shouldn't still be around"),
728     }
729 }
730
731 pub fn lower_trait_item(lctx: &LoweringContext, i: &TraitItem) -> hir::TraitItem {
732     hir::TraitItem {
733         id: i.id,
734         name: i.ident.name,
735         attrs: lower_attrs(lctx, &i.attrs),
736         node: match i.node {
737             TraitItemKind::Const(ref ty, ref default) => {
738                 hir::ConstTraitItem(lower_ty(lctx, ty),
739                                     default.as_ref().map(|x| lower_expr(lctx, x)))
740             }
741             TraitItemKind::Method(ref sig, ref body) => {
742                 hir::MethodTraitItem(lower_method_sig(lctx, sig),
743                                      body.as_ref().map(|x| lower_block(lctx, x)))
744             }
745             TraitItemKind::Type(ref bounds, ref default) => {
746                 hir::TypeTraitItem(lower_bounds(lctx, bounds),
747                                    default.as_ref().map(|x| lower_ty(lctx, x)))
748             }
749         },
750         span: i.span,
751     }
752 }
753
754 pub fn lower_impl_item(lctx: &LoweringContext, i: &ImplItem) -> hir::ImplItem {
755     hir::ImplItem {
756         id: i.id,
757         name: i.ident.name,
758         attrs: lower_attrs(lctx, &i.attrs),
759         vis: lower_visibility(lctx, i.vis),
760         node: match i.node {
761             ImplItemKind::Const(ref ty, ref expr) => {
762                 hir::ImplItemKind::Const(lower_ty(lctx, ty), lower_expr(lctx, expr))
763             }
764             ImplItemKind::Method(ref sig, ref body) => {
765                 hir::ImplItemKind::Method(lower_method_sig(lctx, sig), lower_block(lctx, body))
766             }
767             ImplItemKind::Type(ref ty) => hir::ImplItemKind::Type(lower_ty(lctx, ty)),
768             ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
769         },
770         span: i.span,
771     }
772 }
773
774 pub fn lower_mod(lctx: &LoweringContext, m: &Mod) -> hir::Mod {
775     hir::Mod {
776         inner: m.inner,
777         item_ids: m.items.iter().map(|x| lower_item_id(lctx, x)).collect(),
778     }
779 }
780
781 struct ItemLowerer<'lcx, 'interner: 'lcx> {
782     items: BTreeMap<NodeId, hir::Item>,
783     lctx: &'lcx LoweringContext<'interner>,
784 }
785
786 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
787     fn visit_item(&mut self, item: &'lcx Item) {
788         self.items.insert(item.id, lower_item(self.lctx, item));
789         visit::walk_item(self, item);
790     }
791 }
792
793 pub fn lower_crate(lctx: &LoweringContext, c: &Crate) -> hir::Crate {
794     let items = {
795         let mut item_lowerer = ItemLowerer { items: BTreeMap::new(), lctx: lctx };
796         visit::walk_crate(&mut item_lowerer, c);
797         item_lowerer.items
798     };
799
800     hir::Crate {
801         module: lower_mod(lctx, &c.module),
802         attrs: lower_attrs(lctx, &c.attrs),
803         config: c.config.clone().into(),
804         span: c.span,
805         exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(lctx, m)).collect(),
806         items: items,
807     }
808 }
809
810 pub fn lower_macro_def(lctx: &LoweringContext, m: &MacroDef) -> hir::MacroDef {
811     hir::MacroDef {
812         name: m.ident.name,
813         attrs: lower_attrs(lctx, &m.attrs),
814         id: m.id,
815         span: m.span,
816         imported_from: m.imported_from.map(|x| x.name),
817         export: m.export,
818         use_locally: m.use_locally,
819         allow_internal_unstable: m.allow_internal_unstable,
820         body: m.body.clone().into(),
821     }
822 }
823
824 pub fn lower_item_id(_lctx: &LoweringContext, i: &Item) -> hir::ItemId {
825     hir::ItemId { id: i.id }
826 }
827
828 pub fn lower_item(lctx: &LoweringContext, i: &Item) -> hir::Item {
829     let node = lower_item_kind(lctx, &i.node);
830
831     hir::Item {
832         id: i.id,
833         name: i.ident.name,
834         attrs: lower_attrs(lctx, &i.attrs),
835         node: node,
836         vis: lower_visibility(lctx, i.vis),
837         span: i.span,
838     }
839 }
840
841 pub fn lower_foreign_item(lctx: &LoweringContext, i: &ForeignItem) -> hir::ForeignItem {
842     hir::ForeignItem {
843         id: i.id,
844         name: i.ident.name,
845         attrs: lower_attrs(lctx, &i.attrs),
846         node: match i.node {
847             ForeignItemKind::Fn(ref fdec, ref generics) => {
848                 hir::ForeignItemFn(lower_fn_decl(lctx, fdec), lower_generics(lctx, generics))
849             }
850             ForeignItemKind::Static(ref t, m) => {
851                 hir::ForeignItemStatic(lower_ty(lctx, t), m)
852             }
853         },
854         vis: lower_visibility(lctx, i.vis),
855         span: i.span,
856     }
857 }
858
859 pub fn lower_method_sig(lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig {
860     hir::MethodSig {
861         generics: lower_generics(lctx, &sig.generics),
862         abi: sig.abi,
863         explicit_self: lower_explicit_self(lctx, &sig.explicit_self),
864         unsafety: lower_unsafety(lctx, sig.unsafety),
865         constness: lower_constness(lctx, sig.constness),
866         decl: lower_fn_decl(lctx, &sig.decl),
867     }
868 }
869
870 pub fn lower_unsafety(_lctx: &LoweringContext, u: Unsafety) -> hir::Unsafety {
871     match u {
872         Unsafety::Unsafe => hir::Unsafety::Unsafe,
873         Unsafety::Normal => hir::Unsafety::Normal,
874     }
875 }
876
877 pub fn lower_constness(_lctx: &LoweringContext, c: Constness) -> hir::Constness {
878     match c {
879         Constness::Const => hir::Constness::Const,
880         Constness::NotConst => hir::Constness::NotConst,
881     }
882 }
883
884 pub fn lower_unop(_lctx: &LoweringContext, u: UnOp) -> hir::UnOp {
885     match u {
886         UnOp::Deref => hir::UnDeref,
887         UnOp::Not => hir::UnNot,
888         UnOp::Neg => hir::UnNeg,
889     }
890 }
891
892 pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp {
893     Spanned {
894         node: match b.node {
895             BinOpKind::Add => hir::BiAdd,
896             BinOpKind::Sub => hir::BiSub,
897             BinOpKind::Mul => hir::BiMul,
898             BinOpKind::Div => hir::BiDiv,
899             BinOpKind::Rem => hir::BiRem,
900             BinOpKind::And => hir::BiAnd,
901             BinOpKind::Or => hir::BiOr,
902             BinOpKind::BitXor => hir::BiBitXor,
903             BinOpKind::BitAnd => hir::BiBitAnd,
904             BinOpKind::BitOr => hir::BiBitOr,
905             BinOpKind::Shl => hir::BiShl,
906             BinOpKind::Shr => hir::BiShr,
907             BinOpKind::Eq => hir::BiEq,
908             BinOpKind::Lt => hir::BiLt,
909             BinOpKind::Le => hir::BiLe,
910             BinOpKind::Ne => hir::BiNe,
911             BinOpKind::Ge => hir::BiGe,
912             BinOpKind::Gt => hir::BiGt,
913         },
914         span: b.span,
915     }
916 }
917
918 pub fn lower_pat(lctx: &LoweringContext, p: &Pat) -> P<hir::Pat> {
919     P(hir::Pat {
920         id: p.id,
921         node: match p.node {
922             PatKind::Wild => hir::PatKind::Wild,
923             PatKind::Ident(ref binding_mode, pth1, ref sub) => {
924                 hir::PatKind::Ident(lower_binding_mode(lctx, binding_mode),
925                               respan(pth1.span, lower_ident(lctx, pth1.node)),
926                               sub.as_ref().map(|x| lower_pat(lctx, x)))
927             }
928             PatKind::Lit(ref e) => hir::PatKind::Lit(lower_expr(lctx, e)),
929             PatKind::TupleStruct(ref pth, ref pats) => {
930                 hir::PatKind::TupleStruct(lower_path(lctx, pth),
931                              pats.as_ref()
932                                  .map(|pats| pats.iter().map(|x| lower_pat(lctx, x)).collect()))
933             }
934             PatKind::Path(ref pth) => {
935                 hir::PatKind::Path(lower_path(lctx, pth))
936             }
937             PatKind::QPath(ref qself, ref pth) => {
938                 let qself = hir::QSelf {
939                     ty: lower_ty(lctx, &qself.ty),
940                     position: qself.position,
941                 };
942                 hir::PatKind::QPath(qself, lower_path(lctx, pth))
943             }
944             PatKind::Struct(ref pth, ref fields, etc) => {
945                 let pth = lower_path(lctx, pth);
946                 let fs = fields.iter()
947                                .map(|f| {
948                                    Spanned {
949                                        span: f.span,
950                                        node: hir::FieldPat {
951                                            name: f.node.ident.name,
952                                            pat: lower_pat(lctx, &f.node.pat),
953                                            is_shorthand: f.node.is_shorthand,
954                                        },
955                                    }
956                                })
957                                .collect();
958                 hir::PatKind::Struct(pth, fs, etc)
959             }
960             PatKind::Tup(ref elts) => {
961                 hir::PatKind::Tup(elts.iter().map(|x| lower_pat(lctx, x)).collect())
962             }
963             PatKind::Box(ref inner) => hir::PatKind::Box(lower_pat(lctx, inner)),
964             PatKind::Ref(ref inner, mutbl) => {
965                 hir::PatKind::Ref(lower_pat(lctx, inner), lower_mutability(lctx, mutbl))
966             }
967             PatKind::Range(ref e1, ref e2) => {
968                 hir::PatKind::Range(lower_expr(lctx, e1), lower_expr(lctx, e2))
969             }
970             PatKind::Vec(ref before, ref slice, ref after) => {
971                 hir::PatKind::Vec(before.iter().map(|x| lower_pat(lctx, x)).collect(),
972                             slice.as_ref().map(|x| lower_pat(lctx, x)),
973                             after.iter().map(|x| lower_pat(lctx, x)).collect())
974             }
975             PatKind::Mac(_) => panic!("Shouldn't exist here"),
976         },
977         span: p.span,
978     })
979 }
980
981 pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
982     P(hir::Expr {
983         id: e.id,
984         node: match e.node {
985             // Issue #22181:
986             // Eventually a desugaring for `box EXPR`
987             // (similar to the desugaring above for `in PLACE BLOCK`)
988             // should go here, desugaring
989             //
990             // to:
991             //
992             // let mut place = BoxPlace::make_place();
993             // let raw_place = Place::pointer(&mut place);
994             // let value = $value;
995             // unsafe {
996             //     ::std::ptr::write(raw_place, value);
997             //     Boxed::finalize(place)
998             // }
999             //
1000             // But for now there are type-inference issues doing that.
1001             ExprKind::Box(ref e) => {
1002                 hir::ExprBox(lower_expr(lctx, e))
1003             }
1004
1005             // Desugar ExprBox: `in (PLACE) EXPR`
1006             ExprKind::InPlace(ref placer, ref value_expr) => {
1007                 // to:
1008                 //
1009                 // let p = PLACE;
1010                 // let mut place = Placer::make_place(p);
1011                 // let raw_place = Place::pointer(&mut place);
1012                 // push_unsafe!({
1013                 //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1014                 //     InPlace::finalize(place)
1015                 // })
1016                 return cache_ids(lctx, e.id, |lctx| {
1017                     let placer_expr = lower_expr(lctx, placer);
1018                     let value_expr = lower_expr(lctx, value_expr);
1019
1020                     let placer_ident = lctx.str_to_ident("placer");
1021                     let place_ident = lctx.str_to_ident("place");
1022                     let p_ptr_ident = lctx.str_to_ident("p_ptr");
1023
1024                     let make_place = ["ops", "Placer", "make_place"];
1025                     let place_pointer = ["ops", "Place", "pointer"];
1026                     let move_val_init = ["intrinsics", "move_val_init"];
1027                     let inplace_finalize = ["ops", "InPlace", "finalize"];
1028
1029                     let make_call = |lctx: &LoweringContext, p, args| {
1030                         let path = core_path(lctx, e.span, p);
1031                         let path = expr_path(lctx, path, None);
1032                         expr_call(lctx, e.span, path, args, None)
1033                     };
1034
1035                     let mk_stmt_let = |lctx: &LoweringContext, bind, expr| {
1036                         stmt_let(lctx, e.span, false, bind, expr, None)
1037                     };
1038
1039                     let mk_stmt_let_mut = |lctx: &LoweringContext, bind, expr| {
1040                         stmt_let(lctx, e.span, true, bind, expr, None)
1041                     };
1042
1043                     // let placer = <placer_expr> ;
1044                     let s1 = {
1045                         let placer_expr = signal_block_expr(lctx,
1046                                                             hir_vec![],
1047                                                             placer_expr,
1048                                                             e.span,
1049                                                             hir::PopUnstableBlock,
1050                                                             None);
1051                         mk_stmt_let(lctx, placer_ident, placer_expr)
1052                     };
1053
1054                     // let mut place = Placer::make_place(placer);
1055                     let s2 = {
1056                         let placer = expr_ident(lctx, e.span, placer_ident, None);
1057                         let call = make_call(lctx, &make_place, hir_vec![placer]);
1058                         mk_stmt_let_mut(lctx, place_ident, call)
1059                     };
1060
1061                     // let p_ptr = Place::pointer(&mut place);
1062                     let s3 = {
1063                         let agent = expr_ident(lctx, e.span, place_ident, None);
1064                         let args = hir_vec![expr_mut_addr_of(lctx, e.span, agent, None)];
1065                         let call = make_call(lctx, &place_pointer, args);
1066                         mk_stmt_let(lctx, p_ptr_ident, call)
1067                     };
1068
1069                     // pop_unsafe!(EXPR));
1070                     let pop_unsafe_expr = {
1071                         let value_expr = signal_block_expr(lctx,
1072                                                            hir_vec![],
1073                                                            value_expr,
1074                                                            e.span,
1075                                                            hir::PopUnstableBlock,
1076                                                            None);
1077                         signal_block_expr(lctx,
1078                                           hir_vec![],
1079                                           value_expr,
1080                                           e.span,
1081                                           hir::PopUnsafeBlock(hir::CompilerGenerated), None)
1082                     };
1083
1084                     // push_unsafe!({
1085                     //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1086                     //     InPlace::finalize(place)
1087                     // })
1088                     let expr = {
1089                         let ptr = expr_ident(lctx, e.span, p_ptr_ident, None);
1090                         let call_move_val_init =
1091                             hir::StmtSemi(
1092                                 make_call(lctx, &move_val_init, hir_vec![ptr, pop_unsafe_expr]),
1093                                 lctx.next_id());
1094                         let call_move_val_init = respan(e.span, call_move_val_init);
1095
1096                         let place = expr_ident(lctx, e.span, place_ident, None);
1097                         let call = make_call(lctx, &inplace_finalize, hir_vec![place]);
1098                         signal_block_expr(lctx,
1099                                           hir_vec![call_move_val_init],
1100                                           call,
1101                                           e.span,
1102                                           hir::PushUnsafeBlock(hir::CompilerGenerated), None)
1103                     };
1104
1105                     signal_block_expr(lctx,
1106                                       hir_vec![s1, s2, s3],
1107                                       expr,
1108                                       e.span,
1109                                       hir::PushUnstableBlock,
1110                                       e.attrs.clone())
1111                 });
1112             }
1113
1114             ExprKind::Vec(ref exprs) => {
1115                 hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect())
1116             }
1117             ExprKind::Repeat(ref expr, ref count) => {
1118                 let expr = lower_expr(lctx, expr);
1119                 let count = lower_expr(lctx, count);
1120                 hir::ExprRepeat(expr, count)
1121             }
1122             ExprKind::Tup(ref elts) => {
1123                 hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect())
1124             }
1125             ExprKind::Call(ref f, ref args) => {
1126                 let f = lower_expr(lctx, f);
1127                 hir::ExprCall(f, args.iter().map(|x| lower_expr(lctx, x)).collect())
1128             }
1129             ExprKind::MethodCall(i, ref tps, ref args) => {
1130                 let tps = tps.iter().map(|x| lower_ty(lctx, x)).collect();
1131                 let args = args.iter().map(|x| lower_expr(lctx, x)).collect();
1132                 hir::ExprMethodCall(respan(i.span, i.node.name), tps, args)
1133             }
1134             ExprKind::Binary(binop, ref lhs, ref rhs) => {
1135                 let binop = lower_binop(lctx, binop);
1136                 let lhs = lower_expr(lctx, lhs);
1137                 let rhs = lower_expr(lctx, rhs);
1138                 hir::ExprBinary(binop, lhs, rhs)
1139             }
1140             ExprKind::Unary(op, ref ohs) => {
1141                 let op = lower_unop(lctx, op);
1142                 let ohs = lower_expr(lctx, ohs);
1143                 hir::ExprUnary(op, ohs)
1144             }
1145             ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
1146             ExprKind::Cast(ref expr, ref ty) => {
1147                 let expr = lower_expr(lctx, expr);
1148                 hir::ExprCast(expr, lower_ty(lctx, ty))
1149             }
1150             ExprKind::Type(ref expr, ref ty) => {
1151                 let expr = lower_expr(lctx, expr);
1152                 hir::ExprType(expr, lower_ty(lctx, ty))
1153             }
1154             ExprKind::AddrOf(m, ref ohs) => {
1155                 let m = lower_mutability(lctx, m);
1156                 let ohs = lower_expr(lctx, ohs);
1157                 hir::ExprAddrOf(m, ohs)
1158             }
1159             // More complicated than you might expect because the else branch
1160             // might be `if let`.
1161             ExprKind::If(ref cond, ref blk, ref else_opt) => {
1162                 let else_opt = else_opt.as_ref().map(|els| {
1163                     match els.node {
1164                         ExprKind::IfLet(..) => {
1165                             cache_ids(lctx, e.id, |lctx| {
1166                                 // wrap the if-let expr in a block
1167                                 let span = els.span;
1168                                 let els = lower_expr(lctx, els);
1169                                 let id = lctx.next_id();
1170                                 let blk = P(hir::Block {
1171                                     stmts: hir_vec![],
1172                                     expr: Some(els),
1173                                     id: id,
1174                                     rules: hir::DefaultBlock,
1175                                     span: span,
1176                                 });
1177                                 expr_block(lctx, blk, None)
1178                             })
1179                         }
1180                         _ => lower_expr(lctx, els),
1181                     }
1182                 });
1183
1184                 hir::ExprIf(lower_expr(lctx, cond), lower_block(lctx, blk), else_opt)
1185             }
1186             ExprKind::While(ref cond, ref body, opt_ident) => {
1187                 hir::ExprWhile(lower_expr(lctx, cond), lower_block(lctx, body),
1188                                opt_ident.map(|ident| lower_ident(lctx, ident)))
1189             }
1190             ExprKind::Loop(ref body, opt_ident) => {
1191                 hir::ExprLoop(lower_block(lctx, body),
1192                               opt_ident.map(|ident| lower_ident(lctx, ident)))
1193             }
1194             ExprKind::Match(ref expr, ref arms) => {
1195                 hir::ExprMatch(lower_expr(lctx, expr),
1196                                arms.iter().map(|x| lower_arm(lctx, x)).collect(),
1197                                hir::MatchSource::Normal)
1198             }
1199             ExprKind::Closure(capture_clause, ref decl, ref body) => {
1200                 hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
1201                                  lower_fn_decl(lctx, decl),
1202                                  lower_block(lctx, body))
1203             }
1204             ExprKind::Block(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
1205             ExprKind::Assign(ref el, ref er) => {
1206                 hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
1207             }
1208             ExprKind::AssignOp(op, ref el, ref er) => {
1209                 hir::ExprAssignOp(lower_binop(lctx, op),
1210                                   lower_expr(lctx, el),
1211                                   lower_expr(lctx, er))
1212             }
1213             ExprKind::Field(ref el, ident) => {
1214                 hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name))
1215             }
1216             ExprKind::TupField(ref el, ident) => {
1217                 hir::ExprTupField(lower_expr(lctx, el), ident)
1218             }
1219             ExprKind::Index(ref el, ref er) => {
1220                 hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
1221             }
1222             ExprKind::Range(ref e1, ref e2) => {
1223                 hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)),
1224                                e2.as_ref().map(|x| lower_expr(lctx, x)))
1225             }
1226             ExprKind::Path(ref qself, ref path) => {
1227                 let hir_qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
1228                     hir::QSelf {
1229                         ty: lower_ty(lctx, ty),
1230                         position: position,
1231                     }
1232                 });
1233                 hir::ExprPath(hir_qself, lower_path_full(lctx, path, qself.is_none()))
1234             }
1235             ExprKind::Break(opt_ident) => hir::ExprBreak(opt_ident.map(|sp_ident| {
1236                 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1237             })),
1238             ExprKind::Again(opt_ident) => hir::ExprAgain(opt_ident.map(|sp_ident| {
1239                 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1240             })),
1241             ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
1242             ExprKind::InlineAsm(InlineAsm {
1243                     ref inputs,
1244                     ref outputs,
1245                     ref asm,
1246                     asm_str_style,
1247                     ref clobbers,
1248                     volatile,
1249                     alignstack,
1250                     dialect,
1251                     expn_id,
1252                 }) => hir::ExprInlineAsm(hir::InlineAsm {
1253                 inputs: inputs.iter()
1254                               .map(|&(ref c, ref input)| (c.clone(), lower_expr(lctx, input)))
1255                               .collect(),
1256                 outputs: outputs.iter()
1257                                 .map(|out| {
1258                                     hir::InlineAsmOutput {
1259                                         constraint: out.constraint.clone(),
1260                                         expr: lower_expr(lctx, &out.expr),
1261                                         is_rw: out.is_rw,
1262                                         is_indirect: out.is_indirect,
1263                                     }
1264                                 })
1265                                 .collect(),
1266                 asm: asm.clone(),
1267                 asm_str_style: asm_str_style,
1268                 clobbers: clobbers.clone().into(),
1269                 volatile: volatile,
1270                 alignstack: alignstack,
1271                 dialect: dialect,
1272                 expn_id: expn_id,
1273             }),
1274             ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
1275                 hir::ExprStruct(lower_path(lctx, path),
1276                                 fields.iter().map(|x| lower_field(lctx, x)).collect(),
1277                                 maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
1278             }
1279             ExprKind::Paren(ref ex) => {
1280                 // merge attributes into the inner expression.
1281                 return lower_expr(lctx, ex).map(|mut ex| {
1282                     ex.attrs.update(|attrs| {
1283                         attrs.prepend(e.attrs.clone())
1284                     });
1285                     ex
1286                 });
1287             }
1288
1289             // Desugar ExprIfLet
1290             // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
1291             ExprKind::IfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
1292                 // to:
1293                 //
1294                 //   match <sub_expr> {
1295                 //     <pat> => <body>,
1296                 //     [_ if <else_opt_if_cond> => <else_opt_if_body>,]
1297                 //     _ => [<else_opt> | ()]
1298                 //   }
1299
1300                 return cache_ids(lctx, e.id, |lctx| {
1301                     // `<pat> => <body>`
1302                     let pat_arm = {
1303                         let body = lower_block(lctx, body);
1304                         let body_expr = expr_block(lctx, body, None);
1305                         arm(hir_vec![lower_pat(lctx, pat)], body_expr)
1306                     };
1307
1308                     // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
1309                     let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e));
1310                     let else_if_arms = {
1311                         let mut arms = vec![];
1312                         loop {
1313                             let else_opt_continue = else_opt.and_then(|els| {
1314                                 els.and_then(|els| {
1315                                     match els.node {
1316                                         // else if
1317                                         hir::ExprIf(cond, then, else_opt) => {
1318                                             let pat_under = pat_wild(lctx, e.span);
1319                                             arms.push(hir::Arm {
1320                                                 attrs: hir_vec![],
1321                                                 pats: hir_vec![pat_under],
1322                                                 guard: Some(cond),
1323                                                 body: expr_block(lctx, then, None),
1324                                             });
1325                                             else_opt.map(|else_opt| (else_opt, true))
1326                                         }
1327                                         _ => Some((P(els), false)),
1328                                     }
1329                                 })
1330                             });
1331                             match else_opt_continue {
1332                                 Some((e, true)) => {
1333                                     else_opt = Some(e);
1334                                 }
1335                                 Some((e, false)) => {
1336                                     else_opt = Some(e);
1337                                     break;
1338                                 }
1339                                 None => {
1340                                     else_opt = None;
1341                                     break;
1342                                 }
1343                             }
1344                         }
1345                         arms
1346                     };
1347
1348                     let contains_else_clause = else_opt.is_some();
1349
1350                     // `_ => [<else_opt> | ()]`
1351                     let else_arm = {
1352                         let pat_under = pat_wild(lctx, e.span);
1353                         let else_expr =
1354                             else_opt.unwrap_or_else(
1355                                 || expr_tuple(lctx, e.span, hir_vec![], None));
1356                         arm(hir_vec![pat_under], else_expr)
1357                     };
1358
1359                     let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
1360                     arms.push(pat_arm);
1361                     arms.extend(else_if_arms);
1362                     arms.push(else_arm);
1363
1364                     let sub_expr = lower_expr(lctx, sub_expr);
1365                     // add attributes to the outer returned expr node
1366                     expr(lctx,
1367                          e.span,
1368                          hir::ExprMatch(sub_expr,
1369                                         arms.into(),
1370                                         hir::MatchSource::IfLetDesugar {
1371                                             contains_else_clause: contains_else_clause,
1372                                         }),
1373                          e.attrs.clone())
1374                 });
1375             }
1376
1377             // Desugar ExprWhileLet
1378             // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
1379             ExprKind::WhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
1380                 // to:
1381                 //
1382                 //   [opt_ident]: loop {
1383                 //     match <sub_expr> {
1384                 //       <pat> => <body>,
1385                 //       _ => break
1386                 //     }
1387                 //   }
1388
1389                 return cache_ids(lctx, e.id, |lctx| {
1390                     // `<pat> => <body>`
1391                     let pat_arm = {
1392                         let body = lower_block(lctx, body);
1393                         let body_expr = expr_block(lctx, body, None);
1394                         arm(hir_vec![lower_pat(lctx, pat)], body_expr)
1395                     };
1396
1397                     // `_ => break`
1398                     let break_arm = {
1399                         let pat_under = pat_wild(lctx, e.span);
1400                         let break_expr = expr_break(lctx, e.span, None);
1401                         arm(hir_vec![pat_under], break_expr)
1402                     };
1403
1404                     // `match <sub_expr> { ... }`
1405                     let arms = hir_vec![pat_arm, break_arm];
1406                     let sub_expr = lower_expr(lctx, sub_expr);
1407                     let match_expr = expr(lctx,
1408                                           e.span,
1409                                           hir::ExprMatch(sub_expr,
1410                                                          arms,
1411                                                          hir::MatchSource::WhileLetDesugar),
1412                                           None);
1413
1414                     // `[opt_ident]: loop { ... }`
1415                     let loop_block = block_expr(lctx, match_expr);
1416                     let loop_expr = hir::ExprLoop(loop_block,
1417                                                   opt_ident.map(|ident| lower_ident(lctx, ident)));
1418                     // add attributes to the outer returned expr node
1419                     expr(lctx, e.span, loop_expr, e.attrs.clone())
1420                 });
1421             }
1422
1423             // Desugar ExprForLoop
1424             // From: `[opt_ident]: for <pat> in <head> <body>`
1425             ExprKind::ForLoop(ref pat, ref head, ref body, opt_ident) => {
1426                 // to:
1427                 //
1428                 //   {
1429                 //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1430                 //       mut iter => {
1431                 //         [opt_ident]: loop {
1432                 //           match ::std::iter::Iterator::next(&mut iter) {
1433                 //             ::std::option::Option::Some(<pat>) => <body>,
1434                 //             ::std::option::Option::None => break
1435                 //           }
1436                 //         }
1437                 //       }
1438                 //     };
1439                 //     result
1440                 //   }
1441
1442                 return cache_ids(lctx, e.id, |lctx| {
1443                     // expand <head>
1444                     let head = lower_expr(lctx, head);
1445
1446                     let iter = lctx.str_to_ident("iter");
1447
1448                     // `::std::option::Option::Some(<pat>) => <body>`
1449                     let pat_arm = {
1450                         let body_block = lower_block(lctx, body);
1451                         let body_span = body_block.span;
1452                         let body_expr = P(hir::Expr {
1453                             id: lctx.next_id(),
1454                             node: hir::ExprBlock(body_block),
1455                             span: body_span,
1456                             attrs: None,
1457                         });
1458                         let pat = lower_pat(lctx, pat);
1459                         let some_pat = pat_some(lctx, e.span, pat);
1460
1461                         arm(hir_vec![some_pat], body_expr)
1462                     };
1463
1464                     // `::std::option::Option::None => break`
1465                     let break_arm = {
1466                         let break_expr = expr_break(lctx, e.span, None);
1467
1468                         arm(hir_vec![pat_none(lctx, e.span)], break_expr)
1469                     };
1470
1471                     // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1472                     let match_expr = {
1473                         let next_path = {
1474                             let strs = std_path(lctx, &["iter", "Iterator", "next"]);
1475
1476                             path_global(e.span, strs)
1477                         };
1478                         let iter = expr_ident(lctx, e.span, iter, None);
1479                         let ref_mut_iter = expr_mut_addr_of(lctx, e.span, iter, None);
1480                         let next_path = expr_path(lctx, next_path, None);
1481                         let next_expr = expr_call(lctx,
1482                                                   e.span,
1483                                                   next_path,
1484                                                   hir_vec![ref_mut_iter],
1485                                                   None);
1486                         let arms = hir_vec![pat_arm, break_arm];
1487
1488                         expr(lctx,
1489                              e.span,
1490                              hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
1491                              None)
1492                     };
1493
1494                     // `[opt_ident]: loop { ... }`
1495                     let loop_block = block_expr(lctx, match_expr);
1496                     let loop_expr = hir::ExprLoop(loop_block,
1497                                                   opt_ident.map(|ident| lower_ident(lctx, ident)));
1498                     let loop_expr = expr(lctx, e.span, loop_expr, None);
1499
1500                     // `mut iter => { ... }`
1501                     let iter_arm = {
1502                         let iter_pat = pat_ident_binding_mode(lctx,
1503                                                               e.span,
1504                                                               iter,
1505                                                               hir::BindByValue(hir::MutMutable));
1506                         arm(hir_vec![iter_pat], loop_expr)
1507                     };
1508
1509                     // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1510                     let into_iter_expr = {
1511                         let into_iter_path = {
1512                             let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
1513
1514                             path_global(e.span, strs)
1515                         };
1516
1517                         let into_iter = expr_path(lctx, into_iter_path, None);
1518                         expr_call(lctx, e.span, into_iter, hir_vec![head], None)
1519                     };
1520
1521                     let match_expr = expr_match(lctx,
1522                                                 e.span,
1523                                                 into_iter_expr,
1524                                                 hir_vec![iter_arm],
1525                                                 hir::MatchSource::ForLoopDesugar,
1526                                                 None);
1527
1528                     // `{ let _result = ...; _result }`
1529                     // underscore prevents an unused_variables lint if the head diverges
1530                     let result_ident = lctx.str_to_ident("_result");
1531                     let let_stmt = stmt_let(lctx, e.span, false, result_ident, match_expr, None);
1532                     let result = expr_ident(lctx, e.span, result_ident, None);
1533                     let block = block_all(lctx, e.span, hir_vec![let_stmt], Some(result));
1534                     // add the attributes to the outer returned expr node
1535                     expr_block(lctx, block, e.attrs.clone())
1536                 });
1537             }
1538
1539             ExprKind::Mac(_) => panic!("Shouldn't exist here"),
1540         },
1541         span: e.span,
1542         attrs: e.attrs.clone(),
1543     })
1544 }
1545
1546 pub fn lower_stmt(lctx: &LoweringContext, s: &Stmt) -> hir::Stmt {
1547     match s.node {
1548         StmtKind::Decl(ref d, id) => {
1549             Spanned {
1550                 node: hir::StmtDecl(lower_decl(lctx, d), id),
1551                 span: s.span,
1552             }
1553         }
1554         StmtKind::Expr(ref e, id) => {
1555             Spanned {
1556                 node: hir::StmtExpr(lower_expr(lctx, e), id),
1557                 span: s.span,
1558             }
1559         }
1560         StmtKind::Semi(ref e, id) => {
1561             Spanned {
1562                 node: hir::StmtSemi(lower_expr(lctx, e), id),
1563                 span: s.span,
1564             }
1565         }
1566         StmtKind::Mac(..) => panic!("Shouldn't exist here"),
1567     }
1568 }
1569
1570 pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureBy) -> hir::CaptureClause {
1571     match c {
1572         CaptureBy::Value => hir::CaptureByValue,
1573         CaptureBy::Ref => hir::CaptureByRef,
1574     }
1575 }
1576
1577 pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1578     match v {
1579         Visibility::Public => hir::Public,
1580         Visibility::Inherited => hir::Inherited,
1581     }
1582 }
1583
1584 pub fn lower_block_check_mode(lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1585     match *b {
1586         BlockCheckMode::Default => hir::DefaultBlock,
1587         BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(lower_unsafe_source(lctx, u)),
1588     }
1589 }
1590
1591 pub fn lower_binding_mode(lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1592     match *b {
1593         BindingMode::ByRef(m) => hir::BindByRef(lower_mutability(lctx, m)),
1594         BindingMode::ByValue(m) => hir::BindByValue(lower_mutability(lctx, m)),
1595     }
1596 }
1597
1598 pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1599     match u {
1600         CompilerGenerated => hir::CompilerGenerated,
1601         UserProvided => hir::UserProvided,
1602     }
1603 }
1604
1605 pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1606     match i {
1607         ImplPolarity::Positive => hir::ImplPolarity::Positive,
1608         ImplPolarity::Negative => hir::ImplPolarity::Negative,
1609     }
1610 }
1611
1612 pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
1613                                   f: TraitBoundModifier)
1614                                   -> hir::TraitBoundModifier {
1615     match f {
1616         TraitBoundModifier::None => hir::TraitBoundModifier::None,
1617         TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
1618     }
1619 }
1620
1621 // Helper methods for building HIR.
1622
1623 fn arm(pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1624     hir::Arm {
1625         attrs: hir_vec![],
1626         pats: pats,
1627         guard: None,
1628         body: expr,
1629     }
1630 }
1631
1632 fn expr_break(lctx: &LoweringContext, span: Span,
1633               attrs: ThinAttributes) -> P<hir::Expr> {
1634     expr(lctx, span, hir::ExprBreak(None), attrs)
1635 }
1636
1637 fn expr_call(lctx: &LoweringContext,
1638              span: Span,
1639              e: P<hir::Expr>,
1640              args: hir::HirVec<P<hir::Expr>>,
1641              attrs: ThinAttributes)
1642              -> P<hir::Expr> {
1643     expr(lctx, span, hir::ExprCall(e, args), attrs)
1644 }
1645
1646 fn expr_ident(lctx: &LoweringContext, span: Span, id: hir::Ident,
1647               attrs: ThinAttributes) -> P<hir::Expr> {
1648     expr_path(lctx, path_ident(span, id), attrs)
1649 }
1650
1651 fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>,
1652                     attrs: ThinAttributes) -> P<hir::Expr> {
1653     expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e), attrs)
1654 }
1655
1656 fn expr_path(lctx: &LoweringContext, path: hir::Path,
1657              attrs: ThinAttributes) -> P<hir::Expr> {
1658     expr(lctx, path.span, hir::ExprPath(None, path), attrs)
1659 }
1660
1661 fn expr_match(lctx: &LoweringContext,
1662               span: Span,
1663               arg: P<hir::Expr>,
1664               arms: hir::HirVec<hir::Arm>,
1665               source: hir::MatchSource,
1666               attrs: ThinAttributes)
1667               -> P<hir::Expr> {
1668     expr(lctx, span, hir::ExprMatch(arg, arms, source), attrs)
1669 }
1670
1671 fn expr_block(lctx: &LoweringContext, b: P<hir::Block>,
1672               attrs: ThinAttributes) -> P<hir::Expr> {
1673     expr(lctx, b.span, hir::ExprBlock(b), attrs)
1674 }
1675
1676 fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: hir::HirVec<P<hir::Expr>>,
1677               attrs: ThinAttributes) -> P<hir::Expr> {
1678     expr(lctx, sp, hir::ExprTup(exprs), attrs)
1679 }
1680
1681 fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_,
1682         attrs: ThinAttributes) -> P<hir::Expr> {
1683     P(hir::Expr {
1684         id: lctx.next_id(),
1685         node: node,
1686         span: span,
1687         attrs: attrs,
1688     })
1689 }
1690
1691 fn stmt_let(lctx: &LoweringContext,
1692             sp: Span,
1693             mutbl: bool,
1694             ident: hir::Ident,
1695             ex: P<hir::Expr>,
1696             attrs: ThinAttributes)
1697             -> hir::Stmt {
1698     let pat = if mutbl {
1699         pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
1700     } else {
1701         pat_ident(lctx, sp, ident)
1702     };
1703     let local = P(hir::Local {
1704         pat: pat,
1705         ty: None,
1706         init: Some(ex),
1707         id: lctx.next_id(),
1708         span: sp,
1709         attrs: attrs,
1710     });
1711     let decl = respan(sp, hir::DeclLocal(local));
1712     respan(sp, hir::StmtDecl(P(decl), lctx.next_id()))
1713 }
1714
1715 fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
1716     block_all(lctx, expr.span, hir::HirVec::new(), Some(expr))
1717 }
1718
1719 fn block_all(lctx: &LoweringContext,
1720              span: Span,
1721              stmts: hir::HirVec<hir::Stmt>,
1722              expr: Option<P<hir::Expr>>)
1723              -> P<hir::Block> {
1724     P(hir::Block {
1725         stmts: stmts,
1726         expr: expr,
1727         id: lctx.next_id(),
1728         rules: hir::DefaultBlock,
1729         span: span,
1730     })
1731 }
1732
1733 fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1734     let some = std_path(lctx, &["option", "Option", "Some"]);
1735     let path = path_global(span, some);
1736     pat_enum(lctx, span, path, hir_vec![pat])
1737 }
1738
1739 fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1740     let none = std_path(lctx, &["option", "Option", "None"]);
1741     let path = path_global(span, none);
1742     pat_enum(lctx, span, path, hir_vec![])
1743 }
1744
1745 fn pat_enum(lctx: &LoweringContext,
1746             span: Span,
1747             path: hir::Path,
1748             subpats: hir::HirVec<P<hir::Pat>>)
1749             -> P<hir::Pat> {
1750     let pt = if subpats.is_empty() {
1751         hir::PatKind::Path(path)
1752     } else {
1753         hir::PatKind::TupleStruct(path, Some(subpats))
1754     };
1755     pat(lctx, span, pt)
1756 }
1757
1758 fn pat_ident(lctx: &LoweringContext, span: Span, ident: hir::Ident) -> P<hir::Pat> {
1759     pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
1760 }
1761
1762 fn pat_ident_binding_mode(lctx: &LoweringContext,
1763                           span: Span,
1764                           ident: hir::Ident,
1765                           bm: hir::BindingMode)
1766                           -> P<hir::Pat> {
1767     let pat_ident = hir::PatKind::Ident(bm,
1768                                   Spanned {
1769                                       span: span,
1770                                       node: ident,
1771                                   },
1772                                   None);
1773     pat(lctx, span, pat_ident)
1774 }
1775
1776 fn pat_wild(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1777     pat(lctx, span, hir::PatKind::Wild)
1778 }
1779
1780 fn pat(lctx: &LoweringContext, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
1781     P(hir::Pat {
1782         id: lctx.next_id(),
1783         node: pat,
1784         span: span,
1785     })
1786 }
1787
1788 fn path_ident(span: Span, id: hir::Ident) -> hir::Path {
1789     path(span, vec![id])
1790 }
1791
1792 fn path(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1793     path_all(span, false, strs, hir::HirVec::new(), hir::HirVec::new(), hir::HirVec::new())
1794 }
1795
1796 fn path_global(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1797     path_all(span, true, strs, hir::HirVec::new(), hir::HirVec::new(), hir::HirVec::new())
1798 }
1799
1800 fn path_all(sp: Span,
1801             global: bool,
1802             mut idents: Vec<hir::Ident>,
1803             lifetimes: hir::HirVec<hir::Lifetime>,
1804             types: hir::HirVec<P<hir::Ty>>,
1805             bindings: hir::HirVec<hir::TypeBinding>)
1806             -> hir::Path {
1807     let last_identifier = idents.pop().unwrap();
1808     let mut segments: Vec<hir::PathSegment> = idents.into_iter()
1809                                                     .map(|ident| {
1810                                                         hir::PathSegment {
1811                                                             identifier: ident,
1812                                                             parameters: hir::PathParameters::none(),
1813                                                         }
1814                                                     })
1815                                                     .collect();
1816     segments.push(hir::PathSegment {
1817         identifier: last_identifier,
1818         parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1819             lifetimes: lifetimes,
1820             types: types,
1821             bindings: bindings,
1822         }),
1823     });
1824     hir::Path {
1825         span: sp,
1826         global: global,
1827         segments: segments.into(),
1828     }
1829 }
1830
1831 fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<hir::Ident> {
1832     let mut v = Vec::new();
1833     if let Some(s) = lctx.crate_root {
1834         v.push(hir::Ident::from_name(token::intern(s)));
1835     }
1836     v.extend(components.iter().map(|s| hir::Ident::from_name(token::intern(s))));
1837     return v;
1838 }
1839
1840 // Given suffix ["b","c","d"], returns path `::std::b::c::d` when
1841 // `fld.cx.use_std`, and `::core::b::c::d` otherwise.
1842 fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Path {
1843     let idents = std_path(lctx, components);
1844     path_global(span, idents)
1845 }
1846
1847 fn signal_block_expr(lctx: &LoweringContext,
1848                      stmts: hir::HirVec<hir::Stmt>,
1849                      expr: P<hir::Expr>,
1850                      span: Span,
1851                      rule: hir::BlockCheckMode,
1852                      attrs: ThinAttributes)
1853                      -> P<hir::Expr> {
1854     let id = lctx.next_id();
1855     expr_block(lctx,
1856                P(hir::Block {
1857                    rules: rule,
1858                    span: span,
1859                    id: id,
1860                    stmts: stmts,
1861                    expr: Some(expr),
1862                }),
1863                attrs)
1864 }
1865
1866
1867
1868 #[cfg(test)]
1869 mod test {
1870     use super::*;
1871     use syntax::ast::{self, NodeId, NodeIdAssigner};
1872     use syntax::{parse, codemap};
1873     use syntax::fold::Folder;
1874     use std::cell::Cell;
1875
1876     struct MockAssigner {
1877         next_id: Cell<NodeId>,
1878     }
1879
1880     impl MockAssigner {
1881         fn new() -> MockAssigner {
1882             MockAssigner { next_id: Cell::new(0) }
1883         }
1884     }
1885
1886     trait FakeExtCtxt {
1887         fn call_site(&self) -> codemap::Span;
1888         fn cfg(&self) -> ast::CrateConfig;
1889         fn ident_of(&self, st: &str) -> ast::Ident;
1890         fn name_of(&self, st: &str) -> ast::Name;
1891         fn parse_sess(&self) -> &parse::ParseSess;
1892     }
1893
1894     impl FakeExtCtxt for parse::ParseSess {
1895         fn call_site(&self) -> codemap::Span {
1896             codemap::Span {
1897                 lo: codemap::BytePos(0),
1898                 hi: codemap::BytePos(0),
1899                 expn_id: codemap::NO_EXPANSION,
1900             }
1901         }
1902         fn cfg(&self) -> ast::CrateConfig {
1903             Vec::new()
1904         }
1905         fn ident_of(&self, st: &str) -> ast::Ident {
1906             parse::token::str_to_ident(st)
1907         }
1908         fn name_of(&self, st: &str) -> ast::Name {
1909             parse::token::intern(st)
1910         }
1911         fn parse_sess(&self) -> &parse::ParseSess {
1912             self
1913         }
1914     }
1915
1916     impl NodeIdAssigner for MockAssigner {
1917         fn next_node_id(&self) -> NodeId {
1918             let result = self.next_id.get();
1919             self.next_id.set(result + 1);
1920             result
1921         }
1922
1923         fn peek_node_id(&self) -> NodeId {
1924             self.next_id.get()
1925         }
1926     }
1927
1928     impl Folder for MockAssigner {
1929         fn new_id(&mut self, old_id: NodeId) -> NodeId {
1930             assert_eq!(old_id, ast::DUMMY_NODE_ID);
1931             self.next_node_id()
1932         }
1933     }
1934
1935     #[test]
1936     fn test_preserves_ids() {
1937         let cx = parse::ParseSess::new();
1938         let mut assigner = MockAssigner::new();
1939
1940         let ast_if_let = quote_expr!(&cx,
1941                                      if let Some(foo) = baz {
1942                                          bar(foo);
1943                                      });
1944         let ast_if_let = assigner.fold_expr(ast_if_let);
1945         let ast_while_let = quote_expr!(&cx,
1946                                         while let Some(foo) = baz {
1947                                             bar(foo);
1948                                         });
1949         let ast_while_let = assigner.fold_expr(ast_while_let);
1950         let ast_for = quote_expr!(&cx,
1951                                   for i in 0..10 {
1952                                       for j in 0..10 {
1953                                           foo(i, j);
1954                                       }
1955                                   });
1956         let ast_for = assigner.fold_expr(ast_for);
1957         let ast_in = quote_expr!(&cx, in HEAP { foo() });
1958         let ast_in = assigner.fold_expr(ast_in);
1959
1960         let lctx = LoweringContext::new(&assigner, None);
1961         let hir1 = lower_expr(&lctx, &ast_if_let);
1962         let hir2 = lower_expr(&lctx, &ast_if_let);
1963         assert!(hir1 == hir2);
1964
1965         let hir1 = lower_expr(&lctx, &ast_while_let);
1966         let hir2 = lower_expr(&lctx, &ast_while_let);
1967         assert!(hir1 == hir2);
1968
1969         let hir1 = lower_expr(&lctx, &ast_for);
1970         let hir2 = lower_expr(&lctx, &ast_for);
1971         assert!(hir1 == hir2);
1972
1973         let hir1 = lower_expr(&lctx, &ast_in);
1974         let hir2 = lower_expr(&lctx, &ast_in);
1975         assert!(hir1 == hir2);
1976     }
1977 }