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