1 #![allow(cast_possible_truncation)]
3 use rustc::lint::LateContext;
4 use rustc::hir::def::Def;
5 use rustc_const_eval::lookup_const_by_id;
6 use rustc_const_math::ConstInt;
8 use rustc::ty::{self, Ty, TyCtxt};
9 use rustc::ty::subst::{Subst, Substs};
10 use std::cmp::Ordering::{self, Equal};
11 use std::cmp::PartialOrd;
12 use std::hash::{Hash, Hasher};
15 use syntax::ast::{FloatTy, LitKind, StrStyle};
17 use utils::const_to_u64;
19 #[derive(Debug, Copy, Clone)]
26 impl From<FloatTy> for FloatWidth {
27 fn from(ty: FloatTy) -> Self {
29 FloatTy::F32 => FloatWidth::F32,
30 FloatTy::F64 => FloatWidth::F64,
35 /// A `LitKind`-like enum to fold constant `Expr`s into.
36 #[derive(Debug, Clone)]
39 Str(String, StrStyle),
40 /// a Binary String b"abc"
44 /// an integer, third argument is whether the value is negated
46 /// a float with given type
47 Float(String, FloatWidth),
50 /// an array of constants
52 /// also an array, but with only one constant, repeated N times
53 Repeat(Box<Constant>, u64),
54 /// a tuple of constants
58 impl PartialEq for Constant {
59 fn eq(&self, other: &Self) -> bool {
61 (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => ls == rs && l_sty == r_sty,
62 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
63 (&Constant::Char(l), &Constant::Char(r)) => l == r,
64 (&Constant::Int(l), &Constant::Int(r)) => {
65 l.is_negative() == r.is_negative() && l.to_u128_unchecked() == r.to_u128_unchecked()
67 (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
68 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
69 // `Fw32 == Fw64` so don’t compare them
70 match (ls.parse::<f64>(), rs.parse::<f64>()) {
71 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
72 (Ok(l), Ok(r)) => unsafe { mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r) },
76 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
77 (&Constant::Vec(ref l), &Constant::Vec(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
78 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
79 _ => false, // TODO: Are there inter-type equalities?
84 impl Hash for Constant {
85 fn hash<H>(&self, state: &mut H)
90 Constant::Str(ref s, ref k) => {
94 Constant::Binary(ref b) => {
97 Constant::Char(c) => {
100 Constant::Int(i) => {
101 i.to_u128_unchecked().hash(state);
102 i.is_negative().hash(state);
104 Constant::Float(ref f, _) => {
105 // don’t use the width here because of PartialEq implementation
106 if let Ok(f) = f.parse::<f64>() {
107 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
110 Constant::Bool(b) => {
113 Constant::Vec(ref v) | Constant::Tuple(ref v) => {
116 Constant::Repeat(ref c, l) => {
124 impl PartialOrd for Constant {
125 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
126 match (self, other) {
127 (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => if l_sty == r_sty {
132 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
133 (&Constant::Int(l), &Constant::Int(r)) => Some(l.cmp(&r)),
134 (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
135 match (ls.parse::<f64>(), rs.parse::<f64>()) {
136 (Ok(ref l), Ok(ref r)) => {
137 match (l.partial_cmp(r), l.is_sign_positive() == r.is_sign_positive()) {
138 // Check for comparison of -0.0 and 0.0
139 (Some(Ordering::Equal), false) => None,
146 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
147 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => {
150 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => match lv.partial_cmp(rv) {
151 Some(Equal) => Some(ls.cmp(rs)),
154 _ => None, // TODO: Are there any useful inter-type orderings?
159 /// parse a `LitKind` to a `Constant`
160 #[allow(cast_possible_wrap)]
161 pub fn lit_to_constant<'a, 'tcx>(lit: &LitKind, tcx: TyCtxt<'a, 'tcx, 'tcx>, mut ty: Ty<'tcx>) -> Constant {
163 use syntax::ast::LitIntType::*;
164 use rustc::ty::util::IntTypeExt;
166 if let ty::TyAdt(adt, _) = ty.sty {
168 ty = adt.repr.discr_type().to_ty(tcx)
172 LitKind::Str(ref is, style) => Constant::Str(is.to_string(), style),
173 LitKind::Byte(b) => Constant::Int(ConstInt::U8(b)),
174 LitKind::ByteStr(ref s) => Constant::Binary(Rc::clone(s)),
175 LitKind::Char(c) => Constant::Char(c),
176 LitKind::Int(n, hint) => match (&ty.sty, hint) {
177 (&ty::TyInt(ity), _) | (_, Signed(ity)) => {
178 Constant::Int(ConstInt::new_signed_truncating(n as i128, ity, tcx.sess.target.isize_ty))
180 (&ty::TyUint(uty), _) | (_, Unsigned(uty)) => {
181 Constant::Int(ConstInt::new_unsigned_truncating(n as u128, uty, tcx.sess.target.usize_ty))
185 LitKind::Float(ref is, ty) => Constant::Float(is.to_string(), ty.into()),
186 LitKind::FloatUnsuffixed(ref is) => Constant::Float(is.to_string(), FloatWidth::Any),
187 LitKind::Bool(b) => Constant::Bool(b),
191 fn constant_not(o: &Constant) -> Option<Constant> {
192 use self::Constant::*;
194 Bool(b) => Some(Bool(!b)),
195 Int(value) => (!value).ok().map(Int),
200 fn constant_negate(o: Constant) -> Option<Constant> {
201 use self::Constant::*;
203 Int(value) => (-value).ok().map(Int),
204 Float(is, ty) => Some(Float(neg_float_str(&is), ty)),
209 fn neg_float_str(s: &str) -> String {
210 if s.starts_with('-') {
217 pub fn constant(lcx: &LateContext, e: &Expr) -> Option<(Constant, bool)> {
218 let mut cx = ConstEvalLateContext {
221 param_env: lcx.param_env,
222 needed_resolution: false,
223 substs: lcx.tcx.intern_substs(&[]),
225 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
228 pub fn constant_simple(lcx: &LateContext, e: &Expr) -> Option<Constant> {
229 constant(lcx, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
232 /// Creates a ConstEvalLateContext from the given LateContext and TypeckTables
233 pub fn constant_context<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'cc ty::TypeckTables<'cc>) -> ConstEvalLateContext<'c, 'cc> {
234 ConstEvalLateContext {
237 param_env: lcx.param_env,
238 needed_resolution: false,
239 substs: lcx.tcx.intern_substs(&[]),
243 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
244 tcx: TyCtxt<'a, 'tcx, 'tcx>,
245 tables: &'a ty::TypeckTables<'tcx>,
246 param_env: ty::ParamEnv<'tcx>,
247 needed_resolution: bool,
248 substs: &'tcx Substs<'tcx>,
251 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
252 /// simple constant folding: Insert an expression, get a constant or none.
253 pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
255 ExprPath(ref qpath) => self.fetch_path(qpath, e.hir_id),
256 ExprBlock(ref block) => self.block(block),
257 ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
258 ExprLit(ref lit) => Some(lit_to_constant(&lit.node, self.tcx, self.tables.expr_ty(e))),
259 ExprArray(ref vec) => self.multi(vec).map(Constant::Vec),
260 ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
261 ExprRepeat(ref value, _) => {
262 let n = match self.tables.expr_ty(e).sty {
263 ty::TyArray(_, n) => const_to_u64(n),
264 _ => span_bug!(e.span, "typeck error"),
266 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
268 ExprUnary(op, ref operand) => self.expr(operand).and_then(|o| match op {
269 UnNot => constant_not(&o),
270 UnNeg => constant_negate(o),
273 ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
274 // TODO: add other expressions
279 /// create `Some(Vec![..])` of all constants, unless there is any
280 /// non-constant part
281 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
283 .map(|elem| self.expr(elem))
284 .collect::<Option<_>>()
287 /// lookup a possibly constant expression from a ExprPath
288 fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
289 let def = self.tables.qpath_def(qpath, id);
291 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
292 let substs = self.tables.node_substs(id);
293 let substs = if self.substs.is_empty() {
296 substs.subst(self.tcx, self.substs)
298 let param_env = self.param_env.and((def_id, substs));
299 if let Some((def_id, substs)) = lookup_const_by_id(self.tcx, param_env) {
302 tables: self.tcx.typeck_tables_of(def_id),
303 needed_resolution: false,
305 param_env: param_env.param_env,
307 let body = if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
308 self.tcx.mir_const_qualif(def_id);
309 self.tcx.hir.body(self.tcx.hir.body_owned_by(id))
311 self.tcx.extern_const_body(def_id).body
313 let ret = cx.expr(&body.value);
315 self.needed_resolution = true;
325 /// A block can only yield a constant if it only has one constant expression
326 fn block(&mut self, block: &Block) -> Option<Constant> {
327 if block.stmts.is_empty() {
328 block.expr.as_ref().and_then(|b| self.expr(b))
334 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
335 if let Some(Constant::Bool(b)) = self.expr(cond) {
339 otherwise.as_ref().and_then(|expr| self.expr(expr))
346 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
347 let l = if let Some(l) = self.expr(left) {
352 let r = self.expr(right);
353 match (op.node, l, r) {
354 (BiAdd, Constant::Int(l), Some(Constant::Int(r))) => (l + r).ok().map(Constant::Int),
355 (BiSub, Constant::Int(l), Some(Constant::Int(r))) => (l - r).ok().map(Constant::Int),
356 (BiMul, Constant::Int(l), Some(Constant::Int(r))) => (l * r).ok().map(Constant::Int),
357 (BiDiv, Constant::Int(l), Some(Constant::Int(r))) => (l / r).ok().map(Constant::Int),
358 (BiRem, Constant::Int(l), Some(Constant::Int(r))) => (l % r).ok().map(Constant::Int),
359 (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
360 (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
361 (BiAnd, Constant::Bool(true), Some(r)) | (BiOr, Constant::Bool(false), Some(r)) => Some(r),
362 (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
363 (BiBitXor, Constant::Int(l), Some(Constant::Int(r))) => (l ^ r).ok().map(Constant::Int),
364 (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
365 (BiBitAnd, Constant::Int(l), Some(Constant::Int(r))) => (l & r).ok().map(Constant::Int),
366 (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
367 (BiBitOr, Constant::Int(l), Some(Constant::Int(r))) => (l | r).ok().map(Constant::Int),
368 (BiShl, Constant::Int(l), Some(Constant::Int(r))) => (l << r).ok().map(Constant::Int),
369 (BiShr, Constant::Int(l), Some(Constant::Int(r))) => (l >> r).ok().map(Constant::Int),
370 (BiEq, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l == r)),
371 (BiNe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l != r)),
372 (BiLt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l < r)),
373 (BiLe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l <= r)),
374 (BiGe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l >= r)),
375 (BiGt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l > r)),