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};
14 use syntax::ast::{FloatTy, LitIntType, LitKind, StrStyle, UintTy, IntTy};
17 #[derive(Debug, Copy, Clone)]
24 impl From<FloatTy> for FloatWidth {
25 fn from(ty: FloatTy) -> FloatWidth {
27 FloatTy::F32 => FloatWidth::F32,
28 FloatTy::F64 => FloatWidth::F64,
33 /// A `LitKind`-like enum to fold constant `Expr`s into.
34 #[derive(Debug, Clone)]
37 Str(String, StrStyle),
38 /// a Binary String b"abc"
42 /// an integer, third argument is whether the value is negated
44 /// a float with given type
45 Float(String, FloatWidth),
48 /// an array of constants
50 /// also an array, but with only one constant, repeated N times
51 Repeat(Box<Constant>, usize),
52 /// a tuple of constants
57 /// convert to u64 if possible
61 /// if the constant could not be converted to u64 losslessly
62 fn as_u64(&self) -> u64 {
63 if let Constant::Int(val) = *self {
64 val.to_u64().expect("negative constant can't be casted to u64")
66 panic!("Could not convert a {:?} to u64", self);
70 /// convert this constant to a f64, if possible
71 #[allow(cast_precision_loss, cast_possible_wrap)]
72 pub fn as_float(&self) -> Option<f64> {
74 Constant::Float(ref s, _) => s.parse().ok(),
75 Constant::Int(i) if i.is_negative() => Some(i.to_u64_unchecked() as i64 as f64),
76 Constant::Int(i) => Some(i.to_u64_unchecked() as f64),
82 impl PartialEq for Constant {
83 fn eq(&self, other: &Constant) -> bool {
85 (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => ls == rs && l_sty == r_sty,
86 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
87 (&Constant::Char(l), &Constant::Char(r)) => l == r,
88 (&Constant::Int(l), &Constant::Int(r)) => {
89 l.is_negative() == r.is_negative() && l.to_u64_unchecked() == r.to_u64_unchecked()
91 (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
92 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
93 // `Fw32 == Fw64` so don’t compare them
94 match (ls.parse::<f64>(), rs.parse::<f64>()) {
95 (Ok(l), Ok(r)) => l.eq(&r),
99 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
100 (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l == r,
101 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
102 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
103 _ => false, //TODO: Are there inter-type equalities?
108 impl Hash for Constant {
109 fn hash<H>(&self, state: &mut H)
113 Constant::Str(ref s, ref k) => {
117 Constant::Binary(ref b) => {
120 Constant::Char(c) => {
123 Constant::Int(i) => {
124 i.to_u64_unchecked().hash(state);
125 i.is_negative().hash(state);
127 Constant::Float(ref f, _) => {
128 // don’t use the width here because of PartialEq implementation
129 if let Ok(f) = f.parse::<f64>() {
130 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
133 Constant::Bool(b) => {
136 Constant::Vec(ref v) |
137 Constant::Tuple(ref v) => {
140 Constant::Repeat(ref c, l) => {
148 impl PartialOrd for Constant {
149 fn partial_cmp(&self, other: &Constant) -> Option<Ordering> {
150 match (self, other) {
151 (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => {
158 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
159 (&Constant::Int(l), &Constant::Int(r)) => Some(l.cmp(&r)),
160 (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
161 match (ls.parse::<f64>(), rs.parse::<f64>()) {
162 (Ok(ref l), Ok(ref r)) => l.partial_cmp(r),
166 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
167 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) |
168 (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l.partial_cmp(r),
169 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
170 match lv.partial_cmp(rv) {
171 Some(Equal) => Some(ls.cmp(rs)),
175 _ => None, //TODO: Are there any useful inter-type orderings?
180 /// parse a `LitKind` to a `Constant`
181 #[allow(cast_possible_wrap)]
182 pub fn lit_to_constant(lit: &LitKind) -> Constant {
184 LitKind::Str(ref is, style) => Constant::Str(is.to_string(), style),
185 LitKind::Byte(b) => Constant::Int(ConstInt::U8(b)),
186 LitKind::ByteStr(ref s) => Constant::Binary(s.clone()),
187 LitKind::Char(c) => Constant::Char(c),
188 LitKind::Int(value, LitIntType::Unsuffixed) => Constant::Int(ConstInt::Infer(value)),
189 LitKind::Int(value, LitIntType::Unsigned(UintTy::U8)) => Constant::Int(ConstInt::U8(value as u8)),
190 LitKind::Int(value, LitIntType::Unsigned(UintTy::U16)) => Constant::Int(ConstInt::U16(value as u16)),
191 LitKind::Int(value, LitIntType::Unsigned(UintTy::U32)) => Constant::Int(ConstInt::U32(value as u32)),
192 LitKind::Int(value, LitIntType::Unsigned(UintTy::U64)) => Constant::Int(ConstInt::U64(value as u64)),
193 LitKind::Int(value, LitIntType::Unsigned(UintTy::Us)) => {
194 Constant::Int(ConstInt::Usize(ConstUsize::Us32(value as u32)))
196 LitKind::Int(value, LitIntType::Signed(IntTy::I8)) => Constant::Int(ConstInt::I8(value as i8)),
197 LitKind::Int(value, LitIntType::Signed(IntTy::I16)) => Constant::Int(ConstInt::I16(value as i16)),
198 LitKind::Int(value, LitIntType::Signed(IntTy::I32)) => Constant::Int(ConstInt::I32(value as i32)),
199 LitKind::Int(value, LitIntType::Signed(IntTy::I64)) => Constant::Int(ConstInt::I64(value as i64)),
200 LitKind::Int(value, LitIntType::Signed(IntTy::Is)) => {
201 Constant::Int(ConstInt::Isize(ConstIsize::Is32(value as i32)))
203 LitKind::Float(ref is, ty) => Constant::Float(is.to_string(), ty.into()),
204 LitKind::FloatUnsuffixed(ref is) => Constant::Float(is.to_string(), FloatWidth::Any),
205 LitKind::Bool(b) => Constant::Bool(b),
209 fn constant_not(o: Constant) -> Option<Constant> {
210 use self::Constant::*;
212 Bool(b) => Some(Bool(!b)),
213 Int(value) => (!value).ok().map(Int),
218 fn constant_negate(o: Constant) -> Option<Constant> {
219 use self::Constant::*;
221 Int(value) => (-value).ok().map(Int),
222 Float(is, ty) => Some(Float(neg_float_str(is), ty)),
227 fn neg_float_str(s: String) -> String {
228 if s.starts_with('-') {
235 pub fn constant(lcx: &LateContext, e: &Expr) -> Option<(Constant, bool)> {
236 let mut cx = ConstEvalLateContext {
238 needed_resolution: false,
240 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
243 pub fn constant_simple(e: &Expr) -> Option<Constant> {
244 let mut cx = ConstEvalLateContext {
246 needed_resolution: false,
251 struct ConstEvalLateContext<'c, 'cc: 'c> {
252 lcx: Option<&'c LateContext<'c, 'cc>>,
253 needed_resolution: bool,
256 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
257 /// simple constant folding: Insert an expression, get a constant or none.
258 fn expr(&mut self, e: &Expr) -> Option<Constant> {
260 ExprPath(_, _) => self.fetch_path(e),
261 ExprBlock(ref block) => self.block(block),
262 ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
263 ExprLit(ref lit) => Some(lit_to_constant(&lit.node)),
264 ExprVec(ref vec) => self.multi(vec).map(Constant::Vec),
265 ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
266 ExprRepeat(ref value, ref number) => {
267 self.binop_apply(value, number, |v, n| Some(Constant::Repeat(Box::new(v), n.as_u64() as usize)))
269 ExprUnary(op, ref operand) => {
270 self.expr(operand).and_then(|o| {
272 UnNot => constant_not(o),
273 UnNeg => constant_negate(o),
278 ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
279 // TODO: add other expressions
284 /// create `Some(Vec![..])` of all constants, unless there is any
285 /// non-constant part
286 fn multi<E: Deref<Target = Expr> + Sized>(&mut self, vec: &[E]) -> Option<Vec<Constant>> {
288 .map(|elem| self.expr(elem))
289 .collect::<Option<_>>()
292 /// lookup a possibly constant expression from a ExprPath
293 fn fetch_path(&mut self, e: &Expr) -> Option<Constant> {
294 if let Some(lcx) = self.lcx {
295 let mut maybe_id = None;
296 if let Some(&PathResolution { base_def: Def::Const(id), .. }) = lcx.tcx.def_map.borrow().get(&e.id) {
299 // separate if lets to avoid double borrowing the def_map
300 if let Some(id) = maybe_id {
301 if let Some((const_expr, _ty)) = lookup_const_by_id(lcx.tcx, id, None) {
302 let ret = self.expr(const_expr);
304 self.needed_resolution = true;
313 /// A block can only yield a constant if it only has one constant expression
314 fn block(&mut self, block: &Block) -> Option<Constant> {
315 if block.stmts.is_empty() {
316 block.expr.as_ref().and_then(|ref b| self.expr(b))
322 fn ifthenelse(&mut self, cond: &Expr, then: &Block, otherwise: &Option<P<Expr>>) -> Option<Constant> {
323 if let Some(Constant::Bool(b)) = self.expr(cond) {
327 otherwise.as_ref().and_then(|expr| self.expr(expr))
334 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
335 let l = if let Some(l) = self.expr(left) {
340 let r = self.expr(right);
341 match (op.node, l, r) {
342 (BiAdd, Constant::Int(l), Some(Constant::Int(r))) => (l + r).ok().map(Constant::Int),
343 (BiSub, Constant::Int(l), Some(Constant::Int(r))) => (l - r).ok().map(Constant::Int),
344 (BiMul, Constant::Int(l), Some(Constant::Int(r))) => (l * r).ok().map(Constant::Int),
345 (BiDiv, Constant::Int(l), Some(Constant::Int(r))) => (l / r).ok().map(Constant::Int),
346 (BiRem, Constant::Int(l), Some(Constant::Int(r))) => (l % r).ok().map(Constant::Int),
347 (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
348 (BiAnd, Constant::Bool(true), Some(r)) => Some(r),
349 (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
350 (BiOr, Constant::Bool(false), Some(r)) => Some(r),
351 (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
352 (BiBitXor, Constant::Int(l), Some(Constant::Int(r))) => (l ^ r).ok().map(Constant::Int),
353 (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
354 (BiBitAnd, Constant::Int(l), Some(Constant::Int(r))) => (l & r).ok().map(Constant::Int),
355 (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
356 (BiBitOr, Constant::Int(l), Some(Constant::Int(r))) => (l | r).ok().map(Constant::Int),
357 (BiShl, Constant::Int(l), Some(Constant::Int(r))) => (l << r).ok().map(Constant::Int),
358 (BiShr, Constant::Int(l), Some(Constant::Int(r))) => (l >> r).ok().map(Constant::Int),
359 (BiEq, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l == r)),
360 (BiNe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l != r)),
361 (BiLt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l < r)),
362 (BiLe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l <= r)),
363 (BiGe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l >= r)),
364 (BiGt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l > r)),
370 fn binop_apply<F>(&mut self, left: &Expr, right: &Expr, op: F) -> Option<Constant>
371 where F: Fn(Constant, Constant) -> Option<Constant>
373 if let (Some(lc), Some(rc)) = (self.expr(left), self.expr(right)) {