Skip to content

Commit

Permalink
Auto merge of rust-lang#12617 - y21:issue-12616, r=Alexendoo
Browse files Browse the repository at this point in the history
avoid an ICE in `ptr_as_ptr` when getting the def_id of a local

Fixes rust-lang#12616

`Res::def_id` can panic, so avoid calling it in favor of `opt_def_id`, so we can gracefully handle resolutions that don't have a `DefId` (e.g. local variables) and get a false negative in the worst case, rather than an ICE

changelog: Fix ICE in [`ptr_as_ptr`] when the cast expression is a function call to a local variable
  • Loading branch information
bors committed Apr 2, 2024
2 parents 3b1b654 + e575f05 commit f9f854f
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 1 deletion.
2 changes: 1 addition & 1 deletion clippy_lints/src/casts/ptr_as_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, msrv: &Msrv) {
// we omit following `cast`:
let omit_cast = if let ExprKind::Call(func, []) = cast_expr.kind
&& let ExprKind::Path(ref qpath @ QPath::Resolved(None, path)) = func.kind
&& let Some(method_defid) = path.res.opt_def_id()
{
let method_defid = path.res.def_id();
if cx.tcx.is_diagnostic_item(sym::ptr_null, method_defid) {
OmitFollowedCastReason::Null(qpath)
} else if cx.tcx.is_diagnostic_item(sym::ptr_null_mut, method_defid) {
Expand Down
7 changes: 7 additions & 0 deletions tests/ui/crashes/ice-12616.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#![warn(clippy::ptr_as_ptr)]
#![allow(clippy::unnecessary_operation, clippy::unnecessary_cast)]

fn main() {
let s = std::ptr::null::<()>;
s().cast::<()>();
}
7 changes: 7 additions & 0 deletions tests/ui/crashes/ice-12616.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#![warn(clippy::ptr_as_ptr)]
#![allow(clippy::unnecessary_operation, clippy::unnecessary_cast)]

fn main() {
let s = std::ptr::null::<()>;
s() as *const ();
}
19 changes: 19 additions & 0 deletions tests/ui/crashes/ice-12616.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
error: `as` casting between raw pointers without changing its mutability
--> tests/ui/crashes/ice-12616.rs:6:5
|
LL | s() as *const ();
| ^^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `s().cast::<()>()`
|
= note: `-D clippy::ptr-as-ptr` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::ptr_as_ptr)]`

error: `as` casting between raw pointers without changing its mutability
--> tests/ui/crashes/ice-12616.rs:6:5
|
LL | s() as *const ();
| ^^^^^^^^^^^^^^^^ help: try `pointer::cast`, a safer alternative: `s().cast::<()>()`
|
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`

error: aborting due to 2 previous errors

0 comments on commit f9f854f

Please sign in to comment.