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