@@ -10,7 +10,7 @@ use rustc::hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisito
1010use rustc:: hir:: * ;
1111use rustc:: lint:: { in_external_macro, LateContext , LateLintPass , LintArray , LintContext , LintPass } ;
1212use rustc:: ty:: layout:: LayoutOf ;
13- use rustc:: ty:: { self , Ty , TyCtxt , TypeckTables } ;
13+ use rustc:: ty:: { self , InferTy , Ty , TyCtxt , TypeckTables } ;
1414use rustc:: { declare_tool_lint, lint_array} ;
1515use rustc_errors:: Applicability ;
1616use rustc_target:: spec:: abi:: Abi ;
@@ -1150,13 +1150,41 @@ fn is_c_void(tcx: TyCtxt<'_, '_, '_>, ty: Ty<'_>) -> bool {
11501150 false
11511151}
11521152
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+
11531163impl < ' a , ' tcx > LateLintPass < ' a , ' tcx > for CastPass {
11541164 fn check_expr ( & mut self , cx : & LateContext < ' a , ' tcx > , expr : & ' tcx Expr ) {
11551165 if let ExprKind :: Cast ( ref ex, _) = expr. node {
11561166 let ( cast_from, cast_to) = ( cx. tables . expr_ty ( ex) , cx. tables . expr_ty ( expr) ) ;
11571167 lint_fn_to_numeric_cast ( cx, expr, ex, cast_from, cast_to) ;
11581168 if let ExprKind :: Lit ( ref lit) = ex. node {
11591169 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+ }
11601188 match lit. node {
11611189 LitKind :: Int ( _, LitIntType :: Unsuffixed ) | LitKind :: FloatUnsuffixed ( _) => { } ,
11621190 _ => {
0 commit comments