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