]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/consts.rs
Auto merge of #4372 - phansch:changelog_update, 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::hir::def::{DefKind, Res};
6 use rustc::hir::*;
7 use rustc::lint::LateContext;
8 use rustc::ty::subst::{Subst, SubstsRef};
9 use rustc::ty::{self, Instance, Ty, TyCtxt};
10 use rustc::{bug, span_bug};
11 use rustc_data_structures::sync::Lrc;
12 use std::cmp::Ordering::{self, Equal};
13 use std::cmp::PartialOrd;
14 use std::convert::TryInto;
15 use std::hash::{Hash, Hasher};
16 use syntax::ast::{FloatTy, LitKind};
17 use syntax_pos::symbol::Symbol;
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.sty {
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: 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, _) | LitKind::FloatUnsuffixed(ref is) => match ty.sty {
165             ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
166             ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
167             _ => bug!(),
168         },
169         LitKind::Bool(b) => Constant::Bool(b),
170         LitKind::Err(s) => Constant::Err(s),
171     }
172 }
173
174 pub fn constant<'c, 'cc>(
175     lcx: &LateContext<'c, 'cc>,
176     tables: &'c ty::TypeckTables<'cc>,
177     e: &Expr,
178 ) -> Option<(Constant, bool)> {
179     let mut cx = ConstEvalLateContext {
180         lcx,
181         tables,
182         param_env: lcx.param_env,
183         needed_resolution: false,
184         substs: lcx.tcx.intern_substs(&[]),
185     };
186     cx.expr(e).map(|cst| (cst, cx.needed_resolution))
187 }
188
189 pub fn constant_simple<'c, 'cc>(
190     lcx: &LateContext<'c, 'cc>,
191     tables: &'c ty::TypeckTables<'cc>,
192     e: &Expr,
193 ) -> Option<Constant> {
194     constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
195 }
196
197 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`.
198 pub fn constant_context<'c, 'cc>(
199     lcx: &'c LateContext<'c, 'cc>,
200     tables: &'c ty::TypeckTables<'cc>,
201 ) -> ConstEvalLateContext<'c, 'cc> {
202     ConstEvalLateContext {
203         lcx,
204         tables,
205         param_env: lcx.param_env,
206         needed_resolution: false,
207         substs: lcx.tcx.intern_substs(&[]),
208     }
209 }
210
211 pub struct ConstEvalLateContext<'a, 'tcx> {
212     lcx: &'a LateContext<'a, 'tcx>,
213     tables: &'a ty::TypeckTables<'tcx>,
214     param_env: ty::ParamEnv<'tcx>,
215     needed_resolution: bool,
216     substs: SubstsRef<'tcx>,
217 }
218
219 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
220     /// Simple constant folding: Insert an expression, get a constant or none.
221     pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
222         if let Some((ref cond, ref then, otherwise)) = higher::if_block(&e) {
223             return self.ifthenelse(cond, then, otherwise);
224         }
225         match e.node {
226             ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
227             ExprKind::Block(ref block, _) => self.block(block),
228             ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
229             ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
230             ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
231             ExprKind::Repeat(ref value, _) => {
232                 let n = match self.tables.expr_ty(e).sty {
233                     ty::Array(_, n) => n.eval_usize(self.lcx.tcx, self.lcx.param_env),
234                     _ => span_bug!(e.span, "typeck error"),
235                 };
236                 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
237             },
238             ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
239                 UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
240                 UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
241                 UnDeref => Some(o),
242             }),
243             ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
244             ExprKind::Call(ref callee, ref args) => {
245                 // We only handle a few const functions for now.
246                 if_chain! {
247                     if args.is_empty();
248                     if let ExprKind::Path(qpath) = &callee.node;
249                     let res = self.tables.qpath_res(qpath, callee.hir_id);
250                     if let Some(def_id) = res.opt_def_id();
251                     let get_def_path = self.lcx.get_def_path(def_id, );
252                     let def_path = get_def_path
253                         .iter()
254                         .copied()
255                         .map(Symbol::as_str)
256                         .collect::<Vec<_>>();
257                     if def_path[0] == "core";
258                     if def_path[1] == "num";
259                     if def_path[3] == "max_value";
260                     if def_path.len() == 4;
261                     then {
262                        let value = match &*def_path[2] {
263                            "<impl i8>" => i8::max_value() as u128,
264                            "<impl i16>" => i16::max_value() as u128,
265                            "<impl i32>" => i32::max_value() as u128,
266                            "<impl i64>" => i64::max_value() as u128,
267                            "<impl i128>" => i128::max_value() as u128,
268                            _ => return None,
269                        };
270                        Some(Constant::Int(value))
271                     }
272                     else {
273                         None
274                     }
275                 }
276             },
277             // TODO: add other expressions.
278             _ => None,
279         }
280     }
281
282     #[allow(clippy::cast_possible_wrap)]
283     fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
284         use self::Constant::*;
285         match *o {
286             Bool(b) => Some(Bool(!b)),
287             Int(value) => {
288                 let value = !value;
289                 match ty.sty {
290                     ty::Int(ity) => Some(Int(unsext(self.lcx.tcx, value as i128, ity))),
291                     ty::Uint(ity) => Some(Int(clip(self.lcx.tcx, value, ity))),
292                     _ => None,
293                 }
294             },
295             _ => None,
296         }
297     }
298
299     fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
300         use self::Constant::*;
301         match *o {
302             Int(value) => {
303                 let ity = match ty.sty {
304                     ty::Int(ity) => ity,
305                     _ => return None,
306                 };
307                 // sign extend
308                 let value = sext(self.lcx.tcx, value, ity);
309                 let value = value.checked_neg()?;
310                 // clear unused bits
311                 Some(Int(unsext(self.lcx.tcx, value, ity)))
312             },
313             F32(f) => Some(F32(-f)),
314             F64(f) => Some(F64(-f)),
315             _ => None,
316         }
317     }
318
319     /// Create `Some(Vec![..])` of all constants, unless there is any
320     /// non-constant part.
321     fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
322         vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
323     }
324
325     /// Lookup a possibly constant expression from a ExprKind::Path.
326     fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
327         use rustc::mir::interpret::GlobalId;
328
329         let res = self.tables.qpath_res(qpath, id);
330         match res {
331             Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
332                 let substs = self.tables.node_substs(id);
333                 let substs = if self.substs.is_empty() {
334                     substs
335                 } else {
336                     substs.subst(self.lcx.tcx, self.substs)
337                 };
338                 let instance = Instance::resolve(self.lcx.tcx, self.param_env, def_id, substs)?;
339                 let gid = GlobalId {
340                     instance,
341                     promoted: None,
342                 };
343
344                 let result = self.lcx.tcx.const_eval(self.param_env.and(gid)).ok()?;
345                 let result = miri_to_const(&result);
346                 if result.is_some() {
347                     self.needed_resolution = true;
348                 }
349                 result
350             },
351             // FIXME: cover all usable cases.
352             _ => None,
353         }
354     }
355
356     /// A block can only yield a constant if it only has one constant expression.
357     fn block(&mut self, block: &Block) -> Option<Constant> {
358         if block.stmts.is_empty() {
359             block.expr.as_ref().and_then(|b| self.expr(b))
360         } else {
361             None
362         }
363     }
364
365     fn ifthenelse(&mut self, cond: &Expr, then: &Expr, otherwise: Option<&Expr>) -> Option<Constant> {
366         if let Some(Constant::Bool(b)) = self.expr(cond) {
367             if b {
368                 self.expr(&*then)
369             } else {
370                 otherwise.as_ref().and_then(|expr| self.expr(expr))
371             }
372         } else {
373             None
374         }
375     }
376
377     fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
378         let l = self.expr(left)?;
379         let r = self.expr(right);
380         match (l, r) {
381             (Constant::Int(l), Some(Constant::Int(r))) => match self.tables.expr_ty(left).sty {
382                 ty::Int(ity) => {
383                     let l = sext(self.lcx.tcx, l, ity);
384                     let r = sext(self.lcx.tcx, r, ity);
385                     let zext = |n: i128| Constant::Int(unsext(self.lcx.tcx, n, ity));
386                     match op.node {
387                         BinOpKind::Add => l.checked_add(r).map(zext),
388                         BinOpKind::Sub => l.checked_sub(r).map(zext),
389                         BinOpKind::Mul => l.checked_mul(r).map(zext),
390                         BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
391                         BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
392                         BinOpKind::Shr => l.checked_shr(r.try_into().expect("invalid shift")).map(zext),
393                         BinOpKind::Shl => l.checked_shl(r.try_into().expect("invalid shift")).map(zext),
394                         BinOpKind::BitXor => Some(zext(l ^ r)),
395                         BinOpKind::BitOr => Some(zext(l | r)),
396                         BinOpKind::BitAnd => Some(zext(l & r)),
397                         BinOpKind::Eq => Some(Constant::Bool(l == r)),
398                         BinOpKind::Ne => Some(Constant::Bool(l != r)),
399                         BinOpKind::Lt => Some(Constant::Bool(l < r)),
400                         BinOpKind::Le => Some(Constant::Bool(l <= r)),
401                         BinOpKind::Ge => Some(Constant::Bool(l >= r)),
402                         BinOpKind::Gt => Some(Constant::Bool(l > r)),
403                         _ => None,
404                     }
405                 },
406                 ty::Uint(_) => match op.node {
407                     BinOpKind::Add => l.checked_add(r).map(Constant::Int),
408                     BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
409                     BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
410                     BinOpKind::Div => l.checked_div(r).map(Constant::Int),
411                     BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
412                     BinOpKind::Shr => l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int),
413                     BinOpKind::Shl => l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int),
414                     BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
415                     BinOpKind::BitOr => Some(Constant::Int(l | r)),
416                     BinOpKind::BitAnd => Some(Constant::Int(l & r)),
417                     BinOpKind::Eq => Some(Constant::Bool(l == r)),
418                     BinOpKind::Ne => Some(Constant::Bool(l != r)),
419                     BinOpKind::Lt => Some(Constant::Bool(l < r)),
420                     BinOpKind::Le => Some(Constant::Bool(l <= r)),
421                     BinOpKind::Ge => Some(Constant::Bool(l >= r)),
422                     BinOpKind::Gt => Some(Constant::Bool(l > r)),
423                     _ => None,
424                 },
425                 _ => None,
426             },
427             (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
428                 BinOpKind::Add => Some(Constant::F32(l + r)),
429                 BinOpKind::Sub => Some(Constant::F32(l - r)),
430                 BinOpKind::Mul => Some(Constant::F32(l * r)),
431                 BinOpKind::Div => Some(Constant::F32(l / r)),
432                 BinOpKind::Rem => Some(Constant::F32(l % r)),
433                 BinOpKind::Eq => Some(Constant::Bool(l == r)),
434                 BinOpKind::Ne => Some(Constant::Bool(l != r)),
435                 BinOpKind::Lt => Some(Constant::Bool(l < r)),
436                 BinOpKind::Le => Some(Constant::Bool(l <= r)),
437                 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
438                 BinOpKind::Gt => Some(Constant::Bool(l > r)),
439                 _ => None,
440             },
441             (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
442                 BinOpKind::Add => Some(Constant::F64(l + r)),
443                 BinOpKind::Sub => Some(Constant::F64(l - r)),
444                 BinOpKind::Mul => Some(Constant::F64(l * r)),
445                 BinOpKind::Div => Some(Constant::F64(l / r)),
446                 BinOpKind::Rem => Some(Constant::F64(l % r)),
447                 BinOpKind::Eq => Some(Constant::Bool(l == r)),
448                 BinOpKind::Ne => Some(Constant::Bool(l != r)),
449                 BinOpKind::Lt => Some(Constant::Bool(l < r)),
450                 BinOpKind::Le => Some(Constant::Bool(l <= r)),
451                 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
452                 BinOpKind::Gt => Some(Constant::Bool(l > r)),
453                 _ => None,
454             },
455             (l, r) => match (op.node, l, r) {
456                 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
457                 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
458                 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
459                     Some(r)
460                 },
461                 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
462                 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
463                 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
464                 _ => None,
465             },
466         }
467     }
468 }
469
470 pub fn miri_to_const(result: &ty::Const<'_>) -> Option<Constant> {
471     use rustc::mir::interpret::{ConstValue, Scalar};
472     match result.val {
473         ConstValue::Scalar(Scalar::Raw { data: d, .. }) => match result.ty.sty {
474             ty::Bool => Some(Constant::Bool(d == 1)),
475             ty::Uint(_) | ty::Int(_) => Some(Constant::Int(d)),
476             ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(
477                 d.try_into().expect("invalid f32 bit representation"),
478             ))),
479             ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(
480                 d.try_into().expect("invalid f64 bit representation"),
481             ))),
482             ty::RawPtr(type_and_mut) => {
483                 if let ty::Uint(_) = type_and_mut.ty.sty {
484                     return Some(Constant::RawPtr(d));
485                 }
486                 None
487             },
488             // FIXME: implement other conversions.
489             _ => None,
490         },
491         ConstValue::Slice { data, start, end } => match result.ty.sty {
492             ty::Ref(_, tam, _) => match tam.sty {
493                 ty::Str => String::from_utf8(data.bytes[start..end].to_owned())
494                     .ok()
495                     .map(Constant::Str),
496                 _ => None,
497             },
498             _ => None,
499         },
500         // FIXME: implement other conversions.
501         _ => None,
502     }
503 }