]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/large_enum_variant.rs
Rustup to rust-lang/rust#67806
[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::lint::{LateContext, LateLintPass};
5 use rustc::ty::layout::LayoutOf;
6 use rustc_errors::Applicability;
7 use rustc_hir::*;
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
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     #[must_use]
39     pub fn new(maximum_size_difference_allowed: u64) -> Self {
40         Self {
41             maximum_size_difference_allowed,
42         }
43     }
44 }
45
46 impl_lint_pass!(LargeEnumVariant => [LARGE_ENUM_VARIANT]);
47
48 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeEnumVariant {
49     fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &Item<'_>) {
50         let did = cx.tcx.hir().local_def_id(item.hir_id);
51         if let ItemKind::Enum(ref def, _) = item.kind {
52             let ty = cx.tcx.type_of(did);
53             let adt = ty.ty_adt_def().expect("already checked whether this is an enum");
54
55             let mut smallest_variant: Option<(_, _)> = None;
56             let mut largest_variant: Option<(_, _)> = None;
57
58             for (i, variant) in adt.variants.iter().enumerate() {
59                 let size: u64 = variant
60                     .fields
61                     .iter()
62                     .filter_map(|f| {
63                         let ty = cx.tcx.type_of(f.did);
64                         // don't count generics by filtering out everything
65                         // that does not have a layout
66                         cx.layout_of(ty).ok().map(|l| l.size.bytes())
67                     })
68                     .sum();
69
70                 let grouped = (size, (i, variant));
71
72                 update_if(&mut smallest_variant, grouped, |a, b| b.0 <= a.0);
73                 update_if(&mut largest_variant, grouped, |a, b| b.0 >= a.0);
74             }
75
76             if let (Some(smallest), Some(largest)) = (smallest_variant, largest_variant) {
77                 let difference = largest.0 - smallest.0;
78
79                 if difference > self.maximum_size_difference_allowed {
80                     let (i, variant) = largest.1;
81
82                     span_lint_and_then(
83                         cx,
84                         LARGE_ENUM_VARIANT,
85                         def.variants[i].span,
86                         "large size difference between variants",
87                         |db| {
88                             if variant.fields.len() == 1 {
89                                 let span = match def.variants[i].data {
90                                     VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => {
91                                         fields[0].ty.span
92                                     },
93                                     VariantData::Unit(..) => unreachable!(),
94                                 };
95                                 if let Some(snip) = snippet_opt(cx, span) {
96                                     db.span_suggestion(
97                                         span,
98                                         "consider boxing the large fields to reduce the total size of the \
99                                          enum",
100                                         format!("Box<{}>", snip),
101                                         Applicability::MaybeIncorrect,
102                                     );
103                                     return;
104                                 }
105                             }
106                             db.span_help(
107                                 def.variants[i].span,
108                                 "consider boxing the large fields to reduce the total size of the enum",
109                             );
110                         },
111                     );
112                 }
113             }
114         }
115     }
116 }
117
118 fn update_if<T, F>(old: &mut Option<T>, new: T, f: F)
119 where
120     F: Fn(&T, &T) -> bool,
121 {
122     if let Some(ref mut val) = *old {
123         if f(val, &new) {
124             *val = new;
125         }
126     } else {
127         *old = Some(new);
128     }
129 }