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 quote::{ToTokens, quote};
use syn::{
    BinOp, Expr, ExprPath, GenericArgument, Item, Member, Pat, PatIdent, PatStruct, PathArguments,
    Type, TypeArray, TypePath, TypeReference, TypeSlice, TypeTuple,
};

pub fn unwrap_expr(expr: &Expr) -> &Expr {
    match expr {
        Expr::Paren(p) => unwrap_expr(&p.expr),
        Expr::Group(g) => unwrap_expr(&g.expr),
        Expr::Reference(r) => unwrap_expr(&r.expr),
        Expr::Unary(u) if matches!(u.op, syn::UnOp::Deref(_)) => unwrap_expr(&u.expr),
        other => other,
    }
}

pub fn unwrap_pat(pat: &Pat) -> &Pat {
    match pat {
        Pat::Reference(r) => unwrap_pat(&r.pat),
        Pat::Paren(p) => unwrap_pat(&p.pat),
        Pat::Type(t) => unwrap_pat(&t.pat),
        other => other,
    }
}

pub fn is_target_path(expr: &Expr, target: &str) -> bool {
    if let Expr::Path(ExprPath {
        path, qself: None, ..
    }) = unwrap_expr(expr)
    {
        return path.segments.len() == 1 && path.segments[0].ident == target;
    }
    false
}

pub fn path_to_string(path: &syn::Path) -> String {
    path.segments
        .iter()
        .map(|s| s.ident.to_string())
        .collect::<Vec<_>>()
        .join("::")
}

pub fn simple_type_name(ty: &Type) -> Option<String> {
    match ty {
        Type::Path(TypePath {
            path, qself: None, ..
        }) => path.segments.last().map(|s| s.ident.to_string()),
        _ => None,
    }
}

pub fn extract_element_struct_name(ty: &Type) -> Option<String> {
    match ty {
        Type::Reference(TypeReference { elem, .. }) => extract_element_struct_name(elem),
        Type::Array(TypeArray { elem, .. }) => simple_type_name(elem),
        Type::Slice(TypeSlice { elem, .. }) => simple_type_name(elem),
        Type::Path(TypePath {
            path, qself: None, ..
        }) => {
            let seg = path.segments.last()?;
            if matches!(seg.ident.to_string().as_str(), "Vec" | "VecDeque")
                && let PathArguments::AngleBracketed(ab) = &seg.arguments
            {
                for arg in &ab.args {
                    if let GenericArgument::Type(inner) = arg {
                        return simple_type_name(inner);
                    }
                }
            }
            None
        }
        _ => None,
    }
}

pub fn is_assign_op(op: &BinOp) -> bool {
    matches!(
        op,
        BinOp::AddAssign(_)
            | BinOp::SubAssign(_)
            | BinOp::MulAssign(_)
            | BinOp::DivAssign(_)
            | BinOp::RemAssign(_)
            | BinOp::BitXorAssign(_)
            | BinOp::BitAndAssign(_)
            | BinOp::BitOrAssign(_)
            | BinOp::ShlAssign(_)
            | BinOp::ShrAssign(_)
    )
}

pub enum LoopBinding {
    Ident(String),
    Destructured(Vec<String>),
    Unsupported,
}

pub fn classify_loop_pattern(pat: &Pat) -> LoopBinding {
    match unwrap_pat(pat) {
        Pat::Ident(PatIdent { ident, .. }) => LoopBinding::Ident(ident.to_string()),
        Pat::Struct(PatStruct { fields, rest, .. }) => {
            if rest.is_some() {
                let names = fields
                    .iter()
                    .filter_map(|fp| match &fp.member {
                        Member::Named(id) => Some(id.to_string()),
                        Member::Unnamed(_) => None,
                    })
                    .collect();
                LoopBinding::Destructured(names)
            } else {
                LoopBinding::Unsupported
            }
        }
        _ => LoopBinding::Unsupported,
    }
}

pub fn estimate_type_size(ty: &Type) -> usize {
    match ty {
        Type::Path(TypePath {
            path, qself: None, ..
        }) => {
            let Some(seg) = path.segments.last() else {
                return 8;
            };
            match seg.ident.to_string().as_str() {
                "u8" | "i8" | "bool" => 1,
                "u16" | "i16" => 2,
                "u32" | "i32" | "f32" | "char" => 4,
                "u64" | "i64" | "f64" | "usize" | "isize" => 8,
                "u128" | "i128" => 16,
                "String" => 24,
                "Vec" | "VecDeque" | "HashMap" | "BTreeMap" | "HashSet" | "BTreeSet" => 24,
                "Box" | "Rc" | "Arc" => 8,
                "Option" => {
                    if let PathArguments::AngleBracketed(ab) = &seg.arguments
                        && let Some(GenericArgument::Type(inner)) = ab.args.first()
                    {
                        return estimate_type_size(inner) + 8;
                    }
                    16
                }
                _ => 8,
            }
        }
        Type::Array(TypeArray { elem, len, .. }) => {
            let n = match len {
                syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Int(li),
                    ..
                }) => li.base10_parse::<usize>().unwrap_or(1),
                _ => 1,
            };
            n.saturating_mul(estimate_type_size(elem))
        }
        Type::Tuple(TypeTuple { elems, .. }) => elems.iter().map(estimate_type_size).sum(),
        _ => 8,
    }
}

pub fn type_to_string(ty: &Type) -> String {
    let tokens = quote! { type T = #ty; };
    if let Ok(item) = syn::parse2::<Item>(tokens) {
        let file = syn::File {
            shebang: None,
            attrs: vec![],
            items: vec![item],
        };
        let pretty = prettyplease::unparse(&file);
        let cleaned = pretty
            .trim()
            .strip_prefix("type T = ")
            .unwrap_or(&pretty)
            .trim_end_matches(';')
            .to_string();
        return cleaned;
    }
    ty.to_token_stream().to_string()
}

pub fn pluralize(word: &str) -> String {
    if word.chars().count() <= 2 {
        return format!("{word}s");
    }
    let lower = word.to_lowercase();
    if lower.ends_with('s') {
        word.to_string()
    } else if lower.ends_with('x')
        || lower.ends_with('z')
        || lower.ends_with("ch")
        || lower.ends_with("sh")
    {
        format!("{word}es")
    } else if let Some(prefix) = word.strip_suffix('y') {
        let consonant_before_y = prefix
            .chars()
            .last()
            .map(|c| !"aeiouAEIOU".contains(c))
            .unwrap_or(false);
        if consonant_before_y {
            format!("{prefix}ies")
        } else {
            format!("{word}s")
        }
    } else {
        format!("{word}s")
    }
}