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