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