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