1 #![allow(cast_possible_truncation)]
4 use rustc::lint::LateContext;
5 use rustc::{span_bug, bug};
6 use rustc::hir::def::Def;
8 use rustc::ty::{self, Ty, TyCtxt, Instance};
9 use rustc::ty::subst::{Subst, Substs};
10 use std::cmp::Ordering::{self, Equal};
11 use std::cmp::PartialOrd;
12 use std::hash::{Hash, Hasher};
15 use syntax::ast::{FloatTy, LitKind};
17 use crate::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) => {
126 pub fn partial_cmp(tcx: TyCtxt<'_, '_, '_>, cmp_type: &ty::TypeVariants<'_>, left: &Self, right: &Self) -> Option<Ordering> {
127 match (left, right) {
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)) => {
131 if let ty::TyInt(int_ty) = *cmp_type {
132 Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
137 (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
138 (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
139 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
140 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l
143 .map(|(li, ri)| Constant::partial_cmp(tcx, cmp_type, li, ri))
144 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
145 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
146 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
147 match Constant::partial_cmp(tcx, cmp_type, lv, rv) {
148 Some(Equal) => Some(ls.cmp(rs)),
152 _ => None, // TODO: Are there any useful inter-type orderings?
157 /// parse a `LitKind` to a `Constant`
158 pub fn lit_to_constant<'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
162 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
163 LitKind::Byte(b) => Constant::Int(u128::from(b)),
164 LitKind::ByteStr(ref s) => Constant::Binary(Rc::clone(s)),
165 LitKind::Char(c) => Constant::Char(c),
166 LitKind::Int(n, _) => Constant::Int(n),
167 LitKind::Float(ref is, _) |
168 LitKind::FloatUnsuffixed(ref is) => match ty.sty {
169 ty::TyFloat(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
170 ty::TyFloat(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
173 LitKind::Bool(b) => Constant::Bool(b),
177 pub fn constant<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<(Constant, bool)> {
178 let mut cx = ConstEvalLateContext {
181 param_env: lcx.param_env,
182 needed_resolution: false,
183 substs: lcx.tcx.intern_substs(&[]),
185 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
188 pub fn constant_simple<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<Constant> {
189 constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
192 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`
193 pub fn constant_context<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>) -> ConstEvalLateContext<'c, 'cc> {
194 ConstEvalLateContext {
197 param_env: lcx.param_env,
198 needed_resolution: false,
199 substs: lcx.tcx.intern_substs(&[]),
203 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
204 tcx: TyCtxt<'a, 'tcx, 'tcx>,
205 tables: &'a ty::TypeckTables<'tcx>,
206 param_env: ty::ParamEnv<'tcx>,
207 needed_resolution: bool,
208 substs: &'tcx Substs<'tcx>,
211 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
212 /// simple constant folding: Insert an expression, get a constant or none.
213 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
215 ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
216 ExprKind::Block(ref block, _) => self.block(block),
217 ExprKind::If(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
218 ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
219 ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
220 ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
221 ExprKind::Repeat(ref value, _) => {
222 let n = match self.tables.expr_ty(e).sty {
223 ty::TyArray(_, n) => n.assert_usize(self.tcx).expect("array length"),
224 _ => span_bug!(e.span, "typeck error"),
226 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n as u64))
228 ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
229 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
230 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
233 ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
234 // TODO: add other expressions
239 fn constant_not(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
240 use self::Constant::*;
242 Bool(b) => Some(Bool(!b)),
244 let mut value = !value;
246 ty::TyInt(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
247 ty::TyUint(ity) => Some(Int(clip(self.tcx, value, ity))),
255 fn constant_negate(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
256 use self::Constant::*;
259 let ity = match ty.sty {
260 ty::TyInt(ity) => ity,
264 let value = sext(self.tcx, value, ity);
265 let value = value.checked_neg()?;
267 Some(Int(unsext(self.tcx, value, ity)))
269 F32(f) => Some(F32(-f)),
270 F64(f) => Some(F64(-f)),
275 /// create `Some(Vec![..])` of all constants, unless there is any
276 /// non-constant part
277 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
279 .map(|elem| self.expr(elem))
280 .collect::<Option<_>>()
283 /// lookup a possibly constant expression from a ExprKind::Path
284 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
285 let def = self.tables.qpath_def(qpath, id);
287 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
288 let substs = self.tables.node_substs(id);
289 let substs = if self.substs.is_empty() {
292 substs.subst(self.tcx, self.substs)
294 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
299 use rustc::mir::interpret::GlobalId;
300 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
301 let ret = miri_to_const(self.tcx, result);
303 self.needed_resolution = true;
312 /// A block can only yield a constant if it only has one constant expression
313 fn block(&mut self, block: &Block) -> Option<Constant> {
314 if block.stmts.is_empty() {
315 block.expr.as_ref().and_then(|b| self.expr(b))
321 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
322 if let Some(Constant::Bool(b)) = self.expr(cond) {
326 otherwise.as_ref().and_then(|expr| self.expr(expr))
333 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
334 let l = self.expr(left)?;
335 let r = self.expr(right);
337 (Constant::Int(l), Some(Constant::Int(r))) => {
338 match self.tables.expr_ty(left).sty {
340 let l = sext(self.tcx, l, ity);
341 let r = sext(self.tcx, r, ity);
342 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
344 BinOpKind::Add => l.checked_add(r).map(zext),
345 BinOpKind::Sub => l.checked_sub(r).map(zext),
346 BinOpKind::Mul => l.checked_mul(r).map(zext),
347 BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
348 BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
349 BinOpKind::Shr => l.checked_shr(r as u128 as u32).map(zext),
350 BinOpKind::Shl => l.checked_shl(r as u128 as u32).map(zext),
351 BinOpKind::BitXor => Some(zext(l ^ r)),
352 BinOpKind::BitOr => Some(zext(l | r)),
353 BinOpKind::BitAnd => Some(zext(l & r)),
354 BinOpKind::Eq => Some(Constant::Bool(l == r)),
355 BinOpKind::Ne => Some(Constant::Bool(l != r)),
356 BinOpKind::Lt => Some(Constant::Bool(l < r)),
357 BinOpKind::Le => Some(Constant::Bool(l <= r)),
358 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
359 BinOpKind::Gt => Some(Constant::Bool(l > r)),
365 BinOpKind::Add => l.checked_add(r).map(Constant::Int),
366 BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
367 BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
368 BinOpKind::Div => l.checked_div(r).map(Constant::Int),
369 BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
370 BinOpKind::Shr => l.checked_shr(r as u32).map(Constant::Int),
371 BinOpKind::Shl => l.checked_shl(r as u32).map(Constant::Int),
372 BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
373 BinOpKind::BitOr => Some(Constant::Int(l | r)),
374 BinOpKind::BitAnd => Some(Constant::Int(l & r)),
375 BinOpKind::Eq => Some(Constant::Bool(l == r)),
376 BinOpKind::Ne => Some(Constant::Bool(l != r)),
377 BinOpKind::Lt => Some(Constant::Bool(l < r)),
378 BinOpKind::Le => Some(Constant::Bool(l <= r)),
379 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
380 BinOpKind::Gt => Some(Constant::Bool(l > r)),
387 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
388 BinOpKind::Add => Some(Constant::F32(l + r)),
389 BinOpKind::Sub => Some(Constant::F32(l - r)),
390 BinOpKind::Mul => Some(Constant::F32(l * r)),
391 BinOpKind::Div => Some(Constant::F32(l / r)),
392 BinOpKind::Rem => Some(Constant::F32(l % r)),
393 BinOpKind::Eq => Some(Constant::Bool(l == r)),
394 BinOpKind::Ne => Some(Constant::Bool(l != r)),
395 BinOpKind::Lt => Some(Constant::Bool(l < r)),
396 BinOpKind::Le => Some(Constant::Bool(l <= r)),
397 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
398 BinOpKind::Gt => Some(Constant::Bool(l > r)),
401 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
402 BinOpKind::Add => Some(Constant::F64(l + r)),
403 BinOpKind::Sub => Some(Constant::F64(l - r)),
404 BinOpKind::Mul => Some(Constant::F64(l * r)),
405 BinOpKind::Div => Some(Constant::F64(l / r)),
406 BinOpKind::Rem => Some(Constant::F64(l % r)),
407 BinOpKind::Eq => Some(Constant::Bool(l == r)),
408 BinOpKind::Ne => Some(Constant::Bool(l != r)),
409 BinOpKind::Lt => Some(Constant::Bool(l < r)),
410 BinOpKind::Le => Some(Constant::Bool(l <= r)),
411 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
412 BinOpKind::Gt => Some(Constant::Bool(l > r)),
415 (l, r) => match (op.node, l, r) {
416 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
417 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
418 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => Some(r),
419 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
420 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
421 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
428 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
429 use rustc::mir::interpret::{Scalar, ConstValue};
431 ConstValue::Scalar(Scalar::Bits{ bits: b, ..}) => match result.ty.sty {
432 ty::TyBool => Some(Constant::Bool(b == 1)),
433 ty::TyUint(_) | ty::TyInt(_) => Some(Constant::Int(b)),
434 ty::TyFloat(FloatTy::F32) => Some(Constant::F32(f32::from_bits(b as u32))),
435 ty::TyFloat(FloatTy::F64) => Some(Constant::F64(f64::from_bits(b as u64))),
436 // FIXME: implement other conversion
439 ConstValue::ScalarPair(Scalar::Ptr(ptr), Scalar::Bits { bits: n, .. }) => match result.ty.sty {
440 ty::TyRef(_, tam, _) => match tam.sty {
445 .unwrap_memory(ptr.alloc_id);
446 let offset = ptr.offset.bytes() as usize;
448 String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned()).ok().map(Constant::Str)
454 // FIXME: implement other conversions