1 // Copyright 2012-2014 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.
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.
11 #[allow(non_camel_case_types)];
13 use metadata::csearch;
14 use middle::astencode;
17 use middle::typeck::astconv;
21 use syntax::parse::token::InternedString;
22 use syntax::visit::Visitor;
24 use syntax::{ast, ast_map, ast_util};
26 use std::cell::RefCell;
27 use collections::HashMap;
31 // This pass classifies expressions by their constant-ness.
33 // Constant-ness comes in 3 flavours:
35 // - Integer-constants: can be evaluated by the frontend all the way down
36 // to their actual value. They are used in a few places (enum
37 // discriminants, switch arms) and are a subset of
38 // general-constants. They cover all the integer and integer-ish
39 // literals (nil, bool, int, uint, char, iNN, uNN) and all integer
40 // operators and copies applied to them.
42 // - General-constants: can be evaluated by LLVM but not necessarily by
43 // the frontend; usually due to reliance on target-specific stuff such
44 // as "where in memory the value goes" or "what floating point mode the
45 // target uses". This _includes_ integer-constants, plus the following
48 // fixed-size vectors and strings: [] and ""/_
49 // vector and string slices: &[] and &""
53 // floating point literals and operators
55 // copies of general constants
57 // (in theory, probably not at first: if/match on integer-const
58 // conditions / descriminants)
60 // - Non-constants: everything else.
69 type constness_cache = HashMap<ast::DefId, constness>;
71 pub fn join(a: constness, b: constness) -> constness {
73 (integral_const, integral_const) => integral_const,
74 (integral_const, general_const)
75 | (general_const, integral_const)
76 | (general_const, general_const) => general_const,
81 pub fn join_all<It: Iterator<constness>>(mut cs: It) -> constness {
82 cs.fold(integral_const, |a, b| join(a, b))
85 pub fn lookup_const(tcx: ty::ctxt, e: &Expr) -> Option<@Expr> {
87 let def_map = tcx.def_map.borrow();
88 def_map.get().find_copy(&e.id)
91 Some(ast::DefStatic(def_id, false)) => {
92 lookup_const_by_id(tcx, def_id)
94 Some(ast::DefVariant(enum_def, variant_def, _)) => {
95 lookup_variant_by_id(tcx, enum_def, variant_def)
101 pub fn lookup_variant_by_id(tcx: ty::ctxt,
102 enum_def: ast::DefId,
103 variant_def: ast::DefId)
105 fn variant_expr(variants: &[ast::P<ast::Variant>], id: ast::NodeId) -> Option<@Expr> {
106 for variant in variants.iter() {
107 if variant.node.id == id {
108 return variant.node.disr_expr;
114 if ast_util::is_local(enum_def) {
116 match tcx.map.find(enum_def.node) {
118 Some(ast_map::NodeItem(it)) => match it.node {
119 ItemEnum(ast::EnumDef { variants: ref variants }, _) => {
120 variant_expr(*variants, variant_def.node)
129 let extern_const_variants = tcx.extern_const_variants.borrow();
130 match extern_const_variants.get().find(&variant_def) {
131 Some(&e) => return e,
135 let maps = astencode::Maps {
136 root_map: @RefCell::new(HashMap::new()),
137 method_map: @RefCell::new(HashMap::new()),
138 vtable_map: @RefCell::new(HashMap::new()),
139 capture_map: @RefCell::new(HashMap::new())
141 let e = match csearch::maybe_get_item_ast(tcx, enum_def,
142 |a, b, c, d| astencode::decode_inlined_item(a, b,
145 csearch::found(ast::IIItem(item)) => match item.node {
146 ItemEnum(ast::EnumDef { variants: ref variants }, _) => {
147 variant_expr(*variants, variant_def.node)
154 let mut extern_const_variants = tcx.extern_const_variants
156 extern_const_variants.get().insert(variant_def, e);
162 pub fn lookup_const_by_id(tcx: ty::ctxt, def_id: ast::DefId)
164 if ast_util::is_local(def_id) {
166 match tcx.map.find(def_id.node) {
168 Some(ast_map::NodeItem(it)) => match it.node {
169 ItemStatic(_, ast::MutImmutable, const_expr) => {
179 let extern_const_statics = tcx.extern_const_statics.borrow();
180 match extern_const_statics.get().find(&def_id) {
181 Some(&e) => return e,
185 let maps = astencode::Maps {
186 root_map: @RefCell::new(HashMap::new()),
187 method_map: @RefCell::new(HashMap::new()),
188 vtable_map: @RefCell::new(HashMap::new()),
189 capture_map: @RefCell::new(HashMap::new())
191 let e = match csearch::maybe_get_item_ast(tcx, def_id,
192 |a, b, c, d| astencode::decode_inlined_item(a, b, maps, c, d)) {
193 csearch::found(ast::IIItem(item)) => match item.node {
194 ItemStatic(_, ast::MutImmutable, const_expr) => Some(const_expr),
200 let mut extern_const_statics = tcx.extern_const_statics
202 extern_const_statics.get().insert(def_id, e);
208 struct ConstEvalVisitor {
210 ccache: constness_cache,
213 impl ConstEvalVisitor {
214 fn classify(&mut self, e: &Expr) -> constness {
215 let did = ast_util::local_def(e.id);
216 match self.ccache.find(&did) {
217 Some(&x) => return x,
220 let cn = match e.node {
221 ast::ExprLit(lit) => {
223 ast::LitStr(..) | ast::LitFloat(..) => general_const,
228 ast::ExprUnary(_, inner) | ast::ExprParen(inner) =>
229 self.classify(inner),
231 ast::ExprBinary(_, a, b) =>
232 join(self.classify(a), self.classify(b)),
234 ast::ExprTup(ref es) |
235 ast::ExprVec(ref es, ast::MutImmutable) =>
236 join_all(es.iter().map(|e| self.classify(*e))),
238 ast::ExprVstore(e, vstore) => {
240 ast::ExprVstoreSlice => self.classify(e),
241 ast::ExprVstoreUniq |
242 ast::ExprVstoreMutSlice => non_const
246 ast::ExprStruct(_, ref fs, None) => {
247 let cs = fs.iter().map(|f| self.classify(f.expr));
251 ast::ExprCast(base, _) => {
252 let ty = ty::expr_ty(self.tcx, e);
253 let base = self.classify(base);
254 if ty::type_is_integral(ty) {
255 join(integral_const, base)
256 } else if ty::type_is_fp(ty) {
257 join(general_const, base)
263 ast::ExprField(base, _, _) => self.classify(base),
265 ast::ExprIndex(base, idx) =>
266 join(self.classify(base), self.classify(idx)),
268 ast::ExprAddrOf(ast::MutImmutable, base) => self.classify(base),
270 // FIXME: (#3728) we can probably do something CCI-ish
271 // surrounding nonlocal constants. But we don't yet.
272 ast::ExprPath(_) => self.lookup_constness(e),
274 ast::ExprRepeat(..) => general_const,
278 self.ccache.insert(did, cn);
282 fn lookup_constness(&self, e: &Expr) -> constness {
283 match lookup_const(self.tcx, e) {
285 let ty = ty::expr_ty(self.tcx, rhs);
286 if ty::type_is_integral(ty) {
298 impl Visitor<()> for ConstEvalVisitor {
299 fn visit_expr_post(&mut self, e: &Expr, _: ()) {
304 pub fn process_crate(krate: &ast::Crate,
306 let mut v = ConstEvalVisitor {
308 ccache: HashMap::new(),
310 visit::walk_crate(&mut v, krate, ());
311 tcx.sess.abort_if_errors();
315 // FIXME (#33): this doesn't handle big integer/float literals correctly
316 // (nor does the rest of our literal handling).
317 #[deriving(Clone, Eq)]
322 const_str(InternedString),
323 const_binary(Rc<~[u8]>),
327 pub fn eval_const_expr(tcx: middle::ty::ctxt, e: &Expr) -> const_val {
328 match eval_const_expr_partial(&tcx, e) {
330 Err(s) => tcx.sess.span_fatal(e.span, s)
334 pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &Expr)
335 -> Result<const_val, ~str> {
337 fn fromb(b: bool) -> Result<const_val, ~str> { Ok(const_int(b as i64)) }
339 ExprUnary(UnNeg, inner) => {
340 match eval_const_expr_partial(tcx, inner) {
341 Ok(const_float(f)) => Ok(const_float(-f)),
342 Ok(const_int(i)) => Ok(const_int(-i)),
343 Ok(const_uint(i)) => Ok(const_uint(-i)),
344 Ok(const_str(_)) => Err(~"negate on string"),
345 Ok(const_bool(_)) => Err(~"negate on boolean"),
346 ref err => ((*err).clone())
349 ExprUnary(UnNot, inner) => {
350 match eval_const_expr_partial(tcx, inner) {
351 Ok(const_int(i)) => Ok(const_int(!i)),
352 Ok(const_uint(i)) => Ok(const_uint(!i)),
353 Ok(const_bool(b)) => Ok(const_bool(!b)),
354 _ => Err(~"not on float or string")
357 ExprBinary(op, a, b) => {
358 match (eval_const_expr_partial(tcx, a),
359 eval_const_expr_partial(tcx, b)) {
360 (Ok(const_float(a)), Ok(const_float(b))) => {
362 BiAdd => Ok(const_float(a + b)),
363 BiSub => Ok(const_float(a - b)),
364 BiMul => Ok(const_float(a * b)),
365 BiDiv => Ok(const_float(a / b)),
366 BiRem => Ok(const_float(a % b)),
367 BiEq => fromb(a == b),
368 BiLt => fromb(a < b),
369 BiLe => fromb(a <= b),
370 BiNe => fromb(a != b),
371 BiGe => fromb(a >= b),
372 BiGt => fromb(a > b),
373 _ => Err(~"can't do this op on floats")
376 (Ok(const_int(a)), Ok(const_int(b))) => {
378 BiAdd => Ok(const_int(a + b)),
379 BiSub => Ok(const_int(a - b)),
380 BiMul => Ok(const_int(a * b)),
381 BiDiv if b == 0 => Err(~"attempted to divide by zero"),
382 BiDiv => Ok(const_int(a / b)),
383 BiRem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
384 BiRem => Ok(const_int(a % b)),
385 BiAnd | BiBitAnd => Ok(const_int(a & b)),
386 BiOr | BiBitOr => Ok(const_int(a | b)),
387 BiBitXor => Ok(const_int(a ^ b)),
388 BiShl => Ok(const_int(a << b)),
389 BiShr => Ok(const_int(a >> b)),
390 BiEq => fromb(a == b),
391 BiLt => fromb(a < b),
392 BiLe => fromb(a <= b),
393 BiNe => fromb(a != b),
394 BiGe => fromb(a >= b),
398 (Ok(const_uint(a)), Ok(const_uint(b))) => {
400 BiAdd => Ok(const_uint(a + b)),
401 BiSub => Ok(const_uint(a - b)),
402 BiMul => Ok(const_uint(a * b)),
403 BiDiv if b == 0 => Err(~"attempted to divide by zero"),
404 BiDiv => Ok(const_uint(a / b)),
405 BiRem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
406 BiRem => Ok(const_uint(a % b)),
407 BiAnd | BiBitAnd => Ok(const_uint(a & b)),
408 BiOr | BiBitOr => Ok(const_uint(a | b)),
409 BiBitXor => Ok(const_uint(a ^ b)),
410 BiShl => Ok(const_uint(a << b)),
411 BiShr => Ok(const_uint(a >> b)),
412 BiEq => fromb(a == b),
413 BiLt => fromb(a < b),
414 BiLe => fromb(a <= b),
415 BiNe => fromb(a != b),
416 BiGe => fromb(a >= b),
417 BiGt => fromb(a > b),
420 // shifts can have any integral type as their rhs
421 (Ok(const_int(a)), Ok(const_uint(b))) => {
423 BiShl => Ok(const_int(a << b)),
424 BiShr => Ok(const_int(a >> b)),
425 _ => Err(~"can't do this op on an int and uint")
428 (Ok(const_uint(a)), Ok(const_int(b))) => {
430 BiShl => Ok(const_uint(a << b)),
431 BiShr => Ok(const_uint(a >> b)),
432 _ => Err(~"can't do this op on a uint and int")
435 (Ok(const_bool(a)), Ok(const_bool(b))) => {
436 Ok(const_bool(match op {
444 _ => return Err(~"can't do this op on bools")
447 _ => Err(~"bad operands for binary")
450 ExprCast(base, target_ty) => {
451 // This tends to get called w/o the type actually having been
452 // populated in the ctxt, which was causing things to blow up
453 // (#5900). Fall back to doing a limited lookup to get past it.
454 let ety = ty::expr_ty_opt(tcx.ty_ctxt(), e)
455 .or_else(|| astconv::ast_ty_to_prim_ty(tcx.ty_ctxt(), target_ty))
456 .unwrap_or_else(|| tcx.ty_ctxt().sess.span_fatal(
458 format!("target type not found for const cast")
461 let base = eval_const_expr_partial(tcx, base);
465 match ty::get(ety).sty {
468 const_uint(u) => Ok(const_float(u as f64)),
469 const_int(i) => Ok(const_float(i as f64)),
470 const_float(f) => Ok(const_float(f)),
471 _ => Err(~"can't cast float to str"),
476 const_uint(u) => Ok(const_uint(u)),
477 const_int(i) => Ok(const_uint(i as u64)),
478 const_float(f) => Ok(const_uint(f as u64)),
479 _ => Err(~"can't cast str to uint"),
482 ty::ty_int(_) | ty::ty_bool => {
484 const_uint(u) => Ok(const_int(u as i64)),
485 const_int(i) => Ok(const_int(i)),
486 const_float(f) => Ok(const_int(f as i64)),
487 _ => Err(~"can't cast str to int"),
490 _ => Err(~"can't cast this type")
496 match lookup_const(tcx.ty_ctxt(), e) {
497 Some(actual_e) => eval_const_expr_partial(&tcx.ty_ctxt(), actual_e),
498 None => Err(~"non-constant path in constant expr")
501 ExprLit(lit) => Ok(lit_to_const(lit)),
502 // If we have a vstore, just keep going; it has to be a string
503 ExprVstore(e, _) => eval_const_expr_partial(tcx, e),
504 ExprParen(e) => eval_const_expr_partial(tcx, e),
505 _ => Err(~"unsupported constant expr")
509 pub fn lit_to_const(lit: &Lit) -> const_val {
511 LitStr(ref s, _) => const_str((*s).clone()),
512 LitBinary(ref data) => const_binary(data.clone()),
513 LitChar(n) => const_uint(n as u64),
514 LitInt(n, _) => const_int(n),
515 LitUint(n, _) => const_uint(n),
516 LitIntUnsuffixed(n) => const_int(n),
517 LitFloat(ref n, _) | LitFloatUnsuffixed(ref n) => {
518 const_float(from_str::<f64>(n.get()).unwrap() as f64)
520 LitNil => const_int(0i64),
521 LitBool(b) => const_bool(b)
525 fn compare_vals<T : Eq + Ord>(a: T, b: T) -> Option<int> {
526 Some(if a == b { 0 } else if a < b { -1 } else { 1 })
528 pub fn compare_const_vals(a: &const_val, b: &const_val) -> Option<int> {
530 (&const_int(a), &const_int(b)) => compare_vals(a, b),
531 (&const_uint(a), &const_uint(b)) => compare_vals(a, b),
532 (&const_float(a), &const_float(b)) => compare_vals(a, b),
533 (&const_str(ref a), &const_str(ref b)) => compare_vals(a, b),
534 (&const_bool(a), &const_bool(b)) => compare_vals(a, b),
539 pub fn compare_lit_exprs(tcx: middle::ty::ctxt, a: &Expr, b: &Expr) -> Option<int> {
540 compare_const_vals(&eval_const_expr(tcx, a), &eval_const_expr(tcx, b))
543 pub fn lit_expr_eq(tcx: middle::ty::ctxt, a: &Expr, b: &Expr) -> Option<bool> {
544 compare_lit_exprs(tcx, a, b).map(|val| val == 0)
547 pub fn lit_eq(a: &Lit, b: &Lit) -> Option<bool> {
548 compare_const_vals(&lit_to_const(a), &lit_to_const(b)).map(|val| val == 0)