]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/large_enum_variant.rs
Auto merge of #4920 - lily-commure:fix-unnecessary-filter-map-docs, r=phansch
[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 crate::utils::{snippet_opt, span_lint_and_then};
4 use rustc::hir::*;
5 use rustc::impl_lint_pass;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::ty::layout::LayoutOf;
8 use rustc_errors::Applicability;
9 use rustc_session::declare_tool_lint;
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
17     /// can penalize the memory layout of that enum.
18     ///
19     /// **Known problems:** None.
20     ///
21     /// **Example:**
22     /// ```rust
23     /// enum Test {
24     ///     A(i32),
25     ///     B([i32; 8000]),
26     /// }
27     /// ```
28     pub LARGE_ENUM_VARIANT,
29     perf,
30     "large size difference between variants on an enum"
31 }
32
33 #[derive(Copy, Clone)]
34 pub struct LargeEnumVariant {
35     maximum_size_difference_allowed: u64,
36 }
37
38 impl LargeEnumVariant {
39     #[must_use]
40     pub fn new(maximum_size_difference_allowed: u64) -> Self {
41         Self {
42             maximum_size_difference_allowed,
43         }
44     }
45 }
46
47 impl_lint_pass!(LargeEnumVariant => [LARGE_ENUM_VARIANT]);
48
49 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeEnumVariant {
50     fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &Item) {
51         let did = cx.tcx.hir().local_def_id(item.hir_id);
52         if let ItemKind::Enum(ref def, _) = item.kind {
53             let ty = cx.tcx.type_of(did);
54             let adt = ty.ty_adt_def().expect("already checked whether this is an enum");
55
56             let mut smallest_variant: Option<(_, _)> = None;
57             let mut largest_variant: Option<(_, _)> = None;
58
59             for (i, variant) in adt.variants.iter().enumerate() {
60                 let size: u64 = variant
61                     .fields
62                     .iter()
63                     .filter_map(|f| {
64                         let ty = cx.tcx.type_of(f.did);
65                         // don't count generics by filtering out everything
66                         // that does not have a layout
67                         cx.layout_of(ty).ok().map(|l| l.size.bytes())
68                     })
69                     .sum();
70
71                 let grouped = (size, (i, variant));
72
73                 update_if(&mut smallest_variant, grouped, |a, b| b.0 <= a.0);
74                 update_if(&mut largest_variant, grouped, |a, b| b.0 >= a.0);
75             }
76
77             if let (Some(smallest), Some(largest)) = (smallest_variant, largest_variant) {
78                 let difference = largest.0 - smallest.0;
79
80                 if difference > self.maximum_size_difference_allowed {
81                     let (i, variant) = largest.1;
82
83                     span_lint_and_then(
84                         cx,
85                         LARGE_ENUM_VARIANT,
86                         def.variants[i].span,
87                         "large size difference between variants",
88                         |db| {
89                             if variant.fields.len() == 1 {
90                                 let span = match def.variants[i].data {
91                                     VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => {
92                                         fields[0].ty.span
93                                     },
94                                     VariantData::Unit(..) => unreachable!(),
95                                 };
96                                 if let Some(snip) = snippet_opt(cx, span) {
97                                     db.span_suggestion(
98                                         span,
99                                         "consider boxing the large fields to reduce the total size of the \
100                                          enum",
101                                         format!("Box<{}>", snip),
102                                         Applicability::MaybeIncorrect,
103                                     );
104                                     return;
105                                 }
106                             }
107                             db.span_help(
108                                 def.variants[i].span,
109                                 "consider boxing the large fields to reduce the total size of the enum",
110                             );
111                         },
112                     );
113                 }
114             }
115         }
116     }
117 }
118
119 fn update_if<T, F>(old: &mut Option<T>, new: T, f: F)
120 where
121     F: Fn(&T, &T) -> bool,
122 {
123     if let Some(ref mut val) = *old {
124         if f(val, &new) {
125             *val = new;
126         }
127     } else {
128         *old = Some(new);
129     }
130 }