]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/consts.rs
Auto merge of #4809 - iankronquist:patch-1, r=flip1995
[rust.git] / clippy_lints / src / consts.rs
1 #![allow(clippy::float_cmp)]
2
3 use crate::utils::{clip, higher, sext, unsext};
4 use if_chain::if_chain;
5 use rustc::ty::subst::{Subst, SubstsRef};
6 use rustc::ty::{self, Ty, TyCtxt};
7 use rustc::{bug, span_bug};
8 use rustc_data_structures::sync::Lrc;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::*;
11 use rustc_lint::LateContext;
12 use rustc_span::symbol::Symbol;
13 use std::cmp::Ordering::{self, Equal};
14 use std::cmp::PartialOrd;
15 use std::convert::TryInto;
16 use std::hash::{Hash, Hasher};
17 use syntax::ast::{FloatTy, LitKind};
18
19 /// A `LitKind`-like enum to fold constant `Expr`s into.
20 #[derive(Debug, Clone)]
21 pub enum Constant {
22     /// A `String` (e.g., "abc").
23     Str(String),
24     /// A binary string (e.g., `b"abc"`).
25     Binary(Lrc<Vec<u8>>),
26     /// A single `char` (e.g., `'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     /// A raw pointer.
43     RawPtr(u128),
44     /// A literal with syntax error.
45     Err(Symbol),
46 }
47
48 impl PartialEq for Constant {
49     fn eq(&self, other: &Self) -> bool {
50         match (self, other) {
51             (&Self::Str(ref ls), &Self::Str(ref rs)) => ls == rs,
52             (&Self::Binary(ref l), &Self::Binary(ref r)) => l == r,
53             (&Self::Char(l), &Self::Char(r)) => l == r,
54             (&Self::Int(l), &Self::Int(r)) => l == r,
55             (&Self::F64(l), &Self::F64(r)) => {
56                 // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have
57                 // `Fw32 == Fw64`, so don’t compare them.
58                 // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs.
59                 l.to_bits() == r.to_bits()
60             },
61             (&Self::F32(l), &Self::F32(r)) => {
62                 // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have
63                 // `Fw32 == Fw64`, so don’t compare them.
64                 // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs.
65                 f64::from(l).to_bits() == f64::from(r).to_bits()
66             },
67             (&Self::Bool(l), &Self::Bool(r)) => l == r,
68             (&Self::Vec(ref l), &Self::Vec(ref r)) | (&Self::Tuple(ref l), &Self::Tuple(ref r)) => l == r,
69             (&Self::Repeat(ref lv, ref ls), &Self::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
70             // TODO: are there inter-type equalities?
71             _ => false,
72         }
73     }
74 }
75
76 impl Hash for Constant {
77     fn hash<H>(&self, state: &mut H)
78     where
79         H: Hasher,
80     {
81         std::mem::discriminant(self).hash(state);
82         match *self {
83             Self::Str(ref s) => {
84                 s.hash(state);
85             },
86             Self::Binary(ref b) => {
87                 b.hash(state);
88             },
89             Self::Char(c) => {
90                 c.hash(state);
91             },
92             Self::Int(i) => {
93                 i.hash(state);
94             },
95             Self::F32(f) => {
96                 f64::from(f).to_bits().hash(state);
97             },
98             Self::F64(f) => {
99                 f.to_bits().hash(state);
100             },
101             Self::Bool(b) => {
102                 b.hash(state);
103             },
104             Self::Vec(ref v) | Self::Tuple(ref v) => {
105                 v.hash(state);
106             },
107             Self::Repeat(ref c, l) => {
108                 c.hash(state);
109                 l.hash(state);
110             },
111             Self::RawPtr(u) => {
112                 u.hash(state);
113             },
114             Self::Err(ref s) => {
115                 s.hash(state);
116             },
117         }
118     }
119 }
120
121 impl Constant {
122     pub fn partial_cmp(tcx: TyCtxt<'_>, cmp_type: Ty<'_>, left: &Self, right: &Self) -> Option<Ordering> {
123         match (left, right) {
124             (&Self::Str(ref ls), &Self::Str(ref rs)) => Some(ls.cmp(rs)),
125             (&Self::Char(ref l), &Self::Char(ref r)) => Some(l.cmp(r)),
126             (&Self::Int(l), &Self::Int(r)) => {
127                 if let ty::Int(int_ty) = cmp_type.kind {
128                     Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
129                 } else {
130                     Some(l.cmp(&r))
131                 }
132             },
133             (&Self::F64(l), &Self::F64(r)) => l.partial_cmp(&r),
134             (&Self::F32(l), &Self::F32(r)) => l.partial_cmp(&r),
135             (&Self::Bool(ref l), &Self::Bool(ref r)) => Some(l.cmp(r)),
136             (&Self::Tuple(ref l), &Self::Tuple(ref r)) | (&Self::Vec(ref l), &Self::Vec(ref r)) => l
137                 .iter()
138                 .zip(r.iter())
139                 .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
140                 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
141                 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
142             (&Self::Repeat(ref lv, ref ls), &Self::Repeat(ref rv, ref rs)) => {
143                 match Self::partial_cmp(tcx, cmp_type, lv, rv) {
144                     Some(Equal) => Some(ls.cmp(rs)),
145                     x => x,
146                 }
147             },
148             // TODO: are there any useful inter-type orderings?
149             _ => None,
150         }
151     }
152 }
153
154 /// Parses a `LitKind` to a `Constant`.
155 pub fn lit_to_constant(lit: &LitKind, ty: Option<Ty<'_>>) -> Constant {
156     use syntax::ast::*;
157
158     match *lit {
159         LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
160         LitKind::Byte(b) => Constant::Int(u128::from(b)),
161         LitKind::ByteStr(ref s) => Constant::Binary(Lrc::clone(s)),
162         LitKind::Char(c) => Constant::Char(c),
163         LitKind::Int(n, _) => Constant::Int(n),
164         LitKind::Float(ref is, LitFloatType::Suffixed(fty)) => match fty {
165             FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()),
166             FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()),
167         },
168         LitKind::Float(ref is, LitFloatType::Unsuffixed) => match ty.expect("type of float is known").kind {
169             ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
170             ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
171             _ => bug!(),
172         },
173         LitKind::Bool(b) => Constant::Bool(b),
174         LitKind::Err(s) => Constant::Err(s),
175     }
176 }
177
178 pub fn constant<'c, 'cc>(
179     lcx: &LateContext<'c, 'cc>,
180     tables: &'c ty::TypeckTables<'cc>,
181     e: &Expr<'_>,
182 ) -> Option<(Constant, bool)> {
183     let mut cx = ConstEvalLateContext {
184         lcx,
185         tables,
186         param_env: lcx.param_env,
187         needed_resolution: false,
188         substs: lcx.tcx.intern_substs(&[]),
189     };
190     cx.expr(e).map(|cst| (cst, cx.needed_resolution))
191 }
192
193 pub fn constant_simple<'c, 'cc>(
194     lcx: &LateContext<'c, 'cc>,
195     tables: &'c ty::TypeckTables<'cc>,
196     e: &Expr<'_>,
197 ) -> Option<Constant> {
198     constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
199 }
200
201 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`.
202 pub fn constant_context<'c, 'cc>(
203     lcx: &'c LateContext<'c, 'cc>,
204     tables: &'c ty::TypeckTables<'cc>,
205 ) -> ConstEvalLateContext<'c, 'cc> {
206     ConstEvalLateContext {
207         lcx,
208         tables,
209         param_env: lcx.param_env,
210         needed_resolution: false,
211         substs: lcx.tcx.intern_substs(&[]),
212     }
213 }
214
215 pub struct ConstEvalLateContext<'a, 'tcx> {
216     lcx: &'a LateContext<'a, 'tcx>,
217     tables: &'a ty::TypeckTables<'tcx>,
218     param_env: ty::ParamEnv<'tcx>,
219     needed_resolution: bool,
220     substs: SubstsRef<'tcx>,
221 }
222
223 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
224     /// Simple constant folding: Insert an expression, get a constant or none.
225     pub fn expr(&mut self, e: &Expr<'_>) -> Option<Constant> {
226         if let Some((ref cond, ref then, otherwise)) = higher::if_block(&e) {
227             return self.ifthenelse(cond, then, otherwise);
228         }
229         match e.kind {
230             ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
231             ExprKind::Block(ref block, _) => self.block(block),
232             ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty_opt(e))),
233             ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
234             ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
235             ExprKind::Repeat(ref value, _) => {
236                 let n = match self.tables.expr_ty(e).kind {
237                     ty::Array(_, n) => n.eval_usize(self.lcx.tcx, self.lcx.param_env),
238                     _ => span_bug!(e.span, "typeck error"),
239                 };
240                 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
241             },
242             ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
243                 UnOp::UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
244                 UnOp::UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
245                 UnOp::UnDeref => Some(o),
246             }),
247             ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
248             ExprKind::Call(ref callee, ref args) => {
249                 // We only handle a few const functions for now.
250                 if_chain! {
251                     if args.is_empty();
252                     if let ExprKind::Path(qpath) = &callee.kind;
253                     let res = self.tables.qpath_res(qpath, callee.hir_id);
254                     if let Some(def_id) = res.opt_def_id();
255                     let def_path: Vec<_> = self.lcx.get_def_path(def_id).into_iter().map(Symbol::as_str).collect();
256                     let def_path: Vec<&str> = def_path.iter().take(4).map(|s| &**s).collect();
257                     if let ["core", "num", int_impl, "max_value"] = *def_path;
258                     then {
259                        let value = match int_impl {
260                            "<impl i8>" => i8::max_value() as u128,
261                            "<impl i16>" => i16::max_value() as u128,
262                            "<impl i32>" => i32::max_value() as u128,
263                            "<impl i64>" => i64::max_value() as u128,
264                            "<impl i128>" => i128::max_value() as u128,
265                            _ => return None,
266                        };
267                        Some(Constant::Int(value))
268                     }
269                     else {
270                         None
271                     }
272                 }
273             },
274             // TODO: add other expressions.
275             _ => None,
276         }
277     }
278
279     #[allow(clippy::cast_possible_wrap)]
280     fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
281         use self::Constant::*;
282         match *o {
283             Bool(b) => Some(Bool(!b)),
284             Int(value) => {
285                 let value = !value;
286                 match ty.kind {
287                     ty::Int(ity) => Some(Int(unsext(self.lcx.tcx, value as i128, ity))),
288                     ty::Uint(ity) => Some(Int(clip(self.lcx.tcx, value, ity))),
289                     _ => None,
290                 }
291             },
292             _ => None,
293         }
294     }
295
296     fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
297         use self::Constant::*;
298         match *o {
299             Int(value) => {
300                 let ity = match ty.kind {
301                     ty::Int(ity) => ity,
302                     _ => return None,
303                 };
304                 // sign extend
305                 let value = sext(self.lcx.tcx, value, ity);
306                 let value = value.checked_neg()?;
307                 // clear unused bits
308                 Some(Int(unsext(self.lcx.tcx, value, ity)))
309             },
310             F32(f) => Some(F32(-f)),
311             F64(f) => Some(F64(-f)),
312             _ => None,
313         }
314     }
315
316     /// Create `Some(Vec![..])` of all constants, unless there is any
317     /// non-constant part.
318     fn multi(&mut self, vec: &[Expr<'_>]) -> Option<Vec<Constant>> {
319         vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
320     }
321
322     /// Lookup a possibly constant expression from a `ExprKind::Path`.
323     fn fetch_path(&mut self, qpath: &QPath<'_>, id: HirId) -> Option<Constant> {
324         let res = self.tables.qpath_res(qpath, id);
325         match res {
326             Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
327                 let substs = self.tables.node_substs(id);
328                 let substs = if self.substs.is_empty() {
329                     substs
330                 } else {
331                     substs.subst(self.lcx.tcx, self.substs)
332                 };
333
334                 let result = self
335                     .lcx
336                     .tcx
337                     .const_eval_resolve(self.param_env, def_id, substs, None, None)
338                     .ok()?;
339                 let result = miri_to_const(&result);
340                 if result.is_some() {
341                     self.needed_resolution = true;
342                 }
343                 result
344             },
345             // FIXME: cover all usable cases.
346             _ => None,
347         }
348     }
349
350     /// A block can only yield a constant if it only has one constant expression.
351     fn block(&mut self, block: &Block<'_>) -> Option<Constant> {
352         if block.stmts.is_empty() {
353             block.expr.as_ref().and_then(|b| self.expr(b))
354         } else {
355             None
356         }
357     }
358
359     fn ifthenelse(&mut self, cond: &Expr<'_>, then: &Expr<'_>, otherwise: Option<&Expr<'_>>) -> Option<Constant> {
360         if let Some(Constant::Bool(b)) = self.expr(cond) {
361             if b {
362                 self.expr(&*then)
363             } else {
364                 otherwise.as_ref().and_then(|expr| self.expr(expr))
365             }
366         } else {
367             None
368         }
369     }
370
371     fn binop(&mut self, op: BinOp, left: &Expr<'_>, right: &Expr<'_>) -> Option<Constant> {
372         let l = self.expr(left)?;
373         let r = self.expr(right);
374         match (l, r) {
375             (Constant::Int(l), Some(Constant::Int(r))) => match self.tables.expr_ty(left).kind {
376                 ty::Int(ity) => {
377                     let l = sext(self.lcx.tcx, l, ity);
378                     let r = sext(self.lcx.tcx, r, ity);
379                     let zext = |n: i128| Constant::Int(unsext(self.lcx.tcx, n, ity));
380                     match op.node {
381                         BinOpKind::Add => l.checked_add(r).map(zext),
382                         BinOpKind::Sub => l.checked_sub(r).map(zext),
383                         BinOpKind::Mul => l.checked_mul(r).map(zext),
384                         BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
385                         BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
386                         BinOpKind::Shr => l.checked_shr(r.try_into().expect("invalid shift")).map(zext),
387                         BinOpKind::Shl => l.checked_shl(r.try_into().expect("invalid shift")).map(zext),
388                         BinOpKind::BitXor => Some(zext(l ^ r)),
389                         BinOpKind::BitOr => Some(zext(l | r)),
390                         BinOpKind::BitAnd => Some(zext(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                 },
400                 ty::Uint(_) => match op.node {
401                     BinOpKind::Add => l.checked_add(r).map(Constant::Int),
402                     BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
403                     BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
404                     BinOpKind::Div => l.checked_div(r).map(Constant::Int),
405                     BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
406                     BinOpKind::Shr => l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int),
407                     BinOpKind::Shl => l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int),
408                     BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
409                     BinOpKind::BitOr => Some(Constant::Int(l | r)),
410                     BinOpKind::BitAnd => Some(Constant::Int(l & r)),
411                     BinOpKind::Eq => Some(Constant::Bool(l == r)),
412                     BinOpKind::Ne => Some(Constant::Bool(l != r)),
413                     BinOpKind::Lt => Some(Constant::Bool(l < r)),
414                     BinOpKind::Le => Some(Constant::Bool(l <= r)),
415                     BinOpKind::Ge => Some(Constant::Bool(l >= r)),
416                     BinOpKind::Gt => Some(Constant::Bool(l > r)),
417                     _ => None,
418                 },
419                 _ => None,
420             },
421             (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
422                 BinOpKind::Add => Some(Constant::F32(l + r)),
423                 BinOpKind::Sub => Some(Constant::F32(l - r)),
424                 BinOpKind::Mul => Some(Constant::F32(l * r)),
425                 BinOpKind::Div => Some(Constant::F32(l / r)),
426                 BinOpKind::Rem => Some(Constant::F32(l % r)),
427                 BinOpKind::Eq => Some(Constant::Bool(l == r)),
428                 BinOpKind::Ne => Some(Constant::Bool(l != r)),
429                 BinOpKind::Lt => Some(Constant::Bool(l < r)),
430                 BinOpKind::Le => Some(Constant::Bool(l <= r)),
431                 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
432                 BinOpKind::Gt => Some(Constant::Bool(l > r)),
433                 _ => None,
434             },
435             (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
436                 BinOpKind::Add => Some(Constant::F64(l + r)),
437                 BinOpKind::Sub => Some(Constant::F64(l - r)),
438                 BinOpKind::Mul => Some(Constant::F64(l * r)),
439                 BinOpKind::Div => Some(Constant::F64(l / r)),
440                 BinOpKind::Rem => Some(Constant::F64(l % r)),
441                 BinOpKind::Eq => Some(Constant::Bool(l == r)),
442                 BinOpKind::Ne => Some(Constant::Bool(l != r)),
443                 BinOpKind::Lt => Some(Constant::Bool(l < r)),
444                 BinOpKind::Le => Some(Constant::Bool(l <= r)),
445                 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
446                 BinOpKind::Gt => Some(Constant::Bool(l > r)),
447                 _ => None,
448             },
449             (l, r) => match (op.node, l, r) {
450                 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
451                 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
452                 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
453                     Some(r)
454                 },
455                 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
456                 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
457                 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
458                 _ => None,
459             },
460         }
461     }
462 }
463
464 pub fn miri_to_const(result: &ty::Const<'_>) -> Option<Constant> {
465     use rustc::mir::interpret::{ConstValue, Scalar};
466     match result.val {
467         ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw { data: d, .. })) => match result.ty.kind {
468             ty::Bool => Some(Constant::Bool(d == 1)),
469             ty::Uint(_) | ty::Int(_) => Some(Constant::Int(d)),
470             ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(
471                 d.try_into().expect("invalid f32 bit representation"),
472             ))),
473             ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(
474                 d.try_into().expect("invalid f64 bit representation"),
475             ))),
476             ty::RawPtr(type_and_mut) => {
477                 if let ty::Uint(_) = type_and_mut.ty.kind {
478                     return Some(Constant::RawPtr(d));
479                 }
480                 None
481             },
482             // FIXME: implement other conversions.
483             _ => None,
484         },
485         ty::ConstKind::Value(ConstValue::Slice { data, start, end }) => match result.ty.kind {
486             ty::Ref(_, tam, _) => match tam.kind {
487                 ty::Str => String::from_utf8(
488                     data.inspect_with_undef_and_ptr_outside_interpreter(start..end)
489                         .to_owned(),
490                 )
491                 .ok()
492                 .map(Constant::Str),
493                 _ => None,
494             },
495             _ => None,
496         },
497         // FIXME: implement other conversions.
498         _ => None,
499     }
500 }