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> {
86 let opt_def = tcx.def_map.borrow().find_copy(&e.id);
88 Some(ast::DefStatic(def_id, false)) => {
89 lookup_const_by_id(tcx, def_id)
91 Some(ast::DefVariant(enum_def, variant_def, _)) => {
92 lookup_variant_by_id(tcx, enum_def, variant_def)
98 pub fn lookup_variant_by_id(tcx: &ty::ctxt,
100 variant_def: ast::DefId)
102 fn variant_expr(variants: &[ast::P<ast::Variant>], id: ast::NodeId) -> Option<@Expr> {
103 for variant in variants.iter() {
104 if variant.node.id == id {
105 return variant.node.disr_expr;
111 if ast_util::is_local(enum_def) {
113 match tcx.map.find(enum_def.node) {
115 Some(ast_map::NodeItem(it)) => match it.node {
116 ItemEnum(ast::EnumDef { variants: ref variants }, _) => {
117 variant_expr(variants.as_slice(), variant_def.node)
125 match tcx.extern_const_variants.borrow().find(&variant_def) {
126 Some(&e) => return e,
129 let maps = astencode::Maps {
130 root_map: @RefCell::new(HashMap::new()),
131 method_map: @RefCell::new(FnvHashMap::new()),
132 vtable_map: @RefCell::new(FnvHashMap::new()),
133 capture_map: RefCell::new(NodeMap::new())
135 let e = match csearch::maybe_get_item_ast(tcx, enum_def,
136 |a, b, c, d| astencode::decode_inlined_item(a, b, &maps, c, d)) {
137 csearch::found(ast::IIItem(item)) => match item.node {
138 ItemEnum(ast::EnumDef { variants: ref variants }, _) => {
139 variant_expr(variants.as_slice(), variant_def.node)
145 tcx.extern_const_variants.borrow_mut().insert(variant_def, e);
150 pub fn lookup_const_by_id(tcx: &ty::ctxt, def_id: ast::DefId)
152 if ast_util::is_local(def_id) {
154 match tcx.map.find(def_id.node) {
156 Some(ast_map::NodeItem(it)) => match it.node {
157 ItemStatic(_, ast::MutImmutable, const_expr) => {
166 match tcx.extern_const_statics.borrow().find(&def_id) {
167 Some(&e) => return e,
170 let maps = astencode::Maps {
171 root_map: @RefCell::new(HashMap::new()),
172 method_map: @RefCell::new(FnvHashMap::new()),
173 vtable_map: @RefCell::new(FnvHashMap::new()),
174 capture_map: RefCell::new(NodeMap::new())
176 let e = match csearch::maybe_get_item_ast(tcx, def_id,
177 |a, b, c, d| astencode::decode_inlined_item(a, b, &maps, c, d)) {
178 csearch::found(ast::IIItem(item)) => match item.node {
179 ItemStatic(_, ast::MutImmutable, const_expr) => Some(const_expr),
184 tcx.extern_const_statics.borrow_mut().insert(def_id, e);
189 struct ConstEvalVisitor<'a> {
191 ccache: constness_cache,
194 impl<'a> ConstEvalVisitor<'a> {
195 fn classify(&mut self, e: &Expr) -> constness {
196 let did = ast_util::local_def(e.id);
197 match self.ccache.find(&did) {
198 Some(&x) => return x,
201 let cn = match e.node {
202 ast::ExprLit(lit) => {
204 ast::LitStr(..) | ast::LitFloat(..) => general_const,
209 ast::ExprUnary(_, inner) | ast::ExprParen(inner) =>
210 self.classify(inner),
212 ast::ExprBinary(_, a, b) =>
213 join(self.classify(a), self.classify(b)),
215 ast::ExprTup(ref es) |
216 ast::ExprVec(ref es, ast::MutImmutable) =>
217 join_all(es.iter().map(|e| self.classify(*e))),
219 ast::ExprVstore(e, vstore) => {
221 ast::ExprVstoreSlice => self.classify(e),
222 ast::ExprVstoreUniq |
223 ast::ExprVstoreMutSlice => non_const
227 ast::ExprStruct(_, ref fs, None) => {
228 let cs = fs.iter().map(|f| self.classify(f.expr));
232 ast::ExprCast(base, _) => {
233 let ty = ty::expr_ty(self.tcx, e);
234 let base = self.classify(base);
235 if ty::type_is_integral(ty) {
236 join(integral_const, base)
237 } else if ty::type_is_fp(ty) {
238 join(general_const, base)
244 ast::ExprField(base, _, _) => self.classify(base),
246 ast::ExprIndex(base, idx) =>
247 join(self.classify(base), self.classify(idx)),
249 ast::ExprAddrOf(ast::MutImmutable, base) => self.classify(base),
251 // FIXME: (#3728) we can probably do something CCI-ish
252 // surrounding nonlocal constants. But we don't yet.
253 ast::ExprPath(_) => self.lookup_constness(e),
255 ast::ExprRepeat(..) => general_const,
259 self.ccache.insert(did, cn);
263 fn lookup_constness(&self, e: &Expr) -> constness {
264 match lookup_const(self.tcx, e) {
266 let ty = ty::expr_ty(self.tcx, rhs);
267 if ty::type_is_integral(ty) {
279 impl<'a> Visitor<()> for ConstEvalVisitor<'a> {
280 fn visit_expr_post(&mut self, e: &Expr, _: ()) {
285 pub fn process_crate(krate: &ast::Crate,
287 let mut v = ConstEvalVisitor {
289 ccache: DefIdMap::new(),
291 visit::walk_crate(&mut v, krate, ());
292 tcx.sess.abort_if_errors();
296 // FIXME (#33): this doesn't handle big integer/float literals correctly
297 // (nor does the rest of our literal handling).
298 #[deriving(Clone, Eq)]
303 const_str(InternedString),
304 const_binary(Rc<Vec<u8> >),
308 pub fn eval_const_expr(tcx: &ty::ctxt, e: &Expr) -> const_val {
309 match eval_const_expr_partial(tcx, e) {
311 Err(s) => tcx.sess.span_fatal(e.span, s)
315 pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &Expr)
316 -> Result<const_val, ~str> {
317 fn fromb(b: bool) -> Result<const_val, ~str> { Ok(const_int(b as i64)) }
319 ExprUnary(UnNeg, inner) => {
320 match eval_const_expr_partial(tcx, inner) {
321 Ok(const_float(f)) => Ok(const_float(-f)),
322 Ok(const_int(i)) => Ok(const_int(-i)),
323 Ok(const_uint(i)) => Ok(const_uint(-i)),
324 Ok(const_str(_)) => Err(~"negate on string"),
325 Ok(const_bool(_)) => Err(~"negate on boolean"),
326 ref err => ((*err).clone())
329 ExprUnary(UnNot, inner) => {
330 match eval_const_expr_partial(tcx, inner) {
331 Ok(const_int(i)) => Ok(const_int(!i)),
332 Ok(const_uint(i)) => Ok(const_uint(!i)),
333 Ok(const_bool(b)) => Ok(const_bool(!b)),
334 _ => Err(~"not on float or string")
337 ExprBinary(op, a, b) => {
338 match (eval_const_expr_partial(tcx, a),
339 eval_const_expr_partial(tcx, b)) {
340 (Ok(const_float(a)), Ok(const_float(b))) => {
342 BiAdd => Ok(const_float(a + b)),
343 BiSub => Ok(const_float(a - b)),
344 BiMul => Ok(const_float(a * b)),
345 BiDiv => Ok(const_float(a / b)),
346 BiRem => Ok(const_float(a % b)),
347 BiEq => fromb(a == b),
348 BiLt => fromb(a < b),
349 BiLe => fromb(a <= b),
350 BiNe => fromb(a != b),
351 BiGe => fromb(a >= b),
352 BiGt => fromb(a > b),
353 _ => Err(~"can't do this op on floats")
356 (Ok(const_int(a)), Ok(const_int(b))) => {
358 BiAdd => Ok(const_int(a + b)),
359 BiSub => Ok(const_int(a - b)),
360 BiMul => Ok(const_int(a * b)),
361 BiDiv if b == 0 => Err(~"attempted to divide by zero"),
362 BiDiv => Ok(const_int(a / b)),
363 BiRem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
364 BiRem => Ok(const_int(a % b)),
365 BiAnd | BiBitAnd => Ok(const_int(a & b)),
366 BiOr | BiBitOr => Ok(const_int(a | b)),
367 BiBitXor => Ok(const_int(a ^ b)),
368 BiShl => Ok(const_int(a << b)),
369 BiShr => Ok(const_int(a >> b)),
370 BiEq => fromb(a == b),
371 BiLt => fromb(a < b),
372 BiLe => fromb(a <= b),
373 BiNe => fromb(a != b),
374 BiGe => fromb(a >= b),
378 (Ok(const_uint(a)), Ok(const_uint(b))) => {
380 BiAdd => Ok(const_uint(a + b)),
381 BiSub => Ok(const_uint(a - b)),
382 BiMul => Ok(const_uint(a * b)),
383 BiDiv if b == 0 => Err(~"attempted to divide by zero"),
384 BiDiv => Ok(const_uint(a / b)),
385 BiRem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
386 BiRem => Ok(const_uint(a % b)),
387 BiAnd | BiBitAnd => Ok(const_uint(a & b)),
388 BiOr | BiBitOr => Ok(const_uint(a | b)),
389 BiBitXor => Ok(const_uint(a ^ b)),
390 BiShl => Ok(const_uint(a << b)),
391 BiShr => Ok(const_uint(a >> b)),
392 BiEq => fromb(a == b),
393 BiLt => fromb(a < b),
394 BiLe => fromb(a <= b),
395 BiNe => fromb(a != b),
396 BiGe => fromb(a >= b),
397 BiGt => fromb(a > b),
400 // shifts can have any integral type as their rhs
401 (Ok(const_int(a)), Ok(const_uint(b))) => {
403 BiShl => Ok(const_int(a << b)),
404 BiShr => Ok(const_int(a >> b)),
405 _ => Err(~"can't do this op on an int and uint")
408 (Ok(const_uint(a)), Ok(const_int(b))) => {
410 BiShl => Ok(const_uint(a << b)),
411 BiShr => Ok(const_uint(a >> b)),
412 _ => Err(~"can't do this op on a uint and int")
415 (Ok(const_bool(a)), Ok(const_bool(b))) => {
416 Ok(const_bool(match op {
424 _ => return Err(~"can't do this op on bools")
427 _ => Err(~"bad operands for binary")
430 ExprCast(base, target_ty) => {
431 // This tends to get called w/o the type actually having been
432 // populated in the ctxt, which was causing things to blow up
433 // (#5900). Fall back to doing a limited lookup to get past it.
434 let ety = ty::expr_ty_opt(tcx.ty_ctxt(), e)
435 .or_else(|| astconv::ast_ty_to_prim_ty(tcx.ty_ctxt(), target_ty))
436 .unwrap_or_else(|| tcx.ty_ctxt().sess.span_fatal(
438 format!("target type not found for const cast")
441 let base = eval_const_expr_partial(tcx, base);
445 match ty::get(ety).sty {
448 const_uint(u) => Ok(const_float(u as f64)),
449 const_int(i) => Ok(const_float(i as f64)),
450 const_float(f) => Ok(const_float(f)),
451 _ => Err(~"can't cast float to str"),
456 const_uint(u) => Ok(const_uint(u)),
457 const_int(i) => Ok(const_uint(i as u64)),
458 const_float(f) => Ok(const_uint(f as u64)),
459 _ => Err(~"can't cast str to uint"),
462 ty::ty_int(_) | ty::ty_bool => {
464 const_uint(u) => Ok(const_int(u as i64)),
465 const_int(i) => Ok(const_int(i)),
466 const_float(f) => Ok(const_int(f as i64)),
467 _ => Err(~"can't cast str to int"),
470 _ => Err(~"can't cast this type")
476 match lookup_const(tcx.ty_ctxt(), e) {
477 Some(actual_e) => eval_const_expr_partial(tcx.ty_ctxt(), actual_e),
478 None => Err(~"non-constant path in constant expr")
481 ExprLit(lit) => Ok(lit_to_const(lit)),
482 // If we have a vstore, just keep going; it has to be a string
483 ExprVstore(e, _) => eval_const_expr_partial(tcx, e),
484 ExprParen(e) => eval_const_expr_partial(tcx, e),
485 _ => Err(~"unsupported constant expr")
489 pub fn lit_to_const(lit: &Lit) -> const_val {
491 LitStr(ref s, _) => const_str((*s).clone()),
492 LitBinary(ref data) => {
493 const_binary(Rc::new(data.iter().map(|x| *x).collect()))
495 LitChar(n) => const_uint(n as u64),
496 LitInt(n, _) => const_int(n),
497 LitUint(n, _) => const_uint(n),
498 LitIntUnsuffixed(n) => const_int(n),
499 LitFloat(ref n, _) | LitFloatUnsuffixed(ref n) => {
500 const_float(from_str::<f64>(n.get()).unwrap() as f64)
502 LitNil => const_int(0i64),
503 LitBool(b) => const_bool(b)
507 fn compare_vals<T: Ord>(a: T, b: T) -> Option<int> {
508 Some(if a == b { 0 } else if a < b { -1 } else { 1 })
510 pub fn compare_const_vals(a: &const_val, b: &const_val) -> Option<int> {
512 (&const_int(a), &const_int(b)) => compare_vals(a, b),
513 (&const_uint(a), &const_uint(b)) => compare_vals(a, b),
514 (&const_float(a), &const_float(b)) => compare_vals(a, b),
515 (&const_str(ref a), &const_str(ref b)) => compare_vals(a, b),
516 (&const_bool(a), &const_bool(b)) => compare_vals(a, b),
521 pub fn compare_lit_exprs(tcx: &ty::ctxt, a: &Expr, b: &Expr) -> Option<int> {
522 compare_const_vals(&eval_const_expr(tcx, a), &eval_const_expr(tcx, b))
525 pub fn lit_expr_eq(tcx: &ty::ctxt, a: &Expr, b: &Expr) -> Option<bool> {
526 compare_lit_exprs(tcx, a, b).map(|val| val == 0)
529 pub fn lit_eq(a: &Lit, b: &Lit) -> Option<bool> {
530 compare_const_vals(&lit_to_const(a), &lit_to_const(b)).map(|val| val == 0)