1 // Copyright 2012-2013 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.
12 use metadata::csearch;
13 use middle::astencode;
17 use syntax::{ast, ast_map, ast_util, oldvisit};
21 use std::hashmap::{HashMap, HashSet};
24 // This pass classifies expressions by their constant-ness.
26 // Constant-ness comes in 3 flavours:
28 // - Integer-constants: can be evaluated by the frontend all the way down
29 // to their actual value. They are used in a few places (enum
30 // discriminants, switch arms) and are a subset of
31 // general-constants. They cover all the integer and integer-ish
32 // literals (nil, bool, int, uint, char, iNN, uNN) and all integer
33 // operators and copies applied to them.
35 // - General-constants: can be evaluated by LLVM but not necessarily by
36 // the frontend; usually due to reliance on target-specific stuff such
37 // as "where in memory the value goes" or "what floating point mode the
38 // target uses". This _includes_ integer-constants, plus the following
41 // fixed-size vectors and strings: [] and ""/_
42 // vector and string slices: &[] and &""
46 // floating point literals and operators
48 // copies of general constants
50 // (in theory, probably not at first: if/match on integer-const
51 // conditions / descriminants)
53 // - Non-constants: everything else.
62 pub fn join(a: constness, b: constness) -> constness {
64 (integral_const, integral_const) => integral_const,
65 (integral_const, general_const)
66 | (general_const, integral_const)
67 | (general_const, general_const) => general_const,
72 pub fn join_all<It: Iterator<constness>>(mut cs: It) -> constness {
73 cs.fold(integral_const, |a, b| join(a, b))
76 pub fn classify(e: &expr,
79 let did = ast_util::local_def(e.id);
80 match tcx.ccache.find(&did) {
85 ast::expr_lit(lit) => {
88 ast::lit_float(*) => general_const,
93 ast::expr_unary(_, _, inner) |
94 ast::expr_paren(inner) => {
98 ast::expr_binary(_, _, a, b) => {
99 join(classify(a, tcx),
103 ast::expr_tup(ref es) |
104 ast::expr_vec(ref es, ast::m_imm) => {
105 join_all(es.iter().map(|e| classify(*e, tcx)))
108 ast::expr_vstore(e, vstore) => {
110 ast::expr_vstore_slice => classify(e, tcx),
111 ast::expr_vstore_uniq |
112 ast::expr_vstore_box |
113 ast::expr_vstore_mut_box |
114 ast::expr_vstore_mut_slice => non_const
118 ast::expr_struct(_, ref fs, None) => {
119 let cs = do fs.iter().map |f| {
120 classify(f.expr, tcx)
125 ast::expr_cast(base, _) => {
126 let ty = ty::expr_ty(tcx, e);
127 let base = classify(base, tcx);
128 if ty::type_is_integral(ty) {
129 join(integral_const, base)
130 } else if ty::type_is_fp(ty) {
131 join(general_const, base)
137 ast::expr_field(base, _, _) => {
141 ast::expr_index(_, base, idx) => {
142 join(classify(base, tcx),
146 ast::expr_addr_of(ast::m_imm, base) => {
150 // FIXME: (#3728) we can probably do something CCI-ish
151 // surrounding nonlocal constants. But we don't yet.
152 ast::expr_path(_) => {
153 lookup_constness(tcx, e)
156 ast::expr_repeat(*) => general_const,
160 tcx.ccache.insert(did, cn);
166 pub fn lookup_const(tcx: ty::ctxt, e: &expr) -> Option<@expr> {
167 match tcx.def_map.find(&e.id) {
168 Some(&ast::def_static(def_id, false)) => lookup_const_by_id(tcx, def_id),
169 Some(&ast::def_variant(enum_def, variant_def)) => lookup_variant_by_id(tcx,
176 pub fn lookup_variant_by_id(tcx: ty::ctxt,
177 enum_def: ast::def_id,
178 variant_def: ast::def_id)
180 fn variant_expr(variants: &[ast::variant], id: ast::NodeId) -> Option<@expr> {
181 for variant in variants.iter() {
182 if variant.node.id == id {
183 return variant.node.disr_expr;
189 if ast_util::is_local(enum_def) {
190 match tcx.items.find(&enum_def.node) {
192 Some(&ast_map::node_item(it, _)) => match it.node {
193 item_enum(ast::enum_def { variants: ref variants }, _) => {
194 variant_expr(*variants, variant_def.node)
201 let maps = astencode::Maps {
202 root_map: @mut HashMap::new(),
203 method_map: @mut HashMap::new(),
204 vtable_map: @mut HashMap::new(),
205 write_guard_map: @mut HashSet::new(),
206 capture_map: @mut HashMap::new()
208 match csearch::maybe_get_item_ast(tcx, enum_def,
209 |a, b, c, d| astencode::decode_inlined_item(a,
214 csearch::found(ast::ii_item(item)) => match item.node {
215 item_enum(ast::enum_def { variants: ref variants }, _) => {
216 variant_expr(*variants, variant_def.node)
225 pub fn lookup_const_by_id(tcx: ty::ctxt,
228 if ast_util::is_local(def_id) {
229 match tcx.items.find(&def_id.node) {
231 Some(&ast_map::node_item(it, _)) => match it.node {
232 item_static(_, ast::m_imm, const_expr) => Some(const_expr),
238 let maps = astencode::Maps {
239 root_map: @mut HashMap::new(),
240 method_map: @mut HashMap::new(),
241 vtable_map: @mut HashMap::new(),
242 write_guard_map: @mut HashSet::new(),
243 capture_map: @mut HashMap::new()
245 match csearch::maybe_get_item_ast(tcx, def_id,
246 |a, b, c, d| astencode::decode_inlined_item(a, b, maps, c, d)) {
247 csearch::found(ast::ii_item(item)) => match item.node {
248 item_static(_, ast::m_imm, const_expr) => Some(const_expr),
256 pub fn lookup_constness(tcx: ty::ctxt, e: &expr) -> constness {
257 match lookup_const(tcx, e) {
259 let ty = ty::expr_ty(tcx, rhs);
260 if ty::type_is_integral(ty) {
270 pub fn process_crate(crate: &ast::Crate,
272 let v = oldvisit::mk_simple_visitor(@oldvisit::SimpleVisitor {
273 visit_expr_post: |e| { classify(e, tcx); },
274 .. *oldvisit::default_simple_visitor()
276 oldvisit::visit_crate(crate, ((), v));
277 tcx.sess.abort_if_errors();
281 // FIXME (#33): this doesn't handle big integer/float literals correctly
282 // (nor does the rest of our literal handling).
283 #[deriving(Clone, Eq)]
292 pub fn eval_const_expr(tcx: middle::ty::ctxt, e: &expr) -> const_val {
293 match eval_const_expr_partial(&tcx, e) {
295 Err(s) => tcx.sess.span_fatal(e.span, s)
299 pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &expr)
300 -> Result<const_val, ~str> {
302 fn fromb(b: bool) -> Result<const_val, ~str> { Ok(const_int(b as i64)) }
304 expr_unary(_, neg, inner) => {
305 match eval_const_expr_partial(tcx, inner) {
306 Ok(const_float(f)) => Ok(const_float(-f)),
307 Ok(const_int(i)) => Ok(const_int(-i)),
308 Ok(const_uint(i)) => Ok(const_uint(-i)),
309 Ok(const_str(_)) => Err(~"Negate on string"),
310 Ok(const_bool(_)) => Err(~"Negate on boolean"),
311 ref err => ((*err).clone())
314 expr_unary(_, not, inner) => {
315 match eval_const_expr_partial(tcx, inner) {
316 Ok(const_int(i)) => Ok(const_int(!i)),
317 Ok(const_uint(i)) => Ok(const_uint(!i)),
318 Ok(const_bool(b)) => Ok(const_bool(!b)),
319 _ => Err(~"Not on float or string")
322 expr_binary(_, op, a, b) => {
323 match (eval_const_expr_partial(tcx, a),
324 eval_const_expr_partial(tcx, b)) {
325 (Ok(const_float(a)), Ok(const_float(b))) => {
327 add => Ok(const_float(a + b)),
328 subtract => Ok(const_float(a - b)),
329 mul => Ok(const_float(a * b)),
330 div => Ok(const_float(a / b)),
331 rem => Ok(const_float(a % b)),
338 _ => Err(~"Can't do this op on floats")
341 (Ok(const_int(a)), Ok(const_int(b))) => {
343 add => Ok(const_int(a + b)),
344 subtract => Ok(const_int(a - b)),
345 mul => Ok(const_int(a * b)),
346 div if b == 0 => Err(~"attempted to divide by zero"),
347 div => Ok(const_int(a / b)),
348 rem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
349 rem => Ok(const_int(a % b)),
350 and | bitand => Ok(const_int(a & b)),
351 or | bitor => Ok(const_int(a | b)),
352 bitxor => Ok(const_int(a ^ b)),
353 shl => Ok(const_int(a << b)),
354 shr => Ok(const_int(a >> b)),
363 (Ok(const_uint(a)), Ok(const_uint(b))) => {
365 add => Ok(const_uint(a + b)),
366 subtract => Ok(const_uint(a - b)),
367 mul => Ok(const_uint(a * b)),
368 div if b == 0 => Err(~"attempted to divide by zero"),
369 div => Ok(const_uint(a / b)),
370 rem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
371 rem => Ok(const_uint(a % b)),
372 and | bitand => Ok(const_uint(a & b)),
373 or | bitor => Ok(const_uint(a | b)),
374 bitxor => Ok(const_uint(a ^ b)),
375 shl => Ok(const_uint(a << b)),
376 shr => Ok(const_uint(a >> b)),
385 // shifts can have any integral type as their rhs
386 (Ok(const_int(a)), Ok(const_uint(b))) => {
388 shl => Ok(const_int(a << b)),
389 shr => Ok(const_int(a >> b)),
390 _ => Err(~"Can't do this op on an int and uint")
393 (Ok(const_uint(a)), Ok(const_int(b))) => {
395 shl => Ok(const_uint(a << b)),
396 shr => Ok(const_uint(a >> b)),
397 _ => Err(~"Can't do this op on a uint and int")
400 (Ok(const_bool(a)), Ok(const_bool(b))) => {
401 Ok(const_bool(match op {
409 _ => return Err(~"Can't do this op on bools")
412 _ => Err(~"Bad operands for binary")
415 expr_cast(base, _) => {
416 let ety = tcx.expr_ty(e);
417 let base = eval_const_expr_partial(tcx, base);
421 match ty::get(ety).sty {
424 const_uint(u) => Ok(const_float(u as f64)),
425 const_int(i) => Ok(const_float(i as f64)),
426 const_float(f) => Ok(const_float(f)),
427 _ => Err(~"Can't cast float to str"),
432 const_uint(u) => Ok(const_uint(u)),
433 const_int(i) => Ok(const_uint(i as u64)),
434 const_float(f) => Ok(const_uint(f as u64)),
435 _ => Err(~"Can't cast str to uint"),
438 ty::ty_int(_) | ty::ty_bool => {
440 const_uint(u) => Ok(const_int(u as i64)),
441 const_int(i) => Ok(const_int(i)),
442 const_float(f) => Ok(const_int(f as i64)),
443 _ => Err(~"Can't cast str to int"),
446 _ => Err(~"Can't cast this type")
452 match lookup_const(tcx.ty_ctxt(), e) {
453 Some(actual_e) => eval_const_expr_partial(&tcx.ty_ctxt(), actual_e),
454 None => Err(~"Non-constant path in constant expr")
457 expr_lit(lit) => Ok(lit_to_const(lit)),
458 // If we have a vstore, just keep going; it has to be a string
459 expr_vstore(e, _) => eval_const_expr_partial(tcx, e),
460 expr_paren(e) => eval_const_expr_partial(tcx, e),
461 _ => Err(~"Unsupported constant expr")
465 pub fn lit_to_const(lit: &lit) -> const_val {
467 lit_str(s) => const_str(s),
468 lit_int(n, _) => const_int(n),
469 lit_uint(n, _) => const_uint(n),
470 lit_int_unsuffixed(n) => const_int(n),
471 lit_float(n, _) => const_float(float::from_str(n).unwrap() as f64),
472 lit_float_unsuffixed(n) =>
473 const_float(float::from_str(n).unwrap() as f64),
474 lit_nil => const_int(0i64),
475 lit_bool(b) => const_bool(b)
479 fn compare_vals<T : Eq + Ord>(a: T, b: T) -> Option<int> {
480 Some(if a == b { 0 } else if a < b { -1 } else { 1 })
482 pub fn compare_const_vals(a: &const_val, b: &const_val) -> Option<int> {
484 (&const_int(a), &const_int(b)) => compare_vals(a, b),
485 (&const_uint(a), &const_uint(b)) => compare_vals(a, b),
486 (&const_float(a), &const_float(b)) => compare_vals(a, b),
487 (&const_str(a), &const_str(b)) => compare_vals(a, b),
488 (&const_bool(a), &const_bool(b)) => compare_vals(a, b),
493 pub fn compare_lit_exprs(tcx: middle::ty::ctxt, a: &expr, b: &expr) -> Option<int> {
494 compare_const_vals(&eval_const_expr(tcx, a), &eval_const_expr(tcx, b))
497 pub fn lit_expr_eq(tcx: middle::ty::ctxt, a: &expr, b: &expr) -> Option<bool> {
498 compare_lit_exprs(tcx, a, b).map_move(|val| val == 0)
501 pub fn lit_eq(a: &lit, b: &lit) -> Option<bool> {
502 compare_const_vals(&lit_to_const(a), &lit_to_const(b)).map_move(|val| val == 0)