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