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