Skip to content

Commit a6b72d3

Browse files
committed
Auto merge of #6542 - rail-rain:ptr_as_ptr, r=flip1995
Add a new lint `ptr_as_ptr` This PR adds a new lint `ptr_as_ptr` which checks for `as` casts between raw pointers without changing its mutability and suggest replacing it with `pointer::cast`. Closes #5890. Open question: should this lint be `pedantic` or `style`? I set it `pedantic` for now because the original post suggests using it, but I think the lint also fits well to `style`. --- changelog: New lint `ptr_as_ptr`
2 parents 311186b + dfa5d7e commit a6b72d3

File tree

6 files changed

+247
-4
lines changed

6 files changed

+247
-4
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -2141,6 +2141,7 @@ Released 2018-09-13
21412141
[`print_with_newline`]: https://rust-lang.github.io/rust-clippy/master/index.html#print_with_newline
21422142
[`println_empty_string`]: https://rust-lang.github.io/rust-clippy/master/index.html#println_empty_string
21432143
[`ptr_arg`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_arg
2144+
[`ptr_as_ptr`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_as_ptr
21442145
[`ptr_eq`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_eq
21452146
[`ptr_offset_with_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_offset_with_cast
21462147
[`pub_enum_variant_names`]: https://rust-lang.github.io/rust-clippy/master/index.html#pub_enum_variant_names

clippy_lints/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -912,6 +912,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
912912
&types::LET_UNIT_VALUE,
913913
&types::LINKEDLIST,
914914
&types::OPTION_OPTION,
915+
&types::PTR_AS_PTR,
915916
&types::RC_BUFFER,
916917
&types::REDUNDANT_ALLOCATION,
917918
&types::TYPE_COMPLEXITY,
@@ -1222,6 +1223,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12221223
store.register_late_pass(|| box strings::StringToString);
12231224
store.register_late_pass(|| box zero_sized_map_values::ZeroSizedMapValues);
12241225
store.register_late_pass(|| box vec_init_then_push::VecInitThenPush::default());
1226+
store.register_late_pass(move || box types::PtrAsPtr::new(msrv));
12251227

12261228
store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![
12271229
LintId::of(&arithmetic::FLOAT_ARITHMETIC),
@@ -1348,6 +1350,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
13481350
LintId::of(&types::LET_UNIT_VALUE),
13491351
LintId::of(&types::LINKEDLIST),
13501352
LintId::of(&types::OPTION_OPTION),
1353+
LintId::of(&types::PTR_AS_PTR),
13511354
LintId::of(&unicode::NON_ASCII_LITERAL),
13521355
LintId::of(&unicode::UNICODE_NOT_NFC),
13531356
LintId::of(&unnested_or_patterns::UNNESTED_OR_PATTERNS),

clippy_lints/src/types.rs

+97-4
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ use rustc_lint::{LateContext, LateLintPass, LintContext};
1919
use rustc_middle::hir::map::Map;
2020
use rustc_middle::lint::in_external_macro;
2121
use rustc_middle::ty::TypeFoldable;
22-
use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TyS, TypeckResults};
22+
use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TyS, TypeAndMut, TypeckResults};
23+
use rustc_semver::RustcVersion;
2324
use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
2425
use rustc_span::hygiene::{ExpnKind, MacroKind};
2526
use rustc_span::source_map::Span;
@@ -30,11 +31,13 @@ use rustc_typeck::hir_ty_to_ty;
3031

3132
use crate::consts::{constant, Constant};
3233
use crate::utils::paths;
34+
use crate::utils::sugg::Sugg;
3335
use crate::utils::{
3436
clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_type_diagnostic_item,
35-
last_path_segment, match_def_path, match_path, method_chain_args, multispan_sugg, numeric_literal::NumericLiteral,
36-
qpath_res, reindent_multiline, sext, snippet, snippet_opt, snippet_with_applicability, snippet_with_macro_callsite,
37-
span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, unsext,
37+
last_path_segment, match_def_path, match_path, meets_msrv, method_chain_args, multispan_sugg,
38+
numeric_literal::NumericLiteral, qpath_res, reindent_multiline, sext, snippet, snippet_opt,
39+
snippet_with_applicability, snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg,
40+
span_lint_and_then, unsext,
3841
};
3942

4043
declare_clippy_lint! {
@@ -2878,3 +2881,93 @@ impl<'tcx> LateLintPass<'tcx> for RefToMut {
28782881
}
28792882
}
28802883
}
2884+
2885+
const PTR_AS_PTR_MSRV: RustcVersion = RustcVersion::new(1, 38, 0);
2886+
2887+
declare_clippy_lint! {
2888+
/// **What it does:**
2889+
/// Checks for `as` casts between raw pointers without changing its mutability,
2890+
/// namely `*const T` to `*const U` and `*mut T` to `*mut U`.
2891+
///
2892+
/// **Why is this bad?**
2893+
/// Though `as` casts between raw pointers is not terrible, `pointer::cast` is safer because
2894+
/// it cannot accidentally change the pointer's mutability nor cast the pointer to other types like `usize`.
2895+
///
2896+
/// **Known problems:** None.
2897+
///
2898+
/// **Example:**
2899+
///
2900+
/// ```rust
2901+
/// let ptr: *const u32 = &42_u32;
2902+
/// let mut_ptr: *mut u32 = &mut 42_u32;
2903+
/// let _ = ptr as *const i32;
2904+
/// let _ = mut_ptr as *mut i32;
2905+
/// ```
2906+
/// Use instead:
2907+
/// ```rust
2908+
/// let ptr: *const u32 = &42_u32;
2909+
/// let mut_ptr: *mut u32 = &mut 42_u32;
2910+
/// let _ = ptr.cast::<i32>();
2911+
/// let _ = mut_ptr.cast::<i32>();
2912+
/// ```
2913+
pub PTR_AS_PTR,
2914+
pedantic,
2915+
"casting using `as` from and to raw pointers that doesn't change its mutability, where `pointer::cast` could take the place of `as`"
2916+
}
2917+
2918+
pub struct PtrAsPtr {
2919+
msrv: Option<RustcVersion>,
2920+
}
2921+
2922+
impl PtrAsPtr {
2923+
#[must_use]
2924+
pub fn new(msrv: Option<RustcVersion>) -> Self {
2925+
Self { msrv }
2926+
}
2927+
}
2928+
2929+
impl_lint_pass!(PtrAsPtr => [PTR_AS_PTR]);
2930+
2931+
impl<'tcx> LateLintPass<'tcx> for PtrAsPtr {
2932+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2933+
if !meets_msrv(self.msrv.as_ref(), &PTR_AS_PTR_MSRV) {
2934+
return;
2935+
}
2936+
2937+
if expr.span.from_expansion() {
2938+
return;
2939+
}
2940+
2941+
if_chain! {
2942+
if let ExprKind::Cast(cast_expr, cast_to_hir_ty) = expr.kind;
2943+
let (cast_from, cast_to) = (cx.typeck_results().expr_ty(cast_expr), cx.typeck_results().expr_ty(expr));
2944+
if let ty::RawPtr(TypeAndMut { mutbl: from_mutbl, .. }) = cast_from.kind();
2945+
if let ty::RawPtr(TypeAndMut { ty: to_pointee_ty, mutbl: to_mutbl }) = cast_to.kind();
2946+
if matches!((from_mutbl, to_mutbl),
2947+
(Mutability::Not, Mutability::Not) | (Mutability::Mut, Mutability::Mut));
2948+
// The `U` in `pointer::cast` have to be `Sized`
2949+
// as explained here: https://github.com/rust-lang/rust/issues/60602.
2950+
if to_pointee_ty.is_sized(cx.tcx.at(expr.span), cx.param_env);
2951+
then {
2952+
let mut applicability = Applicability::MachineApplicable;
2953+
let cast_expr_sugg = Sugg::hir_with_applicability(cx, cast_expr, "_", &mut applicability);
2954+
let turbofish = match &cast_to_hir_ty.kind {
2955+
TyKind::Infer => Cow::Borrowed(""),
2956+
TyKind::Ptr(mut_ty) if matches!(mut_ty.ty.kind, TyKind::Infer) => Cow::Borrowed(""),
2957+
_ => Cow::Owned(format!("::<{}>", to_pointee_ty)),
2958+
};
2959+
span_lint_and_sugg(
2960+
cx,
2961+
PTR_AS_PTR,
2962+
expr.span,
2963+
"`as` casting between raw pointers without changing its mutability",
2964+
"try `pointer::cast`, a safer alternative",
2965+
format!("{}.cast{}()", cast_expr_sugg.maybe_par(), turbofish),
2966+
applicability,
2967+
);
2968+
}
2969+
}
2970+
}
2971+
2972+
extract_msrv_attr!(LateContext);
2973+
}

tests/ui/ptr_as_ptr.fixed

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// run-rustfix
2+
3+
#![warn(clippy::ptr_as_ptr)]
4+
#![feature(custom_inner_attributes)]
5+
6+
fn main() {
7+
let ptr: *const u32 = &42_u32;
8+
let mut_ptr: *mut u32 = &mut 42_u32;
9+
10+
let _ = ptr.cast::<i32>();
11+
let _ = mut_ptr.cast::<i32>();
12+
13+
// Make sure the lint can handle the difference in their operator precedences.
14+
unsafe {
15+
let ptr_ptr: *const *const u32 = &ptr;
16+
let _ = (*ptr_ptr).cast::<i32>();
17+
}
18+
19+
// Changes in mutability. Do not lint this.
20+
let _ = ptr as *mut i32;
21+
let _ = mut_ptr as *const i32;
22+
23+
// `pointer::cast` cannot perform unsized coercions unlike `as`. Do not lint this.
24+
let ptr_of_array: *const [u32; 4] = &[1, 2, 3, 4];
25+
let _ = ptr_of_array as *const [u32];
26+
let _ = ptr_of_array as *const dyn std::fmt::Debug;
27+
28+
// Ensure the lint doesn't produce unnecessary turbofish for inferred types.
29+
let _: *const i32 = ptr.cast();
30+
let _: *mut i32 = mut_ptr.cast();
31+
}
32+
33+
fn _msrv_1_37() {
34+
#![clippy::msrv = "1.37"]
35+
let ptr: *const u32 = &42_u32;
36+
let mut_ptr: *mut u32 = &mut 42_u32;
37+
38+
// `pointer::cast` was stabilized in 1.38. Do not lint this
39+
let _ = ptr as *const i32;
40+
let _ = mut_ptr as *mut i32;
41+
}
42+
43+
fn _msrv_1_38() {
44+
#![clippy::msrv = "1.38"]
45+
let ptr: *const u32 = &42_u32;
46+
let mut_ptr: *mut u32 = &mut 42_u32;
47+
48+
let _ = ptr.cast::<i32>();
49+
let _ = mut_ptr.cast::<i32>();
50+
}

tests/ui/ptr_as_ptr.rs

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// run-rustfix
2+
3+
#![warn(clippy::ptr_as_ptr)]
4+
#![feature(custom_inner_attributes)]
5+
6+
fn main() {
7+
let ptr: *const u32 = &42_u32;
8+
let mut_ptr: *mut u32 = &mut 42_u32;
9+
10+
let _ = ptr as *const i32;
11+
let _ = mut_ptr as *mut i32;
12+
13+
// Make sure the lint can handle the difference in their operator precedences.
14+
unsafe {
15+
let ptr_ptr: *const *const u32 = &ptr;
16+
let _ = *ptr_ptr as *const i32;
17+
}
18+
19+
// Changes in mutability. Do not lint this.
20+
let _ = ptr as *mut i32;
21+
let _ = mut_ptr as *const i32;
22+
23+
// `pointer::cast` cannot perform unsized coercions unlike `as`. Do not lint this.
24+
let ptr_of_array: *const [u32; 4] = &[1, 2, 3, 4];
25+
let _ = ptr_of_array as *const [u32];
26+
let _ = ptr_of_array as *const dyn std::fmt::Debug;
27+
28+
// Ensure the lint doesn't produce unnecessary turbofish for inferred types.
29+
let _: *const i32 = ptr as *const _;
30+
let _: *mut i32 = mut_ptr as _;
31+
}
32+
33+
fn _msrv_1_37() {
34+
#![clippy::msrv = "1.37"]
35+
let ptr: *const u32 = &42_u32;
36+
let mut_ptr: *mut u32 = &mut 42_u32;
37+
38+
// `pointer::cast` was stabilized in 1.38. Do not lint this
39+
let _ = ptr as *const i32;
40+
let _ = mut_ptr as *mut i32;
41+
}
42+
43+
fn _msrv_1_38() {
44+
#![clippy::msrv = "1.38"]
45+
let ptr: *const u32 = &42_u32;
46+
let mut_ptr: *mut u32 = &mut 42_u32;
47+
48+
let _ = ptr as *const i32;
49+
let _ = mut_ptr as *mut i32;
50+
}

tests/ui/ptr_as_ptr.stderr

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
error: `as` casting between raw pointers without changing its mutability
2+
--> $DIR/ptr_as_ptr.rs:10:13
3+
|
4+
LL | let _ = ptr as *const i32;
5+
| ^^^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `ptr.cast::<i32>()`
6+
|
7+
= note: `-D clippy::ptr-as-ptr` implied by `-D warnings`
8+
9+
error: `as` casting between raw pointers without changing its mutability
10+
--> $DIR/ptr_as_ptr.rs:11:13
11+
|
12+
LL | let _ = mut_ptr as *mut i32;
13+
| ^^^^^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `mut_ptr.cast::<i32>()`
14+
15+
error: `as` casting between raw pointers without changing its mutability
16+
--> $DIR/ptr_as_ptr.rs:16:17
17+
|
18+
LL | let _ = *ptr_ptr as *const i32;
19+
| ^^^^^^^^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `(*ptr_ptr).cast::<i32>()`
20+
21+
error: `as` casting between raw pointers without changing its mutability
22+
--> $DIR/ptr_as_ptr.rs:29:25
23+
|
24+
LL | let _: *const i32 = ptr as *const _;
25+
| ^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `ptr.cast()`
26+
27+
error: `as` casting between raw pointers without changing its mutability
28+
--> $DIR/ptr_as_ptr.rs:30:23
29+
|
30+
LL | let _: *mut i32 = mut_ptr as _;
31+
| ^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `mut_ptr.cast()`
32+
33+
error: `as` casting between raw pointers without changing its mutability
34+
--> $DIR/ptr_as_ptr.rs:48:13
35+
|
36+
LL | let _ = ptr as *const i32;
37+
| ^^^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `ptr.cast::<i32>()`
38+
39+
error: `as` casting between raw pointers without changing its mutability
40+
--> $DIR/ptr_as_ptr.rs:49:13
41+
|
42+
LL | let _ = mut_ptr as *mut i32;
43+
| ^^^^^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `mut_ptr.cast::<i32>()`
44+
45+
error: aborting due to 7 previous errors
46+

0 commit comments

Comments
 (0)