]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/large_enum_variant.rs
Auto merge of #3597 - xfix:match-ergonomics, r=phansch
[rust.git] / clippy_lints / src / large_enum_variant.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 //! lint when there is a large size difference between variants on an enum
11
12 use crate::utils::{snippet_opt, span_lint_and_then};
13 use rustc::hir::*;
14 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use rustc::ty::layout::LayoutOf;
16 use rustc::{declare_tool_lint, lint_array};
17 use rustc_errors::Applicability;
18
19 /// **What it does:** Checks for large size differences between variants on
20 /// `enum`s.
21 ///
22 /// **Why is this bad?** Enum size is bounded by the largest variant. Having a
23 /// large variant
24 /// can penalize the memory layout of that enum.
25 ///
26 /// **Known problems:** None.
27 ///
28 /// **Example:**
29 /// ```rust
30 /// enum Test {
31 ///     A(i32),
32 ///     B([i32; 8000]),
33 /// }
34 /// ```
35 declare_clippy_lint! {
36     pub LARGE_ENUM_VARIANT,
37     perf,
38     "large size difference between variants on an enum"
39 }
40
41 #[derive(Copy, Clone)]
42 pub struct LargeEnumVariant {
43     maximum_size_difference_allowed: u64,
44 }
45
46 impl LargeEnumVariant {
47     pub fn new(maximum_size_difference_allowed: u64) -> Self {
48         Self {
49             maximum_size_difference_allowed,
50         }
51     }
52 }
53
54 impl LintPass for LargeEnumVariant {
55     fn get_lints(&self) -> LintArray {
56         lint_array!(LARGE_ENUM_VARIANT)
57     }
58 }
59
60 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeEnumVariant {
61     fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &Item) {
62         let did = cx.tcx.hir().local_def_id(item.id);
63         if let ItemKind::Enum(ref def, _) = item.node {
64             let ty = cx.tcx.type_of(did);
65             let adt = ty.ty_adt_def().expect("already checked whether this is an enum");
66
67             let mut smallest_variant: Option<(_, _)> = None;
68             let mut largest_variant: Option<(_, _)> = None;
69
70             for (i, variant) in adt.variants.iter().enumerate() {
71                 let size: u64 = variant
72                     .fields
73                     .iter()
74                     .filter_map(|f| {
75                         let ty = cx.tcx.type_of(f.did);
76                         // don't count generics by filtering out everything
77                         // that does not have a layout
78                         cx.layout_of(ty).ok().map(|l| l.size.bytes())
79                     })
80                     .sum();
81
82                 let grouped = (size, (i, variant));
83
84                 update_if(&mut smallest_variant, grouped, |a, b| b.0 <= a.0);
85                 update_if(&mut largest_variant, grouped, |a, b| b.0 >= a.0);
86             }
87
88             if let (Some(smallest), Some(largest)) = (smallest_variant, largest_variant) {
89                 let difference = largest.0 - smallest.0;
90
91                 if difference > self.maximum_size_difference_allowed {
92                     let (i, variant) = largest.1;
93
94                     span_lint_and_then(
95                         cx,
96                         LARGE_ENUM_VARIANT,
97                         def.variants[i].span,
98                         "large size difference between variants",
99                         |db| {
100                             if variant.fields.len() == 1 {
101                                 let span = match def.variants[i].node.data {
102                                     VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => {
103                                         fields[0].ty.span
104                                     },
105                                     VariantData::Unit(_) => unreachable!(),
106                                 };
107                                 if let Some(snip) = snippet_opt(cx, span) {
108                                     db.span_suggestion_with_applicability(
109                                         span,
110                                         "consider boxing the large fields to reduce the total size of the \
111                                          enum",
112                                         format!("Box<{}>", snip),
113                                         Applicability::MaybeIncorrect,
114                                     );
115                                     return;
116                                 }
117                             }
118                             db.span_help(
119                                 def.variants[i].span,
120                                 "consider boxing the large fields to reduce the total size of the enum",
121                             );
122                         },
123                     );
124                 }
125             }
126         }
127     }
128 }
129
130 fn update_if<T, F>(old: &mut Option<T>, new: T, f: F)
131 where
132     F: Fn(&T, &T) -> bool,
133 {
134     if let Some(ref mut val) = *old {
135         if f(val, &new) {
136             *val = new;
137         }
138     } else {
139         *old = Some(new);
140     }
141 }