Auto merge of #12617 - y21:issue-12616, r=Alexendoo

avoid an ICE in `ptr_as_ptr` when getting the def_id of a local

Fixes #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
This commit is contained in:
bors 2024-04-02 13:40:00 +00:00
commit f9f854f428
4 changed files with 34 additions and 1 deletions

View File

@ -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) {

View File

@ -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::<()>();
}

View File

@ -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 ();
}

View File

@ -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