]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/consts.rs
Merge pull request #1823 from eddyb/nightly-magic
[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::{self, TyCtxt, Ty};
9 use rustc::ty::subst::{Substs, Subst};
10 use std::cmp::Ordering::{self, Equal};
11 use std::cmp::PartialOrd;
12 use std::hash::{Hash, Hasher};
13 use std::mem;
14 use std::rc::Rc;
15 use syntax::ast::{FloatTy, LitKind, StrStyle, NodeId};
16 use syntax::ptr::P;
17
18 #[derive(Debug, Copy, Clone)]
19 pub enum FloatWidth {
20     F32,
21     F64,
22     Any,
23 }
24
25 impl From<FloatTy> for FloatWidth {
26     fn from(ty: FloatTy) -> FloatWidth {
27         match ty {
28             FloatTy::F32 => FloatWidth::F32,
29             FloatTy::F64 => FloatWidth::F64,
30         }
31     }
32 }
33
34 /// A `LitKind`-like enum to fold constant `Expr`s into.
35 #[derive(Debug, Clone)]
36 pub enum Constant {
37     /// a String "abc"
38     Str(String, StrStyle),
39     /// a Binary String b"abc"
40     Binary(Rc<Vec<u8>>),
41     /// a single char 'a'
42     Char(char),
43     /// an integer, third argument is whether the value is negated
44     Int(ConstInt),
45     /// a float with given type
46     Float(String, FloatWidth),
47     /// true or false
48     Bool(bool),
49     /// an array of constants
50     Vec(Vec<Constant>),
51     /// also an array, but with only one constant, repeated N times
52     Repeat(Box<Constant>, usize),
53     /// a tuple of constants
54     Tuple(Vec<Constant>),
55 }
56
57 impl PartialEq for Constant {
58     fn eq(&self, other: &Constant) -> bool {
59         match (self, other) {
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()
65             },
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) },
72                     _ => false,
73                 }
74             },
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?
80         }
81     }
82 }
83
84 impl Hash for Constant {
85     fn hash<H>(&self, state: &mut H)
86         where H: Hasher
87     {
88         match *self {
89             Constant::Str(ref s, ref k) => {
90                 s.hash(state);
91                 k.hash(state);
92             },
93             Constant::Binary(ref b) => {
94                 b.hash(state);
95             },
96             Constant::Char(c) => {
97                 c.hash(state);
98             },
99             Constant::Int(i) => {
100                 i.to_u128_unchecked().hash(state);
101                 i.is_negative().hash(state);
102             },
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);
107                 }
108             },
109             Constant::Bool(b) => {
110                 b.hash(state);
111             },
112             Constant::Vec(ref v) |
113             Constant::Tuple(ref v) => {
114                 v.hash(state);
115             },
116             Constant::Repeat(ref c, l) => {
117                 c.hash(state);
118                 l.hash(state);
119             },
120         }
121     }
122 }
123
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)) => {
128                 if l_sty == r_sty {
129                     Some(ls.cmp(rs))
130                 } else {
131                     None
132                 }
133             },
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,
142                             (x, _) => x,
143                         }
144                     },
145                     _ => None,
146                 }
147             },
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)),
154                     x => x,
155                 }
156             },
157             _ => None, //TODO: Are there any useful inter-type orderings?
158         }
159     }
160 }
161
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<'tcx>) -> Constant {
165     use syntax::ast::*;
166     use syntax::ast::LitIntType::*;
167     use rustc::ty::util::IntTypeExt;
168
169     if let ty::TyAdt(adt, _) = ty.sty {
170         if adt.is_enum() {
171             ty = adt.repr.discr_type().to_ty(tcx)
172         }
173     }
174     match *lit {
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))
184                 },
185                 (&ty::TyUint(uty), _) |
186                 (_, Unsigned(uty)) => {
187                     Constant::Int(ConstInt::new_unsigned_truncating(n as u128, uty, tcx.sess.target.uint_type))
188                 },
189                 _ => bug!(),
190             }
191         },
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),
195     }
196 }
197
198 fn constant_not(o: &Constant) -> Option<Constant> {
199     use self::Constant::*;
200     match *o {
201         Bool(b) => Some(Bool(!b)),
202         Int(value) => (!value).ok().map(Int),
203         _ => None,
204     }
205 }
206
207 fn constant_negate(o: Constant) -> Option<Constant> {
208     use self::Constant::*;
209     match o {
210         Int(value) => (-value).ok().map(Int),
211         Float(is, ty) => Some(Float(neg_float_str(&is), ty)),
212         _ => None,
213     }
214 }
215
216 fn neg_float_str(s: &str) -> String {
217     if s.starts_with('-') {
218         s[1..].to_owned()
219     } else {
220         format!("-{}", s)
221     }
222 }
223
224 pub fn constant(lcx: &LateContext, e: &Expr) -> Option<(Constant, bool)> {
225     let mut cx = ConstEvalLateContext {
226         tcx: lcx.tcx,
227         tables: lcx.tables,
228         needed_resolution: false,
229         substs: lcx.tcx.intern_substs(&[]),
230     };
231     cx.expr(e).map(|cst| (cst, cx.needed_resolution))
232 }
233
234 pub fn constant_simple(lcx: &LateContext, e: &Expr) -> Option<Constant> {
235     constant(lcx, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
236 }
237
238 struct ConstEvalLateContext<'a, 'tcx: 'a> {
239     tcx: TyCtxt<'a, 'tcx, 'tcx>,
240     tables: &'a ty::TypeckTables<'tcx>,
241     needed_resolution: bool,
242     substs: &'tcx Substs<'tcx>,
243 }
244
245 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
246     /// simple constant folding: Insert an expression, get a constant or none.
247     fn expr(&mut self, e: &Expr) -> Option<Constant> {
248         match e.node {
249             ExprPath(ref qpath) => self.fetch_path(qpath, e.id),
250             ExprBlock(ref block) => self.block(block),
251             ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
252             ExprLit(ref lit) => Some(lit_to_constant(&lit.node, self.tcx, self.tables.expr_ty(e))),
253             ExprArray(ref vec) => self.multi(vec).map(Constant::Vec),
254             ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
255             ExprRepeat(ref value, _) => {
256                 let n = match self.tables.expr_ty(e).sty {
257                     ty::TyArray(_, n) => n,
258                     _ => span_bug!(e.span, "typeck error"),
259                 };
260                 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
261             },
262             ExprUnary(op, ref operand) => {
263                 self.expr(operand).and_then(|o| match op {
264                     UnNot => constant_not(&o),
265                     UnNeg => constant_negate(o),
266                     UnDeref => Some(o),
267                 })
268             },
269             ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
270             // TODO: add other expressions
271             _ => None,
272         }
273     }
274
275     /// create `Some(Vec![..])` of all constants, unless there is any
276     /// non-constant part
277     fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
278         vec.iter()
279             .map(|elem| self.expr(elem))
280             .collect::<Option<_>>()
281     }
282
283     /// lookup a possibly constant expression from a ExprPath
284     fn fetch_path(&mut self, qpath: &QPath, id: NodeId) -> Option<Constant> {
285         let def = self.tables.qpath_def(qpath, id);
286         match def {
287             Def::Const(def_id) |
288             Def::AssociatedConst(def_id) => {
289                 let substs = self.tables.node_substs(id);
290                 let substs = if self.substs.is_empty() {
291                     substs
292                 } else {
293                     substs.subst(self.tcx, self.substs)
294                 };
295                 if let Some((def_id, substs)) = lookup_const_by_id(self.tcx, def_id, substs) {
296                     let mut cx = ConstEvalLateContext {
297                         tcx: self.tcx,
298                         tables: self.tcx.typeck_tables_of(def_id),
299                         needed_resolution: false,
300                         substs: substs,
301                     };
302                     let body = if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
303                         self.tcx.mir_const_qualif(def_id);
304                         self.tcx.hir.body(self.tcx.hir.body_owned_by(id))
305                     } else {
306                         self.tcx.sess.cstore.item_body(self.tcx, def_id)
307                     };
308                     let ret = cx.expr(&body.value);
309                     if ret.is_some() {
310                         self.needed_resolution = true;
311                     }
312                     return ret;
313                 }
314             },
315             _ => {},
316         }
317         None
318     }
319
320     /// A block can only yield a constant if it only has one constant expression
321     fn block(&mut self, block: &Block) -> Option<Constant> {
322         if block.stmts.is_empty() {
323             block.expr.as_ref().and_then(|b| self.expr(b))
324         } else {
325             None
326         }
327     }
328
329     fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
330         if let Some(Constant::Bool(b)) = self.expr(cond) {
331             if b {
332                 self.expr(&**then)
333             } else {
334                 otherwise.as_ref().and_then(|expr| self.expr(expr))
335             }
336         } else {
337             None
338         }
339     }
340
341     fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
342         let l = if let Some(l) = self.expr(left) {
343             l
344         } else {
345             return None;
346         };
347         let r = self.expr(right);
348         match (op.node, l, r) {
349             (BiAdd, Constant::Int(l), Some(Constant::Int(r))) => (l + r).ok().map(Constant::Int),
350             (BiSub, Constant::Int(l), Some(Constant::Int(r))) => (l - r).ok().map(Constant::Int),
351             (BiMul, Constant::Int(l), Some(Constant::Int(r))) => (l * r).ok().map(Constant::Int),
352             (BiDiv, Constant::Int(l), Some(Constant::Int(r))) => (l / r).ok().map(Constant::Int),
353             (BiRem, Constant::Int(l), Some(Constant::Int(r))) => (l % r).ok().map(Constant::Int),
354             (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
355             (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
356             (BiAnd, Constant::Bool(true), Some(r)) |
357             (BiOr, Constant::Bool(false), Some(r)) => Some(r),
358             (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
359             (BiBitXor, Constant::Int(l), Some(Constant::Int(r))) => (l ^ r).ok().map(Constant::Int),
360             (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
361             (BiBitAnd, Constant::Int(l), Some(Constant::Int(r))) => (l & r).ok().map(Constant::Int),
362             (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
363             (BiBitOr, Constant::Int(l), Some(Constant::Int(r))) => (l | r).ok().map(Constant::Int),
364             (BiShl, Constant::Int(l), Some(Constant::Int(r))) => (l << r).ok().map(Constant::Int),
365             (BiShr, Constant::Int(l), Some(Constant::Int(r))) => (l >> r).ok().map(Constant::Int),
366             (BiEq, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l == r)),
367             (BiNe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l != r)),
368             (BiLt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l < r)),
369             (BiLe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l <= r)),
370             (BiGe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l >= r)),
371             (BiGt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l > r)),
372             _ => None,
373         }
374     }
375 }