cache-lens 0.1.0

A static analyzer that detects cache-unfriendly Array-of-Structures (AoS) usage in Rust and suggests Structure-of-Arrays (SoA) refactors.
use serde::Serialize;
use syn::Type;

/// One field of a struct definition, as discovered by StructCollector.
#[derive(Debug, Clone)]
pub struct FieldInfo {
    pub name: String,
    pub ty: Type,
}

/// A struct definition discovered anywhere in the scanned input.
#[derive(Debug, Clone)]
pub struct StructInfo {
    pub name: String,
    pub fields: Vec<FieldInfo>,
    /// Line the struct is defined on, purely for report context.
    pub def_line: usize,
}

/// Read/write tally for a single field within one loop body.
#[derive(Debug, Default, Clone, Copy)]
pub struct FieldAccessStat {
    pub reads: u32,
    pub writes: u32,
}

/// A field as it will be rendered in a finished report.
#[derive(Debug, Clone, Serialize)]
pub struct FieldReport {
    pub name: String,
    pub ty: String,
    pub reads: u32,
    pub writes: u32,
    pub approx_size_bytes: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    High,
    Medium,
}

impl std::fmt::Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Severity::High => write!(f, "HIGH"),
            Severity::Medium => write!(f, "MEDIUM"),
        }
    }
}

/// One reported AoS→SoA opportunity.
#[derive(Debug, Clone, Serialize)]
pub struct Finding {
    pub file: String,
    pub line: usize,
    pub struct_name: String,
    pub struct_def_line: usize,
    pub total_fields: usize,
    pub collection_expr: String,
    pub loop_var: String,
    pub loop_kind: String,
    pub hot_fields: Vec<FieldReport>,
    pub cold_fields: Vec<FieldReport>,
    pub access_ratio: f64,
    pub byte_ratio: f64,
    pub severity: Severity,
    pub soa_suggestion: String,
    pub soa_derive_suggestion: String,
}