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)]
12 #![allow(unsigned_negate)]
14 use metadata::csearch;
15 use middle::astencode;
17 use middle::pat_util::def_to_path;
19 use middle::typeck::astconv;
20 use util::nodemap::{DefIdMap};
23 use syntax::parse::token::InternedString;
24 use syntax::visit::Visitor;
26 use syntax::{ast, ast_map, ast_util};
29 use std::gc::{Gc, GC};
32 // This pass classifies expressions by their constant-ness.
34 // Constant-ness comes in 3 flavours:
36 // - Integer-constants: can be evaluated by the frontend all the way down
37 // to their actual value. They are used in a few places (enum
38 // discriminants, switch arms) and are a subset of
39 // general-constants. They cover all the integer and integer-ish
40 // literals (nil, bool, int, uint, char, iNN, uNN) and all integer
41 // operators and copies applied to them.
43 // - General-constants: can be evaluated by LLVM but not necessarily by
44 // the frontend; usually due to reliance on target-specific stuff such
45 // as "where in memory the value goes" or "what floating point mode the
46 // target uses". This _includes_ integer-constants, plus the following
49 // fixed-size vectors and strings: [] and ""/_
50 // 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<Gc<Expr>> {
86 let opt_def = tcx.def_map.borrow().find_copy(&e.id);
88 Some(def::DefStatic(def_id, false)) => {
89 lookup_const_by_id(tcx, def_id)
91 Some(def::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)
101 -> Option<Gc<Expr>> {
102 fn variant_expr(variants: &[ast::P<ast::Variant>],
103 id: ast::NodeId) -> Option<Gc<Expr>> {
104 for variant in variants.iter() {
105 if variant.node.id == id {
106 return variant.node.disr_expr;
112 if ast_util::is_local(enum_def) {
114 match tcx.map.find(enum_def.node) {
116 Some(ast_map::NodeItem(it)) => match it.node {
117 ItemEnum(ast::EnumDef { variants: ref variants }, _) => {
118 variant_expr(variants.as_slice(), variant_def.node)
126 match tcx.extern_const_variants.borrow().find(&variant_def) {
127 Some(&e) => return e,
130 let e = match csearch::maybe_get_item_ast(tcx, enum_def,
131 |a, b, c, d| astencode::decode_inlined_item(a, b, c, d)) {
132 csearch::found(ast::IIItem(item)) => match item.node {
133 ItemEnum(ast::EnumDef { variants: ref variants }, _) => {
134 variant_expr(variants.as_slice(), variant_def.node)
140 tcx.extern_const_variants.borrow_mut().insert(variant_def, e);
145 pub fn lookup_const_by_id(tcx: &ty::ctxt, def_id: ast::DefId)
146 -> Option<Gc<Expr>> {
147 if ast_util::is_local(def_id) {
149 match tcx.map.find(def_id.node) {
151 Some(ast_map::NodeItem(it)) => match it.node {
152 ItemStatic(_, ast::MutImmutable, const_expr) => {
161 match tcx.extern_const_statics.borrow().find(&def_id) {
162 Some(&e) => return e,
165 let e = match csearch::maybe_get_item_ast(tcx, def_id,
166 |a, b, c, d| astencode::decode_inlined_item(a, b, c, d)) {
167 csearch::found(ast::IIItem(item)) => match item.node {
168 ItemStatic(_, ast::MutImmutable, const_expr) => Some(const_expr),
173 tcx.extern_const_statics.borrow_mut().insert(def_id, e);
178 struct ConstEvalVisitor<'a> {
180 ccache: constness_cache,
183 impl<'a> ConstEvalVisitor<'a> {
184 fn classify(&mut self, e: &Expr) -> constness {
185 let did = ast_util::local_def(e.id);
186 match self.ccache.find(&did) {
187 Some(&x) => return x,
190 let cn = match e.node {
191 ast::ExprLit(ref lit) => {
193 ast::LitStr(..) | ast::LitFloat(..) => general_const,
198 ast::ExprUnary(_, ref inner) | ast::ExprParen(ref inner) =>
199 self.classify(&**inner),
201 ast::ExprBinary(_, ref a, ref b) =>
202 join(self.classify(&**a), self.classify(&**b)),
204 ast::ExprTup(ref es) |
205 ast::ExprVec(ref es) =>
206 join_all(es.iter().map(|e| self.classify(&**e))),
208 ast::ExprVstore(ref e, vstore) => {
210 ast::ExprVstoreSlice => self.classify(&**e),
211 ast::ExprVstoreUniq |
212 ast::ExprVstoreMutSlice => non_const
216 ast::ExprStruct(_, ref fs, None) => {
217 let cs = fs.iter().map(|f| self.classify(&*f.expr));
221 ast::ExprCast(ref base, _) => {
222 let ty = ty::expr_ty(self.tcx, e);
223 let base = self.classify(&**base);
224 if ty::type_is_integral(ty) {
225 join(integral_const, base)
226 } else if ty::type_is_fp(ty) {
227 join(general_const, base)
233 ast::ExprField(ref base, _, _) => self.classify(&**base),
235 ast::ExprIndex(ref base, ref idx) =>
236 join(self.classify(&**base), self.classify(&**idx)),
238 ast::ExprAddrOf(ast::MutImmutable, ref base) =>
239 self.classify(&**base),
241 // FIXME: (#3728) we can probably do something CCI-ish
242 // surrounding nonlocal constants. But we don't yet.
243 ast::ExprPath(_) => self.lookup_constness(e),
245 ast::ExprRepeat(..) => general_const,
247 ast::ExprBlock(ref block) => {
249 Some(ref e) => self.classify(&**e),
250 None => integral_const
256 self.ccache.insert(did, cn);
260 fn lookup_constness(&self, e: &Expr) -> constness {
261 match lookup_const(self.tcx, e) {
263 let ty = ty::expr_ty(self.tcx, &*rhs);
264 if ty::type_is_integral(ty) {
276 impl<'a> Visitor<()> for ConstEvalVisitor<'a> {
277 fn visit_expr_post(&mut self, e: &Expr, _: ()) {
282 pub fn process_crate(krate: &ast::Crate,
284 let mut v = ConstEvalVisitor {
286 ccache: DefIdMap::new(),
288 visit::walk_crate(&mut v, krate, ());
289 tcx.sess.abort_if_errors();
293 // FIXME (#33): this doesn't handle big integer/float literals correctly
294 // (nor does the rest of our literal handling).
295 #[deriving(Clone, PartialEq)]
300 const_str(InternedString),
301 const_binary(Rc<Vec<u8> >),
306 pub fn const_expr_to_pat(tcx: &ty::ctxt, expr: Gc<Expr>) -> Gc<Pat> {
307 let pat = match expr.node {
308 ExprTup(ref exprs) =>
309 PatTup(exprs.iter().map(|&expr| const_expr_to_pat(tcx, expr)).collect()),
311 ExprCall(callee, ref args) => {
312 let def = tcx.def_map.borrow().get_copy(&callee.id);
313 tcx.def_map.borrow_mut().find_or_insert(expr.id, def);
314 let path = match def {
315 def::DefStruct(def_id) => def_to_path(tcx, def_id),
316 def::DefVariant(_, variant_did, _) => def_to_path(tcx, variant_did),
319 let pats = args.iter().map(|&expr| const_expr_to_pat(tcx, expr)).collect();
320 PatEnum(path, Some(pats))
323 ExprStruct(ref path, ref fields, None) => {
324 let field_pats = fields.iter().map(|field| FieldPat {
325 ident: field.ident.node,
326 pat: const_expr_to_pat(tcx, field.expr)
328 PatStruct(path.clone(), field_pats, false)
331 ExprVec(ref exprs) => {
332 let pats = exprs.iter().map(|&expr| const_expr_to_pat(tcx, expr)).collect();
333 PatVec(pats, None, vec![])
336 ExprPath(ref path) => {
337 let opt_def = tcx.def_map.borrow().find_copy(&expr.id);
339 Some(def::DefStruct(..)) =>
340 PatStruct(path.clone(), vec![], false),
341 Some(def::DefVariant(..)) =>
342 PatEnum(path.clone(), None),
344 match lookup_const(tcx, &*expr) {
345 Some(actual) => return const_expr_to_pat(tcx, actual),
354 box (GC) Pat { id: expr.id, node: pat, span: expr.span }
357 pub fn eval_const_expr(tcx: &ty::ctxt, e: &Expr) -> const_val {
358 match eval_const_expr_partial(tcx, e) {
360 Err(s) => tcx.sess.span_fatal(e.span, s.as_slice())
364 pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &Expr)
365 -> Result<const_val, String> {
366 fn fromb(b: bool) -> Result<const_val, String> { Ok(const_int(b as i64)) }
368 ExprUnary(UnNeg, ref inner) => {
369 match eval_const_expr_partial(tcx, &**inner) {
370 Ok(const_float(f)) => Ok(const_float(-f)),
371 Ok(const_int(i)) => Ok(const_int(-i)),
372 Ok(const_uint(i)) => Ok(const_uint(-i)),
373 Ok(const_str(_)) => Err("negate on string".to_string()),
374 Ok(const_bool(_)) => Err("negate on boolean".to_string()),
375 ref err => ((*err).clone())
378 ExprUnary(UnNot, ref inner) => {
379 match eval_const_expr_partial(tcx, &**inner) {
380 Ok(const_int(i)) => Ok(const_int(!i)),
381 Ok(const_uint(i)) => Ok(const_uint(!i)),
382 Ok(const_bool(b)) => Ok(const_bool(!b)),
383 _ => Err("not on float or string".to_string())
386 ExprBinary(op, ref a, ref b) => {
387 match (eval_const_expr_partial(tcx, &**a),
388 eval_const_expr_partial(tcx, &**b)) {
389 (Ok(const_float(a)), Ok(const_float(b))) => {
391 BiAdd => Ok(const_float(a + b)),
392 BiSub => Ok(const_float(a - b)),
393 BiMul => Ok(const_float(a * b)),
394 BiDiv => Ok(const_float(a / b)),
395 BiRem => Ok(const_float(a % b)),
396 BiEq => fromb(a == b),
397 BiLt => fromb(a < b),
398 BiLe => fromb(a <= b),
399 BiNe => fromb(a != b),
400 BiGe => fromb(a >= b),
401 BiGt => fromb(a > b),
402 _ => Err("can't do this op on floats".to_string())
405 (Ok(const_int(a)), Ok(const_int(b))) => {
407 BiAdd => Ok(const_int(a + b)),
408 BiSub => Ok(const_int(a - b)),
409 BiMul => Ok(const_int(a * b)),
411 Err("attempted to divide by zero".to_string())
413 BiDiv => Ok(const_int(a / b)),
415 Err("attempted remainder with a divisor of \
418 BiRem => Ok(const_int(a % b)),
419 BiAnd | BiBitAnd => Ok(const_int(a & b)),
420 BiOr | BiBitOr => Ok(const_int(a | b)),
421 BiBitXor => Ok(const_int(a ^ b)),
422 BiShl => Ok(const_int(a << b as uint)),
423 BiShr => Ok(const_int(a >> b as uint)),
424 BiEq => fromb(a == b),
425 BiLt => fromb(a < b),
426 BiLe => fromb(a <= b),
427 BiNe => fromb(a != b),
428 BiGe => fromb(a >= b),
432 (Ok(const_uint(a)), Ok(const_uint(b))) => {
434 BiAdd => Ok(const_uint(a + b)),
435 BiSub => Ok(const_uint(a - b)),
436 BiMul => Ok(const_uint(a * b)),
438 Err("attempted to divide by zero".to_string())
440 BiDiv => Ok(const_uint(a / b)),
442 Err("attempted remainder with a divisor of \
445 BiRem => Ok(const_uint(a % b)),
446 BiAnd | BiBitAnd => Ok(const_uint(a & b)),
447 BiOr | BiBitOr => Ok(const_uint(a | b)),
448 BiBitXor => Ok(const_uint(a ^ b)),
449 BiShl => Ok(const_uint(a << b as uint)),
450 BiShr => Ok(const_uint(a >> b as uint)),
451 BiEq => fromb(a == b),
452 BiLt => fromb(a < b),
453 BiLe => fromb(a <= b),
454 BiNe => fromb(a != b),
455 BiGe => fromb(a >= b),
456 BiGt => fromb(a > b),
459 // shifts can have any integral type as their rhs
460 (Ok(const_int(a)), Ok(const_uint(b))) => {
462 BiShl => Ok(const_int(a << b as uint)),
463 BiShr => Ok(const_int(a >> b as uint)),
464 _ => Err("can't do this op on an int and uint".to_string())
467 (Ok(const_uint(a)), Ok(const_int(b))) => {
469 BiShl => Ok(const_uint(a << b as uint)),
470 BiShr => Ok(const_uint(a >> b as uint)),
471 _ => Err("can't do this op on a uint and int".to_string())
474 (Ok(const_bool(a)), Ok(const_bool(b))) => {
475 Ok(const_bool(match op {
483 _ => return Err("can't do this op on bools".to_string())
486 _ => Err("bad operands for binary".to_string())
489 ExprCast(ref base, ref target_ty) => {
490 // This tends to get called w/o the type actually having been
491 // populated in the ctxt, which was causing things to blow up
492 // (#5900). Fall back to doing a limited lookup to get past it.
493 let ety = ty::expr_ty_opt(tcx.ty_ctxt(), e)
494 .or_else(|| astconv::ast_ty_to_prim_ty(tcx.ty_ctxt(), &**target_ty))
496 tcx.ty_ctxt().sess.span_fatal(target_ty.span,
497 "target type not found for \
501 let base = eval_const_expr_partial(tcx, &**base);
505 match ty::get(ety).sty {
508 const_uint(u) => Ok(const_float(u as f64)),
509 const_int(i) => Ok(const_float(i as f64)),
510 const_float(f) => Ok(const_float(f)),
511 _ => Err("can't cast float to str".to_string()),
516 const_uint(u) => Ok(const_uint(u)),
517 const_int(i) => Ok(const_uint(i as u64)),
518 const_float(f) => Ok(const_uint(f as u64)),
519 _ => Err("can't cast str to uint".to_string()),
522 ty::ty_int(_) | ty::ty_bool => {
524 const_uint(u) => Ok(const_int(u as i64)),
525 const_int(i) => Ok(const_int(i)),
526 const_float(f) => Ok(const_int(f as i64)),
527 _ => Err("can't cast str to int".to_string()),
530 _ => Err("can't cast this type".to_string())
536 match lookup_const(tcx.ty_ctxt(), e) {
537 Some(actual_e) => eval_const_expr_partial(tcx.ty_ctxt(), &*actual_e),
538 None => Err("non-constant path in constant expr".to_string())
541 ExprLit(ref lit) => Ok(lit_to_const(&**lit)),
542 // If we have a vstore, just keep going; it has to be a string
543 ExprVstore(ref e, _) => eval_const_expr_partial(tcx, &**e),
544 ExprParen(ref e) => eval_const_expr_partial(tcx, &**e),
545 ExprBlock(ref block) => {
547 Some(ref expr) => eval_const_expr_partial(tcx, &**expr),
548 None => Ok(const_int(0i64))
551 _ => Err("unsupported constant expr".to_string())
555 pub fn lit_to_const(lit: &Lit) -> const_val {
557 LitStr(ref s, _) => const_str((*s).clone()),
558 LitBinary(ref data) => {
559 const_binary(Rc::new(data.iter().map(|x| *x).collect()))
561 LitByte(n) => const_uint(n as u64),
562 LitChar(n) => const_uint(n as u64),
563 LitInt(n, _) => const_int(n),
564 LitUint(n, _) => const_uint(n),
565 LitIntUnsuffixed(n) => const_int(n),
566 LitFloat(ref n, _) | LitFloatUnsuffixed(ref n) => {
567 const_float(from_str::<f64>(n.get()).unwrap() as f64)
570 LitBool(b) => const_bool(b)
574 fn compare_vals<T: PartialOrd>(a: T, b: T) -> Option<int> {
575 Some(if a == b { 0 } else if a < b { -1 } else { 1 })
577 pub fn compare_const_vals(a: &const_val, b: &const_val) -> Option<int> {
579 (&const_int(a), &const_int(b)) => compare_vals(a, b),
580 (&const_uint(a), &const_uint(b)) => compare_vals(a, b),
581 (&const_float(a), &const_float(b)) => compare_vals(a, b),
582 (&const_str(ref a), &const_str(ref b)) => compare_vals(a, b),
583 (&const_bool(a), &const_bool(b)) => compare_vals(a, b),
584 (&const_binary(ref a), &const_binary(ref b)) => compare_vals(a, b),
585 (&const_nil, &const_nil) => compare_vals((), ()),
590 pub fn compare_lit_exprs(tcx: &ty::ctxt, a: &Expr, b: &Expr) -> Option<int> {
591 compare_const_vals(&eval_const_expr(tcx, a), &eval_const_expr(tcx, b))