]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/consts.rs
Add handling of float arrays to miri_to_const
[rust.git] / clippy_lints / src / consts.rs
index fe57c300a340d0186bda23fc9a5e829d68190617..c64c00134e89a1e77dadadf5bc306c536aa1b45d 100644 (file)
@@ -2,19 +2,18 @@
 
 use crate::utils::{clip, higher, sext, unsext};
 use if_chain::if_chain;
-use rustc::hir::def::{DefKind, Res};
-use rustc::hir::*;
-use rustc::lint::LateContext;
-use rustc::ty::subst::{Subst, SubstsRef};
-use rustc::ty::{self, Instance, Ty, TyCtxt};
-use rustc::{bug, span_bug};
+use rustc_ast::ast::{FloatTy, LitFloatType, LitKind};
 use rustc_data_structures::sync::Lrc;
+use rustc_hir::def::{DefKind, Res};
+use rustc_hir::{BinOp, BinOpKind, Block, Expr, ExprKind, HirId, QPath, UnOp};
+use rustc_lint::LateContext;
+use rustc_middle::ty::subst::{Subst, SubstsRef};
+use rustc_middle::ty::{self, Ty, TyCtxt};
+use rustc_middle::{bug, span_bug};
+use rustc_span::symbol::Symbol;
 use std::cmp::Ordering::{self, Equal};
-use std::cmp::PartialOrd;
 use std::convert::TryInto;
 use std::hash::{Hash, Hasher};
-use syntax::ast::{FloatTy, LitKind};
-use syntax_pos::symbol::Symbol;
 
 /// A `LitKind`-like enum to fold constant `Expr`s into.
 #[derive(Debug, Clone)]
@@ -124,7 +123,7 @@ pub fn partial_cmp(tcx: TyCtxt<'_>, cmp_type: Ty<'_>, left: &Self, right: &Self)
             (&Self::Str(ref ls), &Self::Str(ref rs)) => Some(ls.cmp(rs)),
             (&Self::Char(ref l), &Self::Char(ref r)) => Some(l.cmp(r)),
             (&Self::Int(l), &Self::Int(r)) => {
-                if let ty::Int(int_ty) = cmp_type.sty {
+                if let ty::Int(int_ty) = cmp_type.kind {
                     Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
                 } else {
                     Some(l.cmp(&r))
@@ -152,16 +151,18 @@ pub fn partial_cmp(tcx: TyCtxt<'_>, cmp_type: Ty<'_>, left: &Self, right: &Self)
 }
 
 /// Parses a `LitKind` to a `Constant`.
-pub fn lit_to_constant(lit: &LitKind, ty: Ty<'_>) -> Constant {
-    use syntax::ast::*;
-
+pub fn lit_to_constant(lit: &LitKind, ty: Option<Ty<'_>>) -> Constant {
     match *lit {
         LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
         LitKind::Byte(b) => Constant::Int(u128::from(b)),
         LitKind::ByteStr(ref s) => Constant::Binary(Lrc::clone(s)),
         LitKind::Char(c) => Constant::Char(c),
         LitKind::Int(n, _) => Constant::Int(n),
-        LitKind::Float(ref is, _) | LitKind::FloatUnsuffixed(ref is) => match ty.sty {
+        LitKind::Float(ref is, LitFloatType::Suffixed(fty)) => match fty {
+            FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()),
+            FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()),
+        },
+        LitKind::Float(ref is, LitFloatType::Unsuffixed) => match ty.expect("type of float is known").kind {
             ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
             ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
             _ => bug!(),
@@ -174,7 +175,7 @@ pub fn lit_to_constant(lit: &LitKind, ty: Ty<'_>) -> Constant {
 pub fn constant<'c, 'cc>(
     lcx: &LateContext<'c, 'cc>,
     tables: &'c ty::TypeckTables<'cc>,
-    e: &Expr,
+    e: &Expr<'_>,
 ) -> Option<(Constant, bool)> {
     let mut cx = ConstEvalLateContext {
         lcx,
@@ -189,7 +190,7 @@ pub fn constant<'c, 'cc>(
 pub fn constant_simple<'c, 'cc>(
     lcx: &LateContext<'c, 'cc>,
     tables: &'c ty::TypeckTables<'cc>,
-    e: &Expr,
+    e: &Expr<'_>,
 ) -> Option<Constant> {
     constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
 }
@@ -218,48 +219,41 @@ pub struct ConstEvalLateContext<'a, 'tcx> {
 
 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
     /// Simple constant folding: Insert an expression, get a constant or none.
-    pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
+    pub fn expr(&mut self, e: &Expr<'_>) -> Option<Constant> {
         if let Some((ref cond, ref then, otherwise)) = higher::if_block(&e) {
             return self.ifthenelse(cond, then, otherwise);
         }
-        match e.node {
-            ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id),
+        match e.kind {
+            ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id, self.tables.expr_ty(e)),
             ExprKind::Block(ref block, _) => self.block(block),
-            ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty(e))),
+            ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.tables.expr_ty_opt(e))),
             ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
             ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
             ExprKind::Repeat(ref value, _) => {
-                let n = match self.tables.expr_ty(e).sty {
-                    ty::Array(_, n) => n.eval_usize(self.lcx.tcx, self.lcx.param_env),
+                let n = match self.tables.expr_ty(e).kind {
+                    ty::Array(_, n) => n.try_eval_usize(self.lcx.tcx, self.lcx.param_env)?,
                     _ => span_bug!(e.span, "typeck error"),
                 };
                 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
             },
             ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
-                UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
-                UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
-                UnDeref => Some(o),
+                UnOp::UnNot => self.constant_not(&o, self.tables.expr_ty(e)),
+                UnOp::UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)),
+                UnOp::UnDeref => Some(o),
             }),
             ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
             ExprKind::Call(ref callee, ref args) => {
                 // We only handle a few const functions for now.
                 if_chain! {
                     if args.is_empty();
-                    if let ExprKind::Path(qpath) = &callee.node;
+                    if let ExprKind::Path(qpath) = &callee.kind;
                     let res = self.tables.qpath_res(qpath, callee.hir_id);
                     if let Some(def_id) = res.opt_def_id();
-                    let get_def_path = self.lcx.get_def_path(def_id, );
-                    let def_path = get_def_path
-                        .iter()
-                        .copied()
-                        .map(Symbol::as_str)
-                        .collect::<Vec<_>>();
-                    if def_path[0] == "core";
-                    if def_path[1] == "num";
-                    if def_path[3] == "max_value";
-                    if def_path.len() == 4;
+                    let def_path: Vec<_> = self.lcx.get_def_path(def_id).into_iter().map(Symbol::as_str).collect();
+                    let def_path: Vec<&str> = def_path.iter().take(4).map(|s| &**s).collect();
+                    if let ["core", "num", int_impl, "max_value"] = *def_path;
                     then {
-                       let value = match &*def_path[2] {
+                       let value = match int_impl {
                            "<impl i8>" => i8::max_value() as u128,
                            "<impl i16>" => i16::max_value() as u128,
                            "<impl i32>" => i32::max_value() as u128,
@@ -281,12 +275,12 @@ pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
 
     #[allow(clippy::cast_possible_wrap)]
     fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
-        use self::Constant::*;
+        use self::Constant::{Bool, Int};
         match *o {
             Bool(b) => Some(Bool(!b)),
             Int(value) => {
                 let value = !value;
-                match ty.sty {
+                match ty.kind {
                     ty::Int(ity) => Some(Int(unsext(self.lcx.tcx, value as i128, ity))),
                     ty::Uint(ity) => Some(Int(clip(self.lcx.tcx, value, ity))),
                     _ => None,
@@ -297,10 +291,10 @@ fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
     }
 
     fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
-        use self::Constant::*;
+        use self::Constant::{Int, F32, F64};
         match *o {
             Int(value) => {
-                let ity = match ty.sty {
+                let ity = match ty.kind {
                     ty::Int(ity) => ity,
                     _ => return None,
                 };
@@ -318,30 +312,28 @@ fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
 
     /// Create `Some(Vec![..])` of all constants, unless there is any
     /// non-constant part.
-    fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
+    fn multi(&mut self, vec: &[Expr<'_>]) -> Option<Vec<Constant>> {
         vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
     }
 
-    /// Lookup a possibly constant expression from a ExprKind::Path.
-    fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
-        use rustc::mir::interpret::GlobalId;
-
+    /// Lookup a possibly constant expression from a `ExprKind::Path`.
+    fn fetch_path(&mut self, qpath: &QPath<'_>, id: HirId, ty: Ty<'cc>) -> Option<Constant> {
         let res = self.tables.qpath_res(qpath, id);
         match res {
-            Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
+            Res::Def(DefKind::Const | DefKind::AssocConst, def_id) => {
                 let substs = self.tables.node_substs(id);
                 let substs = if self.substs.is_empty() {
                     substs
                 } else {
                     substs.subst(self.lcx.tcx, self.substs)
                 };
-                let instance = Instance::resolve(self.lcx.tcx, self.param_env, def_id, substs)?;
-                let gid = GlobalId {
-                    instance,
-                    promoted: None,
-                };
 
-                let result = self.lcx.tcx.const_eval(self.param_env.and(gid)).ok()?;
+                let result = self
+                    .lcx
+                    .tcx
+                    .const_eval_resolve(self.param_env, def_id, substs, None, None)
+                    .ok()
+                    .map(|val| rustc_middle::ty::Const::from_value(self.lcx.tcx, val, ty))?;
                 let result = miri_to_const(&result);
                 if result.is_some() {
                     self.needed_resolution = true;
@@ -354,7 +346,7 @@ fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
     }
 
     /// A block can only yield a constant if it only has one constant expression.
-    fn block(&mut self, block: &Block) -> Option<Constant> {
+    fn block(&mut self, block: &Block<'_>) -> Option<Constant> {
         if block.stmts.is_empty() {
             block.expr.as_ref().and_then(|b| self.expr(b))
         } else {
@@ -362,7 +354,7 @@ fn block(&mut self, block: &Block) -> Option<Constant> {
         }
     }
 
-    fn ifthenelse(&mut self, cond: &Expr, then: &Expr, otherwise: Option<&Expr>) -> Option<Constant> {
+    fn ifthenelse(&mut self, cond: &Expr<'_>, then: &Expr<'_>, otherwise: Option<&Expr<'_>>) -> Option<Constant> {
         if let Some(Constant::Bool(b)) = self.expr(cond) {
             if b {
                 self.expr(&*then)
@@ -374,11 +366,11 @@ fn ifthenelse(&mut self, cond: &Expr, then: &Expr, otherwise: Option<&Expr>) ->
         }
     }
 
-    fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
+    fn binop(&mut self, op: BinOp, left: &Expr<'_>, right: &Expr<'_>) -> Option<Constant> {
         let l = self.expr(left)?;
         let r = self.expr(right);
         match (l, r) {
-            (Constant::Int(l), Some(Constant::Int(r))) => match self.tables.expr_ty(left).sty {
+            (Constant::Int(l), Some(Constant::Int(r))) => match self.tables.expr_ty(left).kind {
                 ty::Int(ity) => {
                     let l = sext(self.lcx.tcx, l, ity);
                     let r = sext(self.lcx.tcx, r, ity);
@@ -468,9 +460,9 @@ fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
 }
 
 pub fn miri_to_const(result: &ty::Const<'_>) -> Option<Constant> {
-    use rustc::mir::interpret::{ConstValue, Scalar};
+    use rustc_middle::mir::interpret::{ConstValue, Scalar};
     match result.val {
-        ConstValue::Scalar(Scalar::Raw { data: d, .. }) => match result.ty.sty {
+        ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw { data: d, .. })) => match result.ty.kind {
             ty::Bool => Some(Constant::Bool(d == 1)),
             ty::Uint(_) | ty::Int(_) => Some(Constant::Int(d)),
             ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(
@@ -480,7 +472,7 @@ pub fn miri_to_const(result: &ty::Const<'_>) -> Option<Constant> {
                 d.try_into().expect("invalid f64 bit representation"),
             ))),
             ty::RawPtr(type_and_mut) => {
-                if let ty::Uint(_) = type_and_mut.ty.sty {
+                if let ty::Uint(_) = type_and_mut.ty.kind {
                     return Some(Constant::RawPtr(d));
                 }
                 None
@@ -488,11 +480,49 @@ pub fn miri_to_const(result: &ty::Const<'_>) -> Option<Constant> {
             // FIXME: implement other conversions.
             _ => None,
         },
-        ConstValue::Slice { data, start, end } => match result.ty.sty {
-            ty::Ref(_, tam, _) => match tam.sty {
-                ty::Str => String::from_utf8(data.bytes[start..end].to_owned())
-                    .ok()
-                    .map(Constant::Str),
+        ty::ConstKind::Value(ConstValue::Slice { data, start, end }) => match result.ty.kind {
+            ty::Ref(_, tam, _) => match tam.kind {
+                ty::Str => String::from_utf8(
+                    data.inspect_with_undef_and_ptr_outside_interpreter(start..end)
+                        .to_owned(),
+                )
+                .ok()
+                .map(Constant::Str),
+                _ => None,
+            },
+            _ => None,
+        },
+        ty::ConstKind::Value(ConstValue::ByRef { alloc, offset: _ }) => match result.ty.kind {
+            ty::Array(sub_type, len) => match sub_type.kind {
+                ty::Float(FloatTy::F32) => match miri_to_const(len) {
+                    Some(Constant::Int(len)) => alloc
+                        .inspect_with_undef_and_ptr_outside_interpreter(0..(4 * len as usize))
+                        .to_owned()
+                        .chunks(4)
+                        .map(|chunk| {
+                            Some(Constant::F32(f32::from_le_bytes(
+                                chunk.try_into().expect("this shouldn't happen"),
+                            )))
+                        })
+                        .collect::<Option<Vec<Constant>>>()
+                        .map(Constant::Vec),
+                    _ => None,
+                },
+                ty::Float(FloatTy::F64) => match miri_to_const(len) {
+                    Some(Constant::Int(len)) => alloc
+                        .inspect_with_undef_and_ptr_outside_interpreter(0..(8 * len as usize))
+                        .to_owned()
+                        .chunks(8)
+                        .map(|chunk| {
+                            Some(Constant::F64(f64::from_le_bytes(
+                                chunk.try_into().expect("this shouldn't happen"),
+                            )))
+                        })
+                        .collect::<Option<Vec<Constant>>>()
+                        .map(Constant::Vec),
+                    _ => None,
+                },
+                // FIXME: implement other array type conversions.
                 _ => None,
             },
             _ => None,