lowering.rs 70.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

N
Nick Cameron 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Lowers the AST to the HIR.
//
// Since the AST and HIR are fairly similar, this is mostly a simple procedure,
// much like a fold. Where lowering involves a bit more work things get more
// interesting and there are some invariants you should know about. These mostly
// concern spans and ids.
//
// Spans are assigned to AST nodes during parsing and then are modified during
// expansion to indicate the origin of a node and the process it went through
// being expanded. Ids are assigned to AST nodes just before lowering.
//
// For the simpler lowering steps, ids and spans should be preserved. Unlike
// expansion we do not preserve the process of lowering in the spans, so spans
// should not be modified here. When creating a new node (as opposed to
// 'folding' an existing one), then you create a new id using `next_id()`.
//
// You must ensure that ids are unique. That means that you should only use the
N
Nick Cameron 已提交
28
// id from an AST node in a single HIR node (you can assume that AST node ids
N
Nick Cameron 已提交
29
// are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
N
Nick Cameron 已提交
30
// If you do, you must then set the new node's id to a fresh one.
N
Nick Cameron 已提交
31 32 33
//
// Lowering must be reproducable (the compiler only lowers once, but tools and
// custom lints may lower an AST node to a HIR node to interact with the
N
Nick Cameron 已提交
34
// compiler). The most interesting bit of this is ids - if you lower an AST node
N
Nick Cameron 已提交
35 36 37 38 39 40 41 42 43 44 45 46
// and create new HIR nodes with fresh ids, when re-lowering the same node, you
// must ensure you get the same ids! To do this, we keep track of the next id
// when we translate a node which requires new ids. By checking this cache and
// using node ids starting with the cached id, we ensure ids are reproducible.
// To use this system, you just need to hold on to a CachedIdSetter object
// whilst lowering. This is an RAII object that takes care of setting and
// restoring the cached id, etc.
//
// This whole system relies on node ids being incremented one at a time and
// all increments being for lowering. This means that you should not call any
// non-lowering function which will use new node ids.
//
N
Nick Cameron 已提交
47 48 49 50 51 52
// We must also cache gensym'ed Idents to ensure that we get the same Ident
// every time we lower a node with gensym'ed names. One consequence of this is
// that you can only gensym a name once in a lowering (you don't need to worry
// about nested lowering though). That's because we cache based on the name and
// the currently cached node id, which is unique per lowered node.
//
N
Nick Cameron 已提交
53 54 55 56 57 58 59 60 61 62
// Spans are used for error messages and for tools to map semantics back to
// source code. It is therefore not as important with spans as ids to be strict
// about use (you can't break the compiler by screwing up a span). Obviously, a
// HIR node can only have a single span. But multiple nodes can have the same
// span and spans don't need to be kept in order, etc. Where code is preserved
// by lowering, it should have the same span as in the AST. Where HIR nodes are
// new it is probably best to give a span for the whole AST node being lowered.
// All nodes should have real spans, don't use dummy spans. Tools are likely to
// get confused if the spans from leaf AST nodes occur in multiple places
// in the HIR, especially for multiple identifiers.
63 64 65

use hir;

N
Nick Cameron 已提交
66 67
use std::collections::HashMap;

68 69
use syntax::ast::*;
use syntax::ptr::P;
70
use syntax::codemap::{respan, Spanned, Span};
71
use syntax::owned_slice::OwnedSlice;
72 73
use syntax::parse::token::{self, str_to_ident};
use syntax::std_inject;
74

N
Nick Cameron 已提交
75 76 77
use std::cell::{Cell, RefCell};

pub struct LoweringContext<'a> {
78
    crate_root: Option<&'static str>,
N
Nick Cameron 已提交
79
    // Map AST ids to ids used for expanded nodes.
N
Nick Cameron 已提交
80
    id_cache: RefCell<HashMap<NodeId, NodeId>>,
N
Nick Cameron 已提交
81
    // Use if there are no cached ids for the current node.
N
Nick Cameron 已提交
82
    id_assigner: &'a NodeIdAssigner,
N
Nick Cameron 已提交
83 84
    // 0 == no cached id. Must be incremented to align with previous id
    // incrementing.
N
Nick Cameron 已提交
85
    cached_id: Cell<u32>,
N
Nick Cameron 已提交
86 87 88 89
    // Keep track of gensym'ed idents.
    gensym_cache: RefCell<HashMap<(NodeId, &'static str), Ident>>,
    // A copy of cached_id, but is also set to an id while it is being cached.
    gensym_key: Cell<u32>,
N
Nick Cameron 已提交
90 91
}

N
Nick Cameron 已提交
92
impl<'a, 'hir> LoweringContext<'a> {
N
Nick Cameron 已提交
93 94 95 96 97 98 99 100 101 102
    pub fn new(id_assigner: &'a NodeIdAssigner, c: Option<&Crate>) -> LoweringContext<'a> {
        let crate_root = c.and_then(|c| {
            if std_inject::no_core(c) {
                None
            } else if std_inject::no_std(c) {
                Some("core")
            } else {
                Some("std")
            }
        });
103

N
Nick Cameron 已提交
104
        LoweringContext {
105
            crate_root: crate_root,
N
Nick Cameron 已提交
106 107 108
            id_cache: RefCell::new(HashMap::new()),
            id_assigner: id_assigner,
            cached_id: Cell::new(0),
N
Nick Cameron 已提交
109 110
            gensym_cache: RefCell::new(HashMap::new()),
            gensym_key: Cell::new(0),
N
Nick Cameron 已提交
111 112
        }
    }
113 114

    fn next_id(&self) -> NodeId {
N
Nick Cameron 已提交
115 116 117 118 119 120 121
        let cached = self.cached_id.get();
        if cached == 0 {
            return self.id_assigner.next_node_id()
        }

        self.cached_id.set(cached + 1);
        cached
122
    }
N
Nick Cameron 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

    fn str_to_ident(&self, s: &'static str) -> Ident {
        let cached_id = self.gensym_key.get();
        if cached_id == 0 {
            return token::gensym_ident(s);
        }

        let cached = self.gensym_cache.borrow().contains_key(&(cached_id, s));
        if cached {
            self.gensym_cache.borrow()[&(cached_id, s)]
        } else {
            let result = token::gensym_ident(s);
            self.gensym_cache.borrow_mut().insert((cached_id, s), result);
            result
        }
    }
N
Nick Cameron 已提交
139
}
140

N
Nick Cameron 已提交
141
pub fn lower_view_path(_lctx: &LoweringContext, view_path: &ViewPath) -> P<hir::ViewPath> {
142 143 144
    P(Spanned {
        node: match view_path.node {
            ViewPathSimple(ident, ref path) => {
N
Nick Cameron 已提交
145
                hir::ViewPathSimple(ident.name, lower_path(_lctx, path))
146 147
            }
            ViewPathGlob(ref path) => {
N
Nick Cameron 已提交
148
                hir::ViewPathGlob(lower_path(_lctx, path))
149 150
            }
            ViewPathList(ref path, ref path_list_idents) => {
N
Nick Cameron 已提交
151
                hir::ViewPathList(lower_path(_lctx, path),
N
Nick Cameron 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
                                  path_list_idents.iter()
                                                  .map(|path_list_ident| {
                                                      Spanned {
                                                          node: match path_list_ident.node {
                                                              PathListIdent { id, name, rename } =>
                                                                  hir::PathListIdent {
                                                                  id: id,
                                                                  name: name.name,
                                                                  rename: rename.map(|x| x.name),
                                                              },
                                                              PathListMod { id, rename } =>
                                                                  hir::PathListMod {
                                                                  id: id,
                                                                  rename: rename.map(|x| x.name),
                                                              },
                                                          },
                                                          span: path_list_ident.span,
                                                      }
                                                  })
                                                  .collect())
172 173 174 175 176 177
            }
        },
        span: view_path.span,
    })
}

N
Nick Cameron 已提交
178
pub fn lower_arm(_lctx: &LoweringContext, arm: &Arm) -> hir::Arm {
179
    hir::Arm {
180
        attrs: arm.attrs.clone(),
N
Nick Cameron 已提交
181 182 183
        pats: arm.pats.iter().map(|x| lower_pat(_lctx, x)).collect(),
        guard: arm.guard.as_ref().map(|ref x| lower_expr(_lctx, x)),
        body: lower_expr(_lctx, &arm.body),
184 185 186
    }
}

N
Nick Cameron 已提交
187
pub fn lower_decl(_lctx: &LoweringContext, d: &Decl) -> P<hir::Decl> {
188 189
    match d.node {
        DeclLocal(ref l) => P(Spanned {
N
Nick Cameron 已提交
190
            node: hir::DeclLocal(lower_local(_lctx, l)),
N
Nick Cameron 已提交
191
            span: d.span,
192 193
        }),
        DeclItem(ref it) => P(Spanned {
N
Nick Cameron 已提交
194
            node: hir::DeclItem(lower_item(_lctx, it)),
N
Nick Cameron 已提交
195
            span: d.span,
196 197 198 199
        }),
    }
}

N
Nick Cameron 已提交
200
pub fn lower_ty_binding(_lctx: &LoweringContext, b: &TypeBinding) -> P<hir::TypeBinding> {
N
Nick Cameron 已提交
201 202 203 204 205 206
    P(hir::TypeBinding {
        id: b.id,
        name: b.ident.name,
        ty: lower_ty(_lctx, &b.ty),
        span: b.span,
    })
207 208
}

N
Nick Cameron 已提交
209
pub fn lower_ty(_lctx: &LoweringContext, t: &Ty) -> P<hir::Ty> {
210 211 212 213
    P(hir::Ty {
        id: t.id,
        node: match t.node {
            TyInfer => hir::TyInfer,
N
Nick Cameron 已提交
214 215
            TyVec(ref ty) => hir::TyVec(lower_ty(_lctx, ty)),
            TyPtr(ref mt) => hir::TyPtr(lower_mt(_lctx, mt)),
216
            TyRptr(ref region, ref mt) => {
N
Nick Cameron 已提交
217 218
                hir::TyRptr(lower_opt_lifetime(_lctx, region),
                            lower_mt(_lctx, mt))
219 220 221
            }
            TyBareFn(ref f) => {
                hir::TyBareFn(P(hir::BareFnTy {
N
Nick Cameron 已提交
222 223
                    lifetimes: lower_lifetime_defs(_lctx, &f.lifetimes),
                    unsafety: lower_unsafety(_lctx, f.unsafety),
224
                    abi: f.abi,
N
Nick Cameron 已提交
225
                    decl: lower_fn_decl(_lctx, &f.decl),
226 227
                }))
            }
N
Nick Cameron 已提交
228 229
            TyTup(ref tys) => hir::TyTup(tys.iter().map(|ty| lower_ty(_lctx, ty)).collect()),
            TyParen(ref ty) => hir::TyParen(lower_ty(_lctx, ty)),
230 231 232
            TyPath(ref qself, ref path) => {
                let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
                    hir::QSelf {
N
Nick Cameron 已提交
233
                        ty: lower_ty(_lctx, ty),
N
Nick Cameron 已提交
234
                        position: position,
235 236
                    }
                });
N
Nick Cameron 已提交
237
                hir::TyPath(qself, lower_path(_lctx, path))
238 239
            }
            TyObjectSum(ref ty, ref bounds) => {
N
Nick Cameron 已提交
240
                hir::TyObjectSum(lower_ty(_lctx, ty), lower_bounds(_lctx, bounds))
241 242
            }
            TyFixedLengthVec(ref ty, ref e) => {
N
Nick Cameron 已提交
243
                hir::TyFixedLengthVec(lower_ty(_lctx, ty), lower_expr(_lctx, e))
244 245
            }
            TyTypeof(ref expr) => {
N
Nick Cameron 已提交
246
                hir::TyTypeof(lower_expr(_lctx, expr))
247 248
            }
            TyPolyTraitRef(ref bounds) => {
N
Nick Cameron 已提交
249
                hir::TyPolyTraitRef(bounds.iter().map(|b| lower_ty_param_bound(_lctx, b)).collect())
250 251 252 253 254 255 256
            }
            TyMac(_) => panic!("TyMac should have been expanded by now."),
        },
        span: t.span,
    })
}

N
Nick Cameron 已提交
257
pub fn lower_foreign_mod(_lctx: &LoweringContext, fm: &ForeignMod) -> hir::ForeignMod {
258 259
    hir::ForeignMod {
        abi: fm.abi,
N
Nick Cameron 已提交
260
        items: fm.items.iter().map(|x| lower_foreign_item(_lctx, x)).collect(),
261 262 263
    }
}

N
Nick Cameron 已提交
264
pub fn lower_variant(_lctx: &LoweringContext, v: &Variant) -> P<hir::Variant> {
265 266
    P(Spanned {
        node: hir::Variant_ {
267
            name: v.node.name.name,
268
            attrs: v.node.attrs.clone(),
269
            data: lower_struct_def(_lctx, &v.node.data),
270
            disr_expr: v.node.disr_expr.as_ref().map(|e| lower_expr(e)),
271 272 273 274 275
        },
        span: v.span,
    })
}

N
Nick Cameron 已提交
276
pub fn lower_path(_lctx: &LoweringContext, p: &Path) -> hir::Path {
277 278
    hir::Path {
        global: p.global,
N
Nick Cameron 已提交
279 280 281 282 283 284 285 286 287
        segments: p.segments
                   .iter()
                   .map(|&PathSegment { identifier, ref parameters }| {
                       hir::PathSegment {
                           identifier: identifier,
                           parameters: lower_path_parameters(_lctx, parameters),
                       }
                   })
                   .collect(),
288 289 290 291
        span: p.span,
    }
}

N
Nick Cameron 已提交
292 293 294
pub fn lower_path_parameters(_lctx: &LoweringContext,
                             path_parameters: &PathParameters)
                             -> hir::PathParameters {
295 296
    match *path_parameters {
        AngleBracketedParameters(ref data) =>
N
Nick Cameron 已提交
297
            hir::AngleBracketedParameters(lower_angle_bracketed_parameter_data(_lctx, data)),
298
        ParenthesizedParameters(ref data) =>
N
Nick Cameron 已提交
299
            hir::ParenthesizedParameters(lower_parenthesized_parameter_data(_lctx, data)),
300 301 302
    }
}

N
Nick Cameron 已提交
303 304
pub fn lower_angle_bracketed_parameter_data(_lctx: &LoweringContext,
                                            data: &AngleBracketedParameterData)
305 306 307
                                            -> hir::AngleBracketedParameterData {
    let &AngleBracketedParameterData { ref lifetimes, ref types, ref bindings } = data;
    hir::AngleBracketedParameterData {
N
Nick Cameron 已提交
308 309 310
        lifetimes: lower_lifetimes(_lctx, lifetimes),
        types: types.iter().map(|ty| lower_ty(_lctx, ty)).collect(),
        bindings: bindings.iter().map(|b| lower_ty_binding(_lctx, b)).collect(),
311 312 313
    }
}

N
Nick Cameron 已提交
314 315
pub fn lower_parenthesized_parameter_data(_lctx: &LoweringContext,
                                          data: &ParenthesizedParameterData)
316 317 318
                                          -> hir::ParenthesizedParameterData {
    let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
    hir::ParenthesizedParameterData {
N
Nick Cameron 已提交
319 320
        inputs: inputs.iter().map(|ty| lower_ty(_lctx, ty)).collect(),
        output: output.as_ref().map(|ty| lower_ty(_lctx, ty)),
321 322 323 324
        span: span,
    }
}

N
Nick Cameron 已提交
325
pub fn lower_local(_lctx: &LoweringContext, l: &Local) -> P<hir::Local> {
326
    P(hir::Local {
N
Nick Cameron 已提交
327 328 329 330 331 332
        id: l.id,
        ty: l.ty.as_ref().map(|t| lower_ty(_lctx, t)),
        pat: lower_pat(_lctx, &l.pat),
        init: l.init.as_ref().map(|e| lower_expr(_lctx, e)),
        span: l.span,
    })
333 334
}

N
Nick Cameron 已提交
335 336 337
pub fn lower_explicit_self_underscore(_lctx: &LoweringContext,
                                      es: &ExplicitSelf_)
                                      -> hir::ExplicitSelf_ {
338 339
    match *es {
        SelfStatic => hir::SelfStatic,
340
        SelfValue(v) => hir::SelfValue(v.name),
341
        SelfRegion(ref lifetime, m, ident) => {
N
Nick Cameron 已提交
342 343
            hir::SelfRegion(lower_opt_lifetime(_lctx, lifetime),
                            lower_mutability(_lctx, m),
N
Nick Cameron 已提交
344
                            ident.name)
345 346
        }
        SelfExplicit(ref typ, ident) => {
N
Nick Cameron 已提交
347
            hir::SelfExplicit(lower_ty(_lctx, typ), ident.name)
348 349 350 351
        }
    }
}

N
Nick Cameron 已提交
352
pub fn lower_mutability(_lctx: &LoweringContext, m: Mutability) -> hir::Mutability {
353 354 355 356 357 358
    match m {
        MutMutable => hir::MutMutable,
        MutImmutable => hir::MutImmutable,
    }
}

N
Nick Cameron 已提交
359
pub fn lower_explicit_self(_lctx: &LoweringContext, s: &ExplicitSelf) -> hir::ExplicitSelf {
N
Nick Cameron 已提交
360 361 362 363
    Spanned {
        node: lower_explicit_self_underscore(_lctx, &s.node),
        span: s.span,
    }
364 365
}

N
Nick Cameron 已提交
366
pub fn lower_arg(_lctx: &LoweringContext, arg: &Arg) -> hir::Arg {
N
Nick Cameron 已提交
367 368 369 370 371
    hir::Arg {
        id: arg.id,
        pat: lower_pat(_lctx, &arg.pat),
        ty: lower_ty(_lctx, &arg.ty),
    }
372 373
}

N
Nick Cameron 已提交
374
pub fn lower_fn_decl(_lctx: &LoweringContext, decl: &FnDecl) -> P<hir::FnDecl> {
375
    P(hir::FnDecl {
N
Nick Cameron 已提交
376
        inputs: decl.inputs.iter().map(|x| lower_arg(_lctx, x)).collect(),
377
        output: match decl.output {
N
Nick Cameron 已提交
378
            Return(ref ty) => hir::Return(lower_ty(_lctx, ty)),
379
            DefaultReturn(span) => hir::DefaultReturn(span),
N
Nick Cameron 已提交
380
            NoReturn(span) => hir::NoReturn(span),
381 382 383 384 385
        },
        variadic: decl.variadic,
    })
}

N
Nick Cameron 已提交
386
pub fn lower_ty_param_bound(_lctx: &LoweringContext, tpb: &TyParamBound) -> hir::TyParamBound {
387 388
    match *tpb {
        TraitTyParamBound(ref ty, modifier) => {
N
Nick Cameron 已提交
389 390 391 392 393
            hir::TraitTyParamBound(lower_poly_trait_ref(_lctx, ty),
                                   lower_trait_bound_modifier(_lctx, modifier))
        }
        RegionTyParamBound(ref lifetime) => {
            hir::RegionTyParamBound(lower_lifetime(_lctx, lifetime))
394 395 396 397
        }
    }
}

N
Nick Cameron 已提交
398
pub fn lower_ty_param(_lctx: &LoweringContext, tp: &TyParam) -> hir::TyParam {
399 400
    hir::TyParam {
        id: tp.id,
401
        name: tp.ident.name,
N
Nick Cameron 已提交
402 403
        bounds: lower_bounds(_lctx, &tp.bounds),
        default: tp.default.as_ref().map(|x| lower_ty(_lctx, x)),
404 405 406 407
        span: tp.span,
    }
}

N
Nick Cameron 已提交
408 409 410 411
pub fn lower_ty_params(_lctx: &LoweringContext,
                       tps: &OwnedSlice<TyParam>)
                       -> OwnedSlice<hir::TyParam> {
    tps.iter().map(|tp| lower_ty_param(_lctx, tp)).collect()
412 413
}

N
Nick Cameron 已提交
414
pub fn lower_lifetime(_lctx: &LoweringContext, l: &Lifetime) -> hir::Lifetime {
N
Nick Cameron 已提交
415 416 417 418 419
    hir::Lifetime {
        id: l.id,
        name: l.name,
        span: l.span,
    }
420 421
}

N
Nick Cameron 已提交
422
pub fn lower_lifetime_def(_lctx: &LoweringContext, l: &LifetimeDef) -> hir::LifetimeDef {
N
Nick Cameron 已提交
423
    hir::LifetimeDef {
N
Nick Cameron 已提交
424
        lifetime: lower_lifetime(_lctx, &l.lifetime),
N
Nick Cameron 已提交
425
        bounds: lower_lifetimes(_lctx, &l.bounds),
N
Nick Cameron 已提交
426
    }
427 428
}

N
Nick Cameron 已提交
429 430
pub fn lower_lifetimes(_lctx: &LoweringContext, lts: &Vec<Lifetime>) -> Vec<hir::Lifetime> {
    lts.iter().map(|l| lower_lifetime(_lctx, l)).collect()
431 432
}

N
Nick Cameron 已提交
433 434 435 436
pub fn lower_lifetime_defs(_lctx: &LoweringContext,
                           lts: &Vec<LifetimeDef>)
                           -> Vec<hir::LifetimeDef> {
    lts.iter().map(|l| lower_lifetime_def(_lctx, l)).collect()
437 438
}

N
Nick Cameron 已提交
439 440 441 442
pub fn lower_opt_lifetime(_lctx: &LoweringContext,
                          o_lt: &Option<Lifetime>)
                          -> Option<hir::Lifetime> {
    o_lt.as_ref().map(|lt| lower_lifetime(_lctx, lt))
443 444
}

N
Nick Cameron 已提交
445
pub fn lower_generics(_lctx: &LoweringContext, g: &Generics) -> hir::Generics {
446
    hir::Generics {
N
Nick Cameron 已提交
447 448 449
        ty_params: lower_ty_params(_lctx, &g.ty_params),
        lifetimes: lower_lifetime_defs(_lctx, &g.lifetimes),
        where_clause: lower_where_clause(_lctx, &g.where_clause),
450 451 452
    }
}

N
Nick Cameron 已提交
453
pub fn lower_where_clause(_lctx: &LoweringContext, wc: &WhereClause) -> hir::WhereClause {
454 455
    hir::WhereClause {
        id: wc.id,
N
Nick Cameron 已提交
456 457 458 459
        predicates: wc.predicates
                      .iter()
                      .map(|predicate| lower_where_predicate(_lctx, predicate))
                      .collect(),
460 461 462
    }
}

N
Nick Cameron 已提交
463 464 465
pub fn lower_where_predicate(_lctx: &LoweringContext,
                             pred: &WherePredicate)
                             -> hir::WherePredicate {
466 467 468 469 470 471
    match *pred {
        WherePredicate::BoundPredicate(WhereBoundPredicate{ ref bound_lifetimes,
                                                            ref bounded_ty,
                                                            ref bounds,
                                                            span}) => {
            hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
N
Nick Cameron 已提交
472 473 474
                bound_lifetimes: lower_lifetime_defs(_lctx, bound_lifetimes),
                bounded_ty: lower_ty(_lctx, bounded_ty),
                bounds: bounds.iter().map(|x| lower_ty_param_bound(_lctx, x)).collect(),
N
Nick Cameron 已提交
475
                span: span,
476 477 478 479 480 481 482
            })
        }
        WherePredicate::RegionPredicate(WhereRegionPredicate{ ref lifetime,
                                                              ref bounds,
                                                              span}) => {
            hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
                span: span,
N
Nick Cameron 已提交
483
                lifetime: lower_lifetime(_lctx, lifetime),
N
Nick Cameron 已提交
484
                bounds: bounds.iter().map(|bound| lower_lifetime(_lctx, bound)).collect(),
485 486 487 488 489 490
            })
        }
        WherePredicate::EqPredicate(WhereEqPredicate{ id,
                                                      ref path,
                                                      ref ty,
                                                      span}) => {
N
Nick Cameron 已提交
491
            hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
492
                id: id,
N
Nick Cameron 已提交
493
                path: lower_path(_lctx, path),
N
Nick Cameron 已提交
494 495
                ty: lower_ty(_lctx, ty),
                span: span,
496 497 498 499 500
            })
        }
    }
}

501 502
pub fn lower_struct_def(sd: &VariantData) -> P<hir::VariantData> {
    P(hir::VariantData {
503
        id: sd.id,
504 505 506 507 508 509 510 511
        data_: match sd.data_ {
            VariantData_::Struct(ref fields) => {
                hir::VariantData_::Struct(fields.iter().map(|f| lower_struct_field(_lctx, f)).collect())
            }
            VariantData_::Tuple(ref fields) => {
                hir::VariantData_::Tuple(fields.iter().map(|f| lower_struct_field(_lctx, f)).collect())
            }
            VariantData_::Unit => hir::VariantData_::Unit
512
        }
513 514 515
    })
}

N
Nick Cameron 已提交
516
pub fn lower_trait_ref(_lctx: &LoweringContext, p: &TraitRef) -> hir::TraitRef {
N
Nick Cameron 已提交
517 518 519 520
    hir::TraitRef {
        path: lower_path(_lctx, &p.path),
        ref_id: p.ref_id,
    }
521 522
}

N
Nick Cameron 已提交
523
pub fn lower_poly_trait_ref(_lctx: &LoweringContext, p: &PolyTraitRef) -> hir::PolyTraitRef {
524
    hir::PolyTraitRef {
N
Nick Cameron 已提交
525 526
        bound_lifetimes: lower_lifetime_defs(_lctx, &p.bound_lifetimes),
        trait_ref: lower_trait_ref(_lctx, &p.trait_ref),
527 528 529 530
        span: p.span,
    }
}

N
Nick Cameron 已提交
531
pub fn lower_struct_field(_lctx: &LoweringContext, f: &StructField) -> hir::StructField {
532 533 534
    Spanned {
        node: hir::StructField_ {
            id: f.node.id,
N
Nick Cameron 已提交
535 536
            kind: lower_struct_field_kind(_lctx, &f.node.kind),
            ty: lower_ty(_lctx, &f.node.ty),
537
            attrs: f.node.attrs.clone(),
538 539 540 541 542
        },
        span: f.span,
    }
}

N
Nick Cameron 已提交
543
pub fn lower_field(_lctx: &LoweringContext, f: &Field) -> hir::Field {
544 545
    hir::Field {
        name: respan(f.ident.span, f.ident.node.name),
N
Nick Cameron 已提交
546 547
        expr: lower_expr(_lctx, &f.expr),
        span: f.span,
548
    }
549 550
}

N
Nick Cameron 已提交
551
pub fn lower_mt(_lctx: &LoweringContext, mt: &MutTy) -> hir::MutTy {
N
Nick Cameron 已提交
552 553 554 555
    hir::MutTy {
        ty: lower_ty(_lctx, &mt.ty),
        mutbl: lower_mutability(_lctx, mt.mutbl),
    }
556 557
}

N
Nick Cameron 已提交
558 559
pub fn lower_opt_bounds(_lctx: &LoweringContext,
                        b: &Option<OwnedSlice<TyParamBound>>)
560
                        -> Option<OwnedSlice<hir::TyParamBound>> {
N
Nick Cameron 已提交
561
    b.as_ref().map(|ref bounds| lower_bounds(_lctx, bounds))
562 563
}

N
Nick Cameron 已提交
564 565
fn lower_bounds(_lctx: &LoweringContext, bounds: &TyParamBounds) -> hir::TyParamBounds {
    bounds.iter().map(|bound| lower_ty_param_bound(_lctx, bound)).collect()
566 567
}

N
Nick Cameron 已提交
568
pub fn lower_block(_lctx: &LoweringContext, b: &Block) -> P<hir::Block> {
569 570
    P(hir::Block {
        id: b.id,
N
Nick Cameron 已提交
571 572 573
        stmts: b.stmts.iter().map(|s| lower_stmt(_lctx, s)).collect(),
        expr: b.expr.as_ref().map(|ref x| lower_expr(_lctx, x)),
        rules: lower_block_check_mode(_lctx, &b.rules),
574 575 576 577
        span: b.span,
    })
}

N
Nick Cameron 已提交
578
pub fn lower_item_underscore(_lctx: &LoweringContext, i: &Item_) -> hir::Item_ {
579 580 581
    match *i {
        ItemExternCrate(string) => hir::ItemExternCrate(string),
        ItemUse(ref view_path) => {
N
Nick Cameron 已提交
582
            hir::ItemUse(lower_view_path(_lctx, view_path))
583 584
        }
        ItemStatic(ref t, m, ref e) => {
N
Nick Cameron 已提交
585 586 587
            hir::ItemStatic(lower_ty(_lctx, t),
                            lower_mutability(_lctx, m),
                            lower_expr(_lctx, e))
588 589
        }
        ItemConst(ref t, ref e) => {
N
Nick Cameron 已提交
590
            hir::ItemConst(lower_ty(_lctx, t), lower_expr(_lctx, e))
591 592
        }
        ItemFn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
N
Nick Cameron 已提交
593 594 595 596 597 598
            hir::ItemFn(lower_fn_decl(_lctx, decl),
                        lower_unsafety(_lctx, unsafety),
                        lower_constness(_lctx, constness),
                        abi,
                        lower_generics(_lctx, generics),
                        lower_block(_lctx, body))
599
        }
N
Nick Cameron 已提交
600 601
        ItemMod(ref m) => hir::ItemMod(lower_mod(_lctx, m)),
        ItemForeignMod(ref nm) => hir::ItemForeignMod(lower_foreign_mod(_lctx, nm)),
602
        ItemTy(ref t, ref generics) => {
N
Nick Cameron 已提交
603
            hir::ItemTy(lower_ty(_lctx, t), lower_generics(_lctx, generics))
604 605
        }
        ItemEnum(ref enum_definition, ref generics) => {
N
Nick Cameron 已提交
606 607 608 609 610 611 612
            hir::ItemEnum(hir::EnumDef {
                              variants: enum_definition.variants
                                                       .iter()
                                                       .map(|x| lower_variant(_lctx, x))
                                                       .collect(),
                          },
                          lower_generics(_lctx, generics))
613 614
        }
        ItemStruct(ref struct_def, ref generics) => {
N
Nick Cameron 已提交
615 616
            let struct_def = lower_struct_def(_lctx, struct_def);
            hir::ItemStruct(struct_def, lower_generics(_lctx, generics))
617 618
        }
        ItemDefaultImpl(unsafety, ref trait_ref) => {
N
Nick Cameron 已提交
619 620
            hir::ItemDefaultImpl(lower_unsafety(_lctx, unsafety),
                                 lower_trait_ref(_lctx, trait_ref))
621 622
        }
        ItemImpl(unsafety, polarity, ref generics, ref ifce, ref ty, ref impl_items) => {
N
Nick Cameron 已提交
623 624 625
            let new_impl_items = impl_items.iter()
                                           .map(|item| lower_impl_item(_lctx, item))
                                           .collect();
N
Nick Cameron 已提交
626 627 628 629
            let ifce = ifce.as_ref().map(|trait_ref| lower_trait_ref(_lctx, trait_ref));
            hir::ItemImpl(lower_unsafety(_lctx, unsafety),
                          lower_impl_polarity(_lctx, polarity),
                          lower_generics(_lctx, generics),
630
                          ifce,
N
Nick Cameron 已提交
631
                          lower_ty(_lctx, ty),
632 633 634
                          new_impl_items)
        }
        ItemTrait(unsafety, ref generics, ref bounds, ref items) => {
N
Nick Cameron 已提交
635 636 637 638
            let bounds = lower_bounds(_lctx, bounds);
            let items = items.iter().map(|item| lower_trait_item(_lctx, item)).collect();
            hir::ItemTrait(lower_unsafety(_lctx, unsafety),
                           lower_generics(_lctx, generics),
639 640 641 642 643 644 645
                           bounds,
                           items)
        }
        ItemMac(_) => panic!("Shouldn't still be around"),
    }
}

N
Nick Cameron 已提交
646
pub fn lower_trait_item(_lctx: &LoweringContext, i: &TraitItem) -> P<hir::TraitItem> {
647
    P(hir::TraitItem {
N
Nick Cameron 已提交
648 649 650 651
        id: i.id,
        name: i.ident.name,
        attrs: i.attrs.clone(),
        node: match i.node {
652
            ConstTraitItem(ref ty, ref default) => {
N
Nick Cameron 已提交
653 654
                hir::ConstTraitItem(lower_ty(_lctx, ty),
                                    default.as_ref().map(|x| lower_expr(_lctx, x)))
655 656
            }
            MethodTraitItem(ref sig, ref body) => {
N
Nick Cameron 已提交
657 658
                hir::MethodTraitItem(lower_method_sig(_lctx, sig),
                                     body.as_ref().map(|x| lower_block(_lctx, x)))
659 660
            }
            TypeTraitItem(ref bounds, ref default) => {
N
Nick Cameron 已提交
661 662
                hir::TypeTraitItem(lower_bounds(_lctx, bounds),
                                   default.as_ref().map(|x| lower_ty(_lctx, x)))
663 664
            }
        },
N
Nick Cameron 已提交
665 666
        span: i.span,
    })
667 668
}

N
Nick Cameron 已提交
669
pub fn lower_impl_item(_lctx: &LoweringContext, i: &ImplItem) -> P<hir::ImplItem> {
670
    P(hir::ImplItem {
N
Nick Cameron 已提交
671 672 673 674 675
        id: i.id,
        name: i.ident.name,
        attrs: i.attrs.clone(),
        vis: lower_visibility(_lctx, i.vis),
        node: match i.node {
676
            ConstImplItem(ref ty, ref expr) => {
N
Nick Cameron 已提交
677
                hir::ConstImplItem(lower_ty(_lctx, ty), lower_expr(_lctx, expr))
678 679
            }
            MethodImplItem(ref sig, ref body) => {
N
Nick Cameron 已提交
680 681
                hir::MethodImplItem(lower_method_sig(_lctx, sig),
                                    lower_block(_lctx, body))
682
            }
N
Nick Cameron 已提交
683
            TypeImplItem(ref ty) => hir::TypeImplItem(lower_ty(_lctx, ty)),
684 685
            MacImplItem(..) => panic!("Shouldn't exist any more"),
        },
N
Nick Cameron 已提交
686 687
        span: i.span,
    })
688 689
}

N
Nick Cameron 已提交
690
pub fn lower_mod(_lctx: &LoweringContext, m: &Mod) -> hir::Mod {
N
Nick Cameron 已提交
691 692 693 694
    hir::Mod {
        inner: m.inner,
        items: m.items.iter().map(|x| lower_item(_lctx, x)).collect(),
    }
695 696
}

N
Nick Cameron 已提交
697
pub fn lower_crate(_lctx: &LoweringContext, c: &Crate) -> hir::Crate {
698
    hir::Crate {
N
Nick Cameron 已提交
699
        module: lower_mod(_lctx, &c.module),
700 701
        attrs: c.attrs.clone(),
        config: c.config.clone(),
702
        span: c.span,
N
Nick Cameron 已提交
703
        exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(_lctx, m)).collect(),
704 705 706
    }
}

N
Nick Cameron 已提交
707
pub fn lower_macro_def(_lctx: &LoweringContext, m: &MacroDef) -> hir::MacroDef {
708
    hir::MacroDef {
709
        name: m.ident.name,
710
        attrs: m.attrs.clone(),
711 712
        id: m.id,
        span: m.span,
713
        imported_from: m.imported_from.map(|x| x.name),
714 715 716 717 718 719 720 721
        export: m.export,
        use_locally: m.use_locally,
        allow_internal_unstable: m.allow_internal_unstable,
        body: m.body.clone(),
    }
}

// fold one item into possibly many items
N
Nick Cameron 已提交
722 723
pub fn lower_item(_lctx: &LoweringContext, i: &Item) -> P<hir::Item> {
    P(lower_item_simple(_lctx, i))
724 725 726
}

// fold one item into exactly one item
N
Nick Cameron 已提交
727 728
pub fn lower_item_simple(_lctx: &LoweringContext, i: &Item) -> hir::Item {
    let node = lower_item_underscore(_lctx, &i.node);
729 730 731

    hir::Item {
        id: i.id,
V
Vadim Petrochenkov 已提交
732
        name: i.ident.name,
733
        attrs: i.attrs.clone(),
734
        node: node,
N
Nick Cameron 已提交
735
        vis: lower_visibility(_lctx, i.vis),
736 737 738 739
        span: i.span,
    }
}

N
Nick Cameron 已提交
740
pub fn lower_foreign_item(_lctx: &LoweringContext, i: &ForeignItem) -> P<hir::ForeignItem> {
741
    P(hir::ForeignItem {
N
Nick Cameron 已提交
742 743 744 745
        id: i.id,
        name: i.ident.name,
        attrs: i.attrs.clone(),
        node: match i.node {
746
            ForeignItemFn(ref fdec, ref generics) => {
N
Nick Cameron 已提交
747 748
                hir::ForeignItemFn(lower_fn_decl(_lctx, fdec),
                                   lower_generics(_lctx, generics))
749 750
            }
            ForeignItemStatic(ref t, m) => {
N
Nick Cameron 已提交
751
                hir::ForeignItemStatic(lower_ty(_lctx, t), m)
752 753
            }
        },
N
Nick Cameron 已提交
754 755 756
        vis: lower_visibility(_lctx, i.vis),
        span: i.span,
    })
757 758
}

N
Nick Cameron 已提交
759
pub fn lower_method_sig(_lctx: &LoweringContext, sig: &MethodSig) -> hir::MethodSig {
760
    hir::MethodSig {
N
Nick Cameron 已提交
761
        generics: lower_generics(_lctx, &sig.generics),
762
        abi: sig.abi,
N
Nick Cameron 已提交
763 764 765 766
        explicit_self: lower_explicit_self(_lctx, &sig.explicit_self),
        unsafety: lower_unsafety(_lctx, sig.unsafety),
        constness: lower_constness(_lctx, sig.constness),
        decl: lower_fn_decl(_lctx, &sig.decl),
767 768 769
    }
}

N
Nick Cameron 已提交
770
pub fn lower_unsafety(_lctx: &LoweringContext, u: Unsafety) -> hir::Unsafety {
771 772 773 774 775 776
    match u {
        Unsafety::Unsafe => hir::Unsafety::Unsafe,
        Unsafety::Normal => hir::Unsafety::Normal,
    }
}

N
Nick Cameron 已提交
777
pub fn lower_constness(_lctx: &LoweringContext, c: Constness) -> hir::Constness {
778 779 780 781 782 783
    match c {
        Constness::Const => hir::Constness::Const,
        Constness::NotConst => hir::Constness::NotConst,
    }
}

N
Nick Cameron 已提交
784
pub fn lower_unop(_lctx: &LoweringContext, u: UnOp) -> hir::UnOp {
785 786 787 788 789 790 791
    match u {
        UnDeref => hir::UnDeref,
        UnNot => hir::UnNot,
        UnNeg => hir::UnNeg,
    }
}

N
Nick Cameron 已提交
792
pub fn lower_binop(_lctx: &LoweringContext, b: BinOp) -> hir::BinOp {
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
    Spanned {
        node: match b.node {
            BiAdd => hir::BiAdd,
            BiSub => hir::BiSub,
            BiMul => hir::BiMul,
            BiDiv => hir::BiDiv,
            BiRem => hir::BiRem,
            BiAnd => hir::BiAnd,
            BiOr => hir::BiOr,
            BiBitXor => hir::BiBitXor,
            BiBitAnd => hir::BiBitAnd,
            BiBitOr => hir::BiBitOr,
            BiShl => hir::BiShl,
            BiShr => hir::BiShr,
            BiEq => hir::BiEq,
            BiLt => hir::BiLt,
            BiLe => hir::BiLe,
            BiNe => hir::BiNe,
            BiGe => hir::BiGe,
            BiGt => hir::BiGt,
        },
        span: b.span,
    }
}

N
Nick Cameron 已提交
818
pub fn lower_pat(_lctx: &LoweringContext, p: &Pat) -> P<hir::Pat> {
819
    P(hir::Pat {
N
Nick Cameron 已提交
820 821
        id: p.id,
        node: match p.node {
N
Nick Cameron 已提交
822
            PatWild(k) => hir::PatWild(lower_pat_wild_kind(_lctx, k)),
823
            PatIdent(ref binding_mode, pth1, ref sub) => {
N
Nick Cameron 已提交
824
                hir::PatIdent(lower_binding_mode(_lctx, binding_mode),
N
Nick Cameron 已提交
825 826
                              pth1,
                              sub.as_ref().map(|x| lower_pat(_lctx, x)))
827
            }
N
Nick Cameron 已提交
828
            PatLit(ref e) => hir::PatLit(lower_expr(_lctx, e)),
829
            PatEnum(ref pth, ref pats) => {
N
Nick Cameron 已提交
830 831 832
                hir::PatEnum(lower_path(_lctx, pth),
                             pats.as_ref()
                                 .map(|pats| pats.iter().map(|x| lower_pat(_lctx, x)).collect()))
833 834 835
            }
            PatQPath(ref qself, ref pth) => {
                let qself = hir::QSelf {
N
Nick Cameron 已提交
836
                    ty: lower_ty(_lctx, &qself.ty),
837 838
                    position: qself.position,
                };
N
Nick Cameron 已提交
839
                hir::PatQPath(qself, lower_path(_lctx, pth))
840 841
            }
            PatStruct(ref pth, ref fields, etc) => {
N
Nick Cameron 已提交
842
                let pth = lower_path(_lctx, pth);
N
Nick Cameron 已提交
843 844 845 846 847 848 849 850 851 852 853 854
                let fs = fields.iter()
                               .map(|f| {
                                   Spanned {
                                       span: f.span,
                                       node: hir::FieldPat {
                                           name: f.node.ident.name,
                                           pat: lower_pat(_lctx, &f.node.pat),
                                           is_shorthand: f.node.is_shorthand,
                                       },
                                   }
                               })
                               .collect();
855 856
                hir::PatStruct(pth, fs, etc)
            }
N
Nick Cameron 已提交
857 858 859 860
            PatTup(ref elts) => hir::PatTup(elts.iter().map(|x| lower_pat(_lctx, x)).collect()),
            PatBox(ref inner) => hir::PatBox(lower_pat(_lctx, inner)),
            PatRegion(ref inner, mutbl) => hir::PatRegion(lower_pat(_lctx, inner),
                                                          lower_mutability(_lctx, mutbl)),
861
            PatRange(ref e1, ref e2) => {
N
Nick Cameron 已提交
862
                hir::PatRange(lower_expr(_lctx, e1), lower_expr(_lctx, e2))
N
Nick Cameron 已提交
863
            }
864
            PatVec(ref before, ref slice, ref after) => {
N
Nick Cameron 已提交
865
                hir::PatVec(before.iter().map(|x| lower_pat(_lctx, x)).collect(),
N
Nick Cameron 已提交
866 867
                            slice.as_ref().map(|x| lower_pat(_lctx, x)),
                            after.iter().map(|x| lower_pat(_lctx, x)).collect())
868 869 870
            }
            PatMac(_) => panic!("Shouldn't exist here"),
        },
N
Nick Cameron 已提交
871 872
        span: p.span,
    })
873 874
}

N
Nick Cameron 已提交
875 876 877 878 879 880 881 882
// RAII utility for setting and unsetting the cached id.
struct CachedIdSetter<'a> {
    reset: bool,
    lctx: &'a LoweringContext<'a>,
}

impl<'a> CachedIdSetter<'a> {
    fn new(lctx: &'a LoweringContext, expr_id: NodeId) -> CachedIdSetter<'a> {
N
Nick Cameron 已提交
883 884 885 886 887
        // Only reset the id if it was previously 0, i.e., was not cached.
        // If it was cached, we are in a nested node, but our id count will
        // still count towards the parent's count.
        let reset_cached_id = lctx.cached_id.get() == 0;

N
Nick Cameron 已提交
888 889 890 891 892 893 894 895
        let id_cache: &mut HashMap<_, _> = &mut lctx.id_cache.borrow_mut();

        if id_cache.contains_key(&expr_id) {
            let cached_id = lctx.cached_id.get();
            if cached_id == 0 {
                // We're entering a node where we need to track ids, but are not
                // yet tracking.
                lctx.cached_id.set(id_cache[&expr_id]);
N
Nick Cameron 已提交
896
                lctx.gensym_key.set(id_cache[&expr_id]);
N
Nick Cameron 已提交
897 898 899 900 901 902
            } else {
                // We're already tracking - check that the tracked id is the same
                // as the expected id.
                assert!(cached_id == id_cache[&expr_id], "id mismatch");
            }
        } else {
N
Nick Cameron 已提交
903 904 905
            let next_id = lctx.id_assigner.peek_node_id();
            id_cache.insert(expr_id, next_id);
            lctx.gensym_key.set(next_id);
N
Nick Cameron 已提交
906 907 908
        }

        CachedIdSetter {
N
Nick Cameron 已提交
909
            reset: reset_cached_id,
N
Nick Cameron 已提交
910 911 912 913 914 915 916 917 918
            lctx: lctx,
        }
    }
}

impl<'a> Drop for CachedIdSetter<'a> {
    fn drop(&mut self) {
        if self.reset {
            self.lctx.cached_id.set(0);
N
Nick Cameron 已提交
919
            self.lctx.gensym_key.set(0);
N
Nick Cameron 已提交
920 921 922 923
        }
    }
}

924
pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
925
    P(hir::Expr {
N
Nick Cameron 已提交
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
        id: e.id,
        node: match e.node {
            // Issue #22181:
            // Eventually a desugaring for `box EXPR`
            // (similar to the desugaring above for `in PLACE BLOCK`)
            // should go here, desugaring
            //
            // to:
            //
            // let mut place = BoxPlace::make_place();
            // let raw_place = Place::pointer(&mut place);
            // let value = $value;
            // unsafe {
            //     ::std::ptr::write(raw_place, value);
            //     Boxed::finalize(place)
            // }
            //
            // But for now there are type-inference issues doing that.
            ExprBox(ref e) => {
                hir::ExprBox(lower_expr(lctx, e))
            }

            // Desugar ExprBox: `in (PLACE) EXPR`
            ExprInPlace(ref placer, ref value_expr) => {
N
Nick Cameron 已提交
950 951
                // to:
                //
N
Nick Cameron 已提交
952 953
                // let p = PLACE;
                // let mut place = Placer::make_place(p);
N
Nick Cameron 已提交
954
                // let raw_place = Place::pointer(&mut place);
N
Nick Cameron 已提交
955 956 957 958 959 960 961 962 963
                // push_unsafe!({
                //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
                //     InPlace::finalize(place)
                // })
                let _old_cached = CachedIdSetter::new(lctx, e.id);

                let placer_expr = lower_expr(lctx, placer);
                let value_expr = lower_expr(lctx, value_expr);

N
Nick Cameron 已提交
964 965 966
                let placer_ident = lctx.str_to_ident("placer");
                let agent_ident = lctx.str_to_ident("place");
                let p_ptr_ident = lctx.str_to_ident("p_ptr");
N
Nick Cameron 已提交
967 968 969 970 971 972 973 974 975 976 977

                let make_place = ["ops", "Placer", "make_place"];
                let place_pointer = ["ops", "Place", "pointer"];
                let move_val_init = ["intrinsics", "move_val_init"];
                let inplace_finalize = ["ops", "InPlace", "finalize"];

                let make_call = |lctx, p, args| {
                    let path = core_path(lctx, e.span, p);
                    let path = expr_path(lctx, path);
                    expr_call(lctx, e.span, path, args)
                };
978

N
Nick Cameron 已提交
979 980
                let mk_stmt_let = |lctx, bind, expr| stmt_let(lctx, e.span, false, bind, expr);
                let mk_stmt_let_mut = |lctx, bind, expr| stmt_let(lctx, e.span, true, bind, expr);
981

N
Nick Cameron 已提交
982
                // let placer = <placer_expr> ;
N
Nick Cameron 已提交
983 984 985 986 987 988 989
                let s1 = mk_stmt_let(lctx,
                                     placer_ident,
                                     signal_block_expr(lctx,
                                                       vec![],
                                                       placer_expr,
                                                       e.span,
                                                       hir::PopUnstableBlock));
990

N
Nick Cameron 已提交
991 992 993 994 995 996 997
                // let mut place = Placer::make_place(placer);
                let s2 = {
                    let call = make_call(lctx,
                                         &make_place,
                                         vec![expr_ident(lctx, e.span, placer_ident)]);
                    mk_stmt_let_mut(lctx, agent_ident, call)
                };
998

N
Nick Cameron 已提交
999 1000 1001 1002 1003 1004 1005 1006
                // let p_ptr = Place::pointer(&mut place);
                let s3 = {
                    let args = vec![expr_mut_addr_of(lctx,
                                                     e.span,
                                                     expr_ident(lctx, e.span, agent_ident))];
                    let call = make_call(lctx, &place_pointer, args);
                    mk_stmt_let(lctx, p_ptr_ident, call)
                };
1007

N
Nick Cameron 已提交
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
                // pop_unsafe!(EXPR));
                let pop_unsafe_expr =
                    signal_block_expr(lctx,
                                      vec![],
                                      signal_block_expr(lctx,
                                                        vec![],
                                                        value_expr,
                                                        e.span,
                                                        hir::PopUnstableBlock),
                                      e.span,
                                      hir::PopUnsafeBlock(hir::CompilerGenerated));

                // push_unsafe!({
                //     std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
                //     InPlace::finalize(place)
                // })
                let expr = {
                    let call_move_val_init = hir::StmtSemi(make_call(lctx,
N
Nick Cameron 已提交
1026 1027 1028
                                                    &move_val_init,
                                                    vec![expr_ident(lctx, e.span, p_ptr_ident),
                                                         pop_unsafe_expr]),
N
Nick Cameron 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
                                                           lctx.next_id());
                    let call_move_val_init = respan(e.span, call_move_val_init);

                    let call = make_call(lctx,
                                         &inplace_finalize,
                                         vec![expr_ident(lctx, e.span, agent_ident)]);
                    signal_block_expr(lctx,
                                      vec![P(call_move_val_init)],
                                      call,
                                      e.span,
                                      hir::PushUnsafeBlock(hir::CompilerGenerated))
                };
1041

N
Nick Cameron 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
                return signal_block_expr(lctx,
                                         vec![s1, s2, s3],
                                         expr,
                                         e.span,
                                         hir::PushUnstableBlock);
            }

            ExprVec(ref exprs) => {
                hir::ExprVec(exprs.iter().map(|x| lower_expr(lctx, x)).collect())
            }
            ExprRepeat(ref expr, ref count) => {
                hir::ExprRepeat(lower_expr(lctx, expr), lower_expr(lctx, count))
            }
            ExprTup(ref elts) => {
                hir::ExprTup(elts.iter().map(|x| lower_expr(lctx, x)).collect())
            }
            ExprCall(ref f, ref args) => {
                hir::ExprCall(lower_expr(lctx, f),
                              args.iter().map(|x| lower_expr(lctx, x)).collect())
            }
            ExprMethodCall(i, ref tps, ref args) => {
                hir::ExprMethodCall(respan(i.span, i.node.name),
                                    tps.iter().map(|x| lower_ty(lctx, x)).collect(),
                                    args.iter().map(|x| lower_expr(lctx, x)).collect())
            }
            ExprBinary(binop, ref lhs, ref rhs) => {
                hir::ExprBinary(lower_binop(lctx, binop),
                                lower_expr(lctx, lhs),
                                lower_expr(lctx, rhs))
            }
            ExprUnary(op, ref ohs) => {
                hir::ExprUnary(lower_unop(lctx, op), lower_expr(lctx, ohs))
            }
            ExprLit(ref l) => hir::ExprLit(P((**l).clone())),
            ExprCast(ref expr, ref ty) => {
                hir::ExprCast(lower_expr(lctx, expr), lower_ty(lctx, ty))
            }
            ExprAddrOf(m, ref ohs) => {
                hir::ExprAddrOf(lower_mutability(lctx, m), lower_expr(lctx, ohs))
            }
            // More complicated than you might expect because the else branch
            // might be `if let`.
            ExprIf(ref cond, ref blk, ref else_opt) => {
                let else_opt = else_opt.as_ref().map(|els| {
                    match els.node {
N
Nick Cameron 已提交
1087
                        ExprIfLet(..) => {
1088
                            let _old_cached = CachedIdSetter::new(lctx, e.id);
N
Nick Cameron 已提交
1089 1090 1091 1092 1093 1094 1095
                            // wrap the if-let expr in a block
                            let span = els.span;
                            let blk = P(hir::Block {
                                stmts: vec![],
                                expr: Some(lower_expr(lctx, els)),
                                id: lctx.next_id(),
                                rules: hir::DefaultBlock,
N
Nick Cameron 已提交
1096
                                span: span,
N
Nick Cameron 已提交
1097 1098 1099
                            });
                            expr_block(lctx, blk)
                        }
N
Nick Cameron 已提交
1100 1101 1102
                        _ => lower_expr(lctx, els),
                    }
                });
N
Nick Cameron 已提交
1103

N
Nick Cameron 已提交
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
                hir::ExprIf(lower_expr(lctx, cond),
                            lower_block(lctx, blk),
                            else_opt)
            }
            ExprWhile(ref cond, ref body, opt_ident) => {
                hir::ExprWhile(lower_expr(lctx, cond),
                               lower_block(lctx, body),
                               opt_ident)
            }
            ExprLoop(ref body, opt_ident) => {
                hir::ExprLoop(lower_block(lctx, body), opt_ident)
            }
            ExprMatch(ref expr, ref arms) => {
                hir::ExprMatch(lower_expr(lctx, expr),
                               arms.iter().map(|x| lower_arm(lctx, x)).collect(),
                               hir::MatchSource::Normal)
            }
            ExprClosure(capture_clause, ref decl, ref body) => {
                hir::ExprClosure(lower_capture_clause(lctx, capture_clause),
                                 lower_fn_decl(lctx, decl),
                                 lower_block(lctx, body))
            }
            ExprBlock(ref blk) => hir::ExprBlock(lower_block(lctx, blk)),
            ExprAssign(ref el, ref er) => {
                hir::ExprAssign(lower_expr(lctx, el), lower_expr(lctx, er))
            }
            ExprAssignOp(op, ref el, ref er) => {
                hir::ExprAssignOp(lower_binop(lctx, op),
                                  lower_expr(lctx, el),
                                  lower_expr(lctx, er))
            }
            ExprField(ref el, ident) => {
                hir::ExprField(lower_expr(lctx, el),
                               respan(ident.span, ident.node.name))
            }
            ExprTupField(ref el, ident) => {
                hir::ExprTupField(lower_expr(lctx, el), ident)
            }
            ExprIndex(ref el, ref er) => {
                hir::ExprIndex(lower_expr(lctx, el), lower_expr(lctx, er))
            }
            ExprRange(ref e1, ref e2) => {
                hir::ExprRange(e1.as_ref().map(|x| lower_expr(lctx, x)),
                               e2.as_ref().map(|x| lower_expr(lctx, x)))
            }
            ExprPath(ref qself, ref path) => {
                let qself = qself.as_ref().map(|&QSelf { ref ty, position }| {
                    hir::QSelf {
                        ty: lower_ty(lctx, ty),
                        position: position,
                    }
                });
                hir::ExprPath(qself, lower_path(lctx, path))
            }
            ExprBreak(opt_ident) => hir::ExprBreak(opt_ident),
            ExprAgain(opt_ident) => hir::ExprAgain(opt_ident),
            ExprRet(ref e) => hir::ExprRet(e.as_ref().map(|x| lower_expr(lctx, x))),
            ExprInlineAsm(InlineAsm {
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
                    ref inputs,
                    ref outputs,
                    ref asm,
                    asm_str_style,
                    ref clobbers,
                    volatile,
                    alignstack,
                    dialect,
                    expn_id,
                }) => hir::ExprInlineAsm(hir::InlineAsm {
N
Nick Cameron 已提交
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
                inputs: inputs.iter()
                              .map(|&(ref c, ref input)| (c.clone(), lower_expr(lctx, input)))
                              .collect(),
                outputs: outputs.iter()
                                .map(|&(ref c, ref out, ref is_rw)| {
                                    (c.clone(), lower_expr(lctx, out), *is_rw)
                                })
                                .collect(),
                asm: asm.clone(),
                asm_str_style: asm_str_style,
                clobbers: clobbers.clone(),
                volatile: volatile,
                alignstack: alignstack,
                dialect: dialect,
                expn_id: expn_id,
            }),
            ExprStruct(ref path, ref fields, ref maybe_expr) => {
                hir::ExprStruct(lower_path(lctx, path),
                                fields.iter().map(|x| lower_field(lctx, x)).collect(),
                                maybe_expr.as_ref().map(|x| lower_expr(lctx, x)))
            }
            ExprParen(ref ex) => {
                return lower_expr(lctx, ex);
            }
N
Nick Cameron 已提交
1196

N
Nick Cameron 已提交
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
            // Desugar ExprIfLet
            // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
            ExprIfLet(ref pat, ref sub_expr, ref body, ref else_opt) => {
                // to:
                //
                //   match <sub_expr> {
                //     <pat> => <body>,
                //     [_ if <else_opt_if_cond> => <else_opt_if_body>,]
                //     _ => [<else_opt> | ()]
                //   }

                let _old_cached = CachedIdSetter::new(lctx, e.id);

                // `<pat> => <body>`
                let pat_arm = {
                    let body_expr = expr_block(lctx, lower_block(lctx, body));
                    arm(vec![lower_pat(lctx, pat)], body_expr)
                };
N
Nick Cameron 已提交
1215

N
Nick Cameron 已提交
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
                // `[_ if <else_opt_if_cond> => <else_opt_if_body>,]`
                let mut else_opt = else_opt.as_ref().map(|e| lower_expr(lctx, e));
                let else_if_arms = {
                    let mut arms = vec![];
                    loop {
                        let else_opt_continue = else_opt.and_then(|els| {
                            els.and_then(|els| {
                                match els.node {
                                    // else if
                                    hir::ExprIf(cond, then, else_opt) => {
                                        let pat_under = pat_wild(lctx, e.span);
                                        arms.push(hir::Arm {
                                            attrs: vec![],
                                            pats: vec![pat_under],
                                            guard: Some(cond),
                                            body: expr_block(lctx, then),
                                        });
                                        else_opt.map(|else_opt| (else_opt, true))
                                    }
                                    _ => Some((P(els), false)),
N
Nick Cameron 已提交
1236
                                }
N
Nick Cameron 已提交
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
                            })
                        });
                        match else_opt_continue {
                            Some((e, true)) => {
                                else_opt = Some(e);
                            }
                            Some((e, false)) => {
                                else_opt = Some(e);
                                break;
                            }
                            None => {
                                else_opt = None;
                                break;
N
Nick Cameron 已提交
1250 1251
                            }
                        }
N
Nick Cameron 已提交
1252 1253 1254
                    }
                    arms
                };
N
Nick Cameron 已提交
1255

N
Nick Cameron 已提交
1256
                let contains_else_clause = else_opt.is_some();
N
Nick Cameron 已提交
1257

N
Nick Cameron 已提交
1258 1259 1260 1261 1262 1263
                // `_ => [<else_opt> | ()]`
                let else_arm = {
                    let pat_under = pat_wild(lctx, e.span);
                    let else_expr = else_opt.unwrap_or_else(|| expr_tuple(lctx, e.span, vec![]));
                    arm(vec![pat_under], else_expr)
                };
N
Nick Cameron 已提交
1264

N
Nick Cameron 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
                let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
                arms.push(pat_arm);
                arms.extend(else_if_arms);
                arms.push(else_arm);

                let match_expr = expr(lctx,
                                      e.span,
                                      hir::ExprMatch(lower_expr(lctx, sub_expr),
                                                     arms,
                                                     hir::MatchSource::IfLetDesugar {
                                                         contains_else_clause: contains_else_clause,
                                                     }));
                return match_expr;
            }
N
Nick Cameron 已提交
1279

N
Nick Cameron 已提交
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
            // Desugar ExprWhileLet
            // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
            ExprWhileLet(ref pat, ref sub_expr, ref body, opt_ident) => {
                // to:
                //
                //   [opt_ident]: loop {
                //     match <sub_expr> {
                //       <pat> => <body>,
                //       _ => break
                //     }
                //   }

                let _old_cached = CachedIdSetter::new(lctx, e.id);

                // `<pat> => <body>`
                let pat_arm = {
                    let body_expr = expr_block(lctx, lower_block(lctx, body));
                    arm(vec![lower_pat(lctx, pat)], body_expr)
                };
N
Nick Cameron 已提交
1299

N
Nick Cameron 已提交
1300 1301 1302 1303 1304 1305
                // `_ => break`
                let break_arm = {
                    let pat_under = pat_wild(lctx, e.span);
                    let break_expr = expr_break(lctx, e.span);
                    arm(vec![pat_under], break_expr)
                };
N
Nick Cameron 已提交
1306

N
Nick Cameron 已提交
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
                // `match <sub_expr> { ... }`
                let arms = vec![pat_arm, break_arm];
                let match_expr = expr(lctx,
                                      e.span,
                                      hir::ExprMatch(lower_expr(lctx, sub_expr),
                                                     arms,
                                                     hir::MatchSource::WhileLetDesugar));

                // `[opt_ident]: loop { ... }`
                let loop_block = block_expr(lctx, match_expr);
                return expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident));
            }
N
Nick Cameron 已提交
1319

N
Nick Cameron 已提交
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
            // Desugar ExprForLoop
            // From: `[opt_ident]: for <pat> in <head> <body>`
            ExprForLoop(ref pat, ref head, ref body, opt_ident) => {
                // to:
                //
                //   {
                //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
                //       mut iter => {
                //         [opt_ident]: loop {
                //           match ::std::iter::Iterator::next(&mut iter) {
                //             ::std::option::Option::Some(<pat>) => <body>,
                //             ::std::option::Option::None => break
                //           }
                //         }
                //       }
                //     };
                //     result
                //   }

                let _old_cached = CachedIdSetter::new(lctx, e.id);

                // expand <head>
                let head = lower_expr(lctx, head);

N
Nick Cameron 已提交
1344
                let iter = lctx.str_to_ident("iter");
N
Nick Cameron 已提交
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356

                // `::std::option::Option::Some(<pat>) => <body>`
                let pat_arm = {
                    let body_block = lower_block(lctx, body);
                    let body_span = body_block.span;
                    let body_expr = P(hir::Expr {
                        id: lctx.next_id(),
                        node: hir::ExprBlock(body_block),
                        span: body_span,
                    });
                    let pat = lower_pat(lctx, pat);
                    let some_pat = pat_some(lctx, e.span, pat);
1357

N
Nick Cameron 已提交
1358 1359
                    arm(vec![some_pat], body_expr)
                };
1360

N
Nick Cameron 已提交
1361 1362 1363
                // `::std::option::Option::None => break`
                let break_arm = {
                    let break_expr = expr_break(lctx, e.span);
1364

N
Nick Cameron 已提交
1365 1366
                    arm(vec![pat_none(lctx, e.span)], break_expr)
                };
1367

N
Nick Cameron 已提交
1368 1369 1370 1371
                // `match ::std::iter::Iterator::next(&mut iter) { ... }`
                let match_expr = {
                    let next_path = {
                        let strs = std_path(lctx, &["iter", "Iterator", "next"]);
1372

N
Nick Cameron 已提交
1373
                        path_global(e.span, strs)
1374
                    };
N
Nick Cameron 已提交
1375 1376 1377 1378 1379 1380 1381 1382
                    let ref_mut_iter = expr_mut_addr_of(lctx,
                                                        e.span,
                                                        expr_ident(lctx, e.span, iter));
                    let next_expr = expr_call(lctx,
                                              e.span,
                                              expr_path(lctx, next_path),
                                              vec![ref_mut_iter]);
                    let arms = vec![pat_arm, break_arm];
1383

N
Nick Cameron 已提交
1384 1385 1386 1387
                    expr(lctx,
                         e.span,
                         hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar))
                };
1388

N
Nick Cameron 已提交
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
                // `[opt_ident]: loop { ... }`
                let loop_block = block_expr(lctx, match_expr);
                let loop_expr = expr(lctx, e.span, hir::ExprLoop(loop_block, opt_ident));

                // `mut iter => { ... }`
                let iter_arm = {
                    let iter_pat = pat_ident_binding_mode(lctx,
                                                          e.span,
                                                          iter,
                                                          hir::BindByValue(hir::MutMutable));
                    arm(vec![iter_pat], loop_expr)
                };
1401

N
Nick Cameron 已提交
1402 1403 1404 1405
                // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
                let into_iter_expr = {
                    let into_iter_path = {
                        let strs = std_path(lctx, &["iter", "IntoIterator", "into_iter"]);
1406

N
Nick Cameron 已提交
1407
                        path_global(e.span, strs)
1408 1409
                    };

N
Nick Cameron 已提交
1410 1411 1412 1413 1414
                    expr_call(lctx,
                              e.span,
                              expr_path(lctx, into_iter_path),
                              vec![head])
                };
1415

1416 1417 1418 1419 1420
                let match_expr = expr_match(lctx,
                                            e.span,
                                            into_iter_expr,
                                            vec![iter_arm],
                                            hir::MatchSource::ForLoopDesugar);
N
Nick Cameron 已提交
1421 1422

                // `{ let result = ...; result }`
N
Nick Cameron 已提交
1423
                let result_ident = lctx.str_to_ident("result");
N
Nick Cameron 已提交
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
                return expr_block(lctx,
                                  block_all(lctx,
                                            e.span,
                                            vec![stmt_let(lctx,
                                                          e.span,
                                                          false,
                                                          result_ident,
                                                          match_expr)],
                                            Some(expr_ident(lctx, e.span, result_ident))))
            }

            ExprMac(_) => panic!("Shouldn't exist here"),
        },
        span: e.span,
    })
1439 1440
}

N
Nick Cameron 已提交
1441
pub fn lower_stmt(_lctx: &LoweringContext, s: &Stmt) -> P<hir::Stmt> {
1442 1443 1444
    match s.node {
        StmtDecl(ref d, id) => {
            P(Spanned {
N
Nick Cameron 已提交
1445
                node: hir::StmtDecl(lower_decl(_lctx, d), id),
N
Nick Cameron 已提交
1446
                span: s.span,
1447 1448 1449 1450
            })
        }
        StmtExpr(ref e, id) => {
            P(Spanned {
N
Nick Cameron 已提交
1451
                node: hir::StmtExpr(lower_expr(_lctx, e), id),
N
Nick Cameron 已提交
1452
                span: s.span,
1453 1454 1455 1456
            })
        }
        StmtSemi(ref e, id) => {
            P(Spanned {
N
Nick Cameron 已提交
1457
                node: hir::StmtSemi(lower_expr(_lctx, e), id),
N
Nick Cameron 已提交
1458
                span: s.span,
1459 1460
            })
        }
N
Nick Cameron 已提交
1461
        StmtMac(..) => panic!("Shouldn't exist here"),
1462 1463 1464
    }
}

N
Nick Cameron 已提交
1465
pub fn lower_capture_clause(_lctx: &LoweringContext, c: CaptureClause) -> hir::CaptureClause {
1466 1467 1468 1469 1470 1471
    match c {
        CaptureByValue => hir::CaptureByValue,
        CaptureByRef => hir::CaptureByRef,
    }
}

N
Nick Cameron 已提交
1472
pub fn lower_visibility(_lctx: &LoweringContext, v: Visibility) -> hir::Visibility {
1473 1474 1475 1476 1477 1478
    match v {
        Public => hir::Public,
        Inherited => hir::Inherited,
    }
}

N
Nick Cameron 已提交
1479
pub fn lower_block_check_mode(_lctx: &LoweringContext, b: &BlockCheckMode) -> hir::BlockCheckMode {
1480 1481
    match *b {
        DefaultBlock => hir::DefaultBlock,
N
Nick Cameron 已提交
1482 1483 1484
        UnsafeBlock(u) => hir::UnsafeBlock(lower_unsafe_source(_lctx, u)),
        PushUnsafeBlock(u) => hir::PushUnsafeBlock(lower_unsafe_source(_lctx, u)),
        PopUnsafeBlock(u) => hir::PopUnsafeBlock(lower_unsafe_source(_lctx, u)),
1485 1486 1487
    }
}

N
Nick Cameron 已提交
1488
pub fn lower_pat_wild_kind(_lctx: &LoweringContext, p: PatWildKind) -> hir::PatWildKind {
1489 1490 1491 1492 1493 1494
    match p {
        PatWildSingle => hir::PatWildSingle,
        PatWildMulti => hir::PatWildMulti,
    }
}

N
Nick Cameron 已提交
1495
pub fn lower_binding_mode(_lctx: &LoweringContext, b: &BindingMode) -> hir::BindingMode {
1496
    match *b {
N
Nick Cameron 已提交
1497 1498
        BindByRef(m) => hir::BindByRef(lower_mutability(_lctx, m)),
        BindByValue(m) => hir::BindByValue(lower_mutability(_lctx, m)),
1499 1500 1501
    }
}

N
Nick Cameron 已提交
1502 1503 1504
pub fn lower_struct_field_kind(_lctx: &LoweringContext,
                               s: &StructFieldKind)
                               -> hir::StructFieldKind {
1505
    match *s {
N
Nick Cameron 已提交
1506 1507
        NamedField(ident, vis) => hir::NamedField(ident.name, lower_visibility(_lctx, vis)),
        UnnamedField(vis) => hir::UnnamedField(lower_visibility(_lctx, vis)),
1508 1509 1510
    }
}

N
Nick Cameron 已提交
1511
pub fn lower_unsafe_source(_lctx: &LoweringContext, u: UnsafeSource) -> hir::UnsafeSource {
1512 1513 1514 1515 1516 1517
    match u {
        CompilerGenerated => hir::CompilerGenerated,
        UserProvided => hir::UserProvided,
    }
}

N
Nick Cameron 已提交
1518
pub fn lower_impl_polarity(_lctx: &LoweringContext, i: ImplPolarity) -> hir::ImplPolarity {
1519 1520 1521 1522 1523 1524
    match i {
        ImplPolarity::Positive => hir::ImplPolarity::Positive,
        ImplPolarity::Negative => hir::ImplPolarity::Negative,
    }
}

N
Nick Cameron 已提交
1525 1526 1527
pub fn lower_trait_bound_modifier(_lctx: &LoweringContext,
                                  f: TraitBoundModifier)
                                  -> hir::TraitBoundModifier {
1528 1529 1530 1531 1532
    match f {
        TraitBoundModifier::None => hir::TraitBoundModifier::None,
        TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
    }
}
1533 1534 1535 1536 1537 1538 1539 1540

// Helper methods for building HIR.

fn arm(pats: Vec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
    hir::Arm {
        attrs: vec!(),
        pats: pats,
        guard: None,
N
Nick Cameron 已提交
1541
        body: expr,
1542 1543 1544 1545 1546 1547 1548
    }
}

fn expr_break(lctx: &LoweringContext, span: Span) -> P<hir::Expr> {
    expr(lctx, span, hir::ExprBreak(None))
}

N
Nick Cameron 已提交
1549 1550 1551 1552 1553
fn expr_call(lctx: &LoweringContext,
             span: Span,
             e: P<hir::Expr>,
             args: Vec<P<hir::Expr>>)
             -> P<hir::Expr> {
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
    expr(lctx, span, hir::ExprCall(e, args))
}

fn expr_ident(lctx: &LoweringContext, span: Span, id: Ident) -> P<hir::Expr> {
    expr_path(lctx, path_ident(span, id))
}

fn expr_mut_addr_of(lctx: &LoweringContext, span: Span, e: P<hir::Expr>) -> P<hir::Expr> {
    expr(lctx, span, hir::ExprAddrOf(hir::MutMutable, e))
}

fn expr_path(lctx: &LoweringContext, path: hir::Path) -> P<hir::Expr> {
    expr(lctx, path.span, hir::ExprPath(None, path))
}

N
Nick Cameron 已提交
1569 1570 1571
fn expr_match(lctx: &LoweringContext,
              span: Span,
              arg: P<hir::Expr>,
1572 1573
              arms: Vec<hir::Arm>,
              source: hir::MatchSource)
N
Nick Cameron 已提交
1574 1575 1576
              -> P<hir::Expr> {
    expr(lctx,
         span,
1577
         hir::ExprMatch(arg, arms, source))
1578 1579 1580 1581 1582 1583
}

fn expr_block(lctx: &LoweringContext, b: P<hir::Block>) -> P<hir::Expr> {
    expr(lctx, b.span, hir::ExprBlock(b))
}

N
Nick Cameron 已提交
1584 1585 1586 1587
fn expr_tuple(lctx: &LoweringContext, sp: Span, exprs: Vec<P<hir::Expr>>) -> P<hir::Expr> {
    expr(lctx, sp, hir::ExprTup(exprs))
}

1588 1589 1590 1591 1592 1593 1594 1595
fn expr(lctx: &LoweringContext, span: Span, node: hir::Expr_) -> P<hir::Expr> {
    P(hir::Expr {
        id: lctx.next_id(),
        node: node,
        span: span,
    })
}

N
Nick Cameron 已提交
1596 1597 1598 1599 1600 1601
fn stmt_let(lctx: &LoweringContext,
            sp: Span,
            mutbl: bool,
            ident: Ident,
            ex: P<hir::Expr>)
            -> P<hir::Stmt> {
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
    let pat = if mutbl {
        pat_ident_binding_mode(lctx, sp, ident, hir::BindByValue(hir::MutMutable))
    } else {
        pat_ident(lctx, sp, ident)
    };
    let local = P(hir::Local {
        pat: pat,
        ty: None,
        init: Some(ex),
        id: lctx.next_id(),
        span: sp,
    });
    let decl = respan(sp, hir::DeclLocal(local));
    P(respan(sp, hir::StmtDecl(P(decl), lctx.next_id())))
}

fn block_expr(lctx: &LoweringContext, expr: P<hir::Expr>) -> P<hir::Block> {
    block_all(lctx, expr.span, Vec::new(), Some(expr))
}

fn block_all(lctx: &LoweringContext,
             span: Span,
             stmts: Vec<P<hir::Stmt>>,
N
Nick Cameron 已提交
1625 1626 1627 1628 1629 1630 1631 1632 1633
             expr: Option<P<hir::Expr>>)
             -> P<hir::Block> {
    P(hir::Block {
        stmts: stmts,
        expr: expr,
        id: lctx.next_id(),
        rules: hir::DefaultBlock,
        span: span,
    })
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
}

fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
    let some = std_path(lctx, &["option", "Option", "Some"]);
    let path = path_global(span, some);
    pat_enum(lctx, span, path, vec!(pat))
}

fn pat_none(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
    let none = std_path(lctx, &["option", "Option", "None"]);
    let path = path_global(span, none);
    pat_enum(lctx, span, path, vec![])
}

N
Nick Cameron 已提交
1648 1649 1650 1651 1652
fn pat_enum(lctx: &LoweringContext,
            span: Span,
            path: hir::Path,
            subpats: Vec<P<hir::Pat>>)
            -> P<hir::Pat> {
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
    let pt = hir::PatEnum(path, Some(subpats));
    pat(lctx, span, pt)
}

fn pat_ident(lctx: &LoweringContext, span: Span, ident: Ident) -> P<hir::Pat> {
    pat_ident_binding_mode(lctx, span, ident, hir::BindByValue(hir::MutImmutable))
}

fn pat_ident_binding_mode(lctx: &LoweringContext,
                          span: Span,
                          ident: Ident,
N
Nick Cameron 已提交
1664 1665 1666 1667 1668 1669 1670 1671
                          bm: hir::BindingMode)
                          -> P<hir::Pat> {
    let pat_ident = hir::PatIdent(bm,
                                  Spanned {
                                      span: span,
                                      node: ident,
                                  },
                                  None);
1672 1673 1674
    pat(lctx, span, pat_ident)
}

N
Nick Cameron 已提交
1675 1676 1677 1678
fn pat_wild(lctx: &LoweringContext, span: Span) -> P<hir::Pat> {
    pat(lctx, span, hir::PatWild(hir::PatWildSingle))
}

1679
fn pat(lctx: &LoweringContext, span: Span, pat: hir::Pat_) -> P<hir::Pat> {
N
Nick Cameron 已提交
1680 1681 1682 1683 1684
    P(hir::Pat {
        id: lctx.next_id(),
        node: pat,
        span: span,
    })
1685 1686 1687 1688 1689 1690
}

fn path_ident(span: Span, id: Ident) -> hir::Path {
    path(span, vec!(id))
}

N
Nick Cameron 已提交
1691
fn path(span: Span, strs: Vec<Ident>) -> hir::Path {
1692 1693 1694
    path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new())
}

N
Nick Cameron 已提交
1695
fn path_global(span: Span, strs: Vec<Ident>) -> hir::Path {
1696 1697 1698 1699 1700
    path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new())
}

fn path_all(sp: Span,
            global: bool,
N
Nick Cameron 已提交
1701
            mut idents: Vec<Ident>,
1702 1703
            lifetimes: Vec<hir::Lifetime>,
            types: Vec<P<hir::Ty>>,
N
Nick Cameron 已提交
1704
            bindings: Vec<P<hir::TypeBinding>>)
1705 1706 1707 1708
            -> hir::Path {
    let last_identifier = idents.pop().unwrap();
    let mut segments: Vec<hir::PathSegment> = idents.into_iter()
                                                    .map(|ident| {
N
Nick Cameron 已提交
1709 1710 1711 1712 1713 1714
                                                        hir::PathSegment {
                                                            identifier: ident,
                                                            parameters: hir::PathParameters::none(),
                                                        }
                                                    })
                                                    .collect();
1715 1716 1717 1718 1719 1720
    segments.push(hir::PathSegment {
        identifier: last_identifier,
        parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
            lifetimes: lifetimes,
            types: OwnedSlice::from_vec(types),
            bindings: OwnedSlice::from_vec(bindings),
N
Nick Cameron 已提交
1721
        }),
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
    });
    hir::Path {
        span: sp,
        global: global,
        segments: segments,
    }
}

fn std_path(lctx: &LoweringContext, components: &[&str]) -> Vec<Ident> {
    let mut v = Vec::new();
    if let Some(s) = lctx.crate_root {
        v.push(str_to_ident(s));
    }
    v.extend(components.iter().map(|s| str_to_ident(s)));
    return v
}
1738 1739 1740 1741 1742 1743 1744 1745

// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
fn core_path(lctx: &LoweringContext, span: Span, components: &[&str]) -> hir::Path {
    let idents = std_path(lctx, components);
    path_global(span, idents)
}

N
Nick Cameron 已提交
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
fn signal_block_expr(lctx: &LoweringContext,
                     stmts: Vec<P<hir::Stmt>>,
                     expr: P<hir::Expr>,
                     span: Span,
                     rule: hir::BlockCheckMode)
                     -> P<hir::Expr> {
    expr_block(lctx,
               P(hir::Block {
                   rules: rule,
                   span: span,
                   id: lctx.next_id(),
                   stmts: stmts,
                   expr: Some(expr),
               }))
1760
}
N
Nick Cameron 已提交
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860



#[cfg(test)]
mod test {
    use super::*;
    use syntax::ast::{self, NodeId, NodeIdAssigner};
    use syntax::{parse, codemap};
    use syntax::fold::Folder;
    use std::cell::Cell;

    struct MockAssigner {
        next_id: Cell<NodeId>,
    }

    impl MockAssigner {
        fn new() -> MockAssigner {
            MockAssigner {
                next_id: Cell::new(0),
            }
        }
    }

    trait FakeExtCtxt {
        fn call_site(&self) -> codemap::Span;
        fn cfg(&self) -> ast::CrateConfig;
        fn ident_of(&self, st: &str) -> ast::Ident;
        fn name_of(&self, st: &str) -> ast::Name;
        fn parse_sess(&self) -> &parse::ParseSess;
    }

    impl FakeExtCtxt for parse::ParseSess {
        fn call_site(&self) -> codemap::Span {
            codemap::Span {
                lo: codemap::BytePos(0),
                hi: codemap::BytePos(0),
                expn_id: codemap::NO_EXPANSION,
            }
        }
        fn cfg(&self) -> ast::CrateConfig { Vec::new() }
        fn ident_of(&self, st: &str) -> ast::Ident {
            parse::token::str_to_ident(st)
        }
        fn name_of(&self, st: &str) -> ast::Name {
            parse::token::intern(st)
        }
        fn parse_sess(&self) -> &parse::ParseSess { self }
    }

    impl NodeIdAssigner for MockAssigner {
        fn next_node_id(&self) -> NodeId {
            let result = self.next_id.get();
            self.next_id.set(result + 1);
            result
        }

        fn peek_node_id(&self) -> NodeId {
            self.next_id.get()
        }
    }

    impl Folder for MockAssigner {
        fn new_id(&mut self, old_id: NodeId) -> NodeId {
            assert_eq!(old_id, ast::DUMMY_NODE_ID);
            self.next_node_id()
        }
    }

    #[test]
    fn test_preserves_ids() {
        let cx = parse::ParseSess::new();
        let mut assigner = MockAssigner::new();

        let ast_if_let = quote_expr!(&cx, if let Some(foo) = baz { bar(foo); });
        let ast_if_let = assigner.fold_expr(ast_if_let);
        let ast_while_let = quote_expr!(&cx, while let Some(foo) = baz { bar(foo); });
        let ast_while_let = assigner.fold_expr(ast_while_let);
        let ast_for = quote_expr!(&cx, for i in 0..10 { foo(i); });
        let ast_for = assigner.fold_expr(ast_for);
        let ast_in = quote_expr!(&cx, in HEAP { foo() });
        let ast_in = assigner.fold_expr(ast_in);

        let lctx = LoweringContext::new(&assigner, None);
        let hir1 = lower_expr(&lctx, &ast_if_let);
        let hir2 = lower_expr(&lctx, &ast_if_let);
        assert!(hir1 == hir2);

        let hir1 = lower_expr(&lctx, &ast_while_let);
        let hir2 = lower_expr(&lctx, &ast_while_let);
        assert!(hir1 == hir2);

        let hir1 = lower_expr(&lctx, &ast_for);
        let hir2 = lower_expr(&lctx, &ast_for);
        assert!(hir1 == hir2);

        let hir1 = lower_expr(&lctx, &ast_in);
        let hir2 = lower_expr(&lctx, &ast_in);
        assert!(hir1 == hir2);
    }
}