]> git.proxmox.com Git - rustc.git/blob - src/librustc_front/lowering.rs
Imported Upstream version 1.7.0+dfsg1
[rustc.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 PathParameters::AngleBracketed(ref data) =>
323 hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(lctx, data)),
324 PathParameters::Parenthesized(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 -> hir::HirVec<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 ExprType(ref expr, ref ty) => {
1132 let expr = lower_expr(lctx, expr);
1133 hir::ExprType(expr, lower_ty(lctx, ty))
1134 }
1135 ExprAddrOf(m, ref ohs) => {
1136 let m = lower_mutability(lctx, m);
1137 let ohs = lower_expr(lctx, ohs);
1138 hir::ExprAddrOf(m, ohs)
1139 }
1140 // More complicated than you might expect because the else branch
1141 // might be `if let`.
1142 ExprIf(ref cond, ref blk, ref else_opt) => {
1143 let else_opt = else_opt.as_ref().map(|els| {
1144 match els.node {
1145 ExprIfLet(..) => {
1146 cache_ids(lctx, e.id, |lctx| {
1147 // wrap the if-let expr in a block
1148 let span = els.span;
1149 let els = lower_expr(lctx, els);
1150 let id = lctx.next_id();
1151 let blk = P(hir::Block {
1152 stmts: hir_vec![],
1153 expr: Some(els),
1154 id: id,
1155 rules: hir::DefaultBlock,
1156 span: span,
1157 });
1158 expr_block(lctx, blk, None)
1159 })
1160 }
1161 _ => lower_expr(lctx, els),
1162 }
1163 });
1164
1165 hir::ExprIf(lower_expr(lctx, cond), lower_block(lctx, blk), else_opt)
1166 }
1167 ExprWhile(ref cond, ref body, opt_ident) => {
1168 hir::ExprWhile(lower_expr(lctx, cond), lower_block(lctx, body),
1169 opt_ident.map(|ident| lower_ident(lctx, ident)))
1170 }
1171 ExprLoop(ref body, opt_ident) => {
1172 hir::ExprLoop(lower_block(lctx, body),
1173 opt_ident.map(|ident| lower_ident(lctx, ident)))
1174 }
1175 ExprMatch(ref expr, ref arms) => {
1176 hir::ExprMatch(lower_expr(lctx, expr),
1177 arms.iter().map(|x| lower_arm(lctx, x)).collect(),
1178 hir::MatchSource::Normal)
1179 }
1180 ExprClosure(capture_clause, ref decl, ref body) => {
1181 hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
1182 lower_fn_decl(lctx, decl),
1183 lower_block(lctx, body))
1184 }
1185 ExprBlock(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
1186 ExprAssign(ref el, ref er) => {
1187 hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
1188 }
1189 ExprAssignOp(op, ref el, ref er) => {
1190 hir::ExprAssignOp(lower_binop(lctx, op),
1191 lower_expr(lctx, el),
1192 lower_expr(lctx, er))
1193 }
1194 ExprField(ref el, ident) => {
1195 hir::ExprField(lower_expr(lctx, el), respan(ident.span, ident.node.name))
1196 }
1197 ExprTupField(ref el, ident) => {
1198 hir::ExprTupField(lower_expr(lctx, el), ident)
1199 }
1200 ExprIndex(ref el, ref er) => {
1201 hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
1202 }
1203 ExprRange(ref e1, ref e2) => {
1204 hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)),
1205 e2.as_ref().map(|x| lower_expr(lctx, x)))
1206 }
1207 ExprPath(ref qself, ref path) => {
1208 let hir_qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
1209 hir::QSelf {
1210 ty: lower_ty(lctx, ty),
1211 position: position,
1212 }
1213 });
1214 hir::ExprPath(hir_qself, lower_path_full(lctx, path, qself.is_none()))
1215 }
1216 ExprBreak(opt_ident) => hir::ExprBreak(opt_ident.map(|sp_ident| {
1217 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1218 })),
1219 ExprAgain(opt_ident) => hir::ExprAgain(opt_ident.map(|sp_ident| {
1220 respan(sp_ident.span, lower_ident(lctx, sp_ident.node))
1221 })),
1222 ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
1223 ExprInlineAsm(InlineAsm {
1224 ref inputs,
1225 ref outputs,
1226 ref asm,
1227 asm_str_style,
1228 ref clobbers,
1229 volatile,
1230 alignstack,
1231 dialect,
1232 expn_id,
1233 }) => hir::ExprInlineAsm(hir::InlineAsm {
1234 inputs: inputs.iter()
1235 .map(|&(ref c, ref input)| (c.clone(), lower_expr(lctx, input)))
1236 .collect(),
1237 outputs: outputs.iter()
1238 .map(|out| {
1239 hir::InlineAsmOutput {
1240 constraint: out.constraint.clone(),
1241 expr: lower_expr(lctx, &out.expr),
1242 is_rw: out.is_rw,
1243 is_indirect: out.is_indirect,
1244 }
1245 })
1246 .collect(),
1247 asm: asm.clone(),
1248 asm_str_style: asm_str_style,
1249 clobbers: clobbers.clone().into(),
1250 volatile: volatile,
1251 alignstack: alignstack,
1252 dialect: dialect,
1253 expn_id: expn_id,
1254 }),
1255 ExprStruct(ref path, ref fields, ref maybe_expr) => {
1256 hir::ExprStruct(lower_path(lctx, path),
1257 fields.iter().map(|x| lower_field(lctx, x)).collect(),
1258 maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
1259 }
1260 ExprParen(ref ex) => {
1261 // merge attributes into the inner expression.
1262 return lower_expr(lctx, ex).map(|mut ex| {
1263 ex.attrs.update(|attrs| {
1264 attrs.prepend(e.attrs.clone())
1265 });
1266 ex
1267 });
1268 }
1269
1270 // Desugar ExprIfLet
1271 // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
1272 ExprIfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
1273 // to:
1274 //
1275 // match <sub_expr> {
1276 // <pat> => <body>,
1277 // [_ if <else_opt_if_cond> => <else_opt_if_body>,]
1278 // _ => [<else_opt> | ()]
1279 // }
1280
1281 return cache_ids(lctx, e.id, |lctx| {
1282 // `<pat> => <body>`
1283 let pat_arm = {
1284 let body = lower_block(lctx, body);
1285 let body_expr = expr_block(lctx, body, None);
1286 arm(hir_vec![lower_pat(lctx, pat)], body_expr)
1287 };
1288
1289 // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
1290 let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e));
1291 let else_if_arms = {
1292 let mut arms = vec![];
1293 loop {
1294 let else_opt_continue = else_opt.and_then(|els| {
1295 els.and_then(|els| {
1296 match els.node {
1297 // else if
1298 hir::ExprIf(cond, then, else_opt) => {
1299 let pat_under = pat_wild(lctx, e.span);
1300 arms.push(hir::Arm {
1301 attrs: hir_vec![],
1302 pats: hir_vec![pat_under],
1303 guard: Some(cond),
1304 body: expr_block(lctx, then, None),
1305 });
1306 else_opt.map(|else_opt| (else_opt, true))
1307 }
1308 _ => Some((P(els), false)),
1309 }
1310 })
1311 });
1312 match else_opt_continue {
1313 Some((e, true)) => {
1314 else_opt = Some(e);
1315 }
1316 Some((e, false)) => {
1317 else_opt = Some(e);
1318 break;
1319 }
1320 None => {
1321 else_opt = None;
1322 break;
1323 }
1324 }
1325 }
1326 arms
1327 };
1328
1329 let contains_else_clause = else_opt.is_some();
1330
1331 // `_ => [<else_opt> | ()]`
1332 let else_arm = {
1333 let pat_under = pat_wild(lctx, e.span);
1334 let else_expr =
1335 else_opt.unwrap_or_else(
1336 || expr_tuple(lctx, e.span, hir_vec![], None));
1337 arm(hir_vec![pat_under], else_expr)
1338 };
1339
1340 let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
1341 arms.push(pat_arm);
1342 arms.extend(else_if_arms);
1343 arms.push(else_arm);
1344
1345 let sub_expr = lower_expr(lctx, sub_expr);
1346 // add attributes to the outer returned expr node
1347 expr(lctx,
1348 e.span,
1349 hir::ExprMatch(sub_expr,
1350 arms.into(),
1351 hir::MatchSource::IfLetDesugar {
1352 contains_else_clause: contains_else_clause,
1353 }),
1354 e.attrs.clone())
1355 });
1356 }
1357
1358 // Desugar ExprWhileLet
1359 // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
1360 ExprWhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
1361 // to:
1362 //
1363 // [opt_ident]: loop {
1364 // match <sub_expr> {
1365 // <pat> => <body>,
1366 // _ => break
1367 // }
1368 // }
1369
1370 return cache_ids(lctx, e.id, |lctx| {
1371 // `<pat> => <body>`
1372 let pat_arm = {
1373 let body = lower_block(lctx, body);
1374 let body_expr = expr_block(lctx, body, None);
1375 arm(hir_vec![lower_pat(lctx, pat)], body_expr)
1376 };
1377
1378 // `_ => break`
1379 let break_arm = {
1380 let pat_under = pat_wild(lctx, e.span);
1381 let break_expr = expr_break(lctx, e.span, None);
1382 arm(hir_vec![pat_under], break_expr)
1383 };
1384
1385 // `match <sub_expr> { ... }`
1386 let arms = hir_vec![pat_arm, break_arm];
1387 let sub_expr = lower_expr(lctx, sub_expr);
1388 let match_expr = expr(lctx,
1389 e.span,
1390 hir::ExprMatch(sub_expr,
1391 arms,
1392 hir::MatchSource::WhileLetDesugar),
1393 None);
1394
1395 // `[opt_ident]: loop { ... }`
1396 let loop_block = block_expr(lctx, match_expr);
1397 let loop_expr = hir::ExprLoop(loop_block,
1398 opt_ident.map(|ident| lower_ident(lctx, ident)));
1399 // add attributes to the outer returned expr node
1400 expr(lctx, e.span, loop_expr, e.attrs.clone())
1401 });
1402 }
1403
1404 // Desugar ExprForLoop
1405 // From: `[opt_ident]: for <pat> in <head> <body>`
1406 ExprForLoop(ref pat, ref head, ref body, opt_ident) => {
1407 // to:
1408 //
1409 // {
1410 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1411 // mut iter => {
1412 // [opt_ident]: loop {
1413 // match ::std::iter::Iterator::next(&mut iter) {
1414 // ::std::option::Option::Some(<pat>) => <body>,
1415 // ::std::option::Option::None => break
1416 // }
1417 // }
1418 // }
1419 // };
1420 // result
1421 // }
1422
1423 return cache_ids(lctx, e.id, |lctx| {
1424 // expand <head>
1425 let head = lower_expr(lctx, head);
1426
1427 let iter = lctx.str_to_ident("iter");
1428
1429 // `::std::option::Option::Some(<pat>) => <body>`
1430 let pat_arm = {
1431 let body_block = lower_block(lctx, body);
1432 let body_span = body_block.span;
1433 let body_expr = P(hir::Expr {
1434 id: lctx.next_id(),
1435 node: hir::ExprBlock(body_block),
1436 span: body_span,
1437 attrs: None,
1438 });
1439 let pat = lower_pat(lctx, pat);
1440 let some_pat = pat_some(lctx, e.span, pat);
1441
1442 arm(hir_vec![some_pat], body_expr)
1443 };
1444
1445 // `::std::option::Option::None => break`
1446 let break_arm = {
1447 let break_expr = expr_break(lctx, e.span, None);
1448
1449 arm(hir_vec![pat_none(lctx, e.span)], break_expr)
1450 };
1451
1452 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1453 let match_expr = {
1454 let next_path = {
1455 let strs = std_path(lctx, &["iter", "Iterator", "next"]);
1456
1457 path_global(e.span, strs)
1458 };
1459 let iter = expr_ident(lctx, e.span, iter, None);
1460 let ref_mut_iter = expr_mut_addr_of(lctx, e.span, iter, None);
1461 let next_path = expr_path(lctx, next_path, None);
1462 let next_expr = expr_call(lctx,
1463 e.span,
1464 next_path,
1465 hir_vec![ref_mut_iter],
1466 None);
1467 let arms = hir_vec![pat_arm, break_arm];
1468
1469 expr(lctx,
1470 e.span,
1471 hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
1472 None)
1473 };
1474
1475 // `[opt_ident]: loop { ... }`
1476 let loop_block = block_expr(lctx, match_expr);
1477 let loop_expr = hir::ExprLoop(loop_block,
1478 opt_ident.map(|ident| lower_ident(lctx, ident)));
1479 let loop_expr = expr(lctx, e.span, loop_expr, None);
1480
1481 // `mut iter => { ... }`
1482 let iter_arm = {
1483 let iter_pat = pat_ident_binding_mode(lctx,
1484 e.span,
1485 iter,
1486 hir::BindByValue(hir::MutMutable));
1487 arm(hir_vec![iter_pat], loop_expr)
1488 };
1489
1490 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1491 let into_iter_expr = {
1492 let into_iter_path = {
1493 let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
1494
1495 path_global(e.span, strs)
1496 };
1497
1498 let into_iter = expr_path(lctx, into_iter_path, None);
1499 expr_call(lctx, e.span, into_iter, hir_vec![head], None)
1500 };
1501
1502 let match_expr = expr_match(lctx,
1503 e.span,
1504 into_iter_expr,
1505 hir_vec![iter_arm],
1506 hir::MatchSource::ForLoopDesugar,
1507 None);
1508
1509 // `{ let _result = ...; _result }`
1510 // underscore prevents an unused_variables lint if the head diverges
1511 let result_ident = lctx.str_to_ident("_result");
1512 let let_stmt = stmt_let(lctx, e.span, false, result_ident, match_expr, None);
1513 let result = expr_ident(lctx, e.span, result_ident, None);
1514 let block = block_all(lctx, e.span, hir_vec![let_stmt], Some(result));
1515 // add the attributes to the outer returned expr node
1516 expr_block(lctx, block, e.attrs.clone())
1517 });
1518 }
1519
1520 ExprMac(_) => panic!("Shouldn't exist here"),
1521 },
1522 span: e.span,
1523 attrs: e.attrs.clone(),
1524 })
1525 }
1526
1527 pub fn lower_stmt(lctx: &LoweringContext, s: &Stmt) -> hir::Stmt {
1528 match s.node {
1529 StmtDecl(ref d, id) => {
1530 Spanned {
1531 node: hir::StmtDecl(lower_decl(lctx, d), id),
1532 span: s.span,
1533 }
1534 }
1535 StmtExpr(ref e, id) => {
1536 Spanned {
1537 node: hir::StmtExpr(lower_expr(lctx, e), id),
1538 span: s.span,
1539 }
1540 }
1541 StmtSemi(ref e, id) => {
1542 Spanned {
1543 node: hir::StmtSemi(lower_expr(lctx, e), id),
1544 span: s.span,
1545 }
1546 }
1547 StmtMac(..) => panic!("Shouldn't exist here"),
1548 }
1549 }
1550
1551 pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureClause) -> hir::CaptureClause {
1552 match c {
1553 CaptureByValue => hir::CaptureByValue,
1554 CaptureByRef => hir::CaptureByRef,
1555 }
1556 }
1557
1558 pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1559 match v {
1560 Public => hir::Public,
1561 Inherited => hir::Inherited,
1562 }
1563 }
1564
1565 pub fn lower_block_check_mode(lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1566 match *b {
1567 DefaultBlock => hir::DefaultBlock,
1568 UnsafeBlock(u) => hir::UnsafeBlock(lower_unsafe_source(lctx, u)),
1569 }
1570 }
1571
1572 pub fn lower_binding_mode(lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1573 match *b {
1574 BindingMode::ByRef(m) => hir::BindByRef(lower_mutability(lctx, m)),
1575 BindingMode::ByValue(m) => hir::BindByValue(lower_mutability(lctx, m)),
1576 }
1577 }
1578
1579 pub fn lower_struct_field_kind(lctx: &LoweringContext,
1580 s: &StructFieldKind)
1581 -> hir::StructFieldKind {
1582 match *s {
1583 NamedField(ident, vis) => hir::NamedField(ident.name, lower_visibility(lctx, vis)),
1584 UnnamedField(vis) => hir::UnnamedField(lower_visibility(lctx, vis)),
1585 }
1586 }
1587
1588 pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1589 match u {
1590 CompilerGenerated => hir::CompilerGenerated,
1591 UserProvided => hir::UserProvided,
1592 }
1593 }
1594
1595 pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1596 match i {
1597 ImplPolarity::Positive => hir::ImplPolarity::Positive,
1598 ImplPolarity::Negative => hir::ImplPolarity::Negative,
1599 }
1600 }
1601
1602 pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
1603 f: TraitBoundModifier)
1604 -> hir::TraitBoundModifier {
1605 match f {
1606 TraitBoundModifier::None => hir::TraitBoundModifier::None,
1607 TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
1608 }
1609 }
1610
1611 // Helper methods for building HIR.
1612
1613 fn arm(pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1614 hir::Arm {
1615 attrs: hir_vec![],
1616 pats: pats,
1617 guard: None,
1618 body: expr,
1619 }
1620 }
1621
1622 fn expr_break(lctx: &LoweringContext, span: Span,
1623 attrs: ThinAttributes) -> P<hir::Expr> {
1624 expr(lctx, span, hir::ExprBreak(None), attrs)
1625 }
1626
1627 fn expr_call(lctx: &LoweringContext,
1628 span: Span,
1629 e: P<hir::Expr>,
1630 args: hir::HirVec<P<hir::Expr>>,
1631 attrs: ThinAttributes)
1632 -> P<hir::Expr> {
1633 expr(lctx, span, hir::ExprCall(e, args), attrs)
1634 }
1635
1636 fn expr_ident(lctx: &LoweringContext, span: Span, id: hir::Ident,
1637 attrs: ThinAttributes) -> P<hir::Expr> {
1638 expr_path(lctx, path_ident(span, id), attrs)
1639 }
1640
1641 fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>,
1642 attrs: ThinAttributes) -> P<hir::Expr> {
1643 expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e), attrs)
1644 }
1645
1646 fn expr_path(lctx: &LoweringContext, path: hir::Path,
1647 attrs: ThinAttributes) -> P<hir::Expr> {
1648 expr(lctx, path.span, hir::ExprPath(None, path), attrs)
1649 }
1650
1651 fn expr_match(lctx: &LoweringContext,
1652 span: Span,
1653 arg: P<hir::Expr>,
1654 arms: hir::HirVec<hir::Arm>,
1655 source: hir::MatchSource,
1656 attrs: ThinAttributes)
1657 -> P<hir::Expr> {
1658 expr(lctx, span, hir::ExprMatch(arg, arms, source), attrs)
1659 }
1660
1661 fn expr_block(lctx: &LoweringContext, b: P<hir::Block>,
1662 attrs: ThinAttributes) -> P<hir::Expr> {
1663 expr(lctx, b.span, hir::ExprBlock(b), attrs)
1664 }
1665
1666 fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: hir::HirVec<P<hir::Expr>>,
1667 attrs: ThinAttributes) -> P<hir::Expr> {
1668 expr(lctx, sp, hir::ExprTup(exprs), attrs)
1669 }
1670
1671 fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_,
1672 attrs: ThinAttributes) -> P<hir::Expr> {
1673 P(hir::Expr {
1674 id: lctx.next_id(),
1675 node: node,
1676 span: span,
1677 attrs: attrs,
1678 })
1679 }
1680
1681 fn stmt_let(lctx: &LoweringContext,
1682 sp: Span,
1683 mutbl: bool,
1684 ident: hir::Ident,
1685 ex: P<hir::Expr>,
1686 attrs: ThinAttributes)
1687 -> hir::Stmt {
1688 let pat = if mutbl {
1689 pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
1690 } else {
1691 pat_ident(lctx, sp, ident)
1692 };
1693 let local = P(hir::Local {
1694 pat: pat,
1695 ty: None,
1696 init: Some(ex),
1697 id: lctx.next_id(),
1698 span: sp,
1699 attrs: attrs,
1700 });
1701 let decl = respan(sp, hir::DeclLocal(local));
1702 respan(sp, hir::StmtDecl(P(decl), lctx.next_id()))
1703 }
1704
1705 fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
1706 block_all(lctx, expr.span, hir::HirVec::new(), Some(expr))
1707 }
1708
1709 fn block_all(lctx: &LoweringContext,
1710 span: Span,
1711 stmts: hir::HirVec<hir::Stmt>,
1712 expr: Option<P<hir::Expr>>)
1713 -> P<hir::Block> {
1714 P(hir::Block {
1715 stmts: stmts,
1716 expr: expr,
1717 id: lctx.next_id(),
1718 rules: hir::DefaultBlock,
1719 span: span,
1720 })
1721 }
1722
1723 fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
1724 let some = std_path(lctx, &["option", "Option", "Some"]);
1725 let path = path_global(span, some);
1726 pat_enum(lctx, span, path, hir_vec![pat])
1727 }
1728
1729 fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1730 let none = std_path(lctx, &["option", "Option", "None"]);
1731 let path = path_global(span, none);
1732 pat_enum(lctx, span, path, hir_vec![])
1733 }
1734
1735 fn pat_enum(lctx: &LoweringContext,
1736 span: Span,
1737 path: hir::Path,
1738 subpats: hir::HirVec<P<hir::Pat>>)
1739 -> P<hir::Pat> {
1740 let pt = hir::PatEnum(path, Some(subpats));
1741 pat(lctx, span, pt)
1742 }
1743
1744 fn pat_ident(lctx: &LoweringContext, span: Span, ident: hir::Ident) -> P<hir::Pat> {
1745 pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
1746 }
1747
1748 fn pat_ident_binding_mode(lctx: &LoweringContext,
1749 span: Span,
1750 ident: hir::Ident,
1751 bm: hir::BindingMode)
1752 -> P<hir::Pat> {
1753 let pat_ident = hir::PatIdent(bm,
1754 Spanned {
1755 span: span,
1756 node: ident,
1757 },
1758 None);
1759 pat(lctx, span, pat_ident)
1760 }
1761
1762 fn pat_wild(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
1763 pat(lctx, span, hir::PatWild)
1764 }
1765
1766 fn pat(lctx: &LoweringContext, span: Span, pat: hir::Pat_) -> P<hir::Pat> {
1767 P(hir::Pat {
1768 id: lctx.next_id(),
1769 node: pat,
1770 span: span,
1771 })
1772 }
1773
1774 fn path_ident(span: Span, id: hir::Ident) -> hir::Path {
1775 path(span, vec![id])
1776 }
1777
1778 fn path(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1779 path_all(span, false, strs, hir::HirVec::new(), hir::HirVec::new(), hir::HirVec::new())
1780 }
1781
1782 fn path_global(span: Span, strs: Vec<hir::Ident>) -> hir::Path {
1783 path_all(span, true, strs, hir::HirVec::new(), hir::HirVec::new(), hir::HirVec::new())
1784 }
1785
1786 fn path_all(sp: Span,
1787 global: bool,
1788 mut idents: Vec<hir::Ident>,
1789 lifetimes: hir::HirVec<hir::Lifetime>,
1790 types: hir::HirVec<P<hir::Ty>>,
1791 bindings: hir::HirVec<hir::TypeBinding>)
1792 -> hir::Path {
1793 let last_identifier = idents.pop().unwrap();
1794 let mut segments: Vec<hir::PathSegment> = idents.into_iter()
1795 .map(|ident| {
1796 hir::PathSegment {
1797 identifier: ident,
1798 parameters: hir::PathParameters::none(),
1799 }
1800 })
1801 .collect();
1802 segments.push(hir::PathSegment {
1803 identifier: last_identifier,
1804 parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
1805 lifetimes: lifetimes,
1806 types: types,
1807 bindings: bindings,
1808 }),
1809 });
1810 hir::Path {
1811 span: sp,
1812 global: global,
1813 segments: segments.into(),
1814 }
1815 }
1816
1817 fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<hir::Ident> {
1818 let mut v = Vec::new();
1819 if let Some(s) = lctx.crate_root {
1820 v.push(hir::Ident::from_name(token::intern(s)));
1821 }
1822 v.extend(components.iter().map(|s| hir::Ident::from_name(token::intern(s))));
1823 return v;
1824 }
1825
1826 // Given suffix ["b","c","d"], returns path `::std::b::c::d` when
1827 // `fld.cx.use_std`, and `::core::b::c::d` otherwise.
1828 fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Path {
1829 let idents = std_path(lctx, components);
1830 path_global(span, idents)
1831 }
1832
1833 fn signal_block_expr(lctx: &LoweringContext,
1834 stmts: hir::HirVec<hir::Stmt>,
1835 expr: P<hir::Expr>,
1836 span: Span,
1837 rule: hir::BlockCheckMode,
1838 attrs: ThinAttributes)
1839 -> P<hir::Expr> {
1840 let id = lctx.next_id();
1841 expr_block(lctx,
1842 P(hir::Block {
1843 rules: rule,
1844 span: span,
1845 id: id,
1846 stmts: stmts,
1847 expr: Some(expr),
1848 }),
1849 attrs)
1850 }
1851
1852
1853
1854 #[cfg(test)]
1855 mod test {
1856 use super::*;
1857 use syntax::ast::{self, NodeId, NodeIdAssigner};
1858 use syntax::{parse, codemap};
1859 use syntax::fold::Folder;
1860 use std::cell::Cell;
1861
1862 struct MockAssigner {
1863 next_id: Cell<NodeId>,
1864 }
1865
1866 impl MockAssigner {
1867 fn new() -> MockAssigner {
1868 MockAssigner { next_id: Cell::new(0) }
1869 }
1870 }
1871
1872 trait FakeExtCtxt {
1873 fn call_site(&self) -> codemap::Span;
1874 fn cfg(&self) -> ast::CrateConfig;
1875 fn ident_of(&self, st: &str) -> ast::Ident;
1876 fn name_of(&self, st: &str) -> ast::Name;
1877 fn parse_sess(&self) -> &parse::ParseSess;
1878 }
1879
1880 impl FakeExtCtxt for parse::ParseSess {
1881 fn call_site(&self) -> codemap::Span {
1882 codemap::Span {
1883 lo: codemap::BytePos(0),
1884 hi: codemap::BytePos(0),
1885 expn_id: codemap::NO_EXPANSION,
1886 }
1887 }
1888 fn cfg(&self) -> ast::CrateConfig {
1889 Vec::new()
1890 }
1891 fn ident_of(&self, st: &str) -> ast::Ident {
1892 parse::token::str_to_ident(st)
1893 }
1894 fn name_of(&self, st: &str) -> ast::Name {
1895 parse::token::intern(st)
1896 }
1897 fn parse_sess(&self) -> &parse::ParseSess {
1898 self
1899 }
1900 }
1901
1902 impl NodeIdAssigner for MockAssigner {
1903 fn next_node_id(&self) -> NodeId {
1904 let result = self.next_id.get();
1905 self.next_id.set(result + 1);
1906 result
1907 }
1908
1909 fn peek_node_id(&self) -> NodeId {
1910 self.next_id.get()
1911 }
1912 }
1913
1914 impl Folder for MockAssigner {
1915 fn new_id(&mut self, old_id: NodeId) -> NodeId {
1916 assert_eq!(old_id, ast::DUMMY_NODE_ID);
1917 self.next_node_id()
1918 }
1919 }
1920
1921 #[test]
1922 fn test_preserves_ids() {
1923 let cx = parse::ParseSess::new();
1924 let mut assigner = MockAssigner::new();
1925
1926 let ast_if_let = quote_expr!(&cx,
1927 if let Some(foo) = baz {
1928 bar(foo);
1929 });
1930 let ast_if_let = assigner.fold_expr(ast_if_let);
1931 let ast_while_let = quote_expr!(&cx,
1932 while let Some(foo) = baz {
1933 bar(foo);
1934 });
1935 let ast_while_let = assigner.fold_expr(ast_while_let);
1936 let ast_for = quote_expr!(&cx,
1937 for i in 0..10 {
1938 foo(i);
1939 });
1940 let ast_for = assigner.fold_expr(ast_for);
1941 let ast_in = quote_expr!(&cx, in HEAP { foo() });
1942 let ast_in = assigner.fold_expr(ast_in);
1943
1944 let lctx = LoweringContext::new(&assigner, None);
1945 let hir1 = lower_expr(&lctx, &ast_if_let);
1946 let hir2 = lower_expr(&lctx, &ast_if_let);
1947 assert!(hir1 == hir2);
1948
1949 let hir1 = lower_expr(&lctx, &ast_while_let);
1950 let hir2 = lower_expr(&lctx, &ast_while_let);
1951 assert!(hir1 == hir2);
1952
1953 let hir1 = lower_expr(&lctx, &ast_for);
1954 let hir2 = lower_expr(&lctx, &ast_for);
1955 assert!(hir1 == hir2);
1956
1957 let hir1 = lower_expr(&lctx, &ast_in);
1958 let hir2 = lower_expr(&lctx, &ast_in);
1959 assert!(hir1 == hir2);
1960 }
1961 }