]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/consts.rs
Rustup
[rust.git] / clippy_lints / src / consts.rs
1 #![allow(cast_possible_truncation)]
2 #![allow(float_cmp)]
3
4 use rustc::lint::LateContext;
5 use rustc::hir::def::Def;
6 use rustc::hir::*;
7 use rustc::ty::{self, Ty, TyCtxt, Instance};
8 use rustc::ty::subst::{Subst, Substs};
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};
15 use syntax::ptr::P;
16 use crate::utils::{sext, unsext, clip};
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) -> Self {
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),
39     /// a Binary String b"abc"
40     Binary(Rc<Vec<u8>>),
41     /// a single char 'a'
42     Char(char),
43     /// an integer's bit representation
44     Int(u128),
45     /// an f32
46     F32(f32),
47     /// an f64
48     F64(f64),
49     /// true or false
50     Bool(bool),
51     /// an array of constants
52     Vec(Vec<Constant>),
53     /// also an array, but with only one constant, repeated N times
54     Repeat(Box<Constant>, u64),
55     /// a tuple of constants
56     Tuple(Vec<Constant>),
57 }
58
59 impl PartialEq for Constant {
60     fn eq(&self, other: &Self) -> bool {
61         match (self, other) {
62             (&Constant::Str(ref ls), &Constant::Str(ref rs)) => ls == rs,
63             (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
64             (&Constant::Char(l), &Constant::Char(r)) => l == r,
65             (&Constant::Int(l), &Constant::Int(r)) => l == r,
66             (&Constant::F64(l), &Constant::F64(r)) => {
67                 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
68                 // `Fw32 == Fw64` so don’t compare them
69                 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
70                 unsafe { mem::transmute::<f64, u64>(l) == mem::transmute::<f64, u64>(r) }
71             },
72             (&Constant::F32(l), &Constant::F32(r)) => {
73                 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
74                 // `Fw32 == Fw64` so don’t compare them
75                 // mem::transmute is required to catch non-matching 0.0, -0.0, and NaNs
76                 unsafe { mem::transmute::<f64, u64>(f64::from(l)) == mem::transmute::<f64, u64>(f64::from(r)) }
77             },
78             (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
79             (&Constant::Vec(ref l), &Constant::Vec(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
80             (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
81             _ => false, // TODO: Are there inter-type equalities?
82         }
83     }
84 }
85
86 impl Hash for Constant {
87     fn hash<H>(&self, state: &mut H)
88     where
89         H: Hasher,
90     {
91         match *self {
92             Constant::Str(ref s) => {
93                 s.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.hash(state);
103             },
104             Constant::F32(f) => {
105                 unsafe { mem::transmute::<f64, u64>(f64::from(f)) }.hash(state);
106             },
107             Constant::F64(f) => {
108                 unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
109             },
110             Constant::Bool(b) => {
111                 b.hash(state);
112             },
113             Constant::Vec(ref v) | 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 Constant {
125     pub fn partial_cmp(tcx: TyCtxt, cmp_type: &ty::TypeVariants, left: &Self, right: &Self) -> Option<Ordering> {
126         match (left, right) {
127             (&Constant::Str(ref ls), &Constant::Str(ref rs)) => Some(ls.cmp(rs)),
128             (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
129             (&Constant::Int(l), &Constant::Int(r)) => {
130                 if let ty::TyInt(int_ty) = *cmp_type {
131                     Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
132                 } else {
133                     Some(l.cmp(&r))
134                 }
135             },
136             (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
137             (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
138             (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
139             (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l
140                 .iter()
141                 .zip(r.iter())
142                 .map(|(li, ri)| Constant::partial_cmp(tcx, cmp_type, li, ri))
143                 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
144                 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
145             (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
146                 match Constant::partial_cmp(tcx, cmp_type, lv, rv) {
147                     Some(Equal) => Some(ls.cmp(rs)),
148                     x => x,
149                 }
150             },
151             _ => None, // TODO: Are there any useful inter-type orderings?
152         }
153     }
154 }
155
156 /// parse a `LitKind` to a `Constant`
157 pub fn lit_to_constant<'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
158     use syntax::ast::*;
159
160     match *lit {
161         LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
162         LitKind::Byte(b) => Constant::Int(u128::from(b)),
163         LitKind::ByteStr(ref s) => Constant::Binary(Rc::clone(s)),
164         LitKind::Char(c) => Constant::Char(c),
165         LitKind::Int(n, _) => Constant::Int(n),
166         LitKind::Float(ref is, _) |
167         LitKind::FloatUnsuffixed(ref is) => match ty.sty {
168             ty::TyFloat(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
169             ty::TyFloat(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
170             _ => bug!(),
171         },
172         LitKind::Bool(b) => Constant::Bool(b),
173     }
174 }
175
176 pub fn constant<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<(Constant, bool)> {
177     let mut cx = ConstEvalLateContext {
178         tcx: lcx.tcx,
179         tables,
180         param_env: lcx.param_env,
181         needed_resolution: false,
182         substs: lcx.tcx.intern_substs(&[]),
183     };
184     cx.expr(e).map(|cst| (cst, cx.needed_resolution))
185 }
186
187 pub fn constant_simple<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<Constant> {
188     constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
189 }
190
191 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`
192 pub fn constant_context<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>) -> ConstEvalLateContext<'c, 'cc> {
193     ConstEvalLateContext {
194         tcx: lcx.tcx,
195         tables,
196         param_env: lcx.param_env,
197         needed_resolution: false,
198         substs: lcx.tcx.intern_substs(&[]),
199     }
200 }
201
202 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
203     tcx: TyCtxt<'a, 'tcx, 'tcx>,
204     tables: &'a ty::TypeckTables<'tcx>,
205     param_env: ty::ParamEnv<'tcx>,
206     needed_resolution: bool,
207     substs: &'tcx Substs<'tcx>,
208 }
209
210 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
211     /// simple constant folding: Insert an expression, get a constant or none.
212     pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
213         match e.node {
214             ExprPath(ref qpath) => self.fetch_path(qpath, e.hir_id),
215             ExprBlock(ref block, _) => self.block(block),
216             ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
217             ExprLit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
218             ExprArray(ref vec) => self.multi(vec).map(Constant::Vec),
219             ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
220             ExprRepeat(ref value, _) => {
221                 let n = match self.tables.expr_ty(e).sty {
222                     ty::TyArray(_, n) => n.assert_usize(self.tcx).expect("array length"),
223                     _ => span_bug!(e.span, "typeck error"),
224                 };
225                 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n as u64))
226             },
227             ExprUnary(op, ref operand) => self.expr(operand).and_then(|o| match op {
228                 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
229                 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
230                 UnDeref => Some(o),
231             }),
232             ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
233             // TODO: add other expressions
234             _ => None,
235         }
236     }
237
238     fn constant_not(&self, o: &Constant, ty: ty::Ty) -> Option<Constant> {
239         use self::Constant::*;
240         match *o {
241             Bool(b) => Some(Bool(!b)),
242             Int(value) => {
243                 let mut value = !value;
244                 match ty.sty {
245                     ty::TyInt(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
246                     ty::TyUint(ity) => Some(Int(clip(self.tcx, value, ity))),
247                     _ => None,
248                 }
249             },
250             _ => None,
251         }
252     }
253
254     fn constant_negate(&self, o: &Constant, ty: ty::Ty) -> Option<Constant> {
255         use self::Constant::*;
256         match *o {
257             Int(value) => {
258                 let ity = match ty.sty {
259                     ty::TyInt(ity) => ity,
260                     _ => return None,
261                 };
262                 // sign extend
263                 let value = sext(self.tcx, value, ity);
264                 let value = value.checked_neg()?;
265                 // clear unused bits
266                 Some(Int(unsext(self.tcx, value, ity)))
267             },
268             F32(f) => Some(F32(-f)),
269             F64(f) => Some(F64(-f)),
270             _ => None,
271         }
272     }
273
274     /// create `Some(Vec![..])` of all constants, unless there is any
275     /// non-constant part
276     fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
277         vec.iter()
278             .map(|elem| self.expr(elem))
279             .collect::<Option<_>>()
280     }
281
282     /// lookup a possibly constant expression from a ExprPath
283     fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
284         let def = self.tables.qpath_def(qpath, id);
285         match def {
286             Def::Const(def_id) | Def::AssociatedConst(def_id) => {
287                 let substs = self.tables.node_substs(id);
288                 let substs = if self.substs.is_empty() {
289                     substs
290                 } else {
291                     substs.subst(self.tcx, self.substs)
292                 };
293                 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
294                 let gid = GlobalId {
295                     instance,
296                     promoted: None,
297                 };
298                 use rustc::mir::interpret::GlobalId;
299                 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
300                 let ret = miri_to_const(self.tcx, result);
301                 if ret.is_some() {
302                     self.needed_resolution = true;
303                 }
304                 return ret;
305             },
306             _ => {},
307         }
308         None
309     }
310
311     /// A block can only yield a constant if it only has one constant expression
312     fn block(&mut self, block: &Block) -> Option<Constant> {
313         if block.stmts.is_empty() {
314             block.expr.as_ref().and_then(|b| self.expr(b))
315         } else {
316             None
317         }
318     }
319
320     fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
321         if let Some(Constant::Bool(b)) = self.expr(cond) {
322             if b {
323                 self.expr(&**then)
324             } else {
325                 otherwise.as_ref().and_then(|expr| self.expr(expr))
326             }
327         } else {
328             None
329         }
330     }
331
332     fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
333         let l = self.expr(left)?;
334         let r = self.expr(right);
335         match (l, r) {
336             (Constant::Int(l), Some(Constant::Int(r))) => {
337                 match self.tables.expr_ty(left).sty {
338                     ty::TyInt(ity) => {
339                         let l = sext(self.tcx, l, ity);
340                         let r = sext(self.tcx, r, ity);
341                         let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
342                         match op.node {
343                             BiAdd => l.checked_add(r).map(zext),
344                             BiSub => l.checked_sub(r).map(zext),
345                             BiMul => l.checked_mul(r).map(zext),
346                             BiDiv if r != 0 => l.checked_div(r).map(zext),
347                             BiRem if r != 0 => l.checked_rem(r).map(zext),
348                             BiShr => l.checked_shr(r as u128 as u32).map(zext),
349                             BiShl => l.checked_shl(r as u128 as u32).map(zext),
350                             BiBitXor => Some(zext(l ^ r)),
351                             BiBitOr => Some(zext(l | r)),
352                             BiBitAnd => Some(zext(l & r)),
353                             BiEq => Some(Constant::Bool(l == r)),
354                             BiNe => Some(Constant::Bool(l != r)),
355                             BiLt => Some(Constant::Bool(l < r)),
356                             BiLe => Some(Constant::Bool(l <= r)),
357                             BiGe => Some(Constant::Bool(l >= r)),
358                             BiGt => Some(Constant::Bool(l > r)),
359                             _ => None,
360                         }
361                     }
362                     ty::TyUint(_) => {
363                         match op.node {
364                             BiAdd => l.checked_add(r).map(Constant::Int),
365                             BiSub => l.checked_sub(r).map(Constant::Int),
366                             BiMul => l.checked_mul(r).map(Constant::Int),
367                             BiDiv => l.checked_div(r).map(Constant::Int),
368                             BiRem => l.checked_rem(r).map(Constant::Int),
369                             BiShr => l.checked_shr(r as u32).map(Constant::Int),
370                             BiShl => l.checked_shl(r as u32).map(Constant::Int),
371                             BiBitXor => Some(Constant::Int(l ^ r)),
372                             BiBitOr => Some(Constant::Int(l | r)),
373                             BiBitAnd => Some(Constant::Int(l & r)),
374                             BiEq => Some(Constant::Bool(l == r)),
375                             BiNe => Some(Constant::Bool(l != r)),
376                             BiLt => Some(Constant::Bool(l < r)),
377                             BiLe => Some(Constant::Bool(l <= r)),
378                             BiGe => Some(Constant::Bool(l >= r)),
379                             BiGt => Some(Constant::Bool(l > r)),
380                             _ => None,
381                         }
382                     },
383                     _ => None,
384                 }
385             },
386             (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
387                 BiAdd => Some(Constant::F32(l + r)),
388                 BiSub => Some(Constant::F32(l - r)),
389                 BiMul => Some(Constant::F32(l * r)),
390                 BiDiv => Some(Constant::F32(l / r)),
391                 BiRem => Some(Constant::F32(l % r)),
392                 BiEq => Some(Constant::Bool(l == r)),
393                 BiNe => Some(Constant::Bool(l != r)),
394                 BiLt => Some(Constant::Bool(l < r)),
395                 BiLe => Some(Constant::Bool(l <= r)),
396                 BiGe => Some(Constant::Bool(l >= r)),
397                 BiGt => Some(Constant::Bool(l > r)),
398                 _ => None,
399             },
400             (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
401                 BiAdd => Some(Constant::F64(l + r)),
402                 BiSub => Some(Constant::F64(l - r)),
403                 BiMul => Some(Constant::F64(l * r)),
404                 BiDiv => Some(Constant::F64(l / r)),
405                 BiRem => Some(Constant::F64(l % r)),
406                 BiEq => Some(Constant::Bool(l == r)),
407                 BiNe => Some(Constant::Bool(l != r)),
408                 BiLt => Some(Constant::Bool(l < r)),
409                 BiLe => Some(Constant::Bool(l <= r)),
410                 BiGe => Some(Constant::Bool(l >= r)),
411                 BiGt => Some(Constant::Bool(l > r)),
412                 _ => None,
413             },
414             (l, r) => match (op.node, l, r) {
415                 (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
416                 (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
417                 (BiAnd, Constant::Bool(true), Some(r)) | (BiOr, Constant::Bool(false), Some(r)) => Some(r),
418                 (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
419                 (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
420                 (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
421                 _ => None,
422             },
423         }
424     }
425 }
426
427 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
428     use rustc::mir::interpret::{Scalar, ConstValue};
429     match result.val {
430         ConstValue::Scalar(Scalar::Bits{ bits: b, ..}) => match result.ty.sty {
431             ty::TyBool => Some(Constant::Bool(b == 1)),
432             ty::TyUint(_) | ty::TyInt(_) => Some(Constant::Int(b)),
433             ty::TyFloat(FloatTy::F32) => Some(Constant::F32(f32::from_bits(b as u32))),
434             ty::TyFloat(FloatTy::F64) => Some(Constant::F64(f64::from_bits(b as u64))),
435             // FIXME: implement other conversion
436             _ => None,
437         },
438         ConstValue::ScalarPair(Scalar::Ptr(ptr), Scalar::Bits { bits: n, .. }) => match result.ty.sty {
439             ty::TyRef(_, tam, _) => match tam.sty {
440                 ty::TyStr => {
441                     let alloc = tcx
442                         .alloc_map
443                         .lock()
444                         .unwrap_memory(ptr.alloc_id);
445                     let offset = ptr.offset.bytes() as usize;
446                     let n = n as usize;
447                     String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned()).ok().map(Constant::Str)
448                 },
449                 _ => None,
450             },
451             _ => None,
452         }
453         // FIXME: implement other conversions
454         _ => None,
455     }
456 }