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