]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/consts.rs
Merge pull request #1564 from Manishearth/cleanup
[rust.git] / clippy_lints / src / consts.rs
1 #![allow(cast_possible_truncation)]
2
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, ConstUsize, ConstIsize};
7 use rustc::hir::*;
8 use std::cmp::Ordering::{self, Equal};
9 use std::cmp::PartialOrd;
10 use std::hash::{Hash, Hasher};
11 use std::mem;
12 use std::rc::Rc;
13 use syntax::ast::{FloatTy, LitIntType, LitKind, StrStyle, UintTy, IntTy, NodeId};
14 use syntax::ptr::P;
15
16 #[derive(Debug, Copy, Clone)]
17 pub enum FloatWidth {
18     F32,
19     F64,
20     Any,
21 }
22
23 impl From<FloatTy> for FloatWidth {
24     fn from(ty: FloatTy) -> FloatWidth {
25         match ty {
26             FloatTy::F32 => FloatWidth::F32,
27             FloatTy::F64 => FloatWidth::F64,
28         }
29     }
30 }
31
32 /// A `LitKind`-like enum to fold constant `Expr`s into.
33 #[derive(Debug, Clone)]
34 pub enum Constant {
35     /// a String "abc"
36     Str(String, StrStyle),
37     /// a Binary String b"abc"
38     Binary(Rc<Vec<u8>>),
39     /// a single char 'a'
40     Char(char),
41     /// an integer, third argument is whether the value is negated
42     Int(ConstInt),
43     /// a float with given type
44     Float(String, FloatWidth),
45     /// true or false
46     Bool(bool),
47     /// an array of constants
48     Vec(Vec<Constant>),
49     /// also an array, but with only one constant, repeated N times
50     Repeat(Box<Constant>, usize),
51     /// a tuple of constants
52     Tuple(Vec<Constant>),
53 }
54
55 impl Constant {
56     /// Convert to `u64` if possible.
57     ///
58     /// # panics
59     ///
60     /// If the constant could not be converted to `u64` losslessly.
61     fn as_u64(&self) -> u64 {
62         if let Constant::Int(val) = *self {
63             val.to_u64().expect("negative constant can't be casted to `u64`")
64         } else {
65             panic!("Could not convert a `{:?}` to `u64`", self);
66         }
67     }
68 }
69
70 impl PartialEq for Constant {
71     fn eq(&self, other: &Constant) -> bool {
72         match (self, other) {
73             (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => ls == rs && l_sty == r_sty,
74             (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
75             (&Constant::Char(l), &Constant::Char(r)) => l == r,
76             (&Constant::Int(l), &Constant::Int(r)) => {
77                 l.is_negative() == r.is_negative() && l.to_u128_unchecked() == r.to_u128_unchecked()
78             },
79             (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
80                 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
81                 // `Fw32 == Fw64` so don’t compare them
82                 match (ls.parse::<f64>(), rs.parse::<f64>()) {
83                     // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
84                     (Ok(l), Ok(r)) => unsafe { mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r) },
85                     _ => false,
86                 }
87             },
88             (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
89             (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l == r,
90             (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
91             (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
92             _ => false, //TODO: Are there inter-type equalities?
93         }
94     }
95 }
96
97 impl Hash for Constant {
98     fn hash<H>(&self, state: &mut H)
99         where H: Hasher
100     {
101         match *self {
102             Constant::Str(ref s, ref k) => {
103                 s.hash(state);
104                 k.hash(state);
105             },
106             Constant::Binary(ref b) => {
107                 b.hash(state);
108             },
109             Constant::Char(c) => {
110                 c.hash(state);
111             },
112             Constant::Int(i) => {
113                 i.to_u128_unchecked().hash(state);
114                 i.is_negative().hash(state);
115             },
116             Constant::Float(ref f, _) => {
117                 // don’t use the width here because of PartialEq implementation
118                 if let Ok(f) = f.parse::<f64>() {
119                     unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
120                 }
121             },
122             Constant::Bool(b) => {
123                 b.hash(state);
124             },
125             Constant::Vec(ref v) |
126             Constant::Tuple(ref v) => {
127                 v.hash(state);
128             },
129             Constant::Repeat(ref c, l) => {
130                 c.hash(state);
131                 l.hash(state);
132             },
133         }
134     }
135 }
136
137 impl PartialOrd for Constant {
138     fn partial_cmp(&self, other: &Constant) -> Option<Ordering> {
139         match (self, other) {
140             (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => {
141                 if l_sty == r_sty {
142                     Some(ls.cmp(rs))
143                 } else {
144                     None
145                 }
146             },
147             (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
148             (&Constant::Int(l), &Constant::Int(r)) => Some(l.cmp(&r)),
149             (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
150                 match (ls.parse::<f64>(), rs.parse::<f64>()) {
151                     (Ok(ref l), Ok(ref r)) => {
152                         match (l.partial_cmp(r), l.is_sign_positive() == r.is_sign_positive()) {
153                             // Check for comparison of -0.0 and 0.0
154                             (Some(Ordering::Equal), false) => None,
155                             (x, _) => x,
156                         }
157                     },
158                     _ => None,
159                 }
160             },
161             (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
162             (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) |
163             (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l.partial_cmp(r),
164             (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
165                 match lv.partial_cmp(rv) {
166                     Some(Equal) => Some(ls.cmp(rs)),
167                     x => x,
168                 }
169             },
170             _ => None, //TODO: Are there any useful inter-type orderings?
171         }
172     }
173 }
174
175 /// parse a `LitKind` to a `Constant`
176 #[allow(cast_possible_wrap)]
177 pub fn lit_to_constant(lit: &LitKind) -> Constant {
178     match *lit {
179         LitKind::Str(ref is, style) => Constant::Str(is.to_string(), style),
180         LitKind::Byte(b) => Constant::Int(ConstInt::U8(b)),
181         LitKind::ByteStr(ref s) => Constant::Binary(s.clone()),
182         LitKind::Char(c) => Constant::Char(c),
183         LitKind::Int(value, LitIntType::Unsuffixed) => Constant::Int(ConstInt::Infer(value)),
184         LitKind::Int(value, LitIntType::Unsigned(UintTy::U8)) => Constant::Int(ConstInt::U8(value as u8)),
185         LitKind::Int(value, LitIntType::Unsigned(UintTy::U16)) => Constant::Int(ConstInt::U16(value as u16)),
186         LitKind::Int(value, LitIntType::Unsigned(UintTy::U32)) => Constant::Int(ConstInt::U32(value as u32)),
187         LitKind::Int(value, LitIntType::Unsigned(UintTy::U64)) => Constant::Int(ConstInt::U64(value as u64)),
188         LitKind::Int(value, LitIntType::Unsigned(UintTy::U128)) => Constant::Int(ConstInt::U128(value as u128)),
189         LitKind::Int(value, LitIntType::Unsigned(UintTy::Us)) => {
190             Constant::Int(ConstInt::Usize(ConstUsize::Us32(value as u32)))
191         },
192         LitKind::Int(value, LitIntType::Signed(IntTy::I8)) => Constant::Int(ConstInt::I8(value as i8)),
193         LitKind::Int(value, LitIntType::Signed(IntTy::I16)) => Constant::Int(ConstInt::I16(value as i16)),
194         LitKind::Int(value, LitIntType::Signed(IntTy::I32)) => Constant::Int(ConstInt::I32(value as i32)),
195         LitKind::Int(value, LitIntType::Signed(IntTy::I64)) => Constant::Int(ConstInt::I64(value as i64)),
196         LitKind::Int(value, LitIntType::Signed(IntTy::I128)) => Constant::Int(ConstInt::I128(value as i128)),
197         LitKind::Int(value, LitIntType::Signed(IntTy::Is)) => {
198             Constant::Int(ConstInt::Isize(ConstIsize::Is32(value as i32)))
199         },
200         LitKind::Float(ref is, ty) => Constant::Float(is.to_string(), ty.into()),
201         LitKind::FloatUnsuffixed(ref is) => Constant::Float(is.to_string(), FloatWidth::Any),
202         LitKind::Bool(b) => Constant::Bool(b),
203     }
204 }
205
206 fn constant_not(o: &Constant) -> Option<Constant> {
207     use self::Constant::*;
208     match *o {
209         Bool(b) => Some(Bool(!b)),
210         Int(value) => (!value).ok().map(Int),
211         _ => None,
212     }
213 }
214
215 fn constant_negate(o: Constant) -> Option<Constant> {
216     use self::Constant::*;
217     match o {
218         Int(value) => (-value).ok().map(Int),
219         Float(is, ty) => Some(Float(neg_float_str(&is), ty)),
220         _ => None,
221     }
222 }
223
224 fn neg_float_str(s: &str) -> String {
225     if s.starts_with('-') {
226         s[1..].to_owned()
227     } else {
228         format!("-{}", s)
229     }
230 }
231
232 pub fn constant(lcx: &LateContext, e: &Expr) -> Option<(Constant, bool)> {
233     let mut cx = ConstEvalLateContext {
234         lcx: Some(lcx),
235         needed_resolution: false,
236     };
237     cx.expr(e).map(|cst| (cst, cx.needed_resolution))
238 }
239
240 pub fn constant_simple(e: &Expr) -> Option<Constant> {
241     let mut cx = ConstEvalLateContext {
242         lcx: None,
243         needed_resolution: false,
244     };
245     cx.expr(e)
246 }
247
248 struct ConstEvalLateContext<'c, 'cc: 'c> {
249     lcx: Option<&'c LateContext<'c, 'cc>>,
250     needed_resolution: bool,
251 }
252
253 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
254     /// simple constant folding: Insert an expression, get a constant or none.
255     fn expr(&mut self, e: &Expr) -> Option<Constant> {
256         match e.node {
257             ExprPath(ref qpath) => self.fetch_path(qpath, e.id),
258             ExprBlock(ref block) => self.block(block),
259             ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
260             ExprLit(ref lit) => Some(lit_to_constant(&lit.node)),
261             ExprArray(ref vec) => self.multi(vec).map(Constant::Vec),
262             ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
263             ExprRepeat(ref value, number_id) => {
264                 if let Some(lcx) = self.lcx {
265                     self.binop_apply(value,
266                                      &lcx.tcx.hir.body(number_id).value,
267                                      |v, n| Some(Constant::Repeat(Box::new(v), n.as_u64() as usize)))
268                 } else {
269                     None
270                 }
271             },
272             ExprUnary(op, ref operand) => {
273                 self.expr(operand).and_then(|o| match op {
274                     UnNot => constant_not(&o),
275                     UnNeg => constant_negate(o),
276                     UnDeref => Some(o),
277                 })
278             },
279             ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
280             // TODO: add other expressions
281             _ => None,
282         }
283     }
284
285     /// create `Some(Vec![..])` of all constants, unless there is any
286     /// non-constant part
287     fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
288         vec.iter()
289             .map(|elem| self.expr(elem))
290             .collect::<Option<_>>()
291     }
292
293     /// lookup a possibly constant expression from a ExprPath
294     fn fetch_path(&mut self, qpath: &QPath, id: NodeId) -> Option<Constant> {
295         if let Some(lcx) = self.lcx {
296             let def = lcx.tables.qpath_def(qpath, id);
297             match def {
298                 Def::Const(def_id) |
299                 Def::AssociatedConst(def_id) => {
300                     let substs = Some(lcx.tables
301                         .node_id_item_substs(id)
302                         .unwrap_or_else(|| lcx.tcx.intern_substs(&[])));
303                     if let Some((const_expr, _tab, _ty)) = lookup_const_by_id(lcx.tcx, def_id, substs) {
304                         let ret = self.expr(const_expr);
305                         if ret.is_some() {
306                             self.needed_resolution = true;
307                         }
308                         return ret;
309                     }
310                 },
311                 _ => {},
312             }
313         }
314         None
315     }
316
317     /// A block can only yield a constant if it only has one constant expression
318     fn block(&mut self, block: &Block) -> Option<Constant> {
319         if block.stmts.is_empty() {
320             block.expr.as_ref().and_then(|b| self.expr(b))
321         } else {
322             None
323         }
324     }
325
326     fn ifthenelse(&mut self, cond: &Expr, then: &Block, otherwise: &Option<P<Expr>>) -> Option<Constant> {
327         if let Some(Constant::Bool(b)) = self.expr(cond) {
328             if b {
329                 self.block(then)
330             } else {
331                 otherwise.as_ref().and_then(|expr| self.expr(expr))
332             }
333         } else {
334             None
335         }
336     }
337
338     fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
339         let l = if let Some(l) = self.expr(left) {
340             l
341         } else {
342             return None;
343         };
344         let r = self.expr(right);
345         match (op.node, l, r) {
346             (BiAdd, Constant::Int(l), Some(Constant::Int(r))) => (l + r).ok().map(Constant::Int),
347             (BiSub, Constant::Int(l), Some(Constant::Int(r))) => (l - r).ok().map(Constant::Int),
348             (BiMul, Constant::Int(l), Some(Constant::Int(r))) => (l * r).ok().map(Constant::Int),
349             (BiDiv, Constant::Int(l), Some(Constant::Int(r))) => (l / r).ok().map(Constant::Int),
350             (BiRem, Constant::Int(l), Some(Constant::Int(r))) => (l % r).ok().map(Constant::Int),
351             (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
352             (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
353             (BiAnd, Constant::Bool(true), Some(r)) |
354             (BiOr, Constant::Bool(false), Some(r)) => Some(r),
355             (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
356             (BiBitXor, Constant::Int(l), Some(Constant::Int(r))) => (l ^ r).ok().map(Constant::Int),
357             (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
358             (BiBitAnd, Constant::Int(l), Some(Constant::Int(r))) => (l & r).ok().map(Constant::Int),
359             (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
360             (BiBitOr, Constant::Int(l), Some(Constant::Int(r))) => (l | r).ok().map(Constant::Int),
361             (BiShl, Constant::Int(l), Some(Constant::Int(r))) => (l << r).ok().map(Constant::Int),
362             (BiShr, Constant::Int(l), Some(Constant::Int(r))) => (l >> r).ok().map(Constant::Int),
363             (BiEq, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l == r)),
364             (BiNe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l != r)),
365             (BiLt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l < r)),
366             (BiLe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l <= r)),
367             (BiGe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l >= r)),
368             (BiGt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l > r)),
369             _ => None,
370         }
371     }
372
373
374     fn binop_apply<F>(&mut self, left: &Expr, right: &Expr, op: F) -> Option<Constant>
375         where F: Fn(Constant, Constant) -> Option<Constant>
376     {
377         if let (Some(lc), Some(rc)) = (self.expr(left), self.expr(right)) {
378             op(lc, rc)
379         } else {
380             None
381         }
382     }
383 }