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