1 #![allow(clippy::float_cmp)]
3 use crate::rustc::lint::LateContext;
4 use crate::rustc::{span_bug, bug};
5 use crate::rustc::hir::def::Def;
6 use crate::rustc::hir::*;
7 use crate::rustc::ty::{self, Ty, TyCtxt, Instance};
8 use crate::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 crate::syntax::ast::{FloatTy, LitKind};
15 use crate::syntax::ptr::P;
16 use crate::utils::{sext, unsext, clip};
18 /// A `LitKind`-like enum to fold constant `Expr`s into.
19 #[derive(Debug, Clone)]
23 /// a Binary String b"abc"
27 /// an integer's bit representation
35 /// an array of constants
37 /// also an array, but with only one constant, repeated N times
38 Repeat(Box<Constant>, u64),
39 /// a tuple of constants
43 impl PartialEq for Constant {
44 fn eq(&self, other: &Self) -> bool {
46 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => ls == rs,
47 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
48 (&Constant::Char(l), &Constant::Char(r)) => l == r,
49 (&Constant::Int(l), &Constant::Int(r)) => l == r,
50 (&Constant::F64(l), &Constant::F64(r)) => {
51 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
52 // `Fw32 == Fw64` so don’t compare them
53 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
54 unsafe { mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r) }
56 (&Constant::F32(l), &Constant::F32(r)) => {
57 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
58 // `Fw32 == Fw64` so don’t compare them
59 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
60 unsafe { mem::transmute::<f64, u64>(f64::from(l)) == mem::transmute::<f64, u64>(f64::from(r)) }
62 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
63 (&Constant::Vec(ref l), &Constant::Vec(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
64 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
65 _ => false, // TODO: Are there inter-type equalities?
70 impl Hash for Constant {
71 fn hash<H>(&self, state: &mut H)
76 Constant::Str(ref s) => {
79 Constant::Binary(ref b) => {
82 Constant::Char(c) => {
89 unsafe { mem::transmute::<f64, u64>(f64::from(f)) }.hash(state);
92 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
94 Constant::Bool(b) => {
97 Constant::Vec(ref v) | Constant::Tuple(ref v) => {
100 Constant::Repeat(ref c, l) => {
109 pub fn partial_cmp(tcx: TyCtxt<'_, '_, '_>, cmp_type: &ty::TyKind<'_>, left: &Self, right: &Self) -> Option<Ordering> {
110 match (left, right) {
111 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => Some(ls.cmp(rs)),
112 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
113 (&Constant::Int(l), &Constant::Int(r)) => {
114 if let ty::Int(int_ty) = *cmp_type {
115 Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
120 (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
121 (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
122 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
123 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l
126 .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
127 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
128 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
129 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
130 match Self::partial_cmp(tcx, cmp_type, lv, rv) {
131 Some(Equal) => Some(ls.cmp(rs)),
135 _ => None, // TODO: Are there any useful inter-type orderings?
140 /// parse a `LitKind` to a `Constant`
141 pub fn lit_to_constant<'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
142 use crate::syntax::ast::*;
145 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
146 LitKind::Byte(b) => Constant::Int(u128::from(b)),
147 LitKind::ByteStr(ref s) => Constant::Binary(Rc::clone(s)),
148 LitKind::Char(c) => Constant::Char(c),
149 LitKind::Int(n, _) => Constant::Int(n),
150 LitKind::Float(ref is, _) |
151 LitKind::FloatUnsuffixed(ref is) => match ty.sty {
152 ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
153 ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
156 LitKind::Bool(b) => Constant::Bool(b),
160 pub fn constant<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<(Constant, bool)> {
161 let mut cx = ConstEvalLateContext {
164 param_env: lcx.param_env,
165 needed_resolution: false,
166 substs: lcx.tcx.intern_substs(&[]),
168 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
171 pub fn constant_simple<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<Constant> {
172 constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
175 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`
176 pub fn constant_context<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>) -> ConstEvalLateContext<'c, 'cc> {
177 ConstEvalLateContext {
180 param_env: lcx.param_env,
181 needed_resolution: false,
182 substs: lcx.tcx.intern_substs(&[]),
186 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
187 tcx: TyCtxt<'a, 'tcx, 'tcx>,
188 tables: &'a ty::TypeckTables<'tcx>,
189 param_env: ty::ParamEnv<'tcx>,
190 needed_resolution: bool,
191 substs: &'tcx Substs<'tcx>,
194 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
195 /// simple constant folding: Insert an expression, get a constant or none.
196 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
198 ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
199 ExprKind::Block(ref block, _) => self.block(block),
200 ExprKind::If(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
201 ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
202 ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
203 ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
204 ExprKind::Repeat(ref value, _) => {
205 let n = match self.tables.expr_ty(e).sty {
206 ty::Array(_, n) => n.assert_usize(self.tcx).expect("array length"),
207 _ => span_bug!(e.span, "typeck error"),
209 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
211 ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
212 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
213 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
216 ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
217 // TODO: add other expressions
222 fn constant_not(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
223 use self::Constant::*;
225 Bool(b) => Some(Bool(!b)),
229 ty::Int(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
230 ty::Uint(ity) => Some(Int(clip(self.tcx, value, ity))),
238 fn constant_negate(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
239 use self::Constant::*;
242 let ity = match ty.sty {
247 let value = sext(self.tcx, value, ity);
248 let value = value.checked_neg()?;
250 Some(Int(unsext(self.tcx, value, ity)))
252 F32(f) => Some(F32(-f)),
253 F64(f) => Some(F64(-f)),
258 /// create `Some(Vec![..])` of all constants, unless there is any
259 /// non-constant part
260 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
262 .map(|elem| self.expr(elem))
263 .collect::<Option<_>>()
266 /// lookup a possibly constant expression from a ExprKind::Path
267 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
268 let def = self.tables.qpath_def(qpath, id);
270 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
271 let substs = self.tables.node_substs(id);
272 let substs = if self.substs.is_empty() {
275 substs.subst(self.tcx, self.substs)
277 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
282 use crate::rustc::mir::interpret::GlobalId;
283 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
284 let ret = miri_to_const(self.tcx, result);
286 self.needed_resolution = true;
295 /// A block can only yield a constant if it only has one constant expression
296 fn block(&mut self, block: &Block) -> Option<Constant> {
297 if block.stmts.is_empty() {
298 block.expr.as_ref().and_then(|b| self.expr(b))
304 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
305 if let Some(Constant::Bool(b)) = self.expr(cond) {
309 otherwise.as_ref().and_then(|expr| self.expr(expr))
316 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
317 let l = self.expr(left)?;
318 let r = self.expr(right);
320 (Constant::Int(l), Some(Constant::Int(r))) => {
321 match self.tables.expr_ty(left).sty {
323 let l = sext(self.tcx, l, ity);
324 let r = sext(self.tcx, r, ity);
325 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
327 BinOpKind::Add => l.checked_add(r).map(zext),
328 BinOpKind::Sub => l.checked_sub(r).map(zext),
329 BinOpKind::Mul => l.checked_mul(r).map(zext),
330 BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
331 BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
332 BinOpKind::Shr => l.checked_shr(r as u128 as u32).map(zext),
333 BinOpKind::Shl => l.checked_shl(r as u128 as u32).map(zext),
334 BinOpKind::BitXor => Some(zext(l ^ r)),
335 BinOpKind::BitOr => Some(zext(l | r)),
336 BinOpKind::BitAnd => Some(zext(l & r)),
337 BinOpKind::Eq => Some(Constant::Bool(l == r)),
338 BinOpKind::Ne => Some(Constant::Bool(l != r)),
339 BinOpKind::Lt => Some(Constant::Bool(l < r)),
340 BinOpKind::Le => Some(Constant::Bool(l <= r)),
341 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
342 BinOpKind::Gt => Some(Constant::Bool(l > r)),
348 BinOpKind::Add => l.checked_add(r).map(Constant::Int),
349 BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
350 BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
351 BinOpKind::Div => l.checked_div(r).map(Constant::Int),
352 BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
353 BinOpKind::Shr => l.checked_shr(r as u32).map(Constant::Int),
354 BinOpKind::Shl => l.checked_shl(r as u32).map(Constant::Int),
355 BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
356 BinOpKind::BitOr => Some(Constant::Int(l | r)),
357 BinOpKind::BitAnd => Some(Constant::Int(l & r)),
358 BinOpKind::Eq => Some(Constant::Bool(l == r)),
359 BinOpKind::Ne => Some(Constant::Bool(l != r)),
360 BinOpKind::Lt => Some(Constant::Bool(l < r)),
361 BinOpKind::Le => Some(Constant::Bool(l <= r)),
362 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
363 BinOpKind::Gt => Some(Constant::Bool(l > r)),
370 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
371 BinOpKind::Add => Some(Constant::F32(l + r)),
372 BinOpKind::Sub => Some(Constant::F32(l - r)),
373 BinOpKind::Mul => Some(Constant::F32(l * r)),
374 BinOpKind::Div => Some(Constant::F32(l / r)),
375 BinOpKind::Rem => Some(Constant::F32(l % r)),
376 BinOpKind::Eq => Some(Constant::Bool(l == r)),
377 BinOpKind::Ne => Some(Constant::Bool(l != r)),
378 BinOpKind::Lt => Some(Constant::Bool(l < r)),
379 BinOpKind::Le => Some(Constant::Bool(l <= r)),
380 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
381 BinOpKind::Gt => Some(Constant::Bool(l > r)),
384 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
385 BinOpKind::Add => Some(Constant::F64(l + r)),
386 BinOpKind::Sub => Some(Constant::F64(l - r)),
387 BinOpKind::Mul => Some(Constant::F64(l * r)),
388 BinOpKind::Div => Some(Constant::F64(l / r)),
389 BinOpKind::Rem => Some(Constant::F64(l % r)),
390 BinOpKind::Eq => Some(Constant::Bool(l == r)),
391 BinOpKind::Ne => Some(Constant::Bool(l != r)),
392 BinOpKind::Lt => Some(Constant::Bool(l < r)),
393 BinOpKind::Le => Some(Constant::Bool(l <= r)),
394 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
395 BinOpKind::Gt => Some(Constant::Bool(l > r)),
398 (l, r) => match (op.node, l, r) {
399 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
400 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
401 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => Some(r),
402 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
403 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
404 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
411 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
412 use crate::rustc::mir::interpret::{Scalar, ConstValue};
414 ConstValue::Scalar(Scalar::Bits{ bits: b, ..}) => match result.ty.sty {
415 ty::Bool => Some(Constant::Bool(b == 1)),
416 ty::Uint(_) | ty::Int(_) => Some(Constant::Int(b)),
417 ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(b as u32))),
418 ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(b as u64))),
419 // FIXME: implement other conversion
422 ConstValue::ScalarPair(Scalar::Ptr(ptr),
423 Scalar::Bits { bits: n, .. }) => match result.ty.sty {
424 ty::Ref(_, tam, _) => match tam.sty {
429 .unwrap_memory(ptr.alloc_id);
430 let offset = ptr.offset.bytes() as usize;
432 String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned()).ok().map(Constant::Str)
438 // FIXME: implement other conversions