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