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