1 use rustc_hir::{Expr, ExprKind, GenericArg};
2 use rustc_lint::LateContext;
3 use rustc_middle::ty::{self, Ty};
4 use rustc_span::symbol::sym;
5 use rustc_target::abi::LayoutOf;
7 use if_chain::if_chain;
9 use crate::utils::{is_hir_ty_cfg_dependant, span_lint};
11 use super::CAST_PTR_ALIGNMENT;
13 pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
14 if let ExprKind::Cast(ref cast_expr, cast_to) = expr.kind {
15 if is_hir_ty_cfg_dependant(cx, cast_to) {
18 let (cast_from, cast_to) = (
19 cx.typeck_results().expr_ty(cast_expr),
20 cx.typeck_results().expr_ty(expr),
22 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
23 } else if let ExprKind::MethodCall(method_path, _, args, _) = expr.kind {
25 if method_path.ident.name == sym!(cast);
26 if let Some(generic_args) = method_path.args;
27 if let [GenericArg::Type(cast_to)] = generic_args.args;
28 // There probably is no obvious reason to do this, just to be consistent with `as` cases.
29 if !is_hir_ty_cfg_dependant(cx, cast_to);
31 let (cast_from, cast_to) =
32 (cx.typeck_results().expr_ty(&args[0]), cx.typeck_results().expr_ty(expr));
33 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
39 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
41 if let ty::RawPtr(from_ptr_ty) = &cast_from.kind();
42 if let ty::RawPtr(to_ptr_ty) = &cast_to.kind();
43 if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
44 if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
45 if from_layout.align.abi < to_layout.align.abi;
46 // with c_void, we inherently need to trust the user
47 if !is_c_void(cx, from_ptr_ty.ty);
48 // when casting from a ZST, we don't know enough to properly lint
49 if !from_layout.is_zst();
56 "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
59 from_layout.align.abi.bytes(),
60 to_layout.align.abi.bytes(),
67 /// Check if the given type is either `core::ffi::c_void` or
68 /// one of the platform specific `libc::<platform>::c_void` of libc.
69 fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
70 if let ty::Adt(adt, _) = ty.kind() {
71 let names = cx.get_def_path(adt.did);
76 if names[0] == sym::libc || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {