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, TyCtxt};
9 use std::cmp::Ordering::{self, Equal};
10 use std::cmp::PartialOrd;
11 use std::hash::{Hash, Hasher};
14 use syntax::ast::{FloatTy, LitKind, StrStyle, NodeId};
16 use syntax::codemap::DUMMY_SP;
18 #[derive(Debug, Copy, Clone)]
25 impl From<FloatTy> for FloatWidth {
26 fn from(ty: FloatTy) -> FloatWidth {
28 FloatTy::F32 => FloatWidth::F32,
29 FloatTy::F64 => FloatWidth::F64,
34 /// A `LitKind`-like enum to fold constant `Expr`s into.
35 #[derive(Debug, Clone)]
38 Str(String, StrStyle),
39 /// a Binary String b"abc"
43 /// an integer, third argument is whether the value is negated
45 /// a float with given type
46 Float(String, FloatWidth),
49 /// an array of constants
51 /// also an array, but with only one constant, repeated N times
52 Repeat(Box<Constant>, usize),
53 /// a tuple of constants
57 impl PartialEq for Constant {
58 fn eq(&self, other: &Constant) -> bool {
60 (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => ls == rs && l_sty == r_sty,
61 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
62 (&Constant::Char(l), &Constant::Char(r)) => l == r,
63 (&Constant::Int(l), &Constant::Int(r)) => {
64 l.is_negative() == r.is_negative() && l.to_u128_unchecked() == r.to_u128_unchecked()
66 (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
67 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
68 // `Fw32 == Fw64` so don’t compare them
69 match (ls.parse::<f64>(), rs.parse::<f64>()) {
70 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
71 (Ok(l), Ok(r)) => unsafe { mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r) },
75 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
76 (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l == r,
77 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
78 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
79 _ => false, //TODO: Are there inter-type equalities?
84 impl Hash for Constant {
85 fn hash<H>(&self, state: &mut H)
89 Constant::Str(ref s, ref k) => {
93 Constant::Binary(ref b) => {
96 Constant::Char(c) => {
100 i.to_u128_unchecked().hash(state);
101 i.is_negative().hash(state);
103 Constant::Float(ref f, _) => {
104 // don’t use the width here because of PartialEq implementation
105 if let Ok(f) = f.parse::<f64>() {
106 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
109 Constant::Bool(b) => {
112 Constant::Vec(ref v) |
113 Constant::Tuple(ref v) => {
116 Constant::Repeat(ref c, l) => {
124 impl PartialOrd for Constant {
125 fn partial_cmp(&self, other: &Constant) -> Option<Ordering> {
126 match (self, other) {
127 (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => {
134 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
135 (&Constant::Int(l), &Constant::Int(r)) => Some(l.cmp(&r)),
136 (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
137 match (ls.parse::<f64>(), rs.parse::<f64>()) {
138 (Ok(ref l), Ok(ref r)) => {
139 match (l.partial_cmp(r), l.is_sign_positive() == r.is_sign_positive()) {
140 // Check for comparison of -0.0 and 0.0
141 (Some(Ordering::Equal), false) => None,
148 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
149 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) |
150 (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l.partial_cmp(r),
151 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
152 match lv.partial_cmp(rv) {
153 Some(Equal) => Some(ls.cmp(rs)),
157 _ => None, //TODO: Are there any useful inter-type orderings?
162 /// parse a `LitKind` to a `Constant`
163 #[allow(cast_possible_wrap)]
164 pub fn lit_to_constant<'a, 'tcx>(lit: &LitKind, tcx: TyCtxt<'a, 'tcx, 'tcx>, mut ty: ty::Ty<'tcx>) -> Constant {
166 use syntax::ast::LitIntType::*;
167 use rustc::ty::util::IntTypeExt;
169 if let ty::TyAdt(adt, _) = ty.sty {
171 ty = adt.repr.discr_type().to_ty(tcx)
175 LitKind::Str(ref is, style) => Constant::Str(is.to_string(), style),
176 LitKind::Byte(b) => Constant::Int(ConstInt::U8(b)),
177 LitKind::ByteStr(ref s) => Constant::Binary(s.clone()),
178 LitKind::Char(c) => Constant::Char(c),
179 LitKind::Int(n, hint) => {
180 match (&ty.sty, hint) {
181 (&ty::TyInt(ity), _) |
182 (_, Signed(ity)) => {
183 Constant::Int(ConstInt::new_signed_truncating(n as i128, ity, tcx.sess.target.int_type))
185 (&ty::TyUint(uty), _) |
186 (_, Unsigned(uty)) => {
187 Constant::Int(ConstInt::new_unsigned_truncating(n as u128, uty, tcx.sess.target.uint_type))
192 LitKind::Float(ref is, ty) => Constant::Float(is.to_string(), ty.into()),
193 LitKind::FloatUnsuffixed(ref is) => Constant::Float(is.to_string(), FloatWidth::Any),
194 LitKind::Bool(b) => Constant::Bool(b),
198 fn constant_not(o: &Constant) -> Option<Constant> {
199 use self::Constant::*;
201 Bool(b) => Some(Bool(!b)),
202 Int(value) => (!value).ok().map(Int),
207 fn constant_negate(o: Constant) -> Option<Constant> {
208 use self::Constant::*;
210 Int(value) => (-value).ok().map(Int),
211 Float(is, ty) => Some(Float(neg_float_str(&is), ty)),
216 fn neg_float_str(s: &str) -> String {
217 if s.starts_with('-') {
224 pub fn constant(lcx: &LateContext, e: &Expr) -> Option<(Constant, bool)> {
225 let mut cx = ConstEvalLateContext {
228 needed_resolution: false,
230 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
233 pub fn constant_simple(lcx: &LateContext, e: &Expr) -> Option<Constant> {
234 constant(lcx, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
237 struct ConstEvalLateContext<'a, 'tcx: 'a> {
238 tcx: TyCtxt<'a, 'tcx, 'tcx>,
239 tables: &'a ty::TypeckTables<'tcx>,
240 needed_resolution: bool,
243 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
244 /// simple constant folding: Insert an expression, get a constant or none.
245 fn expr(&mut self, e: &Expr) -> Option<Constant> {
247 ExprPath(ref qpath) => self.fetch_path(qpath, e.id),
248 ExprBlock(ref block) => self.block(block),
249 ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
250 ExprLit(ref lit) => Some(lit_to_constant(&lit.node, self.tcx, self.tables.expr_ty(e))),
251 ExprArray(ref vec) => self.multi(vec).map(Constant::Vec),
252 ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
253 ExprRepeat(ref value, _) => {
254 let n = match self.tables.expr_ty(e).sty {
255 ty::TyArray(_, n) => n,
256 _ => span_bug!(e.span, "typeck error"),
258 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
260 ExprUnary(op, ref operand) => {
261 self.expr(operand).and_then(|o| match op {
262 UnNot => constant_not(&o),
263 UnNeg => constant_negate(o),
267 ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
268 // TODO: add other expressions
273 /// create `Some(Vec![..])` of all constants, unless there is any
274 /// non-constant part
275 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
277 .map(|elem| self.expr(elem))
278 .collect::<Option<_>>()
281 /// lookup a possibly constant expression from a ExprPath
282 fn fetch_path(&mut self, qpath: &QPath, id: NodeId) -> Option<Constant> {
283 let def = self.tables.qpath_def(qpath, id);
286 Def::AssociatedConst(def_id) => {
287 let substs = self.tables
288 .node_id_item_substs(id)
289 .unwrap_or_else(|| self.tcx.intern_substs(&[]));
290 if let Some((const_expr, _)) = lookup_const_by_id(self.tcx, def_id, substs) {
291 let mut cx = ConstEvalLateContext {
293 tables: self.tcx.item_tables(const_expr),
294 needed_resolution: false,
296 let body = if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
297 ty::queries::mir_const_qualif::get(self.tcx, DUMMY_SP, def_id);
298 self.tcx.hir.body(self.tcx.hir.body_owned_by(id))
300 self.tcx.sess.cstore.item_body(self.tcx, def_id)
302 let ret = cx.expr(&body.value);
304 self.needed_resolution = true;
314 /// A block can only yield a constant if it only has one constant expression
315 fn block(&mut self, block: &Block) -> Option<Constant> {
316 if block.stmts.is_empty() {
317 block.expr.as_ref().and_then(|b| self.expr(b))
323 fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
324 if let Some(Constant::Bool(b)) = self.expr(cond) {
328 otherwise.as_ref().and_then(|expr| self.expr(expr))
335 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
336 let l = if let Some(l) = self.expr(left) {
341 let r = self.expr(right);
342 match (op.node, l, r) {
343 (BiAdd, Constant::Int(l), Some(Constant::Int(r))) => (l + r).ok().map(Constant::Int),
344 (BiSub, Constant::Int(l), Some(Constant::Int(r))) => (l - r).ok().map(Constant::Int),
345 (BiMul, Constant::Int(l), Some(Constant::Int(r))) => (l * r).ok().map(Constant::Int),
346 (BiDiv, Constant::Int(l), Some(Constant::Int(r))) => (l / r).ok().map(Constant::Int),
347 (BiRem, Constant::Int(l), Some(Constant::Int(r))) => (l % r).ok().map(Constant::Int),
348 (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
349 (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
350 (BiAnd, Constant::Bool(true), Some(r)) |
351 (BiOr, Constant::Bool(false), Some(r)) => Some(r),
352 (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
353 (BiBitXor, Constant::Int(l), Some(Constant::Int(r))) => (l ^ r).ok().map(Constant::Int),
354 (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
355 (BiBitAnd, Constant::Int(l), Some(Constant::Int(r))) => (l & r).ok().map(Constant::Int),
356 (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
357 (BiBitOr, Constant::Int(l), Some(Constant::Int(r))) => (l | r).ok().map(Constant::Int),
358 (BiShl, Constant::Int(l), Some(Constant::Int(r))) => (l << r).ok().map(Constant::Int),
359 (BiShr, Constant::Int(l), Some(Constant::Int(r))) => (l >> r).ok().map(Constant::Int),
360 (BiEq, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l == r)),
361 (BiNe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l != r)),
362 (BiLt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l < r)),
363 (BiLe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l <= r)),
364 (BiGe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l >= r)),
365 (BiGt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l > r)),