@@ -1265,3 +1265,54 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1265
1265
}
1266
1266
}
1267
1267
}
1268
+
1269
+
1270
+ /// Lint for casts from types other than `usize` or `isize` to raw pointers
1271
+ pub struct IntoToRawPtrCast ;
1272
+
1273
+ declare_lint ! {
1274
+ pub INT_TO_RAW_PTR_CAST ,
1275
+ Deny ,
1276
+ "cast from signed int other than `isize` to raw pointer"
1277
+ }
1278
+
1279
+ impl LintPass for IntoToRawPtrCast {
1280
+ fn get_lints ( & self ) -> LintArray {
1281
+ lint_array ! ( INT_TO_RAW_PTR_CAST )
1282
+ }
1283
+ }
1284
+
1285
+ impl < ' a , ' tcx > LateLintPass < ' a , ' tcx > for IntoToRawPtrCast {
1286
+ fn check_expr ( & mut self , cx : & LateContext , expr : & hir:: Expr ) {
1287
+ if let hir:: ExprCast ( ref base, _) = expr. node {
1288
+ let base_ty = cx. tables . expr_ty ( base) ;
1289
+ let target_ty = cx. tables . expr_ty ( expr) ;
1290
+ if let ty:: TyRawPtr ( ..) = target_ty. sty {
1291
+ match base_ty. sty {
1292
+ ty:: TyInt ( ast:: IntTy :: Is ) |
1293
+ ty:: TyInt ( ast:: IntTy :: I128 ) |
1294
+ ty:: TyInt ( ast:: IntTy :: I64 ) => return ,
1295
+ ty:: TyInt ( ast:: IntTy :: I32 ) => {
1296
+ if cx. tcx . data_layout . pointer_size . bytes ( ) <= 4 {
1297
+ return ;
1298
+ }
1299
+ } ,
1300
+ ty:: TyInt ( ast:: IntTy :: I16 ) => {
1301
+ if cx. tcx . data_layout . pointer_size . bytes ( ) <= 2 {
1302
+ return ;
1303
+ }
1304
+ } ,
1305
+ // these we report
1306
+ ty:: TyInt ( _) => { } ,
1307
+ // only int casts are relevant
1308
+ _ => return ,
1309
+ }
1310
+ cx. span_lint (
1311
+ INT_TO_RAW_PTR_CAST ,
1312
+ expr. span ,
1313
+ & format ! ( "cast from `{}` to raw pointer" , base_ty) ,
1314
+ ) ;
1315
+ }
1316
+ }
1317
+ }
1318
+ }
0 commit comments