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 crate::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>(f64::from(l)) == mem::transmute::<f64, u64>(f64::from(r)) }
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>(f64::from(f)) }.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) => {
125 pub fn partial_cmp(tcx: TyCtxt, cmp_type: &ty::TypeVariants, left: &Self, right: &Self) -> Option<Ordering> {
126 match (left, right) {
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)) => {
130 if let ty::TyInt(int_ty) = *cmp_type {
131 Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
136 (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
137 (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
138 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
139 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l
142 .map(|(li, ri)| Constant::partial_cmp(tcx, cmp_type, li, ri))
143 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
144 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
145 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
146 match Constant::partial_cmp(tcx, cmp_type, lv, rv) {
147 Some(Equal) => Some(ls.cmp(rs)),
151 _ => None, // TODO: Are there any useful inter-type orderings?
156 /// parse a `LitKind` to a `Constant`
157 pub fn lit_to_constant<'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
161 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
162 LitKind::Byte(b) => Constant::Int(u128::from(b)),
163 LitKind::ByteStr(ref s) => Constant::Binary(Rc::clone(s)),
164 LitKind::Char(c) => Constant::Char(c),
165 LitKind::Int(n, _) => Constant::Int(n),
166 LitKind::Float(ref is, _) |
167 LitKind::FloatUnsuffixed(ref is) => match ty.sty {
168 ty::TyFloat(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
169 ty::TyFloat(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
172 LitKind::Bool(b) => Constant::Bool(b),
176 pub fn constant<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<(Constant, bool)> {
177 let mut cx = ConstEvalLateContext {
180 param_env: lcx.param_env,
181 needed_resolution: false,
182 substs: lcx.tcx.intern_substs(&[]),
184 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
187 pub fn constant_simple<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<Constant> {
188 constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
191 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`
192 pub fn constant_context<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>) -> ConstEvalLateContext<'c, 'cc> {
193 ConstEvalLateContext {
196 param_env: lcx.param_env,
197 needed_resolution: false,
198 substs: lcx.tcx.intern_substs(&[]),
202 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
203 tcx: TyCtxt<'a, 'tcx, 'tcx>,
204 tables: &'a ty::TypeckTables<'tcx>,
205 param_env: ty::ParamEnv<'tcx>,
206 needed_resolution: bool,
207 substs: &'tcx Substs<'tcx>,
210 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
211 /// simple constant folding: Insert an expression, get a constant or none.
212 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
214 ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
215 ExprKind::Block(ref block, _) => self.block(block),
216 ExprKind::If(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
217 ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
218 ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
219 ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
220 ExprKind::Repeat(ref value, _) => {
221 let n = match self.tables.expr_ty(e).sty {
222 ty::TyArray(_, n) => n.assert_usize(self.tcx).expect("array length"),
223 _ => span_bug!(e.span, "typeck error"),
225 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n as u64))
227 ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
228 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
229 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
232 ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
233 // TODO: add other expressions
238 fn constant_not(&self, o: &Constant, ty: ty::Ty) -> Option<Constant> {
239 use self::Constant::*;
241 Bool(b) => Some(Bool(!b)),
243 let mut value = !value;
245 ty::TyInt(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
246 ty::TyUint(ity) => Some(Int(clip(self.tcx, value, ity))),
254 fn constant_negate(&self, o: &Constant, ty: ty::Ty) -> Option<Constant> {
255 use self::Constant::*;
258 let ity = match ty.sty {
259 ty::TyInt(ity) => ity,
263 let value = sext(self.tcx, value, ity);
264 let value = value.checked_neg()?;
266 Some(Int(unsext(self.tcx, value, ity)))
268 F32(f) => Some(F32(-f)),
269 F64(f) => Some(F64(-f)),
274 /// create `Some(Vec![..])` of all constants, unless there is any
275 /// non-constant part
276 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
278 .map(|elem| self.expr(elem))
279 .collect::<Option<_>>()
282 /// lookup a possibly constant expression from a ExprKind::Path
283 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
284 let def = self.tables.qpath_def(qpath, id);
286 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
287 let substs = self.tables.node_substs(id);
288 let substs = if self.substs.is_empty() {
291 substs.subst(self.tcx, self.substs)
293 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
298 use rustc::mir::interpret::GlobalId;
299 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
300 let ret = miri_to_const(self.tcx, result);
302 self.needed_resolution = true;
311 /// A block can only yield a constant if it only has one constant expression
312 fn block(&mut self, block: &Block) -> Option<Constant> {
313 if block.stmts.is_empty() {
314 block.expr.as_ref().and_then(|b| self.expr(b))
320 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
321 if let Some(Constant::Bool(b)) = self.expr(cond) {
325 otherwise.as_ref().and_then(|expr| self.expr(expr))
332 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
333 let l = self.expr(left)?;
334 let r = self.expr(right);
336 (Constant::Int(l), Some(Constant::Int(r))) => {
337 match self.tables.expr_ty(left).sty {
339 let l = sext(self.tcx, l, ity);
340 let r = sext(self.tcx, r, ity);
341 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
343 BiAdd => l.checked_add(r).map(zext),
344 BiSub => l.checked_sub(r).map(zext),
345 BiMul => l.checked_mul(r).map(zext),
346 BiDiv if r != 0 => l.checked_div(r).map(zext),
347 BiRem if r != 0 => l.checked_rem(r).map(zext),
348 BiShr => l.checked_shr(r as u128 as u32).map(zext),
349 BiShl => l.checked_shl(r as u128 as u32).map(zext),
350 BiBitXor => Some(zext(l ^ r)),
351 BiBitOr => Some(zext(l | r)),
352 BiBitAnd => Some(zext(l & r)),
353 BiEq => Some(Constant::Bool(l == r)),
354 BiNe => Some(Constant::Bool(l != r)),
355 BiLt => Some(Constant::Bool(l < r)),
356 BiLe => Some(Constant::Bool(l <= r)),
357 BiGe => Some(Constant::Bool(l >= r)),
358 BiGt => Some(Constant::Bool(l > r)),
364 BiAdd => l.checked_add(r).map(Constant::Int),
365 BiSub => l.checked_sub(r).map(Constant::Int),
366 BiMul => l.checked_mul(r).map(Constant::Int),
367 BiDiv => l.checked_div(r).map(Constant::Int),
368 BiRem => l.checked_rem(r).map(Constant::Int),
369 BiShr => l.checked_shr(r as u32).map(Constant::Int),
370 BiShl => l.checked_shl(r as u32).map(Constant::Int),
371 BiBitXor => Some(Constant::Int(l ^ r)),
372 BiBitOr => Some(Constant::Int(l | r)),
373 BiBitAnd => Some(Constant::Int(l & r)),
374 BiEq => Some(Constant::Bool(l == r)),
375 BiNe => Some(Constant::Bool(l != r)),
376 BiLt => Some(Constant::Bool(l < r)),
377 BiLe => Some(Constant::Bool(l <= r)),
378 BiGe => Some(Constant::Bool(l >= r)),
379 BiGt => Some(Constant::Bool(l > r)),
386 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
387 BiAdd => Some(Constant::F32(l + r)),
388 BiSub => Some(Constant::F32(l - r)),
389 BiMul => Some(Constant::F32(l * r)),
390 BiDiv => Some(Constant::F32(l / r)),
391 BiRem => Some(Constant::F32(l % r)),
392 BiEq => Some(Constant::Bool(l == r)),
393 BiNe => Some(Constant::Bool(l != r)),
394 BiLt => Some(Constant::Bool(l < r)),
395 BiLe => Some(Constant::Bool(l <= r)),
396 BiGe => Some(Constant::Bool(l >= r)),
397 BiGt => Some(Constant::Bool(l > r)),
400 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
401 BiAdd => Some(Constant::F64(l + r)),
402 BiSub => Some(Constant::F64(l - r)),
403 BiMul => Some(Constant::F64(l * r)),
404 BiDiv => Some(Constant::F64(l / r)),
405 BiRem => Some(Constant::F64(l % r)),
406 BiEq => Some(Constant::Bool(l == r)),
407 BiNe => Some(Constant::Bool(l != r)),
408 BiLt => Some(Constant::Bool(l < r)),
409 BiLe => Some(Constant::Bool(l <= r)),
410 BiGe => Some(Constant::Bool(l >= r)),
411 BiGt => Some(Constant::Bool(l > r)),
414 (l, r) => match (op.node, l, r) {
415 (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
416 (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
417 (BiAnd, Constant::Bool(true), Some(r)) | (BiOr, Constant::Bool(false), Some(r)) => Some(r),
418 (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
419 (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
420 (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
427 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
428 use rustc::mir::interpret::{Scalar, ConstValue};
430 ConstValue::Scalar(Scalar::Bits{ bits: b, ..}) => match result.ty.sty {
431 ty::TyBool => Some(Constant::Bool(b == 1)),
432 ty::TyUint(_) | ty::TyInt(_) => Some(Constant::Int(b)),
433 ty::TyFloat(FloatTy::F32) => Some(Constant::F32(f32::from_bits(b as u32))),
434 ty::TyFloat(FloatTy::F64) => Some(Constant::F64(f64::from_bits(b as u64))),
435 // FIXME: implement other conversion
438 ConstValue::ScalarPair(Scalar::Ptr(ptr), Scalar::Bits { bits: n, .. }) => match result.ty.sty {
439 ty::TyRef(_, tam, _) => match tam.sty {
444 .unwrap_memory(ptr.alloc_id);
445 let offset = ptr.offset.bytes() as usize;
447 String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned()).ok().map(Constant::Str)
453 // FIXME: implement other conversions