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::{TyCtxt, self};
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};
17 #[derive(Debug, Copy, Clone)]
24 impl From<FloatTy> for FloatWidth {
25 fn from(ty: FloatTy) -> FloatWidth {
27 FloatTy::F32 => FloatWidth::F32,
28 FloatTy::F64 => FloatWidth::F64,
33 /// A `LitKind`-like enum to fold constant `Expr`s into.
34 #[derive(Debug, Clone)]
37 Str(String, StrStyle),
38 /// a Binary String b"abc"
42 /// an integer, third argument is whether the value is negated
44 /// a float with given type
45 Float(String, FloatWidth),
48 /// an array of constants
50 /// also an array, but with only one constant, repeated N times
51 Repeat(Box<Constant>, usize),
52 /// a tuple of constants
57 /// Convert to `u64` if possible.
61 /// If the constant could not be converted to `u64` losslessly.
62 fn as_u64(&self) -> u64 {
63 if let Constant::Int(val) = *self {
64 val.to_u64().expect("negative constant can't be casted to `u64`")
66 panic!("Could not convert a `{:?}` to `u64`", self);
71 impl PartialEq for Constant {
72 fn eq(&self, other: &Constant) -> bool {
74 (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => ls == rs && l_sty == r_sty,
75 (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
76 (&Constant::Char(l), &Constant::Char(r)) => l == r,
77 (&Constant::Int(l), &Constant::Int(r)) => {
78 l.is_negative() == r.is_negative() && l.to_u128_unchecked() == r.to_u128_unchecked()
80 (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
81 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
82 // `Fw32 == Fw64` so don’t compare them
83 match (ls.parse::<f64>(), rs.parse::<f64>()) {
84 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
85 (Ok(l), Ok(r)) => unsafe { mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r) },
89 (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
90 (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l == r,
91 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
92 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
93 _ => false, //TODO: Are there inter-type equalities?
98 impl Hash for Constant {
99 fn hash<H>(&self, state: &mut H)
103 Constant::Str(ref s, ref k) => {
107 Constant::Binary(ref b) => {
110 Constant::Char(c) => {
113 Constant::Int(i) => {
114 i.to_u128_unchecked().hash(state);
115 i.is_negative().hash(state);
117 Constant::Float(ref f, _) => {
118 // don’t use the width here because of PartialEq implementation
119 if let Ok(f) = f.parse::<f64>() {
120 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
123 Constant::Bool(b) => {
126 Constant::Vec(ref v) |
127 Constant::Tuple(ref v) => {
130 Constant::Repeat(ref c, l) => {
138 impl PartialOrd for Constant {
139 fn partial_cmp(&self, other: &Constant) -> Option<Ordering> {
140 match (self, other) {
141 (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => {
148 (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
149 (&Constant::Int(l), &Constant::Int(r)) => Some(l.cmp(&r)),
150 (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
151 match (ls.parse::<f64>(), rs.parse::<f64>()) {
152 (Ok(ref l), Ok(ref r)) => {
153 match (l.partial_cmp(r), l.is_sign_positive() == r.is_sign_positive()) {
154 // Check for comparison of -0.0 and 0.0
155 (Some(Ordering::Equal), false) => None,
162 (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
163 (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) |
164 (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l.partial_cmp(r),
165 (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
166 match lv.partial_cmp(rv) {
167 Some(Equal) => Some(ls.cmp(rs)),
171 _ => None, //TODO: Are there any useful inter-type orderings?
176 /// parse a `LitKind` to a `Constant`
177 #[allow(cast_possible_wrap)]
178 pub fn lit_to_constant<'a, 'tcx>(lit: &LitKind, tcx: TyCtxt<'a, 'tcx, 'tcx>, mut ty: ty::Ty<'tcx>) -> Constant {
180 use syntax::ast::LitIntType::*;
181 use rustc::ty::util::IntTypeExt;
183 if let ty::TyAdt(adt, _) = ty.sty {
185 ty = adt.repr.discr_type().to_ty(tcx)
189 LitKind::Str(ref is, style) => Constant::Str(is.to_string(), style),
190 LitKind::Byte(b) => Constant::Int(ConstInt::U8(b)),
191 LitKind::ByteStr(ref s) => Constant::Binary(s.clone()),
192 LitKind::Char(c) => Constant::Char(c),
193 LitKind::Int(n, hint) => {
194 match (&ty.sty, hint) {
195 (&ty::TyInt(ity), _) |
196 (_, Signed(ity)) => {
197 Constant::Int(ConstInt::new_signed_truncating(n as i128,
198 ity, tcx.sess.target.int_type))
200 (&ty::TyUint(uty), _) |
201 (_, Unsigned(uty)) => {
202 Constant::Int(ConstInt::new_unsigned_truncating(n as u128,
203 uty, tcx.sess.target.uint_type))
208 LitKind::Float(ref is, ty) => Constant::Float(is.to_string(), ty.into()),
209 LitKind::FloatUnsuffixed(ref is) => Constant::Float(is.to_string(), FloatWidth::Any),
210 LitKind::Bool(b) => Constant::Bool(b),
214 fn constant_not(o: &Constant) -> Option<Constant> {
215 use self::Constant::*;
217 Bool(b) => Some(Bool(!b)),
218 Int(value) => (!value).ok().map(Int),
223 fn constant_negate(o: Constant) -> Option<Constant> {
224 use self::Constant::*;
226 Int(value) => (-value).ok().map(Int),
227 Float(is, ty) => Some(Float(neg_float_str(&is), ty)),
232 fn neg_float_str(s: &str) -> String {
233 if s.starts_with('-') {
240 pub fn constant(lcx: &LateContext, e: &Expr) -> Option<(Constant, bool)> {
241 let mut cx = ConstEvalLateContext {
244 needed_resolution: false,
246 cx.expr(e).map(|cst| (cst, cx.needed_resolution))
249 pub fn constant_simple(lcx: &LateContext, e: &Expr) -> Option<Constant> {
250 constant(lcx, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
253 struct ConstEvalLateContext<'a, 'tcx: 'a> {
254 tcx: TyCtxt<'a, 'tcx, 'tcx>,
255 tables: &'a ty::TypeckTables<'tcx>,
256 needed_resolution: bool,
259 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
260 /// simple constant folding: Insert an expression, get a constant or none.
261 fn expr(&mut self, e: &Expr) -> Option<Constant> {
263 ExprPath(ref qpath) => self.fetch_path(qpath, e.id),
264 ExprBlock(ref block) => self.block(block),
265 ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
266 ExprLit(ref lit) => Some(lit_to_constant(&lit.node, self.tcx, self.tables.expr_ty(e))),
267 ExprArray(ref vec) => self.multi(vec).map(Constant::Vec),
268 ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
269 ExprRepeat(ref value, number_id) => {
270 let val = &self.tcx.hir.body(number_id).value;
271 self.binop_apply(value,
273 |v, n| Some(Constant::Repeat(Box::new(v), n.as_u64() as usize)))
275 ExprUnary(op, ref operand) => {
276 self.expr(operand).and_then(|o| match op {
277 UnNot => constant_not(&o),
278 UnNeg => constant_negate(o),
282 ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
283 // TODO: add other expressions
288 /// create `Some(Vec![..])` of all constants, unless there is any
289 /// non-constant part
290 fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
292 .map(|elem| self.expr(elem))
293 .collect::<Option<_>>()
296 /// lookup a possibly constant expression from a ExprPath
297 fn fetch_path(&mut self, qpath: &QPath, id: NodeId) -> Option<Constant> {
298 let def = self.tables.qpath_def(qpath, id);
301 Def::AssociatedConst(def_id) => {
302 let substs = self.tables
303 .node_id_item_substs(id)
304 .unwrap_or_else(|| self.tcx.intern_substs(&[]));
305 if let Some((const_expr, tables)) = lookup_const_by_id(self.tcx, def_id, substs) {
306 let mut cx = ConstEvalLateContext {
309 needed_resolution: false,
311 let ret = cx.expr(const_expr);
313 self.needed_resolution = true;
323 /// A block can only yield a constant if it only has one constant expression
324 fn block(&mut self, block: &Block) -> Option<Constant> {
325 if block.stmts.is_empty() {
326 block.expr.as_ref().and_then(|b| self.expr(b))
332 fn ifthenelse(&mut self, cond: &Expr, then: &Block, otherwise: &Option<P<Expr>>) -> Option<Constant> {
333 if let Some(Constant::Bool(b)) = self.expr(cond) {
337 otherwise.as_ref().and_then(|expr| self.expr(expr))
344 fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
345 let l = if let Some(l) = self.expr(left) {
350 let r = self.expr(right);
351 match (op.node, l, r) {
352 (BiAdd, Constant::Int(l), Some(Constant::Int(r))) => (l + r).ok().map(Constant::Int),
353 (BiSub, Constant::Int(l), Some(Constant::Int(r))) => (l - r).ok().map(Constant::Int),
354 (BiMul, Constant::Int(l), Some(Constant::Int(r))) => (l * r).ok().map(Constant::Int),
355 (BiDiv, Constant::Int(l), Some(Constant::Int(r))) => (l / r).ok().map(Constant::Int),
356 (BiRem, Constant::Int(l), Some(Constant::Int(r))) => (l % r).ok().map(Constant::Int),
357 (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
358 (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
359 (BiAnd, Constant::Bool(true), Some(r)) |
360 (BiOr, Constant::Bool(false), Some(r)) => Some(r),
361 (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
362 (BiBitXor, Constant::Int(l), Some(Constant::Int(r))) => (l ^ r).ok().map(Constant::Int),
363 (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
364 (BiBitAnd, Constant::Int(l), Some(Constant::Int(r))) => (l & r).ok().map(Constant::Int),
365 (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
366 (BiBitOr, Constant::Int(l), Some(Constant::Int(r))) => (l | r).ok().map(Constant::Int),
367 (BiShl, Constant::Int(l), Some(Constant::Int(r))) => (l << r).ok().map(Constant::Int),
368 (BiShr, Constant::Int(l), Some(Constant::Int(r))) => (l >> r).ok().map(Constant::Int),
369 (BiEq, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l == r)),
370 (BiNe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l != r)),
371 (BiLt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l < r)),
372 (BiLe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l <= r)),
373 (BiGe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l >= r)),
374 (BiGt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l > r)),
380 fn binop_apply<F>(&mut self, left: &Expr, right: &Expr, op: F) -> Option<Constant>
381 where F: Fn(Constant, Constant) -> Option<Constant>
383 if let (Some(lc), Some(rc)) = (self.expr(left), self.expr(right)) {