]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/consts.rs
Fix ICE for issue 2594
[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 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 PartialOrd for Constant {
126     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
127         match (self, other) {
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)) => Some(l.cmp(&r)),
131             (&Constant::F64(l), &Constant::F64(r)) => l.partial_cmp(&r),
132             (&Constant::F32(l), &Constant::F32(r)) => l.partial_cmp(&r),
133             (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
134             (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => {
135                 l.partial_cmp(r)
136             },
137             (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => match lv.partial_cmp(rv) {
138                 Some(Equal) => Some(ls.cmp(rs)),
139                 x => x,
140             },
141             _ => None, // TODO: Are there any useful inter-type orderings?
142         }
143     }
144 }
145
146 /// parse a `LitKind` to a `Constant`
147 pub fn lit_to_constant<'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
148     use syntax::ast::*;
149
150     match *lit {
151         LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
152         LitKind::Byte(b) => Constant::Int(u128::from(b)),
153         LitKind::ByteStr(ref s) => Constant::Binary(Rc::clone(s)),
154         LitKind::Char(c) => Constant::Char(c),
155         LitKind::Int(n, _) => Constant::Int(n),
156         LitKind::Float(ref is, _) |
157         LitKind::FloatUnsuffixed(ref is) => match ty.sty {
158             ty::TyFloat(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
159             ty::TyFloat(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
160             _ => bug!(),
161         },
162         LitKind::Bool(b) => Constant::Bool(b),
163     }
164 }
165
166 pub fn constant<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<(Constant, bool)> {
167     let mut cx = ConstEvalLateContext {
168         tcx: lcx.tcx,
169         tables,
170         param_env: lcx.param_env,
171         needed_resolution: false,
172         substs: lcx.tcx.intern_substs(&[]),
173     };
174     cx.expr(e).map(|cst| (cst, cx.needed_resolution))
175 }
176
177 pub fn constant_simple<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>, e: &Expr) -> Option<Constant> {
178     constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
179 }
180
181 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`
182 pub fn constant_context<'c, 'cc>(lcx: &LateContext<'c, 'cc>, tables: &'c ty::TypeckTables<'cc>) -> ConstEvalLateContext<'c, 'cc> {
183     ConstEvalLateContext {
184         tcx: lcx.tcx,
185         tables,
186         param_env: lcx.param_env,
187         needed_resolution: false,
188         substs: lcx.tcx.intern_substs(&[]),
189     }
190 }
191
192 pub struct ConstEvalLateContext<'a, 'tcx: 'a> {
193     tcx: TyCtxt<'a, 'tcx, 'tcx>,
194     tables: &'a ty::TypeckTables<'tcx>,
195     param_env: ty::ParamEnv<'tcx>,
196     needed_resolution: bool,
197     substs: &'tcx Substs<'tcx>,
198 }
199
200 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
201     /// simple constant folding: Insert an expression, get a constant or none.
202     pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
203         match e.node {
204             ExprPath(ref qpath) => self.fetch_path(qpath, e.hir_id),
205             ExprBlock(ref block, _) => self.block(block),
206             ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
207             ExprLit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
208             ExprArray(ref vec) => self.multi(vec).map(Constant::Vec),
209             ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
210             ExprRepeat(ref value, _) => {
211                 let n = match self.tables.expr_ty(e).sty {
212                     ty::TyArray(_, n) => n.assert_usize(self.tcx).expect("array length"),
213                     _ => span_bug!(e.span, "typeck error"),
214                 };
215                 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n as u64))
216             },
217             ExprUnary(op, ref operand) => self.expr(operand).and_then(|o| match op {
218                 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
219                 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
220                 UnDeref => Some(o),
221             }),
222             ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
223             // TODO: add other expressions
224             _ => None,
225         }
226     }
227
228     fn constant_not(&self, o: &Constant, ty: ty::Ty) -> Option<Constant> {
229         use self::Constant::*;
230         match *o {
231             Bool(b) => Some(Bool(!b)),
232             Int(value) => {
233                 let mut value = !value;
234                 match ty.sty {
235                     ty::TyInt(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
236                     ty::TyUint(ity) => Some(Int(clip(self.tcx, value, ity))),
237                     _ => None,
238                 }
239             },
240             _ => None,
241         }
242     }
243
244     fn constant_negate(&self, o: &Constant, ty: ty::Ty) -> Option<Constant> {
245         use self::Constant::*;
246         match *o {
247             Int(value) => {
248                 let ity = match ty.sty {
249                     ty::TyInt(ity) => ity,
250                     _ => return None,
251                 };
252                 // sign extend
253                 let value = sext(self.tcx, value, ity);
254                 let value = value.checked_neg()?;
255                 // clear unused bits
256                 Some(Int(unsext(self.tcx, value, ity)))
257             },
258             F32(f) => Some(F32(-f)),
259             F64(f) => Some(F64(-f)),
260             _ => None,
261         }
262     }
263
264     /// create `Some(Vec![..])` of all constants, unless there is any
265     /// non-constant part
266     fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
267         vec.iter()
268             .map(|elem| self.expr(elem))
269             .collect::<Option<_>>()
270     }
271
272     /// lookup a possibly constant expression from a ExprPath
273     fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
274         let def = self.tables.qpath_def(qpath, id);
275         match def {
276             Def::Const(def_id) | Def::AssociatedConst(def_id) => {
277                 let substs = self.tables.node_substs(id);
278                 let substs = if self.substs.is_empty() {
279                     substs
280                 } else {
281                     substs.subst(self.tcx, self.substs)
282                 };
283                 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs)?;
284                 let gid = GlobalId {
285                     instance,
286                     promoted: None,
287                 };
288                 use rustc::mir::interpret::GlobalId;
289                 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
290                 let ret = miri_to_const(self.tcx, result);
291                 if ret.is_some() {
292                     self.needed_resolution = true;
293                 }
294                 return ret;
295             },
296             _ => {},
297         }
298         None
299     }
300
301     /// A block can only yield a constant if it only has one constant expression
302     fn block(&mut self, block: &Block) -> Option<Constant> {
303         if block.stmts.is_empty() {
304             block.expr.as_ref().and_then(|b| self.expr(b))
305         } else {
306             None
307         }
308     }
309
310     fn ifthenelse(&mut self, cond: &Expr, then: &P<Expr>, otherwise: &Option<P<Expr>>) -> Option<Constant> {
311         if let Some(Constant::Bool(b)) = self.expr(cond) {
312             if b {
313                 self.expr(&**then)
314             } else {
315                 otherwise.as_ref().and_then(|expr| self.expr(expr))
316             }
317         } else {
318             None
319         }
320     }
321
322     fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
323         let l = self.expr(left)?;
324         let r = self.expr(right);
325         match (l, r) {
326             (Constant::Int(l), Some(Constant::Int(r))) => {
327                 match self.tables.expr_ty(left).sty {
328                     ty::TyInt(ity) => {
329                         let l = sext(self.tcx, l, ity);
330                         let r = sext(self.tcx, r, ity);
331                         let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
332                         match op.node {
333                             BiAdd => l.checked_add(r).map(zext),
334                             BiSub => l.checked_sub(r).map(zext),
335                             BiMul => l.checked_mul(r).map(zext),
336                             BiDiv if r != 0 => l.checked_div(r).map(zext),
337                             BiRem if r != 0 => l.checked_rem(r).map(zext),
338                             BiShr => l.checked_shr(r as u128 as u32).map(zext),
339                             BiShl => l.checked_shl(r as u128 as u32).map(zext),
340                             BiBitXor => Some(zext(l ^ r)),
341                             BiBitOr => Some(zext(l | r)),
342                             BiBitAnd => Some(zext(l & r)),
343                             BiEq => Some(Constant::Bool(l == r)),
344                             BiNe => Some(Constant::Bool(l != r)),
345                             BiLt => Some(Constant::Bool(l < r)),
346                             BiLe => Some(Constant::Bool(l <= r)),
347                             BiGe => Some(Constant::Bool(l >= r)),
348                             BiGt => Some(Constant::Bool(l > r)),
349                             _ => None,
350                         }
351                     }
352                     ty::TyUint(_) => {
353                         match op.node {
354                             BiAdd => l.checked_add(r).map(Constant::Int),
355                             BiSub => l.checked_sub(r).map(Constant::Int),
356                             BiMul => l.checked_mul(r).map(Constant::Int),
357                             BiDiv => l.checked_div(r).map(Constant::Int),
358                             BiRem => l.checked_rem(r).map(Constant::Int),
359                             BiShr => l.checked_shr(r as u32).map(Constant::Int),
360                             BiShl => l.checked_shl(r as u32).map(Constant::Int),
361                             BiBitXor => Some(Constant::Int(l ^ r)),
362                             BiBitOr => Some(Constant::Int(l | r)),
363                             BiBitAnd => Some(Constant::Int(l & r)),
364                             BiEq => Some(Constant::Bool(l == r)),
365                             BiNe => Some(Constant::Bool(l != r)),
366                             BiLt => Some(Constant::Bool(l < r)),
367                             BiLe => Some(Constant::Bool(l <= r)),
368                             BiGe => Some(Constant::Bool(l >= r)),
369                             BiGt => Some(Constant::Bool(l > r)),
370                             _ => None,
371                         }
372                     },
373                     _ => None,
374                 }
375             },
376             (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
377                 BiAdd => Some(Constant::F32(l + r)),
378                 BiSub => Some(Constant::F32(l - r)),
379                 BiMul => Some(Constant::F32(l * r)),
380                 BiDiv => Some(Constant::F32(l / r)),
381                 BiRem => Some(Constant::F32(l % r)),
382                 BiEq => Some(Constant::Bool(l == r)),
383                 BiNe => Some(Constant::Bool(l != r)),
384                 BiLt => Some(Constant::Bool(l < r)),
385                 BiLe => Some(Constant::Bool(l <= r)),
386                 BiGe => Some(Constant::Bool(l >= r)),
387                 BiGt => Some(Constant::Bool(l > r)),
388                 _ => None,
389             },
390             (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
391                 BiAdd => Some(Constant::F64(l + r)),
392                 BiSub => Some(Constant::F64(l - r)),
393                 BiMul => Some(Constant::F64(l * r)),
394                 BiDiv => Some(Constant::F64(l / r)),
395                 BiRem => Some(Constant::F64(l % r)),
396                 BiEq => Some(Constant::Bool(l == r)),
397                 BiNe => Some(Constant::Bool(l != r)),
398                 BiLt => Some(Constant::Bool(l < r)),
399                 BiLe => Some(Constant::Bool(l <= r)),
400                 BiGe => Some(Constant::Bool(l >= r)),
401                 BiGt => Some(Constant::Bool(l > r)),
402                 _ => None,
403             },
404             (l, r) => match (op.node, l, r) {
405                 (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
406                 (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
407                 (BiAnd, Constant::Bool(true), Some(r)) | (BiOr, Constant::Bool(false), Some(r)) => Some(r),
408                 (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
409                 (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
410                 (BiBitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
411                 _ => None,
412             },
413         }
414     }
415 }
416
417 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
418     use rustc::mir::interpret::{PrimVal, ConstValue};
419     match result.val {
420         ConstVal::Value(ConstValue::ByVal(PrimVal::Bytes(b))) => match result.ty.sty {
421             ty::TyBool => Some(Constant::Bool(b == 1)),
422             ty::TyUint(_) | ty::TyInt(_) => Some(Constant::Int(b)),
423             ty::TyFloat(FloatTy::F32) => Some(Constant::F32(f32::from_bits(b as u32))),
424             ty::TyFloat(FloatTy::F64) => Some(Constant::F64(f64::from_bits(b as u64))),
425             // FIXME: implement other conversion
426             _ => None,
427         },
428         ConstVal::Value(ConstValue::ByValPair(PrimVal::Ptr(ptr), PrimVal::Bytes(n))) => match result.ty.sty {
429             ty::TyRef(_, tam, _) => match tam.sty {
430                 ty::TyStr => {
431                     let alloc = tcx
432                         .interpret_interner
433                         .get_alloc(ptr.alloc_id)
434                         .unwrap();
435                     let offset = ptr.offset as usize;
436                     let n = n as usize;
437                     String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned()).ok().map(Constant::Str)
438                 },
439                 _ => None,
440             },
441             _ => None,
442         }
443         // FIXME: implement other conversions
444         _ => None,
445     }
446 }