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