]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/lowering.rs
546b298a92b72dd11c21c14ba0bc089d466f8b51
[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 use hir;
14
15 use std::collections::HashMap;
16
17 use syntax::ast::*;
18 use syntax::ptr::P;
19 use syntax::codemap::{respan, Spanned, Span};
20 use syntax::owned_slice::OwnedSlice;
21 use syntax::parse::token::{self, str_to_ident};
22 use syntax::std_inject;
23
24 use std::cell::{Cell, RefCell};
25
26 pub struct LoweringContext<'a> {
27     crate_root: Option<&'static str>,
28     id_cache: RefCell<HashMap<NodeId, NodeId>>,
29     id_assigner: &'a NodeIdAssigner,
30     cached_id: Cell<u32>,
31 }
32
33 impl<'a, 'hir> LoweringContext<'a> {
34     pub fn new(id_assigner: &'a NodeIdAssigner, c: &Crate) -> LoweringContext<'a> {
35         let crate_root = if std_inject::no_core(c) {
36             None
37         } else if std_inject::no_std(c) {
38             Some("core")
39         } else {
40             Some("std")
41         };
42
43         LoweringContext {
44             crate_root: crate_root,
45             id_cache: RefCell::new(HashMap::new()),
46             id_assigner: id_assigner,
47             cached_id: Cell::new(0),
48         }
49     }
50
51     fn next_id(&self) -> NodeId {
52         let cached = self.cached_id.get();
53         if cached == 0 {
54             return self.id_assigner.next_node_id()
55         }
56
57         self.cached_id.set(cached + 1);
58         cached
59     }
60 }
61
62 pub fn lower_view_path(_lctx: &LoweringContext, view_path: &ViewPath) -> P<hir::ViewPath> {
63     P(Spanned {
64         node: match view_path.node {
65             ViewPathSimple(ident, ref path) => {
66                 hir::ViewPathSimple(ident.name, lower_path(_lctx, path))
67             }
68             ViewPathGlob(ref path) => {
69                 hir::ViewPathGlob(lower_path(_lctx, path))
70             }
71             ViewPathList(ref path, ref path_list_idents) => {
72                 hir::ViewPathList(lower_path(_lctx, path),
73                              path_list_idents.iter().map(|path_list_ident| {
74                                 Spanned {
75                                     node: match path_list_ident.node {
76                                         PathListIdent { id, name, rename } =>
77                                             hir::PathListIdent {
78                                                 id: id,
79                                                 name: name.name,
80                                                 rename: rename.map(|x| x.name),
81                                             },
82                                         PathListMod { id, rename } =>
83                                             hir::PathListMod {
84                                                 id: id,
85                                                 rename: rename.map(|x| x.name)
86                                             }
87                                     },
88                                     span: path_list_ident.span
89                                 }
90                              }).collect())
91             }
92         },
93         span: view_path.span,
94     })
95 }
96
97 pub fn lower_arm(_lctx: &LoweringContext, arm: &Arm) -> hir::Arm {
98     hir::Arm {
99         attrs: arm.attrs.clone(),
100         pats: arm.pats.iter().map(|x| lower_pat(_lctx, x)).collect(),
101         guard: arm.guard.as_ref().map(|ref x| lower_expr(_lctx, x)),
102         body: lower_expr(_lctx, &arm.body),
103     }
104 }
105
106 pub fn lower_decl(_lctx: &LoweringContext, d: &Decl) -> P<hir::Decl> {
107     match d.node {
108         DeclLocal(ref l) => P(Spanned {
109             node: hir::DeclLocal(lower_local(_lctx, l)),
110             span: d.span
111         }),
112         DeclItem(ref it) => P(Spanned {
113             node: hir::DeclItem(lower_item(_lctx, it)),
114             span: d.span
115         }),
116     }
117 }
118
119 pub fn lower_ty_binding(_lctx: &LoweringContext, b: &TypeBinding) -> P<hir::TypeBinding> {
120     P(hir::TypeBinding { id: b.id, name: b.ident.name, ty: lower_ty(_lctx, &b.ty), span: b.span })
121 }
122
123 pub fn lower_ty(_lctx: &LoweringContext, t: &Ty) -> P<hir::Ty> {
124     P(hir::Ty {
125         id: t.id,
126         node: match t.node {
127             TyInfer => hir::TyInfer,
128             TyVec(ref ty) => hir::TyVec(lower_ty(_lctx, ty)),
129             TyPtr(ref mt) => hir::TyPtr(lower_mt(_lctx, mt)),
130             TyRptr(ref region, ref mt) => {
131                 hir::TyRptr(lower_opt_lifetime(_lctx, region), lower_mt(_lctx, mt))
132             }
133             TyBareFn(ref f) => {
134                 hir::TyBareFn(P(hir::BareFnTy {
135                     lifetimes: lower_lifetime_defs(_lctx, &f.lifetimes),
136                     unsafety: lower_unsafety(_lctx, f.unsafety),
137                     abi: f.abi,
138                     decl: lower_fn_decl(_lctx, &f.decl),
139                 }))
140             }
141             TyTup(ref tys) => hir::TyTup(tys.iter().map(|ty| lower_ty(_lctx, ty)).collect()),
142             TyParen(ref ty) => hir::TyParen(lower_ty(_lctx, ty)),
143             TyPath(ref qself, ref path) => {
144                 let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
145                     hir::QSelf {
146                         ty: lower_ty(_lctx, ty),
147                         position: position,
148                     }
149                 });
150                 hir::TyPath(qself, lower_path(_lctx, path))
151             }
152             TyObjectSum(ref ty, ref bounds) => {
153                 hir::TyObjectSum(lower_ty(_lctx, ty),
154                             lower_bounds(_lctx, bounds))
155             }
156             TyFixedLengthVec(ref ty, ref e) => {
157                 hir::TyFixedLengthVec(lower_ty(_lctx, ty), lower_expr(_lctx, e))
158             }
159             TyTypeof(ref expr) => {
160                 hir::TyTypeof(lower_expr(_lctx, expr))
161             }
162             TyPolyTraitRef(ref bounds) => {
163                 hir::TyPolyTraitRef(bounds.iter().map(|b| lower_ty_param_bound(_lctx, b)).collect())
164             }
165             TyMac(_) => panic!("TyMac should have been expanded by now."),
166         },
167         span: t.span,
168     })
169 }
170
171 pub fn lower_foreign_mod(_lctx: &LoweringContext, fm: &ForeignMod) -> hir::ForeignMod {
172     hir::ForeignMod {
173         abi: fm.abi,
174         items: fm.items.iter().map(|x| lower_foreign_item(_lctx, x)).collect(),
175     }
176 }
177
178 pub fn lower_variant(_lctx: &LoweringContext, v: &Variant) -> P<hir::Variant> {
179     P(Spanned {
180         node: hir::Variant_ {
181             id: v.node.id,
182             name: v.node.name.name,
183             attrs: v.node.attrs.clone(),
184             kind: match v.node.kind {
185                 TupleVariantKind(ref variant_args) => {
186                     hir::TupleVariantKind(variant_args.iter().map(|ref x|
187                         lower_variant_arg(_lctx, x)).collect())
188                 }
189                 StructVariantKind(ref struct_def) => {
190                     hir::StructVariantKind(lower_struct_def(_lctx, struct_def))
191                 }
192             },
193             disr_expr: v.node.disr_expr.as_ref().map(|e| lower_expr(_lctx, e)),
194         },
195         span: v.span,
196     })
197 }
198
199 pub fn lower_path(_lctx: &LoweringContext, p: &Path) -> hir::Path {
200     hir::Path {
201         global: p.global,
202         segments: p.segments.iter().map(|&PathSegment {identifier, ref parameters}|
203             hir::PathSegment {
204                 identifier: identifier,
205                 parameters: lower_path_parameters(_lctx, parameters),
206             }).collect(),
207         span: p.span,
208     }
209 }
210
211 pub fn lower_path_parameters(_lctx: &LoweringContext,
212                              path_parameters: &PathParameters)
213                              -> hir::PathParameters {
214     match *path_parameters {
215         AngleBracketedParameters(ref data) =>
216             hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(_lctx, data)),
217         ParenthesizedParameters(ref data) =>
218             hir::ParenthesizedParameters(lower_parenthesized_parameter_data(_lctx, data)),
219     }
220 }
221
222 pub fn lower_angle_bracketed_parameter_data(_lctx: &LoweringContext,
223                                             data: &AngleBracketedParameterData)
224                                             -> hir::AngleBracketedParameterData {
225     let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
226     hir::AngleBracketedParameterData {
227         lifetimes: lower_lifetimes(_lctx, lifetimes),
228         types: types.iter().map(|ty| lower_ty(_lctx, ty)).collect(),
229         bindings: bindings.iter().map(|b| lower_ty_binding(_lctx, b)).collect(),
230     }
231 }
232
233 pub fn lower_parenthesized_parameter_data(_lctx: &LoweringContext,
234                                           data: &ParenthesizedParameterData)
235                                           -> hir::ParenthesizedParameterData {
236     let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
237     hir::ParenthesizedParameterData {
238         inputs: inputs.iter().map(|ty| lower_ty(_lctx, ty)).collect(),
239         output: output.as_ref().map(|ty| lower_ty(_lctx, ty)),
240         span: span,
241     }
242 }
243
244 pub fn lower_local(_lctx: &LoweringContext, l: &Local) -> P<hir::Local> {
245     P(hir::Local {
246             id: l.id,
247             ty: l.ty.as_ref().map(|t| lower_ty(_lctx, t)),
248             pat: lower_pat(_lctx, &l.pat),
249             init: l.init.as_ref().map(|e| lower_expr(_lctx, e)),
250             span: l.span,
251         })
252 }
253
254 pub fn lower_explicit_self_underscore(_lctx: &LoweringContext,
255                                       es: &ExplicitSelf_)
256                                       -> hir::ExplicitSelf_ {
257     match *es {
258         SelfStatic => hir::SelfStatic,
259         SelfValue(v) => hir::SelfValue(v.name),
260         SelfRegion(ref lifetime, m, ident) => {
261             hir::SelfRegion(lower_opt_lifetime(_lctx, lifetime),
262                             lower_mutability(_lctx, m),
263                             ident.name)
264         }
265         SelfExplicit(ref typ, ident) => {
266             hir::SelfExplicit(lower_ty(_lctx, typ), ident.name)
267         }
268     }
269 }
270
271 pub fn lower_mutability(_lctx: &LoweringContext, m: Mutability) -> hir::Mutability {
272     match m {
273         MutMutable => hir::MutMutable,
274         MutImmutable => hir::MutImmutable,
275     }
276 }
277
278 pub fn lower_explicit_self(_lctx: &LoweringContext, s: &ExplicitSelf) -> hir::ExplicitSelf {
279     Spanned { node: lower_explicit_self_underscore(_lctx, &s.node), span: s.span }
280 }
281
282 pub fn lower_arg(_lctx: &LoweringContext, arg: &Arg) -> hir::Arg {
283     hir::Arg { id: arg.id, pat: lower_pat(_lctx, &arg.pat), ty: lower_ty(_lctx, &arg.ty) }
284 }
285
286 pub fn lower_fn_decl(_lctx: &LoweringContext, decl: &FnDecl) -> P<hir::FnDecl> {
287     P(hir::FnDecl {
288         inputs: decl.inputs.iter().map(|x| lower_arg(_lctx, x)).collect(),
289         output: match decl.output {
290             Return(ref ty) => hir::Return(lower_ty(_lctx, ty)),
291             DefaultReturn(span) => hir::DefaultReturn(span),
292             NoReturn(span) => hir::NoReturn(span),
293         },
294         variadic: decl.variadic,
295     })
296 }
297
298 pub fn lower_ty_param_bound(_lctx: &LoweringContext, tpb: &TyParamBound) -> hir::TyParamBound {
299     match *tpb {
300         TraitTyParamBound(ref ty, modifier) => {
301             hir::TraitTyParamBound(lower_poly_trait_ref(_lctx, ty),
302                                    lower_trait_bound_modifier(_lctx, modifier))
303         }
304         RegionTyParamBound(ref lifetime) => {
305             hir::RegionTyParamBound(lower_lifetime(_lctx, lifetime))
306         }
307     }
308 }
309
310 pub fn lower_ty_param(_lctx: &LoweringContext, tp: &TyParam) -> hir::TyParam {
311     hir::TyParam {
312         id: tp.id,
313         name: tp.ident.name,
314         bounds: lower_bounds(_lctx, &tp.bounds),
315         default: tp.default.as_ref().map(|x| lower_ty(_lctx, x)),
316         span: tp.span,
317     }
318 }
319
320 pub fn lower_ty_params(_lctx: &LoweringContext,
321                        tps: &OwnedSlice<TyParam>)
322                        -> OwnedSlice<hir::TyParam> {
323     tps.iter().map(|tp| lower_ty_param(_lctx, tp)).collect()
324 }
325
326 pub fn lower_lifetime(_lctx: &LoweringContext, l: &Lifetime) -> hir::Lifetime {
327     hir::Lifetime { id: l.id, name: l.name, span: l.span }
328 }
329
330 pub fn lower_lifetime_def(_lctx: &LoweringContext, l: &LifetimeDef) -> hir::LifetimeDef {
331     hir::LifetimeDef {
332         lifetime: lower_lifetime(_lctx, &l.lifetime),
333         bounds: lower_lifetimes(_lctx, &l.bounds)
334     }
335 }
336
337 pub fn lower_lifetimes(_lctx: &LoweringContext, lts: &Vec<Lifetime>) -> Vec<hir::Lifetime> {
338     lts.iter().map(|l| lower_lifetime(_lctx, l)).collect()
339 }
340
341 pub fn lower_lifetime_defs(_lctx: &LoweringContext,
342                            lts: &Vec<LifetimeDef>)
343                            -> Vec<hir::LifetimeDef> {
344     lts.iter().map(|l| lower_lifetime_def(_lctx, l)).collect()
345 }
346
347 pub fn lower_opt_lifetime(_lctx: &LoweringContext,
348                           o_lt: &Option<Lifetime>)
349                           -> Option<hir::Lifetime> {
350     o_lt.as_ref().map(|lt| lower_lifetime(_lctx, lt))
351 }
352
353 pub fn lower_generics(_lctx: &LoweringContext, g: &Generics) -> hir::Generics {
354     hir::Generics {
355         ty_params: lower_ty_params(_lctx, &g.ty_params),
356         lifetimes: lower_lifetime_defs(_lctx, &g.lifetimes),
357         where_clause: lower_where_clause(_lctx, &g.where_clause),
358     }
359 }
360
361 pub fn lower_where_clause(_lctx: &LoweringContext, wc: &WhereClause) -> hir::WhereClause {
362     hir::WhereClause {
363         id: wc.id,
364         predicates: wc.predicates.iter().map(|predicate|
365             lower_where_predicate(_lctx, predicate)).collect(),
366     }
367 }
368
369 pub fn lower_where_predicate(_lctx: &LoweringContext,
370                              pred: &WherePredicate)
371                              -> hir::WherePredicate {
372     match *pred {
373         WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
374                                                             ref bounded_ty,
375                                                             ref bounds,
376                                                             span}) => {
377             hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
378                 bound_lifetimes: lower_lifetime_defs(_lctx, bound_lifetimes),
379                 bounded_ty: lower_ty(_lctx, bounded_ty),
380                 bounds: bounds.iter().map(|x| lower_ty_param_bound(_lctx, x)).collect(),
381                 span: span
382             })
383         }
384         WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
385                                                               ref bounds,
386                                                               span}) => {
387             hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
388                 span: span,
389                 lifetime: lower_lifetime(_lctx, lifetime),
390                 bounds: bounds.iter().map(|bound| lower_lifetime(_lctx, bound)).collect()
391             })
392         }
393         WherePredicate::EqPredicate(WhereEqPredicate{ id,
394                                                       ref path,
395                                                       ref ty,
396                                                       span}) => {
397             hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
398                 id: id,
399                 path: lower_path(_lctx, path),
400                 ty:lower_ty(_lctx, ty),
401                 span: span
402             })
403         }
404     }
405 }
406
407 pub fn lower_struct_def(_lctx: &LoweringContext, sd: &StructDef) -> P<hir::StructDef> {
408     P(hir::StructDef {
409         fields: sd.fields.iter().map(|f| lower_struct_field(_lctx, f)).collect(),
410         ctor_id: sd.ctor_id,
411     })
412 }
413
414 pub fn lower_trait_ref(_lctx: &LoweringContext, p: &TraitRef) -> hir::TraitRef {
415     hir::TraitRef { path: lower_path(_lctx, &p.path), ref_id: p.ref_id }
416 }
417
418 pub fn lower_poly_trait_ref(_lctx: &LoweringContext, p: &PolyTraitRef) -> hir::PolyTraitRef {
419     hir::PolyTraitRef {
420         bound_lifetimes: lower_lifetime_defs(_lctx, &p.bound_lifetimes),
421         trait_ref: lower_trait_ref(_lctx, &p.trait_ref),
422         span: p.span,
423     }
424 }
425
426 pub fn lower_struct_field(_lctx: &LoweringContext, f: &StructField) -> hir::StructField {
427     Spanned {
428         node: hir::StructField_ {
429             id: f.node.id,
430             kind: lower_struct_field_kind(_lctx, &f.node.kind),
431             ty: lower_ty(_lctx, &f.node.ty),
432             attrs: f.node.attrs.clone(),
433         },
434         span: f.span,
435     }
436 }
437
438 pub fn lower_field(_lctx: &LoweringContext, f: &Field) -> hir::Field {
439     hir::Field {
440         name: respan(f.ident.span, f.ident.node.name),
441         expr: lower_expr(_lctx, &f.expr), span: f.span
442     }
443 }
444
445 pub fn lower_mt(_lctx: &LoweringContext, mt: &MutTy) -> hir::MutTy {
446     hir::MutTy { ty: lower_ty(_lctx, &mt.ty), mutbl: lower_mutability(_lctx, mt.mutbl) }
447 }
448
449 pub fn lower_opt_bounds(_lctx: &LoweringContext, b: &Option<OwnedSlice<TyParamBound>>)
450                         -> Option<OwnedSlice<hir::TyParamBound>> {
451     b.as_ref().map(|ref bounds| lower_bounds(_lctx, bounds))
452 }
453
454 fn lower_bounds(_lctx: &LoweringContext, bounds: &TyParamBounds) -> hir::TyParamBounds {
455     bounds.iter().map(|bound| lower_ty_param_bound(_lctx, bound)).collect()
456 }
457
458 fn lower_variant_arg(_lctx: &LoweringContext, va: &VariantArg) -> hir::VariantArg {
459     hir::VariantArg { id: va.id, ty: lower_ty(_lctx, &va.ty) }
460 }
461
462 pub fn lower_block(_lctx: &LoweringContext, b: &Block) -> P<hir::Block> {
463     P(hir::Block {
464         id: b.id,
465         stmts: b.stmts.iter().map(|s| lower_stmt(_lctx, s)).collect(),
466         expr: b.expr.as_ref().map(|ref x| lower_expr(_lctx, x)),
467         rules: lower_block_check_mode(_lctx, &b.rules),
468         span: b.span,
469     })
470 }
471
472 pub fn lower_item_underscore(_lctx: &LoweringContext, i: &Item_) -> hir::Item_ {
473     match *i {
474         ItemExternCrate(string) => hir::ItemExternCrate(string),
475         ItemUse(ref view_path) => {
476             hir::ItemUse(lower_view_path(_lctx, view_path))
477         }
478         ItemStatic(ref t, m, ref e) => {
479             hir::ItemStatic(lower_ty(_lctx, t), lower_mutability(_lctx, m), lower_expr(_lctx, e))
480         }
481         ItemConst(ref t, ref e) => {
482             hir::ItemConst(lower_ty(_lctx, t), lower_expr(_lctx, e))
483         }
484         ItemFn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
485             hir::ItemFn(
486                 lower_fn_decl(_lctx, decl),
487                 lower_unsafety(_lctx, unsafety),
488                 lower_constness(_lctx, constness),
489                 abi,
490                 lower_generics(_lctx, generics),
491                 lower_block(_lctx, body)
492             )
493         }
494         ItemMod(ref m) => hir::ItemMod(lower_mod(_lctx, m)),
495         ItemForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(_lctx, nm)),
496         ItemTy(ref t, ref generics) => {
497             hir::ItemTy(lower_ty(_lctx, t), lower_generics(_lctx, generics))
498         }
499         ItemEnum(ref enum_definition, ref generics) => {
500             hir::ItemEnum(
501                 hir::EnumDef {
502                     variants: enum_definition.variants.iter().map(|x| {
503                         lower_variant(_lctx, x)
504                     }).collect(),
505                 },
506                 lower_generics(_lctx, generics))
507         }
508         ItemStruct(ref struct_def, ref generics) => {
509             let struct_def = lower_struct_def(_lctx, struct_def);
510             hir::ItemStruct(struct_def, lower_generics(_lctx, generics))
511         }
512         ItemDefaultImpl(unsafety, ref trait_ref) => {
513             hir::ItemDefaultImpl(lower_unsafety(_lctx, unsafety), lower_trait_ref(_lctx, trait_ref))
514         }
515         ItemImpl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
516             let new_impl_items =
517                 impl_items.iter().map(|item| lower_impl_item(_lctx, item)).collect();
518             let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(_lctx, trait_ref));
519             hir::ItemImpl(lower_unsafety(_lctx, unsafety),
520                           lower_impl_polarity(_lctx, polarity),
521                           lower_generics(_lctx, generics),
522                           ifce,
523                           lower_ty(_lctx, ty),
524                           new_impl_items)
525         }
526         ItemTrait(unsafety, ref generics, ref bounds, ref items) => {
527             let bounds = lower_bounds(_lctx, bounds);
528             let items = items.iter().map(|item| lower_trait_item(_lctx, item)).collect();
529             hir::ItemTrait(lower_unsafety(_lctx, unsafety),
530                            lower_generics(_lctx, generics),
531                            bounds,
532                            items)
533         }
534         ItemMac(_) => panic!("Shouldn't still be around"),
535     }
536 }
537
538 pub fn lower_trait_item(_lctx: &LoweringContext, i: &TraitItem) -> P<hir::TraitItem> {
539     P(hir::TraitItem {
540         id: i.id,
541         name: i.ident.name,
542         attrs: i.attrs.clone(),
543         node: match i.node {
544             ConstTraitItem(ref ty, ref default) => {
545                 hir::ConstTraitItem(lower_ty(_lctx, ty),
546                                     default.as_ref().map(|x| lower_expr(_lctx, x)))
547             }
548             MethodTraitItem(ref sig, ref body) => {
549                 hir::MethodTraitItem(lower_method_sig(_lctx, sig),
550                                      body.as_ref().map(|x| lower_block(_lctx, x)))
551             }
552             TypeTraitItem(ref bounds, ref default) => {
553                 hir::TypeTraitItem(lower_bounds(_lctx, bounds),
554                                    default.as_ref().map(|x| lower_ty(_lctx, x)))
555             }
556         },
557         span: i.span,
558     })
559 }
560
561 pub fn lower_impl_item(_lctx: &LoweringContext, i: &ImplItem) -> P<hir::ImplItem> {
562     P(hir::ImplItem {
563             id: i.id,
564             name: i.ident.name,
565             attrs: i.attrs.clone(),
566             vis: lower_visibility(_lctx, i.vis),
567             node: match i.node  {
568             ConstImplItem(ref ty, ref expr) => {
569                 hir::ConstImplItem(lower_ty(_lctx, ty), lower_expr(_lctx, expr))
570             }
571             MethodImplItem(ref sig, ref body) => {
572                 hir::MethodImplItem(lower_method_sig(_lctx, sig),
573                                     lower_block(_lctx, body))
574             }
575             TypeImplItem(ref ty) => hir::TypeImplItem(lower_ty(_lctx, ty)),
576             MacImplItem(..) => panic!("Shouldn't exist any more"),
577         },
578         span: i.span,
579     })
580 }
581
582 pub fn lower_mod(_lctx: &LoweringContext, m: &Mod) -> hir::Mod {
583     hir::Mod { inner: m.inner, items: m.items.iter().map(|x| lower_item(_lctx, x)).collect() }
584 }
585
586 pub fn lower_crate(_lctx: &LoweringContext, c: &Crate) -> hir::Crate {
587     hir::Crate {
588         module: lower_mod(_lctx, &c.module),
589         attrs: c.attrs.clone(),
590         config: c.config.clone(),
591         span: c.span,
592         exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(_lctx, m)).collect(),
593     }
594 }
595
596 pub fn lower_macro_def(_lctx: &LoweringContext, m: &MacroDef) -> hir::MacroDef {
597     hir::MacroDef {
598         name: m.ident.name,
599         attrs: m.attrs.clone(),
600         id: m.id,
601         span: m.span,
602         imported_from: m.imported_from.map(|x| x.name),
603         export: m.export,
604         use_locally: m.use_locally,
605         allow_internal_unstable: m.allow_internal_unstable,
606         body: m.body.clone(),
607     }
608 }
609
610 // fold one item into possibly many items
611 pub fn lower_item(_lctx: &LoweringContext, i: &Item) -> P<hir::Item> {
612     P(lower_item_simple(_lctx, i))
613 }
614
615 // fold one item into exactly one item
616 pub fn lower_item_simple(_lctx: &LoweringContext, i: &Item) -> hir::Item {
617     let node = lower_item_underscore(_lctx, &i.node);
618
619     hir::Item {
620         id: i.id,
621         name: i.ident.name,
622         attrs: i.attrs.clone(),
623         node: node,
624         vis: lower_visibility(_lctx, i.vis),
625         span: i.span,
626     }
627 }
628
629 pub fn lower_foreign_item(_lctx: &LoweringContext, i: &ForeignItem) -> P<hir::ForeignItem> {
630     P(hir::ForeignItem {
631         id: i.id,
632         name: i.ident.name,
633         attrs: i.attrs.clone(),
634         node: match i.node {
635             ForeignItemFn(ref fdec, ref generics) => {
636                 hir::ForeignItemFn(lower_fn_decl(_lctx, fdec), lower_generics(_lctx, generics))
637             }
638             ForeignItemStatic(ref t, m) => {
639                 hir::ForeignItemStatic(lower_ty(_lctx, t), m)
640             }
641         },
642             vis: lower_visibility(_lctx, i.vis),
643             span: i.span,
644         })
645 }
646
647 pub fn lower_method_sig(_lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig {
648     hir::MethodSig {
649         generics: lower_generics(_lctx, &sig.generics),
650         abi: sig.abi,
651         explicit_self: lower_explicit_self(_lctx, &sig.explicit_self),
652         unsafety: lower_unsafety(_lctx, sig.unsafety),
653         constness: lower_constness(_lctx, sig.constness),
654         decl: lower_fn_decl(_lctx, &sig.decl),
655     }
656 }
657
658 pub fn lower_unsafety(_lctx: &LoweringContext, u: Unsafety) -> hir::Unsafety {
659     match u {
660         Unsafety::Unsafe => hir::Unsafety::Unsafe,
661         Unsafety::Normal => hir::Unsafety::Normal,
662     }
663 }
664
665 pub fn lower_constness(_lctx: &LoweringContext, c: Constness) -> hir::Constness {
666     match c {
667         Constness::Const => hir::Constness::Const,
668         Constness::NotConst => hir::Constness::NotConst,
669     }
670 }
671
672 pub fn lower_unop(_lctx: &LoweringContext, u: UnOp) -> hir::UnOp {
673     match u {
674         UnDeref => hir::UnDeref,
675         UnNot => hir::UnNot,
676         UnNeg => hir::UnNeg,
677     }
678 }
679
680 pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp {
681     Spanned {
682         node: match b.node {
683             BiAdd => hir::BiAdd,
684             BiSub => hir::BiSub,
685             BiMul => hir::BiMul,
686             BiDiv => hir::BiDiv,
687             BiRem => hir::BiRem,
688             BiAnd => hir::BiAnd,
689             BiOr => hir::BiOr,
690             BiBitXor => hir::BiBitXor,
691             BiBitAnd => hir::BiBitAnd,
692             BiBitOr => hir::BiBitOr,
693             BiShl => hir::BiShl,
694             BiShr => hir::BiShr,
695             BiEq => hir::BiEq,
696             BiLt => hir::BiLt,
697             BiLe => hir::BiLe,
698             BiNe => hir::BiNe,
699             BiGe => hir::BiGe,
700             BiGt => hir::BiGt,
701         },
702         span: b.span,
703     }
704 }
705
706 pub fn lower_pat(_lctx: &LoweringContext, p: &Pat) -> P<hir::Pat> {
707     P(hir::Pat {
708             id: p.id,
709             node: match p.node {
710             PatWild(k) => hir::PatWild(lower_pat_wild_kind(_lctx, k)),
711             PatIdent(ref binding_mode, pth1, ref sub) => {
712                 hir::PatIdent(lower_binding_mode(_lctx, binding_mode),
713                         pth1,
714                         sub.as_ref().map(|x| lower_pat(_lctx, x)))
715             }
716             PatLit(ref e) => hir::PatLit(lower_expr(_lctx, e)),
717             PatEnum(ref pth, ref pats) => {
718                 hir::PatEnum(lower_path(_lctx, pth),
719                              pats.as_ref()
720                                  .map(|pats| pats.iter().map(|x| lower_pat(_lctx, x)).collect()))
721             }
722             PatQPath(ref qself, ref pth) => {
723                 let qself = hir::QSelf {
724                     ty: lower_ty(_lctx, &qself.ty),
725                     position: qself.position,
726                 };
727                 hir::PatQPath(qself, lower_path(_lctx, pth))
728             }
729             PatStruct(ref pth, ref fields, etc) => {
730                 let pth = lower_path(_lctx, pth);
731                 let fs = fields.iter().map(|f| {
732                     Spanned { span: f.span,
733                               node: hir::FieldPat {
734                                   name: f.node.ident.name,
735                                   pat: lower_pat(_lctx, &f.node.pat),
736                                   is_shorthand: f.node.is_shorthand,
737                               }}
738                 }).collect();
739                 hir::PatStruct(pth, fs, etc)
740             }
741             PatTup(ref elts) => hir::PatTup(elts.iter().map(|x| lower_pat(_lctx, x)).collect()),
742             PatBox(ref inner) => hir::PatBox(lower_pat(_lctx, inner)),
743             PatRegion(ref inner, mutbl) => hir::PatRegion(lower_pat(_lctx, inner),
744                                                           lower_mutability(_lctx, mutbl)),
745             PatRange(ref e1, ref e2) => {
746                 hir::PatRange(lower_expr(_lctx, e1), lower_expr(_lctx, e2))
747             },
748             PatVec(ref before, ref slice, ref after) => {
749                 hir::PatVec(before.iter().map(|x| lower_pat(_lctx, x)).collect(),
750                        slice.as_ref().map(|x| lower_pat(_lctx, x)),
751                        after.iter().map(|x| lower_pat(_lctx, x)).collect())
752             }
753             PatMac(_) => panic!("Shouldn't exist here"),
754         },
755         span: p.span,
756     })
757 }
758
759 // RAII utility for setting and unsetting the cached id.
760 struct CachedIdSetter<'a> {
761     reset: bool,
762     lctx: &'a LoweringContext<'a>,
763 }
764
765 impl<'a> CachedIdSetter<'a> {
766     fn new(lctx: &'a LoweringContext, expr_id: NodeId) -> CachedIdSetter<'a> {
767         let id_cache: &mut HashMap<_, _> = &mut lctx.id_cache.borrow_mut();
768
769         if id_cache.contains_key(&expr_id) {
770             let cached_id = lctx.cached_id.get();
771             if cached_id == 0 {
772                 // We're entering a node where we need to track ids, but are not
773                 // yet tracking.
774                 lctx.cached_id.set(id_cache[&expr_id]);
775             } else {
776                 // We're already tracking - check that the tracked id is the same
777                 // as the expected id.
778                 assert!(cached_id == id_cache[&expr_id], "id mismatch");
779             }
780         } else {
781             id_cache.insert(expr_id, lctx.id_assigner.peek_node_id());
782         }
783
784         CachedIdSetter {
785             // Only reset the id if it was previously 0, i.e., was not cached.
786             // If it was cached, we are in a nested node, but our id count will
787             // still count towards the parent's count.
788             reset: lctx.cached_id.get() == 0,
789             lctx: lctx,
790         }
791     }
792 }
793
794 impl<'a> Drop for CachedIdSetter<'a> {
795     fn drop(&mut self) {
796         if self.reset {
797             self.lctx.cached_id.set(0);
798         }
799     }
800 }
801
802 pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
803     P(hir::Expr {
804             id: e.id,
805             node: match e.node {
806                 // Issue #22181:
807                 // Eventually a desugaring for `box EXPR`
808                 // (similar to the desugaring above for `in PLACE BLOCK`)
809                 // should go here, desugaring
810                 //
811                 // to:
812                 //
813                 // let mut place = BoxPlace::make_place();
814                 // let raw_place = Place::pointer(&mut place);
815                 // let value = $value;
816                 // unsafe {
817                 //     ::std::ptr::write(raw_place, value);
818                 //     Boxed::finalize(place)
819                 // }
820                 //
821                 // But for now there are type-inference issues doing that.
822                 ExprBox(ref e) => {
823                     hir::ExprBox(lower_expr(lctx, e))
824                 }
825
826                 // Desugar ExprBox: `in (PLACE) EXPR`
827                 ExprInPlace(ref placer, ref value_expr) => {
828                     // to:
829                     //
830                     // let p = PLACE;
831                     // let mut place = Placer::make_place(p);
832                     // let raw_place = Place::pointer(&mut place);
833                     // push_unsafe!({
834                     //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
835                     //     InPlace::finalize(place)
836                     // })
837                     let _old_cached = CachedIdSetter::new(lctx, e.id);
838
839                     let placer_expr = lower_expr(lctx, placer);
840                     let value_expr = lower_expr(lctx, value_expr);
841
842                     let placer_ident = token::gensym_ident("placer");
843                     let agent_ident = token::gensym_ident("place");
844                     let p_ptr_ident = token::gensym_ident("p_ptr");
845
846                     let make_place = ["ops", "Placer", "make_place"];
847                     let place_pointer = ["ops", "Place", "pointer"];
848                     let move_val_init = ["intrinsics", "move_val_init"];
849                     let inplace_finalize = ["ops", "InPlace", "finalize"];
850
851                     let make_call = |lctx, p, args| {
852                         let path = core_path(lctx, e.span, p);
853                         let path = expr_path(lctx, path);
854                         expr_call(lctx, e.span, path, args)
855                     };
856
857                     let mk_stmt_let = |lctx, bind, expr| {
858                         stmt_let(lctx, e.span, false, bind, expr)
859                     };
860                     let mk_stmt_let_mut = |lctx, bind, expr| {
861                         stmt_let(lctx, e.span, true, bind, expr)
862                     };
863
864                     // let placer = <placer_expr> ;
865                     let s1 = mk_stmt_let(lctx, placer_ident, placer_expr);
866
867                     // let mut place = Placer::make_place(placer);
868                     let s2 = {
869                         let call = make_call(lctx, &make_place, vec![expr_ident(lctx, e.span, placer_ident)]);
870                         mk_stmt_let_mut(lctx, agent_ident, call)
871                     };
872
873                     // let p_ptr = Place::pointer(&mut place);
874                     let s3 = {
875                         let args = vec![expr_mut_addr_of(lctx, e.span, expr_ident(lctx, e.span, agent_ident))];
876                         let call = make_call(lctx, &place_pointer, args);
877                         mk_stmt_let(lctx, p_ptr_ident, call)
878                     };
879
880                     // pop_unsafe!(EXPR));
881                     let pop_unsafe_expr =
882                         signal_block_expr(lctx,
883                                           vec![],
884                                           signal_block_expr(lctx,
885                                                             vec![],
886                                                             value_expr,
887                                                             e.span,
888                                                             hir::PopUnstableBlock),
889                                           e.span,
890                                           hir::PopUnsafeBlock(hir::CompilerGenerated));
891
892                     // push_unsafe!({
893                     //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
894                     //     InPlace::finalize(place)
895                     // })
896                     let expr = {
897                         let call_move_val_init =
898                             hir::StmtSemi(make_call(lctx,
899                                                     &move_val_init,
900                                                     vec![expr_ident(lctx, e.span, p_ptr_ident),
901                                                          pop_unsafe_expr]),
902                                           lctx.next_id());
903                         let call_move_val_init = respan(e.span, call_move_val_init);
904
905                         let call = make_call(lctx, &inplace_finalize, vec![expr_ident(lctx, e.span, agent_ident)]);
906                         signal_block_expr(lctx,
907                                           vec![P(call_move_val_init)],
908                                           call,
909                                           e.span,
910                                           hir::PushUnsafeBlock(hir::CompilerGenerated))
911                     };
912
913                     return signal_block_expr(lctx,
914                                              vec![s1, s2, s3],
915                                              expr,
916                                              e.span,
917                                              hir::PushUnstableBlock);
918                 }
919                 
920                 ExprVec(ref exprs) => {
921                     hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect())
922                 }
923                 ExprRepeat(ref expr, ref count) => {
924                     hir::ExprRepeat(lower_expr(lctx, expr), lower_expr(lctx, count))
925                 }
926                 ExprTup(ref elts) => {
927                     hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect())
928                 }
929                 ExprCall(ref f, ref args) => {
930                     hir::ExprCall(lower_expr(lctx, f),
931                              args.iter().map(|x| lower_expr(lctx, x)).collect())
932                 }
933                 ExprMethodCall(i, ref tps, ref args) => {
934                     hir::ExprMethodCall(
935                         respan(i.span, i.node.name),
936                         tps.iter().map(|x| lower_ty(lctx, x)).collect(),
937                         args.iter().map(|x| lower_expr(lctx, x)).collect())
938                 }
939                 ExprBinary(binop, ref lhs, ref rhs) => {
940                     hir::ExprBinary(lower_binop(lctx, binop),
941                             lower_expr(lctx, lhs),
942                             lower_expr(lctx, rhs))
943                 }
944                 ExprUnary(op, ref ohs) => {
945                     hir::ExprUnary(lower_unop(lctx, op), lower_expr(lctx, ohs))
946                 }
947                 ExprLit(ref l) => hir::ExprLit(P((**l).clone())),
948                 ExprCast(ref expr, ref ty) => {
949                     hir::ExprCast(lower_expr(lctx, expr), lower_ty(lctx, ty))
950                 }
951                 ExprAddrOf(m, ref ohs) => {
952                     hir::ExprAddrOf(lower_mutability(lctx, m), lower_expr(lctx, ohs))
953                 }
954                 // More complicated than you might expect because the else branch
955                 // might be `if let`.
956                 ExprIf(ref cond, ref blk, ref else_opt) => {
957                     let else_opt = else_opt.as_ref().map(|els| match els.node {
958                         ExprIfLet(..) => {
959                             let _old_cached = CachedIdSetter::new(lctx, e.id);
960                             // wrap the if-let expr in a block
961                             let span = els.span;
962                             let blk = P(hir::Block {
963                                 stmts: vec![],
964                                 expr: Some(lower_expr(lctx, els)),
965                                 id: lctx.next_id(),
966                                 rules: hir::DefaultBlock,
967                                 span: span
968                             });
969                             expr_block(lctx, blk)
970                         }
971                         _ => lower_expr(lctx, els)
972                     });
973
974                     hir::ExprIf(lower_expr(lctx, cond),
975                                 lower_block(lctx, blk),
976                                 else_opt)
977                 }
978                 ExprWhile(ref cond, ref body, opt_ident) => {
979                     hir::ExprWhile(lower_expr(lctx, cond),
980                               lower_block(lctx, body),
981                               opt_ident)
982                 }
983                 ExprLoop(ref body, opt_ident) => {
984                     hir::ExprLoop(lower_block(lctx, body),
985                             opt_ident)
986                 }
987                 ExprMatch(ref expr, ref arms) => {
988                     hir::ExprMatch(lower_expr(lctx, expr),
989                             arms.iter().map(|x| lower_arm(lctx, x)).collect(),
990                             hir::MatchSource::Normal)
991                 }
992                 ExprClosure(capture_clause, ref decl, ref body) => {
993                     hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
994                                 lower_fn_decl(lctx, decl),
995                                 lower_block(lctx, body))
996                 }
997                 ExprBlock(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
998                 ExprAssign(ref el, ref er) => {
999                     hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
1000                 }
1001                 ExprAssignOp(op, ref el, ref er) => {
1002                     hir::ExprAssignOp(lower_binop(lctx, op),
1003                                 lower_expr(lctx, el),
1004                                 lower_expr(lctx, er))
1005                 }
1006                 ExprField(ref el, ident) => {
1007                     hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name))
1008                 }
1009                 ExprTupField(ref el, ident) => {
1010                     hir::ExprTupField(lower_expr(lctx, el), ident)
1011                 }
1012                 ExprIndex(ref el, ref er) => {
1013                     hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
1014                 }
1015                 ExprRange(ref e1, ref e2) => {
1016                     hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)),
1017                               e2.as_ref().map(|x| lower_expr(lctx, x)))
1018                 }
1019                 ExprPath(ref qself, ref path) => {
1020                     let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
1021                         hir::QSelf {
1022                             ty: lower_ty(lctx, ty),
1023                             position: position
1024                         }
1025                     });
1026                     hir::ExprPath(qself, lower_path(lctx, path))
1027                 }
1028                 ExprBreak(opt_ident) => hir::ExprBreak(opt_ident),
1029                 ExprAgain(opt_ident) => hir::ExprAgain(opt_ident),
1030                 ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
1031                 ExprInlineAsm(InlineAsm {
1032                     ref inputs,
1033                     ref outputs,
1034                     ref asm,
1035                     asm_str_style,
1036                     ref clobbers,
1037                     volatile,
1038                     alignstack,
1039                     dialect,
1040                     expn_id,
1041                 }) => hir::ExprInlineAsm(hir::InlineAsm {
1042                     inputs: inputs.iter().map(|&(ref c, ref input)| {
1043                         (c.clone(), lower_expr(lctx, input))
1044                     }).collect(),
1045                     outputs: outputs.iter().map(|&(ref c, ref out, ref is_rw)| {
1046                         (c.clone(), lower_expr(lctx, out), *is_rw)
1047                     }).collect(),
1048                     asm: asm.clone(),
1049                     asm_str_style: asm_str_style,
1050                     clobbers: clobbers.clone(),
1051                     volatile: volatile,
1052                     alignstack: alignstack,
1053                     dialect: dialect,
1054                     expn_id: expn_id,
1055                 }),
1056                 ExprStruct(ref path, ref fields, ref maybe_expr) => {
1057                     hir::ExprStruct(lower_path(lctx, path),
1058                             fields.iter().map(|x| lower_field(lctx, x)).collect(),
1059                             maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
1060                 },
1061                 ExprParen(ref ex) => {
1062                     return lower_expr(lctx, ex);
1063                 }
1064
1065                 // Desugar ExprIfLet
1066                 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
1067                 ExprIfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
1068                     // to:
1069                     //
1070                     //   match <sub_expr> {
1071                     //     <pat> => <body>,
1072                     //     [_ if <else_opt_if_cond> => <else_opt_if_body>,]
1073                     //     _ => [<else_opt> | ()]
1074                     //   }
1075                 
1076                     let _old_cached = CachedIdSetter::new(lctx, e.id);
1077
1078                     // `<pat> => <body>`
1079                     let pat_arm = {
1080                         let body_expr = expr_block(lctx, lower_block(lctx, body));
1081                         arm(vec![lower_pat(lctx, pat)], body_expr)
1082                     };
1083
1084                     // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
1085                     let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e));
1086                     let else_if_arms = {
1087                         let mut arms = vec![];
1088                         loop {
1089                             let else_opt_continue = else_opt
1090                                 .and_then(|els| els.and_then(|els| match els.node {
1091                                 // else if
1092                                 hir::ExprIf(cond, then, else_opt) => {
1093                                     let pat_under = pat_wild(lctx, e.span);
1094                                     arms.push(hir::Arm {
1095                                         attrs: vec![],
1096                                         pats: vec![pat_under],
1097                                         guard: Some(cond),
1098                                         body: expr_block(lctx, then)
1099                                     });
1100                                     else_opt.map(|else_opt| (else_opt, true))
1101                                 }
1102                                 _ => Some((P(els), false))
1103                             }));
1104                             match else_opt_continue {
1105                                 Some((e, true)) => {
1106                                     else_opt = Some(e);
1107                                 }
1108                                 Some((e, false)) => {
1109                                     else_opt = Some(e);
1110                                     break;
1111                                 }
1112                                 None => {
1113                                     else_opt = None;
1114                                     break;
1115                                 }
1116                             }
1117                         }
1118                         arms
1119                     };
1120
1121                     let contains_else_clause = else_opt.is_some();
1122
1123                     // `_ => [<else_opt> | ()]`
1124                     let else_arm = {
1125                         let pat_under = pat_wild(lctx, e.span);
1126                         let else_expr = else_opt.unwrap_or_else(|| expr_tuple(lctx, e.span, vec![]));
1127                         arm(vec![pat_under], else_expr)
1128                     };
1129
1130                     let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
1131                     arms.push(pat_arm);
1132                     arms.extend(else_if_arms);
1133                     arms.push(else_arm);
1134
1135                     let match_expr = expr(lctx,
1136                                           e.span,
1137                                           hir::ExprMatch(lower_expr(lctx, sub_expr), arms,
1138                                                  hir::MatchSource::IfLetDesugar {
1139                                                      contains_else_clause: contains_else_clause,
1140                                                  }));
1141                     return match_expr;
1142                 }
1143
1144                 // Desugar ExprWhileLet
1145                 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
1146                 ExprWhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
1147                     // to:
1148                     //
1149                     //   [opt_ident]: loop {
1150                     //     match <sub_expr> {
1151                     //       <pat> => <body>,
1152                     //       _ => break
1153                     //     }
1154                     //   }
1155
1156                     let _old_cached = CachedIdSetter::new(lctx, e.id);
1157
1158                     // `<pat> => <body>`
1159                     let pat_arm = {
1160                         let body_expr = expr_block(lctx, lower_block(lctx, body));
1161                         arm(vec![lower_pat(lctx, pat)], body_expr)
1162                     };
1163
1164                     // `_ => break`
1165                     let break_arm = {
1166                         let pat_under = pat_wild(lctx, e.span);
1167                         let break_expr = expr_break(lctx, e.span);
1168                         arm(vec![pat_under], break_expr)
1169                     };
1170
1171                     // // `match <sub_expr> { ... }`
1172                     let arms = vec![pat_arm, break_arm];
1173                     let match_expr = expr(lctx,
1174                                           e.span,
1175                                           hir::ExprMatch(lower_expr(lctx, sub_expr), arms, hir::MatchSource::WhileLetDesugar));
1176
1177                     // `[opt_ident]: loop { ... }`
1178                     let loop_block = block_expr(lctx, match_expr);
1179                     return expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident));
1180                 }
1181
1182                 // Desugar ExprForLoop
1183                 // From: `[opt_ident]: for <pat> in <head> <body>`
1184                 ExprForLoop(ref pat, ref head, ref body, opt_ident) => {
1185                     // to:
1186                     //
1187                     //   {
1188                     //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1189                     //       mut iter => {
1190                     //         [opt_ident]: loop {
1191                     //           match ::std::iter::Iterator::next(&mut iter) {
1192                     //             ::std::option::Option::Some(<pat>) => <body>,
1193                     //             ::std::option::Option::None => break
1194                     //           }
1195                     //         }
1196                     //       }
1197                     //     };
1198                     //     result
1199                     //   }
1200
1201                     let _old_cached = CachedIdSetter::new(lctx, e.id);
1202
1203                     // expand <head>
1204                     let head = lower_expr(lctx, head);
1205
1206                     let iter = token::gensym_ident("iter");
1207
1208                     // `::std::option::Option::Some(<pat>) => <body>`
1209                     let pat_arm = {
1210                         let body_block = lower_block(lctx, body);
1211                         let body_span = body_block.span;
1212                         let body_expr = P(hir::Expr {
1213                             id: lctx.next_id(),
1214                             node: hir::ExprBlock(body_block),
1215                             span: body_span,
1216                         });
1217                         let pat = lower_pat(lctx, pat);
1218                         let some_pat = pat_some(lctx, e.span, pat);
1219
1220                         arm(vec![some_pat], body_expr)
1221                     };
1222
1223                     // `::std::option::Option::None => break`
1224                     let break_arm = {
1225                         let break_expr = expr_break(lctx, e.span);
1226
1227                         arm(vec![pat_none(lctx, e.span)], break_expr)
1228                     };
1229
1230                     // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1231                     let match_expr = {
1232                         let next_path = {
1233                             let strs = std_path(lctx, &["iter", "Iterator", "next"]);
1234
1235                             path_global(e.span, strs)
1236                         };
1237                         let ref_mut_iter = expr_mut_addr_of(lctx, e.span, expr_ident(lctx, e.span, iter));
1238                         let next_expr =
1239                             expr_call(lctx, e.span, expr_path(lctx, next_path), vec![ref_mut_iter]);
1240                         let arms = vec![pat_arm, break_arm];
1241
1242                         expr(lctx,
1243                              e.span,
1244                              hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar))
1245                     };
1246
1247                     // `[opt_ident]: loop { ... }`
1248                     let loop_block = block_expr(lctx, match_expr);
1249                     let loop_expr = expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident));
1250
1251                     // `mut iter => { ... }`
1252                     let iter_arm = {
1253                         let iter_pat =
1254                             pat_ident_binding_mode(lctx, e.span, iter, hir::BindByValue(hir::MutMutable));
1255                         arm(vec![iter_pat], loop_expr)
1256                     };
1257
1258                     // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1259                     let into_iter_expr = {
1260                         let into_iter_path = {
1261                             let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
1262
1263                             path_global(e.span, strs)
1264                         };
1265
1266                         expr_call(lctx, e.span, expr_path(lctx, into_iter_path), vec![head])
1267                     };
1268
1269                     let match_expr = expr_match(lctx, e.span, into_iter_expr, vec![iter_arm]);
1270
1271                     // `{ let result = ...; result }`
1272                     let result_ident = token::gensym_ident("result");
1273                     return expr_block(lctx,
1274                                       block_all(lctx,
1275                                                 e.span,
1276                                                 vec![stmt_let(lctx, e.span,
1277                                                               false,
1278                                                               result_ident,
1279                                                               match_expr)],
1280                                                 Some(expr_ident(lctx, e.span, result_ident))))
1281                 }
1282
1283                 ExprMac(_) => panic!("Shouldn't exist here"),
1284             },
1285             span: e.span,
1286         })
1287 }
1288
1289 pub fn lower_stmt(_lctx: &LoweringContext, s: &Stmt) -> P<hir::Stmt> {
1290     match s.node {
1291         StmtDecl(ref d, id) => {
1292             P(Spanned {
1293                 node: hir::StmtDecl(lower_decl(_lctx, d), id),
1294                 span: s.span
1295             })
1296         }
1297         StmtExpr(ref e, id) => {
1298             P(Spanned {
1299                 node: hir::StmtExpr(lower_expr(_lctx, e), id),
1300                 span: s.span
1301             })
1302         }
1303         StmtSemi(ref e, id) => {
1304             P(Spanned {
1305                 node: hir::StmtSemi(lower_expr(_lctx, e), id),
1306                 span: s.span
1307             })
1308         }
1309         StmtMac(..) => panic!("Shouldn't exist here"),
1310     }
1311 }
1312
1313 pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureClause) -> hir::CaptureClause {
1314     match c {
1315         CaptureByValue => hir::CaptureByValue,
1316         CaptureByRef => hir::CaptureByRef,
1317     }
1318 }
1319
1320 pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1321     match v {
1322         Public => hir::Public,
1323         Inherited => hir::Inherited,
1324     }
1325 }
1326
1327 pub fn lower_block_check_mode(_lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1328     match *b {
1329         DefaultBlock => hir::DefaultBlock,
1330         UnsafeBlock(u) => hir::UnsafeBlock(lower_unsafe_source(_lctx, u)),
1331         PushUnsafeBlock(u) => hir::PushUnsafeBlock(lower_unsafe_source(_lctx, u)),
1332         PopUnsafeBlock(u) => hir::PopUnsafeBlock(lower_unsafe_source(_lctx, u)),
1333     }
1334 }
1335
1336 pub fn lower_pat_wild_kind(_lctx: &LoweringContext, p: PatWildKind) -> hir::PatWildKind {
1337     match p {
1338         PatWildSingle => hir::PatWildSingle,
1339         PatWildMulti => hir::PatWildMulti,
1340     }
1341 }
1342
1343 pub fn lower_binding_mode(_lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1344     match *b {
1345         BindByRef(m) => hir::BindByRef(lower_mutability(_lctx, m)),
1346         BindByValue(m) => hir::BindByValue(lower_mutability(_lctx, m)),
1347     }
1348 }
1349
1350 pub fn lower_struct_field_kind(_lctx: &LoweringContext,
1351                                s: &StructFieldKind)
1352                                -> hir::StructFieldKind {
1353     match *s {
1354         NamedField(ident, vis) => hir::NamedField(ident.name, lower_visibility(_lctx, vis)),
1355         UnnamedField(vis) => hir::UnnamedField(lower_visibility(_lctx, vis)),
1356     }
1357 }
1358
1359 pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1360     match u {
1361         CompilerGenerated => hir::CompilerGenerated,
1362         UserProvided => hir::UserProvided,
1363     }
1364 }
1365
1366 pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1367     match i {
1368         ImplPolarity::Positive => hir::ImplPolarity::Positive,
1369         ImplPolarity::Negative => hir::ImplPolarity::Negative,
1370     }
1371 }
1372
1373 pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
1374                                   f: TraitBoundModifier)
1375                                   -> hir::TraitBoundModifier {
1376     match f {
1377         TraitBoundModifier::None => hir::TraitBoundModifier::None,
1378         TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
1379     }
1380 }
1381
1382 // Helper methods for building HIR.
1383
1384 fn arm(pats: Vec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1385     hir::Arm {
1386         attrs: vec!(),
1387         pats: pats,
1388         guard: None,
1389         body: expr
1390     }
1391 }
1392
1393 fn expr_break(lctx: &LoweringContext, span: Span) -> P<hir::Expr> {
1394     expr(lctx, span, hir::ExprBreak(None))
1395 }
1396
1397 fn expr_call(lctx: &LoweringContext, span: Span, e: P<hir::Expr>, args: Vec<P<hir::Expr>>) -> P<hir::Expr> {
1398     expr(lctx, span, hir::ExprCall(e, args))
1399 }
1400
1401 fn expr_ident(lctx: &LoweringContext, span: Span, id: Ident) -> P<hir::Expr> {
1402     expr_path(lctx, path_ident(span, id))
1403 }
1404
1405 fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>) -> P<hir::Expr> {
1406     expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e))
1407 }
1408
1409 fn expr_path(lctx: &LoweringContext, path: hir::Path) -> P<hir::Expr> {
1410     expr(lctx, path.span, hir::ExprPath(None, path))
1411 }
1412
1413 fn expr_match(lctx: &LoweringContext, span: Span, arg: P<hir::Expr>, arms: Vec<hir::Arm>) -> P<hir::Expr> {
1414     expr(lctx, span, hir::ExprMatch(arg, arms, hir::MatchSource::Normal))
1415 }
1416
1417 fn expr_block(lctx: &LoweringContext, b: P<hir::Block>) -> P<hir::Expr> {
1418     expr(lctx, b.span, hir::ExprBlock(b))
1419 }
1420
1421 fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: Vec<P<hir::Expr>>) -> P<hir::Expr> {
1422     expr(lctx, sp, hir::ExprTup(exprs))
1423 }
1424
1425 fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_) -> P<hir::Expr> {
1426     P(hir::Expr {
1427         id: lctx.next_id(),
1428         node: node,
1429         span: span,
1430     })
1431 }
1432
1433 fn stmt_let(lctx: &LoweringContext, sp: Span, mutbl: bool, ident: Ident, ex: P<hir::Expr>) -> P<hir::Stmt> {
1434     let pat = if mutbl {
1435         pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
1436     } else {
1437         pat_ident(lctx, sp, ident)
1438     };
1439     let local = P(hir::Local {
1440         pat: pat,
1441         ty: None,
1442         init: Some(ex),
1443         id: lctx.next_id(),
1444         span: sp,
1445     });
1446     let decl = respan(sp, hir::DeclLocal(local));
1447     P(respan(sp, hir::StmtDecl(P(decl), lctx.next_id())))
1448 }
1449
1450 fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
1451     block_all(lctx, expr.span, Vec::new(), Some(expr))
1452 }
1453
1454 fn block_all(lctx: &LoweringContext,
1455              span: Span,
1456              stmts: Vec<P<hir::Stmt>>,
1457              expr: Option<P<hir::Expr>>) -> P<hir::Block> {
1458         P(hir::Block {
1459             stmts: stmts,
1460             expr: expr,
1461             id: lctx.next_id(),
1462             rules: hir::DefaultBlock,
1463             span: span,
1464         })
1465 }
1466
1467 fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1468     let some = std_path(lctx, &["option", "Option", "Some"]);
1469     let path = path_global(span, some);
1470     pat_enum(lctx, span, path, vec!(pat))
1471 }
1472
1473 fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1474     let none = std_path(lctx, &["option", "Option", "None"]);
1475     let path = path_global(span, none);
1476     pat_enum(lctx, span, path, vec![])
1477 }
1478
1479 fn pat_enum(lctx: &LoweringContext, span: Span, path: hir::Path, subpats: Vec<P<hir::Pat>>) -> P<hir::Pat> {
1480     let pt = hir::PatEnum(path, Some(subpats));
1481     pat(lctx, span, pt)
1482 }
1483
1484 fn pat_ident(lctx: &LoweringContext, span: Span, ident: Ident) -> P<hir::Pat> {
1485     pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
1486 }
1487
1488 fn pat_ident_binding_mode(lctx: &LoweringContext,
1489                           span: Span,
1490                           ident: Ident,
1491                           bm: hir::BindingMode) -> P<hir::Pat> {
1492     let pat_ident = hir::PatIdent(bm, Spanned{span: span, node: ident}, None);
1493     pat(lctx, span, pat_ident)
1494 }
1495
1496 fn pat_wild(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1497     pat(lctx, span, hir::PatWild(hir::PatWildSingle))
1498 }
1499
1500 fn pat(lctx: &LoweringContext, span: Span, pat: hir::Pat_) -> P<hir::Pat> {
1501     P(hir::Pat { id: lctx.next_id(), node: pat, span: span })
1502 }
1503
1504 fn path_ident(span: Span, id: Ident) -> hir::Path {
1505     path(span, vec!(id))
1506 }
1507
1508 fn path(span: Span, strs: Vec<Ident> ) -> hir::Path {
1509     path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new())
1510 }
1511
1512 fn path_global(span: Span, strs: Vec<Ident> ) -> hir::Path {
1513     path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new())
1514 }
1515
1516 fn path_all(sp: Span,
1517             global: bool,
1518             mut idents: Vec<Ident> ,
1519             lifetimes: Vec<hir::Lifetime>,
1520             types: Vec<P<hir::Ty>>,
1521             bindings: Vec<P<hir::TypeBinding>> )
1522             -> hir::Path {
1523     let last_identifier = idents.pop().unwrap();
1524     let mut segments: Vec<hir::PathSegment> = idents.into_iter()
1525                                                     .map(|ident| {
1526         hir::PathSegment {
1527             identifier: ident,
1528             parameters: hir::PathParameters::none(),
1529         }
1530     }).collect();
1531     segments.push(hir::PathSegment {
1532         identifier: last_identifier,
1533         parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1534             lifetimes: lifetimes,
1535             types: OwnedSlice::from_vec(types),
1536             bindings: OwnedSlice::from_vec(bindings),
1537         })
1538     });
1539     hir::Path {
1540         span: sp,
1541         global: global,
1542         segments: segments,
1543     }
1544 }
1545
1546 fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<Ident> {
1547     let mut v = Vec::new();
1548     if let Some(s) = lctx.crate_root {
1549         v.push(str_to_ident(s));
1550     }
1551     v.extend(components.iter().map(|s| str_to_ident(s)));
1552     return v
1553 }
1554
1555 // Given suffix ["b","c","d"], returns path `::std::b::c::d` when
1556 // `fld.cx.use_std`, and `::core::b::c::d` otherwise.
1557 fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Path {
1558     let idents = std_path(lctx, components);
1559     path_global(span, idents)
1560 }
1561
1562 fn signal_block_expr(lctx: &LoweringContext, stmts: Vec<P<hir::Stmt>>, expr: P<hir::Expr>, span: Span, rule: hir::BlockCheckMode) -> P<hir::Expr> {
1563     expr_block(lctx, P(hir::Block {
1564         rules: rule, span: span, id: lctx.next_id(),
1565         stmts: stmts, expr: Some(expr),
1566     }))
1567 }