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