1 #![allow(clippy::float_cmp)]
3 use crate::utils::{clip, sext, unsext};
4 use rustc::hir::def::Def;
6 use rustc::lint::LateContext;
7 use rustc::ty::subst::{Subst, Substs};
8 use rustc::ty::{self, Instance, Ty, TyCtxt};
9 use rustc::{bug, span_bug};
10 use rustc_data_structures::sync::Lrc;
11 use std::cmp::Ordering::{self, Equal};
12 use std::cmp::PartialOrd;
13 use std::convert::TryInto;
14 use std::hash::{Hash, Hasher};
15 use syntax::ast::{FloatTy, LitKind};
17 use syntax_pos::symbol::Symbol;
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
42 /// a literal with syntax error
46 impl PartialEq for Constant {
47 fn eq(&self, other: &Self) -> bool {
49 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => ls == rs,
50 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
51 (&Constant::Char(l), &Constant::Char(r)) => l == r,
52 (&Constant::Int(l), &Constant::Int(r)) => l == r,
53 (&Constant::F64(l), &Constant::F64(r)) => {
54 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
55 // `Fw32 == Fw64` so don’t compare them
56 // to_bits is required to catch non-matching 0.0, -0.0, and NaNs
57 l.to_bits() == r.to_bits()
59 (&Constant::F32(l), &Constant::F32(r)) => {
60 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
61 // `Fw32 == Fw64` so don’t compare them
62 // to_bits is required to catch non-matching 0.0, -0.0, and NaNs
63 f64::from(l).to_bits() == f64::from(r).to_bits()
65 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
66 (&Constant::Vec(ref l), &Constant::Vec(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => {
69 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
70 _ => false, // TODO: Are there inter-type equalities?
75 impl Hash for Constant {
76 fn hash<H>(&self, state: &mut H)
81 Constant::Str(ref s) => {
84 Constant::Binary(ref b) => {
87 Constant::Char(c) => {
94 f64::from(f).to_bits().hash(state);
97 f.to_bits().hash(state);
99 Constant::Bool(b) => {
102 Constant::Vec(ref v) | Constant::Tuple(ref v) => {
105 Constant::Repeat(ref c, l) => {
109 Constant::Err(ref s) => {
117 pub fn partial_cmp(tcx: TyCtxt<'_, '_, '_>, cmp_type: ty::Ty<'_>, left: &Self, right: &Self) -> Option<Ordering> {
118 match (left, right) {
119 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => Some(ls.cmp(rs)),
120 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
121 (&Constant::Int(l), &Constant::Int(r)) => {
122 if let ty::Int(int_ty) = cmp_type.sty {
123 Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
128 (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
129 (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
130 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
131 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l
134 .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
135 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
136 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
137 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
138 match Self::partial_cmp(tcx, cmp_type, lv, rv) {
139 Some(Equal) => Some(ls.cmp(rs)),
143 _ => None, // TODO: Are there any useful inter-type orderings?
148 /// parse a `LitKind` to a `Constant`
149 pub fn lit_to_constant<'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
153 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
154 LitKind::Byte(b) => Constant::Int(u128::from(b)),
155 LitKind::ByteStr(ref s) => Constant::Binary(Lrc::clone(s)),
156 LitKind::Char(c) => Constant::Char(c),
157 LitKind::Int(n, _) => Constant::Int(n),
158 LitKind::Float(ref is, _) | LitKind::FloatUnsuffixed(ref is) => match ty.sty {
159 ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
160 ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
163 LitKind::Bool(b) => Constant::Bool(b),
164 LitKind::Err(s) => Constant::Err(s),
168 pub fn constant<'c, 'cc>(
169 lcx: &LateContext<'c, 'cc>,
170 tables: &'c ty::TypeckTables<'cc>,
172 ) -> Option<(Constant, bool)> {
173 let mut cx = ConstEvalLateContext {
176 param_env: lcx.param_env,
177 needed_resolution: false,
178 substs: lcx.tcx.intern_substs(&[]),
180 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
183 pub fn constant_simple<'c, 'cc>(
184 lcx: &LateContext<'c, 'cc>,
185 tables: &'c ty::TypeckTables<'cc>,
187 ) -> 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>(
193 lcx: &LateContext<'c, 'cc>,
194 tables: &'c ty::TypeckTables<'cc>,
195 ) -> ConstEvalLateContext<'c, 'cc> {
196 ConstEvalLateContext {
199 param_env: lcx.param_env,
200 needed_resolution: false,
201 substs: lcx.tcx.intern_substs(&[]),
205 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
206 tcx: TyCtxt<'a, 'tcx, 'tcx>,
207 tables: &'a ty::TypeckTables<'tcx>,
208 param_env: ty::ParamEnv<'tcx>,
209 needed_resolution: bool,
210 substs: &'tcx Substs<'tcx>,
213 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
214 /// simple constant folding: Insert an expression, get a constant or none.
215 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
217 ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
218 ExprKind::Block(ref block, _) => self.block(block),
219 ExprKind::If(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
220 ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
221 ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
222 ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
223 ExprKind::Repeat(ref value, _) => {
224 let n = match self.tables.expr_ty(e).sty {
225 ty::Array(_, n) => n.assert_usize(self.tcx).expect("array length"),
226 _ => span_bug!(e.span, "typeck error"),
228 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
230 ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
231 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
232 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
235 ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
236 // TODO: add other expressions
241 #[allow(clippy::cast_possible_wrap)]
242 fn constant_not(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
243 use self::Constant::*;
245 Bool(b) => Some(Bool(!b)),
249 ty::Int(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
250 ty::Uint(ity) => Some(Int(clip(self.tcx, value, ity))),
258 fn constant_negate(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
259 use self::Constant::*;
262 let ity = match ty.sty {
267 let value = sext(self.tcx, value, ity);
268 let value = value.checked_neg()?;
270 Some(Int(unsext(self.tcx, value, ity)))
272 F32(f) => Some(F32(-f)),
273 F64(f) => Some(F64(-f)),
278 /// create `Some(Vec![..])` of all constants, unless there is any
279 /// non-constant part
280 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
281 vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
284 /// lookup a possibly constant expression from a ExprKind::Path
285 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
286 use rustc::mir::interpret::GlobalId;
288 let def = self.tables.qpath_def(qpath, id);
290 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
291 let substs = self.tables.node_substs(id);
292 let substs = if self.substs.is_empty() {
295 substs.subst(self.tcx, self.substs)
297 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
303 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
304 let ret = miri_to_const(self.tcx, &result);
306 self.needed_resolution = true;
315 /// A block can only yield a constant if it only has one constant expression
316 fn block(&mut self, block: &Block) -> Option<Constant> {
317 if block.stmts.is_empty() {
318 block.expr.as_ref().and_then(|b| self.expr(b))
324 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
325 if let Some(Constant::Bool(b)) = self.expr(cond) {
329 otherwise.as_ref().and_then(|expr| self.expr(expr))
336 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
337 let l = self.expr(left)?;
338 let r = self.expr(right);
340 (Constant::Int(l), Some(Constant::Int(r))) => match self.tables.expr_ty(left).sty {
342 let l = sext(self.tcx, l, ity);
343 let r = sext(self.tcx, r, ity);
344 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
346 BinOpKind::Add => l.checked_add(r).map(zext),
347 BinOpKind::Sub => l.checked_sub(r).map(zext),
348 BinOpKind::Mul => l.checked_mul(r).map(zext),
349 BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
350 BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
351 BinOpKind::Shr => l.checked_shr(r.try_into().expect("invalid shift")).map(zext),
352 BinOpKind::Shl => l.checked_shl(r.try_into().expect("invalid shift")).map(zext),
353 BinOpKind::BitXor => Some(zext(l ^ r)),
354 BinOpKind::BitOr => Some(zext(l | r)),
355 BinOpKind::BitAnd => Some(zext(l & r)),
356 BinOpKind::Eq => Some(Constant::Bool(l == r)),
357 BinOpKind::Ne => Some(Constant::Bool(l != r)),
358 BinOpKind::Lt => Some(Constant::Bool(l < r)),
359 BinOpKind::Le => Some(Constant::Bool(l <= r)),
360 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
361 BinOpKind::Gt => Some(Constant::Bool(l > r)),
365 ty::Uint(_) => match op.node {
366 BinOpKind::Add => l.checked_add(r).map(Constant::Int),
367 BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
368 BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
369 BinOpKind::Div => l.checked_div(r).map(Constant::Int),
370 BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
371 BinOpKind::Shr => l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int),
372 BinOpKind::Shl => l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int),
373 BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
374 BinOpKind::BitOr => Some(Constant::Int(l | r)),
375 BinOpKind::BitAnd => Some(Constant::Int(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)),
386 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
387 BinOpKind::Add => Some(Constant::F32(l + r)),
388 BinOpKind::Sub => Some(Constant::F32(l - r)),
389 BinOpKind::Mul => Some(Constant::F32(l * r)),
390 BinOpKind::Div => Some(Constant::F32(l / r)),
391 BinOpKind::Rem => Some(Constant::F32(l % r)),
392 BinOpKind::Eq => Some(Constant::Bool(l == r)),
393 BinOpKind::Ne => Some(Constant::Bool(l != r)),
394 BinOpKind::Lt => Some(Constant::Bool(l < r)),
395 BinOpKind::Le => Some(Constant::Bool(l <= r)),
396 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
397 BinOpKind::Gt => Some(Constant::Bool(l > r)),
400 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
401 BinOpKind::Add => Some(Constant::F64(l + r)),
402 BinOpKind::Sub => Some(Constant::F64(l - r)),
403 BinOpKind::Mul => Some(Constant::F64(l * r)),
404 BinOpKind::Div => Some(Constant::F64(l / r)),
405 BinOpKind::Rem => Some(Constant::F64(l % r)),
406 BinOpKind::Eq => Some(Constant::Bool(l == r)),
407 BinOpKind::Ne => Some(Constant::Bool(l != r)),
408 BinOpKind::Lt => Some(Constant::Bool(l < r)),
409 BinOpKind::Le => Some(Constant::Bool(l <= r)),
410 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
411 BinOpKind::Gt => Some(Constant::Bool(l > r)),
414 (l, r) => match (op.node, l, r) {
415 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
416 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
417 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
420 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
421 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
422 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
429 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
430 use rustc::mir::interpret::{ConstValue, Scalar};
432 ConstValue::Scalar(Scalar::Bits { bits: b, .. }) => match result.ty.sty {
433 ty::Bool => Some(Constant::Bool(b == 1)),
434 ty::Uint(_) | ty::Int(_) => Some(Constant::Int(b)),
435 ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(
436 b.try_into().expect("invalid f32 bit representation"),
438 ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(
439 b.try_into().expect("invalid f64 bit representation"),
441 // FIXME: implement other conversion
444 ConstValue::ScalarPair(Scalar::Ptr(ptr), Scalar::Bits { bits: n, .. }) => match result.ty.sty {
445 ty::Ref(_, tam, _) => match tam.sty {
447 let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
448 let offset = ptr.offset.bytes().try_into().expect("too-large pointer offset");
450 String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned())
458 // FIXME: implement other conversions