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