1 #![allow(cast_possible_truncation)]
3 use rustc::lint::LateContext;
4 use rustc::hir::def::{Def, PathResolution};
5 use rustc_const_eval::lookup_const_by_id;
6 use rustc_const_math::{ConstInt, ConstUsize, ConstIsize};
8 use std::cmp::Ordering::{self, Equal};
9 use std::cmp::PartialOrd;
10 use std::hash::{Hash, Hasher};
13 use syntax::ast::{FloatTy, LitIntType, LitKind, StrStyle, UintTy, IntTy};
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 /// A `LitKind`-like enum to fold constant `Expr`s into.
33 #[derive(Debug, Clone)]
36 Str(String, StrStyle),
37 /// a Binary String b"abc"
41 /// an integer, third argument is whether the value is negated
43 /// a float with given type
44 Float(String, FloatWidth),
47 /// an array of constants
49 /// also an array, but with only one constant, repeated N times
50 Repeat(Box<Constant>, usize),
51 /// a tuple of constants
56 /// Convert to `u64` if possible.
60 /// If the constant could not be converted to `u64` losslessly.
61 fn as_u64(&self) -> u64 {
62 if let Constant::Int(val) = *self {
63 val.to_u64().expect("negative constant can't be casted to `u64`")
65 panic!("Could not convert a `{:?}` to `u64`", self);
70 impl PartialEq for Constant {
71 fn eq(&self, other: &Constant) -> bool {
73 (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => ls == rs && l_sty == r_sty,
74 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
75 (&Constant::Char(l), &Constant::Char(r)) => l == r,
76 (&Constant::Int(l), &Constant::Int(r)) => {
77 l.is_negative() == r.is_negative() && l.to_u64_unchecked() == r.to_u64_unchecked()
79 (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
80 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
81 // `Fw32 == Fw64` so don’t compare them
82 match (ls.parse::<f64>(), rs.parse::<f64>()) {
83 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
84 (Ok(l), Ok(r)) => unsafe {
85 mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r)
90 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
91 (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l == r,
92 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
93 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
94 _ => false, //TODO: Are there inter-type equalities?
99 impl Hash for Constant {
100 fn hash<H>(&self, state: &mut H)
104 Constant::Str(ref s, ref k) => {
108 Constant::Binary(ref b) => {
111 Constant::Char(c) => {
114 Constant::Int(i) => {
115 i.to_u64_unchecked().hash(state);
116 i.is_negative().hash(state);
118 Constant::Float(ref f, _) => {
119 // don’t use the width here because of PartialEq implementation
120 if let Ok(f) = f.parse::<f64>() {
121 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
124 Constant::Bool(b) => {
127 Constant::Vec(ref v) |
128 Constant::Tuple(ref v) => {
131 Constant::Repeat(ref c, l) => {
139 impl PartialOrd for Constant {
140 fn partial_cmp(&self, other: &Constant) -> Option<Ordering> {
141 match (self, other) {
142 (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => {
149 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
150 (&Constant::Int(l), &Constant::Int(r)) => Some(l.cmp(&r)),
151 (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
152 match (ls.parse::<f64>(), rs.parse::<f64>()) {
153 (Ok(ref l), Ok(ref r)) => match (l.partial_cmp(r), l.is_sign_positive() == r.is_sign_positive()) {
154 // Check for comparison of -0.0 and 0.0
155 (Some(Ordering::Equal), false) => None,
161 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
162 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) |
163 (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l.partial_cmp(r),
164 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
165 match lv.partial_cmp(rv) {
166 Some(Equal) => Some(ls.cmp(rs)),
170 _ => None, //TODO: Are there any useful inter-type orderings?
175 /// parse a `LitKind` to a `Constant`
176 #[allow(cast_possible_wrap)]
177 pub fn lit_to_constant(lit: &LitKind) -> Constant {
179 LitKind::Str(ref is, style) => Constant::Str(is.to_string(), style),
180 LitKind::Byte(b) => Constant::Int(ConstInt::U8(b)),
181 LitKind::ByteStr(ref s) => Constant::Binary(s.clone()),
182 LitKind::Char(c) => Constant::Char(c),
183 LitKind::Int(value, LitIntType::Unsuffixed) => Constant::Int(ConstInt::Infer(value)),
184 LitKind::Int(value, LitIntType::Unsigned(UintTy::U8)) => Constant::Int(ConstInt::U8(value as u8)),
185 LitKind::Int(value, LitIntType::Unsigned(UintTy::U16)) => Constant::Int(ConstInt::U16(value as u16)),
186 LitKind::Int(value, LitIntType::Unsigned(UintTy::U32)) => Constant::Int(ConstInt::U32(value as u32)),
187 LitKind::Int(value, LitIntType::Unsigned(UintTy::U64)) => Constant::Int(ConstInt::U64(value as u64)),
188 LitKind::Int(value, LitIntType::Unsigned(UintTy::Us)) => {
189 Constant::Int(ConstInt::Usize(ConstUsize::Us32(value as u32)))
191 LitKind::Int(value, LitIntType::Signed(IntTy::I8)) => Constant::Int(ConstInt::I8(value as i8)),
192 LitKind::Int(value, LitIntType::Signed(IntTy::I16)) => Constant::Int(ConstInt::I16(value as i16)),
193 LitKind::Int(value, LitIntType::Signed(IntTy::I32)) => Constant::Int(ConstInt::I32(value as i32)),
194 LitKind::Int(value, LitIntType::Signed(IntTy::I64)) => Constant::Int(ConstInt::I64(value as i64)),
195 LitKind::Int(value, LitIntType::Signed(IntTy::Is)) => {
196 Constant::Int(ConstInt::Isize(ConstIsize::Is32(value as i32)))
198 LitKind::Float(ref is, ty) => Constant::Float(is.to_string(), ty.into()),
199 LitKind::FloatUnsuffixed(ref is) => Constant::Float(is.to_string(), FloatWidth::Any),
200 LitKind::Bool(b) => Constant::Bool(b),
204 fn constant_not(o: Constant) -> Option<Constant> {
205 use self::Constant::*;
207 Bool(b) => Some(Bool(!b)),
208 Int(value) => (!value).ok().map(Int),
213 fn constant_negate(o: Constant) -> Option<Constant> {
214 use self::Constant::*;
216 Int(value) => (-value).ok().map(Int),
217 Float(is, ty) => Some(Float(neg_float_str(is), ty)),
222 fn neg_float_str(s: String) -> String {
223 if s.starts_with('-') {
230 pub fn constant(lcx: &LateContext, e: &Expr) -> Option<(Constant, bool)> {
231 let mut cx = ConstEvalLateContext {
233 needed_resolution: false,
235 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
238 pub fn constant_simple(e: &Expr) -> Option<Constant> {
239 let mut cx = ConstEvalLateContext {
241 needed_resolution: false,
246 struct ConstEvalLateContext<'c, 'cc: 'c> {
247 lcx: Option<&'c LateContext<'c, 'cc>>,
248 needed_resolution: bool,
251 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
252 /// simple constant folding: Insert an expression, get a constant or none.
253 fn expr(&mut self, e: &Expr) -> Option<Constant> {
255 ExprPath(_, _) => self.fetch_path(e),
256 ExprBlock(ref block) => self.block(block),
257 ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
258 ExprLit(ref lit) => Some(lit_to_constant(&lit.node)),
259 ExprArray(ref vec) => self.multi(vec).map(Constant::Vec),
260 ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
261 ExprRepeat(ref value, ref number) => {
262 self.binop_apply(value, number, |v, n| Some(Constant::Repeat(Box::new(v), n.as_u64() as usize)))
264 ExprUnary(op, ref operand) => {
265 self.expr(operand).and_then(|o| {
267 UnNot => constant_not(o),
268 UnNeg => constant_negate(o),
273 ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
274 // TODO: add other expressions
279 /// create `Some(Vec![..])` of all constants, unless there is any
280 /// non-constant part
281 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
283 .map(|elem| self.expr(elem))
284 .collect::<Option<_>>()
287 /// lookup a possibly constant expression from a ExprPath
288 fn fetch_path(&mut self, e: &Expr) -> Option<Constant> {
289 if let Some(lcx) = self.lcx {
290 let mut maybe_id = None;
291 if let Some(&PathResolution { base_def: Def::Const(id), .. }) = lcx.tcx.def_map.borrow().get(&e.id) {
294 // separate if lets to avoid double borrowing the def_map
295 if let Some(id) = maybe_id {
296 if let Some((const_expr, _ty)) = lookup_const_by_id(lcx.tcx, id, None) {
297 let ret = self.expr(const_expr);
299 self.needed_resolution = true;
308 /// A block can only yield a constant if it only has one constant expression
309 fn block(&mut self, block: &Block) -> Option<Constant> {
310 if block.stmts.is_empty() {
311 block.expr.as_ref().and_then(|b| self.expr(b))
317 fn ifthenelse(&mut self, cond: &Expr, then: &Block, otherwise: &Option<P<Expr>>) -> Option<Constant> {
318 if let Some(Constant::Bool(b)) = self.expr(cond) {
322 otherwise.as_ref().and_then(|expr| self.expr(expr))
329 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
330 let l = if let Some(l) = self.expr(left) {
335 let r = self.expr(right);
336 match (op.node, l, r) {
337 (BiAdd, Constant::Int(l), Some(Constant::Int(r))) => (l + r).ok().map(Constant::Int),
338 (BiSub, Constant::Int(l), Some(Constant::Int(r))) => (l - r).ok().map(Constant::Int),
339 (BiMul, Constant::Int(l), Some(Constant::Int(r))) => (l * r).ok().map(Constant::Int),
340 (BiDiv, Constant::Int(l), Some(Constant::Int(r))) => (l / r).ok().map(Constant::Int),
341 (BiRem, Constant::Int(l), Some(Constant::Int(r))) => (l % r).ok().map(Constant::Int),
342 (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
343 (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
344 (BiAnd, Constant::Bool(true), Some(r)) |
345 (BiOr, Constant::Bool(false), Some(r)) => Some(r),
346 (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
347 (BiBitXor, Constant::Int(l), Some(Constant::Int(r))) => (l ^ r).ok().map(Constant::Int),
348 (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
349 (BiBitAnd, Constant::Int(l), Some(Constant::Int(r))) => (l & r).ok().map(Constant::Int),
350 (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
351 (BiBitOr, Constant::Int(l), Some(Constant::Int(r))) => (l | r).ok().map(Constant::Int),
352 (BiShl, Constant::Int(l), Some(Constant::Int(r))) => (l << r).ok().map(Constant::Int),
353 (BiShr, Constant::Int(l), Some(Constant::Int(r))) => (l >> r).ok().map(Constant::Int),
354 (BiEq, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l == r)),
355 (BiNe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l != r)),
356 (BiLt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l < r)),
357 (BiLe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l <= r)),
358 (BiGe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l >= r)),
359 (BiGt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l > r)),
365 fn binop_apply<F>(&mut self, left: &Expr, right: &Expr, op: F) -> Option<Constant>
366 where F: Fn(Constant, Constant) -> Option<Constant>
368 if let (Some(lc), Some(rc)) = (self.expr(left), self.expr(right)) {