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