]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/large_enum_variant.rs
Auto merge of #76071 - khyperia:configurable_to_immediate, r=eddyb
[rust.git] / src / tools / clippy / clippy_lints / src / large_enum_variant.rs
1 //! lint when there is a large size difference between variants on an enum
2
3 use crate::utils::{snippet_opt, span_lint_and_then};
4 use rustc_errors::Applicability;
5 use rustc_hir::{Item, ItemKind, VariantData};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_tool_lint, impl_lint_pass};
8 use rustc_target::abi::LayoutOf;
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for large size differences between variants on
12     /// `enum`s.
13     ///
14     /// **Why is this bad?** Enum size is bounded by the largest variant. Having a
15     /// large variant can penalize the memory layout of that enum.
16     ///
17     /// **Known problems:** This lint obviously cannot take the distribution of
18     /// variants in your running program into account. It is possible that the
19     /// smaller variants make up less than 1% of all instances, in which case
20     /// the overhead is negligible and the boxing is counter-productive. Always
21     /// measure the change this lint suggests.
22     ///
23     /// **Example:**
24     ///
25     /// ```rust
26     /// // Bad
27     /// enum Test {
28     ///     A(i32),
29     ///     B([i32; 8000]),
30     /// }
31     ///
32     /// // Possibly better
33     /// enum Test2 {
34     ///     A(i32),
35     ///     B(Box<[i32; 8000]>),
36     /// }
37     /// ```
38     pub LARGE_ENUM_VARIANT,
39     perf,
40     "large size difference between variants on an enum"
41 }
42
43 #[derive(Copy, Clone)]
44 pub struct LargeEnumVariant {
45     maximum_size_difference_allowed: u64,
46 }
47
48 impl LargeEnumVariant {
49     #[must_use]
50     pub fn new(maximum_size_difference_allowed: u64) -> Self {
51         Self {
52             maximum_size_difference_allowed,
53         }
54     }
55 }
56
57 impl_lint_pass!(LargeEnumVariant => [LARGE_ENUM_VARIANT]);
58
59 impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant {
60     fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
61         let did = cx.tcx.hir().local_def_id(item.hir_id);
62         if let ItemKind::Enum(ref def, _) = item.kind {
63             let ty = cx.tcx.type_of(did);
64             let adt = ty.ty_adt_def().expect("already checked whether this is an enum");
65
66             let mut largest_variant: Option<(_, _)> = None;
67             let mut second_variant: Option<(_, _)> = None;
68
69             for (i, variant) in adt.variants.iter().enumerate() {
70                 let size: u64 = variant
71                     .fields
72                     .iter()
73                     .filter_map(|f| {
74                         let ty = cx.tcx.type_of(f.did);
75                         // don't count generics by filtering out everything
76                         // that does not have a layout
77                         cx.layout_of(ty).ok().map(|l| l.size.bytes())
78                     })
79                     .sum();
80
81                 let grouped = (size, (i, variant));
82
83                 if grouped.0 >= largest_variant.map_or(0, |x| x.0) {
84                     second_variant = largest_variant;
85                     largest_variant = Some(grouped);
86                 }
87             }
88
89             if let (Some(largest), Some(second)) = (largest_variant, second_variant) {
90                 let difference = largest.0 - second.0;
91
92                 if difference > self.maximum_size_difference_allowed {
93                     let (i, variant) = largest.1;
94
95                     let help_text = "consider boxing the large fields to reduce the total size of the enum";
96                     span_lint_and_then(
97                         cx,
98                         LARGE_ENUM_VARIANT,
99                         def.variants[i].span,
100                         "large size difference between variants",
101                         |diag| {
102                             diag.span_label(
103                                 def.variants[(largest.1).0].span,
104                                 &format!("this variant is {} bytes", largest.0),
105                             );
106                             diag.span_note(
107                                 def.variants[(second.1).0].span,
108                                 &format!("and the second-largest variant is {} bytes:", second.0),
109                             );
110                             if variant.fields.len() == 1 {
111                                 let span = match def.variants[i].data {
112                                     VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => {
113                                         fields[0].ty.span
114                                     },
115                                     VariantData::Unit(..) => unreachable!(),
116                                 };
117                                 if let Some(snip) = snippet_opt(cx, span) {
118                                     diag.span_suggestion(
119                                         span,
120                                         help_text,
121                                         format!("Box<{}>", snip),
122                                         Applicability::MaybeIncorrect,
123                                     );
124                                     return;
125                                 }
126                             }
127                             diag.span_help(def.variants[i].span, help_text);
128                         },
129                     );
130                 }
131             }
132         }
133     }
134 }