]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/large_enum_variant.rs
Change large_enum_variant to lint against size differences rather than size
[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};
6 use rustc::ty::layout::TargetDataLayout;
7 use rustc::ty::TypeFoldable;
8 use rustc::traits::Reveal;
9
10 /// **What it does:** Checks for large size differences between variants on `enum`s.
11 ///
12 /// **Why is this bad?** Enum size is bounded by the largest variant. Having a 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         LargeEnumVariant { 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.item_type(did);
52             let adt = ty.ty_adt_def().expect("already checked whether this is an enum");
53
54             let mut sizes = Vec::new();
55             let mut variants = Vec::new();
56
57             for variant in &adt.variants {
58                 let data_layout = TargetDataLayout::parse(cx.sess());
59                 cx.tcx.infer_ctxt((), Reveal::All).enter(|infcx| {
60                     let size: u64 = variant.fields
61                         .iter()
62                         .map(|f| {
63                             let ty = cx.tcx.item_type(f.did);
64                             if ty.needs_subst() {
65                                 0 // we can't reason about generics, so we treat them as zero sized
66                             } else {
67                                 ty.layout(&infcx)
68                                     .expect("layout should be computable for concrete type")
69                                     .size(&data_layout)
70                                     .bytes()
71                             }
72                         })
73                         .sum();
74
75                     sizes.push(size);
76                     variants.push(variant);
77                 });
78             }
79
80             let mut grouped = sizes.into_iter().zip(variants.into_iter().enumerate()).collect::<Vec<_>>();
81
82             grouped.sort_by_key(|g| g.0);
83
84             let smallest_variant = grouped.first();
85             let largest_variant = grouped.last();
86
87             if let (Some(smallest), Some(largest)) = (smallest_variant, largest_variant) {
88                 let difference = largest.0 - smallest.0;
89
90                 if difference > self.maximum_size_difference_allowed {
91                     let (i, variant) = largest.1;
92
93                     span_lint_and_then(cx,
94                                        LARGE_ENUM_VARIANT,
95                                        def.variants[i].span,
96                                        "large size difference between variants",
97                                        |db| {
98                         if variant.fields.len() == 1 {
99                             let span = match def.variants[i].node.data {
100                                 VariantData::Struct(ref fields, _) |
101                                 VariantData::Tuple(ref fields, _) => fields[0].ty.span,
102                                 VariantData::Unit(_) => unreachable!(),
103                             };
104                             if let Some(snip) = snippet_opt(cx, span) {
105                                 db.span_suggestion(span,
106                                                    "consider boxing the large fields to reduce the total size of the \
107                                                     enum",
108                                                    format!("Box<{}>", snip));
109                                 return;
110                             }
111                         }
112                         db.span_help(def.variants[i].span,
113                                      "consider boxing the large fields to reduce the total size of the enum");
114                     });
115                 }
116             }
117
118         }
119     }
120 }