]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/lowering.rs
825ab3fbd4c8227107c4c71846e79b5bb3972b5d
[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         defaultness: lower_defaultness(lctx, i.defaultness),
760         node: match i.node {
761             ImplItemKind::Const(ref ty, ref expr) => {
762                 hir::ImplItemKind::Const(lower_ty(lctx, ty), lower_expr(lctx, expr))
763             }
764             ImplItemKind::Method(ref sig, ref body) => {
765                 hir::ImplItemKind::Method(lower_method_sig(lctx, sig), lower_block(lctx, body))
766             }
767             ImplItemKind::Type(ref ty) => hir::ImplItemKind::Type(lower_ty(lctx, ty)),
768             ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
769         },
770         span: i.span,
771     }
772 }
773
774 pub fn lower_mod(lctx: &LoweringContext, m: &Mod) -> hir::Mod {
775     hir::Mod {
776         inner: m.inner,
777         item_ids: m.items.iter().map(|x| lower_item_id(lctx, x)).collect(),
778     }
779 }
780
781 struct ItemLowerer<'lcx, 'interner: 'lcx> {
782     items: BTreeMap<NodeId, hir::Item>,
783     lctx: &'lcx LoweringContext<'interner>,
784 }
785
786 impl<'lcx, 'interner> Visitor<'lcx> for ItemLowerer<'lcx, 'interner> {
787     fn visit_item(&mut self, item: &'lcx Item) {
788         self.items.insert(item.id, lower_item(self.lctx, item));
789         visit::walk_item(self, item);
790     }
791 }
792
793 pub fn lower_crate(lctx: &LoweringContext, c: &Crate) -> hir::Crate {
794     let items = {
795         let mut item_lowerer = ItemLowerer { items: BTreeMap::new(), lctx: lctx };
796         visit::walk_crate(&mut item_lowerer, c);
797         item_lowerer.items
798     };
799
800     hir::Crate {
801         module: lower_mod(lctx, &c.module),
802         attrs: lower_attrs(lctx, &c.attrs),
803         config: c.config.clone().into(),
804         span: c.span,
805         exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(lctx, m)).collect(),
806         items: items,
807     }
808 }
809
810 pub fn lower_macro_def(lctx: &LoweringContext, m: &MacroDef) -> hir::MacroDef {
811     hir::MacroDef {
812         name: m.ident.name,
813         attrs: lower_attrs(lctx, &m.attrs),
814         id: m.id,
815         span: m.span,
816         imported_from: m.imported_from.map(|x| x.name),
817         export: m.export,
818         use_locally: m.use_locally,
819         allow_internal_unstable: m.allow_internal_unstable,
820         body: m.body.clone().into(),
821     }
822 }
823
824 pub fn lower_item_id(_lctx: &LoweringContext, i: &Item) -> hir::ItemId {
825     hir::ItemId { id: i.id }
826 }
827
828 pub fn lower_item(lctx: &LoweringContext, i: &Item) -> hir::Item {
829     let node = lower_item_kind(lctx, &i.node);
830
831     hir::Item {
832         id: i.id,
833         name: i.ident.name,
834         attrs: lower_attrs(lctx, &i.attrs),
835         node: node,
836         vis: lower_visibility(lctx, i.vis),
837         span: i.span,
838     }
839 }
840
841 pub fn lower_foreign_item(lctx: &LoweringContext, i: &ForeignItem) -> hir::ForeignItem {
842     hir::ForeignItem {
843         id: i.id,
844         name: i.ident.name,
845         attrs: lower_attrs(lctx, &i.attrs),
846         node: match i.node {
847             ForeignItemKind::Fn(ref fdec, ref generics) => {
848                 hir::ForeignItemFn(lower_fn_decl(lctx, fdec), lower_generics(lctx, generics))
849             }
850             ForeignItemKind::Static(ref t, m) => {
851                 hir::ForeignItemStatic(lower_ty(lctx, t), m)
852             }
853         },
854         vis: lower_visibility(lctx, i.vis),
855         span: i.span,
856     }
857 }
858
859 pub fn lower_method_sig(lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig {
860     hir::MethodSig {
861         generics: lower_generics(lctx, &sig.generics),
862         abi: sig.abi,
863         explicit_self: lower_explicit_self(lctx, &sig.explicit_self),
864         unsafety: lower_unsafety(lctx, sig.unsafety),
865         constness: lower_constness(lctx, sig.constness),
866         decl: lower_fn_decl(lctx, &sig.decl),
867     }
868 }
869
870 pub fn lower_unsafety(_lctx: &LoweringContext, u: Unsafety) -> hir::Unsafety {
871     match u {
872         Unsafety::Unsafe => hir::Unsafety::Unsafe,
873         Unsafety::Normal => hir::Unsafety::Normal,
874     }
875 }
876
877 pub fn lower_constness(_lctx: &LoweringContext, c: Constness) -> hir::Constness {
878     match c {
879         Constness::Const => hir::Constness::Const,
880         Constness::NotConst => hir::Constness::NotConst,
881     }
882 }
883
884 pub fn lower_unop(_lctx: &LoweringContext, u: UnOp) -> hir::UnOp {
885     match u {
886         UnOp::Deref => hir::UnDeref,
887         UnOp::Not => hir::UnNot,
888         UnOp::Neg => hir::UnNeg,
889     }
890 }
891
892 pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp {
893     Spanned {
894         node: match b.node {
895             BinOpKind::Add => hir::BiAdd,
896             BinOpKind::Sub => hir::BiSub,
897             BinOpKind::Mul => hir::BiMul,
898             BinOpKind::Div => hir::BiDiv,
899             BinOpKind::Rem => hir::BiRem,
900             BinOpKind::And => hir::BiAnd,
901             BinOpKind::Or => hir::BiOr,
902             BinOpKind::BitXor => hir::BiBitXor,
903             BinOpKind::BitAnd => hir::BiBitAnd,
904             BinOpKind::BitOr => hir::BiBitOr,
905             BinOpKind::Shl => hir::BiShl,
906             BinOpKind::Shr => hir::BiShr,
907             BinOpKind::Eq => hir::BiEq,
908             BinOpKind::Lt => hir::BiLt,
909             BinOpKind::Le => hir::BiLe,
910             BinOpKind::Ne => hir::BiNe,
911             BinOpKind::Ge => hir::BiGe,
912             BinOpKind::Gt => hir::BiGt,
913         },
914         span: b.span,
915     }
916 }
917
918 pub fn lower_pat(lctx: &LoweringContext, p: &Pat) -> P<hir::Pat> {
919     P(hir::Pat {
920         id: p.id,
921         node: match p.node {
922             PatKind::Wild => hir::PatKind::Wild,
923             PatKind::Ident(ref binding_mode, pth1, ref sub) => {
924                 hir::PatKind::Ident(lower_binding_mode(lctx, binding_mode),
925                               respan(pth1.span, lower_ident(lctx, pth1.node)),
926                               sub.as_ref().map(|x| lower_pat(lctx, x)))
927             }
928             PatKind::Lit(ref e) => hir::PatKind::Lit(lower_expr(lctx, e)),
929             PatKind::TupleStruct(ref pth, ref pats) => {
930                 hir::PatKind::TupleStruct(lower_path(lctx, pth),
931                              pats.as_ref()
932                                  .map(|pats| pats.iter().map(|x| lower_pat(lctx, x)).collect()))
933             }
934             PatKind::Path(ref pth) => {
935                 hir::PatKind::Path(lower_path(lctx, pth))
936             }
937             PatKind::QPath(ref qself, ref pth) => {
938                 let qself = hir::QSelf {
939                     ty: lower_ty(lctx, &qself.ty),
940                     position: qself.position,
941                 };
942                 hir::PatKind::QPath(qself, lower_path(lctx, pth))
943             }
944             PatKind::Struct(ref pth, ref fields, etc) => {
945                 let pth = lower_path(lctx, pth);
946                 let fs = fields.iter()
947                                .map(|f| {
948                                    Spanned {
949                                        span: f.span,
950                                        node: hir::FieldPat {
951                                            name: f.node.ident.name,
952                                            pat: lower_pat(lctx, &f.node.pat),
953                                            is_shorthand: f.node.is_shorthand,
954                                        },
955                                    }
956                                })
957                                .collect();
958                 hir::PatKind::Struct(pth, fs, etc)
959             }
960             PatKind::Tup(ref elts) => {
961                 hir::PatKind::Tup(elts.iter().map(|x| lower_pat(lctx, x)).collect())
962             }
963             PatKind::Box(ref inner) => hir::PatKind::Box(lower_pat(lctx, inner)),
964             PatKind::Ref(ref inner, mutbl) => {
965                 hir::PatKind::Ref(lower_pat(lctx, inner), lower_mutability(lctx, mutbl))
966             }
967             PatKind::Range(ref e1, ref e2) => {
968                 hir::PatKind::Range(lower_expr(lctx, e1), lower_expr(lctx, e2))
969             }
970             PatKind::Vec(ref before, ref slice, ref after) => {
971                 hir::PatKind::Vec(before.iter().map(|x| lower_pat(lctx, x)).collect(),
972                             slice.as_ref().map(|x| lower_pat(lctx, x)),
973                             after.iter().map(|x| lower_pat(lctx, x)).collect())
974             }
975             PatKind::Mac(_) => panic!("Shouldn't exist here"),
976         },
977         span: p.span,
978     })
979 }
980
981 pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
982     P(hir::Expr {
983         id: e.id,
984         node: match e.node {
985             // Issue #22181:
986             // Eventually a desugaring for `box EXPR`
987             // (similar to the desugaring above for `in PLACE BLOCK`)
988             // should go here, desugaring
989             //
990             // to:
991             //
992             // let mut place = BoxPlace::make_place();
993             // let raw_place = Place::pointer(&mut place);
994             // let value = $value;
995             // unsafe {
996             //     ::std::ptr::write(raw_place, value);
997             //     Boxed::finalize(place)
998             // }
999             //
1000             // But for now there are type-inference issues doing that.
1001             ExprKind::Box(ref e) => {
1002                 hir::ExprBox(lower_expr(lctx, e))
1003             }
1004
1005             // Desugar ExprBox: `in (PLACE) EXPR`
1006             ExprKind::InPlace(ref placer, ref value_expr) => {
1007                 // to:
1008                 //
1009                 // let p = PLACE;
1010                 // let mut place = Placer::make_place(p);
1011                 // let raw_place = Place::pointer(&mut place);
1012                 // push_unsafe!({
1013                 //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1014                 //     InPlace::finalize(place)
1015                 // })
1016                 return cache_ids(lctx, e.id, |lctx| {
1017                     let placer_expr = lower_expr(lctx, placer);
1018                     let value_expr = lower_expr(lctx, value_expr);
1019
1020                     let placer_ident = lctx.str_to_ident("placer");
1021                     let place_ident = lctx.str_to_ident("place");
1022                     let p_ptr_ident = lctx.str_to_ident("p_ptr");
1023
1024                     let make_place = ["ops", "Placer", "make_place"];
1025                     let place_pointer = ["ops", "Place", "pointer"];
1026                     let move_val_init = ["intrinsics", "move_val_init"];
1027                     let inplace_finalize = ["ops", "InPlace", "finalize"];
1028
1029                     let make_call = |lctx: &LoweringContext, p, args| {
1030                         let path = core_path(lctx, e.span, p);
1031                         let path = expr_path(lctx, path, None);
1032                         expr_call(lctx, e.span, path, args, None)
1033                     };
1034
1035                     let mk_stmt_let = |lctx: &LoweringContext, bind, expr| {
1036                         stmt_let(lctx, e.span, false, bind, expr, None)
1037                     };
1038
1039                     let mk_stmt_let_mut = |lctx: &LoweringContext, bind, expr| {
1040                         stmt_let(lctx, e.span, true, bind, expr, None)
1041                     };
1042
1043                     // let placer = <placer_expr> ;
1044                     let s1 = {
1045                         let placer_expr = signal_block_expr(lctx,
1046                                                             hir_vec![],
1047                                                             placer_expr,
1048                                                             e.span,
1049                                                             hir::PopUnstableBlock,
1050                                                             None);
1051                         mk_stmt_let(lctx, placer_ident, placer_expr)
1052                     };
1053
1054                     // let mut place = Placer::make_place(placer);
1055                     let s2 = {
1056                         let placer = expr_ident(lctx, e.span, placer_ident, None);
1057                         let call = make_call(lctx, &make_place, hir_vec![placer]);
1058                         mk_stmt_let_mut(lctx, place_ident, call)
1059                     };
1060
1061                     // let p_ptr = Place::pointer(&mut place);
1062                     let s3 = {
1063                         let agent = expr_ident(lctx, e.span, place_ident, None);
1064                         let args = hir_vec![expr_mut_addr_of(lctx, e.span, agent, None)];
1065                         let call = make_call(lctx, &place_pointer, args);
1066                         mk_stmt_let(lctx, p_ptr_ident, call)
1067                     };
1068
1069                     // pop_unsafe!(EXPR));
1070                     let pop_unsafe_expr = {
1071                         let value_expr = signal_block_expr(lctx,
1072                                                            hir_vec![],
1073                                                            value_expr,
1074                                                            e.span,
1075                                                            hir::PopUnstableBlock,
1076                                                            None);
1077                         signal_block_expr(lctx,
1078                                           hir_vec![],
1079                                           value_expr,
1080                                           e.span,
1081                                           hir::PopUnsafeBlock(hir::CompilerGenerated), None)
1082                     };
1083
1084                     // push_unsafe!({
1085                     //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
1086                     //     InPlace::finalize(place)
1087                     // })
1088                     let expr = {
1089                         let ptr = expr_ident(lctx, e.span, p_ptr_ident, None);
1090                         let call_move_val_init =
1091                             hir::StmtSemi(
1092                                 make_call(lctx, &move_val_init, hir_vec![ptr, pop_unsafe_expr]),
1093                                 lctx.next_id());
1094                         let call_move_val_init = respan(e.span, call_move_val_init);
1095
1096                         let place = expr_ident(lctx, e.span, place_ident, None);
1097                         let call = make_call(lctx, &inplace_finalize, hir_vec![place]);
1098                         signal_block_expr(lctx,
1099                                           hir_vec![call_move_val_init],
1100                                           call,
1101                                           e.span,
1102                                           hir::PushUnsafeBlock(hir::CompilerGenerated), None)
1103                     };
1104
1105                     signal_block_expr(lctx,
1106                                       hir_vec![s1, s2, s3],
1107                                       expr,
1108                                       e.span,
1109                                       hir::PushUnstableBlock,
1110                                       e.attrs.clone())
1111                 });
1112             }
1113
1114             ExprKind::Vec(ref exprs) => {
1115                 hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect())
1116             }
1117             ExprKind::Repeat(ref expr, ref count) => {
1118                 let expr = lower_expr(lctx, expr);
1119                 let count = lower_expr(lctx, count);
1120                 hir::ExprRepeat(expr, count)
1121             }
1122             ExprKind::Tup(ref elts) => {
1123                 hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect())
1124             }
1125             ExprKind::Call(ref f, ref args) => {
1126                 let f = lower_expr(lctx, f);
1127                 hir::ExprCall(f, args.iter().map(|x| lower_expr(lctx, x)).collect())
1128             }
1129             ExprKind::MethodCall(i, ref tps, ref args) => {
1130                 let tps = tps.iter().map(|x| lower_ty(lctx, x)).collect();
1131                 let args = args.iter().map(|x| lower_expr(lctx, x)).collect();
1132                 hir::ExprMethodCall(respan(i.span, i.node.name), tps, args)
1133             }
1134             ExprKind::Binary(binop, ref lhs, ref rhs) => {
1135                 let binop = lower_binop(lctx, binop);
1136                 let lhs = lower_expr(lctx, lhs);
1137                 let rhs = lower_expr(lctx, rhs);
1138                 hir::ExprBinary(binop, lhs, rhs)
1139             }
1140             ExprKind::Unary(op, ref ohs) => {
1141                 let op = lower_unop(lctx, op);
1142                 let ohs = lower_expr(lctx, ohs);
1143                 hir::ExprUnary(op, ohs)
1144             }
1145             ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
1146             ExprKind::Cast(ref expr, ref ty) => {
1147                 let expr = lower_expr(lctx, expr);
1148                 hir::ExprCast(expr, lower_ty(lctx, ty))
1149             }
1150             ExprKind::Type(ref expr, ref ty) => {
1151                 let expr = lower_expr(lctx, expr);
1152                 hir::ExprType(expr, lower_ty(lctx, ty))
1153             }
1154             ExprKind::AddrOf(m, ref ohs) => {
1155                 let m = lower_mutability(lctx, m);
1156                 let ohs = lower_expr(lctx, ohs);
1157                 hir::ExprAddrOf(m, ohs)
1158             }
1159             // More complicated than you might expect because the else branch
1160             // might be `if let`.
1161             ExprKind::If(ref cond, ref blk, ref else_opt) => {
1162                 let else_opt = else_opt.as_ref().map(|els| {
1163                     match els.node {
1164                         ExprKind::IfLet(..) => {
1165                             cache_ids(lctx, e.id, |lctx| {
1166                                 // wrap the if-let expr in a block
1167                                 let span = els.span;
1168                                 let els = lower_expr(lctx, els);
1169                                 let id = lctx.next_id();
1170                                 let blk = P(hir::Block {
1171                                     stmts: hir_vec![],
1172                                     expr: Some(els),
1173                                     id: id,
1174                                     rules: hir::DefaultBlock,
1175                                     span: span,
1176                                 });
1177                                 expr_block(lctx, blk, None)
1178                             })
1179                         }
1180                         _ => lower_expr(lctx, els),
1181                     }
1182                 });
1183
1184                 hir::ExprIf(lower_expr(lctx, cond), lower_block(lctx, blk), else_opt)
1185             }
1186             ExprKind::While(ref cond, ref body, opt_ident) => {
1187                 hir::ExprWhile(lower_expr(lctx, cond), lower_block(lctx, body),
1188                                opt_ident.map(|ident| lower_ident(lctx, ident)))
1189             }
1190             ExprKind::Loop(ref body, opt_ident) => {
1191                 hir::ExprLoop(lower_block(lctx, body),
1192                               opt_ident.map(|ident| lower_ident(lctx, ident)))
1193             }
1194             ExprKind::Match(ref expr, ref arms) => {
1195                 hir::ExprMatch(lower_expr(lctx, expr),
1196                                arms.iter().map(|x| lower_arm(lctx, x)).collect(),
1197                                hir::MatchSource::Normal)
1198             }
1199             ExprKind::Closure(capture_clause, ref decl, ref body) => {
1200                 hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
1201                                  lower_fn_decl(lctx, decl),
1202                                  lower_block(lctx, body))
1203             }
1204             ExprKind::Block(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
1205             ExprKind::Assign(ref el, ref er) => {
1206                 hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
1207             }
1208             ExprKind::AssignOp(op, ref el, ref er) => {
1209                 hir::ExprAssignOp(lower_binop(lctx, op),
1210                                   lower_expr(lctx, el),
1211                                   lower_expr(lctx, er))
1212             }
1213             ExprKind::Field(ref el, ident) => {
1214                 hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name))
1215             }
1216             ExprKind::TupField(ref el, ident) => {
1217                 hir::ExprTupField(lower_expr(lctx, el), ident)
1218             }
1219             ExprKind::Index(ref el, ref er) => {
1220                 hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
1221             }
1222             ExprKind::Range(ref e1, ref e2, lims) => {
1223                 fn make_struct(lctx: &LoweringContext,
1224                                ast_expr: &Expr,
1225                                path: &[&str],
1226                                fields: &[(&str, &P<Expr>)]) -> P<hir::Expr> {
1227                     let strs = std_path(lctx, &iter::once(&"ops")
1228                                                     .chain(path)
1229                                                     .map(|s| *s)
1230                                                     .collect::<Vec<_>>());
1231
1232                     let structpath = path_global(ast_expr.span, strs);
1233
1234                     let hir_expr = if fields.len() == 0 {
1235                         expr_path(lctx,
1236                                   structpath,
1237                                   ast_expr.attrs.clone())
1238                     } else {
1239                         expr_struct(lctx,
1240                                     ast_expr.span,
1241                                     structpath,
1242                                     fields.into_iter().map(|&(s, e)| {
1243                                         field(token::intern(s),
1244                                               signal_block_expr(lctx,
1245                                                                 hir_vec![],
1246                                                                 lower_expr(lctx, &**e),
1247                                                                 e.span,
1248                                                                 hir::PopUnstableBlock,
1249                                                                 None),
1250                                               ast_expr.span)
1251                                     }).collect(),
1252                                     None,
1253                                     ast_expr.attrs.clone())
1254                     };
1255
1256                     signal_block_expr(lctx,
1257                                       hir_vec![],
1258                                       hir_expr,
1259                                       ast_expr.span,
1260                                       hir::PushUnstableBlock,
1261                                       None)
1262                 }
1263
1264                 return cache_ids(lctx, e.id, |lctx| {
1265                     use syntax::ast::RangeLimits::*;
1266
1267                     match (e1, e2, lims) {
1268                         (&None,         &None,         HalfOpen) =>
1269                             make_struct(lctx, e, &["RangeFull"],
1270                                                  &[]),
1271
1272                         (&Some(ref e1), &None,         HalfOpen) =>
1273                             make_struct(lctx, e, &["RangeFrom"],
1274                                                  &[("start", e1)]),
1275
1276                         (&None,         &Some(ref e2), HalfOpen) =>
1277                             make_struct(lctx, e, &["RangeTo"],
1278                                                  &[("end", e2)]),
1279
1280                         (&Some(ref e1), &Some(ref e2), HalfOpen) =>
1281                             make_struct(lctx, e, &["Range"],
1282                                                  &[("start", e1), ("end", e2)]),
1283
1284                         (&None,         &Some(ref e2), Closed)   =>
1285                             make_struct(lctx, e, &["RangeToInclusive"],
1286                                                  &[("end", e2)]),
1287
1288                         (&Some(ref e1), &Some(ref e2), Closed)   =>
1289                             make_struct(lctx, e, &["RangeInclusive", "NonEmpty"],
1290                                                  &[("start", e1), ("end", e2)]),
1291
1292                         _ => panic!("impossible range in AST"),
1293                     }
1294                 });
1295             }
1296             ExprKind::Path(ref qself, ref path) => {
1297                 let hir_qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
1298                     hir::QSelf {
1299                         ty: lower_ty(lctx, ty),
1300                         position: position,
1301                     }
1302                 });
1303                 hir::ExprPath(hir_qself, lower_path_full(lctx, path, qself.is_none()))
1304             }
1305             ExprKind::Break(opt_ident) => hir::ExprBreak(opt_ident.map(|sp_ident| {
1306                 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1307             })),
1308             ExprKind::Again(opt_ident) => hir::ExprAgain(opt_ident.map(|sp_ident| {
1309                 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1310             })),
1311             ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
1312             ExprKind::InlineAsm(InlineAsm {
1313                     ref inputs,
1314                     ref outputs,
1315                     ref asm,
1316                     asm_str_style,
1317                     ref clobbers,
1318                     volatile,
1319                     alignstack,
1320                     dialect,
1321                     expn_id,
1322                 }) => hir::ExprInlineAsm(hir::InlineAsm {
1323                 inputs: inputs.iter()
1324                               .map(|&(ref c, ref input)| (c.clone(), lower_expr(lctx, input)))
1325                               .collect(),
1326                 outputs: outputs.iter()
1327                                 .map(|out| {
1328                                     hir::InlineAsmOutput {
1329                                         constraint: out.constraint.clone(),
1330                                         expr: lower_expr(lctx, &out.expr),
1331                                         is_rw: out.is_rw,
1332                                         is_indirect: out.is_indirect,
1333                                     }
1334                                 })
1335                                 .collect(),
1336                 asm: asm.clone(),
1337                 asm_str_style: asm_str_style,
1338                 clobbers: clobbers.clone().into(),
1339                 volatile: volatile,
1340                 alignstack: alignstack,
1341                 dialect: dialect,
1342                 expn_id: expn_id,
1343             }),
1344             ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
1345                 hir::ExprStruct(lower_path(lctx, path),
1346                                 fields.iter().map(|x| lower_field(lctx, x)).collect(),
1347                                 maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
1348             }
1349             ExprKind::Paren(ref ex) => {
1350                 // merge attributes into the inner expression.
1351                 return lower_expr(lctx, ex).map(|mut ex| {
1352                     ex.attrs.update(|attrs| {
1353                         attrs.prepend(e.attrs.clone())
1354                     });
1355                     ex
1356                 });
1357             }
1358
1359             // Desugar ExprIfLet
1360             // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
1361             ExprKind::IfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
1362                 // to:
1363                 //
1364                 //   match <sub_expr> {
1365                 //     <pat> => <body>,
1366                 //     [_ if <else_opt_if_cond> => <else_opt_if_body>,]
1367                 //     _ => [<else_opt> | ()]
1368                 //   }
1369
1370                 return cache_ids(lctx, e.id, |lctx| {
1371                     // `<pat> => <body>`
1372                     let pat_arm = {
1373                         let body = lower_block(lctx, body);
1374                         let body_expr = expr_block(lctx, body, None);
1375                         arm(hir_vec![lower_pat(lctx, pat)], body_expr)
1376                     };
1377
1378                     // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
1379                     let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e));
1380                     let else_if_arms = {
1381                         let mut arms = vec![];
1382                         loop {
1383                             let else_opt_continue = else_opt.and_then(|els| {
1384                                 els.and_then(|els| {
1385                                     match els.node {
1386                                         // else if
1387                                         hir::ExprIf(cond, then, else_opt) => {
1388                                             let pat_under = pat_wild(lctx, e.span);
1389                                             arms.push(hir::Arm {
1390                                                 attrs: hir_vec![],
1391                                                 pats: hir_vec![pat_under],
1392                                                 guard: Some(cond),
1393                                                 body: expr_block(lctx, then, None),
1394                                             });
1395                                             else_opt.map(|else_opt| (else_opt, true))
1396                                         }
1397                                         _ => Some((P(els), false)),
1398                                     }
1399                                 })
1400                             });
1401                             match else_opt_continue {
1402                                 Some((e, true)) => {
1403                                     else_opt = Some(e);
1404                                 }
1405                                 Some((e, false)) => {
1406                                     else_opt = Some(e);
1407                                     break;
1408                                 }
1409                                 None => {
1410                                     else_opt = None;
1411                                     break;
1412                                 }
1413                             }
1414                         }
1415                         arms
1416                     };
1417
1418                     let contains_else_clause = else_opt.is_some();
1419
1420                     // `_ => [<else_opt> | ()]`
1421                     let else_arm = {
1422                         let pat_under = pat_wild(lctx, e.span);
1423                         let else_expr =
1424                             else_opt.unwrap_or_else(
1425                                 || expr_tuple(lctx, e.span, hir_vec![], None));
1426                         arm(hir_vec![pat_under], else_expr)
1427                     };
1428
1429                     let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
1430                     arms.push(pat_arm);
1431                     arms.extend(else_if_arms);
1432                     arms.push(else_arm);
1433
1434                     let sub_expr = lower_expr(lctx, sub_expr);
1435                     // add attributes to the outer returned expr node
1436                     expr(lctx,
1437                          e.span,
1438                          hir::ExprMatch(sub_expr,
1439                                         arms.into(),
1440                                         hir::MatchSource::IfLetDesugar {
1441                                             contains_else_clause: contains_else_clause,
1442                                         }),
1443                          e.attrs.clone())
1444                 });
1445             }
1446
1447             // Desugar ExprWhileLet
1448             // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
1449             ExprKind::WhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
1450                 // to:
1451                 //
1452                 //   [opt_ident]: loop {
1453                 //     match <sub_expr> {
1454                 //       <pat> => <body>,
1455                 //       _ => break
1456                 //     }
1457                 //   }
1458
1459                 return cache_ids(lctx, e.id, |lctx| {
1460                     // `<pat> => <body>`
1461                     let pat_arm = {
1462                         let body = lower_block(lctx, body);
1463                         let body_expr = expr_block(lctx, body, None);
1464                         arm(hir_vec![lower_pat(lctx, pat)], body_expr)
1465                     };
1466
1467                     // `_ => break`
1468                     let break_arm = {
1469                         let pat_under = pat_wild(lctx, e.span);
1470                         let break_expr = expr_break(lctx, e.span, None);
1471                         arm(hir_vec![pat_under], break_expr)
1472                     };
1473
1474                     // `match <sub_expr> { ... }`
1475                     let arms = hir_vec![pat_arm, break_arm];
1476                     let sub_expr = lower_expr(lctx, sub_expr);
1477                     let match_expr = expr(lctx,
1478                                           e.span,
1479                                           hir::ExprMatch(sub_expr,
1480                                                          arms,
1481                                                          hir::MatchSource::WhileLetDesugar),
1482                                           None);
1483
1484                     // `[opt_ident]: loop { ... }`
1485                     let loop_block = block_expr(lctx, match_expr);
1486                     let loop_expr = hir::ExprLoop(loop_block,
1487                                                   opt_ident.map(|ident| lower_ident(lctx, ident)));
1488                     // add attributes to the outer returned expr node
1489                     expr(lctx, e.span, loop_expr, e.attrs.clone())
1490                 });
1491             }
1492
1493             // Desugar ExprForLoop
1494             // From: `[opt_ident]: for <pat> in <head> <body>`
1495             ExprKind::ForLoop(ref pat, ref head, ref body, opt_ident) => {
1496                 // to:
1497                 //
1498                 //   {
1499                 //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1500                 //       mut iter => {
1501                 //         [opt_ident]: loop {
1502                 //           match ::std::iter::Iterator::next(&mut iter) {
1503                 //             ::std::option::Option::Some(<pat>) => <body>,
1504                 //             ::std::option::Option::None => break
1505                 //           }
1506                 //         }
1507                 //       }
1508                 //     };
1509                 //     result
1510                 //   }
1511
1512                 return cache_ids(lctx, e.id, |lctx| {
1513                     // expand <head>
1514                     let head = lower_expr(lctx, head);
1515
1516                     let iter = lctx.str_to_ident("iter");
1517
1518                     // `::std::option::Option::Some(<pat>) => <body>`
1519                     let pat_arm = {
1520                         let body_block = lower_block(lctx, body);
1521                         let body_span = body_block.span;
1522                         let body_expr = P(hir::Expr {
1523                             id: lctx.next_id(),
1524                             node: hir::ExprBlock(body_block),
1525                             span: body_span,
1526                             attrs: None,
1527                         });
1528                         let pat = lower_pat(lctx, pat);
1529                         let some_pat = pat_some(lctx, e.span, pat);
1530
1531                         arm(hir_vec![some_pat], body_expr)
1532                     };
1533
1534                     // `::std::option::Option::None => break`
1535                     let break_arm = {
1536                         let break_expr = expr_break(lctx, e.span, None);
1537
1538                         arm(hir_vec![pat_none(lctx, e.span)], break_expr)
1539                     };
1540
1541                     // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1542                     let match_expr = {
1543                         let next_path = {
1544                             let strs = std_path(lctx, &["iter", "Iterator", "next"]);
1545
1546                             path_global(e.span, strs)
1547                         };
1548                         let iter = expr_ident(lctx, e.span, iter, None);
1549                         let ref_mut_iter = expr_mut_addr_of(lctx, e.span, iter, None);
1550                         let next_path = expr_path(lctx, next_path, None);
1551                         let next_expr = expr_call(lctx,
1552                                                   e.span,
1553                                                   next_path,
1554                                                   hir_vec![ref_mut_iter],
1555                                                   None);
1556                         let arms = hir_vec![pat_arm, break_arm];
1557
1558                         expr(lctx,
1559                              e.span,
1560                              hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
1561                              None)
1562                     };
1563
1564                     // `[opt_ident]: loop { ... }`
1565                     let loop_block = block_expr(lctx, match_expr);
1566                     let loop_expr = hir::ExprLoop(loop_block,
1567                                                   opt_ident.map(|ident| lower_ident(lctx, ident)));
1568                     let loop_expr = expr(lctx, e.span, loop_expr, None);
1569
1570                     // `mut iter => { ... }`
1571                     let iter_arm = {
1572                         let iter_pat = pat_ident_binding_mode(lctx,
1573                                                               e.span,
1574                                                               iter,
1575                                                               hir::BindByValue(hir::MutMutable));
1576                         arm(hir_vec![iter_pat], loop_expr)
1577                     };
1578
1579                     // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1580                     let into_iter_expr = {
1581                         let into_iter_path = {
1582                             let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
1583
1584                             path_global(e.span, strs)
1585                         };
1586
1587                         let into_iter = expr_path(lctx, into_iter_path, None);
1588                         expr_call(lctx, e.span, into_iter, hir_vec![head], None)
1589                     };
1590
1591                     let match_expr = expr_match(lctx,
1592                                                 e.span,
1593                                                 into_iter_expr,
1594                                                 hir_vec![iter_arm],
1595                                                 hir::MatchSource::ForLoopDesugar,
1596                                                 None);
1597
1598                     // `{ let _result = ...; _result }`
1599                     // underscore prevents an unused_variables lint if the head diverges
1600                     let result_ident = lctx.str_to_ident("_result");
1601                     let let_stmt = stmt_let(lctx, e.span, false, result_ident, match_expr, None);
1602                     let result = expr_ident(lctx, e.span, result_ident, None);
1603                     let block = block_all(lctx, e.span, hir_vec![let_stmt], Some(result));
1604                     // add the attributes to the outer returned expr node
1605                     expr_block(lctx, block, e.attrs.clone())
1606                 });
1607             }
1608
1609             // Desugar ExprKind::Try
1610             // From: `<expr>?`
1611             ExprKind::Try(ref sub_expr) => {
1612                 // to:
1613                 //
1614                 // {
1615                 //     match <expr> {
1616                 //         Ok(val) => val,
1617                 //         Err(err) => {
1618                 //             return Err(From::from(err))
1619                 //         }
1620                 //     }
1621                 // }
1622
1623                 return cache_ids(lctx, e.id, |lctx| {
1624                     // expand <expr>
1625                     let sub_expr = lower_expr(lctx, sub_expr);
1626
1627                     // Ok(val) => val
1628                     let ok_arm = {
1629                         let val_ident = lctx.str_to_ident("val");
1630                         let val_pat = pat_ident(lctx, e.span, val_ident);
1631                         let val_expr = expr_ident(lctx, e.span, val_ident, None);
1632                         let ok_pat = pat_ok(lctx, e.span, val_pat);
1633
1634                         arm(hir_vec![ok_pat], val_expr)
1635                     };
1636
1637                     // Err(err) => return Err(From::from(err))
1638                     let err_arm = {
1639                         let err_ident = lctx.str_to_ident("err");
1640                         let from_expr = {
1641                             let path = std_path(lctx, &["convert", "From", "from"]);
1642                             let path = path_global(e.span, path);
1643                             let from = expr_path(lctx, path, None);
1644                             let err_expr = expr_ident(lctx, e.span, err_ident, None);
1645
1646                             expr_call(lctx, e.span, from, hir_vec![err_expr], None)
1647                         };
1648                         let err_expr = {
1649                             let path = std_path(lctx, &["result", "Result", "Err"]);
1650                             let path = path_global(e.span, path);
1651                             let err_ctor = expr_path(lctx, path, None);
1652                             expr_call(lctx, e.span, err_ctor, hir_vec![from_expr], None)
1653                         };
1654                         let err_pat = pat_err(lctx, e.span, pat_ident(lctx, e.span, err_ident));
1655                         let ret_expr = expr(lctx, e.span,
1656                                             hir::Expr_::ExprRet(Some(err_expr)), None);
1657
1658                         arm(hir_vec![err_pat], ret_expr)
1659                     };
1660
1661                     expr_match(lctx, e.span, sub_expr, hir_vec![err_arm, ok_arm],
1662                                hir::MatchSource::TryDesugar, None)
1663                 })
1664             }
1665
1666             ExprKind::Mac(_) => panic!("Shouldn't exist here"),
1667         },
1668         span: e.span,
1669         attrs: e.attrs.clone(),
1670     })
1671 }
1672
1673 pub fn lower_stmt(lctx: &LoweringContext, s: &Stmt) -> hir::Stmt {
1674     match s.node {
1675         StmtKind::Decl(ref d, id) => {
1676             Spanned {
1677                 node: hir::StmtDecl(lower_decl(lctx, d), id),
1678                 span: s.span,
1679             }
1680         }
1681         StmtKind::Expr(ref e, id) => {
1682             Spanned {
1683                 node: hir::StmtExpr(lower_expr(lctx, e), id),
1684                 span: s.span,
1685             }
1686         }
1687         StmtKind::Semi(ref e, id) => {
1688             Spanned {
1689                 node: hir::StmtSemi(lower_expr(lctx, e), id),
1690                 span: s.span,
1691             }
1692         }
1693         StmtKind::Mac(..) => panic!("Shouldn't exist here"),
1694     }
1695 }
1696
1697 pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureBy) -> hir::CaptureClause {
1698     match c {
1699         CaptureBy::Value => hir::CaptureByValue,
1700         CaptureBy::Ref => hir::CaptureByRef,
1701     }
1702 }
1703
1704 pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1705     match v {
1706         Visibility::Public => hir::Public,
1707         Visibility::Inherited => hir::Inherited,
1708     }
1709 }
1710
1711 pub fn lower_defaultness(_lctx: &LoweringContext, d: Defaultness) -> hir::Defaultness {
1712     match d {
1713         Defaultness::Default => hir::Defaultness::Default,
1714         Defaultness::Final => hir::Defaultness::Final,
1715     }
1716 }
1717
1718 pub fn lower_block_check_mode(lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1719     match *b {
1720         BlockCheckMode::Default => hir::DefaultBlock,
1721         BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(lower_unsafe_source(lctx, u)),
1722     }
1723 }
1724
1725 pub fn lower_binding_mode(lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1726     match *b {
1727         BindingMode::ByRef(m) => hir::BindByRef(lower_mutability(lctx, m)),
1728         BindingMode::ByValue(m) => hir::BindByValue(lower_mutability(lctx, m)),
1729     }
1730 }
1731
1732 pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1733     match u {
1734         CompilerGenerated => hir::CompilerGenerated,
1735         UserProvided => hir::UserProvided,
1736     }
1737 }
1738
1739 pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1740     match i {
1741         ImplPolarity::Positive => hir::ImplPolarity::Positive,
1742         ImplPolarity::Negative => hir::ImplPolarity::Negative,
1743     }
1744 }
1745
1746 pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
1747                                   f: TraitBoundModifier)
1748                                   -> hir::TraitBoundModifier {
1749     match f {
1750         TraitBoundModifier::None => hir::TraitBoundModifier::None,
1751         TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
1752     }
1753 }
1754
1755 // Helper methods for building HIR.
1756
1757 fn arm(pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1758     hir::Arm {
1759         attrs: hir_vec![],
1760         pats: pats,
1761         guard: None,
1762         body: expr,
1763     }
1764 }
1765
1766 fn field(name: Name, expr: P<hir::Expr>, span: Span) -> hir::Field {
1767     hir::Field {
1768         name: Spanned {
1769             node: name,
1770             span: span,
1771         },
1772         span: span,
1773         expr: expr,
1774     }
1775 }
1776
1777 fn expr_break(lctx: &LoweringContext, span: Span,
1778               attrs: ThinAttributes) -> P<hir::Expr> {
1779     expr(lctx, span, hir::ExprBreak(None), attrs)
1780 }
1781
1782 fn expr_call(lctx: &LoweringContext,
1783              span: Span,
1784              e: P<hir::Expr>,
1785              args: hir::HirVec<P<hir::Expr>>,
1786              attrs: ThinAttributes)
1787              -> P<hir::Expr> {
1788     expr(lctx, span, hir::ExprCall(e, args), attrs)
1789 }
1790
1791 fn expr_ident(lctx: &LoweringContext, span: Span, id: hir::Ident,
1792               attrs: ThinAttributes) -> P<hir::Expr> {
1793     expr_path(lctx, path_ident(span, id), attrs)
1794 }
1795
1796 fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>,
1797                     attrs: ThinAttributes) -> P<hir::Expr> {
1798     expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e), attrs)
1799 }
1800
1801 fn expr_path(lctx: &LoweringContext, path: hir::Path,
1802              attrs: ThinAttributes) -> P<hir::Expr> {
1803     expr(lctx, path.span, hir::ExprPath(None, path), attrs)
1804 }
1805
1806 fn expr_match(lctx: &LoweringContext,
1807               span: Span,
1808               arg: P<hir::Expr>,
1809               arms: hir::HirVec<hir::Arm>,
1810               source: hir::MatchSource,
1811               attrs: ThinAttributes)
1812               -> P<hir::Expr> {
1813     expr(lctx, span, hir::ExprMatch(arg, arms, source), attrs)
1814 }
1815
1816 fn expr_block(lctx: &LoweringContext, b: P<hir::Block>,
1817               attrs: ThinAttributes) -> P<hir::Expr> {
1818     expr(lctx, b.span, hir::ExprBlock(b), attrs)
1819 }
1820
1821 fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: hir::HirVec<P<hir::Expr>>,
1822               attrs: ThinAttributes) -> P<hir::Expr> {
1823     expr(lctx, sp, hir::ExprTup(exprs), attrs)
1824 }
1825
1826 fn expr_struct(lctx: &LoweringContext,
1827                sp: Span,
1828                path: hir::Path,
1829                fields: hir::HirVec<hir::Field>,
1830                e: Option<P<hir::Expr>>,
1831                attrs: ThinAttributes) -> P<hir::Expr> {
1832     expr(lctx, sp, hir::ExprStruct(path, fields, e), attrs)
1833 }
1834
1835 fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_,
1836         attrs: ThinAttributes) -> P<hir::Expr> {
1837     P(hir::Expr {
1838         id: lctx.next_id(),
1839         node: node,
1840         span: span,
1841         attrs: attrs,
1842     })
1843 }
1844
1845 fn stmt_let(lctx: &LoweringContext,
1846             sp: Span,
1847             mutbl: bool,
1848             ident: hir::Ident,
1849             ex: P<hir::Expr>,
1850             attrs: ThinAttributes)
1851             -> hir::Stmt {
1852     let pat = if mutbl {
1853         pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
1854     } else {
1855         pat_ident(lctx, sp, ident)
1856     };
1857     let local = P(hir::Local {
1858         pat: pat,
1859         ty: None,
1860         init: Some(ex),
1861         id: lctx.next_id(),
1862         span: sp,
1863         attrs: attrs,
1864     });
1865     let decl = respan(sp, hir::DeclLocal(local));
1866     respan(sp, hir::StmtDecl(P(decl), lctx.next_id()))
1867 }
1868
1869 fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
1870     block_all(lctx, expr.span, hir::HirVec::new(), Some(expr))
1871 }
1872
1873 fn block_all(lctx: &LoweringContext,
1874              span: Span,
1875              stmts: hir::HirVec<hir::Stmt>,
1876              expr: Option<P<hir::Expr>>)
1877              -> P<hir::Block> {
1878     P(hir::Block {
1879         stmts: stmts,
1880         expr: expr,
1881         id: lctx.next_id(),
1882         rules: hir::DefaultBlock,
1883         span: span,
1884     })
1885 }
1886
1887 fn pat_ok(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1888     let ok = std_path(lctx, &["result", "Result", "Ok"]);
1889     let path = path_global(span, ok);
1890     pat_enum(lctx, span, path, hir_vec![pat])
1891 }
1892
1893 fn pat_err(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1894     let err = std_path(lctx, &["result", "Result", "Err"]);
1895     let path = path_global(span, err);
1896     pat_enum(lctx, span, path, hir_vec![pat])
1897 }
1898
1899 fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1900     let some = std_path(lctx, &["option", "Option", "Some"]);
1901     let path = path_global(span, some);
1902     pat_enum(lctx, span, path, hir_vec![pat])
1903 }
1904
1905 fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1906     let none = std_path(lctx, &["option", "Option", "None"]);
1907     let path = path_global(span, none);
1908     pat_enum(lctx, span, path, hir_vec![])
1909 }
1910
1911 fn pat_enum(lctx: &LoweringContext,
1912             span: Span,
1913             path: hir::Path,
1914             subpats: hir::HirVec<P<hir::Pat>>)
1915             -> P<hir::Pat> {
1916     let pt = if subpats.is_empty() {
1917         hir::PatKind::Path(path)
1918     } else {
1919         hir::PatKind::TupleStruct(path, Some(subpats))
1920     };
1921     pat(lctx, span, pt)
1922 }
1923
1924 fn pat_ident(lctx: &LoweringContext, span: Span, ident: hir::Ident) -> P<hir::Pat> {
1925     pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
1926 }
1927
1928 fn pat_ident_binding_mode(lctx: &LoweringContext,
1929                           span: Span,
1930                           ident: hir::Ident,
1931                           bm: hir::BindingMode)
1932                           -> P<hir::Pat> {
1933     let pat_ident = hir::PatKind::Ident(bm,
1934                                   Spanned {
1935                                       span: span,
1936                                       node: ident,
1937                                   },
1938                                   None);
1939     pat(lctx, span, pat_ident)
1940 }
1941
1942 fn pat_wild(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1943     pat(lctx, span, hir::PatKind::Wild)
1944 }
1945
1946 fn pat(lctx: &LoweringContext, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
1947     P(hir::Pat {
1948         id: lctx.next_id(),
1949         node: pat,
1950         span: span,
1951     })
1952 }
1953
1954 fn path_ident(span: Span, id: hir::Ident) -> hir::Path {
1955     path(span, vec![id])
1956 }
1957
1958 fn path(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1959     path_all(span, false, strs, hir::HirVec::new(), hir::HirVec::new(), hir::HirVec::new())
1960 }
1961
1962 fn path_global(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1963     path_all(span, true, strs, hir::HirVec::new(), hir::HirVec::new(), hir::HirVec::new())
1964 }
1965
1966 fn path_all(sp: Span,
1967             global: bool,
1968             mut idents: Vec<hir::Ident>,
1969             lifetimes: hir::HirVec<hir::Lifetime>,
1970             types: hir::HirVec<P<hir::Ty>>,
1971             bindings: hir::HirVec<hir::TypeBinding>)
1972             -> hir::Path {
1973     let last_identifier = idents.pop().unwrap();
1974     let mut segments: Vec<hir::PathSegment> = idents.into_iter()
1975                                                     .map(|ident| {
1976                                                         hir::PathSegment {
1977                                                             identifier: ident,
1978                                                             parameters: hir::PathParameters::none(),
1979                                                         }
1980                                                     })
1981                                                     .collect();
1982     segments.push(hir::PathSegment {
1983         identifier: last_identifier,
1984         parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1985             lifetimes: lifetimes,
1986             types: types,
1987             bindings: bindings,
1988         }),
1989     });
1990     hir::Path {
1991         span: sp,
1992         global: global,
1993         segments: segments.into(),
1994     }
1995 }
1996
1997 fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<hir::Ident> {
1998     let mut v = Vec::new();
1999     if let Some(s) = lctx.crate_root {
2000         v.push(hir::Ident::from_name(token::intern(s)));
2001     }
2002     v.extend(components.iter().map(|s| hir::Ident::from_name(token::intern(s))));
2003     return v;
2004 }
2005
2006 // Given suffix ["b","c","d"], returns path `::std::b::c::d` when
2007 // `fld.cx.use_std`, and `::core::b::c::d` otherwise.
2008 fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Path {
2009     let idents = std_path(lctx, components);
2010     path_global(span, idents)
2011 }
2012
2013 fn signal_block_expr(lctx: &LoweringContext,
2014                      stmts: hir::HirVec<hir::Stmt>,
2015                      expr: P<hir::Expr>,
2016                      span: Span,
2017                      rule: hir::BlockCheckMode,
2018                      attrs: ThinAttributes)
2019                      -> P<hir::Expr> {
2020     let id = lctx.next_id();
2021     expr_block(lctx,
2022                P(hir::Block {
2023                    rules: rule,
2024                    span: span,
2025                    id: id,
2026                    stmts: stmts,
2027                    expr: Some(expr),
2028                }),
2029                attrs)
2030 }
2031
2032
2033
2034 #[cfg(test)]
2035 mod test {
2036     use super::*;
2037     use syntax::ast::{self, NodeId, NodeIdAssigner};
2038     use syntax::{parse, codemap};
2039     use syntax::fold::Folder;
2040     use std::cell::Cell;
2041
2042     struct MockAssigner {
2043         next_id: Cell<NodeId>,
2044     }
2045
2046     impl MockAssigner {
2047         fn new() -> MockAssigner {
2048             MockAssigner { next_id: Cell::new(0) }
2049         }
2050     }
2051
2052     trait FakeExtCtxt {
2053         fn call_site(&self) -> codemap::Span;
2054         fn cfg(&self) -> ast::CrateConfig;
2055         fn ident_of(&self, st: &str) -> ast::Ident;
2056         fn name_of(&self, st: &str) -> ast::Name;
2057         fn parse_sess(&self) -> &parse::ParseSess;
2058     }
2059
2060     impl FakeExtCtxt for parse::ParseSess {
2061         fn call_site(&self) -> codemap::Span {
2062             codemap::Span {
2063                 lo: codemap::BytePos(0),
2064                 hi: codemap::BytePos(0),
2065                 expn_id: codemap::NO_EXPANSION,
2066             }
2067         }
2068         fn cfg(&self) -> ast::CrateConfig {
2069             Vec::new()
2070         }
2071         fn ident_of(&self, st: &str) -> ast::Ident {
2072             parse::token::str_to_ident(st)
2073         }
2074         fn name_of(&self, st: &str) -> ast::Name {
2075             parse::token::intern(st)
2076         }
2077         fn parse_sess(&self) -> &parse::ParseSess {
2078             self
2079         }
2080     }
2081
2082     impl NodeIdAssigner for MockAssigner {
2083         fn next_node_id(&self) -> NodeId {
2084             let result = self.next_id.get();
2085             self.next_id.set(result + 1);
2086             result
2087         }
2088
2089         fn peek_node_id(&self) -> NodeId {
2090             self.next_id.get()
2091         }
2092     }
2093
2094     impl Folder for MockAssigner {
2095         fn new_id(&mut self, old_id: NodeId) -> NodeId {
2096             assert_eq!(old_id, ast::DUMMY_NODE_ID);
2097             self.next_node_id()
2098         }
2099     }
2100
2101     #[test]
2102     fn test_preserves_ids() {
2103         let cx = parse::ParseSess::new();
2104         let mut assigner = MockAssigner::new();
2105
2106         let ast_if_let = quote_expr!(&cx,
2107                                      if let Some(foo) = baz {
2108                                          bar(foo);
2109                                      });
2110         let ast_if_let = assigner.fold_expr(ast_if_let);
2111         let ast_while_let = quote_expr!(&cx,
2112                                         while let Some(foo) = baz {
2113                                             bar(foo);
2114                                         });
2115         let ast_while_let = assigner.fold_expr(ast_while_let);
2116         let ast_for = quote_expr!(&cx,
2117                                   for i in 0..10 {
2118                                       for j in 0..10 {
2119                                           foo(i, j);
2120                                       }
2121                                   });
2122         let ast_for = assigner.fold_expr(ast_for);
2123         let ast_in = quote_expr!(&cx, in HEAP { foo() });
2124         let ast_in = assigner.fold_expr(ast_in);
2125
2126         let lctx = LoweringContext::new(&assigner, None);
2127         let hir1 = lower_expr(&lctx, &ast_if_let);
2128         let hir2 = lower_expr(&lctx, &ast_if_let);
2129         assert!(hir1 == hir2);
2130
2131         let hir1 = lower_expr(&lctx, &ast_while_let);
2132         let hir2 = lower_expr(&lctx, &ast_while_let);
2133         assert!(hir1 == hir2);
2134
2135         let hir1 = lower_expr(&lctx, &ast_for);
2136         let hir2 = lower_expr(&lctx, &ast_for);
2137         assert!(hir1 == hir2);
2138
2139         let hir1 = lower_expr(&lctx, &ast_in);
2140         let hir2 = lower_expr(&lctx, &ast_in);
2141         assert!(hir1 == hir2);
2142     }
2143 }