]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/lowering.rs
c8f5f89b669109142e1f2f485e214475c727d7fa
[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 syntax::ast::*;
16 use syntax::ptr::P;
17 use syntax::codemap::{respan, Spanned, Span};
18 use syntax::owned_slice::OwnedSlice;
19 use syntax::parse::token::{self, str_to_ident};
20 use syntax::std_inject;
21
22 pub struct LoweringContext<'a, 'hir> {
23     // TODO
24     foo: &'hir i32,
25     id_assigner: &'a NodeIdAssigner,
26     crate_root: Option<&'static str>,
27 }
28
29 impl<'a, 'hir> LoweringContext<'a, 'hir> {
30     pub fn new(foo: &'hir i32, id_assigner: &'a NodeIdAssigner, c: &Crate) -> LoweringContext<'a, 'hir> {
31         let crate_root = if std_inject::no_core(c) {
32             None
33         } else if std_inject::no_std(c) {
34             Some("core")
35         } else {
36             Some("std")
37         };
38
39         LoweringContext {
40             foo: foo,
41             id_assigner: id_assigner,
42             crate_root: crate_root,
43         }
44     }
45
46     fn next_id(&self) -> NodeId {
47         self.id_assigner.next_node_id()
48     }
49 }
50
51 pub fn lower_view_path(_lctx: &LoweringContext, view_path: &ViewPath) -> P<hir::ViewPath> {
52     P(Spanned {
53         node: match view_path.node {
54             ViewPathSimple(ident, ref path) => {
55                 hir::ViewPathSimple(ident.name, lower_path(_lctx, path))
56             }
57             ViewPathGlob(ref path) => {
58                 hir::ViewPathGlob(lower_path(_lctx, path))
59             }
60             ViewPathList(ref path, ref path_list_idents) => {
61                 hir::ViewPathList(lower_path(_lctx, path),
62                              path_list_idents.iter().map(|path_list_ident| {
63                                 Spanned {
64                                     node: match path_list_ident.node {
65                                         PathListIdent { id, name, rename } =>
66                                             hir::PathListIdent {
67                                                 id: id,
68                                                 name: name.name,
69                                                 rename: rename.map(|x| x.name),
70                                             },
71                                         PathListMod { id, rename } =>
72                                             hir::PathListMod {
73                                                 id: id,
74                                                 rename: rename.map(|x| x.name)
75                                             }
76                                     },
77                                     span: path_list_ident.span
78                                 }
79                              }).collect())
80             }
81         },
82         span: view_path.span,
83     })
84 }
85
86 pub fn lower_arm(_lctx: &LoweringContext, arm: &Arm) -> hir::Arm {
87     hir::Arm {
88         attrs: arm.attrs.clone(),
89         pats: arm.pats.iter().map(|x| lower_pat(_lctx, x)).collect(),
90         guard: arm.guard.as_ref().map(|ref x| lower_expr(_lctx, x)),
91         body: lower_expr(_lctx, &arm.body),
92     }
93 }
94
95 pub fn lower_decl(_lctx: &LoweringContext, d: &Decl) -> P<hir::Decl> {
96     match d.node {
97         DeclLocal(ref l) => P(Spanned {
98             node: hir::DeclLocal(lower_local(_lctx, l)),
99             span: d.span
100         }),
101         DeclItem(ref it) => P(Spanned {
102             node: hir::DeclItem(lower_item(_lctx, it)),
103             span: d.span
104         }),
105     }
106 }
107
108 pub fn lower_ty_binding(_lctx: &LoweringContext, b: &TypeBinding) -> P<hir::TypeBinding> {
109     P(hir::TypeBinding { id: b.id, name: b.ident.name, ty: lower_ty(_lctx, &b.ty), span: b.span })
110 }
111
112 pub fn lower_ty(_lctx: &LoweringContext, t: &Ty) -> P<hir::Ty> {
113     P(hir::Ty {
114         id: t.id,
115         node: match t.node {
116             TyInfer => hir::TyInfer,
117             TyVec(ref ty) => hir::TyVec(lower_ty(_lctx, ty)),
118             TyPtr(ref mt) => hir::TyPtr(lower_mt(_lctx, mt)),
119             TyRptr(ref region, ref mt) => {
120                 hir::TyRptr(lower_opt_lifetime(_lctx, region), lower_mt(_lctx, mt))
121             }
122             TyBareFn(ref f) => {
123                 hir::TyBareFn(P(hir::BareFnTy {
124                     lifetimes: lower_lifetime_defs(_lctx, &f.lifetimes),
125                     unsafety: lower_unsafety(_lctx, f.unsafety),
126                     abi: f.abi,
127                     decl: lower_fn_decl(_lctx, &f.decl),
128                 }))
129             }
130             TyTup(ref tys) => hir::TyTup(tys.iter().map(|ty| lower_ty(_lctx, ty)).collect()),
131             TyParen(ref ty) => hir::TyParen(lower_ty(_lctx, ty)),
132             TyPath(ref qself, ref path) => {
133                 let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
134                     hir::QSelf {
135                         ty: lower_ty(_lctx, ty),
136                         position: position,
137                     }
138                 });
139                 hir::TyPath(qself, lower_path(_lctx, path))
140             }
141             TyObjectSum(ref ty, ref bounds) => {
142                 hir::TyObjectSum(lower_ty(_lctx, ty),
143                             lower_bounds(_lctx, bounds))
144             }
145             TyFixedLengthVec(ref ty, ref e) => {
146                 hir::TyFixedLengthVec(lower_ty(_lctx, ty), lower_expr(_lctx, e))
147             }
148             TyTypeof(ref expr) => {
149                 hir::TyTypeof(lower_expr(_lctx, expr))
150             }
151             TyPolyTraitRef(ref bounds) => {
152                 hir::TyPolyTraitRef(bounds.iter().map(|b| lower_ty_param_bound(_lctx, b)).collect())
153             }
154             TyMac(_) => panic!("TyMac should have been expanded by now."),
155         },
156         span: t.span,
157     })
158 }
159
160 pub fn lower_foreign_mod(_lctx: &LoweringContext, fm: &ForeignMod) -> hir::ForeignMod {
161     hir::ForeignMod {
162         abi: fm.abi,
163         items: fm.items.iter().map(|x| lower_foreign_item(_lctx, x)).collect(),
164     }
165 }
166
167 pub fn lower_variant(_lctx: &LoweringContext, v: &Variant) -> P<hir::Variant> {
168     P(Spanned {
169         node: hir::Variant_ {
170             id: v.node.id,
171             name: v.node.name.name,
172             attrs: v.node.attrs.clone(),
173             kind: match v.node.kind {
174                 TupleVariantKind(ref variant_args) => {
175                     hir::TupleVariantKind(variant_args.iter().map(|ref x|
176                         lower_variant_arg(_lctx, x)).collect())
177                 }
178                 StructVariantKind(ref struct_def) => {
179                     hir::StructVariantKind(lower_struct_def(_lctx, struct_def))
180                 }
181             },
182             disr_expr: v.node.disr_expr.as_ref().map(|e| lower_expr(_lctx, e)),
183         },
184         span: v.span,
185     })
186 }
187
188 pub fn lower_path(_lctx: &LoweringContext, p: &Path) -> hir::Path {
189     hir::Path {
190         global: p.global,
191         segments: p.segments.iter().map(|&PathSegment {identifier, ref parameters}|
192             hir::PathSegment {
193                 identifier: identifier,
194                 parameters: lower_path_parameters(_lctx, parameters),
195             }).collect(),
196         span: p.span,
197     }
198 }
199
200 pub fn lower_path_parameters(_lctx: &LoweringContext,
201                              path_parameters: &PathParameters)
202                              -> hir::PathParameters {
203     match *path_parameters {
204         AngleBracketedParameters(ref data) =>
205             hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(_lctx, data)),
206         ParenthesizedParameters(ref data) =>
207             hir::ParenthesizedParameters(lower_parenthesized_parameter_data(_lctx, data)),
208     }
209 }
210
211 pub fn lower_angle_bracketed_parameter_data(_lctx: &LoweringContext,
212                                             data: &AngleBracketedParameterData)
213                                             -> hir::AngleBracketedParameterData {
214     let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
215     hir::AngleBracketedParameterData {
216         lifetimes: lower_lifetimes(_lctx, lifetimes),
217         types: types.iter().map(|ty| lower_ty(_lctx, ty)).collect(),
218         bindings: bindings.iter().map(|b| lower_ty_binding(_lctx, b)).collect(),
219     }
220 }
221
222 pub fn lower_parenthesized_parameter_data(_lctx: &LoweringContext,
223                                           data: &ParenthesizedParameterData)
224                                           -> hir::ParenthesizedParameterData {
225     let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
226     hir::ParenthesizedParameterData {
227         inputs: inputs.iter().map(|ty| lower_ty(_lctx, ty)).collect(),
228         output: output.as_ref().map(|ty| lower_ty(_lctx, ty)),
229         span: span,
230     }
231 }
232
233 pub fn lower_local(_lctx: &LoweringContext, l: &Local) -> P<hir::Local> {
234     P(hir::Local {
235             id: l.id,
236             ty: l.ty.as_ref().map(|t| lower_ty(_lctx, t)),
237             pat: lower_pat(_lctx, &l.pat),
238             init: l.init.as_ref().map(|e| lower_expr(_lctx, e)),
239             span: l.span,
240         })
241 }
242
243 pub fn lower_explicit_self_underscore(_lctx: &LoweringContext,
244                                       es: &ExplicitSelf_)
245                                       -> hir::ExplicitSelf_ {
246     match *es {
247         SelfStatic => hir::SelfStatic,
248         SelfValue(v) => hir::SelfValue(v.name),
249         SelfRegion(ref lifetime, m, ident) => {
250             hir::SelfRegion(lower_opt_lifetime(_lctx, lifetime),
251                             lower_mutability(_lctx, m),
252                             ident.name)
253         }
254         SelfExplicit(ref typ, ident) => {
255             hir::SelfExplicit(lower_ty(_lctx, typ), ident.name)
256         }
257     }
258 }
259
260 pub fn lower_mutability(_lctx: &LoweringContext, m: Mutability) -> hir::Mutability {
261     match m {
262         MutMutable => hir::MutMutable,
263         MutImmutable => hir::MutImmutable,
264     }
265 }
266
267 pub fn lower_explicit_self(_lctx: &LoweringContext, s: &ExplicitSelf) -> hir::ExplicitSelf {
268     Spanned { node: lower_explicit_self_underscore(_lctx, &s.node), span: s.span }
269 }
270
271 pub fn lower_arg(_lctx: &LoweringContext, arg: &Arg) -> hir::Arg {
272     hir::Arg { id: arg.id, pat: lower_pat(_lctx, &arg.pat), ty: lower_ty(_lctx, &arg.ty) }
273 }
274
275 pub fn lower_fn_decl(_lctx: &LoweringContext, decl: &FnDecl) -> P<hir::FnDecl> {
276     P(hir::FnDecl {
277         inputs: decl.inputs.iter().map(|x| lower_arg(_lctx, x)).collect(),
278         output: match decl.output {
279             Return(ref ty) => hir::Return(lower_ty(_lctx, ty)),
280             DefaultReturn(span) => hir::DefaultReturn(span),
281             NoReturn(span) => hir::NoReturn(span),
282         },
283         variadic: decl.variadic,
284     })
285 }
286
287 pub fn lower_ty_param_bound(_lctx: &LoweringContext, tpb: &TyParamBound) -> hir::TyParamBound {
288     match *tpb {
289         TraitTyParamBound(ref ty, modifier) => {
290             hir::TraitTyParamBound(lower_poly_trait_ref(_lctx, ty),
291                                    lower_trait_bound_modifier(_lctx, modifier))
292         }
293         RegionTyParamBound(ref lifetime) => {
294             hir::RegionTyParamBound(lower_lifetime(_lctx, lifetime))
295         }
296     }
297 }
298
299 pub fn lower_ty_param(_lctx: &LoweringContext, tp: &TyParam) -> hir::TyParam {
300     hir::TyParam {
301         id: tp.id,
302         name: tp.ident.name,
303         bounds: lower_bounds(_lctx, &tp.bounds),
304         default: tp.default.as_ref().map(|x| lower_ty(_lctx, x)),
305         span: tp.span,
306     }
307 }
308
309 pub fn lower_ty_params(_lctx: &LoweringContext,
310                        tps: &OwnedSlice<TyParam>)
311                        -> OwnedSlice<hir::TyParam> {
312     tps.iter().map(|tp| lower_ty_param(_lctx, tp)).collect()
313 }
314
315 pub fn lower_lifetime(_lctx: &LoweringContext, l: &Lifetime) -> hir::Lifetime {
316     hir::Lifetime { id: l.id, name: l.name, span: l.span }
317 }
318
319 pub fn lower_lifetime_def(_lctx: &LoweringContext, l: &LifetimeDef) -> hir::LifetimeDef {
320     hir::LifetimeDef {
321         lifetime: lower_lifetime(_lctx, &l.lifetime),
322         bounds: lower_lifetimes(_lctx, &l.bounds)
323     }
324 }
325
326 pub fn lower_lifetimes(_lctx: &LoweringContext, lts: &Vec<Lifetime>) -> Vec<hir::Lifetime> {
327     lts.iter().map(|l| lower_lifetime(_lctx, l)).collect()
328 }
329
330 pub fn lower_lifetime_defs(_lctx: &LoweringContext,
331                            lts: &Vec<LifetimeDef>)
332                            -> Vec<hir::LifetimeDef> {
333     lts.iter().map(|l| lower_lifetime_def(_lctx, l)).collect()
334 }
335
336 pub fn lower_opt_lifetime(_lctx: &LoweringContext,
337                           o_lt: &Option<Lifetime>)
338                           -> Option<hir::Lifetime> {
339     o_lt.as_ref().map(|lt| lower_lifetime(_lctx, lt))
340 }
341
342 pub fn lower_generics(_lctx: &LoweringContext, g: &Generics) -> hir::Generics {
343     hir::Generics {
344         ty_params: lower_ty_params(_lctx, &g.ty_params),
345         lifetimes: lower_lifetime_defs(_lctx, &g.lifetimes),
346         where_clause: lower_where_clause(_lctx, &g.where_clause),
347     }
348 }
349
350 pub fn lower_where_clause(_lctx: &LoweringContext, wc: &WhereClause) -> hir::WhereClause {
351     hir::WhereClause {
352         id: wc.id,
353         predicates: wc.predicates.iter().map(|predicate|
354             lower_where_predicate(_lctx, predicate)).collect(),
355     }
356 }
357
358 pub fn lower_where_predicate(_lctx: &LoweringContext,
359                              pred: &WherePredicate)
360                              -> hir::WherePredicate {
361     match *pred {
362         WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
363                                                             ref bounded_ty,
364                                                             ref bounds,
365                                                             span}) => {
366             hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
367                 bound_lifetimes: lower_lifetime_defs(_lctx, bound_lifetimes),
368                 bounded_ty: lower_ty(_lctx, bounded_ty),
369                 bounds: bounds.iter().map(|x| lower_ty_param_bound(_lctx, x)).collect(),
370                 span: span
371             })
372         }
373         WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
374                                                               ref bounds,
375                                                               span}) => {
376             hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
377                 span: span,
378                 lifetime: lower_lifetime(_lctx, lifetime),
379                 bounds: bounds.iter().map(|bound| lower_lifetime(_lctx, bound)).collect()
380             })
381         }
382         WherePredicate::EqPredicate(WhereEqPredicate{ id,
383                                                       ref path,
384                                                       ref ty,
385                                                       span}) => {
386             hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
387                 id: id,
388                 path: lower_path(_lctx, path),
389                 ty:lower_ty(_lctx, ty),
390                 span: span
391             })
392         }
393     }
394 }
395
396 pub fn lower_struct_def(_lctx: &LoweringContext, sd: &StructDef) -> P<hir::StructDef> {
397     P(hir::StructDef {
398         fields: sd.fields.iter().map(|f| lower_struct_field(_lctx, f)).collect(),
399         ctor_id: sd.ctor_id,
400     })
401 }
402
403 pub fn lower_trait_ref(_lctx: &LoweringContext, p: &TraitRef) -> hir::TraitRef {
404     hir::TraitRef { path: lower_path(_lctx, &p.path), ref_id: p.ref_id }
405 }
406
407 pub fn lower_poly_trait_ref(_lctx: &LoweringContext, p: &PolyTraitRef) -> hir::PolyTraitRef {
408     hir::PolyTraitRef {
409         bound_lifetimes: lower_lifetime_defs(_lctx, &p.bound_lifetimes),
410         trait_ref: lower_trait_ref(_lctx, &p.trait_ref),
411         span: p.span,
412     }
413 }
414
415 pub fn lower_struct_field(_lctx: &LoweringContext, f: &StructField) -> hir::StructField {
416     Spanned {
417         node: hir::StructField_ {
418             id: f.node.id,
419             kind: lower_struct_field_kind(_lctx, &f.node.kind),
420             ty: lower_ty(_lctx, &f.node.ty),
421             attrs: f.node.attrs.clone(),
422         },
423         span: f.span,
424     }
425 }
426
427 pub fn lower_field(_lctx: &LoweringContext, f: &Field) -> hir::Field {
428     hir::Field {
429         name: respan(f.ident.span, f.ident.node.name),
430         expr: lower_expr(_lctx, &f.expr), span: f.span
431     }
432 }
433
434 pub fn lower_mt(_lctx: &LoweringContext, mt: &MutTy) -> hir::MutTy {
435     hir::MutTy { ty: lower_ty(_lctx, &mt.ty), mutbl: lower_mutability(_lctx, mt.mutbl) }
436 }
437
438 pub fn lower_opt_bounds(_lctx: &LoweringContext, b: &Option<OwnedSlice<TyParamBound>>)
439                         -> Option<OwnedSlice<hir::TyParamBound>> {
440     b.as_ref().map(|ref bounds| lower_bounds(_lctx, bounds))
441 }
442
443 fn lower_bounds(_lctx: &LoweringContext, bounds: &TyParamBounds) -> hir::TyParamBounds {
444     bounds.iter().map(|bound| lower_ty_param_bound(_lctx, bound)).collect()
445 }
446
447 fn lower_variant_arg(_lctx: &LoweringContext, va: &VariantArg) -> hir::VariantArg {
448     hir::VariantArg { id: va.id, ty: lower_ty(_lctx, &va.ty) }
449 }
450
451 pub fn lower_block(_lctx: &LoweringContext, b: &Block) -> P<hir::Block> {
452     P(hir::Block {
453         id: b.id,
454         stmts: b.stmts.iter().map(|s| lower_stmt(_lctx, s)).collect(),
455         expr: b.expr.as_ref().map(|ref x| lower_expr(_lctx, x)),
456         rules: lower_block_check_mode(_lctx, &b.rules),
457         span: b.span,
458     })
459 }
460
461 pub fn lower_item_underscore(_lctx: &LoweringContext, i: &Item_) -> hir::Item_ {
462     match *i {
463         ItemExternCrate(string) => hir::ItemExternCrate(string),
464         ItemUse(ref view_path) => {
465             hir::ItemUse(lower_view_path(_lctx, view_path))
466         }
467         ItemStatic(ref t, m, ref e) => {
468             hir::ItemStatic(lower_ty(_lctx, t), lower_mutability(_lctx, m), lower_expr(_lctx, e))
469         }
470         ItemConst(ref t, ref e) => {
471             hir::ItemConst(lower_ty(_lctx, t), lower_expr(_lctx, e))
472         }
473         ItemFn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
474             hir::ItemFn(
475                 lower_fn_decl(_lctx, decl),
476                 lower_unsafety(_lctx, unsafety),
477                 lower_constness(_lctx, constness),
478                 abi,
479                 lower_generics(_lctx, generics),
480                 lower_block(_lctx, body)
481             )
482         }
483         ItemMod(ref m) => hir::ItemMod(lower_mod(_lctx, m)),
484         ItemForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(_lctx, nm)),
485         ItemTy(ref t, ref generics) => {
486             hir::ItemTy(lower_ty(_lctx, t), lower_generics(_lctx, generics))
487         }
488         ItemEnum(ref enum_definition, ref generics) => {
489             hir::ItemEnum(
490                 hir::EnumDef {
491                     variants: enum_definition.variants.iter().map(|x| {
492                         lower_variant(_lctx, x)
493                     }).collect(),
494                 },
495                 lower_generics(_lctx, generics))
496         }
497         ItemStruct(ref struct_def, ref generics) => {
498             let struct_def = lower_struct_def(_lctx, struct_def);
499             hir::ItemStruct(struct_def, lower_generics(_lctx, generics))
500         }
501         ItemDefaultImpl(unsafety, ref trait_ref) => {
502             hir::ItemDefaultImpl(lower_unsafety(_lctx, unsafety), lower_trait_ref(_lctx, trait_ref))
503         }
504         ItemImpl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
505             let new_impl_items =
506                 impl_items.iter().map(|item| lower_impl_item(_lctx, item)).collect();
507             let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(_lctx, trait_ref));
508             hir::ItemImpl(lower_unsafety(_lctx, unsafety),
509                           lower_impl_polarity(_lctx, polarity),
510                           lower_generics(_lctx, generics),
511                           ifce,
512                           lower_ty(_lctx, ty),
513                           new_impl_items)
514         }
515         ItemTrait(unsafety, ref generics, ref bounds, ref items) => {
516             let bounds = lower_bounds(_lctx, bounds);
517             let items = items.iter().map(|item| lower_trait_item(_lctx, item)).collect();
518             hir::ItemTrait(lower_unsafety(_lctx, unsafety),
519                            lower_generics(_lctx, generics),
520                            bounds,
521                            items)
522         }
523         ItemMac(_) => panic!("Shouldn't still be around"),
524     }
525 }
526
527 pub fn lower_trait_item(_lctx: &LoweringContext, i: &TraitItem) -> P<hir::TraitItem> {
528     P(hir::TraitItem {
529         id: i.id,
530         name: i.ident.name,
531         attrs: i.attrs.clone(),
532         node: match i.node {
533             ConstTraitItem(ref ty, ref default) => {
534                 hir::ConstTraitItem(lower_ty(_lctx, ty),
535                                     default.as_ref().map(|x| lower_expr(_lctx, x)))
536             }
537             MethodTraitItem(ref sig, ref body) => {
538                 hir::MethodTraitItem(lower_method_sig(_lctx, sig),
539                                      body.as_ref().map(|x| lower_block(_lctx, x)))
540             }
541             TypeTraitItem(ref bounds, ref default) => {
542                 hir::TypeTraitItem(lower_bounds(_lctx, bounds),
543                                    default.as_ref().map(|x| lower_ty(_lctx, x)))
544             }
545         },
546         span: i.span,
547     })
548 }
549
550 pub fn lower_impl_item(_lctx: &LoweringContext, i: &ImplItem) -> P<hir::ImplItem> {
551     P(hir::ImplItem {
552             id: i.id,
553             name: i.ident.name,
554             attrs: i.attrs.clone(),
555             vis: lower_visibility(_lctx, i.vis),
556             node: match i.node  {
557             ConstImplItem(ref ty, ref expr) => {
558                 hir::ConstImplItem(lower_ty(_lctx, ty), lower_expr(_lctx, expr))
559             }
560             MethodImplItem(ref sig, ref body) => {
561                 hir::MethodImplItem(lower_method_sig(_lctx, sig),
562                                     lower_block(_lctx, body))
563             }
564             TypeImplItem(ref ty) => hir::TypeImplItem(lower_ty(_lctx, ty)),
565             MacImplItem(..) => panic!("Shouldn't exist any more"),
566         },
567         span: i.span,
568     })
569 }
570
571 pub fn lower_mod(_lctx: &LoweringContext, m: &Mod) -> hir::Mod {
572     hir::Mod { inner: m.inner, items: m.items.iter().map(|x| lower_item(_lctx, x)).collect() }
573 }
574
575 pub fn lower_crate(_lctx: &LoweringContext, c: &Crate) -> hir::Crate {
576     hir::Crate {
577         module: lower_mod(_lctx, &c.module),
578         attrs: c.attrs.clone(),
579         config: c.config.clone(),
580         span: c.span,
581         exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(_lctx, m)).collect(),
582     }
583 }
584
585 pub fn lower_macro_def(_lctx: &LoweringContext, m: &MacroDef) -> hir::MacroDef {
586     hir::MacroDef {
587         name: m.ident.name,
588         attrs: m.attrs.clone(),
589         id: m.id,
590         span: m.span,
591         imported_from: m.imported_from.map(|x| x.name),
592         export: m.export,
593         use_locally: m.use_locally,
594         allow_internal_unstable: m.allow_internal_unstable,
595         body: m.body.clone(),
596     }
597 }
598
599 // fold one item into possibly many items
600 pub fn lower_item(_lctx: &LoweringContext, i: &Item) -> P<hir::Item> {
601     P(lower_item_simple(_lctx, i))
602 }
603
604 // fold one item into exactly one item
605 pub fn lower_item_simple(_lctx: &LoweringContext, i: &Item) -> hir::Item {
606     let node = lower_item_underscore(_lctx, &i.node);
607
608     hir::Item {
609         id: i.id,
610         name: i.ident.name,
611         attrs: i.attrs.clone(),
612         node: node,
613         vis: lower_visibility(_lctx, i.vis),
614         span: i.span,
615     }
616 }
617
618 pub fn lower_foreign_item(_lctx: &LoweringContext, i: &ForeignItem) -> P<hir::ForeignItem> {
619     P(hir::ForeignItem {
620         id: i.id,
621         name: i.ident.name,
622         attrs: i.attrs.clone(),
623         node: match i.node {
624             ForeignItemFn(ref fdec, ref generics) => {
625                 hir::ForeignItemFn(lower_fn_decl(_lctx, fdec), lower_generics(_lctx, generics))
626             }
627             ForeignItemStatic(ref t, m) => {
628                 hir::ForeignItemStatic(lower_ty(_lctx, t), m)
629             }
630         },
631             vis: lower_visibility(_lctx, i.vis),
632             span: i.span,
633         })
634 }
635
636 pub fn lower_method_sig(_lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig {
637     hir::MethodSig {
638         generics: lower_generics(_lctx, &sig.generics),
639         abi: sig.abi,
640         explicit_self: lower_explicit_self(_lctx, &sig.explicit_self),
641         unsafety: lower_unsafety(_lctx, sig.unsafety),
642         constness: lower_constness(_lctx, sig.constness),
643         decl: lower_fn_decl(_lctx, &sig.decl),
644     }
645 }
646
647 pub fn lower_unsafety(_lctx: &LoweringContext, u: Unsafety) -> hir::Unsafety {
648     match u {
649         Unsafety::Unsafe => hir::Unsafety::Unsafe,
650         Unsafety::Normal => hir::Unsafety::Normal,
651     }
652 }
653
654 pub fn lower_constness(_lctx: &LoweringContext, c: Constness) -> hir::Constness {
655     match c {
656         Constness::Const => hir::Constness::Const,
657         Constness::NotConst => hir::Constness::NotConst,
658     }
659 }
660
661 pub fn lower_unop(_lctx: &LoweringContext, u: UnOp) -> hir::UnOp {
662     match u {
663         UnDeref => hir::UnDeref,
664         UnNot => hir::UnNot,
665         UnNeg => hir::UnNeg,
666     }
667 }
668
669 pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp {
670     Spanned {
671         node: match b.node {
672             BiAdd => hir::BiAdd,
673             BiSub => hir::BiSub,
674             BiMul => hir::BiMul,
675             BiDiv => hir::BiDiv,
676             BiRem => hir::BiRem,
677             BiAnd => hir::BiAnd,
678             BiOr => hir::BiOr,
679             BiBitXor => hir::BiBitXor,
680             BiBitAnd => hir::BiBitAnd,
681             BiBitOr => hir::BiBitOr,
682             BiShl => hir::BiShl,
683             BiShr => hir::BiShr,
684             BiEq => hir::BiEq,
685             BiLt => hir::BiLt,
686             BiLe => hir::BiLe,
687             BiNe => hir::BiNe,
688             BiGe => hir::BiGe,
689             BiGt => hir::BiGt,
690         },
691         span: b.span,
692     }
693 }
694
695 pub fn lower_pat(_lctx: &LoweringContext, p: &Pat) -> P<hir::Pat> {
696     P(hir::Pat {
697             id: p.id,
698             node: match p.node {
699             PatWild(k) => hir::PatWild(lower_pat_wild_kind(_lctx, k)),
700             PatIdent(ref binding_mode, pth1, ref sub) => {
701                 hir::PatIdent(lower_binding_mode(_lctx, binding_mode),
702                         pth1,
703                         sub.as_ref().map(|x| lower_pat(_lctx, x)))
704             }
705             PatLit(ref e) => hir::PatLit(lower_expr(_lctx, e)),
706             PatEnum(ref pth, ref pats) => {
707                 hir::PatEnum(lower_path(_lctx, pth),
708                              pats.as_ref()
709                                  .map(|pats| pats.iter().map(|x| lower_pat(_lctx, x)).collect()))
710             }
711             PatQPath(ref qself, ref pth) => {
712                 let qself = hir::QSelf {
713                     ty: lower_ty(_lctx, &qself.ty),
714                     position: qself.position,
715                 };
716                 hir::PatQPath(qself, lower_path(_lctx, pth))
717             }
718             PatStruct(ref pth, ref fields, etc) => {
719                 let pth = lower_path(_lctx, pth);
720                 let fs = fields.iter().map(|f| {
721                     Spanned { span: f.span,
722                               node: hir::FieldPat {
723                                   name: f.node.ident.name,
724                                   pat: lower_pat(_lctx, &f.node.pat),
725                                   is_shorthand: f.node.is_shorthand,
726                               }}
727                 }).collect();
728                 hir::PatStruct(pth, fs, etc)
729             }
730             PatTup(ref elts) => hir::PatTup(elts.iter().map(|x| lower_pat(_lctx, x)).collect()),
731             PatBox(ref inner) => hir::PatBox(lower_pat(_lctx, inner)),
732             PatRegion(ref inner, mutbl) => hir::PatRegion(lower_pat(_lctx, inner),
733                                                           lower_mutability(_lctx, mutbl)),
734             PatRange(ref e1, ref e2) => {
735                 hir::PatRange(lower_expr(_lctx, e1), lower_expr(_lctx, e2))
736             },
737             PatVec(ref before, ref slice, ref after) => {
738                 hir::PatVec(before.iter().map(|x| lower_pat(_lctx, x)).collect(),
739                        slice.as_ref().map(|x| lower_pat(_lctx, x)),
740                        after.iter().map(|x| lower_pat(_lctx, x)).collect())
741             }
742             PatMac(_) => panic!("Shouldn't exist here"),
743         },
744         span: p.span,
745     })
746 }
747
748 pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
749     P(hir::Expr {
750             id: e.id,
751             node: match e.node {
752                 ExprBox(ref e) => {
753                     hir::ExprBox(lower_expr(lctx, e))
754                 }
755                 ExprVec(ref exprs) => {
756                     hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect())
757                 }
758                 ExprRepeat(ref expr, ref count) => {
759                     hir::ExprRepeat(lower_expr(lctx, expr), lower_expr(lctx, count))
760                 }
761                 ExprTup(ref elts) => {
762                     hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect())
763                 }
764                 ExprCall(ref f, ref args) => {
765                     hir::ExprCall(lower_expr(lctx, f),
766                              args.iter().map(|x| lower_expr(lctx, x)).collect())
767                 }
768                 ExprMethodCall(i, ref tps, ref args) => {
769                     hir::ExprMethodCall(
770                         respan(i.span, i.node.name),
771                         tps.iter().map(|x| lower_ty(lctx, x)).collect(),
772                         args.iter().map(|x| lower_expr(lctx, x)).collect())
773                 }
774                 ExprBinary(binop, ref lhs, ref rhs) => {
775                     hir::ExprBinary(lower_binop(lctx, binop),
776                             lower_expr(lctx, lhs),
777                             lower_expr(lctx, rhs))
778                 }
779                 ExprUnary(op, ref ohs) => {
780                     hir::ExprUnary(lower_unop(lctx, op), lower_expr(lctx, ohs))
781                 }
782                 ExprLit(ref l) => hir::ExprLit(P((**l).clone())),
783                 ExprCast(ref expr, ref ty) => {
784                     hir::ExprCast(lower_expr(lctx, expr), lower_ty(lctx, ty))
785                 }
786                 ExprAddrOf(m, ref ohs) => {
787                     hir::ExprAddrOf(lower_mutability(lctx, m), lower_expr(lctx, ohs))
788                 }
789                 ExprIf(ref cond, ref tr, ref fl) => {
790                     hir::ExprIf(lower_expr(lctx, cond),
791                            lower_block(lctx, tr),
792                            fl.as_ref().map(|x| lower_expr(lctx, x)))
793                 }
794                 ExprWhile(ref cond, ref body, opt_ident) => {
795                     hir::ExprWhile(lower_expr(lctx, cond),
796                               lower_block(lctx, body),
797                               opt_ident)
798                 }
799                 ExprLoop(ref body, opt_ident) => {
800                     hir::ExprLoop(lower_block(lctx, body),
801                             opt_ident)
802                 }
803                 ExprMatch(ref expr, ref arms, ref source) => {
804                     hir::ExprMatch(lower_expr(lctx, expr),
805                             arms.iter().map(|x| lower_arm(lctx, x)).collect(),
806                             lower_match_source(lctx, source))
807                 }
808                 ExprClosure(capture_clause, ref decl, ref body) => {
809                     hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
810                                 lower_fn_decl(lctx, decl),
811                                 lower_block(lctx, body))
812                 }
813                 ExprBlock(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
814                 ExprAssign(ref el, ref er) => {
815                     hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
816                 }
817                 ExprAssignOp(op, ref el, ref er) => {
818                     hir::ExprAssignOp(lower_binop(lctx, op),
819                                 lower_expr(lctx, el),
820                                 lower_expr(lctx, er))
821                 }
822                 ExprField(ref el, ident) => {
823                     hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name))
824                 }
825                 ExprTupField(ref el, ident) => {
826                     hir::ExprTupField(lower_expr(lctx, el), ident)
827                 }
828                 ExprIndex(ref el, ref er) => {
829                     hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
830                 }
831                 ExprRange(ref e1, ref e2) => {
832                     hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)),
833                               e2.as_ref().map(|x| lower_expr(lctx, x)))
834                 }
835                 ExprPath(ref qself, ref path) => {
836                     let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
837                         hir::QSelf {
838                             ty: lower_ty(lctx, ty),
839                             position: position
840                         }
841                     });
842                     hir::ExprPath(qself, lower_path(lctx, path))
843                 }
844                 ExprBreak(opt_ident) => hir::ExprBreak(opt_ident),
845                 ExprAgain(opt_ident) => hir::ExprAgain(opt_ident),
846                 ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
847                 ExprInlineAsm(InlineAsm {
848                     ref inputs,
849                     ref outputs,
850                     ref asm,
851                     asm_str_style,
852                     ref clobbers,
853                     volatile,
854                     alignstack,
855                     dialect,
856                     expn_id,
857                 }) => hir::ExprInlineAsm(hir::InlineAsm {
858                     inputs: inputs.iter().map(|&(ref c, ref input)| {
859                         (c.clone(), lower_expr(lctx, input))
860                     }).collect(),
861                     outputs: outputs.iter().map(|&(ref c, ref out, ref is_rw)| {
862                         (c.clone(), lower_expr(lctx, out), *is_rw)
863                     }).collect(),
864                     asm: asm.clone(),
865                     asm_str_style: asm_str_style,
866                     clobbers: clobbers.clone(),
867                     volatile: volatile,
868                     alignstack: alignstack,
869                     dialect: dialect,
870                     expn_id: expn_id,
871                 }),
872                 ExprStruct(ref path, ref fields, ref maybe_expr) => {
873                     hir::ExprStruct(lower_path(lctx, path),
874                             fields.iter().map(|x| lower_field(lctx, x)).collect(),
875                             maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
876                 },
877                 ExprParen(ref ex) => {
878                     return lower_expr(lctx, ex);
879                 }
880                 ExprInPlace(..) => {
881                     panic!("todo");
882                 }
883                 ExprIfLet(..) => {
884                     panic!("todo");
885                 }
886                 ExprWhileLet(..) => {
887                     panic!("todo");
888                 }
889
890                 // Desugar ExprForLoop
891                 // From: `[opt_ident]: for <pat> in <head> <body>`
892                 ExprForLoop(ref pat, ref head, ref body, ref opt_ident) => {
893                     // to:
894                     //
895                     //   {
896                     //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
897                     //       mut iter => {
898                     //         [opt_ident]: loop {
899                     //           match ::std::iter::Iterator::next(&mut iter) {
900                     //             ::std::option::Option::Some(<pat>) => <body>,
901                     //             ::std::option::Option::None => break
902                     //           }
903                     //         }
904                     //       }
905                     //     };
906                     //     result
907                     //   }
908
909                     // expand <head>
910                     let head = lower_expr(lctx, head);
911
912                     let iter = token::gensym_ident("iter");
913
914                     // `::std::option::Option::Some(<pat>) => <body>`
915                     let pat_arm = {
916                         let body_block = lower_block(lctx, body);
917                         let body_span = body_block.span;
918                         let body_expr = P(hir::Expr {
919                             id: lctx.next_id(),
920                             node: hir::ExprBlock(body_block),
921                             span: body_span,
922                         });
923                         let pat = lower_pat(lctx, pat);
924                         let some_pat = pat_some(lctx, e.span, pat);
925
926                         arm(vec![some_pat], body_expr)
927                     };
928
929                     // `::std::option::Option::None => break`
930                     let break_arm = {
931                         let break_expr = expr_break(lctx, e.span);
932
933                         arm(vec![pat_none(lctx, e.span)], break_expr)
934                     };
935
936                     // `match ::std::iter::Iterator::next(&mut iter) { ... }`
937                     let match_expr = {
938                         let next_path = {
939                             let strs = std_path(lctx, &["iter", "Iterator", "next"]);
940
941                             path_global(e.span, strs)
942                         };
943                         let ref_mut_iter = expr_mut_addr_of(lctx, e.span, expr_ident(lctx, e.span, iter));
944                         let next_expr =
945                             expr_call(lctx, e.span, expr_path(lctx, next_path), vec![ref_mut_iter]);
946                         let arms = vec![pat_arm, break_arm];
947
948                         expr(lctx,
949                              e.span,
950                              hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar))
951                     };
952
953                     // `[opt_ident]: loop { ... }`
954                     let loop_block = block_expr(lctx, match_expr);
955                     let loop_expr = expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident.clone()));
956
957                     // `mut iter => { ... }`
958                     let iter_arm = {
959                         let iter_pat =
960                             pat_ident_binding_mode(lctx, e.span, iter, hir::BindByValue(hir::MutMutable));
961                         arm(vec![iter_pat], loop_expr)
962                     };
963
964                     // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
965                     let into_iter_expr = {
966                         let into_iter_path = {
967                             let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
968
969                             path_global(e.span, strs)
970                         };
971
972                         expr_call(lctx, e.span, expr_path(lctx, into_iter_path), vec![head])
973                     };
974
975                     let match_expr = expr_match(lctx, e.span, into_iter_expr, vec![iter_arm]);
976
977                     // `{ let result = ...; result }`
978                     let result_ident = token::gensym_ident("result");
979                     let result = expr_block(lctx,
980                                             block_all(lctx,
981                                                       e.span,
982                                                       vec![stmt_let(lctx,
983                                                                     e.span,
984                                                                     false,
985                                                                     result_ident,
986                                                                     match_expr)],
987                                                       Some(expr_ident(lctx, e.span, result_ident))));
988                     return result;
989                 }
990
991                 ExprMac(_) => panic!("Shouldn't exist here"),
992             },
993             span: e.span,
994         })
995 }
996
997 pub fn lower_stmt(_lctx: &LoweringContext, s: &Stmt) -> P<hir::Stmt> {
998     match s.node {
999         StmtDecl(ref d, id) => {
1000             P(Spanned {
1001                 node: hir::StmtDecl(lower_decl(_lctx, d), id),
1002                 span: s.span
1003             })
1004         }
1005         StmtExpr(ref e, id) => {
1006             P(Spanned {
1007                 node: hir::StmtExpr(lower_expr(_lctx, e), id),
1008                 span: s.span
1009             })
1010         }
1011         StmtSemi(ref e, id) => {
1012             P(Spanned {
1013                 node: hir::StmtSemi(lower_expr(_lctx, e), id),
1014                 span: s.span
1015             })
1016         }
1017         StmtMac(..) => panic!("Shouldn't exist here"),
1018     }
1019 }
1020
1021 pub fn lower_match_source(_lctx: &LoweringContext, m: &MatchSource) -> hir::MatchSource {
1022     match *m {
1023         MatchSource::Normal => hir::MatchSource::Normal,
1024         MatchSource::IfLetDesugar { contains_else_clause } => {
1025             hir::MatchSource::IfLetDesugar { contains_else_clause: contains_else_clause }
1026         }
1027         MatchSource::WhileLetDesugar => hir::MatchSource::WhileLetDesugar,
1028         MatchSource::ForLoopDesugar => hir::MatchSource::ForLoopDesugar,
1029     }
1030 }
1031
1032 pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureClause) -> hir::CaptureClause {
1033     match c {
1034         CaptureByValue => hir::CaptureByValue,
1035         CaptureByRef => hir::CaptureByRef,
1036     }
1037 }
1038
1039 pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1040     match v {
1041         Public => hir::Public,
1042         Inherited => hir::Inherited,
1043     }
1044 }
1045
1046 pub fn lower_block_check_mode(_lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1047     match *b {
1048         DefaultBlock => hir::DefaultBlock,
1049         UnsafeBlock(u) => hir::UnsafeBlock(lower_unsafe_source(_lctx, u)),
1050         PushUnsafeBlock(u) => hir::PushUnsafeBlock(lower_unsafe_source(_lctx, u)),
1051         PopUnsafeBlock(u) => hir::PopUnsafeBlock(lower_unsafe_source(_lctx, u)),
1052     }
1053 }
1054
1055 pub fn lower_pat_wild_kind(_lctx: &LoweringContext, p: PatWildKind) -> hir::PatWildKind {
1056     match p {
1057         PatWildSingle => hir::PatWildSingle,
1058         PatWildMulti => hir::PatWildMulti,
1059     }
1060 }
1061
1062 pub fn lower_binding_mode(_lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1063     match *b {
1064         BindByRef(m) => hir::BindByRef(lower_mutability(_lctx, m)),
1065         BindByValue(m) => hir::BindByValue(lower_mutability(_lctx, m)),
1066     }
1067 }
1068
1069 pub fn lower_struct_field_kind(_lctx: &LoweringContext,
1070                                s: &StructFieldKind)
1071                                -> hir::StructFieldKind {
1072     match *s {
1073         NamedField(ident, vis) => hir::NamedField(ident.name, lower_visibility(_lctx, vis)),
1074         UnnamedField(vis) => hir::UnnamedField(lower_visibility(_lctx, vis)),
1075     }
1076 }
1077
1078 pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1079     match u {
1080         CompilerGenerated => hir::CompilerGenerated,
1081         UserProvided => hir::UserProvided,
1082     }
1083 }
1084
1085 pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1086     match i {
1087         ImplPolarity::Positive => hir::ImplPolarity::Positive,
1088         ImplPolarity::Negative => hir::ImplPolarity::Negative,
1089     }
1090 }
1091
1092 pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
1093                                   f: TraitBoundModifier)
1094                                   -> hir::TraitBoundModifier {
1095     match f {
1096         TraitBoundModifier::None => hir::TraitBoundModifier::None,
1097         TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
1098     }
1099 }
1100
1101 // Helper methods for building HIR.
1102
1103 fn arm(pats: Vec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1104     hir::Arm {
1105         attrs: vec!(),
1106         pats: pats,
1107         guard: None,
1108         body: expr
1109     }
1110 }
1111
1112 fn expr_break(lctx: &LoweringContext, span: Span) -> P<hir::Expr> {
1113     expr(lctx, span, hir::ExprBreak(None))
1114 }
1115
1116 fn expr_call(lctx: &LoweringContext, span: Span, e: P<hir::Expr>, args: Vec<P<hir::Expr>>) -> P<hir::Expr> {
1117     expr(lctx, span, hir::ExprCall(e, args))
1118 }
1119
1120 fn expr_ident(lctx: &LoweringContext, span: Span, id: Ident) -> P<hir::Expr> {
1121     expr_path(lctx, path_ident(span, id))
1122 }
1123
1124 fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>) -> P<hir::Expr> {
1125     expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e))
1126 }
1127
1128 fn expr_path(lctx: &LoweringContext, path: hir::Path) -> P<hir::Expr> {
1129     expr(lctx, path.span, hir::ExprPath(None, path))
1130 }
1131
1132 fn expr_match(lctx: &LoweringContext, span: Span, arg: P<hir::Expr>, arms: Vec<hir::Arm>) -> P<hir::Expr> {
1133     expr(lctx, span, hir::ExprMatch(arg, arms, hir::MatchSource::Normal))
1134 }
1135
1136 fn expr_block(lctx: &LoweringContext, b: P<hir::Block>) -> P<hir::Expr> {
1137     expr(lctx, b.span, hir::ExprBlock(b))
1138 }
1139
1140 fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_) -> P<hir::Expr> {
1141     P(hir::Expr {
1142         id: lctx.next_id(),
1143         node: node,
1144         span: span,
1145     })
1146 }
1147
1148 fn stmt_let(lctx: &LoweringContext, sp: Span, mutbl: bool, ident: Ident, ex: P<hir::Expr>) -> P<hir::Stmt> {
1149     let pat = if mutbl {
1150         pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
1151     } else {
1152         pat_ident(lctx, sp, ident)
1153     };
1154     let local = P(hir::Local {
1155         pat: pat,
1156         ty: None,
1157         init: Some(ex),
1158         id: lctx.next_id(),
1159         span: sp,
1160     });
1161     let decl = respan(sp, hir::DeclLocal(local));
1162     P(respan(sp, hir::StmtDecl(P(decl), lctx.next_id())))
1163 }
1164
1165 fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
1166     block_all(lctx, expr.span, Vec::new(), Some(expr))
1167 }
1168
1169 fn block_all(lctx: &LoweringContext,
1170              span: Span,
1171              stmts: Vec<P<hir::Stmt>>,
1172              expr: Option<P<hir::Expr>>) -> P<hir::Block> {
1173         P(hir::Block {
1174             stmts: stmts,
1175             expr: expr,
1176             id: lctx.next_id(),
1177             rules: hir::DefaultBlock,
1178             span: span,
1179         })
1180 }
1181
1182 fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1183     let some = std_path(lctx, &["option", "Option", "Some"]);
1184     let path = path_global(span, some);
1185     pat_enum(lctx, span, path, vec!(pat))
1186 }
1187
1188 fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1189     let none = std_path(lctx, &["option", "Option", "None"]);
1190     let path = path_global(span, none);
1191     pat_enum(lctx, span, path, vec![])
1192 }
1193
1194 fn pat_enum(lctx: &LoweringContext, span: Span, path: hir::Path, subpats: Vec<P<hir::Pat>>) -> P<hir::Pat> {
1195     let pt = hir::PatEnum(path, Some(subpats));
1196     pat(lctx, span, pt)
1197 }
1198
1199 fn pat_ident(lctx: &LoweringContext, span: Span, ident: Ident) -> P<hir::Pat> {
1200     pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
1201 }
1202
1203 fn pat_ident_binding_mode(lctx: &LoweringContext,
1204                           span: Span,
1205                           ident: Ident,
1206                           bm: hir::BindingMode) -> P<hir::Pat> {
1207     let pat_ident = hir::PatIdent(bm, Spanned{span: span, node: ident}, None);
1208     pat(lctx, span, pat_ident)
1209 }
1210
1211 fn pat(lctx: &LoweringContext, span: Span, pat: hir::Pat_) -> P<hir::Pat> {
1212     P(hir::Pat { id: lctx.next_id(), node: pat, span: span })
1213 }
1214
1215 fn path_ident(span: Span, id: Ident) -> hir::Path {
1216     path(span, vec!(id))
1217 }
1218
1219 fn path(span: Span, strs: Vec<Ident> ) -> hir::Path {
1220     path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new())
1221 }
1222
1223 fn path_global(span: Span, strs: Vec<Ident> ) -> hir::Path {
1224     path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new())
1225 }
1226
1227 fn path_all(sp: Span,
1228             global: bool,
1229             mut idents: Vec<Ident> ,
1230             lifetimes: Vec<hir::Lifetime>,
1231             types: Vec<P<hir::Ty>>,
1232             bindings: Vec<P<hir::TypeBinding>> )
1233             -> hir::Path {
1234     let last_identifier = idents.pop().unwrap();
1235     let mut segments: Vec<hir::PathSegment> = idents.into_iter()
1236                                                     .map(|ident| {
1237         hir::PathSegment {
1238             identifier: ident,
1239             parameters: hir::PathParameters::none(),
1240         }
1241     }).collect();
1242     segments.push(hir::PathSegment {
1243         identifier: last_identifier,
1244         parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1245             lifetimes: lifetimes,
1246             types: OwnedSlice::from_vec(types),
1247             bindings: OwnedSlice::from_vec(bindings),
1248         })
1249     });
1250     hir::Path {
1251         span: sp,
1252         global: global,
1253         segments: segments,
1254     }
1255 }
1256
1257 fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<Ident> {
1258     let mut v = Vec::new();
1259     if let Some(s) = lctx.crate_root {
1260         v.push(str_to_ident(s));
1261     }
1262     v.extend(components.iter().map(|s| str_to_ident(s)));
1263     return v
1264 }