]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/large_enum_variant.rs
TyCtxt::map is now called TyCtxt::hir
[rust.git] / clippy_lints / src / large_enum_variant.rs
1 //! lint when there are large 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 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 variants on an enum"
28 }
29
30 #[derive(Copy,Clone)]
31 pub struct LargeEnumVariant {
32     maximum_variant_size_allowed: u64,
33 }
34
35 impl LargeEnumVariant {
36     pub fn new(maximum_variant_size_allowed: u64) -> Self {
37         LargeEnumVariant { maximum_variant_size_allowed: maximum_variant_size_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             for (i, variant) in adt.variants.iter().enumerate() {
54                 let data_layout = TargetDataLayout::parse(cx.sess());
55                 cx.tcx.infer_ctxt((), Reveal::All).enter(|infcx| {
56                     let size: u64 = variant.fields
57                         .iter()
58                         .map(|f| {
59                             let ty = cx.tcx.item_type(f.did);
60                             if ty.needs_subst() {
61                                 0 // we can't reason about generics, so we treat them as zero sized
62                             } else {
63                                 ty.layout(&infcx)
64                                     .expect("layout should be computable for concrete type")
65                                     .size(&data_layout)
66                                     .bytes()
67                             }
68                         })
69                         .sum();
70                     if size > self.maximum_variant_size_allowed {
71                         span_lint_and_then(cx,
72                                            LARGE_ENUM_VARIANT,
73                                            def.variants[i].span,
74                                            "large enum variant found",
75                                            |db| {
76                             if variant.fields.len() == 1 {
77                                 let span = match def.variants[i].node.data {
78                                     VariantData::Struct(ref fields, _) |
79                                     VariantData::Tuple(ref fields, _) => fields[0].ty.span,
80                                     VariantData::Unit(_) => unreachable!(),
81                                 };
82                                 if let Some(snip) = snippet_opt(cx, span) {
83                                     db.span_suggestion(span,
84                                                        "consider boxing the large fields to reduce the total size of \
85                                                         the enum",
86                                                        format!("Box<{}>", snip));
87                                     return;
88                                 }
89                             }
90                             db.span_help(def.variants[i].span,
91                                          "consider boxing the large fields to reduce the total size of the enum");
92                         });
93                     }
94                 });
95             }
96         }
97     }
98 }