]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/clippy_lints/src/default_union_representation.rs
bump version to 1.79.0+dfsg1-1~bpo12+pve2
[rustc.git] / src / tools / clippy / clippy_lints / src / default_union_representation.rs
CommitLineData
5099ac24 1use clippy_utils::diagnostics::span_lint_and_help;
781aab86 2use rustc_hir::{HirId, Item, ItemKind};
5099ac24
FG
3use rustc_lint::{LateContext, LateLintPass};
4use rustc_middle::ty::layout::LayoutOf;
781aab86 5use rustc_middle::ty::{self, FieldDef, GenericArg, List};
4b012472 6use rustc_session::declare_lint_pass;
5099ac24 7use rustc_span::sym;
5099ac24
FG
8
9declare_clippy_lint! {
10 /// ### What it does
11 /// Displays a warning when a union is declared with the default representation (without a `#[repr(C)]` attribute).
12 ///
13 /// ### Why is this bad?
14 /// Unions in Rust have unspecified layout by default, despite many people thinking that they
15 /// lay out each field at the start of the union (like C does). That is, there are no guarantees
16 /// about the offset of the fields for unions with multiple non-ZST fields without an explicitly
17 /// specified layout. These cases may lead to undefined behavior in unsafe blocks.
18 ///
19 /// ### Example
ed00b5ec 20 /// ```no_run
5099ac24
FG
21 /// union Foo {
22 /// a: i32,
23 /// b: u32,
24 /// }
25 ///
26 /// fn main() {
27 /// let _x: u32 = unsafe {
923072b8 28 /// Foo { a: 0_i32 }.b // Undefined behavior: `b` is allowed to be padding
5099ac24
FG
29 /// };
30 /// }
31 /// ```
32 /// Use instead:
ed00b5ec 33 /// ```no_run
5099ac24
FG
34 /// #[repr(C)]
35 /// union Foo {
36 /// a: i32,
37 /// b: u32,
38 /// }
39 ///
40 /// fn main() {
41 /// let _x: u32 = unsafe {
923072b8 42 /// Foo { a: 0_i32 }.b // Now defined behavior, this is just an i32 -> u32 transmute
5099ac24
FG
43 /// };
44 /// }
45 /// ```
46 #[clippy::version = "1.60.0"]
47 pub DEFAULT_UNION_REPRESENTATION,
48 restriction,
49 "unions without a `#[repr(C)]` attribute"
50}
51declare_lint_pass!(DefaultUnionRepresentation => [DEFAULT_UNION_REPRESENTATION]);
52
53impl<'tcx> LateLintPass<'tcx> for DefaultUnionRepresentation {
54 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
781aab86
FG
55 if !item.span.from_expansion()
56 && is_union_with_two_non_zst_fields(cx, item)
57 && !has_c_repr_attr(cx, item.hir_id())
58 {
5099ac24
FG
59 span_lint_and_help(
60 cx,
61 DEFAULT_UNION_REPRESENTATION,
62 item.span,
63 "this union has the default representation",
64 None,
e8be2606 65 format!(
5099ac24 66 "consider annotating `{}` with `#[repr(C)]` to explicitly specify memory layout",
49aad941 67 cx.tcx.def_path_str(item.owner_id)
5099ac24
FG
68 ),
69 );
70 }
71 }
72}
73
74/// Returns true if the given item is a union with at least two non-ZST fields.
781aab86
FG
75/// (ZST fields having an arbitrary offset is completely inconsequential, and
76/// if there is only one field left after ignoring ZST fields then the offset
77/// of that field does not matter either.)
c0240ec0 78fn is_union_with_two_non_zst_fields<'tcx>(cx: &LateContext<'tcx>, item: &Item<'tcx>) -> bool {
781aab86
FG
79 if let ItemKind::Union(..) = &item.kind
80 && let ty::Adt(adt_def, args) = cx.tcx.type_of(item.owner_id).instantiate_identity().kind()
81 {
82 adt_def.all_fields().filter(|f| !is_zst(cx, f, args)).count() >= 2
5099ac24
FG
83 } else {
84 false
85 }
86}
87
781aab86
FG
88fn is_zst<'tcx>(cx: &LateContext<'tcx>, field: &FieldDef, args: &'tcx List<GenericArg<'tcx>>) -> bool {
89 let ty = field.ty(cx.tcx, args);
5099ac24
FG
90 if let Ok(layout) = cx.layout_of(ty) {
91 layout.is_zst()
92 } else {
93 false
94 }
95}
96
97fn has_c_repr_attr(cx: &LateContext<'_>, hir_id: HirId) -> bool {
98 cx.tcx.hir().attrs(hir_id).iter().any(|attr| {
99 if attr.has_name(sym::repr) {
100 if let Some(items) = attr.meta_item_list() {
101 for item in items {
102 if item.is_word() && matches!(item.name_or_empty(), sym::C) {
103 return true;
104 }
105 }
106 }
107 }
108 false
109 })
110}