@@ -10,7 +10,7 @@ use rustc::hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisito
10
10
use rustc:: hir:: * ;
11
11
use rustc:: lint:: { in_external_macro, LateContext , LateLintPass , LintArray , LintContext , LintPass } ;
12
12
use rustc:: ty:: layout:: LayoutOf ;
13
- use rustc:: ty:: { self , Ty , TyCtxt , TypeckTables } ;
13
+ use rustc:: ty:: { self , InferTy , Ty , TyCtxt , TypeckTables } ;
14
14
use rustc:: { declare_tool_lint, lint_array} ;
15
15
use rustc_errors:: Applicability ;
16
16
use rustc_target:: spec:: abi:: Abi ;
@@ -1150,13 +1150,41 @@ fn is_c_void(tcx: TyCtxt<'_, '_, '_>, ty: Ty<'_>) -> bool {
1150
1150
false
1151
1151
}
1152
1152
1153
+ /// Returns the mantissa bits wide of a fp type.
1154
+ /// Will return 0 if the type is not a fp
1155
+ fn fp_ty_mantissa_nbits ( typ : Ty < ' _ > ) -> u32 {
1156
+ match typ. sty {
1157
+ ty:: Float ( FloatTy :: F32 ) => 23 ,
1158
+ ty:: Float ( FloatTy :: F64 ) | ty:: Infer ( InferTy :: FloatVar ( _) ) => 52 ,
1159
+ _ => 0 ,
1160
+ }
1161
+ }
1162
+
1153
1163
impl < ' a , ' tcx > LateLintPass < ' a , ' tcx > for CastPass {
1154
1164
fn check_expr ( & mut self , cx : & LateContext < ' a , ' tcx > , expr : & ' tcx Expr ) {
1155
1165
if let ExprKind :: Cast ( ref ex, _) = expr. node {
1156
1166
let ( cast_from, cast_to) = ( cx. tables . expr_ty ( ex) , cx. tables . expr_ty ( expr) ) ;
1157
1167
lint_fn_to_numeric_cast ( cx, expr, ex, cast_from, cast_to) ;
1158
1168
if let ExprKind :: Lit ( ref lit) = ex. node {
1159
1169
use syntax:: ast:: { LitIntType , LitKind } ;
1170
+ if let LitKind :: Int ( n, _) = lit. node {
1171
+ if cast_to. is_fp ( ) {
1172
+ let from_nbits = 128 - n. leading_zeros ( ) ;
1173
+ let to_nbits = fp_ty_mantissa_nbits ( cast_to) ;
1174
+ if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits {
1175
+ span_lint_and_sugg (
1176
+ cx,
1177
+ UNNECESSARY_CAST ,
1178
+ expr. span ,
1179
+ & format ! ( "casting integer literal to {} is unnecessary" , cast_to) ,
1180
+ "try" ,
1181
+ format ! ( "{}_{}" , n, cast_to) ,
1182
+ Applicability :: MachineApplicable ,
1183
+ ) ;
1184
+ return ;
1185
+ }
1186
+ }
1187
+ }
1160
1188
match lit. node {
1161
1189
LitKind :: Int ( _, LitIntType :: Unsuffixed ) | LitKind :: FloatUnsuffixed ( _) => { } ,
1162
1190
_ => {
0 commit comments