1 #![allow(cast_possible_truncation)]
3 use rustc::lint::LateContext;
4 use rustc::middle::const_eval::lookup_const_by_id;
5 use rustc::middle::def::{Def, PathResolution};
6 use rustc_front::hir::*;
7 use std::cmp::Ordering::{self, Greater, Less, Equal};
8 use std::cmp::PartialOrd;
9 use std::hash::{Hash, Hasher};
13 use syntax::ast::{FloatTy, LitIntType, LitKind, StrStyle, UintTy};
16 #[derive(Debug, Copy, Clone)]
23 impl From<FloatTy> for FloatWidth {
24 fn from(ty: FloatTy) -> FloatWidth {
26 FloatTy::F32 => FloatWidth::F32,
27 FloatTy::F64 => FloatWidth::F64,
32 #[derive(Copy, Eq, Debug, Clone, PartialEq, Hash)]
38 /// a Lit_-like enum to fold constant `Expr`s into
39 #[derive(Debug, Clone)]
42 Str(String, StrStyle),
43 /// a Binary String b"abc"
45 /// a single byte b'a'
49 /// an integer, third argument is whether the value is negated
50 Int(u64, LitIntType, Sign),
51 /// a float with given type
52 Float(String, FloatWidth),
55 /// an array of constants
57 /// also an array, but with only one constant, repeated N times
58 Repeat(Box<Constant>, usize),
59 /// a tuple of constants
64 /// convert to u64 if possible
68 /// if the constant could not be converted to u64 losslessly
69 fn as_u64(&self) -> u64 {
70 if let Constant::Int(val, _, _) = *self {
71 val // TODO we may want to check the sign if any
73 panic!("Could not convert a {:?} to u64", self);
77 /// convert this constant to a f64, if possible
78 #[allow(cast_precision_loss)]
79 pub fn as_float(&self) -> Option<f64> {
81 Constant::Byte(b) => Some(b as f64),
82 Constant::Float(ref s, _) => s.parse().ok(),
83 Constant::Int(i, _, Sign::Minus) => Some(-(i as f64)),
84 Constant::Int(i, _, Sign::Plus) => Some(i as f64),
90 impl PartialEq for Constant {
91 fn eq(&self, other: &Constant) -> bool {
93 (&Constant::Str(ref ls, ref lsty), &Constant::Str(ref rs, ref rsty)) => ls == rs && lsty == rsty,
94 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
95 (&Constant::Byte(l), &Constant::Byte(r)) => l == r,
96 (&Constant::Char(l), &Constant::Char(r)) => l == r,
97 (&Constant::Int(0, _, _), &Constant::Int(0, _, _)) => true,
98 (&Constant::Int(lv, _, lneg), &Constant::Int(rv, _, rneg)) => lv == rv && lneg == rneg,
99 (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
100 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
101 // `Fw32 == Fw64` so don’t compare them
102 match (ls.parse::<f64>(), rs.parse::<f64>()) {
103 (Ok(l), Ok(r)) => l.eq(&r),
107 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
108 (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l == r,
109 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
110 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
111 _ => false, //TODO: Are there inter-type equalities?
116 impl Hash for Constant {
117 fn hash<H>(&self, state: &mut H)
121 Constant::Str(ref s, ref k) => {
125 Constant::Binary(ref b) => {
128 Constant::Byte(u) => {
131 Constant::Char(c) => {
134 Constant::Int(u, _, t) => {
138 Constant::Float(ref f, _) => {
139 // don’t use the width here because of PartialEq implementation
140 if let Ok(f) = f.parse::<f64>() {
141 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
144 Constant::Bool(b) => {
147 Constant::Vec(ref v) | Constant::Tuple(ref v) => {
150 Constant::Repeat(ref c, l) => {
158 impl PartialOrd for Constant {
159 fn partial_cmp(&self, other: &Constant) -> Option<Ordering> {
160 match (self, other) {
161 (&Constant::Str(ref ls, ref lsty), &Constant::Str(ref rs, ref rsty)) => {
168 (&Constant::Byte(ref l), &Constant::Byte(ref r)) => Some(l.cmp(r)),
169 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
170 (&Constant::Int(0, _, _), &Constant::Int(0, _, _)) => Some(Equal),
171 (&Constant::Int(ref lv, _, Sign::Plus), &Constant::Int(ref rv, _, Sign::Plus)) => Some(lv.cmp(rv)),
172 (&Constant::Int(ref lv, _, Sign::Minus), &Constant::Int(ref rv, _, Sign::Minus)) => Some(rv.cmp(lv)),
173 (&Constant::Int(_, _, Sign::Minus), &Constant::Int(_, _, Sign::Plus)) => Some(Less),
174 (&Constant::Int(_, _, Sign::Plus), &Constant::Int(_, _, Sign::Minus)) => Some(Greater),
175 (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
176 match (ls.parse::<f64>(), rs.parse::<f64>()) {
177 (Ok(ref l), Ok(ref r)) => l.partial_cmp(r),
181 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
182 (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l.partial_cmp(&r),
183 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
184 match lv.partial_cmp(rv) {
185 Some(Equal) => Some(ls.cmp(rs)),
189 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l.partial_cmp(r),
190 _ => None, //TODO: Are there any useful inter-type orderings?
195 fn lit_to_constant(lit: &LitKind) -> Constant {
197 LitKind::Str(ref is, style) => Constant::Str(is.to_string(), style),
198 LitKind::Byte(b) => Constant::Byte(b),
199 LitKind::ByteStr(ref s) => Constant::Binary(s.clone()),
200 LitKind::Char(c) => Constant::Char(c),
201 LitKind::Int(value, ty) => Constant::Int(value, ty, Sign::Plus),
202 LitKind::Float(ref is, ty) => Constant::Float(is.to_string(), ty.into()),
203 LitKind::FloatUnsuffixed(ref is) => Constant::Float(is.to_string(), FloatWidth::Any),
204 LitKind::Bool(b) => Constant::Bool(b),
208 fn constant_not(o: Constant) -> Option<Constant> {
209 use self::Constant::*;
211 Bool(b) => Some(Bool(!b)),
212 Int(value, LitIntType::Signed(ity), Sign::Plus) if value != ::std::u64::MAX => {
213 Some(Int(value + 1, LitIntType::Signed(ity), Sign::Minus))
215 Int(0, LitIntType::Signed(ity), Sign::Minus) => Some(Int(1, LitIntType::Signed(ity), Sign::Minus)),
216 Int(value, LitIntType::Signed(ity), Sign::Minus) => Some(Int(value - 1, LitIntType::Signed(ity), Sign::Plus)),
217 Int(value, LitIntType::Unsigned(ity), Sign::Plus) => {
218 let mask = match ity {
219 UintTy::U8 => ::std::u8::MAX as u64,
220 UintTy::U16 => ::std::u16::MAX as u64,
221 UintTy::U32 => ::std::u32::MAX as u64,
222 UintTy::U64 => ::std::u64::MAX,
227 Some(Int(!value & mask, LitIntType::Unsigned(ity), Sign::Plus))
233 fn constant_negate(o: Constant) -> Option<Constant> {
234 use self::Constant::*;
236 Int(value, LitIntType::Signed(ity), sign) => Some(Int(value, LitIntType::Signed(ity), neg_sign(sign))),
237 Int(value, LitIntType::Unsuffixed, sign) => Some(Int(value, LitIntType::Unsuffixed, neg_sign(sign))),
238 Float(is, ty) => Some(Float(neg_float_str(is), ty)),
243 fn neg_sign(s: Sign) -> Sign {
245 Sign::Plus => Sign::Minus,
246 Sign::Minus => Sign::Plus,
250 fn neg_float_str(s: String) -> String {
251 if s.starts_with('-') {
258 fn unify_int_type(l: LitIntType, r: LitIntType) -> Option<LitIntType> {
259 use syntax::ast::LitIntType::*;
261 (Signed(lty), Signed(rty)) => {
263 Some(LitIntType::Signed(lty))
268 (Unsigned(lty), Unsigned(rty)) => {
270 Some(LitIntType::Unsigned(lty))
275 (Unsuffixed, Unsuffixed) => Some(Unsuffixed),
276 (Signed(lty), Unsuffixed) => Some(Signed(lty)),
277 (Unsigned(lty), Unsuffixed) => Some(Unsigned(lty)),
278 (Unsuffixed, Signed(rty)) => Some(Signed(rty)),
279 (Unsuffixed, Unsigned(rty)) => Some(Unsigned(rty)),
284 pub fn constant(lcx: &LateContext, e: &Expr) -> Option<(Constant, bool)> {
285 let mut cx = ConstEvalLateContext {
287 needed_resolution: false,
289 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
292 pub fn constant_simple(e: &Expr) -> Option<Constant> {
293 let mut cx = ConstEvalLateContext {
295 needed_resolution: false,
300 struct ConstEvalLateContext<'c, 'cc: 'c> {
301 lcx: Option<&'c LateContext<'c, 'cc>>,
302 needed_resolution: bool,
305 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
306 /// simple constant folding: Insert an expression, get a constant or none.
307 fn expr(&mut self, e: &Expr) -> Option<Constant> {
309 ExprPath(_, _) => self.fetch_path(e),
310 ExprBlock(ref block) => self.block(block),
311 ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
312 ExprLit(ref lit) => Some(lit_to_constant(&lit.node)),
313 ExprVec(ref vec) => self.multi(vec).map(Constant::Vec),
314 ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
315 ExprRepeat(ref value, ref number) => {
316 self.binop_apply(value, number, |v, n| Some(Constant::Repeat(Box::new(v), n.as_u64() as usize)))
318 ExprUnary(op, ref operand) => {
319 self.expr(operand).and_then(|o| {
321 UnNot => constant_not(o),
322 UnNeg => constant_negate(o),
327 ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
328 // TODO: add other expressions
333 /// create `Some(Vec![..])` of all constants, unless there is any
334 /// non-constant part
335 fn multi<E: Deref<Target = Expr> + Sized>(&mut self, vec: &[E]) -> Option<Vec<Constant>> {
337 .map(|elem| self.expr(elem))
338 .collect::<Option<_>>()
341 /// lookup a possibly constant expression from a ExprPath
342 fn fetch_path(&mut self, e: &Expr) -> Option<Constant> {
343 if let Some(lcx) = self.lcx {
344 let mut maybe_id = None;
345 if let Some(&PathResolution { base_def: Def::Const(id), ..}) = lcx.tcx.def_map.borrow().get(&e.id) {
348 // separate if lets to avoid double borrowing the def_map
349 if let Some(id) = maybe_id {
350 if let Some(const_expr) = lookup_const_by_id(lcx.tcx, id, None, None) {
351 let ret = self.expr(const_expr);
353 self.needed_resolution = true;
362 /// A block can only yield a constant if it only has one constant expression
363 fn block(&mut self, block: &Block) -> Option<Constant> {
364 if block.stmts.is_empty() {
365 block.expr.as_ref().and_then(|ref b| self.expr(b))
371 fn ifthenelse(&mut self, cond: &Expr, then: &Block, otherwise: &Option<P<Expr>>) -> Option<Constant> {
372 if let Some(Constant::Bool(b)) = self.expr(cond) {
376 otherwise.as_ref().and_then(|expr| self.expr(expr))
383 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
386 self.binop_apply(left, right, |l, r| {
388 (Constant::Byte(l8), Constant::Byte(r8)) => l8.checked_add(r8).map(Constant::Byte),
389 (Constant::Int(l64, lty, lsign), Constant::Int(r64, rty, rsign)) => {
390 add_ints(l64, r64, lty, rty, lsign, rsign)
392 // TODO: float (would need bignum library?)
398 self.binop_apply(left, right, |l, r| {
400 (Constant::Byte(l8), Constant::Byte(r8)) => {
404 Some(Constant::Byte(l8 - r8))
407 (Constant::Int(l64, lty, lsign), Constant::Int(r64, rty, rsign)) => {
408 add_ints(l64, r64, lty, rty, lsign, neg_sign(rsign))
414 BiMul => self.divmul(left, right, u64::checked_mul),
415 BiDiv => self.divmul(left, right, u64::checked_div),
417 BiAnd => self.short_circuit(left, right, false),
418 BiOr => self.short_circuit(left, right, true),
419 BiBitXor => self.bitop(left, right, |x, y| x ^ y),
420 BiBitAnd => self.bitop(left, right, |x, y| x & y),
421 BiBitOr => self.bitop(left, right, |x, y| (x | y)),
422 BiShl => self.bitop(left, right, |x, y| x << y),
423 BiShr => self.bitop(left, right, |x, y| x >> y),
424 BiEq => self.binop_apply(left, right, |l, r| Some(Constant::Bool(l == r))),
425 BiNe => self.binop_apply(left, right, |l, r| Some(Constant::Bool(l != r))),
426 BiLt => self.cmp(left, right, Less, true),
427 BiLe => self.cmp(left, right, Greater, false),
428 BiGe => self.cmp(left, right, Less, false),
429 BiGt => self.cmp(left, right, Greater, true),
434 fn divmul<F>(&mut self, left: &Expr, right: &Expr, f: F) -> Option<Constant>
435 where F: Fn(u64, u64) -> Option<u64>
437 self.binop_apply(left, right, |l, r| {
439 (Constant::Int(l64, lty, lsign), Constant::Int(r64, rty, rsign)) => {
440 f(l64, r64).and_then(|value| {
441 let sign = if lsign == rsign {
446 unify_int_type(lty, rty).map(|ty| Constant::Int(value, ty, sign))
454 fn bitop<F>(&mut self, left: &Expr, right: &Expr, f: F) -> Option<Constant>
455 where F: Fn(u64, u64) -> u64
457 self.binop_apply(left, right, |l, r| {
459 (Constant::Bool(l), Constant::Bool(r)) => Some(Constant::Bool(f(l as u64, r as u64) != 0)),
460 (Constant::Byte(l8), Constant::Byte(r8)) => Some(Constant::Byte(f(l8 as u64, r8 as u64) as u8)),
461 (Constant::Int(l, lty, lsign), Constant::Int(r, rty, rsign)) => {
462 if lsign == Sign::Plus && rsign == Sign::Plus {
463 unify_int_type(lty, rty).map(|ty| Constant::Int(f(l, r), ty, Sign::Plus))
473 fn cmp(&mut self, left: &Expr, right: &Expr, ordering: Ordering, b: bool) -> Option<Constant> {
474 self.binop_apply(left,
476 |l, r| l.partial_cmp(&r).map(|o| Constant::Bool(b == (o == ordering))))
479 fn binop_apply<F>(&mut self, left: &Expr, right: &Expr, op: F) -> Option<Constant>
480 where F: Fn(Constant, Constant) -> Option<Constant>
482 if let (Some(lc), Some(rc)) = (self.expr(left), self.expr(right)) {
489 fn short_circuit(&mut self, left: &Expr, right: &Expr, b: bool) -> Option<Constant> {
490 self.expr(left).and_then(|left| {
491 if let Constant::Bool(lbool) = left {
495 self.expr(right).and_then(|right| {
496 if let Constant::Bool(_) = right {
510 fn add_ints(l64: u64, r64: u64, lty: LitIntType, rty: LitIntType, lsign: Sign, rsign: Sign) -> Option<Constant> {
511 let ty = if let Some(ty) = unify_int_type(lty, rty) {
517 match (lsign, rsign) {
518 (Sign::Plus, Sign::Plus) => l64.checked_add(r64).map(|v| Constant::Int(v, ty, Sign::Plus)),
519 (Sign::Plus, Sign::Minus) => {
521 Some(Constant::Int(r64 - l64, ty, Sign::Minus))
523 Some(Constant::Int(l64 - r64, ty, Sign::Plus))
526 (Sign::Minus, Sign::Minus) => l64.checked_add(r64).map(|v| Constant::Int(v, ty, Sign::Minus)),
527 (Sign::Minus, Sign::Plus) => {
529 Some(Constant::Int(l64 - r64, ty, Sign::Minus))
531 Some(Constant::Int(r64 - l64, ty, Sign::Plus))