1 #![allow(cast_possible_truncation)]
4 use rustc::lint::LateContext;
5 use rustc::hir::def::Def;
7 use rustc::ty::{self, Ty, TyCtxt, Instance};
8 use rustc::ty::subst::{Subst, Substs};
9 use std::cmp::Ordering::{self, Equal};
10 use std::cmp::PartialOrd;
11 use std::hash::{Hash, Hasher};
14 use syntax::ast::{FloatTy, LitKind};
16 use rustc::middle::const_val::ConstVal;
17 use utils::{sext, unsext, clip};
19 #[derive(Debug, Copy, Clone)]
26 impl From<FloatTy> for FloatWidth {
27 fn from(ty: FloatTy) -> Self {
29 FloatTy::F32 => FloatWidth::F32,
30 FloatTy::F64 => FloatWidth::F64,
35 /// A `LitKind`-like enum to fold constant `Expr`s into.
36 #[derive(Debug, Clone)]
40 /// a Binary String b"abc"
44 /// an integer's bit representation
52 /// an array of constants
54 /// also an array, but with only one constant, repeated N times
55 Repeat(Box<Constant>, u64),
56 /// a tuple of constants
60 impl PartialEq for Constant {
61 fn eq(&self, other: &Self) -> bool {
63 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => ls == rs,
64 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
65 (&Constant::Char(l), &Constant::Char(r)) => l == r,
66 (&Constant::Int(l), &Constant::Int(r)) => l == r,
67 (&Constant::F64(l), &Constant::F64(r)) => {
68 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
69 // `Fw32 == Fw64` so don’t compare them
70 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
71 unsafe { mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r) }
73 (&Constant::F32(l), &Constant::F32(r)) => {
74 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
75 // `Fw32 == Fw64` so don’t compare them
76 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
77 unsafe { mem::transmute::<f64, u64>(f64::from(l)) == mem::transmute::<f64, u64>(f64::from(r)) }
79 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
80 (&Constant::Vec(ref l), &Constant::Vec(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
81 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
82 _ => false, // TODO: Are there inter-type equalities?
87 impl Hash for Constant {
88 fn hash<H>(&self, state: &mut H)
93 Constant::Str(ref s) => {
96 Constant::Binary(ref b) => {
99 Constant::Char(c) => {
102 Constant::Int(i) => {
105 Constant::F32(f) => {
106 unsafe { mem::transmute::<f64, u64>(f64::from(f)) }.hash(state);
108 Constant::F64(f) => {
109 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
111 Constant::Bool(b) => {
114 Constant::Vec(ref v) | Constant::Tuple(ref v) => {
117 Constant::Repeat(ref c, l) => {
125 impl PartialOrd for Constant {
126 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
127 match (self, other) {
128 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => Some(ls.cmp(rs)),
129 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
130 (&Constant::Int(l), &Constant::Int(r)) => Some(l.cmp(&r)),
131 (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
132 (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
133 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
134 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => {
137 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => match lv.partial_cmp(rv) {
138 Some(Equal) => Some(ls.cmp(rs)),
141 _ => None, // TODO: Are there any useful inter-type orderings?
146 /// parse a `LitKind` to a `Constant`
147 pub fn lit_to_constant<'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
151 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
152 LitKind::Byte(b) => Constant::Int(u128::from(b)),
153 LitKind::ByteStr(ref s) => Constant::Binary(Rc::clone(s)),
154 LitKind::Char(c) => Constant::Char(c),
155 LitKind::Int(n, _) => Constant::Int(n),
156 LitKind::Float(ref is, _) |
157 LitKind::FloatUnsuffixed(ref is) => match ty.sty {
158 ty::TyFloat(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
159 ty::TyFloat(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
162 LitKind::Bool(b) => Constant::Bool(b),
166 pub fn constant<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<(Constant, bool)> {
167 let mut cx = ConstEvalLateContext {
170 param_env: lcx.param_env,
171 needed_resolution: false,
172 substs: lcx.tcx.intern_substs(&[]),
174 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
177 pub fn constant_simple<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<Constant> {
178 constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
181 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`
182 pub fn constant_context<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>) -> ConstEvalLateContext<'c, 'cc> {
183 ConstEvalLateContext {
186 param_env: lcx.param_env,
187 needed_resolution: false,
188 substs: lcx.tcx.intern_substs(&[]),
192 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
193 tcx: TyCtxt<'a, 'tcx, 'tcx>,
194 tables: &'a ty::TypeckTables<'tcx>,
195 param_env: ty::ParamEnv<'tcx>,
196 needed_resolution: bool,
197 substs: &'tcx Substs<'tcx>,
200 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
201 /// simple constant folding: Insert an expression, get a constant or none.
202 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
204 ExprPath(ref qpath) => self.fetch_path(qpath, e.hir_id),
205 ExprBlock(ref block, _) => self.block(block),
206 ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
207 ExprLit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
208 ExprArray(ref vec) => self.multi(vec).map(Constant::Vec),
209 ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
210 ExprRepeat(ref value, _) => {
211 let n = match self.tables.expr_ty(e).sty {
212 ty::TyArray(_, n) => n.assert_usize(self.tcx).expect("array length"),
213 _ => span_bug!(e.span, "typeck error"),
215 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n as u64))
217 ExprUnary(op, ref operand) => self.expr(operand).and_then(|o| match op {
218 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
219 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
222 ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
223 // TODO: add other expressions
228 fn constant_not(&self, o: &Constant, ty: ty::Ty) -> Option<Constant> {
229 use self::Constant::*;
231 Bool(b) => Some(Bool(!b)),
233 let mut value = !value;
235 ty::TyInt(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
236 ty::TyUint(ity) => Some(Int(clip(self.tcx, value, ity))),
244 fn constant_negate(&self, o: &Constant, ty: ty::Ty) -> Option<Constant> {
245 use self::Constant::*;
248 let ity = match ty.sty {
249 ty::TyInt(ity) => ity,
253 let value = sext(self.tcx, value, ity);
254 let value = value.checked_neg()?;
256 Some(Int(unsext(self.tcx, value, ity)))
258 F32(f) => Some(F32(-f)),
259 F64(f) => Some(F64(-f)),
264 /// create `Some(Vec![..])` of all constants, unless there is any
265 /// non-constant part
266 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
268 .map(|elem| self.expr(elem))
269 .collect::<Option<_>>()
272 /// lookup a possibly constant expression from a ExprPath
273 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
274 let def = self.tables.qpath_def(qpath, id);
276 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
277 let substs = self.tables.node_substs(id);
278 let substs = if self.substs.is_empty() {
281 substs.subst(self.tcx, self.substs)
283 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
288 use rustc::mir::interpret::GlobalId;
289 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
290 let ret = miri_to_const(self.tcx, result);
292 self.needed_resolution = true;
301 /// A block can only yield a constant if it only has one constant expression
302 fn block(&mut self, block: &Block) -> Option<Constant> {
303 if block.stmts.is_empty() {
304 block.expr.as_ref().and_then(|b| self.expr(b))
310 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
311 if let Some(Constant::Bool(b)) = self.expr(cond) {
315 otherwise.as_ref().and_then(|expr| self.expr(expr))
322 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
323 let l = self.expr(left)?;
324 let r = self.expr(right);
326 (Constant::Int(l), Some(Constant::Int(r))) => {
327 match self.tables.expr_ty(left).sty {
329 let l = sext(self.tcx, l, ity);
330 let r = sext(self.tcx, r, ity);
331 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
333 BiAdd => l.checked_add(r).map(zext),
334 BiSub => l.checked_sub(r).map(zext),
335 BiMul => l.checked_mul(r).map(zext),
336 BiDiv if r != 0 => l.checked_div(r).map(zext),
337 BiRem if r != 0 => l.checked_rem(r).map(zext),
338 BiShr => l.checked_shr(r as u128 as u32).map(zext),
339 BiShl => l.checked_shl(r as u128 as u32).map(zext),
340 BiBitXor => Some(zext(l ^ r)),
341 BiBitOr => Some(zext(l | r)),
342 BiBitAnd => Some(zext(l & r)),
343 BiEq => Some(Constant::Bool(l == r)),
344 BiNe => Some(Constant::Bool(l != r)),
345 BiLt => Some(Constant::Bool(l < r)),
346 BiLe => Some(Constant::Bool(l <= r)),
347 BiGe => Some(Constant::Bool(l >= r)),
348 BiGt => Some(Constant::Bool(l > r)),
354 BiAdd => l.checked_add(r).map(Constant::Int),
355 BiSub => l.checked_sub(r).map(Constant::Int),
356 BiMul => l.checked_mul(r).map(Constant::Int),
357 BiDiv => l.checked_div(r).map(Constant::Int),
358 BiRem => l.checked_rem(r).map(Constant::Int),
359 BiShr => l.checked_shr(r as u32).map(Constant::Int),
360 BiShl => l.checked_shl(r as u32).map(Constant::Int),
361 BiBitXor => Some(Constant::Int(l ^ r)),
362 BiBitOr => Some(Constant::Int(l | r)),
363 BiBitAnd => Some(Constant::Int(l & r)),
364 BiEq => Some(Constant::Bool(l == r)),
365 BiNe => Some(Constant::Bool(l != r)),
366 BiLt => Some(Constant::Bool(l < r)),
367 BiLe => Some(Constant::Bool(l <= r)),
368 BiGe => Some(Constant::Bool(l >= r)),
369 BiGt => Some(Constant::Bool(l > r)),
376 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
377 BiAdd => Some(Constant::F32(l + r)),
378 BiSub => Some(Constant::F32(l - r)),
379 BiMul => Some(Constant::F32(l * r)),
380 BiDiv => Some(Constant::F32(l / r)),
381 BiRem => Some(Constant::F32(l % r)),
382 BiEq => Some(Constant::Bool(l == r)),
383 BiNe => Some(Constant::Bool(l != r)),
384 BiLt => Some(Constant::Bool(l < r)),
385 BiLe => Some(Constant::Bool(l <= r)),
386 BiGe => Some(Constant::Bool(l >= r)),
387 BiGt => Some(Constant::Bool(l > r)),
390 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
391 BiAdd => Some(Constant::F64(l + r)),
392 BiSub => Some(Constant::F64(l - r)),
393 BiMul => Some(Constant::F64(l * r)),
394 BiDiv => Some(Constant::F64(l / r)),
395 BiRem => Some(Constant::F64(l % r)),
396 BiEq => Some(Constant::Bool(l == r)),
397 BiNe => Some(Constant::Bool(l != r)),
398 BiLt => Some(Constant::Bool(l < r)),
399 BiLe => Some(Constant::Bool(l <= r)),
400 BiGe => Some(Constant::Bool(l >= r)),
401 BiGt => Some(Constant::Bool(l > r)),
404 (l, r) => match (op.node, l, r) {
405 (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
406 (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
407 (BiAnd, Constant::Bool(true), Some(r)) | (BiOr, Constant::Bool(false), Some(r)) => Some(r),
408 (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
409 (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
410 (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
417 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
418 use rustc::mir::interpret::{PrimVal, ConstValue};
420 ConstVal::Value(ConstValue::ByVal(PrimVal::Bytes(b))) => match result.ty.sty {
421 ty::TyBool => Some(Constant::Bool(b == 1)),
422 ty::TyUint(_) | ty::TyInt(_) => Some(Constant::Int(b)),
423 ty::TyFloat(FloatTy::F32) => Some(Constant::F32(f32::from_bits(b as u32))),
424 ty::TyFloat(FloatTy::F64) => Some(Constant::F64(f64::from_bits(b as u64))),
425 // FIXME: implement other conversion
428 ConstVal::Value(ConstValue::ByValPair(PrimVal::Ptr(ptr), PrimVal::Bytes(n))) => match result.ty.sty {
429 ty::TyRef(_, tam, _) => match tam.sty {
433 .get_alloc(ptr.alloc_id)
435 let offset = ptr.offset as usize;
437 String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned()).ok().map(Constant::Str)
443 // FIXME: implement other conversions