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