]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/large_enum_variant.rs
Merge pull request #1959 from DarkEld3r/1884-borrowed-box-any
[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::hir::*;
5 use utils::{span_lint_and_then, snippet_opt, type_size};
6 use rustc::ty::TypeFoldable;
7
8 /// **What it does:** Checks for large size differences between variants on
9 /// `enum`s.
10 ///
11 /// **Why is this bad?** Enum size is bounded by the largest variant. Having a
12 /// large variant
13 /// can penalize the memory layout of that enum.
14 ///
15 /// **Known problems:** None.
16 ///
17 /// **Example:**
18 /// ```rust
19 /// enum Test {
20 ///    A(i32),
21 ///    B([i32; 8000]),
22 /// }
23 /// ```
24 declare_lint! {
25     pub LARGE_ENUM_VARIANT,
26     Warn,
27     "large size difference between variants on an enum"
28 }
29
30 #[derive(Copy, Clone)]
31 pub struct LargeEnumVariant {
32     maximum_size_difference_allowed: u64,
33 }
34
35 impl LargeEnumVariant {
36     pub fn new(maximum_size_difference_allowed: u64) -> Self {
37         Self { maximum_size_difference_allowed: maximum_size_difference_allowed }
38     }
39 }
40
41 impl LintPass for LargeEnumVariant {
42     fn get_lints(&self) -> LintArray {
43         lint_array!(LARGE_ENUM_VARIANT)
44     }
45 }
46
47 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeEnumVariant {
48     fn check_item(&mut self, cx: &LateContext, item: &Item) {
49         let did = cx.tcx.hir.local_def_id(item.id);
50         if let ItemEnum(ref def, _) = item.node {
51             let ty = cx.tcx.type_of(did);
52             let adt = ty.ty_adt_def().expect(
53                 "already checked whether this is an enum",
54             );
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                     .map(|f| {
64                         let ty = cx.tcx.type_of(f.did);
65                         if ty.needs_subst() {
66                             0 // we can't reason about generics, so we treat them as zero sized
67                         } else {
68                             type_size(cx, ty).expect("size should be computable for concrete type")
69                         }
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, _) |
94                                     VariantData::Tuple(ref fields, _) => fields[0].ty.span,
95                                     VariantData::Unit(_) => unreachable!(),
96                                 };
97                                 if let Some(snip) = snippet_opt(cx, span) {
98                                     db.span_suggestion(
99                                         span,
100                                         "consider boxing the large fields to reduce the total size of the \
101                                                     enum",
102                                         format!("Box<{}>", snip),
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
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 }