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