1 #![allow(clippy::float_cmp)]
3 use crate::utils::{clip, higher, sext, unsext};
4 use if_chain::if_chain;
5 use rustc::hir::def::{DefKind, Res};
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::TryInto;
15 use std::hash::{Hash, Hasher};
16 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)]
22 /// A `String` (e.g., "abc").
24 /// A binary string (e.g., `b"abc"`).
26 /// A single `char` (e.g., `'a'`).
28 /// An integer's bit representation.
34 /// `true` or `false`.
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 /// A literal with syntax error.
48 impl PartialEq for Constant {
49 fn eq(&self, other: &Self) -> bool {
51 (&Self::Str(ref ls), &Self::Str(ref rs)) => ls == rs,
52 (&Self::Binary(ref l), &Self::Binary(ref r)) => l == r,
53 (&Self::Char(l), &Self::Char(r)) => l == r,
54 (&Self::Int(l), &Self::Int(r)) => l == r,
55 (&Self::F64(l), &Self::F64(r)) => {
56 // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have
57 // `Fw32 == Fw64`, so don’t compare them.
58 // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs.
59 l.to_bits() == r.to_bits()
61 (&Self::F32(l), &Self::F32(r)) => {
62 // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have
63 // `Fw32 == Fw64`, so don’t compare them.
64 // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs.
65 f64::from(l).to_bits() == f64::from(r).to_bits()
67 (&Self::Bool(l), &Self::Bool(r)) => l == r,
68 (&Self::Vec(ref l), &Self::Vec(ref r)) | (&Self::Tuple(ref l), &Self::Tuple(ref r)) => l == r,
69 (&Self::Repeat(ref lv, ref ls), &Self::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
70 // TODO: are there inter-type equalities?
76 impl Hash for Constant {
77 fn hash<H>(&self, state: &mut H)
81 std::mem::discriminant(self).hash(state);
86 Self::Binary(ref b) => {
96 f64::from(f).to_bits().hash(state);
99 f.to_bits().hash(state);
104 Self::Vec(ref v) | Self::Tuple(ref v) => {
107 Self::Repeat(ref c, l) => {
114 Self::Err(ref s) => {
122 pub fn partial_cmp(tcx: TyCtxt<'_>, cmp_type: Ty<'_>, left: &Self, right: &Self) -> Option<Ordering> {
123 match (left, right) {
124 (&Self::Str(ref ls), &Self::Str(ref rs)) => Some(ls.cmp(rs)),
125 (&Self::Char(ref l), &Self::Char(ref r)) => Some(l.cmp(r)),
126 (&Self::Int(l), &Self::Int(r)) => {
127 if let ty::Int(int_ty) = cmp_type.kind {
128 Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
133 (&Self::F64(l), &Self::F64(r)) => l.partial_cmp(&r),
134 (&Self::F32(l), &Self::F32(r)) => l.partial_cmp(&r),
135 (&Self::Bool(ref l), &Self::Bool(ref r)) => Some(l.cmp(r)),
136 (&Self::Tuple(ref l), &Self::Tuple(ref r)) | (&Self::Vec(ref l), &Self::Vec(ref r)) => l
139 .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
140 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
141 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
142 (&Self::Repeat(ref lv, ref ls), &Self::Repeat(ref rv, ref rs)) => {
143 match Self::partial_cmp(tcx, cmp_type, lv, rv) {
144 Some(Equal) => Some(ls.cmp(rs)),
148 // TODO: are there any useful inter-type orderings?
154 /// Parses a `LitKind` to a `Constant`.
155 pub fn lit_to_constant(lit: &LitKind, ty: Option<Ty<'_>>) -> Constant {
159 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
160 LitKind::Byte(b) => Constant::Int(u128::from(b)),
161 LitKind::ByteStr(ref s) => Constant::Binary(Lrc::clone(s)),
162 LitKind::Char(c) => Constant::Char(c),
163 LitKind::Int(n, _) => Constant::Int(n),
164 LitKind::Float(ref is, FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
165 LitKind::Float(ref is, FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
166 LitKind::FloatUnsuffixed(ref is) => match ty.expect("type of float is known").kind {
167 ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
168 ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
171 LitKind::Bool(b) => Constant::Bool(b),
172 LitKind::Err(s) => Constant::Err(s),
176 pub fn constant<'c, 'cc>(
177 lcx: &LateContext<'c, 'cc>,
178 tables: &'c ty::TypeckTables<'cc>,
180 ) -> Option<(Constant, bool)> {
181 let mut cx = ConstEvalLateContext {
184 param_env: lcx.param_env,
185 needed_resolution: false,
186 substs: lcx.tcx.intern_substs(&[]),
188 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
191 pub fn constant_simple<'c, 'cc>(
192 lcx: &LateContext<'c, 'cc>,
193 tables: &'c ty::TypeckTables<'cc>,
195 ) -> Option<Constant> {
196 constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
199 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`.
200 pub fn constant_context<'c, 'cc>(
201 lcx: &'c LateContext<'c, 'cc>,
202 tables: &'c ty::TypeckTables<'cc>,
203 ) -> ConstEvalLateContext<'c, 'cc> {
204 ConstEvalLateContext {
207 param_env: lcx.param_env,
208 needed_resolution: false,
209 substs: lcx.tcx.intern_substs(&[]),
213 pub struct ConstEvalLateContext<'a, 'tcx> {
214 lcx: &'a LateContext<'a, 'tcx>,
215 tables: &'a ty::TypeckTables<'tcx>,
216 param_env: ty::ParamEnv<'tcx>,
217 needed_resolution: bool,
218 substs: SubstsRef<'tcx>,
221 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
222 /// Simple constant folding: Insert an expression, get a constant or none.
223 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
224 if let Some((ref cond, ref then, otherwise)) = higher::if_block(&e) {
225 return self.ifthenelse(cond, then, otherwise);
228 ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
229 ExprKind::Block(ref block, _) => self.block(block),
230 ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty_opt(e))),
231 ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
232 ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
233 ExprKind::Repeat(ref value, _) => {
234 let n = match self.tables.expr_ty(e).kind {
235 ty::Array(_, n) => n.eval_usize(self.lcx.tcx, self.lcx.param_env),
236 _ => span_bug!(e.span, "typeck error"),
238 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
240 ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
241 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
242 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
245 ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
246 ExprKind::Call(ref callee, ref args) => {
247 // We only handle a few const functions for now.
250 if let ExprKind::Path(qpath) = &callee.kind;
251 let res = self.tables.qpath_res(qpath, callee.hir_id);
252 if let Some(def_id) = res.opt_def_id();
253 let get_def_path = self.lcx.get_def_path(def_id, );
254 let def_path = get_def_path
258 .collect::<Vec<_>>();
259 if def_path[0] == "core";
260 if def_path[1] == "num";
261 if def_path[3] == "max_value";
262 if def_path.len() == 4;
264 let value = match &*def_path[2] {
265 "<impl i8>" => i8::max_value() as u128,
266 "<impl i16>" => i16::max_value() as u128,
267 "<impl i32>" => i32::max_value() as u128,
268 "<impl i64>" => i64::max_value() as u128,
269 "<impl i128>" => i128::max_value() as u128,
272 Some(Constant::Int(value))
279 // TODO: add other expressions.
284 #[allow(clippy::cast_possible_wrap)]
285 fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
286 use self::Constant::*;
288 Bool(b) => Some(Bool(!b)),
292 ty::Int(ity) => Some(Int(unsext(self.lcx.tcx, value as i128, ity))),
293 ty::Uint(ity) => Some(Int(clip(self.lcx.tcx, value, ity))),
301 fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
302 use self::Constant::*;
305 let ity = match ty.kind {
310 let value = sext(self.lcx.tcx, value, ity);
311 let value = value.checked_neg()?;
313 Some(Int(unsext(self.lcx.tcx, value, ity)))
315 F32(f) => Some(F32(-f)),
316 F64(f) => Some(F64(-f)),
321 /// Create `Some(Vec![..])` of all constants, unless there is any
322 /// non-constant part.
323 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
324 vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
327 /// Lookup a possibly constant expression from a ExprKind::Path.
328 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
329 use rustc::mir::interpret::GlobalId;
331 let res = self.tables.qpath_res(qpath, id);
333 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
334 let substs = self.tables.node_substs(id);
335 let substs = if self.substs.is_empty() {
338 substs.subst(self.lcx.tcx, self.substs)
340 let instance = Instance::resolve(self.lcx.tcx, self.param_env, def_id, substs)?;
346 let result = self.lcx.tcx.const_eval(self.param_env.and(gid)).ok()?;
347 let result = miri_to_const(&result);
348 if result.is_some() {
349 self.needed_resolution = true;
353 // FIXME: cover all usable cases.
358 /// A block can only yield a constant if it only has one constant expression.
359 fn block(&mut self, block: &Block) -> Option<Constant> {
360 if block.stmts.is_empty() {
361 block.expr.as_ref().and_then(|b| self.expr(b))
367 fn ifthenelse(&mut self, cond: &Expr, then: &Expr, otherwise: Option<&Expr>) -> Option<Constant> {
368 if let Some(Constant::Bool(b)) = self.expr(cond) {
372 otherwise.as_ref().and_then(|expr| self.expr(expr))
379 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
380 let l = self.expr(left)?;
381 let r = self.expr(right);
383 (Constant::Int(l), Some(Constant::Int(r))) => match self.tables.expr_ty(left).kind {
385 let l = sext(self.lcx.tcx, l, ity);
386 let r = sext(self.lcx.tcx, r, ity);
387 let zext = |n: i128| Constant::Int(unsext(self.lcx.tcx, n, ity));
389 BinOpKind::Add => l.checked_add(r).map(zext),
390 BinOpKind::Sub => l.checked_sub(r).map(zext),
391 BinOpKind::Mul => l.checked_mul(r).map(zext),
392 BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
393 BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
394 BinOpKind::Shr => l.checked_shr(r.try_into().expect("invalid shift")).map(zext),
395 BinOpKind::Shl => l.checked_shl(r.try_into().expect("invalid shift")).map(zext),
396 BinOpKind::BitXor => Some(zext(l ^ r)),
397 BinOpKind::BitOr => Some(zext(l | r)),
398 BinOpKind::BitAnd => Some(zext(l & r)),
399 BinOpKind::Eq => Some(Constant::Bool(l == r)),
400 BinOpKind::Ne => Some(Constant::Bool(l != r)),
401 BinOpKind::Lt => Some(Constant::Bool(l < r)),
402 BinOpKind::Le => Some(Constant::Bool(l <= r)),
403 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
404 BinOpKind::Gt => Some(Constant::Bool(l > r)),
408 ty::Uint(_) => match op.node {
409 BinOpKind::Add => l.checked_add(r).map(Constant::Int),
410 BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
411 BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
412 BinOpKind::Div => l.checked_div(r).map(Constant::Int),
413 BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
414 BinOpKind::Shr => l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int),
415 BinOpKind::Shl => l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int),
416 BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
417 BinOpKind::BitOr => Some(Constant::Int(l | r)),
418 BinOpKind::BitAnd => Some(Constant::Int(l & r)),
419 BinOpKind::Eq => Some(Constant::Bool(l == r)),
420 BinOpKind::Ne => Some(Constant::Bool(l != r)),
421 BinOpKind::Lt => Some(Constant::Bool(l < r)),
422 BinOpKind::Le => Some(Constant::Bool(l <= r)),
423 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
424 BinOpKind::Gt => Some(Constant::Bool(l > r)),
429 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
430 BinOpKind::Add => Some(Constant::F32(l + r)),
431 BinOpKind::Sub => Some(Constant::F32(l - r)),
432 BinOpKind::Mul => Some(Constant::F32(l * r)),
433 BinOpKind::Div => Some(Constant::F32(l / r)),
434 BinOpKind::Rem => Some(Constant::F32(l % r)),
435 BinOpKind::Eq => Some(Constant::Bool(l == r)),
436 BinOpKind::Ne => Some(Constant::Bool(l != r)),
437 BinOpKind::Lt => Some(Constant::Bool(l < r)),
438 BinOpKind::Le => Some(Constant::Bool(l <= r)),
439 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
440 BinOpKind::Gt => Some(Constant::Bool(l > r)),
443 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
444 BinOpKind::Add => Some(Constant::F64(l + r)),
445 BinOpKind::Sub => Some(Constant::F64(l - r)),
446 BinOpKind::Mul => Some(Constant::F64(l * r)),
447 BinOpKind::Div => Some(Constant::F64(l / r)),
448 BinOpKind::Rem => Some(Constant::F64(l % r)),
449 BinOpKind::Eq => Some(Constant::Bool(l == r)),
450 BinOpKind::Ne => Some(Constant::Bool(l != r)),
451 BinOpKind::Lt => Some(Constant::Bool(l < r)),
452 BinOpKind::Le => Some(Constant::Bool(l <= r)),
453 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
454 BinOpKind::Gt => Some(Constant::Bool(l > r)),
457 (l, r) => match (op.node, l, r) {
458 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
459 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
460 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
463 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
464 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
465 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
472 pub fn miri_to_const(result: &ty::Const<'_>) -> Option<Constant> {
473 use rustc::mir::interpret::{ConstValue, Scalar};
475 ConstValue::Scalar(Scalar::Raw { data: d, .. }) => match result.ty.kind {
476 ty::Bool => Some(Constant::Bool(d == 1)),
477 ty::Uint(_) | ty::Int(_) => Some(Constant::Int(d)),
478 ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(
479 d.try_into().expect("invalid f32 bit representation"),
481 ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(
482 d.try_into().expect("invalid f64 bit representation"),
484 ty::RawPtr(type_and_mut) => {
485 if let ty::Uint(_) = type_and_mut.ty.kind {
486 return Some(Constant::RawPtr(d));
490 // FIXME: implement other conversions.
493 ConstValue::Slice { data, start, end } => match result.ty.kind {
494 ty::Ref(_, tam, _) => match tam.kind {
495 ty::Str => String::from_utf8(
496 data.inspect_with_undef_and_ptr_outside_interpreter(start..end)
505 // FIXME: implement other conversions.