]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/lowering.rs
Auto merge of #28649 - nhowell:improve-rustbook, r=steveklabnik
[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};
18 use syntax::owned_slice::OwnedSlice;
19
20
21 pub fn lower_view_path(view_path: &ViewPath) -> P<hir::ViewPath> {
22     P(Spanned {
23         node: match view_path.node {
24             ViewPathSimple(ident, ref path) => {
25                 hir::ViewPathSimple(ident.name, lower_path(path))
26             }
27             ViewPathGlob(ref path) => {
28                 hir::ViewPathGlob(lower_path(path))
29             }
30             ViewPathList(ref path, ref path_list_idents) => {
31                 hir::ViewPathList(lower_path(path),
32                              path_list_idents.iter().map(|path_list_ident| {
33                                 Spanned {
34                                     node: match path_list_ident.node {
35                                         PathListIdent { id, name, rename } =>
36                                             hir::PathListIdent {
37                                                 id: id,
38                                                 name: name.name,
39                                                 rename: rename.map(|x| x.name),
40                                             },
41                                         PathListMod { id, rename } =>
42                                             hir::PathListMod {
43                                                 id: id,
44                                                 rename: rename.map(|x| x.name)
45                                             }
46                                     },
47                                     span: path_list_ident.span
48                                 }
49                              }).collect())
50             }
51         },
52         span: view_path.span,
53     })
54 }
55
56 pub fn lower_arm(arm: &Arm) -> hir::Arm {
57     hir::Arm {
58         attrs: arm.attrs.clone(),
59         pats: arm.pats.iter().map(|x| lower_pat(x)).collect(),
60         guard: arm.guard.as_ref().map(|ref x| lower_expr(x)),
61         body: lower_expr(&arm.body),
62     }
63 }
64
65 pub fn lower_decl(d: &Decl) -> P<hir::Decl> {
66     match d.node {
67         DeclLocal(ref l) => P(Spanned {
68             node: hir::DeclLocal(lower_local(l)),
69             span: d.span
70         }),
71         DeclItem(ref it) => P(Spanned {
72             node: hir::DeclItem(lower_item(it)),
73             span: d.span
74         }),
75     }
76 }
77
78 pub fn lower_ty_binding(b: &TypeBinding) -> P<hir::TypeBinding> {
79     P(hir::TypeBinding { id: b.id, name: b.ident.name, ty: lower_ty(&b.ty), span: b.span })
80 }
81
82 pub fn lower_ty(t: &Ty) -> P<hir::Ty> {
83     P(hir::Ty {
84         id: t.id,
85         node: match t.node {
86             TyInfer => hir::TyInfer,
87             TyVec(ref ty) => hir::TyVec(lower_ty(ty)),
88             TyPtr(ref mt) => hir::TyPtr(lower_mt(mt)),
89             TyRptr(ref region, ref mt) => {
90                 hir::TyRptr(lower_opt_lifetime(region), lower_mt(mt))
91             }
92             TyBareFn(ref f) => {
93                 hir::TyBareFn(P(hir::BareFnTy {
94                     lifetimes: lower_lifetime_defs(&f.lifetimes),
95                     unsafety: lower_unsafety(f.unsafety),
96                     abi: f.abi,
97                     decl: lower_fn_decl(&f.decl)
98                 }))
99             }
100             TyTup(ref tys) => hir::TyTup(tys.iter().map(|ty| lower_ty(ty)).collect()),
101             TyParen(ref ty) => hir::TyParen(lower_ty(ty)),
102             TyPath(ref qself, ref path) => {
103                 let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
104                     hir::QSelf {
105                         ty: lower_ty(ty),
106                         position: position
107                     }
108                 });
109                 hir::TyPath(qself, lower_path(path))
110             }
111             TyObjectSum(ref ty, ref bounds) => {
112                 hir::TyObjectSum(lower_ty(ty),
113                             lower_bounds(bounds))
114             }
115             TyFixedLengthVec(ref ty, ref e) => {
116                 hir::TyFixedLengthVec(lower_ty(ty), lower_expr(e))
117             }
118             TyTypeof(ref expr) => {
119                 hir::TyTypeof(lower_expr(expr))
120             }
121             TyPolyTraitRef(ref bounds) => {
122                 hir::TyPolyTraitRef(bounds.iter().map(|b| lower_ty_param_bound(b)).collect())
123             }
124             TyMac(_) => panic!("TyMac should have been expanded by now."),
125         },
126         span: t.span,
127     })
128 }
129
130 pub fn lower_foreign_mod(fm: &ForeignMod) -> hir::ForeignMod {
131     hir::ForeignMod {
132         abi: fm.abi,
133         items: fm.items.iter().map(|x| lower_foreign_item(x)).collect(),
134     }
135 }
136
137 pub fn lower_variant(v: &Variant) -> P<hir::Variant> {
138     P(Spanned {
139         node: hir::Variant_ {
140             id: v.node.id,
141             name: v.node.name.name,
142             attrs: v.node.attrs.clone(),
143             kind: match v.node.kind {
144                 TupleVariantKind(ref variant_args) => {
145                     hir::TupleVariantKind(variant_args.iter().map(|ref x|
146                         lower_variant_arg(x)).collect())
147                 }
148                 StructVariantKind(ref struct_def) => {
149                     hir::StructVariantKind(lower_struct_def(struct_def))
150                 }
151             },
152             disr_expr: v.node.disr_expr.as_ref().map(|e| lower_expr(e)),
153         },
154         span: v.span,
155     })
156 }
157
158 pub fn lower_path(p: &Path) -> hir::Path {
159     hir::Path {
160         global: p.global,
161         segments: p.segments.iter().map(|&PathSegment {identifier, ref parameters}|
162             hir::PathSegment {
163                 identifier: identifier,
164                 parameters: lower_path_parameters(parameters),
165             }).collect(),
166         span: p.span,
167     }
168 }
169
170 pub fn lower_path_parameters(path_parameters: &PathParameters) -> hir::PathParameters {
171     match *path_parameters {
172         AngleBracketedParameters(ref data) =>
173             hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(data)),
174         ParenthesizedParameters(ref data) =>
175             hir::ParenthesizedParameters(lower_parenthesized_parameter_data(data)),
176     }
177 }
178
179 pub fn lower_angle_bracketed_parameter_data(data: &AngleBracketedParameterData)
180                                             -> hir::AngleBracketedParameterData {
181     let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
182     hir::AngleBracketedParameterData {
183         lifetimes: lower_lifetimes(lifetimes),
184         types: types.iter().map(|ty| lower_ty(ty)).collect(),
185         bindings: bindings.iter().map(|b| lower_ty_binding(b)).collect(),
186     }
187 }
188
189 pub fn lower_parenthesized_parameter_data(data: &ParenthesizedParameterData)
190                                           -> hir::ParenthesizedParameterData {
191     let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
192     hir::ParenthesizedParameterData {
193         inputs: inputs.iter().map(|ty| lower_ty(ty)).collect(),
194         output: output.as_ref().map(|ty| lower_ty(ty)),
195         span: span,
196     }
197 }
198
199 pub fn lower_local(l: &Local) -> P<hir::Local> {
200     P(hir::Local {
201             id: l.id,
202             ty: l.ty.as_ref().map(|t| lower_ty(t)),
203             pat: lower_pat(&l.pat),
204             init: l.init.as_ref().map(|e| lower_expr(e)),
205             span: l.span,
206         })
207 }
208
209 pub fn lower_explicit_self_underscore(es: &ExplicitSelf_) -> hir::ExplicitSelf_ {
210     match *es {
211         SelfStatic => hir::SelfStatic,
212         SelfValue(v) => hir::SelfValue(v.name),
213         SelfRegion(ref lifetime, m, ident) => {
214             hir::SelfRegion(lower_opt_lifetime(lifetime), lower_mutability(m), ident.name)
215         }
216         SelfExplicit(ref typ, ident) => {
217             hir::SelfExplicit(lower_ty(typ), ident.name)
218         }
219     }
220 }
221
222 pub fn lower_mutability(m: Mutability) -> hir::Mutability {
223     match m {
224         MutMutable => hir::MutMutable,
225         MutImmutable => hir::MutImmutable,
226     }
227 }
228
229 pub fn lower_explicit_self(s: &ExplicitSelf) -> hir::ExplicitSelf {
230     Spanned { node: lower_explicit_self_underscore(&s.node), span: s.span }
231 }
232
233 pub fn lower_arg(arg: &Arg) -> hir::Arg {
234     hir::Arg { id: arg.id, pat: lower_pat(&arg.pat), ty: lower_ty(&arg.ty) }
235 }
236
237 pub fn lower_fn_decl(decl: &FnDecl) -> P<hir::FnDecl> {
238     P(hir::FnDecl {
239         inputs: decl.inputs.iter().map(|x| lower_arg(x)).collect(),
240         output: match decl.output {
241             Return(ref ty) => hir::Return(lower_ty(ty)),
242             DefaultReturn(span) => hir::DefaultReturn(span),
243             NoReturn(span) => hir::NoReturn(span)
244         },
245         variadic: decl.variadic,
246     })
247 }
248
249 pub fn lower_ty_param_bound(tpb: &TyParamBound) -> hir::TyParamBound {
250     match *tpb {
251         TraitTyParamBound(ref ty, modifier) => {
252             hir::TraitTyParamBound(lower_poly_trait_ref(ty), lower_trait_bound_modifier(modifier))
253         }
254         RegionTyParamBound(ref lifetime) => hir::RegionTyParamBound(lower_lifetime(lifetime)),
255     }
256 }
257
258 pub fn lower_ty_param(tp: &TyParam) -> hir::TyParam {
259     hir::TyParam {
260         id: tp.id,
261         name: tp.ident.name,
262         bounds: lower_bounds(&tp.bounds),
263         default: tp.default.as_ref().map(|x| lower_ty(x)),
264         span: tp.span,
265     }
266 }
267
268 pub fn lower_ty_params(tps: &OwnedSlice<TyParam>) -> OwnedSlice<hir::TyParam> {
269     tps.iter().map(|tp| lower_ty_param(tp)).collect()
270 }
271
272 pub fn lower_lifetime(l: &Lifetime) -> hir::Lifetime {
273     hir::Lifetime { id: l.id, name: l.name, span: l.span }
274 }
275
276 pub fn lower_lifetime_def(l: &LifetimeDef) -> hir::LifetimeDef {
277     hir::LifetimeDef { lifetime: lower_lifetime(&l.lifetime), bounds: lower_lifetimes(&l.bounds) }
278 }
279
280 pub fn lower_lifetimes(lts: &Vec<Lifetime>) -> Vec<hir::Lifetime> {
281     lts.iter().map(|l| lower_lifetime(l)).collect()
282 }
283
284 pub fn lower_lifetime_defs(lts: &Vec<LifetimeDef>) -> Vec<hir::LifetimeDef> {
285     lts.iter().map(|l| lower_lifetime_def(l)).collect()
286 }
287
288 pub fn lower_opt_lifetime(o_lt: &Option<Lifetime>) -> Option<hir::Lifetime> {
289     o_lt.as_ref().map(|lt| lower_lifetime(lt))
290 }
291
292 pub fn lower_generics(g: &Generics) -> hir::Generics {
293     hir::Generics {
294         ty_params: lower_ty_params(&g.ty_params),
295         lifetimes: lower_lifetime_defs(&g.lifetimes),
296         where_clause: lower_where_clause(&g.where_clause),
297     }
298 }
299
300 pub fn lower_where_clause(wc: &WhereClause) -> hir::WhereClause {
301     hir::WhereClause {
302         id: wc.id,
303         predicates: wc.predicates.iter().map(|predicate|
304             lower_where_predicate(predicate)).collect(),
305     }
306 }
307
308 pub fn lower_where_predicate(pred: &WherePredicate) -> hir::WherePredicate {
309     match *pred {
310         WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
311                                                             ref bounded_ty,
312                                                             ref bounds,
313                                                             span}) => {
314             hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
315                 bound_lifetimes: lower_lifetime_defs(bound_lifetimes),
316                 bounded_ty: lower_ty(bounded_ty),
317                 bounds: bounds.iter().map(|x| lower_ty_param_bound(x)).collect(),
318                 span: span
319             })
320         }
321         WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
322                                                               ref bounds,
323                                                               span}) => {
324             hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
325                 span: span,
326                 lifetime: lower_lifetime(lifetime),
327                 bounds: bounds.iter().map(|bound| lower_lifetime(bound)).collect()
328             })
329         }
330         WherePredicate::EqPredicate(WhereEqPredicate{ id,
331                                                       ref path,
332                                                       ref ty,
333                                                       span}) => {
334             hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{
335                 id: id,
336                 path: lower_path(path),
337                 ty:lower_ty(ty),
338                 span: span
339             })
340         }
341     }
342 }
343
344 pub fn lower_struct_def(sd: &StructDef) -> P<hir::StructDef> {
345     P(hir::StructDef {
346         fields: sd.fields.iter().map(|f| lower_struct_field(f)).collect(),
347         ctor_id: sd.ctor_id,
348     })
349 }
350
351 pub fn lower_trait_ref(p: &TraitRef) -> hir::TraitRef {
352     hir::TraitRef { path: lower_path(&p.path), ref_id: p.ref_id }
353 }
354
355 pub fn lower_poly_trait_ref(p: &PolyTraitRef) -> hir::PolyTraitRef {
356     hir::PolyTraitRef {
357         bound_lifetimes: lower_lifetime_defs(&p.bound_lifetimes),
358         trait_ref: lower_trait_ref(&p.trait_ref),
359         span: p.span,
360     }
361 }
362
363 pub fn lower_struct_field(f: &StructField) -> hir::StructField {
364     Spanned {
365         node: hir::StructField_ {
366             id: f.node.id,
367             kind: lower_struct_field_kind(&f.node.kind),
368             ty: lower_ty(&f.node.ty),
369             attrs: f.node.attrs.clone(),
370         },
371         span: f.span,
372     }
373 }
374
375 pub fn lower_field(f: &Field) -> hir::Field {
376     hir::Field {
377         name: respan(f.ident.span, f.ident.node.name),
378         expr: lower_expr(&f.expr), span: f.span
379     }
380 }
381
382 pub fn lower_mt(mt: &MutTy) -> hir::MutTy {
383     hir::MutTy { ty: lower_ty(&mt.ty), mutbl: lower_mutability(mt.mutbl) }
384 }
385
386 pub fn lower_opt_bounds(b: &Option<OwnedSlice<TyParamBound>>)
387                         -> Option<OwnedSlice<hir::TyParamBound>> {
388     b.as_ref().map(|ref bounds| lower_bounds(bounds))
389 }
390
391 fn lower_bounds(bounds: &TyParamBounds) -> hir::TyParamBounds {
392     bounds.iter().map(|bound| lower_ty_param_bound(bound)).collect()
393 }
394
395 fn lower_variant_arg(va: &VariantArg) -> hir::VariantArg {
396     hir::VariantArg { id: va.id, ty: lower_ty(&va.ty) }
397 }
398
399 pub fn lower_block(b: &Block) -> P<hir::Block> {
400     P(hir::Block {
401         id: b.id,
402         stmts: b.stmts.iter().map(|s| lower_stmt(s)).collect(),
403         expr: b.expr.as_ref().map(|ref x| lower_expr(x)),
404         rules: lower_block_check_mode(&b.rules),
405         span: b.span,
406     })
407 }
408
409 pub fn lower_item_underscore(i: &Item_) -> hir::Item_ {
410     match *i {
411         ItemExternCrate(string) => hir::ItemExternCrate(string),
412         ItemUse(ref view_path) => {
413             hir::ItemUse(lower_view_path(view_path))
414         }
415         ItemStatic(ref t, m, ref e) => {
416             hir::ItemStatic(lower_ty(t), lower_mutability(m), lower_expr(e))
417         }
418         ItemConst(ref t, ref e) => {
419             hir::ItemConst(lower_ty(t), lower_expr(e))
420         }
421         ItemFn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
422             hir::ItemFn(
423                 lower_fn_decl(decl),
424                 lower_unsafety(unsafety),
425                 lower_constness(constness),
426                 abi,
427                 lower_generics(generics),
428                 lower_block(body)
429             )
430         }
431         ItemMod(ref m) => hir::ItemMod(lower_mod(m)),
432         ItemForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(nm)),
433         ItemTy(ref t, ref generics) => {
434             hir::ItemTy(lower_ty(t), lower_generics(generics))
435         }
436         ItemEnum(ref enum_definition, ref generics) => {
437             hir::ItemEnum(
438                 hir::EnumDef {
439                     variants: enum_definition.variants.iter().map(|x| lower_variant(x)).collect(),
440                 },
441                 lower_generics(generics))
442         }
443         ItemStruct(ref struct_def, ref generics) => {
444             let struct_def = lower_struct_def(struct_def);
445             hir::ItemStruct(struct_def, lower_generics(generics))
446         }
447         ItemDefaultImpl(unsafety, ref trait_ref) => {
448             hir::ItemDefaultImpl(lower_unsafety(unsafety), lower_trait_ref(trait_ref))
449         }
450         ItemImpl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
451             let new_impl_items = impl_items.iter().map(|item| lower_impl_item(item)).collect();
452             let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(trait_ref));
453             hir::ItemImpl(lower_unsafety(unsafety),
454                           lower_impl_polarity(polarity),
455                           lower_generics(generics),
456                           ifce,
457                           lower_ty(ty),
458                           new_impl_items)
459         }
460         ItemTrait(unsafety, ref generics, ref bounds, ref items) => {
461             let bounds = lower_bounds(bounds);
462             let items = items.iter().map(|item| lower_trait_item(item)).collect();
463             hir::ItemTrait(lower_unsafety(unsafety),
464                            lower_generics(generics),
465                            bounds,
466                            items)
467         }
468         ItemMac(_) => panic!("Shouldn't still be around"),
469     }
470 }
471
472 pub fn lower_trait_item(i: &TraitItem) -> P<hir::TraitItem> {
473     P(hir::TraitItem {
474             id: i.id,
475             name: i.ident.name,
476             attrs: i.attrs.clone(),
477             node: match i.node {
478             ConstTraitItem(ref ty, ref default) => {
479                 hir::ConstTraitItem(lower_ty(ty),
480                                     default.as_ref().map(|x| lower_expr(x)))
481             }
482             MethodTraitItem(ref sig, ref body) => {
483                 hir::MethodTraitItem(lower_method_sig(sig),
484                                      body.as_ref().map(|x| lower_block(x)))
485             }
486             TypeTraitItem(ref bounds, ref default) => {
487                 hir::TypeTraitItem(lower_bounds(bounds),
488                                    default.as_ref().map(|x| lower_ty(x)))
489             }
490         },
491             span: i.span,
492         })
493 }
494
495 pub fn lower_impl_item(i: &ImplItem) -> P<hir::ImplItem> {
496     P(hir::ImplItem {
497             id: i.id,
498             name: i.ident.name,
499             attrs: i.attrs.clone(),
500             vis: lower_visibility(i.vis),
501             node: match i.node  {
502             ConstImplItem(ref ty, ref expr) => {
503                 hir::ConstImplItem(lower_ty(ty), lower_expr(expr))
504             }
505             MethodImplItem(ref sig, ref body) => {
506                 hir::MethodImplItem(lower_method_sig(sig),
507                                     lower_block(body))
508             }
509             TypeImplItem(ref ty) => hir::TypeImplItem(lower_ty(ty)),
510             MacImplItem(..) => panic!("Shouldn't exist any more"),
511         },
512             span: i.span,
513         })
514 }
515
516 pub fn lower_mod(m: &Mod) -> hir::Mod {
517     hir::Mod { inner: m.inner, items: m.items.iter().map(|x| lower_item(x)).collect() }
518 }
519
520 pub fn lower_crate(c: &Crate) -> hir::Crate {
521     hir::Crate {
522         module: lower_mod(&c.module),
523         attrs: c.attrs.clone(),
524         config: c.config.clone(),
525         span: c.span,
526         exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(m)).collect(),
527     }
528 }
529
530 pub fn lower_macro_def(m: &MacroDef) -> hir::MacroDef {
531     hir::MacroDef {
532         name: m.ident.name,
533         attrs: m.attrs.clone(),
534         id: m.id,
535         span: m.span,
536         imported_from: m.imported_from.map(|x| x.name),
537         export: m.export,
538         use_locally: m.use_locally,
539         allow_internal_unstable: m.allow_internal_unstable,
540         body: m.body.clone(),
541     }
542 }
543
544 // fold one item into possibly many items
545 pub fn lower_item(i: &Item) -> P<hir::Item> {
546     P(lower_item_simple(i))
547 }
548
549 // fold one item into exactly one item
550 pub fn lower_item_simple(i: &Item) -> hir::Item {
551     let node = lower_item_underscore(&i.node);
552
553     hir::Item {
554         id: i.id,
555         name: i.ident.name,
556         attrs: i.attrs.clone(),
557         node: node,
558         vis: lower_visibility(i.vis),
559         span: i.span,
560     }
561 }
562
563 pub fn lower_foreign_item(i: &ForeignItem) -> P<hir::ForeignItem> {
564     P(hir::ForeignItem {
565             id: i.id,
566             name: i.ident.name,
567             attrs: i.attrs.clone(),
568             node: match i.node {
569             ForeignItemFn(ref fdec, ref generics) => {
570                 hir::ForeignItemFn(lower_fn_decl(fdec), lower_generics(generics))
571             }
572             ForeignItemStatic(ref t, m) => {
573                 hir::ForeignItemStatic(lower_ty(t), m)
574             }
575         },
576             vis: lower_visibility(i.vis),
577             span: i.span,
578         })
579 }
580
581 pub fn lower_method_sig(sig: &MethodSig) -> hir::MethodSig {
582     hir::MethodSig {
583         generics: lower_generics(&sig.generics),
584         abi: sig.abi,
585         explicit_self: lower_explicit_self(&sig.explicit_self),
586         unsafety: lower_unsafety(sig.unsafety),
587         constness: lower_constness(sig.constness),
588         decl: lower_fn_decl(&sig.decl),
589     }
590 }
591
592 pub fn lower_unsafety(u: Unsafety) -> hir::Unsafety {
593     match u {
594         Unsafety::Unsafe => hir::Unsafety::Unsafe,
595         Unsafety::Normal => hir::Unsafety::Normal,
596     }
597 }
598
599 pub fn lower_constness(c: Constness) -> hir::Constness {
600     match c {
601         Constness::Const => hir::Constness::Const,
602         Constness::NotConst => hir::Constness::NotConst,
603     }
604 }
605
606 pub fn lower_unop(u: UnOp) -> hir::UnOp {
607     match u {
608         UnDeref => hir::UnDeref,
609         UnNot => hir::UnNot,
610         UnNeg => hir::UnNeg,
611     }
612 }
613
614 pub fn lower_binop(b: BinOp) -> hir::BinOp {
615     Spanned {
616         node: match b.node {
617             BiAdd => hir::BiAdd,
618             BiSub => hir::BiSub,
619             BiMul => hir::BiMul,
620             BiDiv => hir::BiDiv,
621             BiRem => hir::BiRem,
622             BiAnd => hir::BiAnd,
623             BiOr => hir::BiOr,
624             BiBitXor => hir::BiBitXor,
625             BiBitAnd => hir::BiBitAnd,
626             BiBitOr => hir::BiBitOr,
627             BiShl => hir::BiShl,
628             BiShr => hir::BiShr,
629             BiEq => hir::BiEq,
630             BiLt => hir::BiLt,
631             BiLe => hir::BiLe,
632             BiNe => hir::BiNe,
633             BiGe => hir::BiGe,
634             BiGt => hir::BiGt,
635         },
636         span: b.span,
637     }
638 }
639
640 pub fn lower_pat(p: &Pat) -> P<hir::Pat> {
641     P(hir::Pat {
642             id: p.id,
643             node: match p.node {
644             PatWild(k) => hir::PatWild(lower_pat_wild_kind(k)),
645             PatIdent(ref binding_mode, pth1, ref sub) => {
646                 hir::PatIdent(lower_binding_mode(binding_mode),
647                         pth1,
648                         sub.as_ref().map(|x| lower_pat(x)))
649             }
650             PatLit(ref e) => hir::PatLit(lower_expr(e)),
651             PatEnum(ref pth, ref pats) => {
652                 hir::PatEnum(lower_path(pth),
653                         pats.as_ref().map(|pats| pats.iter().map(|x| lower_pat(x)).collect()))
654             }
655             PatQPath(ref qself, ref pth) => {
656                 let qself = hir::QSelf {
657                     ty: lower_ty(&qself.ty),
658                     position: qself.position,
659                 };
660                 hir::PatQPath(qself, lower_path(pth))
661             }
662             PatStruct(ref pth, ref fields, etc) => {
663                 let pth = lower_path(pth);
664                 let fs = fields.iter().map(|f| {
665                     Spanned { span: f.span,
666                               node: hir::FieldPat {
667                                   name: f.node.ident.name,
668                                   pat: lower_pat(&f.node.pat),
669                                   is_shorthand: f.node.is_shorthand,
670                               }}
671                 }).collect();
672                 hir::PatStruct(pth, fs, etc)
673             }
674             PatTup(ref elts) => hir::PatTup(elts.iter().map(|x| lower_pat(x)).collect()),
675             PatBox(ref inner) => hir::PatBox(lower_pat(inner)),
676             PatRegion(ref inner, mutbl) => hir::PatRegion(lower_pat(inner),
677                                                           lower_mutability(mutbl)),
678             PatRange(ref e1, ref e2) => {
679                 hir::PatRange(lower_expr(e1), lower_expr(e2))
680             },
681             PatVec(ref before, ref slice, ref after) => {
682                 hir::PatVec(before.iter().map(|x| lower_pat(x)).collect(),
683                        slice.as_ref().map(|x| lower_pat(x)),
684                        after.iter().map(|x| lower_pat(x)).collect())
685             }
686             PatMac(_) => panic!("Shouldn't exist here"),
687         },
688             span: p.span,
689         })
690 }
691
692 pub fn lower_expr(e: &Expr) -> P<hir::Expr> {
693     P(hir::Expr {
694             id: e.id,
695             node: match e.node {
696                 ExprBox(ref e) => {
697                     hir::ExprBox(lower_expr(e))
698                 }
699                 ExprVec(ref exprs) => {
700                     hir::ExprVec(exprs.iter().map(|x| lower_expr(x)).collect())
701                 }
702                 ExprRepeat(ref expr, ref count) => {
703                     hir::ExprRepeat(lower_expr(expr), lower_expr(count))
704                 }
705                 ExprTup(ref elts) => hir::ExprTup(elts.iter().map(|x| lower_expr(x)).collect()),
706                 ExprCall(ref f, ref args) => {
707                     hir::ExprCall(lower_expr(f),
708                              args.iter().map(|x| lower_expr(x)).collect())
709                 }
710                 ExprMethodCall(i, ref tps, ref args) => {
711                     hir::ExprMethodCall(
712                         respan(i.span, i.node.name),
713                         tps.iter().map(|x| lower_ty(x)).collect(),
714                         args.iter().map(|x| lower_expr(x)).collect())
715                 }
716                 ExprBinary(binop, ref lhs, ref rhs) => {
717                     hir::ExprBinary(lower_binop(binop),
718                             lower_expr(lhs),
719                             lower_expr(rhs))
720                 }
721                 ExprUnary(op, ref ohs) => {
722                     hir::ExprUnary(lower_unop(op), lower_expr(ohs))
723                 }
724                 ExprLit(ref l) => hir::ExprLit(P((**l).clone())),
725                 ExprCast(ref expr, ref ty) => {
726                     hir::ExprCast(lower_expr(expr), lower_ty(ty))
727                 }
728                 ExprAddrOf(m, ref ohs) => hir::ExprAddrOf(lower_mutability(m), lower_expr(ohs)),
729                 ExprIf(ref cond, ref tr, ref fl) => {
730                     hir::ExprIf(lower_expr(cond),
731                            lower_block(tr),
732                            fl.as_ref().map(|x| lower_expr(x)))
733                 }
734                 ExprWhile(ref cond, ref body, opt_ident) => {
735                     hir::ExprWhile(lower_expr(cond),
736                               lower_block(body),
737                               opt_ident)
738                 }
739                 ExprLoop(ref body, opt_ident) => {
740                     hir::ExprLoop(lower_block(body),
741                             opt_ident)
742                 }
743                 ExprMatch(ref expr, ref arms, ref source) => {
744                     hir::ExprMatch(lower_expr(expr),
745                             arms.iter().map(|x| lower_arm(x)).collect(),
746                             lower_match_source(source))
747                 }
748                 ExprClosure(capture_clause, ref decl, ref body) => {
749                     hir::ExprClosure(lower_capture_clause(capture_clause),
750                                 lower_fn_decl(decl),
751                                 lower_block(body))
752                 }
753                 ExprBlock(ref blk) => hir::ExprBlock(lower_block(blk)),
754                 ExprAssign(ref el, ref er) => {
755                     hir::ExprAssign(lower_expr(el), lower_expr(er))
756                 }
757                 ExprAssignOp(op, ref el, ref er) => {
758                     hir::ExprAssignOp(lower_binop(op),
759                                 lower_expr(el),
760                                 lower_expr(er))
761                 }
762                 ExprField(ref el, ident) => {
763                     hir::ExprField(lower_expr(el), respan(ident.span, ident.node.name))
764                 }
765                 ExprTupField(ref el, ident) => {
766                     hir::ExprTupField(lower_expr(el), ident)
767                 }
768                 ExprIndex(ref el, ref er) => {
769                     hir::ExprIndex(lower_expr(el), lower_expr(er))
770                 }
771                 ExprRange(ref e1, ref e2) => {
772                     hir::ExprRange(e1.as_ref().map(|x| lower_expr(x)),
773                               e2.as_ref().map(|x| lower_expr(x)))
774                 }
775                 ExprPath(ref qself, ref path) => {
776                     let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
777                         hir::QSelf {
778                             ty: lower_ty(ty),
779                             position: position
780                         }
781                     });
782                     hir::ExprPath(qself, lower_path(path))
783                 }
784                 ExprBreak(opt_ident) => hir::ExprBreak(opt_ident),
785                 ExprAgain(opt_ident) => hir::ExprAgain(opt_ident),
786                 ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(x))),
787                 ExprInlineAsm(InlineAsm {
788                     ref inputs,
789                     ref outputs,
790                     ref asm,
791                     asm_str_style,
792                     ref clobbers,
793                     volatile,
794                     alignstack,
795                     dialect,
796                     expn_id,
797                 }) => hir::ExprInlineAsm(hir::InlineAsm {
798                     inputs: inputs.iter().map(|&(ref c, ref input)| {
799                         (c.clone(), lower_expr(input))
800                     }).collect(),
801                     outputs: outputs.iter().map(|&(ref c, ref out, ref is_rw)| {
802                         (c.clone(), lower_expr(out), *is_rw)
803                     }).collect(),
804                     asm: asm.clone(),
805                     asm_str_style: asm_str_style,
806                     clobbers: clobbers.clone(),
807                     volatile: volatile,
808                     alignstack: alignstack,
809                     dialect: dialect,
810                     expn_id: expn_id,
811                 }),
812                 ExprStruct(ref path, ref fields, ref maybe_expr) => {
813                     hir::ExprStruct(lower_path(path),
814                             fields.iter().map(|x| lower_field(x)).collect(),
815                             maybe_expr.as_ref().map(|x| lower_expr(x)))
816                 },
817                 ExprParen(ref ex) => {
818                     return lower_expr(ex);
819                 }
820                 ExprInPlace(..) |
821                 ExprIfLet(..) |
822                 ExprWhileLet(..) |
823                 ExprForLoop(..) |
824                 ExprMac(_) => panic!("Shouldn't exist here"),
825             },
826             span: e.span,
827         })
828 }
829
830 pub fn lower_stmt(s: &Stmt) -> P<hir::Stmt> {
831     match s.node {
832         StmtDecl(ref d, id) => {
833             P(Spanned {
834                 node: hir::StmtDecl(lower_decl(d), id),
835                 span: s.span
836             })
837         }
838         StmtExpr(ref e, id) => {
839             P(Spanned {
840                 node: hir::StmtExpr(lower_expr(e), id),
841                 span: s.span
842             })
843         }
844         StmtSemi(ref e, id) => {
845             P(Spanned {
846                 node: hir::StmtSemi(lower_expr(e), id),
847                 span: s.span
848             })
849         }
850         StmtMac(..) => panic!("Shouldn't exist here")
851     }
852 }
853
854 pub fn lower_match_source(m: &MatchSource) -> hir::MatchSource {
855     match *m {
856         MatchSource::Normal => hir::MatchSource::Normal,
857         MatchSource::IfLetDesugar { contains_else_clause } => {
858             hir::MatchSource::IfLetDesugar { contains_else_clause: contains_else_clause }
859         }
860         MatchSource::WhileLetDesugar => hir::MatchSource::WhileLetDesugar,
861         MatchSource::ForLoopDesugar => hir::MatchSource::ForLoopDesugar,
862     }
863 }
864
865 pub fn lower_capture_clause(c: CaptureClause) -> hir::CaptureClause {
866     match c {
867         CaptureByValue => hir::CaptureByValue,
868         CaptureByRef => hir::CaptureByRef,
869     }
870 }
871
872 pub fn lower_visibility(v: Visibility) -> hir::Visibility {
873     match v {
874         Public => hir::Public,
875         Inherited => hir::Inherited,
876     }
877 }
878
879 pub fn lower_block_check_mode(b: &BlockCheckMode) -> hir::BlockCheckMode {
880     match *b {
881         DefaultBlock => hir::DefaultBlock,
882         UnsafeBlock(u) => hir::UnsafeBlock(lower_unsafe_source(u)),
883         PushUnsafeBlock(u) => hir::PushUnsafeBlock(lower_unsafe_source(u)),
884         PopUnsafeBlock(u) => hir::PopUnsafeBlock(lower_unsafe_source(u)),
885     }
886 }
887
888 pub fn lower_pat_wild_kind(p: PatWildKind) -> hir::PatWildKind {
889     match p {
890         PatWildSingle => hir::PatWildSingle,
891         PatWildMulti => hir::PatWildMulti,
892     }
893 }
894
895 pub fn lower_binding_mode(b: &BindingMode) -> hir::BindingMode {
896     match *b {
897         BindByRef(m) => hir::BindByRef(lower_mutability(m)),
898         BindByValue(m) => hir::BindByValue(lower_mutability(m)),
899     }
900 }
901
902 pub fn lower_struct_field_kind(s: &StructFieldKind) -> hir::StructFieldKind {
903     match *s {
904         NamedField(ident, vis) => hir::NamedField(ident.name, lower_visibility(vis)),
905         UnnamedField(vis) => hir::UnnamedField(lower_visibility(vis)),
906     }
907 }
908
909 pub fn lower_unsafe_source(u: UnsafeSource) -> hir::UnsafeSource {
910     match u {
911         CompilerGenerated => hir::CompilerGenerated,
912         UserProvided => hir::UserProvided,
913     }
914 }
915
916 pub fn lower_impl_polarity(i: ImplPolarity) -> hir::ImplPolarity {
917     match i {
918         ImplPolarity::Positive => hir::ImplPolarity::Positive,
919         ImplPolarity::Negative => hir::ImplPolarity::Negative,
920     }
921 }
922
923 pub fn lower_trait_bound_modifier(f: TraitBoundModifier) -> hir::TraitBoundModifier {
924     match f {
925         TraitBoundModifier::None => hir::TraitBoundModifier::None,
926         TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
927     }
928 }