]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/large_enum_variant.rs
Rollup merge of #87528 - :stack_overflow_obsd, r=joshtriplett
[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_with_applicability;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Item, ItemKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::lint::in_external_macro;
9 use rustc_middle::ty::layout::LayoutOf;
10 use rustc_session::{declare_tool_lint, impl_lint_pass};
11 use rustc_span::source_map::Span;
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// Checks for large size differences between variants on
16     /// `enum`s.
17     ///
18     /// ### Why is this bad?
19     /// Enum size is bounded by the largest variant. Having a
20     /// large variant can penalize the memory layout of that enum.
21     ///
22     /// ### Known problems
23     /// This lint obviously cannot take the distribution of
24     /// variants in your running program into account. It is possible that the
25     /// smaller variants make up less than 1% of all instances, in which case
26     /// the overhead is negligible and the boxing is counter-productive. Always
27     /// measure the change this lint suggests.
28     ///
29     /// ### Example
30     /// ```rust
31     /// // Bad
32     /// enum Test {
33     ///     A(i32),
34     ///     B([i32; 8000]),
35     /// }
36     ///
37     /// // Possibly better
38     /// enum Test2 {
39     ///     A(i32),
40     ///     B(Box<[i32; 8000]>),
41     /// }
42     /// ```
43     pub LARGE_ENUM_VARIANT,
44     perf,
45     "large size difference between variants on an enum"
46 }
47
48 #[derive(Copy, Clone)]
49 pub struct LargeEnumVariant {
50     maximum_size_difference_allowed: u64,
51 }
52
53 impl LargeEnumVariant {
54     #[must_use]
55     pub fn new(maximum_size_difference_allowed: u64) -> Self {
56         Self {
57             maximum_size_difference_allowed,
58         }
59     }
60 }
61
62 struct FieldInfo {
63     ind: usize,
64     size: u64,
65 }
66
67 struct VariantInfo {
68     ind: usize,
69     size: u64,
70     fields_size: Vec<FieldInfo>,
71 }
72
73 impl_lint_pass!(LargeEnumVariant => [LARGE_ENUM_VARIANT]);
74
75 impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant {
76     fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
77         if in_external_macro(cx.tcx.sess, item.span) {
78             return;
79         }
80         if let ItemKind::Enum(ref def, _) = item.kind {
81             let ty = cx.tcx.type_of(item.def_id);
82             let adt = ty.ty_adt_def().expect("already checked whether this is an enum");
83             if adt.variants.len() <= 1 {
84                 return;
85             }
86             let mut variants_size: Vec<VariantInfo> = adt
87                 .variants
88                 .iter()
89                 .enumerate()
90                 .map(|(i, variant)| {
91                     let mut fields_size = Vec::new();
92                     let size: u64 = variant
93                         .fields
94                         .iter()
95                         .enumerate()
96                         .filter_map(|(i, f)| {
97                             let ty = cx.tcx.type_of(f.did);
98                             // don't count generics by filtering out everything
99                             // that does not have a layout
100                             cx.layout_of(ty).ok().map(|l| {
101                                 let size = l.size.bytes();
102                                 fields_size.push(FieldInfo { ind: i, size });
103                                 size
104                             })
105                         })
106                         .sum();
107                     VariantInfo {
108                         ind: i,
109                         size,
110                         fields_size,
111                     }
112                 })
113                 .collect();
114
115             variants_size.sort_by(|a, b| (b.size.cmp(&a.size)));
116
117             let mut difference = variants_size[0].size - variants_size[1].size;
118             if difference > self.maximum_size_difference_allowed {
119                 let help_text = "consider boxing the large fields to reduce the total size of the enum";
120                 span_lint_and_then(
121                     cx,
122                     LARGE_ENUM_VARIANT,
123                     def.variants[variants_size[0].ind].span,
124                     "large size difference between variants",
125                     |diag| {
126                         diag.span_label(
127                             def.variants[variants_size[0].ind].span,
128                             &format!("this variant is {} bytes", variants_size[0].size),
129                         );
130                         diag.span_note(
131                             def.variants[variants_size[1].ind].span,
132                             &format!("and the second-largest variant is {} bytes:", variants_size[1].size),
133                         );
134
135                         let fields = def.variants[variants_size[0].ind].data.fields();
136                         variants_size[0].fields_size.sort_by(|a, b| (a.size.cmp(&b.size)));
137                         let mut applicability = Applicability::MaybeIncorrect;
138                         let sugg: Vec<(Span, String)> = variants_size[0]
139                             .fields_size
140                             .iter()
141                             .rev()
142                             .map_while(|val| {
143                                 if difference > self.maximum_size_difference_allowed {
144                                     difference = difference.saturating_sub(val.size);
145                                     Some((
146                                         fields[val.ind].ty.span,
147                                         format!(
148                                             "Box<{}>",
149                                             snippet_with_applicability(
150                                                 cx,
151                                                 fields[val.ind].ty.span,
152                                                 "..",
153                                                 &mut applicability
154                                             )
155                                             .into_owned()
156                                         ),
157                                     ))
158                                 } else {
159                                     None
160                                 }
161                             })
162                             .collect();
163
164                         if !sugg.is_empty() {
165                             diag.multipart_suggestion(help_text, sugg, Applicability::MaybeIncorrect);
166                             return;
167                         }
168
169                         diag.span_help(def.variants[variants_size[0].ind].span, help_text);
170                     },
171                 );
172             }
173         }
174     }
175 }