]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/consts.rs
Merge pull request #3294 from mikerite/fix-3276
[rust.git] / clippy_lints / src / consts.rs
index 6f646e340a070b66458ffe942f65ebc49caf154d..5d509ef76f3f2c071ef37fda6d6188ef5017089b 100644 (file)
@@ -1,18 +1,29 @@
+// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+
 #![allow(clippy::float_cmp)]
 
-use rustc::lint::LateContext;
-use rustc::{span_bug, bug};
-use rustc::hir::def::Def;
-use rustc::hir::*;
-use rustc::ty::{self, Ty, TyCtxt, Instance};
-use rustc::ty::subst::{Subst, Substs};
+use crate::rustc::lint::LateContext;
+use crate::rustc::{span_bug, bug};
+use crate::rustc::hir::def::Def;
+use crate::rustc::hir::*;
+use crate::rustc::ty::{self, Ty, TyCtxt, Instance};
+use crate::rustc::ty::subst::{Subst, Substs};
 use std::cmp::Ordering::{self, Equal};
 use std::cmp::PartialOrd;
+use std::convert::TryInto;
 use std::hash::{Hash, Hasher};
 use std::mem;
 use std::rc::Rc;
-use syntax::ast::{FloatTy, LitKind};
-use syntax::ptr::P;
+use crate::syntax::ast::{FloatTy, LitKind};
+use crate::syntax::ptr::P;
 use crate::utils::{sext, unsext, clip};
 
 /// A `LitKind`-like enum to fold constant `Expr`s into.
@@ -123,11 +134,11 @@ pub fn partial_cmp(tcx: TyCtxt<'_, '_, '_>, cmp_type: &ty::TyKind<'_>, left: &Se
             (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l
                 .iter()
                 .zip(r.iter())
-                .map(|(li, ri)| Constant::partial_cmp(tcx, cmp_type, li, ri))
+                .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
                 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
                 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
             (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
-                match Constant::partial_cmp(tcx, cmp_type, lv, rv) {
+                match Self::partial_cmp(tcx, cmp_type, lv, rv) {
                     Some(Equal) => Some(ls.cmp(rs)),
                     x => x,
                 }
@@ -139,7 +150,7 @@ pub fn partial_cmp(tcx: TyCtxt<'_, '_, '_>, cmp_type: &ty::TyKind<'_>, left: &Se
 
 /// parse a `LitKind` to a `Constant`
 pub fn lit_to_constant<'tcx>(lit: &LitKind, ty: Ty<'tcx>) -> Constant {
-    use syntax::ast::*;
+    use crate::syntax::ast::*;
 
     match *lit {
         LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
@@ -206,7 +217,7 @@ pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
                     ty::Array(_, n) => n.assert_usize(self.tcx).expect("array length"),
                     _ => span_bug!(e.span, "typeck error"),
                 };
-                self.expr(value).map(|v| Constant::Repeat(Box::new(v), n as u64))
+                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)),
@@ -219,6 +230,7 @@ pub fn expr(&mut self, e: &Expr) -> Option<Constant> {
         }
     }
 
+    #[allow(clippy::cast_possible_wrap)]
     fn constant_not(&self, o: &Constant, ty: ty::Ty<'_>) -> Option<Constant> {
         use self::Constant::*;
         match *o {
@@ -265,6 +277,8 @@ fn multi(&mut self, vec: &[Expr]) -> Option<Vec<Constant>> {
 
     /// lookup a possibly constant expression from a ExprKind::Path
     fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
+        use crate::rustc::mir::interpret::GlobalId;
+
         let def = self.tables.qpath_def(qpath, id);
         match def {
             Def::Const(def_id) | Def::AssociatedConst(def_id) => {
@@ -279,7 +293,7 @@ fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
                     instance,
                     promoted: None,
                 };
-                use rustc::mir::interpret::GlobalId;
+                
                 let result = self.tcx.const_eval(self.param_env.and(gid)).ok()?;
                 let ret = miri_to_const(self.tcx, result);
                 if ret.is_some() {
@@ -329,8 +343,12 @@ fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
                             BinOpKind::Mul => l.checked_mul(r).map(zext),
                             BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
                             BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
-                            BinOpKind::Shr => l.checked_shr(r as u128 as u32).map(zext),
-                            BinOpKind::Shl => l.checked_shl(r as u128 as u32).map(zext),
+                            BinOpKind::Shr => l.checked_shr(
+                                    r.try_into().expect("invalid shift")
+                                ).map(zext),
+                            BinOpKind::Shl => l.checked_shl(
+                                    r.try_into().expect("invalid shift")
+                                ).map(zext),
                             BinOpKind::BitXor => Some(zext(l ^ r)),
                             BinOpKind::BitOr => Some(zext(l | r)),
                             BinOpKind::BitAnd => Some(zext(l & r)),
@@ -350,8 +368,12 @@ fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
                             BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
                             BinOpKind::Div => l.checked_div(r).map(Constant::Int),
                             BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
-                            BinOpKind::Shr => l.checked_shr(r as u32).map(Constant::Int),
-                            BinOpKind::Shl => l.checked_shl(r as u32).map(Constant::Int),
+                            BinOpKind::Shr => l.checked_shr(
+                                    r.try_into().expect("shift too large")
+                                ).map(Constant::Int),
+                            BinOpKind::Shl => l.checked_shl(
+                                    r.try_into().expect("shift too large")
+                                ).map(Constant::Int),
                             BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
                             BinOpKind::BitOr => Some(Constant::Int(l | r)),
                             BinOpKind::BitAnd => Some(Constant::Int(l & r)),
@@ -409,26 +431,29 @@ fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
 }
 
 pub fn miri_to_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, result: &ty::Const<'tcx>) -> Option<Constant> {
-    use rustc::mir::interpret::{Scalar, ScalarMaybeUndef, ConstValue};
+    use crate::rustc::mir::interpret::{Scalar, ConstValue};
     match result.val {
         ConstValue::Scalar(Scalar::Bits{ bits: b, ..}) => match result.ty.sty {
             ty::Bool => Some(Constant::Bool(b == 1)),
             ty::Uint(_) | ty::Int(_) => Some(Constant::Int(b)),
-            ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(b as u32))),
-            ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(b as u64))),
+            ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(
+                b.try_into().expect("invalid f32 bit representation")
+            ))),
+            ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(
+                b.try_into().expect("invalid f64 bit representation")
+            ))),
             // FIXME: implement other conversion
             _ => None,
         },
         ConstValue::ScalarPair(Scalar::Ptr(ptr),
-                               ScalarMaybeUndef::Scalar(
-                                Scalar::Bits { bits: n, .. })) => match result.ty.sty {
+                                Scalar::Bits { bits: n, .. }) => match result.ty.sty {
             ty::Ref(_, tam, _) => match tam.sty {
                 ty::Str => {
                     let alloc = tcx
                         .alloc_map
                         .lock()
                         .unwrap_memory(ptr.alloc_id);
-                    let offset = ptr.offset.bytes() as usize;
+                    let offset = ptr.offset.bytes().try_into().expect("too-large pointer offset");
                     let n = n as usize;
                     String::from_utf8(alloc.bytes[offset..(offset + n)].to_owned()).ok().map(Constant::Str)
                 },