Wrap transmutes_expressible_as_ptr_casts suggestions in parentheses

This commit is contained in:
Alex Macleod 2023-03-23 18:58:10 +00:00
parent be01b983c4
commit ecc201253e
4 changed files with 30 additions and 5 deletions

View file

@ -2,8 +2,9 @@ use super::utils::check_cast;
use super::TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::sugg::Sugg;
use rustc_ast::ExprPrecedence;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_hir::{Expr, Node};
use rustc_lint::LateContext;
use rustc_middle::ty::{cast::CastKind, Ty};
@ -19,7 +20,7 @@ pub(super) fn check<'tcx>(
) -> bool {
use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast};
let mut app = Applicability::MachineApplicable;
let sugg = match check_cast(cx, e, from_ty, to_ty) {
let mut sugg = match check_cast(cx, e, from_ty, to_ty) {
Some(PtrPtrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast) => {
Sugg::hir_with_context(cx, arg, e.span.ctxt(), "..", &mut app)
.as_ty(to_ty.to_string())
@ -39,6 +40,12 @@ pub(super) fn check<'tcx>(
_ => return false,
};
if let Node::Expr(parent) = cx.tcx.hir().get_parent(e.hir_id)
&& parent.precedence().order() > ExprPrecedence::Cast.order()
{
sugg = format!("({sugg})");
}
span_lint_and_sugg(
cx,
TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,

View file

@ -4,7 +4,7 @@
// would otherwise be responsible for
#![warn(clippy::useless_transmute)]
#![warn(clippy::transmute_ptr_to_ptr)]
#![allow(dead_code, unused_unsafe, clippy::borrow_as_ptr)]
#![allow(unused, clippy::borrow_as_ptr)]
use std::mem::{size_of, transmute};
@ -77,3 +77,9 @@ fn cannot_be_expressed_as_pointer_cast(in_param: Single) -> Pair {
unsafe { transmute::<Single, Pair>(in_param) }
}
fn issue_10449() {
fn f() {}
let _x: u8 = unsafe { *(f as *const u8) };
}

View file

@ -4,7 +4,7 @@
// would otherwise be responsible for
#![warn(clippy::useless_transmute)]
#![warn(clippy::transmute_ptr_to_ptr)]
#![allow(dead_code, unused_unsafe, clippy::borrow_as_ptr)]
#![allow(unused, clippy::borrow_as_ptr)]
use std::mem::{size_of, transmute};
@ -77,3 +77,9 @@ fn cannot_be_expressed_as_pointer_cast(in_param: Single) -> Pair {
unsafe { transmute::<Single, Pair>(in_param) }
}
fn issue_10449() {
fn f() {}
let _x: u8 = unsafe { *std::mem::transmute::<fn(), *const u8>(f) };
}

View file

@ -58,5 +58,11 @@ error: transmute from a reference to a pointer
LL | unsafe { transmute::<&[i32; 1], *const u8>(in_param) }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `in_param as *const [i32; 1] as *const u8`
error: aborting due to 9 previous errors
error: transmute from `fn()` to `*const u8` which could be expressed as a pointer cast instead
--> $DIR/transmutes_expressible_as_ptr_casts.rs:84:28
|
LL | let _x: u8 = unsafe { *std::mem::transmute::<fn(), *const u8>(f) };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `(f as *const u8)`
error: aborting due to 10 previous errors