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