1 //! lint when there is a large size difference between variants on an enum
3 use crate::utils::{snippet_opt, span_lint_and_then};
4 use rustc_errors::Applicability;
5 use rustc_hir::{Item, ItemKind, VariantData};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::ty::layout::LayoutOf;
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 declare_clippy_lint! {
11 /// **What it does:** Checks for large size differences between variants on
14 /// **Why is this bad?** Enum size is bounded by the largest variant. Having a
16 /// can penalize the memory layout of that enum.
18 /// **Known problems:** None.
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 {
39 pub fn new(maximum_size_difference_allowed: u64) -> Self {
41 maximum_size_difference_allowed,
46 impl_lint_pass!(LargeEnumVariant => [LARGE_ENUM_VARIANT]);
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");
55 let mut smallest_variant: Option<(_, _)> = None;
56 let mut largest_variant: Option<(_, _)> = None;
58 for (i, variant) in adt.variants.iter().enumerate() {
59 let size: u64 = variant
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())
70 let grouped = (size, (i, variant));
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);
76 if let (Some(smallest), Some(largest)) = (smallest_variant, largest_variant) {
77 let difference = largest.0 - smallest.0;
79 if difference > self.maximum_size_difference_allowed {
80 let (i, variant) = largest.1;
86 "large size difference between variants",
88 if variant.fields.len() == 1 {
89 let span = match def.variants[i].data {
90 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => {
93 VariantData::Unit(..) => unreachable!(),
95 if let Some(snip) = snippet_opt(cx, span) {
98 "consider boxing the large fields to reduce the total size of the \
100 format!("Box<{}>", snip),
101 Applicability::MaybeIncorrect,
107 def.variants[i].span,
108 "consider boxing the large fields to reduce the total size of the enum",
118 fn update_if<T, F>(old: &mut Option<T>, new: T, f: F)
120 F: Fn(&T, &T) -> bool,
122 if let Some(ref mut val) = *old {