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};
28 /// A `LitKind`-like enum to fold constant `Expr`s into.
29 #[derive(Debug, Clone)]
33 /// a Binary String b"abc"
37 /// an integer's bit representation
45 /// an array of constants
47 /// also an array, but with only one constant, repeated N times
48 Repeat(Box<Constant>, u64),
49 /// a tuple of constants
53 impl PartialEq for Constant {
54 fn eq(&self, other: &Self) -> bool {
56 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => ls == rs,
57 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
58 (&Constant::Char(l), &Constant::Char(r)) => l == r,
59 (&Constant::Int(l), &Constant::Int(r)) => l == r,
60 (&Constant::F64(l), &Constant::F64(r)) => {
61 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
62 // `Fw32 == Fw64` so don’t compare them
63 // to_bits is required to catch non-matching 0.0, -0.0, and NaNs
64 l.to_bits() == r.to_bits()
66 (&Constant::F32(l), &Constant::F32(r)) => {
67 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
68 // `Fw32 == Fw64` so don’t compare them
69 // to_bits is required to catch non-matching 0.0, -0.0, and NaNs
70 f64::from(l).to_bits() == f64::from(r).to_bits()
72 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
73 (&Constant::Vec(ref l), &Constant::Vec(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => {
76 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
77 _ => false, // TODO: Are there inter-type equalities?
82 impl Hash for Constant {
83 fn hash<H>(&self, state: &mut H)
88 Constant::Str(ref s) => {
91 Constant::Binary(ref b) => {
94 Constant::Char(c) => {
100 Constant::F32(f) => {
101 f64::from(f).to_bits().hash(state);
103 Constant::F64(f) => {
104 f.to_bits().hash(state);
106 Constant::Bool(b) => {
109 Constant::Vec(ref v) | Constant::Tuple(ref v) => {
112 Constant::Repeat(ref c, l) => {
121 pub fn partial_cmp(tcx: TyCtxt<'_, '_, '_>, cmp_type: ty::Ty<'_>, left: &Self, right: &Self) -> Option<Ordering> {
122 match (left, right) {
123 (&Constant::Str(ref ls), &Constant::Str(ref rs)) => Some(ls.cmp(rs)),
124 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
125 (&Constant::Int(l), &Constant::Int(r)) => {
126 if let ty::Int(int_ty) = cmp_type.sty {
127 Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
132 (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
133 (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
134 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
135 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l
138 .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
139 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
140 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
141 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
142 match Self::partial_cmp(tcx, cmp_type, lv, rv) {
143 Some(Equal) => Some(ls.cmp(rs)),
147 _ => None, // TODO: Are there any useful inter-type orderings?
152 /// parse a `LitKind` to a `Constant`
153 pub fn lit_to_constant<'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
154 use crate::syntax::ast::*;
157 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
158 LitKind::Byte(b) => Constant::Int(u128::from(b)),
159 LitKind::ByteStr(ref s) => Constant::Binary(Rc::clone(s)),
160 LitKind::Char(c) => Constant::Char(c),
161 LitKind::Int(n, _) => Constant::Int(n),
162 LitKind::Float(ref is, _) | LitKind::FloatUnsuffixed(ref is) => match ty.sty {
163 ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
164 ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
167 LitKind::Bool(b) => Constant::Bool(b),
171 pub fn constant<'c, 'cc>(
172 lcx: &LateContext<'c, 'cc>,
173 tables: &'c ty::TypeckTables<'cc>,
175 ) -> Option<(Constant, bool)> {
176 let mut cx = ConstEvalLateContext {
179 param_env: lcx.param_env,
180 needed_resolution: false,
181 substs: lcx.tcx.intern_substs(&[]),
183 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
186 pub fn constant_simple<'c, 'cc>(
187 lcx: &LateContext<'c, 'cc>,
188 tables: &'c ty::TypeckTables<'cc>,
190 ) -> Option<Constant> {
191 constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
194 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`
195 pub fn constant_context<'c, 'cc>(
196 lcx: &LateContext<'c, 'cc>,
197 tables: &'c ty::TypeckTables<'cc>,
198 ) -> ConstEvalLateContext<'c, 'cc> {
199 ConstEvalLateContext {
202 param_env: lcx.param_env,
203 needed_resolution: false,
204 substs: lcx.tcx.intern_substs(&[]),
208 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
209 tcx: TyCtxt<'a, 'tcx, 'tcx>,
210 tables: &'a ty::TypeckTables<'tcx>,
211 param_env: ty::ParamEnv<'tcx>,
212 needed_resolution: bool,
213 substs: &'tcx Substs<'tcx>,
216 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
217 /// simple constant folding: Insert an expression, get a constant or none.
218 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
220 ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
221 ExprKind::Block(ref block, _) => self.block(block),
222 ExprKind::If(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
223 ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
224 ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
225 ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
226 ExprKind::Repeat(ref value, _) => {
227 let n = match self.tables.expr_ty(e).sty {
228 ty::Array(_, n) => n.assert_usize(self.tcx).expect("array length"),
229 _ => span_bug!(e.span, "typeck error"),
231 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
233 ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
234 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
235 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
238 ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
239 // TODO: add other expressions
244 #[allow(clippy::cast_possible_wrap)]
245 fn constant_not(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
246 use self::Constant::*;
248 Bool(b) => Some(Bool(!b)),
252 ty::Int(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
253 ty::Uint(ity) => Some(Int(clip(self.tcx, value, ity))),
261 fn constant_negate(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
262 use self::Constant::*;
265 let ity = match ty.sty {
270 let value = sext(self.tcx, value, ity);
271 let value = value.checked_neg()?;
273 Some(Int(unsext(self.tcx, value, ity)))
275 F32(f) => Some(F32(-f)),
276 F64(f) => Some(F64(-f)),
281 /// create `Some(Vec![..])` of all constants, unless there is any
282 /// non-constant part
283 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
284 vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
287 /// lookup a possibly constant expression from a ExprKind::Path
288 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
289 use crate::rustc::mir::interpret::GlobalId;
291 let def = self.tables.qpath_def(qpath, id);
293 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
294 let substs = self.tables.node_substs(id);
295 let substs = if self.substs.is_empty() {
298 substs.subst(self.tcx, self.substs)
300 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
306 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
307 let ret = miri_to_const(self.tcx, result);
309 self.needed_resolution = true;
318 /// A block can only yield a constant if it only has one constant expression
319 fn block(&mut self, block: &Block) -> Option<Constant> {
320 if block.stmts.is_empty() {
321 block.expr.as_ref().and_then(|b| self.expr(b))
327 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
328 if let Some(Constant::Bool(b)) = self.expr(cond) {
332 otherwise.as_ref().and_then(|expr| self.expr(expr))
339 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
340 let l = self.expr(left)?;
341 let r = self.expr(right);
343 (Constant::Int(l), Some(Constant::Int(r))) => match self.tables.expr_ty(left).sty {
345 let l = sext(self.tcx, l, ity);
346 let r = sext(self.tcx, r, ity);
347 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
349 BinOpKind::Add => l.checked_add(r).map(zext),
350 BinOpKind::Sub => l.checked_sub(r).map(zext),
351 BinOpKind::Mul => l.checked_mul(r).map(zext),
352 BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
353 BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
354 BinOpKind::Shr => l.checked_shr(r.try_into().expect("invalid shift")).map(zext),
355 BinOpKind::Shl => l.checked_shl(r.try_into().expect("invalid shift")).map(zext),
356 BinOpKind::BitXor => Some(zext(l ^ r)),
357 BinOpKind::BitOr => Some(zext(l | r)),
358 BinOpKind::BitAnd => Some(zext(l & r)),
359 BinOpKind::Eq => Some(Constant::Bool(l == r)),
360 BinOpKind::Ne => Some(Constant::Bool(l != r)),
361 BinOpKind::Lt => Some(Constant::Bool(l < r)),
362 BinOpKind::Le => Some(Constant::Bool(l <= r)),
363 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
364 BinOpKind::Gt => Some(Constant::Bool(l > r)),
368 ty::Uint(_) => match op.node {
369 BinOpKind::Add => l.checked_add(r).map(Constant::Int),
370 BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
371 BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
372 BinOpKind::Div => l.checked_div(r).map(Constant::Int),
373 BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
374 BinOpKind::Shr => l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int),
375 BinOpKind::Shl => l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int),
376 BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
377 BinOpKind::BitOr => Some(Constant::Int(l | r)),
378 BinOpKind::BitAnd => Some(Constant::Int(l & r)),
379 BinOpKind::Eq => Some(Constant::Bool(l == r)),
380 BinOpKind::Ne => Some(Constant::Bool(l != r)),
381 BinOpKind::Lt => Some(Constant::Bool(l < r)),
382 BinOpKind::Le => Some(Constant::Bool(l <= r)),
383 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
384 BinOpKind::Gt => Some(Constant::Bool(l > r)),
389 (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
390 BinOpKind::Add => Some(Constant::F32(l + r)),
391 BinOpKind::Sub => Some(Constant::F32(l - r)),
392 BinOpKind::Mul => Some(Constant::F32(l * r)),
393 BinOpKind::Div => Some(Constant::F32(l / r)),
394 BinOpKind::Rem => Some(Constant::F32(l % r)),
395 BinOpKind::Eq => Some(Constant::Bool(l == r)),
396 BinOpKind::Ne => Some(Constant::Bool(l != r)),
397 BinOpKind::Lt => Some(Constant::Bool(l < r)),
398 BinOpKind::Le => Some(Constant::Bool(l <= r)),
399 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
400 BinOpKind::Gt => Some(Constant::Bool(l > r)),
403 (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
404 BinOpKind::Add => Some(Constant::F64(l + r)),
405 BinOpKind::Sub => Some(Constant::F64(l - r)),
406 BinOpKind::Mul => Some(Constant::F64(l * r)),
407 BinOpKind::Div => Some(Constant::F64(l / r)),
408 BinOpKind::Rem => Some(Constant::F64(l % r)),
409 BinOpKind::Eq => Some(Constant::Bool(l == r)),
410 BinOpKind::Ne => Some(Constant::Bool(l != r)),
411 BinOpKind::Lt => Some(Constant::Bool(l < r)),
412 BinOpKind::Le => Some(Constant::Bool(l <= r)),
413 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
414 BinOpKind::Gt => Some(Constant::Bool(l > r)),
417 (l, r) => match (op.node, l, r) {
418 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
419 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
420 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
423 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
424 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
425 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
432 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
433 use crate::rustc::mir::interpret::{ConstValue, Scalar};
435 ConstValue::Scalar(Scalar::Bits { bits: b, .. }) => match result.ty.sty {
436 ty::Bool => Some(Constant::Bool(b == 1)),
437 ty::Uint(_) | ty::Int(_) => Some(Constant::Int(b)),
438 ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(
439 b.try_into().expect("invalid f32 bit representation"),
441 ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(
442 b.try_into().expect("invalid f64 bit representation"),
444 // FIXME: implement other conversion
447 ConstValue::ScalarPair(Scalar::Ptr(ptr), Scalar::Bits { bits: n, .. }) => match result.ty.sty {
448 ty::Ref(_, tam, _) => match tam.sty {
450 let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
451 let offset = ptr.offset.bytes().try_into().expect("too-large pointer offset");
453 String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned())
461 // FIXME: implement other conversions