1 //! lint when there are large 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 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 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.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");
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")
72 let mut f = ::std::fs::File::create("log").unwrap();
74 writeln!(f, "size, max size: {}, {}", size, self.maximum_variant_size_allowed).unwrap();
75 if size > self.maximum_variant_size_allowed {
76 writeln!(f, "size > max").unwrap();
79 span_lint_and_then(cx,
82 "large enum variant found",
84 if variant.fields.len() == 1 {
85 let span = match def.variants[i].node.data {
86 VariantData::Struct(ref fields, _) |
87 VariantData::Tuple(ref fields, _) => fields[0].ty.span,
88 VariantData::Unit(_) => unreachable!(),
90 if let Some(snip) = snippet_opt(cx, span) {
91 db.span_suggestion(span,
92 "consider boxing the large fields to reduce the total size of \
94 format!("Box<{}>", snip));
98 db.span_help(def.variants[i].span,
99 "consider boxing the large fields to reduce the total size of the enum");