|
| 1 | +//! lint when there are large variants on an enum |
| 2 | +
|
| 3 | +use rustc::lint::*; |
| 4 | +use rustc::hir::*; |
| 5 | +use utils::span_help_and_lint; |
| 6 | +use rustc::ty::layout::TargetDataLayout; |
| 7 | +use rustc::ty::TypeFoldable; |
| 8 | + |
| 9 | +/// **What it does:** Checks for large variants on enums. |
| 10 | +/// |
| 11 | +/// **Why is this bad?** Enum size is bounded by the largest variant. Having a large variant |
| 12 | +/// can penalize the memory layout of that enum. |
| 13 | +/// |
| 14 | +/// **Known problems:** None. |
| 15 | +/// |
| 16 | +/// **Example:** |
| 17 | +/// ```rust |
| 18 | +/// enum Test { |
| 19 | +/// A(i32), |
| 20 | +/// B([i32; 8000]), |
| 21 | +/// } |
| 22 | +/// ``` |
| 23 | +declare_lint! { |
| 24 | + pub LARGE_ENUM_VARIANT, |
| 25 | + Warn, |
| 26 | + "large variants on an enum" |
| 27 | +} |
| 28 | + |
| 29 | +#[derive(Copy,Clone)] |
| 30 | +pub struct LargeEnumVariant { |
| 31 | + maximum_variant_size_allowed: u64, |
| 32 | +} |
| 33 | + |
| 34 | +impl LargeEnumVariant { |
| 35 | + pub fn new(maximum_variant_size_allowed: u64) -> Self { |
| 36 | + LargeEnumVariant { maximum_variant_size_allowed: maximum_variant_size_allowed } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +impl LintPass for LargeEnumVariant { |
| 41 | + fn get_lints(&self) -> LintArray { |
| 42 | + lint_array!(LARGE_ENUM_VARIANT) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeEnumVariant { |
| 47 | + fn check_item(&mut self, cx: &LateContext, item: &Item) { |
| 48 | + let did = cx.tcx.map.local_def_id(item.id); |
| 49 | + if let ItemEnum(ref def, _) = item.node { |
| 50 | + let ty = cx.tcx.item_type(did); |
| 51 | + let adt = ty.ty_adt_def().expect("already checked whether this is an enum"); |
| 52 | + for (i, variant) in adt.variants.iter().enumerate() { |
| 53 | + let data_layout = TargetDataLayout::parse(cx.sess()); |
| 54 | + let param_env = cx.tcx.empty_parameter_environment(); |
| 55 | + let infcx = cx.tcx.borrowck_fake_infer_ctxt(param_env); |
| 56 | + let size: u64 = variant.fields |
| 57 | + .iter() |
| 58 | + .map(|f| { |
| 59 | + let ty = cx.tcx.item_type(f.did); |
| 60 | + if ty.needs_subst() { |
| 61 | + 0 // we can't reason about generics, so we treat them as zero sized |
| 62 | + } else { |
| 63 | + ty.layout(&infcx) |
| 64 | + .expect("layout should be computable for concrete type") |
| 65 | + .size(&data_layout) |
| 66 | + .bytes() |
| 67 | + } |
| 68 | + }) |
| 69 | + .sum(); |
| 70 | + if size > self.maximum_variant_size_allowed { |
| 71 | + span_help_and_lint(cx, |
| 72 | + LARGE_ENUM_VARIANT, |
| 73 | + def.variants[i].span, |
| 74 | + &format!("large enum variant found on variant `{}`", variant.name), |
| 75 | + "consider boxing the large branches to reduce the total size of the enum"); |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments