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.
mod config;
mod model;
mod passes;
mod reporter;
mod suggestion;
mod utils;

use std::fs;
use std::path::PathBuf;
use std::process::ExitCode;

use anyhow::{Context, Result};
use clap::Parser;
use syn::visit::Visit;
use walkdir::WalkDir;

use config::{Cli, Config};
use passes::{CacheLensVisitor, StructCollector};
use reporter::{print_human_report, print_json_report};

fn main() -> ExitCode {
    let cli = Cli::parse();
    match run(&cli) {
        Ok(code) => code,
        Err(err) => {
            eprintln!("cache-lens: error: {err:#}");
            ExitCode::from(2)
        }
    }
}

fn run(cli: &Cli) -> Result<ExitCode> {
    let files = collect_rust_files(&cli.paths)?;
    if files.is_empty() {
        anyhow::bail!("no .rs files found in the given path(s)");
    }
    if !cli.quiet && !cli.json {
        eprintln!("cache-lens: scanning {} file(s)...", files.len());
    }

    let mut parsed = Vec::new();
    for path in &files {
        let src = fs::read_to_string(path)
            .with_context(|| format!("failed to read {}", path.display()))?;
        match syn::parse_file(&src) {
            Ok(file) => parsed.push((path.clone(), file)),
            Err(err) => {
                eprintln!(
                    "cache-lens: warning: failed to parse {} ({err}) \u{2014} skipping",
                    path.display()
                );
            }
        }
    }

    // Pass 1: collect every struct definition across all files first
    let mut struct_collector = StructCollector::default();
    for (_, file) in &parsed {
        struct_collector.visit_file(file);
    }
    let structs = struct_collector.structs;

    // Pass 2: analyze loops / collections against the completed struct table
    let config = Config {
        min_fields: cli.min_fields,
        max_access_ratio: cli.max_access_ratio,
    };
    let mut findings = Vec::new();
    for (path, file) in &parsed {
        let mut visitor = CacheLensVisitor::new(&structs, &config, path.display().to_string());
        visitor.visit_file(file);
        findings.extend(visitor.findings);
    }
    findings.sort_by(|a, b| a.file.cmp(&b.file).then(a.line.cmp(&b.line)));

    if cli.json {
        print_json_report(&findings)?;
    } else {
        print_human_report(&findings, parsed.len());
    }

    if cli.strict && !findings.is_empty() {
        Ok(ExitCode::from(1))
    } else {
        Ok(ExitCode::SUCCESS)
    }
}

fn is_ignored_dir(entry: &walkdir::DirEntry) -> bool {
    if !entry.file_type().is_dir() {
        return false;
    }
    matches!(
        entry.file_name().to_str(),
        Some("target") | Some(".git") | Some("node_modules")
    )
}

fn collect_rust_files(paths: &[PathBuf]) -> Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    for path in paths {
        if path.is_file() {
            files.push(path.clone());
        } else if path.is_dir() {
            for entry in WalkDir::new(path)
                .into_iter()
                .filter_entry(|e| !is_ignored_dir(e))
            {
                let entry = entry
                    .with_context(|| format!("failed to walk directory {}", path.display()))?;
                if entry.file_type().is_file()
                    && entry.path().extension().map(|e| e == "rs").unwrap_or(false)
                {
                    files.push(entry.into_path());
                }
            }
        } else {
            anyhow::bail!("path not found: {}", path.display());
        }
    }
    files.sort();
    files.dedup();
    Ok(files)
}