1 #![allow(clippy::float_cmp)]
3 use crate::utils::{clip, get_def_path, sext, unsext};
4 use if_chain::if_chain;
5 use rustc::hir::def::Def;
7 use rustc::lint::LateContext;
8 use rustc::ty::subst::{Subst, SubstsRef};
9 use rustc::ty::{self, Instance, Ty, TyCtxt};
10 use rustc::{bug, span_bug};
11 use rustc_data_structures::sync::Lrc;
12 use std::cmp::Ordering::{self, Equal};
13 use std::cmp::PartialOrd;
14 use std::convert::TryFrom;
15 use std::convert::TryInto;
16 use std::hash::{Hash, Hasher};
17 use syntax::ast::{FloatTy, LitKind};
19 use syntax_pos::symbol::{LocalInternedString, Symbol};
21 /// A `LitKind`-like enum to fold constant `Expr`s into.
22 #[derive(Debug, Clone)]
24 /// A `String` (e.g., "abc").
26 /// A binary string (e.g., `b"abc"`).
28 /// A single `char` (e.g., `'a'`).
30 /// An integer's bit representation.
36 /// `true` or `false`.
38 /// An array of constants.
40 /// Also an array, but with only one constant, repeated N times.
41 Repeat(Box<Constant>, u64),
42 /// A tuple of constants.
46 /// A literal with syntax error.
50 impl PartialEq for Constant {
51 fn eq(&self, other: &Self) -> bool {
53 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => ls == rs,
54 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
55 (&Constant::Char(l), &Constant::Char(r)) => l == r,
56 (&Constant::Int(l), &Constant::Int(r)) => l == r,
57 (&Constant::F64(l), &Constant::F64(r)) => {
58 // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have
59 // `Fw32 == Fw64`, so don’t compare them.
60 // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs.
61 l.to_bits() == r.to_bits()
63 (&Constant::F32(l), &Constant::F32(r)) => {
64 // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have
65 // `Fw32 == Fw64`, so don’t compare them.
66 // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs.
67 f64::from(l).to_bits() == f64::from(r).to_bits()
69 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
70 (&Constant::Vec(ref l), &Constant::Vec(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => {
73 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
74 // 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 f64::from(f).to_bits().hash(state);
101 Constant::F64(f) => {
102 f.to_bits().hash(state);
104 Constant::Bool(b) => {
107 Constant::Vec(ref v) | Constant::Tuple(ref v) => {
110 Constant::Repeat(ref c, l) => {
114 Constant::RawPtr(u) => {
117 Constant::Err(ref s) => {
125 pub fn partial_cmp(tcx: TyCtxt<'_, '_, '_>, cmp_type: Ty<'_>, left: &Self, right: &Self) -> Option<Ordering> {
126 match (left, right) {
127 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => Some(ls.cmp(rs)),
128 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
129 (&Constant::Int(l), &Constant::Int(r)) => {
130 if let ty::Int(int_ty) = cmp_type.sty {
131 Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
136 (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
137 (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
138 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
139 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l
142 .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
143 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
144 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
145 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
146 match Self::partial_cmp(tcx, cmp_type, lv, rv) {
147 Some(Equal) => Some(ls.cmp(rs)),
151 // TODO: are there any useful inter-type orderings?
157 /// Parses 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(Lrc::clone(s)),
165 LitKind::Char(c) => Constant::Char(c),
166 LitKind::Int(n, _) => Constant::Int(n),
167 LitKind::Float(ref is, _) | LitKind::FloatUnsuffixed(ref is) => match ty.sty {
168 ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
169 ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
172 LitKind::Bool(b) => Constant::Bool(b),
173 LitKind::Err(s) => Constant::Err(s),
177 pub fn constant<'c, 'cc>(
178 lcx: &LateContext<'c, 'cc>,
179 tables: &'c ty::TypeckTables<'cc>,
181 ) -> Option<(Constant, bool)> {
182 let mut cx = ConstEvalLateContext {
185 param_env: lcx.param_env,
186 needed_resolution: false,
187 substs: lcx.tcx.intern_substs(&[]),
189 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
192 pub fn constant_simple<'c, 'cc>(
193 lcx: &LateContext<'c, 'cc>,
194 tables: &'c ty::TypeckTables<'cc>,
196 ) -> Option<Constant> {
197 constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
200 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`.
201 pub fn constant_context<'c, 'cc>(
202 lcx: &LateContext<'c, 'cc>,
203 tables: &'c ty::TypeckTables<'cc>,
204 ) -> ConstEvalLateContext<'c, 'cc> {
205 ConstEvalLateContext {
208 param_env: lcx.param_env,
209 needed_resolution: false,
210 substs: lcx.tcx.intern_substs(&[]),
214 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
215 tcx: TyCtxt<'a, 'tcx, 'tcx>,
216 tables: &'a ty::TypeckTables<'tcx>,
217 param_env: ty::ParamEnv<'tcx>,
218 needed_resolution: bool,
219 substs: SubstsRef<'tcx>,
222 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
223 /// Simple constant folding: Insert an expression, get a constant or none.
224 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
226 ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
227 ExprKind::Block(ref block, _) => self.block(block),
228 ExprKind::If(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
229 ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
230 ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
231 ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
232 ExprKind::Repeat(ref value, _) => {
233 let n = match self.tables.expr_ty(e).sty {
234 ty::Array(_, n) => n.assert_usize(self.tcx).expect("array length"),
235 _ => span_bug!(e.span, "typeck error"),
237 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
239 ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
240 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
241 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
244 ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
245 ExprKind::Call(ref callee, ref args) => {
246 // We only handle a few const functions for now.
249 if let ExprKind::Path(qpath) = &callee.node;
250 let def = self.tables.qpath_def(qpath, callee.hir_id);
251 if let Some(def_id) = def.opt_def_id();
252 let def_path = get_def_path(self.tcx, def_id)
254 .map(LocalInternedString::get)
255 .collect::<Vec<_>>();
256 if let &["core", "num", impl_ty, "max_value"] = &def_path[..];
258 let value = match impl_ty {
259 "<impl i8>" => i8::max_value() as u128,
260 "<impl i16>" => i16::max_value() as u128,
261 "<impl i32>" => i32::max_value() as u128,
262 "<impl i64>" => i64::max_value() as u128,
263 "<impl i128>" => i128::max_value() as u128,
266 Some(Constant::Int(value))
273 // TODO: add other expressions.
278 #[allow(clippy::cast_possible_wrap)]
279 fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
280 use self::Constant::*;
282 Bool(b) => Some(Bool(!b)),
286 ty::Int(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
287 ty::Uint(ity) => Some(Int(clip(self.tcx, value, ity))),
295 fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
296 use self::Constant::*;
299 let ity = match ty.sty {
304 let value = sext(self.tcx, value, ity);
305 let value = value.checked_neg()?;
307 Some(Int(unsext(self.tcx, value, ity)))
309 F32(f) => Some(F32(-f)),
310 F64(f) => Some(F64(-f)),
315 /// Create `Some(Vec![..])` of all constants, unless there is any
316 /// non-constant part.
317 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
318 vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
321 /// Lookup a possibly constant expression from a ExprKind::Path.
322 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
323 use rustc::mir::interpret::GlobalId;
325 let def = self.tables.qpath_def(qpath, id);
327 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
328 let substs = self.tables.node_substs(id);
329 let substs = if self.substs.is_empty() {
332 substs.subst(self.tcx, self.substs)
334 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
340 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
341 let ret = miri_to_const(self.tcx, &result);
343 self.needed_resolution = true;
347 // FIXME: cover all useable cases.
352 /// A block can only yield a constant if it only has one constant expression.
353 fn block(&mut self, block: &Block) -> Option<Constant> {
354 if block.stmts.is_empty() {
355 block.expr.as_ref().and_then(|b| self.expr(b))
361 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
362 if let Some(Constant::Bool(b)) = self.expr(cond) {
366 otherwise.as_ref().and_then(|expr| self.expr(expr))
373 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
374 let l = self.expr(left)?;
375 let r = self.expr(right);
377 (Constant::Int(l), Some(Constant::Int(r))) => match self.tables.expr_ty(left).sty {
379 let l = sext(self.tcx, l, ity);
380 let r = sext(self.tcx, r, ity);
381 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
383 BinOpKind::Add => l.checked_add(r).map(zext),
384 BinOpKind::Sub => l.checked_sub(r).map(zext),
385 BinOpKind::Mul => l.checked_mul(r).map(zext),
386 BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
387 BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
388 BinOpKind::Shr => l.checked_shr(r.try_into().expect("invalid shift")).map(zext),
389 BinOpKind::Shl => l.checked_shl(r.try_into().expect("invalid shift")).map(zext),
390 BinOpKind::BitXor => Some(zext(l ^ r)),
391 BinOpKind::BitOr => Some(zext(l | r)),
392 BinOpKind::BitAnd => Some(zext(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)),
402 ty::Uint(_) => match op.node {
403 BinOpKind::Add => l.checked_add(r).map(Constant::Int),
404 BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
405 BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
406 BinOpKind::Div => l.checked_div(r).map(Constant::Int),
407 BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
408 BinOpKind::Shr => l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int),
409 BinOpKind::Shl => l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int),
410 BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
411 BinOpKind::BitOr => Some(Constant::Int(l | r)),
412 BinOpKind::BitAnd => Some(Constant::Int(l & r)),
413 BinOpKind::Eq => Some(Constant::Bool(l == r)),
414 BinOpKind::Ne => Some(Constant::Bool(l != r)),
415 BinOpKind::Lt => Some(Constant::Bool(l < r)),
416 BinOpKind::Le => Some(Constant::Bool(l <= r)),
417 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
418 BinOpKind::Gt => Some(Constant::Bool(l > r)),
423 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
424 BinOpKind::Add => Some(Constant::F32(l + r)),
425 BinOpKind::Sub => Some(Constant::F32(l - r)),
426 BinOpKind::Mul => Some(Constant::F32(l * r)),
427 BinOpKind::Div => Some(Constant::F32(l / r)),
428 BinOpKind::Rem => Some(Constant::F32(l % r)),
429 BinOpKind::Eq => Some(Constant::Bool(l == r)),
430 BinOpKind::Ne => Some(Constant::Bool(l != r)),
431 BinOpKind::Lt => Some(Constant::Bool(l < r)),
432 BinOpKind::Le => Some(Constant::Bool(l <= r)),
433 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
434 BinOpKind::Gt => Some(Constant::Bool(l > r)),
437 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
438 BinOpKind::Add => Some(Constant::F64(l + r)),
439 BinOpKind::Sub => Some(Constant::F64(l - r)),
440 BinOpKind::Mul => Some(Constant::F64(l * r)),
441 BinOpKind::Div => Some(Constant::F64(l / r)),
442 BinOpKind::Rem => Some(Constant::F64(l % r)),
443 BinOpKind::Eq => Some(Constant::Bool(l == r)),
444 BinOpKind::Ne => Some(Constant::Bool(l != r)),
445 BinOpKind::Lt => Some(Constant::Bool(l < r)),
446 BinOpKind::Le => Some(Constant::Bool(l <= r)),
447 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
448 BinOpKind::Gt => Some(Constant::Bool(l > r)),
451 (l, r) => match (op.node, l, r) {
452 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
453 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
454 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
457 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
458 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
459 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
466 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
467 use rustc::mir::interpret::{ConstValue, Scalar};
469 ConstValue::Scalar(Scalar::Bits { bits: b, .. }) => match result.ty.sty {
470 ty::Bool => Some(Constant::Bool(b == 1)),
471 ty::Uint(_) | ty::Int(_) => Some(Constant::Int(b)),
472 ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(
473 b.try_into().expect("invalid f32 bit representation"),
475 ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(
476 b.try_into().expect("invalid f64 bit representation"),
478 ty::RawPtr(type_and_mut) => {
479 if let ty::Uint(_) = type_and_mut.ty.sty {
480 return Some(Constant::RawPtr(b));
484 // FIXME: implement other conversions.
487 ConstValue::Slice(Scalar::Ptr(ptr), n) => match result.ty.sty {
488 ty::Ref(_, tam, _) => match tam.sty {
490 let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
491 let offset = ptr.offset.bytes().try_into().expect("too-large pointer offset");
492 let n = usize::try_from(n).unwrap();
493 String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned())
501 // FIXME: implement other conversions.