1 use clippy_utils
::diagnostics
::span_lint
;
2 use clippy_utils
::ty
::is_c_void
;
3 use clippy_utils
::{get_parent_expr, is_hir_ty_cfg_dependant}
;
4 use rustc_hir
::{Expr, ExprKind, GenericArg}
;
5 use rustc_lint
::LateContext
;
6 use rustc_middle
::ty
::layout
::LayoutOf
;
7 use rustc_middle
::ty
::{self, Ty}
;
10 use super::CAST_PTR_ALIGNMENT
;
12 pub(super) fn check(cx
: &LateContext
<'_
>, expr
: &Expr
<'_
>) {
13 if let ExprKind
::Cast(cast_expr
, cast_to
) = expr
.kind
{
14 if is_hir_ty_cfg_dependant(cx
, cast_to
) {
17 let (cast_from
, cast_to
) = (
18 cx
.typeck_results().expr_ty(cast_expr
),
19 cx
.typeck_results().expr_ty(expr
),
21 lint_cast_ptr_alignment(cx
, expr
, cast_from
, cast_to
);
22 } else if let ExprKind
::MethodCall(method_path
, self_arg
, ..) = &expr
.kind
{
23 if method_path
.ident
.name
== sym
!(cast
)
24 && let Some(generic_args
) = method_path
.args
25 && let [GenericArg
::Type(cast_to
)] = generic_args
.args
26 // There probably is no obvious reason to do this, just to be consistent with `as` cases.
27 && !is_hir_ty_cfg_dependant(cx
, cast_to
)
29 let (cast_from
, cast_to
) = (cx
.typeck_results().expr_ty(self_arg
), cx
.typeck_results().expr_ty(expr
));
30 lint_cast_ptr_alignment(cx
, expr
, cast_from
, cast_to
);
35 fn lint_cast_ptr_alignment
<'tcx
>(cx
: &LateContext
<'tcx
>, expr
: &Expr
<'_
>, cast_from
: Ty
<'tcx
>, cast_to
: Ty
<'tcx
>) {
36 if let ty
::RawPtr(from_ptr_ty
) = &cast_from
.kind()
37 && let ty
::RawPtr(to_ptr_ty
) = &cast_to
.kind()
38 && let Ok(from_layout
) = cx
.layout_of(from_ptr_ty
.ty
)
39 && let Ok(to_layout
) = cx
.layout_of(to_ptr_ty
.ty
)
40 && from_layout
.align
.abi
< to_layout
.align
.abi
41 // with c_void, we inherently need to trust the user
42 && !is_c_void(cx
, from_ptr_ty
.ty
)
43 // when casting from a ZST, we don't know enough to properly lint
44 && !from_layout
.is_zst()
45 && !is_used_as_unaligned(cx
, expr
)
52 "casting from `{cast_from}` to a more-strictly-aligned pointer (`{cast_to}`) ({} < {} bytes)",
53 from_layout
.align
.abi
.bytes(),
54 to_layout
.align
.abi
.bytes(),
60 fn is_used_as_unaligned(cx
: &LateContext
<'_
>, e
: &Expr
<'_
>) -> bool
{
61 let Some(parent
) = get_parent_expr(cx
, e
) else {
65 ExprKind
::MethodCall(name
, self_arg
, ..) if self_arg
.hir_id
== e
.hir_id
=> {
66 if matches
!(name
.ident
.as_str(), "read_unaligned" | "write_unaligned")
67 && let Some(def_id
) = cx
.typeck_results().type_dependent_def_id(parent
.hir_id
)
68 && let Some(def_id
) = cx
.tcx
.impl_of_method(def_id
)
69 && cx
.tcx
.type_of(def_id
).instantiate_identity().is_unsafe_ptr()
76 ExprKind
::Call(func
, [arg
, ..]) if arg
.hir_id
== e
.hir_id
=> {
77 if let ExprKind
::Path(path
) = &func
.kind
78 && let Some(def_id
) = cx
.qpath_res(path
, func
.hir_id
).opt_def_id()
80 cx
.tcx
.get_diagnostic_name(def_id
),
82 sym
::ptr_write_unaligned
83 | sym
::ptr_read_unaligned
84 | sym
::intrinsics_unaligned_volatile_load
85 | sym
::intrinsics_unaligned_volatile_store