1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::is_hir_ty_cfg_dependant;
3 use if_chain::if_chain;
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};
8 use rustc_span::symbol::sym;
10 use super::CAST_PTR_ALIGNMENT;
12 pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx 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 {
24 if method_path.ident.name == sym!(cast);
25 if let Some(generic_args) = method_path.args;
26 if let [GenericArg::Type(cast_to)] = generic_args.args;
27 // There probably is no obvious reason to do this, just to be consistent with `as` cases.
28 if !is_hir_ty_cfg_dependant(cx, cast_to);
30 let (cast_from, cast_to) =
31 (cx.typeck_results().expr_ty(self_arg), cx.typeck_results().expr_ty(expr));
32 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
38 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
40 if let ty::RawPtr(from_ptr_ty) = &cast_from.kind();
41 if let ty::RawPtr(to_ptr_ty) = &cast_to.kind();
42 if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
43 if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
44 if from_layout.align.abi < to_layout.align.abi;
45 // with c_void, we inherently need to trust the user
46 if !is_c_void(cx, from_ptr_ty.ty);
47 // when casting from a ZST, we don't know enough to properly lint
48 if !from_layout.is_zst();
55 "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
58 from_layout.align.abi.bytes(),
59 to_layout.align.abi.bytes(),
66 /// Check if the given type is either `core::ffi::c_void` or
67 /// one of the platform specific `libc::<platform>::c_void` of libc.
68 fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
69 if let ty::Adt(adt, _) = ty.kind() {
70 let names = cx.get_def_path(adt.did);
75 if names[0] == sym::libc || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {