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