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