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