]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/consts.rs
Merge pull request #1584 from ensch/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;
5 use rustc_const_eval::lookup_const_by_id;
6 use rustc_const_math::ConstInt;
7 use rustc::hir::*;
8 use rustc::ty::{TyCtxt, self};
9 use std::cmp::Ordering::{self, Equal};
10 use std::cmp::PartialOrd;
11 use std::hash::{Hash, Hasher};
12 use std::mem;
13 use std::rc::Rc;
14 use syntax::ast::{FloatTy, LitKind, StrStyle, NodeId};
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_u128_unchecked() == r.to_u128_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 { mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r) },
86                     _ => false,
87                 }
88             },
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?
94         }
95     }
96 }
97
98 impl Hash for Constant {
99     fn hash<H>(&self, state: &mut H)
100         where H: Hasher
101     {
102         match *self {
103             Constant::Str(ref s, ref k) => {
104                 s.hash(state);
105                 k.hash(state);
106             },
107             Constant::Binary(ref b) => {
108                 b.hash(state);
109             },
110             Constant::Char(c) => {
111                 c.hash(state);
112             },
113             Constant::Int(i) => {
114                 i.to_u128_unchecked().hash(state);
115                 i.is_negative().hash(state);
116             },
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);
121                 }
122             },
123             Constant::Bool(b) => {
124                 b.hash(state);
125             },
126             Constant::Vec(ref v) |
127             Constant::Tuple(ref v) => {
128                 v.hash(state);
129             },
130             Constant::Repeat(ref c, l) => {
131                 c.hash(state);
132                 l.hash(state);
133             },
134         }
135     }
136 }
137
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)) => {
142                 if l_sty == r_sty {
143                     Some(ls.cmp(rs))
144                 } else {
145                     None
146                 }
147             },
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,
156                             (x, _) => x,
157                         }
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<'a, 'tcx>(lit: &LitKind, tcx: TyCtxt<'a, 'tcx, 'tcx>, mut ty: ty::Ty<'tcx>) -> Constant {
179     use syntax::ast::*;
180     use syntax::ast::LitIntType::*;
181     use rustc::ty::util::IntTypeExt;
182
183     if let ty::TyAdt(adt, _) = ty.sty {
184         if adt.is_enum() {
185             ty = adt.repr.discr_type().to_ty(tcx)
186         }
187     }
188     match *lit {
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))
199                 }
200                 (&ty::TyUint(uty), _) |
201                 (_, Unsigned(uty)) => {
202                     Constant::Int(ConstInt::new_unsigned_truncating(n as u128,
203                         uty, tcx.sess.target.uint_type))
204                 }
205                 _ => bug!()
206             }
207         }
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),
211     }
212 }
213
214 fn constant_not(o: &Constant) -> Option<Constant> {
215     use self::Constant::*;
216     match *o {
217         Bool(b) => Some(Bool(!b)),
218         Int(value) => (!value).ok().map(Int),
219         _ => None,
220     }
221 }
222
223 fn constant_negate(o: Constant) -> Option<Constant> {
224     use self::Constant::*;
225     match o {
226         Int(value) => (-value).ok().map(Int),
227         Float(is, ty) => Some(Float(neg_float_str(&is), ty)),
228         _ => None,
229     }
230 }
231
232 fn neg_float_str(s: &str) -> String {
233     if s.starts_with('-') {
234         s[1..].to_owned()
235     } else {
236         format!("-{}", s)
237     }
238 }
239
240 pub fn constant(lcx: &LateContext, e: &Expr) -> Option<(Constant, bool)> {
241     let mut cx = ConstEvalLateContext {
242         tcx: lcx.tcx,
243         tables: lcx.tables,
244         needed_resolution: false,
245     };
246     cx.expr(e).map(|cst| (cst, cx.needed_resolution))
247 }
248
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) })
251 }
252
253 struct ConstEvalLateContext<'a, 'tcx: 'a> {
254     tcx: TyCtxt<'a, 'tcx, 'tcx>,
255     tables: &'a ty::TypeckTables<'tcx>,
256     needed_resolution: bool,
257 }
258
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> {
262         match e.node {
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,
272                                  val,
273                                  |v, n| Some(Constant::Repeat(Box::new(v), n.as_u64() as usize)))
274             },
275             ExprUnary(op, ref operand) => {
276                 self.expr(operand).and_then(|o| match op {
277                     UnNot => constant_not(&o),
278                     UnNeg => constant_negate(o),
279                     UnDeref => Some(o),
280                 })
281             },
282             ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
283             // TODO: add other expressions
284             _ => None,
285         }
286     }
287
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>> {
291         vec.iter()
292             .map(|elem| self.expr(elem))
293             .collect::<Option<_>>()
294     }
295
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);
299         match def {
300             Def::Const(def_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 {
307                         tcx: self.tcx,
308                         tables,
309                         needed_resolution: false,
310                     };
311                     let ret = cx.expr(const_expr);
312                     if ret.is_some() {
313                         self.needed_resolution = true;
314                     }
315                     return ret;
316                 }
317             },
318             _ => {},
319         }
320         None
321     }
322
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))
327         } else {
328             None
329         }
330     }
331
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) {
334             if b {
335                 self.block(then)
336             } else {
337                 otherwise.as_ref().and_then(|expr| self.expr(expr))
338             }
339         } else {
340             None
341         }
342     }
343
344     fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
345         let l = if let Some(l) = self.expr(left) {
346             l
347         } else {
348             return None;
349         };
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)),
375             _ => None,
376         }
377     }
378
379
380     fn binop_apply<F>(&mut self, left: &Expr, right: &Expr, op: F) -> Option<Constant>
381         where F: Fn(Constant, Constant) -> Option<Constant>
382     {
383         if let (Some(lc), Some(rc)) = (self.expr(left), self.expr(right)) {
384             op(lc, rc)
385         } else {
386             None
387         }
388     }
389 }