]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/consts.rs
Rustfmt
[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
87         H: Hasher,
88     {
89         match *self {
90             Constant::Str(ref s, ref k) => {
91                 s.hash(state);
92                 k.hash(state);
93             },
94             Constant::Binary(ref b) => {
95                 b.hash(state);
96             },
97             Constant::Char(c) => {
98                 c.hash(state);
99             },
100             Constant::Int(i) => {
101                 i.to_u128_unchecked().hash(state);
102                 i.is_negative().hash(state);
103             },
104             Constant::Float(ref f, _) => {
105                 // don’t use the width here because of PartialEq implementation
106                 if let Ok(f) = f.parse::<f64>() {
107                     unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
108                 }
109             },
110             Constant::Bool(b) => {
111                 b.hash(state);
112             },
113             Constant::Vec(ref v) |
114             Constant::Tuple(ref v) => {
115                 v.hash(state);
116             },
117             Constant::Repeat(ref c, l) => {
118                 c.hash(state);
119                 l.hash(state);
120             },
121         }
122     }
123 }
124
125 impl PartialOrd for Constant {
126     fn partial_cmp(&self, other: &Constant) -> Option<Ordering> {
127         match (self, other) {
128             (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => {
129                 if l_sty == r_sty {
130                     Some(ls.cmp(rs))
131                 } else {
132                     None
133                 }
134             },
135             (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
136             (&Constant::Int(l), &Constant::Int(r)) => Some(l.cmp(&r)),
137             (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
138                 match (ls.parse::<f64>(), rs.parse::<f64>()) {
139                     (Ok(ref l), Ok(ref r)) => {
140                         match (l.partial_cmp(r), l.is_sign_positive() == r.is_sign_positive()) {
141                             // Check for comparison of -0.0 and 0.0
142                             (Some(Ordering::Equal), false) => None,
143                             (x, _) => x,
144                         }
145                     },
146                     _ => None,
147                 }
148             },
149             (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
150             (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) |
151             (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l.partial_cmp(r),
152             (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
153                 match lv.partial_cmp(rv) {
154                     Some(Equal) => Some(ls.cmp(rs)),
155                     x => x,
156                 }
157             },
158             _ => None, //TODO: Are there any useful inter-type orderings?
159         }
160     }
161 }
162
163 /// parse a `LitKind` to a `Constant`
164 #[allow(cast_possible_wrap)]
165 pub fn lit_to_constant<'a, 'tcx>(lit: &LitKind, tcx: TyCtxt<'a, 'tcx, 'tcx>, mut ty: Ty<'tcx>) -> Constant {
166     use syntax::ast::*;
167     use syntax::ast::LitIntType::*;
168     use rustc::ty::util::IntTypeExt;
169
170     if let ty::TyAdt(adt, _) = ty.sty {
171         if adt.is_enum() {
172             ty = adt.repr.discr_type().to_ty(tcx)
173         }
174     }
175     match *lit {
176         LitKind::Str(ref is, style) => Constant::Str(is.to_string(), style),
177         LitKind::Byte(b) => Constant::Int(ConstInt::U8(b)),
178         LitKind::ByteStr(ref s) => Constant::Binary(s.clone()),
179         LitKind::Char(c) => Constant::Char(c),
180         LitKind::Int(n, hint) => {
181             match (&ty.sty, hint) {
182                 (&ty::TyInt(ity), _) |
183                 (_, Signed(ity)) => {
184                     Constant::Int(ConstInt::new_signed_truncating(n as i128, ity, tcx.sess.target.int_type))
185                 },
186                 (&ty::TyUint(uty), _) |
187                 (_, Unsigned(uty)) => {
188                     Constant::Int(ConstInt::new_unsigned_truncating(n as u128, uty, tcx.sess.target.uint_type))
189                 },
190                 _ => bug!(),
191             }
192         },
193         LitKind::Float(ref is, ty) => Constant::Float(is.to_string(), ty.into()),
194         LitKind::FloatUnsuffixed(ref is) => Constant::Float(is.to_string(), FloatWidth::Any),
195         LitKind::Bool(b) => Constant::Bool(b),
196     }
197 }
198
199 fn constant_not(o: &Constant) -> Option<Constant> {
200     use self::Constant::*;
201     match *o {
202         Bool(b) => Some(Bool(!b)),
203         Int(value) => (!value).ok().map(Int),
204         _ => None,
205     }
206 }
207
208 fn constant_negate(o: Constant) -> Option<Constant> {
209     use self::Constant::*;
210     match o {
211         Int(value) => (-value).ok().map(Int),
212         Float(is, ty) => Some(Float(neg_float_str(&is), ty)),
213         _ => None,
214     }
215 }
216
217 fn neg_float_str(s: &str) -> String {
218     if s.starts_with('-') {
219         s[1..].to_owned()
220     } else {
221         format!("-{}", s)
222     }
223 }
224
225 pub fn constant(lcx: &LateContext, e: &Expr) -> Option<(Constant, bool)> {
226     let mut cx = ConstEvalLateContext {
227         tcx: lcx.tcx,
228         tables: lcx.tables,
229         param_env: lcx.param_env,
230         needed_resolution: false,
231         substs: lcx.tcx.intern_substs(&[]),
232     };
233     cx.expr(e).map(|cst| (cst, cx.needed_resolution))
234 }
235
236 pub fn constant_simple(lcx: &LateContext, e: &Expr) -> Option<Constant> {
237     constant(lcx, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
238 }
239
240 struct ConstEvalLateContext<'a, 'tcx: 'a> {
241     tcx: TyCtxt<'a, 'tcx, 'tcx>,
242     tables: &'a ty::TypeckTables<'tcx>,
243     param_env: ty::ParamEnv<'tcx>,
244     needed_resolution: bool,
245     substs: &'tcx Substs<'tcx>,
246 }
247
248 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
249     /// simple constant folding: Insert an expression, get a constant or none.
250     fn expr(&mut self, e: &Expr) -> Option<Constant> {
251         match e.node {
252             ExprPath(ref qpath) => self.fetch_path(qpath, e.id),
253             ExprBlock(ref block) => self.block(block),
254             ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
255             ExprLit(ref lit) => Some(lit_to_constant(&lit.node, self.tcx, self.tables.expr_ty(e))),
256             ExprArray(ref vec) => self.multi(vec).map(Constant::Vec),
257             ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
258             ExprRepeat(ref value, _) => {
259                 let n = match self.tables.expr_ty(e).sty {
260                     ty::TyArray(_, n) => n,
261                     _ => span_bug!(e.span, "typeck error"),
262                 };
263                 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
264             },
265             ExprUnary(op, ref operand) => {
266                 self.expr(operand).and_then(|o| match op {
267                     UnNot => constant_not(&o),
268                     UnNeg => constant_negate(o),
269                     UnDeref => Some(o),
270                 })
271             },
272             ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
273             // TODO: add other expressions
274             _ => None,
275         }
276     }
277
278     /// create `Some(Vec![..])` of all constants, unless there is any
279     /// non-constant part
280     fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
281         vec.iter()
282             .map(|elem| self.expr(elem))
283             .collect::<Option<_>>()
284     }
285
286     /// lookup a possibly constant expression from a ExprPath
287     fn fetch_path(&mut self, qpath: &QPath, id: NodeId) -> Option<Constant> {
288         let def = self.tables.qpath_def(qpath, id);
289         match def {
290             Def::Const(def_id) |
291             Def::AssociatedConst(def_id) => {
292                 let substs = self.tables.node_substs(id);
293                 let substs = if self.substs.is_empty() {
294                     substs
295                 } else {
296                     substs.subst(self.tcx, self.substs)
297                 };
298                 let param_env = self.param_env.and((def_id, substs));
299                 if let Some((def_id, substs)) = lookup_const_by_id(self.tcx, param_env) {
300                     let mut cx = ConstEvalLateContext {
301                         tcx: self.tcx,
302                         tables: self.tcx.typeck_tables_of(def_id),
303                         needed_resolution: false,
304                         substs: substs,
305                         param_env: param_env.param_env,
306                     };
307                     let body = if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
308                         self.tcx.mir_const_qualif(def_id);
309                         self.tcx.hir.body(self.tcx.hir.body_owned_by(id))
310                     } else {
311                         self.tcx.sess.cstore.item_body(self.tcx, def_id)
312                     };
313                     let ret = cx.expr(&body.value);
314                     if ret.is_some() {
315                         self.needed_resolution = true;
316                     }
317                     return ret;
318                 }
319             },
320             _ => {},
321         }
322         None
323     }
324
325     /// A block can only yield a constant if it only has one constant expression
326     fn block(&mut self, block: &Block) -> Option<Constant> {
327         if block.stmts.is_empty() {
328             block.expr.as_ref().and_then(|b| self.expr(b))
329         } else {
330             None
331         }
332     }
333
334     fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
335         if let Some(Constant::Bool(b)) = self.expr(cond) {
336             if b {
337                 self.expr(&**then)
338             } else {
339                 otherwise.as_ref().and_then(|expr| self.expr(expr))
340             }
341         } else {
342             None
343         }
344     }
345
346     fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
347         let l = if let Some(l) = self.expr(left) {
348             l
349         } else {
350             return None;
351         };
352         let r = self.expr(right);
353         match (op.node, l, r) {
354             (BiAdd, Constant::Int(l), Some(Constant::Int(r))) => (l + r).ok().map(Constant::Int),
355             (BiSub, Constant::Int(l), Some(Constant::Int(r))) => (l - r).ok().map(Constant::Int),
356             (BiMul, Constant::Int(l), Some(Constant::Int(r))) => (l * r).ok().map(Constant::Int),
357             (BiDiv, Constant::Int(l), Some(Constant::Int(r))) => (l / r).ok().map(Constant::Int),
358             (BiRem, Constant::Int(l), Some(Constant::Int(r))) => (l % r).ok().map(Constant::Int),
359             (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
360             (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
361             (BiAnd, Constant::Bool(true), Some(r)) |
362             (BiOr, Constant::Bool(false), Some(r)) => Some(r),
363             (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
364             (BiBitXor, Constant::Int(l), Some(Constant::Int(r))) => (l ^ r).ok().map(Constant::Int),
365             (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
366             (BiBitAnd, Constant::Int(l), Some(Constant::Int(r))) => (l & r).ok().map(Constant::Int),
367             (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
368             (BiBitOr, Constant::Int(l), Some(Constant::Int(r))) => (l | r).ok().map(Constant::Int),
369             (BiShl, Constant::Int(l), Some(Constant::Int(r))) => (l << r).ok().map(Constant::Int),
370             (BiShr, Constant::Int(l), Some(Constant::Int(r))) => (l >> r).ok().map(Constant::Int),
371             (BiEq, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l == r)),
372             (BiNe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l != r)),
373             (BiLt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l < r)),
374             (BiLe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l <= r)),
375             (BiGe, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l >= r)),
376             (BiGt, Constant::Int(l), Some(Constant::Int(r))) => Some(Constant::Bool(l > r)),
377             _ => None,
378         }
379     }
380 }