]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/large_enum_variant.rs
Auto merge of #4551 - mikerite:fix-ice-reporting, r=llogiq
[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, impl_lint_pass};
8 use rustc_errors::Applicability;
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for large size differences between variants on
12     /// `enum`s.
13     ///
14     /// **Why is this bad?** Enum size is bounded by the largest variant. Having a
15     /// large variant
16     /// can penalize the memory layout of that enum.
17     ///
18     /// **Known problems:** None.
19     ///
20     /// **Example:**
21     /// ```rust
22     /// enum Test {
23     ///     A(i32),
24     ///     B([i32; 8000]),
25     /// }
26     /// ```
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_lint_pass!(LargeEnumVariant => [LARGE_ENUM_VARIANT]);
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.hir_id);
50         if let ItemKind::Enum(ref def, _) = item.node {
51             let ty = cx.tcx.type_of(did);
52             let adt = ty.ty_adt_def().expect("already checked whether this is an enum");
53
54             let mut smallest_variant: Option<(_, _)> = None;
55             let mut largest_variant: Option<(_, _)> = None;
56
57             for (i, variant) in adt.variants.iter().enumerate() {
58                 let size: u64 = variant
59                     .fields
60                     .iter()
61                     .filter_map(|f| {
62                         let ty = cx.tcx.type_of(f.did);
63                         // don't count generics by filtering out everything
64                         // that does not have a layout
65                         cx.layout_of(ty).ok().map(|l| l.size.bytes())
66                     })
67                     .sum();
68
69                 let grouped = (size, (i, variant));
70
71                 update_if(&mut smallest_variant, grouped, |a, b| b.0 <= a.0);
72                 update_if(&mut largest_variant, grouped, |a, b| b.0 >= a.0);
73             }
74
75             if let (Some(smallest), Some(largest)) = (smallest_variant, largest_variant) {
76                 let difference = largest.0 - smallest.0;
77
78                 if difference > self.maximum_size_difference_allowed {
79                     let (i, variant) = largest.1;
80
81                     span_lint_and_then(
82                         cx,
83                         LARGE_ENUM_VARIANT,
84                         def.variants[i].span,
85                         "large size difference between variants",
86                         |db| {
87                             if variant.fields.len() == 1 {
88                                 let span = match def.variants[i].data {
89                                     VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => {
90                                         fields[0].ty.span
91                                     },
92                                     VariantData::Unit(..) => unreachable!(),
93                                 };
94                                 if let Some(snip) = snippet_opt(cx, span) {
95                                     db.span_suggestion(
96                                         span,
97                                         "consider boxing the large fields to reduce the total size of the \
98                                          enum",
99                                         format!("Box<{}>", snip),
100                                         Applicability::MaybeIncorrect,
101                                     );
102                                     return;
103                                 }
104                             }
105                             db.span_help(
106                                 def.variants[i].span,
107                                 "consider boxing the large fields to reduce the total size of the enum",
108                             );
109                         },
110                     );
111                 }
112             }
113         }
114     }
115 }
116
117 fn update_if<T, F>(old: &mut Option<T>, new: T, f: F)
118 where
119     F: Fn(&T, &T) -> bool,
120 {
121     if let Some(ref mut val) = *old {
122         if f(val, &new) {
123             *val = new;
124         }
125     } else {
126         *old = Some(new);
127     }
128 }