1 //! lint when there is a large size difference between variants on an enum
3 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use crate::rustc::{declare_tool_lint, lint_array};
5 use crate::rustc::hir::*;
6 use crate::utils::{snippet_opt, span_lint_and_then};
7 use crate::rustc::ty::layout::LayoutOf;
8 use crate::rustc_errors::Applicability;
10 /// **What it does:** Checks for large size differences between variants on
13 /// **Why is this bad?** Enum size is bounded by the largest variant. Having a
15 /// can penalize the memory layout of that enum.
17 /// **Known problems:** None.
26 declare_clippy_lint! {
27 pub LARGE_ENUM_VARIANT,
29 "large size difference between variants on an enum"
32 #[derive(Copy, Clone)]
33 pub struct LargeEnumVariant {
34 maximum_size_difference_allowed: u64,
37 impl LargeEnumVariant {
38 pub fn new(maximum_size_difference_allowed: u64) -> Self {
40 maximum_size_difference_allowed,
45 impl LintPass for LargeEnumVariant {
46 fn get_lints(&self) -> LintArray {
47 lint_array!(LARGE_ENUM_VARIANT)
51 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeEnumVariant {
52 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &Item) {
53 let did = cx.tcx.hir.local_def_id(item.id);
54 if let ItemKind::Enum(ref def, _) = item.node {
55 let ty = cx.tcx.type_of(did);
56 let adt = ty.ty_adt_def()
57 .expect("already checked whether this is an enum");
59 let mut smallest_variant: Option<(_, _)> = None;
60 let mut largest_variant: Option<(_, _)> = None;
62 for (i, variant) in adt.variants.iter().enumerate() {
63 let size: u64 = variant
67 let ty = cx.tcx.type_of(f.did);
68 // don't count generics by filtering out everything
69 // that does not have a layout
70 cx.layout_of(ty).ok().map(|l| l.size.bytes())
74 let grouped = (size, (i, variant));
76 update_if(&mut smallest_variant, grouped, |a, b| b.0 <= a.0);
77 update_if(&mut largest_variant, grouped, |a, b| b.0 >= a.0);
80 if let (Some(smallest), Some(largest)) = (smallest_variant, largest_variant) {
81 let difference = largest.0 - smallest.0;
83 if difference > self.maximum_size_difference_allowed {
84 let (i, variant) = largest.1;
90 "large size difference between variants",
92 if variant.fields.len() == 1 {
93 let span = match def.variants[i].node.data {
94 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => {
97 VariantData::Unit(_) => unreachable!(),
99 if let Some(snip) = snippet_opt(cx, span) {
100 db.span_suggestion_with_applicability(
102 "consider boxing the large fields to reduce the total size of the \
104 format!("Box<{}>", snip),
105 Applicability::Unspecified,
111 def.variants[i].span,
112 "consider boxing the large fields to reduce the total size of the enum",
122 fn update_if<T, F>(old: &mut Option<T>, new: T, f: F)
124 F: Fn(&T, &T) -> bool,
126 if let Some(ref mut val) = *old {