]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/lowering.rs
if let and while let
[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                 // More complicated than you might expect because the else branch
790                 // might be `if let`.
791                 ExprIf(ref cond, ref blk, ref else_opt) => {
792                     let else_opt = else_opt.as_ref().map(|els| match els.node {
793                         ExprIfLet(..) => {
794                             // wrap the if-let expr in a block
795                             let span = els.span;
796                             let blk = P(hir::Block {
797                                 stmts: vec![],
798                                 expr: Some(lower_expr(lctx, els)),
799                                 id: lctx.next_id(),
800                                 rules: hir::DefaultBlock,
801                                 span: span
802                             });
803                             expr_block(lctx, blk)
804                         }
805                         _ => lower_expr(lctx, els)
806                     });
807
808                     hir::ExprIf(lower_expr(lctx, cond),
809                                 lower_block(lctx, blk),
810                                 else_opt)
811                 }
812                 ExprWhile(ref cond, ref body, opt_ident) => {
813                     hir::ExprWhile(lower_expr(lctx, cond),
814                               lower_block(lctx, body),
815                               opt_ident)
816                 }
817                 ExprLoop(ref body, opt_ident) => {
818                     hir::ExprLoop(lower_block(lctx, body),
819                             opt_ident)
820                 }
821                 ExprMatch(ref expr, ref arms, ref source) => {
822                     hir::ExprMatch(lower_expr(lctx, expr),
823                             arms.iter().map(|x| lower_arm(lctx, x)).collect(),
824                             lower_match_source(lctx, source))
825                 }
826                 ExprClosure(capture_clause, ref decl, ref body) => {
827                     hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
828                                 lower_fn_decl(lctx, decl),
829                                 lower_block(lctx, body))
830                 }
831                 ExprBlock(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
832                 ExprAssign(ref el, ref er) => {
833                     hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
834                 }
835                 ExprAssignOp(op, ref el, ref er) => {
836                     hir::ExprAssignOp(lower_binop(lctx, op),
837                                 lower_expr(lctx, el),
838                                 lower_expr(lctx, er))
839                 }
840                 ExprField(ref el, ident) => {
841                     hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name))
842                 }
843                 ExprTupField(ref el, ident) => {
844                     hir::ExprTupField(lower_expr(lctx, el), ident)
845                 }
846                 ExprIndex(ref el, ref er) => {
847                     hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
848                 }
849                 ExprRange(ref e1, ref e2) => {
850                     hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)),
851                               e2.as_ref().map(|x| lower_expr(lctx, x)))
852                 }
853                 ExprPath(ref qself, ref path) => {
854                     let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
855                         hir::QSelf {
856                             ty: lower_ty(lctx, ty),
857                             position: position
858                         }
859                     });
860                     hir::ExprPath(qself, lower_path(lctx, path))
861                 }
862                 ExprBreak(opt_ident) => hir::ExprBreak(opt_ident),
863                 ExprAgain(opt_ident) => hir::ExprAgain(opt_ident),
864                 ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
865                 ExprInlineAsm(InlineAsm {
866                     ref inputs,
867                     ref outputs,
868                     ref asm,
869                     asm_str_style,
870                     ref clobbers,
871                     volatile,
872                     alignstack,
873                     dialect,
874                     expn_id,
875                 }) => hir::ExprInlineAsm(hir::InlineAsm {
876                     inputs: inputs.iter().map(|&(ref c, ref input)| {
877                         (c.clone(), lower_expr(lctx, input))
878                     }).collect(),
879                     outputs: outputs.iter().map(|&(ref c, ref out, ref is_rw)| {
880                         (c.clone(), lower_expr(lctx, out), *is_rw)
881                     }).collect(),
882                     asm: asm.clone(),
883                     asm_str_style: asm_str_style,
884                     clobbers: clobbers.clone(),
885                     volatile: volatile,
886                     alignstack: alignstack,
887                     dialect: dialect,
888                     expn_id: expn_id,
889                 }),
890                 ExprStruct(ref path, ref fields, ref maybe_expr) => {
891                     hir::ExprStruct(lower_path(lctx, path),
892                             fields.iter().map(|x| lower_field(lctx, x)).collect(),
893                             maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
894                 },
895                 ExprParen(ref ex) => {
896                     return lower_expr(lctx, ex);
897                 }
898                 ExprInPlace(..) => {
899                     panic!("todo");
900                 }
901
902                 // Desugar ExprIfLet
903                 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
904                 ExprIfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
905                     // to:
906                     //
907                     //   match <sub_expr> {
908                     //     <pat> => <body>,
909                     //     [_ if <else_opt_if_cond> => <else_opt_if_body>,]
910                     //     _ => [<else_opt> | ()]
911                     //   }
912
913                     // `<pat> => <body>`
914                     let pat_arm = {
915                         let body_expr = expr_block(lctx, lower_block(lctx, body));
916                         arm(vec![lower_pat(lctx, pat)], body_expr)
917                     };
918
919                     // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
920                     let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e));
921                     let else_if_arms = {
922                         let mut arms = vec![];
923                         loop {
924                             let else_opt_continue = else_opt
925                                 .and_then(|els| els.and_then(|els| match els.node {
926                                 // else if
927                                 hir::ExprIf(cond, then, else_opt) => {
928                                     let pat_under = pat_wild(lctx, e.span);
929                                     arms.push(hir::Arm {
930                                         attrs: vec![],
931                                         pats: vec![pat_under],
932                                         guard: Some(cond),
933                                         body: expr_block(lctx, then)
934                                     });
935                                     else_opt.map(|else_opt| (else_opt, true))
936                                 }
937                                 _ => Some((P(els), false))
938                             }));
939                             match else_opt_continue {
940                                 Some((e, true)) => {
941                                     else_opt = Some(e);
942                                 }
943                                 Some((e, false)) => {
944                                     else_opt = Some(e);
945                                     break;
946                                 }
947                                 None => {
948                                     else_opt = None;
949                                     break;
950                                 }
951                             }
952                         }
953                         arms
954                     };
955
956                     let contains_else_clause = else_opt.is_some();
957
958                     // `_ => [<else_opt> | ()]`
959                     let else_arm = {
960                         let pat_under = pat_wild(lctx, e.span);
961                         let else_expr = else_opt.unwrap_or_else(|| expr_tuple(lctx, e.span, vec![]));
962                         arm(vec![pat_under], else_expr)
963                     };
964
965                     let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
966                     arms.push(pat_arm);
967                     arms.extend(else_if_arms);
968                     arms.push(else_arm);
969
970                     let match_expr = expr(lctx,
971                                           e.span,
972                                           hir::ExprMatch(lower_expr(lctx, sub_expr), arms,
973                                                  hir::MatchSource::IfLetDesugar {
974                                                      contains_else_clause: contains_else_clause,
975                                                  }));
976                     return match_expr;
977                 }
978
979                 // Desugar ExprWhileLet
980                 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
981                 ExprWhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
982                     // to:
983                     //
984                     //   [opt_ident]: loop {
985                     //     match <sub_expr> {
986                     //       <pat> => <body>,
987                     //       _ => break
988                     //     }
989                     //   }
990
991                     // `<pat> => <body>`
992                     let pat_arm = {
993                         let body_expr = expr_block(lctx, lower_block(lctx, body));
994                         arm(vec![lower_pat(lctx, pat)], body_expr)
995                     };
996
997                     // `_ => break`
998                     let break_arm = {
999                         let pat_under = pat_wild(lctx, e.span);
1000                         let break_expr = expr_break(lctx, e.span);
1001                         arm(vec![pat_under], break_expr)
1002                     };
1003
1004                     // // `match <sub_expr> { ... }`
1005                     let arms = vec![pat_arm, break_arm];
1006                     let match_expr = expr(lctx,
1007                                           e.span,
1008                                           hir::ExprMatch(lower_expr(lctx, sub_expr), arms, hir::MatchSource::WhileLetDesugar));
1009
1010                     // `[opt_ident]: loop { ... }`
1011                     let loop_block = block_expr(lctx, match_expr);
1012                     return expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident));
1013                 }
1014
1015                 // Desugar ExprForLoop
1016                 // From: `[opt_ident]: for <pat> in <head> <body>`
1017                 ExprForLoop(ref pat, ref head, ref body, opt_ident) => {
1018                     // to:
1019                     //
1020                     //   {
1021                     //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1022                     //       mut iter => {
1023                     //         [opt_ident]: loop {
1024                     //           match ::std::iter::Iterator::next(&mut iter) {
1025                     //             ::std::option::Option::Some(<pat>) => <body>,
1026                     //             ::std::option::Option::None => break
1027                     //           }
1028                     //         }
1029                     //       }
1030                     //     };
1031                     //     result
1032                     //   }
1033
1034                     // expand <head>
1035                     let head = lower_expr(lctx, head);
1036
1037                     let iter = token::gensym_ident("iter");
1038
1039                     // `::std::option::Option::Some(<pat>) => <body>`
1040                     let pat_arm = {
1041                         let body_block = lower_block(lctx, body);
1042                         let body_span = body_block.span;
1043                         let body_expr = P(hir::Expr {
1044                             id: lctx.next_id(),
1045                             node: hir::ExprBlock(body_block),
1046                             span: body_span,
1047                         });
1048                         let pat = lower_pat(lctx, pat);
1049                         let some_pat = pat_some(lctx, e.span, pat);
1050
1051                         arm(vec![some_pat], body_expr)
1052                     };
1053
1054                     // `::std::option::Option::None => break`
1055                     let break_arm = {
1056                         let break_expr = expr_break(lctx, e.span);
1057
1058                         arm(vec![pat_none(lctx, e.span)], break_expr)
1059                     };
1060
1061                     // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1062                     let match_expr = {
1063                         let next_path = {
1064                             let strs = std_path(lctx, &["iter", "Iterator", "next"]);
1065
1066                             path_global(e.span, strs)
1067                         };
1068                         let ref_mut_iter = expr_mut_addr_of(lctx, e.span, expr_ident(lctx, e.span, iter));
1069                         let next_expr =
1070                             expr_call(lctx, e.span, expr_path(lctx, next_path), vec![ref_mut_iter]);
1071                         let arms = vec![pat_arm, break_arm];
1072
1073                         expr(lctx,
1074                              e.span,
1075                              hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar))
1076                     };
1077
1078                     // `[opt_ident]: loop { ... }`
1079                     let loop_block = block_expr(lctx, match_expr);
1080                     let loop_expr = expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident));
1081
1082                     // `mut iter => { ... }`
1083                     let iter_arm = {
1084                         let iter_pat =
1085                             pat_ident_binding_mode(lctx, e.span, iter, hir::BindByValue(hir::MutMutable));
1086                         arm(vec![iter_pat], loop_expr)
1087                     };
1088
1089                     // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1090                     let into_iter_expr = {
1091                         let into_iter_path = {
1092                             let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
1093
1094                             path_global(e.span, strs)
1095                         };
1096
1097                         expr_call(lctx, e.span, expr_path(lctx, into_iter_path), vec![head])
1098                     };
1099
1100                     let match_expr = expr_match(lctx, e.span, into_iter_expr, vec![iter_arm]);
1101
1102                     // `{ let result = ...; result }`
1103                     let result_ident = token::gensym_ident("result");
1104                     return expr_block(lctx,
1105                                       block_all(lctx,
1106                                                 e.span,
1107                                                 vec![stmt_let(lctx, e.span,
1108                                                               false,
1109                                                               result_ident,
1110                                                               match_expr)],
1111                                                 Some(expr_ident(lctx, e.span, result_ident))))
1112                 }
1113
1114                 ExprMac(_) => panic!("Shouldn't exist here"),
1115             },
1116             span: e.span,
1117         })
1118 }
1119
1120 pub fn lower_stmt(_lctx: &LoweringContext, s: &Stmt) -> P<hir::Stmt> {
1121     match s.node {
1122         StmtDecl(ref d, id) => {
1123             P(Spanned {
1124                 node: hir::StmtDecl(lower_decl(_lctx, d), id),
1125                 span: s.span
1126             })
1127         }
1128         StmtExpr(ref e, id) => {
1129             P(Spanned {
1130                 node: hir::StmtExpr(lower_expr(_lctx, e), id),
1131                 span: s.span
1132             })
1133         }
1134         StmtSemi(ref e, id) => {
1135             P(Spanned {
1136                 node: hir::StmtSemi(lower_expr(_lctx, e), id),
1137                 span: s.span
1138             })
1139         }
1140         StmtMac(..) => panic!("Shouldn't exist here"),
1141     }
1142 }
1143
1144 pub fn lower_match_source(_lctx: &LoweringContext, m: &MatchSource) -> hir::MatchSource {
1145     match *m {
1146         MatchSource::Normal => hir::MatchSource::Normal,
1147         MatchSource::IfLetDesugar { contains_else_clause } => {
1148             hir::MatchSource::IfLetDesugar { contains_else_clause: contains_else_clause }
1149         }
1150         MatchSource::WhileLetDesugar => hir::MatchSource::WhileLetDesugar,
1151         MatchSource::ForLoopDesugar => hir::MatchSource::ForLoopDesugar,
1152     }
1153 }
1154
1155 pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureClause) -> hir::CaptureClause {
1156     match c {
1157         CaptureByValue => hir::CaptureByValue,
1158         CaptureByRef => hir::CaptureByRef,
1159     }
1160 }
1161
1162 pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1163     match v {
1164         Public => hir::Public,
1165         Inherited => hir::Inherited,
1166     }
1167 }
1168
1169 pub fn lower_block_check_mode(_lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1170     match *b {
1171         DefaultBlock => hir::DefaultBlock,
1172         UnsafeBlock(u) => hir::UnsafeBlock(lower_unsafe_source(_lctx, u)),
1173         PushUnsafeBlock(u) => hir::PushUnsafeBlock(lower_unsafe_source(_lctx, u)),
1174         PopUnsafeBlock(u) => hir::PopUnsafeBlock(lower_unsafe_source(_lctx, u)),
1175     }
1176 }
1177
1178 pub fn lower_pat_wild_kind(_lctx: &LoweringContext, p: PatWildKind) -> hir::PatWildKind {
1179     match p {
1180         PatWildSingle => hir::PatWildSingle,
1181         PatWildMulti => hir::PatWildMulti,
1182     }
1183 }
1184
1185 pub fn lower_binding_mode(_lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1186     match *b {
1187         BindByRef(m) => hir::BindByRef(lower_mutability(_lctx, m)),
1188         BindByValue(m) => hir::BindByValue(lower_mutability(_lctx, m)),
1189     }
1190 }
1191
1192 pub fn lower_struct_field_kind(_lctx: &LoweringContext,
1193                                s: &StructFieldKind)
1194                                -> hir::StructFieldKind {
1195     match *s {
1196         NamedField(ident, vis) => hir::NamedField(ident.name, lower_visibility(_lctx, vis)),
1197         UnnamedField(vis) => hir::UnnamedField(lower_visibility(_lctx, vis)),
1198     }
1199 }
1200
1201 pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1202     match u {
1203         CompilerGenerated => hir::CompilerGenerated,
1204         UserProvided => hir::UserProvided,
1205     }
1206 }
1207
1208 pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1209     match i {
1210         ImplPolarity::Positive => hir::ImplPolarity::Positive,
1211         ImplPolarity::Negative => hir::ImplPolarity::Negative,
1212     }
1213 }
1214
1215 pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
1216                                   f: TraitBoundModifier)
1217                                   -> hir::TraitBoundModifier {
1218     match f {
1219         TraitBoundModifier::None => hir::TraitBoundModifier::None,
1220         TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
1221     }
1222 }
1223
1224 // Helper methods for building HIR.
1225
1226 fn arm(pats: Vec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1227     hir::Arm {
1228         attrs: vec!(),
1229         pats: pats,
1230         guard: None,
1231         body: expr
1232     }
1233 }
1234
1235 fn expr_break(lctx: &LoweringContext, span: Span) -> P<hir::Expr> {
1236     expr(lctx, span, hir::ExprBreak(None))
1237 }
1238
1239 fn expr_call(lctx: &LoweringContext, span: Span, e: P<hir::Expr>, args: Vec<P<hir::Expr>>) -> P<hir::Expr> {
1240     expr(lctx, span, hir::ExprCall(e, args))
1241 }
1242
1243 fn expr_ident(lctx: &LoweringContext, span: Span, id: Ident) -> P<hir::Expr> {
1244     expr_path(lctx, path_ident(span, id))
1245 }
1246
1247 fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>) -> P<hir::Expr> {
1248     expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e))
1249 }
1250
1251 fn expr_path(lctx: &LoweringContext, path: hir::Path) -> P<hir::Expr> {
1252     expr(lctx, path.span, hir::ExprPath(None, path))
1253 }
1254
1255 fn expr_match(lctx: &LoweringContext, span: Span, arg: P<hir::Expr>, arms: Vec<hir::Arm>) -> P<hir::Expr> {
1256     expr(lctx, span, hir::ExprMatch(arg, arms, hir::MatchSource::Normal))
1257 }
1258
1259 fn expr_block(lctx: &LoweringContext, b: P<hir::Block>) -> P<hir::Expr> {
1260     expr(lctx, b.span, hir::ExprBlock(b))
1261 }
1262
1263 fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: Vec<P<hir::Expr>>) -> P<hir::Expr> {
1264     expr(lctx, sp, hir::ExprTup(exprs))
1265 }
1266
1267 fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_) -> P<hir::Expr> {
1268     P(hir::Expr {
1269         id: lctx.next_id(),
1270         node: node,
1271         span: span,
1272     })
1273 }
1274
1275 fn stmt_let(lctx: &LoweringContext, sp: Span, mutbl: bool, ident: Ident, ex: P<hir::Expr>) -> P<hir::Stmt> {
1276     let pat = if mutbl {
1277         pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
1278     } else {
1279         pat_ident(lctx, sp, ident)
1280     };
1281     let local = P(hir::Local {
1282         pat: pat,
1283         ty: None,
1284         init: Some(ex),
1285         id: lctx.next_id(),
1286         span: sp,
1287     });
1288     let decl = respan(sp, hir::DeclLocal(local));
1289     P(respan(sp, hir::StmtDecl(P(decl), lctx.next_id())))
1290 }
1291
1292 fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
1293     block_all(lctx, expr.span, Vec::new(), Some(expr))
1294 }
1295
1296 fn block_all(lctx: &LoweringContext,
1297              span: Span,
1298              stmts: Vec<P<hir::Stmt>>,
1299              expr: Option<P<hir::Expr>>) -> P<hir::Block> {
1300         P(hir::Block {
1301             stmts: stmts,
1302             expr: expr,
1303             id: lctx.next_id(),
1304             rules: hir::DefaultBlock,
1305             span: span,
1306         })
1307 }
1308
1309 fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1310     let some = std_path(lctx, &["option", "Option", "Some"]);
1311     let path = path_global(span, some);
1312     pat_enum(lctx, span, path, vec!(pat))
1313 }
1314
1315 fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1316     let none = std_path(lctx, &["option", "Option", "None"]);
1317     let path = path_global(span, none);
1318     pat_enum(lctx, span, path, vec![])
1319 }
1320
1321 fn pat_enum(lctx: &LoweringContext, span: Span, path: hir::Path, subpats: Vec<P<hir::Pat>>) -> P<hir::Pat> {
1322     let pt = hir::PatEnum(path, Some(subpats));
1323     pat(lctx, span, pt)
1324 }
1325
1326 fn pat_ident(lctx: &LoweringContext, span: Span, ident: Ident) -> P<hir::Pat> {
1327     pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
1328 }
1329
1330 fn pat_ident_binding_mode(lctx: &LoweringContext,
1331                           span: Span,
1332                           ident: Ident,
1333                           bm: hir::BindingMode) -> P<hir::Pat> {
1334     let pat_ident = hir::PatIdent(bm, Spanned{span: span, node: ident}, None);
1335     pat(lctx, span, pat_ident)
1336 }
1337
1338 fn pat_wild(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1339     pat(lctx, span, hir::PatWild(hir::PatWildSingle))
1340 }
1341
1342 fn pat(lctx: &LoweringContext, span: Span, pat: hir::Pat_) -> P<hir::Pat> {
1343     P(hir::Pat { id: lctx.next_id(), node: pat, span: span })
1344 }
1345
1346 fn path_ident(span: Span, id: Ident) -> hir::Path {
1347     path(span, vec!(id))
1348 }
1349
1350 fn path(span: Span, strs: Vec<Ident> ) -> hir::Path {
1351     path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new())
1352 }
1353
1354 fn path_global(span: Span, strs: Vec<Ident> ) -> hir::Path {
1355     path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new())
1356 }
1357
1358 fn path_all(sp: Span,
1359             global: bool,
1360             mut idents: Vec<Ident> ,
1361             lifetimes: Vec<hir::Lifetime>,
1362             types: Vec<P<hir::Ty>>,
1363             bindings: Vec<P<hir::TypeBinding>> )
1364             -> hir::Path {
1365     let last_identifier = idents.pop().unwrap();
1366     let mut segments: Vec<hir::PathSegment> = idents.into_iter()
1367                                                     .map(|ident| {
1368         hir::PathSegment {
1369             identifier: ident,
1370             parameters: hir::PathParameters::none(),
1371         }
1372     }).collect();
1373     segments.push(hir::PathSegment {
1374         identifier: last_identifier,
1375         parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1376             lifetimes: lifetimes,
1377             types: OwnedSlice::from_vec(types),
1378             bindings: OwnedSlice::from_vec(bindings),
1379         })
1380     });
1381     hir::Path {
1382         span: sp,
1383         global: global,
1384         segments: segments,
1385     }
1386 }
1387
1388 fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<Ident> {
1389     let mut v = Vec::new();
1390     if let Some(s) = lctx.crate_root {
1391         v.push(str_to_ident(s));
1392     }
1393     v.extend(components.iter().map(|s| str_to_ident(s)));
1394     return v
1395 }