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;
18 use util::nodemap::{DefIdMap, FnvHashMap, NodeMap};
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 = DefIdMap<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.as_slice(), variant_def.node)
128 match tcx.extern_const_variants.borrow().get().find(&variant_def) {
129 Some(&e) => return e,
132 let maps = astencode::Maps {
133 root_map: @RefCell::new(HashMap::new()),
134 method_map: @RefCell::new(FnvHashMap::new()),
135 vtable_map: @RefCell::new(NodeMap::new()),
136 capture_map: RefCell::new(NodeMap::new())
138 let e = match csearch::maybe_get_item_ast(tcx, enum_def,
139 |a, b, c, d| astencode::decode_inlined_item(a, b, &maps, c, d)) {
140 csearch::found(ast::IIItem(item)) => match item.node {
141 ItemEnum(ast::EnumDef { variants: ref variants }, _) => {
142 variant_expr(variants.as_slice(), variant_def.node)
148 tcx.extern_const_variants.borrow_mut().get().insert(variant_def, e);
153 pub fn lookup_const_by_id(tcx: &ty::ctxt, def_id: ast::DefId)
155 if ast_util::is_local(def_id) {
157 match tcx.map.find(def_id.node) {
159 Some(ast_map::NodeItem(it)) => match it.node {
160 ItemStatic(_, ast::MutImmutable, const_expr) => {
170 let extern_const_statics = tcx.extern_const_statics.borrow();
171 match extern_const_statics.get().find(&def_id) {
172 Some(&e) => return e,
176 let maps = astencode::Maps {
177 root_map: @RefCell::new(HashMap::new()),
178 method_map: @RefCell::new(FnvHashMap::new()),
179 vtable_map: @RefCell::new(NodeMap::new()),
180 capture_map: RefCell::new(NodeMap::new())
182 let e = match csearch::maybe_get_item_ast(tcx, def_id,
183 |a, b, c, d| astencode::decode_inlined_item(a, b, &maps, c, d)) {
184 csearch::found(ast::IIItem(item)) => match item.node {
185 ItemStatic(_, ast::MutImmutable, const_expr) => Some(const_expr),
191 let mut extern_const_statics = tcx.extern_const_statics
193 extern_const_statics.get().insert(def_id, e);
199 struct ConstEvalVisitor<'a> {
201 ccache: constness_cache,
204 impl<'a> ConstEvalVisitor<'a> {
205 fn classify(&mut self, e: &Expr) -> constness {
206 let did = ast_util::local_def(e.id);
207 match self.ccache.find(&did) {
208 Some(&x) => return x,
211 let cn = match e.node {
212 ast::ExprLit(lit) => {
214 ast::LitStr(..) | ast::LitFloat(..) => general_const,
219 ast::ExprUnary(_, inner) | ast::ExprParen(inner) =>
220 self.classify(inner),
222 ast::ExprBinary(_, a, b) =>
223 join(self.classify(a), self.classify(b)),
225 ast::ExprTup(ref es) |
226 ast::ExprVec(ref es, ast::MutImmutable) =>
227 join_all(es.iter().map(|e| self.classify(*e))),
229 ast::ExprVstore(e, vstore) => {
231 ast::ExprVstoreSlice => self.classify(e),
232 ast::ExprVstoreUniq |
233 ast::ExprVstoreMutSlice => non_const
237 ast::ExprStruct(_, ref fs, None) => {
238 let cs = fs.iter().map(|f| self.classify(f.expr));
242 ast::ExprCast(base, _) => {
243 let ty = ty::expr_ty(self.tcx, e);
244 let base = self.classify(base);
245 if ty::type_is_integral(ty) {
246 join(integral_const, base)
247 } else if ty::type_is_fp(ty) {
248 join(general_const, base)
254 ast::ExprField(base, _, _) => self.classify(base),
256 ast::ExprIndex(base, idx) =>
257 join(self.classify(base), self.classify(idx)),
259 ast::ExprAddrOf(ast::MutImmutable, base) => self.classify(base),
261 // FIXME: (#3728) we can probably do something CCI-ish
262 // surrounding nonlocal constants. But we don't yet.
263 ast::ExprPath(_) => self.lookup_constness(e),
265 ast::ExprRepeat(..) => general_const,
269 self.ccache.insert(did, cn);
273 fn lookup_constness(&self, e: &Expr) -> constness {
274 match lookup_const(self.tcx, e) {
276 let ty = ty::expr_ty(self.tcx, rhs);
277 if ty::type_is_integral(ty) {
289 impl<'a> Visitor<()> for ConstEvalVisitor<'a> {
290 fn visit_expr_post(&mut self, e: &Expr, _: ()) {
295 pub fn process_crate(krate: &ast::Crate,
297 let mut v = ConstEvalVisitor {
299 ccache: DefIdMap::new(),
301 visit::walk_crate(&mut v, krate, ());
302 tcx.sess.abort_if_errors();
306 // FIXME (#33): this doesn't handle big integer/float literals correctly
307 // (nor does the rest of our literal handling).
308 #[deriving(Clone, Eq)]
313 const_str(InternedString),
314 const_binary(Rc<Vec<u8> >),
318 pub fn eval_const_expr(tcx: &ty::ctxt, e: &Expr) -> const_val {
319 match eval_const_expr_partial(tcx, e) {
321 Err(s) => tcx.sess.span_fatal(e.span, s)
325 pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &Expr)
326 -> Result<const_val, ~str> {
327 fn fromb(b: bool) -> Result<const_val, ~str> { Ok(const_int(b as i64)) }
329 ExprUnary(UnNeg, inner) => {
330 match eval_const_expr_partial(tcx, inner) {
331 Ok(const_float(f)) => Ok(const_float(-f)),
332 Ok(const_int(i)) => Ok(const_int(-i)),
333 Ok(const_uint(i)) => Ok(const_uint(-i)),
334 Ok(const_str(_)) => Err(~"negate on string"),
335 Ok(const_bool(_)) => Err(~"negate on boolean"),
336 ref err => ((*err).clone())
339 ExprUnary(UnNot, inner) => {
340 match eval_const_expr_partial(tcx, inner) {
341 Ok(const_int(i)) => Ok(const_int(!i)),
342 Ok(const_uint(i)) => Ok(const_uint(!i)),
343 Ok(const_bool(b)) => Ok(const_bool(!b)),
344 _ => Err(~"not on float or string")
347 ExprBinary(op, a, b) => {
348 match (eval_const_expr_partial(tcx, a),
349 eval_const_expr_partial(tcx, b)) {
350 (Ok(const_float(a)), Ok(const_float(b))) => {
352 BiAdd => Ok(const_float(a + b)),
353 BiSub => Ok(const_float(a - b)),
354 BiMul => Ok(const_float(a * b)),
355 BiDiv => Ok(const_float(a / b)),
356 BiRem => Ok(const_float(a % b)),
357 BiEq => fromb(a == b),
358 BiLt => fromb(a < b),
359 BiLe => fromb(a <= b),
360 BiNe => fromb(a != b),
361 BiGe => fromb(a >= b),
362 BiGt => fromb(a > b),
363 _ => Err(~"can't do this op on floats")
366 (Ok(const_int(a)), Ok(const_int(b))) => {
368 BiAdd => Ok(const_int(a + b)),
369 BiSub => Ok(const_int(a - b)),
370 BiMul => Ok(const_int(a * b)),
371 BiDiv if b == 0 => Err(~"attempted to divide by zero"),
372 BiDiv => Ok(const_int(a / b)),
373 BiRem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
374 BiRem => Ok(const_int(a % b)),
375 BiAnd | BiBitAnd => Ok(const_int(a & b)),
376 BiOr | BiBitOr => Ok(const_int(a | b)),
377 BiBitXor => Ok(const_int(a ^ b)),
378 BiShl => Ok(const_int(a << b)),
379 BiShr => Ok(const_int(a >> b)),
380 BiEq => fromb(a == b),
381 BiLt => fromb(a < b),
382 BiLe => fromb(a <= b),
383 BiNe => fromb(a != b),
384 BiGe => fromb(a >= b),
388 (Ok(const_uint(a)), Ok(const_uint(b))) => {
390 BiAdd => Ok(const_uint(a + b)),
391 BiSub => Ok(const_uint(a - b)),
392 BiMul => Ok(const_uint(a * b)),
393 BiDiv if b == 0 => Err(~"attempted to divide by zero"),
394 BiDiv => Ok(const_uint(a / b)),
395 BiRem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
396 BiRem => Ok(const_uint(a % b)),
397 BiAnd | BiBitAnd => Ok(const_uint(a & b)),
398 BiOr | BiBitOr => Ok(const_uint(a | b)),
399 BiBitXor => Ok(const_uint(a ^ b)),
400 BiShl => Ok(const_uint(a << b)),
401 BiShr => Ok(const_uint(a >> b)),
402 BiEq => fromb(a == b),
403 BiLt => fromb(a < b),
404 BiLe => fromb(a <= b),
405 BiNe => fromb(a != b),
406 BiGe => fromb(a >= b),
407 BiGt => fromb(a > b),
410 // shifts can have any integral type as their rhs
411 (Ok(const_int(a)), Ok(const_uint(b))) => {
413 BiShl => Ok(const_int(a << b)),
414 BiShr => Ok(const_int(a >> b)),
415 _ => Err(~"can't do this op on an int and uint")
418 (Ok(const_uint(a)), Ok(const_int(b))) => {
420 BiShl => Ok(const_uint(a << b)),
421 BiShr => Ok(const_uint(a >> b)),
422 _ => Err(~"can't do this op on a uint and int")
425 (Ok(const_bool(a)), Ok(const_bool(b))) => {
426 Ok(const_bool(match op {
434 _ => return Err(~"can't do this op on bools")
437 _ => Err(~"bad operands for binary")
440 ExprCast(base, target_ty) => {
441 // This tends to get called w/o the type actually having been
442 // populated in the ctxt, which was causing things to blow up
443 // (#5900). Fall back to doing a limited lookup to get past it.
444 let ety = ty::expr_ty_opt(tcx.ty_ctxt(), e)
445 .or_else(|| astconv::ast_ty_to_prim_ty(tcx.ty_ctxt(), target_ty))
446 .unwrap_or_else(|| tcx.ty_ctxt().sess.span_fatal(
448 format!("target type not found for const cast")
451 let base = eval_const_expr_partial(tcx, base);
455 match ty::get(ety).sty {
458 const_uint(u) => Ok(const_float(u as f64)),
459 const_int(i) => Ok(const_float(i as f64)),
460 const_float(f) => Ok(const_float(f)),
461 _ => Err(~"can't cast float to str"),
466 const_uint(u) => Ok(const_uint(u)),
467 const_int(i) => Ok(const_uint(i as u64)),
468 const_float(f) => Ok(const_uint(f as u64)),
469 _ => Err(~"can't cast str to uint"),
472 ty::ty_int(_) | ty::ty_bool => {
474 const_uint(u) => Ok(const_int(u as i64)),
475 const_int(i) => Ok(const_int(i)),
476 const_float(f) => Ok(const_int(f as i64)),
477 _ => Err(~"can't cast str to int"),
480 _ => Err(~"can't cast this type")
486 match lookup_const(tcx.ty_ctxt(), e) {
487 Some(actual_e) => eval_const_expr_partial(tcx.ty_ctxt(), actual_e),
488 None => Err(~"non-constant path in constant expr")
491 ExprLit(lit) => Ok(lit_to_const(lit)),
492 // If we have a vstore, just keep going; it has to be a string
493 ExprVstore(e, _) => eval_const_expr_partial(tcx, e),
494 ExprParen(e) => eval_const_expr_partial(tcx, e),
495 _ => Err(~"unsupported constant expr")
499 pub fn lit_to_const(lit: &Lit) -> const_val {
501 LitStr(ref s, _) => const_str((*s).clone()),
502 LitBinary(ref data) => {
503 const_binary(Rc::new(data.deref().iter().map(|x| *x).collect()))
505 LitChar(n) => const_uint(n as u64),
506 LitInt(n, _) => const_int(n),
507 LitUint(n, _) => const_uint(n),
508 LitIntUnsuffixed(n) => const_int(n),
509 LitFloat(ref n, _) | LitFloatUnsuffixed(ref n) => {
510 const_float(from_str::<f64>(n.get()).unwrap() as f64)
512 LitNil => const_int(0i64),
513 LitBool(b) => const_bool(b)
517 fn compare_vals<T: Ord>(a: T, b: T) -> Option<int> {
518 Some(if a == b { 0 } else if a < b { -1 } else { 1 })
520 pub fn compare_const_vals(a: &const_val, b: &const_val) -> Option<int> {
522 (&const_int(a), &const_int(b)) => compare_vals(a, b),
523 (&const_uint(a), &const_uint(b)) => compare_vals(a, b),
524 (&const_float(a), &const_float(b)) => compare_vals(a, b),
525 (&const_str(ref a), &const_str(ref b)) => compare_vals(a, b),
526 (&const_bool(a), &const_bool(b)) => compare_vals(a, b),
531 pub fn compare_lit_exprs(tcx: &ty::ctxt, a: &Expr, b: &Expr) -> Option<int> {
532 compare_const_vals(&eval_const_expr(tcx, a), &eval_const_expr(tcx, b))
535 pub fn lit_expr_eq(tcx: &ty::ctxt, a: &Expr, b: &Expr) -> Option<bool> {
536 compare_lit_exprs(tcx, a, b).map(|val| val == 0)
539 pub fn lit_eq(a: &Lit, b: &Lit) -> Option<bool> {
540 compare_const_vals(&lit_to_const(a), &lit_to_const(b)).map(|val| val == 0)