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::hir::def::Def;
14 use crate::rustc::hir::*;
15 use crate::rustc::lint::LateContext;
16 use crate::rustc::ty::subst::{Subst, Substs};
17 use crate::rustc::ty::{self, Instance, Ty, TyCtxt};
18 use crate::rustc::{bug, span_bug};
19 use crate::syntax::ast::{FloatTy, LitKind};
20 use crate::syntax::ptr::P;
21 use crate::utils::{clip, sext, unsext};
22 use std::cmp::Ordering::{self, Equal};
23 use std::cmp::PartialOrd;
24 use std::convert::TryInto;
25 use std::hash::{Hash, Hasher};
29 /// A `LitKind`-like enum to fold constant `Expr`s into.
30 #[derive(Debug, Clone)]
34 /// a Binary String b"abc"
38 /// an integer's bit representation
46 /// an array of constants
48 /// also an array, but with only one constant, repeated N times
49 Repeat(Box<Constant>, u64),
50 /// a tuple of constants
54 impl PartialEq for Constant {
55 fn eq(&self, other: &Self) -> bool {
57 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => ls == rs,
58 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
59 (&Constant::Char(l), &Constant::Char(r)) => l == r,
60 (&Constant::Int(l), &Constant::Int(r)) => l == r,
61 (&Constant::F64(l), &Constant::F64(r)) => {
62 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
63 // `Fw32 == Fw64` so don’t compare them
64 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
65 unsafe { mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r) }
67 (&Constant::F32(l), &Constant::F32(r)) => {
68 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
69 // `Fw32 == Fw64` so don’t compare them
70 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
71 unsafe { mem::transmute::<f64, u64>(f64::from(l)) == mem::transmute::<f64, u64>(f64::from(r)) }
73 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
74 (&Constant::Vec(ref l), &Constant::Vec(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => {
77 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
78 _ => false, // TODO: Are there inter-type equalities?
83 impl Hash for Constant {
84 fn hash<H>(&self, state: &mut H)
89 Constant::Str(ref s) => {
92 Constant::Binary(ref b) => {
95 Constant::Char(c) => {
101 Constant::F32(f) => {
102 unsafe { mem::transmute::<f64, u64>(f64::from(f)) }.hash(state);
104 Constant::F64(f) => {
105 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
107 Constant::Bool(b) => {
110 Constant::Vec(ref v) | Constant::Tuple(ref v) => {
113 Constant::Repeat(ref c, l) => {
122 pub fn partial_cmp(tcx: TyCtxt<'_, '_, '_>, cmp_type: ty::Ty<'_>, left: &Self, right: &Self) -> Option<Ordering> {
123 match (left, right) {
124 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => Some(ls.cmp(rs)),
125 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
126 (&Constant::Int(l), &Constant::Int(r)) => {
127 if let ty::Int(int_ty) = cmp_type.sty {
128 Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
133 (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
134 (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
135 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
136 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::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 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
143 match Self::partial_cmp(tcx, cmp_type, lv, rv) {
144 Some(Equal) => Some(ls.cmp(rs)),
148 _ => None, // TODO: Are there any useful inter-type orderings?
153 /// parse a `LitKind` to a `Constant`
154 pub fn lit_to_constant<'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
155 use crate::syntax::ast::*;
158 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
159 LitKind::Byte(b) => Constant::Int(u128::from(b)),
160 LitKind::ByteStr(ref s) => Constant::Binary(Rc::clone(s)),
161 LitKind::Char(c) => Constant::Char(c),
162 LitKind::Int(n, _) => Constant::Int(n),
163 LitKind::Float(ref is, _) | LitKind::FloatUnsuffixed(ref is) => match ty.sty {
164 ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
165 ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
168 LitKind::Bool(b) => Constant::Bool(b),
172 pub fn constant<'c, 'cc>(
173 lcx: &LateContext<'c, 'cc>,
174 tables: &'c ty::TypeckTables<'cc>,
176 ) -> Option<(Constant, bool)> {
177 let mut cx = ConstEvalLateContext {
180 param_env: lcx.param_env,
181 needed_resolution: false,
182 substs: lcx.tcx.intern_substs(&[]),
184 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
187 pub fn constant_simple<'c, 'cc>(
188 lcx: &LateContext<'c, 'cc>,
189 tables: &'c ty::TypeckTables<'cc>,
191 ) -> Option<Constant> {
192 constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
195 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`
196 pub fn constant_context<'c, 'cc>(
197 lcx: &LateContext<'c, 'cc>,
198 tables: &'c ty::TypeckTables<'cc>,
199 ) -> ConstEvalLateContext<'c, 'cc> {
200 ConstEvalLateContext {
203 param_env: lcx.param_env,
204 needed_resolution: false,
205 substs: lcx.tcx.intern_substs(&[]),
209 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
210 tcx: TyCtxt<'a, 'tcx, 'tcx>,
211 tables: &'a ty::TypeckTables<'tcx>,
212 param_env: ty::ParamEnv<'tcx>,
213 needed_resolution: bool,
214 substs: &'tcx Substs<'tcx>,
217 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
218 /// simple constant folding: Insert an expression, get a constant or none.
219 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
221 ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
222 ExprKind::Block(ref block, _) => self.block(block),
223 ExprKind::If(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
224 ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
225 ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
226 ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
227 ExprKind::Repeat(ref value, _) => {
228 let n = match self.tables.expr_ty(e).sty {
229 ty::Array(_, n) => n.assert_usize(self.tcx).expect("array length"),
230 _ => span_bug!(e.span, "typeck error"),
232 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
234 ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
235 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
236 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
239 ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
240 // TODO: add other expressions
245 #[allow(clippy::cast_possible_wrap)]
246 fn constant_not(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
247 use self::Constant::*;
249 Bool(b) => Some(Bool(!b)),
253 ty::Int(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
254 ty::Uint(ity) => Some(Int(clip(self.tcx, value, ity))),
262 fn constant_negate(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
263 use self::Constant::*;
266 let ity = match ty.sty {
271 let value = sext(self.tcx, value, ity);
272 let value = value.checked_neg()?;
274 Some(Int(unsext(self.tcx, value, ity)))
276 F32(f) => Some(F32(-f)),
277 F64(f) => Some(F64(-f)),
282 /// create `Some(Vec![..])` of all constants, unless there is any
283 /// non-constant part
284 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
285 vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
288 /// lookup a possibly constant expression from a ExprKind::Path
289 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
290 use crate::rustc::mir::interpret::GlobalId;
292 let def = self.tables.qpath_def(qpath, id);
294 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
295 let substs = self.tables.node_substs(id);
296 let substs = if self.substs.is_empty() {
299 substs.subst(self.tcx, self.substs)
301 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
307 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
308 let ret = miri_to_const(self.tcx, result);
310 self.needed_resolution = true;
319 /// A block can only yield a constant if it only has one constant expression
320 fn block(&mut self, block: &Block) -> Option<Constant> {
321 if block.stmts.is_empty() {
322 block.expr.as_ref().and_then(|b| self.expr(b))
328 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
329 if let Some(Constant::Bool(b)) = self.expr(cond) {
333 otherwise.as_ref().and_then(|expr| self.expr(expr))
340 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
341 let l = self.expr(left)?;
342 let r = self.expr(right);
344 (Constant::Int(l), Some(Constant::Int(r))) => match self.tables.expr_ty(left).sty {
346 let l = sext(self.tcx, l, ity);
347 let r = sext(self.tcx, r, ity);
348 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
350 BinOpKind::Add => l.checked_add(r).map(zext),
351 BinOpKind::Sub => l.checked_sub(r).map(zext),
352 BinOpKind::Mul => l.checked_mul(r).map(zext),
353 BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
354 BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
355 BinOpKind::Shr => l.checked_shr(r.try_into().expect("invalid shift")).map(zext),
356 BinOpKind::Shl => l.checked_shl(r.try_into().expect("invalid shift")).map(zext),
357 BinOpKind::BitXor => Some(zext(l ^ r)),
358 BinOpKind::BitOr => Some(zext(l | r)),
359 BinOpKind::BitAnd => Some(zext(l & r)),
360 BinOpKind::Eq => Some(Constant::Bool(l == r)),
361 BinOpKind::Ne => Some(Constant::Bool(l != r)),
362 BinOpKind::Lt => Some(Constant::Bool(l < r)),
363 BinOpKind::Le => Some(Constant::Bool(l <= r)),
364 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
365 BinOpKind::Gt => Some(Constant::Bool(l > r)),
369 ty::Uint(_) => match op.node {
370 BinOpKind::Add => l.checked_add(r).map(Constant::Int),
371 BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
372 BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
373 BinOpKind::Div => l.checked_div(r).map(Constant::Int),
374 BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
375 BinOpKind::Shr => l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int),
376 BinOpKind::Shl => l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int),
377 BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
378 BinOpKind::BitOr => Some(Constant::Int(l | r)),
379 BinOpKind::BitAnd => Some(Constant::Int(l & r)),
380 BinOpKind::Eq => Some(Constant::Bool(l == r)),
381 BinOpKind::Ne => Some(Constant::Bool(l != r)),
382 BinOpKind::Lt => Some(Constant::Bool(l < r)),
383 BinOpKind::Le => Some(Constant::Bool(l <= r)),
384 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
385 BinOpKind::Gt => Some(Constant::Bool(l > r)),
390 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
391 BinOpKind::Add => Some(Constant::F32(l + r)),
392 BinOpKind::Sub => Some(Constant::F32(l - r)),
393 BinOpKind::Mul => Some(Constant::F32(l * r)),
394 BinOpKind::Div => Some(Constant::F32(l / r)),
395 BinOpKind::Rem => Some(Constant::F32(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)),
404 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
405 BinOpKind::Add => Some(Constant::F64(l + r)),
406 BinOpKind::Sub => Some(Constant::F64(l - r)),
407 BinOpKind::Mul => Some(Constant::F64(l * r)),
408 BinOpKind::Div => Some(Constant::F64(l / r)),
409 BinOpKind::Rem => Some(Constant::F64(l % r)),
410 BinOpKind::Eq => Some(Constant::Bool(l == r)),
411 BinOpKind::Ne => Some(Constant::Bool(l != r)),
412 BinOpKind::Lt => Some(Constant::Bool(l < r)),
413 BinOpKind::Le => Some(Constant::Bool(l <= r)),
414 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
415 BinOpKind::Gt => Some(Constant::Bool(l > r)),
418 (l, r) => match (op.node, l, r) {
419 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
420 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
421 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
424 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
425 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
426 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
433 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
434 use crate::rustc::mir::interpret::{ConstValue, Scalar};
436 ConstValue::Scalar(Scalar::Bits { bits: b, .. }) => match result.ty.sty {
437 ty::Bool => Some(Constant::Bool(b == 1)),
438 ty::Uint(_) | ty::Int(_) => Some(Constant::Int(b)),
439 ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(
440 b.try_into().expect("invalid f32 bit representation"),
442 ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(
443 b.try_into().expect("invalid f64 bit representation"),
445 // FIXME: implement other conversion
448 ConstValue::ScalarPair(Scalar::Ptr(ptr), Scalar::Bits { bits: n, .. }) => match result.ty.sty {
449 ty::Ref(_, tam, _) => match tam.sty {
451 let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
452 let offset = ptr.offset.bytes().try_into().expect("too-large pointer offset");
454 String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned())
462 // FIXME: implement other conversions