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