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