1 use clippy_utils::diagnostics::span_lint_and_help;
2 use rustc_hir::{HirId, Item, ItemKind};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_middle::ty::Const;
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 /// Displays a warning when a struct with a trailing zero-sized array is declared without a `repr` attribute.
12 /// ### Why is this bad?
13 /// Zero-sized arrays aren't very useful in Rust itself, so such a struct is likely being created to pass to C code or in some other situation where control over memory layout matters (for example, in conjuction with manual allocation to make it easy to compute the offset of the array). Either way, `#[repr(C)]` (or another `repr` attribute) is needed.
17 /// struct RarelyUseful {
26 /// struct MoreOftenUseful {
27 /// some_field: usize,
31 #[clippy::version = "1.58.0"]
32 pub TRAILING_EMPTY_ARRAY,
34 "struct with a trailing zero-sized array but without `#[repr(C)]` or another `repr` attribute"
36 declare_lint_pass!(TrailingEmptyArray => [TRAILING_EMPTY_ARRAY]);
38 impl<'tcx> LateLintPass<'tcx> for TrailingEmptyArray {
39 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
40 if is_struct_with_trailing_zero_sized_array(cx, item) && !has_repr_attr(cx, item.hir_id()) {
45 "trailing zero-sized array in a struct which is not marked with a `repr` attribute",
48 "consider annotating `{}` with `#[repr(C)]` or another `repr` attribute",
49 cx.tcx.def_path_str(item.def_id.to_def_id())
56 fn is_struct_with_trailing_zero_sized_array(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
58 // First check if last field is an array
59 if let ItemKind::Struct(data, _) = &item.kind;
60 if let Some(last_field) = data.fields().last();
61 if let rustc_hir::TyKind::Array(_, length) = last_field.ty.kind;
63 // Then check if that that array zero-sized
64 let length_ldid = cx.tcx.hir().local_def_id(length.hir_id);
65 let length = Const::from_anon_const(cx.tcx, length_ldid);
66 let length = length.try_eval_usize(cx.tcx, cx.param_env);
67 if let Some(length) = length;
76 fn has_repr_attr(cx: &LateContext<'_>, hir_id: HirId) -> bool {
77 cx.tcx.hir().attrs(hir_id).iter().any(|attr| attr.has_name(sym::repr))