1 //! lint when there is a large size difference between variants on an enum
5 use utils::{span_lint_and_then, snippet_opt};
6 use rustc::ty::layout::TargetDataLayout;
7 use rustc::ty::TypeFoldable;
8 use rustc::traits::Reveal;
10 /// **What it does:** Checks for large size differences between variants on `enum`s.
12 /// **Why is this bad?** Enum size is bounded by the largest variant. Having a large variant
13 /// can penalize the memory layout of that enum.
15 /// **Known problems:** None.
25 pub LARGE_ENUM_VARIANT,
27 "large size difference between variants on an enum"
31 pub struct LargeEnumVariant {
32 maximum_size_difference_allowed: u64,
35 impl LargeEnumVariant {
36 pub fn new(maximum_size_difference_allowed: u64) -> Self {
37 LargeEnumVariant { maximum_size_difference_allowed: maximum_size_difference_allowed }
41 impl LintPass for LargeEnumVariant {
42 fn get_lints(&self) -> LintArray {
43 lint_array!(LARGE_ENUM_VARIANT)
47 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeEnumVariant {
48 fn check_item(&mut self, cx: &LateContext, item: &Item) {
49 let did = cx.tcx.hir.local_def_id(item.id);
50 if let ItemEnum(ref def, _) = item.node {
51 let ty = cx.tcx.item_type(did);
52 let adt = ty.ty_adt_def().expect("already checked whether this is an enum");
54 let mut smallest_variant: Option<(_, _)> = None;
55 let mut largest_variant: Option<(_, _)> = None;
57 for (i, variant) in adt.variants.iter().enumerate() {
58 let data_layout = TargetDataLayout::parse(cx.sess());
59 cx.tcx.infer_ctxt((), Reveal::All).enter(|infcx| {
60 let size: u64 = variant.fields
63 let ty = cx.tcx.item_type(f.did);
65 0 // we can't reason about generics, so we treat them as zero sized
68 .expect("layout should be computable for concrete type")
75 let grouped = (size, (i, variant));
77 update_if(&mut smallest_variant, grouped, |a, b| b.0 <= a.0);
78 update_if(&mut largest_variant, grouped, |a, b| b.0 >= a.0);
82 if let (Some(smallest), Some(largest)) = (smallest_variant, largest_variant) {
83 let difference = largest.0 - smallest.0;
85 if difference > self.maximum_size_difference_allowed {
86 let (i, variant) = largest.1;
88 span_lint_and_then(cx,
91 "large size difference between variants",
93 if variant.fields.len() == 1 {
94 let span = match def.variants[i].node.data {
95 VariantData::Struct(ref fields, _) |
96 VariantData::Tuple(ref fields, _) => fields[0].ty.span,
97 VariantData::Unit(_) => unreachable!(),
99 if let Some(snip) = snippet_opt(cx, span) {
100 db.span_suggestion(span,
101 "consider boxing the large fields to reduce the total size of the \
103 format!("Box<{}>", snip));
107 db.span_help(def.variants[i].span,
108 "consider boxing the large fields to reduce the total size of the enum");
117 fn update_if<T, F>(old: &mut Option<T>, new: T, f: F) where F: Fn(&T, &T) -> bool {
118 if let Some(ref mut val) = *old {