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