1 #![allow(cast_possible_truncation)]
3 use rustc::lint::LateContext;
4 use rustc::hir::def::Def;
6 use rustc::ty::{self, Ty, TyCtxt, Instance};
7 use rustc::ty::subst::{Subst, Substs};
8 use std::cmp::Ordering::{self, Equal};
9 use std::cmp::PartialOrd;
10 use std::hash::{Hash, Hasher};
13 use syntax::ast::{FloatTy, LitKind};
15 use rustc::middle::const_val::ConstVal;
16 use utils::{sext, unsext, clip};
18 #[derive(Debug, Copy, Clone)]
25 impl From<FloatTy> for FloatWidth {
26 fn from(ty: FloatTy) -> Self {
28 FloatTy::F32 => FloatWidth::F32,
29 FloatTy::F64 => FloatWidth::F64,
34 /// A `LitKind`-like enum to fold constant `Expr`s into.
35 #[derive(Debug, Clone)]
39 /// a Binary String b"abc"
43 /// an integer's bit representation
51 /// an array of constants
53 /// also an array, but with only one constant, repeated N times
54 Repeat(Box<Constant>, u64),
55 /// a tuple of constants
59 impl PartialEq for Constant {
60 fn eq(&self, other: &Self) -> bool {
62 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => ls == rs,
63 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
64 (&Constant::Char(l), &Constant::Char(r)) => l == r,
65 (&Constant::Int(l), &Constant::Int(r)) => l == r,
66 (&Constant::F64(l), &Constant::F64(r)) => {
67 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
68 // `Fw32 == Fw64` so don’t compare them
69 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
70 unsafe { mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r) }
72 (&Constant::F32(l), &Constant::F32(r)) => {
73 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
74 // `Fw32 == Fw64` so don’t compare them
75 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
76 unsafe { mem::transmute::<f64, u64>(l as f64) == mem::transmute::<f64, u64>(r as f64) }
78 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
79 (&Constant::Vec(ref l), &Constant::Vec(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
80 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
81 _ => false, // TODO: Are there inter-type equalities?
86 impl Hash for Constant {
87 fn hash<H>(&self, state: &mut H)
92 Constant::Str(ref s) => {
95 Constant::Binary(ref b) => {
98 Constant::Char(c) => {
101 Constant::Int(i) => {
104 Constant::F32(f) => {
105 unsafe { mem::transmute::<f64, u64>(f as f64) }.hash(state);
107 Constant::F64(f) => {
108 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
110 Constant::Bool(b) => {
113 Constant::Vec(ref v) | Constant::Tuple(ref v) => {
116 Constant::Repeat(ref c, l) => {
124 impl PartialOrd for Constant {
125 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
126 match (self, other) {
127 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => Some(ls.cmp(rs)),
128 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
129 (&Constant::Int(l), &Constant::Int(r)) => Some(l.cmp(&r)),
130 (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
131 (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
132 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
133 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => {
136 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => match lv.partial_cmp(rv) {
137 Some(Equal) => Some(ls.cmp(rs)),
140 _ => None, // TODO: Are there any useful inter-type orderings?
145 /// parse a `LitKind` to a `Constant`
146 pub fn lit_to_constant<'a, 'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
150 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
151 LitKind::Byte(b) => Constant::Int(b as u128),
152 LitKind::ByteStr(ref s) => Constant::Binary(Rc::clone(s)),
153 LitKind::Char(c) => Constant::Char(c),
154 LitKind::Int(n, _) => Constant::Int(n),
155 LitKind::Float(ref is, _) |
156 LitKind::FloatUnsuffixed(ref is) => match ty.sty {
157 ty::TyFloat(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
158 ty::TyFloat(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
161 LitKind::Bool(b) => Constant::Bool(b),
165 pub fn constant(lcx: &LateContext, e: &Expr) -> Option<(Constant, bool)> {
166 let mut cx = ConstEvalLateContext {
169 param_env: lcx.param_env,
170 needed_resolution: false,
171 substs: lcx.tcx.intern_substs(&[]),
173 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
176 pub fn constant_simple(lcx: &LateContext, e: &Expr) -> Option<Constant> {
177 constant(lcx, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
180 /// Creates a ConstEvalLateContext from the given LateContext and TypeckTables
181 pub fn constant_context<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'cc ty::TypeckTables<'cc>) -> ConstEvalLateContext<'c, 'cc> {
182 ConstEvalLateContext {
185 param_env: lcx.param_env,
186 needed_resolution: false,
187 substs: lcx.tcx.intern_substs(&[]),
191 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
192 tcx: TyCtxt<'a, 'tcx, 'tcx>,
193 tables: &'a ty::TypeckTables<'tcx>,
194 param_env: ty::ParamEnv<'tcx>,
195 needed_resolution: bool,
196 substs: &'tcx Substs<'tcx>,
199 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
200 /// simple constant folding: Insert an expression, get a constant or none.
201 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
203 ExprPath(ref qpath) => self.fetch_path(qpath, e.hir_id),
204 ExprBlock(ref block) => self.block(block),
205 ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
206 ExprLit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
207 ExprArray(ref vec) => self.multi(vec).map(Constant::Vec),
208 ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
209 ExprRepeat(ref value, _) => {
210 let n = match self.tables.expr_ty(e).sty {
211 ty::TyArray(_, n) => n.val.to_raw_bits().expect("array length"),
212 _ => span_bug!(e.span, "typeck error"),
214 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n as u64))
216 ExprUnary(op, ref operand) => self.expr(operand).and_then(|o| match op {
217 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
218 UnNeg => self.constant_negate(o, self.tables.expr_ty(e)),
221 ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
222 // TODO: add other expressions
227 fn constant_not(&self, o: &Constant, ty: ty::Ty) -> Option<Constant> {
228 use self::Constant::*;
230 Bool(b) => Some(Bool(!b)),
232 let mut value = !value;
234 ty::TyInt(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
235 ty::TyUint(ity) => Some(Int(clip(self.tcx, value, ity))),
243 fn constant_negate(&self, o: Constant, ty: ty::Ty) -> Option<Constant> {
244 use self::Constant::*;
247 let ity = match ty.sty {
248 ty::TyInt(ity) => ity,
252 let value = sext(self.tcx, value, ity);
253 let value = value.checked_neg()?;
255 Some(Int(unsext(self.tcx, value, ity)))
257 F32(f) => Some(F32(-f)),
258 F64(f) => Some(F64(-f)),
263 /// create `Some(Vec![..])` of all constants, unless there is any
264 /// non-constant part
265 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
267 .map(|elem| self.expr(elem))
268 .collect::<Option<_>>()
271 /// lookup a possibly constant expression from a ExprPath
272 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
273 let def = self.tables.qpath_def(qpath, id);
275 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
276 let substs = self.tables.node_substs(id);
277 let substs = if self.substs.is_empty() {
280 substs.subst(self.tcx, self.substs)
282 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
287 use rustc::mir::interpret::GlobalId;
288 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
289 let ret = miri_to_const(self.tcx, result);
291 self.needed_resolution = true;
300 /// A block can only yield a constant if it only has one constant expression
301 fn block(&mut self, block: &Block) -> Option<Constant> {
302 if block.stmts.is_empty() {
303 block.expr.as_ref().and_then(|b| self.expr(b))
309 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
310 if let Some(Constant::Bool(b)) = self.expr(cond) {
314 otherwise.as_ref().and_then(|expr| self.expr(expr))
321 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
322 let l = self.expr(left)?;
323 let r = self.expr(right);
325 (Constant::Int(l), Some(Constant::Int(r))) => {
326 match self.tables.expr_ty(left).sty {
328 let l = sext(self.tcx, l, ity);
329 let r = sext(self.tcx, r, ity);
330 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
332 BiAdd => l.checked_add(r).map(zext),
333 BiSub => l.checked_sub(r).map(zext),
334 BiMul => l.checked_mul(r).map(zext),
335 BiDiv if r != 0 => l.checked_div(r).map(zext),
336 BiRem if r != 0 => l.checked_rem(r).map(zext),
337 BiShr => l.checked_shr(r as u128 as u32).map(zext),
338 BiShl => l.checked_shl(r as u128 as u32).map(zext),
339 BiBitXor => Some(zext(l ^ r)),
340 BiBitOr => Some(zext(l | r)),
341 BiBitAnd => Some(zext(l & r)),
342 BiEq => Some(Constant::Bool(l == r)),
343 BiNe => Some(Constant::Bool(l != r)),
344 BiLt => Some(Constant::Bool(l < r)),
345 BiLe => Some(Constant::Bool(l <= r)),
346 BiGe => Some(Constant::Bool(l >= r)),
347 BiGt => Some(Constant::Bool(l > r)),
353 BiAdd => l.checked_add(r).map(Constant::Int),
354 BiSub => l.checked_sub(r).map(Constant::Int),
355 BiMul => l.checked_mul(r).map(Constant::Int),
356 BiDiv => l.checked_div(r).map(Constant::Int),
357 BiRem => l.checked_rem(r).map(Constant::Int),
358 BiShr => l.checked_shr(r as u32).map(Constant::Int),
359 BiShl => l.checked_shl(r as u32).map(Constant::Int),
360 BiBitXor => Some(Constant::Int(l ^ r)),
361 BiBitOr => Some(Constant::Int(l | r)),
362 BiBitAnd => Some(Constant::Int(l & r)),
363 BiEq => Some(Constant::Bool(l == r)),
364 BiNe => Some(Constant::Bool(l != r)),
365 BiLt => Some(Constant::Bool(l < r)),
366 BiLe => Some(Constant::Bool(l <= r)),
367 BiGe => Some(Constant::Bool(l >= r)),
368 BiGt => Some(Constant::Bool(l > r)),
375 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
376 BiAdd => Some(Constant::F32(l + r)),
377 BiSub => Some(Constant::F32(l - r)),
378 BiMul => Some(Constant::F32(l * r)),
379 BiDiv => Some(Constant::F32(l / r)),
380 BiRem => Some(Constant::F32(l * r)),
381 BiEq => Some(Constant::Bool(l == r)),
382 BiNe => Some(Constant::Bool(l != r)),
383 BiLt => Some(Constant::Bool(l < r)),
384 BiLe => Some(Constant::Bool(l <= r)),
385 BiGe => Some(Constant::Bool(l >= r)),
386 BiGt => Some(Constant::Bool(l > r)),
389 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
390 BiAdd => Some(Constant::F64(l + r)),
391 BiSub => Some(Constant::F64(l - r)),
392 BiMul => Some(Constant::F64(l * r)),
393 BiDiv => Some(Constant::F64(l / r)),
394 BiRem => Some(Constant::F64(l * r)),
395 BiEq => Some(Constant::Bool(l == r)),
396 BiNe => Some(Constant::Bool(l != r)),
397 BiLt => Some(Constant::Bool(l < r)),
398 BiLe => Some(Constant::Bool(l <= r)),
399 BiGe => Some(Constant::Bool(l >= r)),
400 BiGt => Some(Constant::Bool(l > r)),
403 (l, r) => match (op.node, l, r) {
404 (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
405 (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
406 (BiAnd, Constant::Bool(true), Some(r)) | (BiOr, Constant::Bool(false), Some(r)) => Some(r),
407 (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
408 (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
409 (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
416 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
417 use rustc::mir::interpret::{Value, PrimVal};
419 ConstVal::Value(Value::ByVal(PrimVal::Bytes(b))) => match result.ty.sty {
420 ty::TyBool => Some(Constant::Bool(b == 1)),
421 ty::TyUint(_) | ty::TyInt(_) => Some(Constant::Int(b)),
422 ty::TyFloat(FloatTy::F32) => Some(Constant::F32(f32::from_bits(b as u32))),
423 ty::TyFloat(FloatTy::F64) => Some(Constant::F64(f64::from_bits(b as u64))),
424 // FIXME: implement other conversion
427 ConstVal::Value(Value::ByValPair(PrimVal::Ptr(ptr), PrimVal::Bytes(n))) => match result.ty.sty {
428 ty::TyRef(_, tam) => match tam.ty.sty {
432 .get_alloc(ptr.alloc_id)
434 let offset = ptr.offset as usize;
436 String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned()).ok().map(Constant::Str)
442 // FIXME: implement other conversions