1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 #![allow(clippy::float_cmp)]
13 use crate::rustc::lint::LateContext;
14 use crate::rustc::{span_bug, bug};
15 use crate::rustc::hir::def::Def;
16 use crate::rustc::hir::*;
17 use crate::rustc::ty::{self, Ty, TyCtxt, Instance};
18 use crate::rustc::ty::subst::{Subst, Substs};
19 use std::cmp::Ordering::{self, Equal};
20 use std::cmp::PartialOrd;
21 use std::hash::{Hash, Hasher};
24 use crate::syntax::ast::{FloatTy, LitKind};
25 use crate::syntax::ptr::P;
26 use crate::utils::{sext, unsext, clip};
28 /// A `LitKind`-like enum to fold constant `Expr`s into.
29 #[derive(Debug, Clone)]
33 /// a Binary String b"abc"
37 /// an integer's bit representation
45 /// an array of constants
47 /// also an array, but with only one constant, repeated N times
48 Repeat(Box<Constant>, u64),
49 /// a tuple of constants
53 impl PartialEq for Constant {
54 fn eq(&self, other: &Self) -> bool {
56 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => ls == rs,
57 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
58 (&Constant::Char(l), &Constant::Char(r)) => l == r,
59 (&Constant::Int(l), &Constant::Int(r)) => l == r,
60 (&Constant::F64(l), &Constant::F64(r)) => {
61 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
62 // `Fw32 == Fw64` so don’t compare them
63 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
64 unsafe { mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r) }
66 (&Constant::F32(l), &Constant::F32(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>(f64::from(l)) == mem::transmute::<f64, u64>(f64::from(r)) }
72 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
73 (&Constant::Vec(ref l), &Constant::Vec(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
74 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
75 _ => false, // TODO: Are there inter-type equalities?
80 impl Hash for Constant {
81 fn hash<H>(&self, state: &mut H)
86 Constant::Str(ref s) => {
89 Constant::Binary(ref b) => {
92 Constant::Char(c) => {
99 unsafe { mem::transmute::<f64, u64>(f64::from(f)) }.hash(state);
101 Constant::F64(f) => {
102 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
104 Constant::Bool(b) => {
107 Constant::Vec(ref v) | Constant::Tuple(ref v) => {
110 Constant::Repeat(ref c, l) => {
119 pub fn partial_cmp(tcx: TyCtxt<'_, '_, '_>, cmp_type: &ty::TyKind<'_>, left: &Self, right: &Self) -> Option<Ordering> {
120 match (left, right) {
121 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => Some(ls.cmp(rs)),
122 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
123 (&Constant::Int(l), &Constant::Int(r)) => {
124 if let ty::Int(int_ty) = *cmp_type {
125 Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
130 (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
131 (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
132 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
133 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l
136 .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
137 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
138 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
139 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
140 match Self::partial_cmp(tcx, cmp_type, lv, rv) {
141 Some(Equal) => Some(ls.cmp(rs)),
145 _ => None, // TODO: Are there any useful inter-type orderings?
150 /// parse a `LitKind` to a `Constant`
151 pub fn lit_to_constant<'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
152 use crate::syntax::ast::*;
155 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
156 LitKind::Byte(b) => Constant::Int(u128::from(b)),
157 LitKind::ByteStr(ref s) => Constant::Binary(Rc::clone(s)),
158 LitKind::Char(c) => Constant::Char(c),
159 LitKind::Int(n, _) => Constant::Int(n),
160 LitKind::Float(ref is, _) |
161 LitKind::FloatUnsuffixed(ref is) => match ty.sty {
162 ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
163 ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
166 LitKind::Bool(b) => Constant::Bool(b),
170 pub fn constant<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<(Constant, bool)> {
171 let mut cx = ConstEvalLateContext {
174 param_env: lcx.param_env,
175 needed_resolution: false,
176 substs: lcx.tcx.intern_substs(&[]),
178 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
181 pub fn constant_simple<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<Constant> {
182 constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
185 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`
186 pub fn constant_context<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>) -> ConstEvalLateContext<'c, 'cc> {
187 ConstEvalLateContext {
190 param_env: lcx.param_env,
191 needed_resolution: false,
192 substs: lcx.tcx.intern_substs(&[]),
196 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
197 tcx: TyCtxt<'a, 'tcx, 'tcx>,
198 tables: &'a ty::TypeckTables<'tcx>,
199 param_env: ty::ParamEnv<'tcx>,
200 needed_resolution: bool,
201 substs: &'tcx Substs<'tcx>,
204 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
205 /// simple constant folding: Insert an expression, get a constant or none.
206 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
208 ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
209 ExprKind::Block(ref block, _) => self.block(block),
210 ExprKind::If(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
211 ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
212 ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
213 ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
214 ExprKind::Repeat(ref value, _) => {
215 let n = match self.tables.expr_ty(e).sty {
216 ty::Array(_, n) => n.assert_usize(self.tcx).expect("array length"),
217 _ => span_bug!(e.span, "typeck error"),
219 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
221 ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
222 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
223 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
226 ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
227 // TODO: add other expressions
232 fn constant_not(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
233 use self::Constant::*;
235 Bool(b) => Some(Bool(!b)),
239 ty::Int(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
240 ty::Uint(ity) => Some(Int(clip(self.tcx, value, ity))),
248 fn constant_negate(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
249 use self::Constant::*;
252 let ity = match ty.sty {
257 let value = sext(self.tcx, value, ity);
258 let value = value.checked_neg()?;
260 Some(Int(unsext(self.tcx, value, ity)))
262 F32(f) => Some(F32(-f)),
263 F64(f) => Some(F64(-f)),
268 /// create `Some(Vec![..])` of all constants, unless there is any
269 /// non-constant part
270 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
272 .map(|elem| self.expr(elem))
273 .collect::<Option<_>>()
276 /// lookup a possibly constant expression from a ExprKind::Path
277 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
278 use crate::rustc::mir::interpret::GlobalId;
280 let def = self.tables.qpath_def(qpath, id);
282 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
283 let substs = self.tables.node_substs(id);
284 let substs = if self.substs.is_empty() {
287 substs.subst(self.tcx, self.substs)
289 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
295 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
296 let ret = miri_to_const(self.tcx, result);
298 self.needed_resolution = true;
307 /// A block can only yield a constant if it only has one constant expression
308 fn block(&mut self, block: &Block) -> Option<Constant> {
309 if block.stmts.is_empty() {
310 block.expr.as_ref().and_then(|b| self.expr(b))
316 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
317 if let Some(Constant::Bool(b)) = self.expr(cond) {
321 otherwise.as_ref().and_then(|expr| self.expr(expr))
328 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
329 let l = self.expr(left)?;
330 let r = self.expr(right);
332 (Constant::Int(l), Some(Constant::Int(r))) => {
333 match self.tables.expr_ty(left).sty {
335 let l = sext(self.tcx, l, ity);
336 let r = sext(self.tcx, r, ity);
337 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
339 BinOpKind::Add => l.checked_add(r).map(zext),
340 BinOpKind::Sub => l.checked_sub(r).map(zext),
341 BinOpKind::Mul => l.checked_mul(r).map(zext),
342 BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
343 BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
344 BinOpKind::Shr => l.checked_shr(r as u128 as u32).map(zext),
345 BinOpKind::Shl => l.checked_shl(r as u128 as u32).map(zext),
346 BinOpKind::BitXor => Some(zext(l ^ r)),
347 BinOpKind::BitOr => Some(zext(l | r)),
348 BinOpKind::BitAnd => Some(zext(l & r)),
349 BinOpKind::Eq => Some(Constant::Bool(l == r)),
350 BinOpKind::Ne => Some(Constant::Bool(l != r)),
351 BinOpKind::Lt => Some(Constant::Bool(l < r)),
352 BinOpKind::Le => Some(Constant::Bool(l <= r)),
353 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
354 BinOpKind::Gt => Some(Constant::Bool(l > r)),
360 BinOpKind::Add => l.checked_add(r).map(Constant::Int),
361 BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
362 BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
363 BinOpKind::Div => l.checked_div(r).map(Constant::Int),
364 BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
365 BinOpKind::Shr => l.checked_shr(r as u32).map(Constant::Int),
366 BinOpKind::Shl => l.checked_shl(r as u32).map(Constant::Int),
367 BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
368 BinOpKind::BitOr => Some(Constant::Int(l | r)),
369 BinOpKind::BitAnd => Some(Constant::Int(l & r)),
370 BinOpKind::Eq => Some(Constant::Bool(l == r)),
371 BinOpKind::Ne => Some(Constant::Bool(l != r)),
372 BinOpKind::Lt => Some(Constant::Bool(l < r)),
373 BinOpKind::Le => Some(Constant::Bool(l <= r)),
374 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
375 BinOpKind::Gt => Some(Constant::Bool(l > r)),
382 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
383 BinOpKind::Add => Some(Constant::F32(l + r)),
384 BinOpKind::Sub => Some(Constant::F32(l - r)),
385 BinOpKind::Mul => Some(Constant::F32(l * r)),
386 BinOpKind::Div => Some(Constant::F32(l / r)),
387 BinOpKind::Rem => Some(Constant::F32(l % r)),
388 BinOpKind::Eq => Some(Constant::Bool(l == r)),
389 BinOpKind::Ne => Some(Constant::Bool(l != r)),
390 BinOpKind::Lt => Some(Constant::Bool(l < r)),
391 BinOpKind::Le => Some(Constant::Bool(l <= r)),
392 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
393 BinOpKind::Gt => Some(Constant::Bool(l > r)),
396 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
397 BinOpKind::Add => Some(Constant::F64(l + r)),
398 BinOpKind::Sub => Some(Constant::F64(l - r)),
399 BinOpKind::Mul => Some(Constant::F64(l * r)),
400 BinOpKind::Div => Some(Constant::F64(l / r)),
401 BinOpKind::Rem => Some(Constant::F64(l % r)),
402 BinOpKind::Eq => Some(Constant::Bool(l == r)),
403 BinOpKind::Ne => Some(Constant::Bool(l != r)),
404 BinOpKind::Lt => Some(Constant::Bool(l < r)),
405 BinOpKind::Le => Some(Constant::Bool(l <= r)),
406 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
407 BinOpKind::Gt => Some(Constant::Bool(l > r)),
410 (l, r) => match (op.node, l, r) {
411 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
412 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
413 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => Some(r),
414 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
415 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
416 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
423 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
424 use crate::rustc::mir::interpret::{Scalar, ConstValue};
426 ConstValue::Scalar(Scalar::Bits{ bits: b, ..}) => match result.ty.sty {
427 ty::Bool => Some(Constant::Bool(b == 1)),
428 ty::Uint(_) | ty::Int(_) => Some(Constant::Int(b)),
429 ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(b as u32))),
430 ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(b as u64))),
431 // FIXME: implement other conversion
434 ConstValue::ScalarPair(Scalar::Ptr(ptr),
435 Scalar::Bits { bits: n, .. }) => match result.ty.sty {
436 ty::Ref(_, tam, _) => match tam.sty {
441 .unwrap_memory(ptr.alloc_id);
442 let offset = ptr.offset.bytes() as usize;
444 String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned()).ok().map(Constant::Str)
450 // FIXME: implement other conversions