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::TryFrom;
15 use std::convert::TryInto;
16 use std::hash::{Hash, Hasher};
17 use syntax::ast::{FloatTy, LitKind};
18 use syntax_pos::symbol::{LocalInternedString, Symbol};
20 /// A `LitKind`-like enum to fold constant `Expr`s into.
21 #[derive(Debug, Clone)]
23 /// A `String` (e.g., "abc").
25 /// A binary string (e.g., `b"abc"`).
27 /// A single `char` (e.g., `'a'`).
29 /// An integer's bit representation.
35 /// `true` or `false`.
37 /// An array of constants.
39 /// Also an array, but with only one constant, repeated N times.
40 Repeat(Box<Constant>, u64),
41 /// A tuple of constants.
45 /// A literal with syntax error.
49 impl PartialEq for Constant {
50 fn eq(&self, other: &Self) -> bool {
52 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => ls == rs,
53 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
54 (&Constant::Char(l), &Constant::Char(r)) => l == r,
55 (&Constant::Int(l), &Constant::Int(r)) => l == r,
56 (&Constant::F64(l), &Constant::F64(r)) => {
57 // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have
58 // `Fw32 == Fw64`, so don’t compare them.
59 // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs.
60 l.to_bits() == r.to_bits()
62 (&Constant::F32(l), &Constant::F32(r)) => {
63 // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have
64 // `Fw32 == Fw64`, so don’t compare them.
65 // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs.
66 f64::from(l).to_bits() == f64::from(r).to_bits()
68 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
69 (&Constant::Vec(ref l), &Constant::Vec(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => {
72 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
73 // TODO: are there inter-type equalities?
79 impl Hash for Constant {
80 fn hash<H>(&self, state: &mut H)
84 std::mem::discriminant(self).hash(state);
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: &'c 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 lcx: &'a LateContext<'a, '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> {
225 if let Some((ref cond, ref then, otherwise)) = higher::if_block(&e) {
226 return self.ifthenelse(cond, then, otherwise);
229 ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
230 ExprKind::Block(ref block, _) => self.block(block),
231 ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
232 ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
233 ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
234 ExprKind::Repeat(ref value, _) => {
235 let n = match self.tables.expr_ty(e).sty {
236 ty::Array(_, n) => n.assert_usize(self.lcx.tcx).expect("array length"),
237 _ => span_bug!(e.span, "typeck error"),
239 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
241 ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
242 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
243 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
246 ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
247 ExprKind::Call(ref callee, ref args) => {
248 // We only handle a few const functions for now.
251 if let ExprKind::Path(qpath) = &callee.node;
252 let res = self.tables.qpath_res(qpath, callee.hir_id);
253 if let Some(def_id) = res.opt_def_id();
254 let get_def_path = self.lcx.get_def_path(def_id);
255 let def_path = get_def_path
257 .map(LocalInternedString::get)
258 .collect::<Vec<_>>();
259 if let &["core", "num", impl_ty, "max_value"] = &def_path[..];
261 let value = match impl_ty {
262 "<impl i8>" => i8::max_value() as u128,
263 "<impl i16>" => i16::max_value() as u128,
264 "<impl i32>" => i32::max_value() as u128,
265 "<impl i64>" => i64::max_value() as u128,
266 "<impl i128>" => i128::max_value() as u128,
269 Some(Constant::Int(value))
276 // TODO: add other expressions.
281 #[allow(clippy::cast_possible_wrap)]
282 fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
283 use self::Constant::*;
285 Bool(b) => Some(Bool(!b)),
289 ty::Int(ity) => Some(Int(unsext(self.lcx.tcx, value as i128, ity))),
290 ty::Uint(ity) => Some(Int(clip(self.lcx.tcx, value, ity))),
298 fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
299 use self::Constant::*;
302 let ity = match ty.sty {
307 let value = sext(self.lcx.tcx, value, ity);
308 let value = value.checked_neg()?;
310 Some(Int(unsext(self.lcx.tcx, value, ity)))
312 F32(f) => Some(F32(-f)),
313 F64(f) => Some(F64(-f)),
318 /// Create `Some(Vec![..])` of all constants, unless there is any
319 /// non-constant part.
320 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
321 vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
324 /// Lookup a possibly constant expression from a ExprKind::Path.
325 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
326 use rustc::mir::interpret::GlobalId;
328 let res = self.tables.qpath_res(qpath, id);
330 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssociatedConst, def_id) => {
331 let substs = self.tables.node_substs(id);
332 let substs = if self.substs.is_empty() {
335 substs.subst(self.lcx.tcx, self.substs)
337 let instance = Instance::resolve(self.lcx.tcx, self.param_env, def_id, substs)?;
343 let result = self.lcx.tcx.const_eval(self.param_env.and(gid)).ok()?;
344 let result = miri_to_const(self.lcx.tcx, &result);
345 if result.is_some() {
346 self.needed_resolution = true;
350 // FIXME: cover all usable cases.
355 /// A block can only yield a constant if it only has one constant expression.
356 fn block(&mut self, block: &Block) -> Option<Constant> {
357 if block.stmts.is_empty() {
358 block.expr.as_ref().and_then(|b| self.expr(b))
364 fn ifthenelse(&mut self, cond: &Expr, then: &Expr, otherwise: Option<&Expr>) -> Option<Constant> {
365 if let Some(Constant::Bool(b)) = self.expr(cond) {
369 otherwise.as_ref().and_then(|expr| self.expr(expr))
376 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
377 let l = self.expr(left)?;
378 let r = self.expr(right);
380 (Constant::Int(l), Some(Constant::Int(r))) => match self.tables.expr_ty(left).sty {
382 let l = sext(self.lcx.tcx, l, ity);
383 let r = sext(self.lcx.tcx, r, ity);
384 let zext = |n: i128| Constant::Int(unsext(self.lcx.tcx, n, ity));
386 BinOpKind::Add => l.checked_add(r).map(zext),
387 BinOpKind::Sub => l.checked_sub(r).map(zext),
388 BinOpKind::Mul => l.checked_mul(r).map(zext),
389 BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
390 BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
391 BinOpKind::Shr => l.checked_shr(r.try_into().expect("invalid shift")).map(zext),
392 BinOpKind::Shl => l.checked_shl(r.try_into().expect("invalid shift")).map(zext),
393 BinOpKind::BitXor => Some(zext(l ^ r)),
394 BinOpKind::BitOr => Some(zext(l | r)),
395 BinOpKind::BitAnd => Some(zext(l & r)),
396 BinOpKind::Eq => Some(Constant::Bool(l == r)),
397 BinOpKind::Ne => Some(Constant::Bool(l != r)),
398 BinOpKind::Lt => Some(Constant::Bool(l < r)),
399 BinOpKind::Le => Some(Constant::Bool(l <= r)),
400 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
401 BinOpKind::Gt => Some(Constant::Bool(l > r)),
405 ty::Uint(_) => match op.node {
406 BinOpKind::Add => l.checked_add(r).map(Constant::Int),
407 BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
408 BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
409 BinOpKind::Div => l.checked_div(r).map(Constant::Int),
410 BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
411 BinOpKind::Shr => l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int),
412 BinOpKind::Shl => l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int),
413 BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
414 BinOpKind::BitOr => Some(Constant::Int(l | r)),
415 BinOpKind::BitAnd => Some(Constant::Int(l & r)),
416 BinOpKind::Eq => Some(Constant::Bool(l == r)),
417 BinOpKind::Ne => Some(Constant::Bool(l != r)),
418 BinOpKind::Lt => Some(Constant::Bool(l < r)),
419 BinOpKind::Le => Some(Constant::Bool(l <= r)),
420 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
421 BinOpKind::Gt => Some(Constant::Bool(l > r)),
426 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
427 BinOpKind::Add => Some(Constant::F32(l + r)),
428 BinOpKind::Sub => Some(Constant::F32(l - r)),
429 BinOpKind::Mul => Some(Constant::F32(l * r)),
430 BinOpKind::Div => Some(Constant::F32(l / r)),
431 BinOpKind::Rem => Some(Constant::F32(l % r)),
432 BinOpKind::Eq => Some(Constant::Bool(l == r)),
433 BinOpKind::Ne => Some(Constant::Bool(l != r)),
434 BinOpKind::Lt => Some(Constant::Bool(l < r)),
435 BinOpKind::Le => Some(Constant::Bool(l <= r)),
436 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
437 BinOpKind::Gt => Some(Constant::Bool(l > r)),
440 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
441 BinOpKind::Add => Some(Constant::F64(l + r)),
442 BinOpKind::Sub => Some(Constant::F64(l - r)),
443 BinOpKind::Mul => Some(Constant::F64(l * r)),
444 BinOpKind::Div => Some(Constant::F64(l / r)),
445 BinOpKind::Rem => Some(Constant::F64(l % r)),
446 BinOpKind::Eq => Some(Constant::Bool(l == r)),
447 BinOpKind::Ne => Some(Constant::Bool(l != r)),
448 BinOpKind::Lt => Some(Constant::Bool(l < r)),
449 BinOpKind::Le => Some(Constant::Bool(l <= r)),
450 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
451 BinOpKind::Gt => Some(Constant::Bool(l > r)),
454 (l, r) => match (op.node, l, r) {
455 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
456 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
457 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
460 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
461 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
462 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
469 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
470 use rustc::mir::interpret::{ConstValue, Scalar};
472 ConstValue::Scalar(Scalar::Bits { bits: b, .. }) => match result.ty.sty {
473 ty::Bool => Some(Constant::Bool(b == 1)),
474 ty::Uint(_) | ty::Int(_) => Some(Constant::Int(b)),
475 ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(
476 b.try_into().expect("invalid f32 bit representation"),
478 ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(
479 b.try_into().expect("invalid f64 bit representation"),
481 ty::RawPtr(type_and_mut) => {
482 if let ty::Uint(_) = type_and_mut.ty.sty {
483 return Some(Constant::RawPtr(b));
487 // FIXME: implement other conversions.
490 ConstValue::Slice(Scalar::Ptr(ptr), n) => match result.ty.sty {
491 ty::Ref(_, tam, _) => match tam.sty {
493 let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
494 let offset = ptr.offset.bytes().try_into().expect("too-large pointer offset");
495 let n = usize::try_from(n).unwrap();
496 String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned())
504 // FIXME: implement other conversions.