rust/clippy_lints/src/trailing_empty_array.rs
Nicholas Nethercote 6222a735b0 Move hir::Item::ident into hir::ItemKind.
`hir::Item` has an `ident` field.

- It's always non-empty for these item kinds: `ExternCrate`, `Static`,
  `Const`, `Fn`, `Macro`, `Mod`, `TyAlias`, `Enum`, `Struct`, `Union`,
  Trait`, TraitAalis`.

- It's always empty for these item kinds: `ForeignMod`, `GlobalAsm`,
  `Impl`.

- For `Use`, it is non-empty for `UseKind::Single` and empty for
  `UseKind::{Glob,ListStem}`.

All of this is quite non-obvious; the only documentation is a single
comment saying "The name might be a dummy name in case of anonymous
items". Some sites that handle items check for an empty ident, some
don't. This is a very C-like way of doing things, but this is Rust, we
have sum types, we can do this properly and never forget to check for
the exceptional case and never YOLO possibly empty identifiers (or
possibly dummy spans) around and hope that things will work out.

The commit is large but it's mostly obvious plumbing work. Some notable
things.

- A similar transformation makes sense for `ast::Item`, but this is
  already a big change. That can be done later.

- Lots of assertions are added to item lowering to ensure that
  identifiers are empty/non-empty as expected. These will be removable
  when `ast::Item` is done later.

- `ItemKind::Use` doesn't get an `Ident`, but `UseKind::Single` does.

- `lower_use_tree` is significantly simpler. No more confusing `&mut
  Ident` to deal with.

- `ItemKind::ident` is a new method, it returns an `Option<Ident>`. It's
  used with `unwrap` in a few places; sometimes it's hard to tell
  exactly which item kinds might occur. None of these unwraps fail on
  the test suite. It's conceivable that some might fail on alternative
  input. We can deal with those if/when they happen.

- In `trait_path` the `find_map`/`if let` is replaced with a loop, and
  things end up much clearer that way.

- `named_span` no longer checks for an empty name; instead the call site
  now checks for a missing identifier if necessary.

- `maybe_inline_local` doesn't need the `glob` argument, it can be
  computed in-function from the `renamed` argument.

- `arbitrary_source_item_ordering::check_mod` had a big `if` statement
  that was just getting the ident from the item kinds that had one. It
  could be mostly replaced by a single call to the new `ItemKind::ident`
  method.

- `ItemKind` grows from 56 to 64 bytes, but `Item` stays the same size,
  and that's what matters, because `ItemKind` only occurs within `Item`.
2025-03-18 06:29:50 +11:00

74 lines
2.6 KiB
Rust

use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::{has_repr_attr, is_in_test};
use rustc_hir::{Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use rustc_session::declare_lint_pass;
declare_clippy_lint! {
/// ### What it does
/// Displays a warning when a struct with a trailing zero-sized array is declared without a `repr` attribute.
///
/// ### Why is this bad?
/// 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 conjunction with manual allocation to make it easy to compute the offset of the array). Either way, `#[repr(C)]` (or another `repr` attribute) is needed.
///
/// ### Example
/// ```no_run
/// struct RarelyUseful {
/// some_field: u32,
/// last: [u32; 0],
/// }
/// ```
///
/// Use instead:
/// ```no_run
/// #[repr(C)]
/// struct MoreOftenUseful {
/// some_field: usize,
/// last: [u32; 0],
/// }
/// ```
#[clippy::version = "1.58.0"]
pub TRAILING_EMPTY_ARRAY,
nursery,
"struct with a trailing zero-sized array but without `#[repr(C)]` or another `repr` attribute"
}
declare_lint_pass!(TrailingEmptyArray => [TRAILING_EMPTY_ARRAY]);
impl<'tcx> LateLintPass<'tcx> for TrailingEmptyArray {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
if is_struct_with_trailing_zero_sized_array(cx, item)
&& !has_repr_attr(cx, item.hir_id())
&& !is_in_test(cx.tcx, item.hir_id())
{
span_lint_and_help(
cx,
TRAILING_EMPTY_ARRAY,
item.span,
"trailing zero-sized array in a struct which is not marked with a `repr` attribute",
None,
format!(
"consider annotating `{}` with `#[repr(C)]` or another `repr` attribute",
cx.tcx.def_path_str(item.owner_id)
),
);
}
}
}
fn is_struct_with_trailing_zero_sized_array<'tcx>(cx: &LateContext<'tcx>, item: &Item<'tcx>) -> bool {
if let ItemKind::Struct(_, data, _) = &item.kind
&& let Some(last_field) = data.fields().last()
&& let field_ty = cx.tcx.normalize_erasing_regions(
cx.typing_env(),
cx.tcx.type_of(last_field.def_id).instantiate_identity(),
)
&& let ty::Array(_, array_len) = *field_ty.kind()
&& let Some(0) = array_len.try_to_target_usize(cx.tcx)
{
true
} else {
false
}
}