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 /// A `LitKind`-like enum to fold constant `Expr`s into.
20 #[derive(Debug, Clone)]
24 /// a Binary String b"abc"
28 /// an integer's bit representation
36 /// an array of constants
38 /// also an array, but with only one constant, repeated N times
39 Repeat(Box<Constant>, u64),
40 /// a tuple of constants
44 impl PartialEq for Constant {
45 fn eq(&self, other: &Self) -> bool {
47 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => ls == rs,
48 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
49 (&Constant::Char(l), &Constant::Char(r)) => l == r,
50 (&Constant::Int(l), &Constant::Int(r)) => l == r,
51 (&Constant::F64(l), &Constant::F64(r)) => {
52 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
53 // `Fw32 == Fw64` so don’t compare them
54 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
55 unsafe { mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r) }
57 (&Constant::F32(l), &Constant::F32(r)) => {
58 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
59 // `Fw32 == Fw64` so don’t compare them
60 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
61 unsafe { mem::transmute::<f64, u64>(f64::from(l)) == mem::transmute::<f64, u64>(f64::from(r)) }
63 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
64 (&Constant::Vec(ref l), &Constant::Vec(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
65 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
66 _ => false, // TODO: Are there inter-type equalities?
71 impl Hash for Constant {
72 fn hash<H>(&self, state: &mut H)
77 Constant::Str(ref s) => {
80 Constant::Binary(ref b) => {
83 Constant::Char(c) => {
90 unsafe { mem::transmute::<f64, u64>(f64::from(f)) }.hash(state);
93 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
95 Constant::Bool(b) => {
98 Constant::Vec(ref v) | Constant::Tuple(ref v) => {
101 Constant::Repeat(ref c, l) => {
110 pub fn partial_cmp(tcx: TyCtxt<'_, '_, '_>, cmp_type: &ty::TyKind<'_>, left: &Self, right: &Self) -> Option<Ordering> {
111 match (left, right) {
112 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => Some(ls.cmp(rs)),
113 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
114 (&Constant::Int(l), &Constant::Int(r)) => {
115 if let ty::Int(int_ty) = *cmp_type {
116 Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
121 (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
122 (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
123 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
124 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l
127 .map(|(li, ri)| Constant::partial_cmp(tcx, cmp_type, li, ri))
128 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
129 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
130 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
131 match Constant::partial_cmp(tcx, cmp_type, lv, rv) {
132 Some(Equal) => Some(ls.cmp(rs)),
136 _ => None, // TODO: Are there any useful inter-type orderings?
141 /// parse a `LitKind` to a `Constant`
142 pub fn lit_to_constant<'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
146 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
147 LitKind::Byte(b) => Constant::Int(u128::from(b)),
148 LitKind::ByteStr(ref s) => Constant::Binary(Rc::clone(s)),
149 LitKind::Char(c) => Constant::Char(c),
150 LitKind::Int(n, _) => Constant::Int(n),
151 LitKind::Float(ref is, _) |
152 LitKind::FloatUnsuffixed(ref is) => match ty.sty {
153 ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
154 ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
157 LitKind::Bool(b) => Constant::Bool(b),
161 pub fn constant<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<(Constant, bool)> {
162 let mut cx = ConstEvalLateContext {
165 param_env: lcx.param_env,
166 needed_resolution: false,
167 substs: lcx.tcx.intern_substs(&[]),
169 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
172 pub fn constant_simple<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<Constant> {
173 constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
176 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`
177 pub fn constant_context<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>) -> ConstEvalLateContext<'c, 'cc> {
178 ConstEvalLateContext {
181 param_env: lcx.param_env,
182 needed_resolution: false,
183 substs: lcx.tcx.intern_substs(&[]),
187 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
188 tcx: TyCtxt<'a, 'tcx, 'tcx>,
189 tables: &'a ty::TypeckTables<'tcx>,
190 param_env: ty::ParamEnv<'tcx>,
191 needed_resolution: bool,
192 substs: &'tcx Substs<'tcx>,
195 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
196 /// simple constant folding: Insert an expression, get a constant or none.
197 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
199 ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
200 ExprKind::Block(ref block, _) => self.block(block),
201 ExprKind::If(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
202 ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
203 ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
204 ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
205 ExprKind::Repeat(ref value, _) => {
206 let n = match self.tables.expr_ty(e).sty {
207 ty::Array(_, n) => n.assert_usize(self.tcx).expect("array length"),
208 _ => span_bug!(e.span, "typeck error"),
210 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n as u64))
212 ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
213 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
214 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
217 ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
218 // TODO: add other expressions
223 fn constant_not(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
224 use self::Constant::*;
226 Bool(b) => Some(Bool(!b)),
230 ty::Int(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
231 ty::Uint(ity) => Some(Int(clip(self.tcx, value, ity))),
239 fn constant_negate(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
240 use self::Constant::*;
243 let ity = match ty.sty {
248 let value = sext(self.tcx, value, ity);
249 let value = value.checked_neg()?;
251 Some(Int(unsext(self.tcx, value, ity)))
253 F32(f) => Some(F32(-f)),
254 F64(f) => Some(F64(-f)),
259 /// create `Some(Vec![..])` of all constants, unless there is any
260 /// non-constant part
261 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
263 .map(|elem| self.expr(elem))
264 .collect::<Option<_>>()
267 /// lookup a possibly constant expression from a ExprKind::Path
268 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
269 let def = self.tables.qpath_def(qpath, id);
271 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
272 let substs = self.tables.node_substs(id);
273 let substs = if self.substs.is_empty() {
276 substs.subst(self.tcx, self.substs)
278 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
283 use rustc::mir::interpret::GlobalId;
284 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
285 let ret = miri_to_const(self.tcx, result);
287 self.needed_resolution = true;
296 /// A block can only yield a constant if it only has one constant expression
297 fn block(&mut self, block: &Block) -> Option<Constant> {
298 if block.stmts.is_empty() {
299 block.expr.as_ref().and_then(|b| self.expr(b))
305 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
306 if let Some(Constant::Bool(b)) = self.expr(cond) {
310 otherwise.as_ref().and_then(|expr| self.expr(expr))
317 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
318 let l = self.expr(left)?;
319 let r = self.expr(right);
321 (Constant::Int(l), Some(Constant::Int(r))) => {
322 match self.tables.expr_ty(left).sty {
324 let l = sext(self.tcx, l, ity);
325 let r = sext(self.tcx, r, ity);
326 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
328 BinOpKind::Add => l.checked_add(r).map(zext),
329 BinOpKind::Sub => l.checked_sub(r).map(zext),
330 BinOpKind::Mul => l.checked_mul(r).map(zext),
331 BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
332 BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
333 BinOpKind::Shr => l.checked_shr(r as u128 as u32).map(zext),
334 BinOpKind::Shl => l.checked_shl(r as u128 as u32).map(zext),
335 BinOpKind::BitXor => Some(zext(l ^ r)),
336 BinOpKind::BitOr => Some(zext(l | r)),
337 BinOpKind::BitAnd => Some(zext(l & r)),
338 BinOpKind::Eq => Some(Constant::Bool(l == r)),
339 BinOpKind::Ne => Some(Constant::Bool(l != r)),
340 BinOpKind::Lt => Some(Constant::Bool(l < r)),
341 BinOpKind::Le => Some(Constant::Bool(l <= r)),
342 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
343 BinOpKind::Gt => Some(Constant::Bool(l > r)),
349 BinOpKind::Add => l.checked_add(r).map(Constant::Int),
350 BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
351 BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
352 BinOpKind::Div => l.checked_div(r).map(Constant::Int),
353 BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
354 BinOpKind::Shr => l.checked_shr(r as u32).map(Constant::Int),
355 BinOpKind::Shl => l.checked_shl(r as u32).map(Constant::Int),
356 BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
357 BinOpKind::BitOr => Some(Constant::Int(l | r)),
358 BinOpKind::BitAnd => Some(Constant::Int(l & r)),
359 BinOpKind::Eq => Some(Constant::Bool(l == r)),
360 BinOpKind::Ne => Some(Constant::Bool(l != r)),
361 BinOpKind::Lt => Some(Constant::Bool(l < r)),
362 BinOpKind::Le => Some(Constant::Bool(l <= r)),
363 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
364 BinOpKind::Gt => Some(Constant::Bool(l > r)),
371 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
372 BinOpKind::Add => Some(Constant::F32(l + r)),
373 BinOpKind::Sub => Some(Constant::F32(l - r)),
374 BinOpKind::Mul => Some(Constant::F32(l * r)),
375 BinOpKind::Div => Some(Constant::F32(l / r)),
376 BinOpKind::Rem => Some(Constant::F32(l % r)),
377 BinOpKind::Eq => Some(Constant::Bool(l == r)),
378 BinOpKind::Ne => Some(Constant::Bool(l != r)),
379 BinOpKind::Lt => Some(Constant::Bool(l < r)),
380 BinOpKind::Le => Some(Constant::Bool(l <= r)),
381 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
382 BinOpKind::Gt => Some(Constant::Bool(l > r)),
385 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
386 BinOpKind::Add => Some(Constant::F64(l + r)),
387 BinOpKind::Sub => Some(Constant::F64(l - r)),
388 BinOpKind::Mul => Some(Constant::F64(l * r)),
389 BinOpKind::Div => Some(Constant::F64(l / r)),
390 BinOpKind::Rem => Some(Constant::F64(l % r)),
391 BinOpKind::Eq => Some(Constant::Bool(l == r)),
392 BinOpKind::Ne => Some(Constant::Bool(l != r)),
393 BinOpKind::Lt => Some(Constant::Bool(l < r)),
394 BinOpKind::Le => Some(Constant::Bool(l <= r)),
395 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
396 BinOpKind::Gt => Some(Constant::Bool(l > r)),
399 (l, r) => match (op.node, l, r) {
400 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
401 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
402 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => Some(r),
403 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
404 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
405 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
412 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
413 use rustc::mir::interpret::{Scalar, ScalarMaybeUndef, ConstValue};
415 ConstValue::Scalar(Scalar::Bits{ bits: b, ..}) => match result.ty.sty {
416 ty::Bool => Some(Constant::Bool(b == 1)),
417 ty::Uint(_) | ty::Int(_) => Some(Constant::Int(b)),
418 ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(b as u32))),
419 ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(b as u64))),
420 // FIXME: implement other conversion
423 ConstValue::ScalarPair(Scalar::Ptr(ptr),
424 ScalarMaybeUndef::Scalar(
425 Scalar::Bits { bits: n, .. })) => match result.ty.sty {
426 ty::Ref(_, tam, _) => match tam.sty {
431 .unwrap_memory(ptr.alloc_id);
432 let offset = ptr.offset.bytes() as usize;
434 String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned()).ok().map(Constant::Str)
440 // FIXME: implement other conversions