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