1 //! lint when there are large variants on an enum
5 use utils::span_help_and_lint;
6 use rustc::ty::layout::TargetDataLayout;
7 use rustc::ty::TypeFoldable;
8 use rustc::traits::Reveal;
10 /// **What it does:** Checks for large variants on enums.
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 variants on an enum"
31 pub struct LargeEnumVariant {
32 maximum_variant_size_allowed: u64,
35 impl LargeEnumVariant {
36 pub fn new(maximum_variant_size_allowed: u64) -> Self {
37 LargeEnumVariant { maximum_variant_size_allowed: maximum_variant_size_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.map.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");
53 for (i, variant) in adt.variants.iter().enumerate() {
54 let data_layout = TargetDataLayout::parse(cx.sess());
55 cx.tcx.infer_ctxt((), Reveal::All).enter(|infcx| {
56 let size: u64 = variant.fields
59 let ty = cx.tcx.item_type(f.did);
61 0 // we can't reason about generics, so we treat them as zero sized
64 .expect("layout should be computable for concrete type")
70 if size > self.maximum_variant_size_allowed {
71 span_help_and_lint(cx,
74 &format!("large enum variant found on variant `{}`", variant.name),
75 "consider boxing the large branches to reduce the total size of the enum");