@@ -1065,6 +1065,23 @@ declare_clippy_lint! {
10651065 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
10661066}
10671067
1068+ declare_clippy_lint ! {
1069+ /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1070+ /// zero-sized types
1071+ ///
1072+ /// **Why is this bad?** This is a no-op, and likely unintended
1073+ ///
1074+ /// **Known problems:** None
1075+ ///
1076+ /// **Example:**
1077+ /// ```ignore
1078+ /// unsafe { (&() as *const ()).offest(1) };
1079+ /// ```
1080+ pub ZST_OFFSET ,
1081+ correctness,
1082+ "Check for offset calculations on raw pointers to zero-sized types"
1083+ }
1084+
10681085declare_lint_pass ! ( Methods => [
10691086 OPTION_UNWRAP_USED ,
10701087 RESULT_UNWRAP_USED ,
@@ -1109,6 +1126,7 @@ declare_lint_pass!(Methods => [
11091126 SUSPICIOUS_MAP ,
11101127 UNINIT_ASSUMED_INIT ,
11111128 MANUAL_SATURATING_ARITHMETIC ,
1129+ ZST_OFFSET ,
11121130] ) ;
11131131
11141132impl < ' a , ' tcx > LateLintPass < ' a , ' tcx > for Methods {
@@ -1167,6 +1185,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
11671185 | [ "unwrap_or" , arith @ "checked_mul" ] => {
11681186 manual_saturating_arithmetic:: lint ( cx, expr, & arg_lists, & arith[ "checked_" . len ( ) ..] )
11691187 } ,
1188+ [ "add" ] | [ "offset" ] | [ "sub" ] | [ "wrapping_offset" ] | [ "wrapping_add" ] | [ "wrapping_sub" ] => {
1189+ check_pointer_offset ( cx, expr, arg_lists[ 0 ] )
1190+ } ,
11701191 _ => { } ,
11711192 }
11721193
@@ -3063,3 +3084,15 @@ fn contains_return(expr: &hir::Expr) -> bool {
30633084 visitor. visit_expr ( expr) ;
30643085 visitor. found
30653086}
3087+
3088+ fn check_pointer_offset ( cx : & LateContext < ' _ , ' _ > , expr : & hir:: Expr , args : & [ hir:: Expr ] ) {
3089+ if_chain ! {
3090+ if args. len( ) == 2 ;
3091+ if let ty:: RawPtr ( ty:: TypeAndMut { ref ty, .. } ) = cx. tables. expr_ty( & args[ 0 ] ) . kind;
3092+ if let Ok ( layout) = cx. tcx. layout_of( cx. param_env. and( ty) ) ;
3093+ if layout. is_zst( ) ;
3094+ then {
3095+ span_lint( cx, ZST_OFFSET , expr. span, "offset calculation on zero-sized value" ) ;
3096+ }
3097+ }
3098+ }
0 commit comments