use std::sync::OnceLock;
use regex::Regex;
use crate::model::StructureMetrics;
pub fn analyze(text: &str, code_lines: usize, extension: Option<&str>) -> StructureMetrics {
let lines = text.lines().collect::<Vec<_>>();
let control_tokens = control_regex().find_iter(text).count();
let max_brace_depth = brace_depth(text);
let function_lengths = if extension == Some("py") {
python_function_lengths(&lines)
} else {
braced_function_lengths(&lines)
};
let max_function_lines = function_lengths.iter().copied().max().unwrap_or(0);
let control_density = control_tokens as f64 / code_lines.max(1) as f64;
let complexity_raw = 0.45 * control_tokens as f64
+ 0.2 * max_brace_depth as f64
+ 0.25 * max_function_lines as f64
+ 0.1 * (control_density * 100.0);
let context_cost_raw = 0.6 * code_lines as f64 + 0.4 * max_function_lines as f64;
StructureMetrics {
control_tokens,
max_brace_depth,
max_function_lines,
function_count: function_lengths.len(),
complexity_raw,
context_cost_raw,
}
}
fn control_regex() -> &'static Regex {
static REGEX: OnceLock<Regex> = OnceLock::new();
REGEX.get_or_init(|| {
Regex::new(r"\b(if|else|elif|match|for|while|loop|case|catch|except|when|switch)\b|&&|\|\|")
.expect("control-flow regex is valid")
})
}
fn function_regex() -> &'static Regex {
static REGEX: OnceLock<Regex> = OnceLock::new();
REGEX.get_or_init(|| {
Regex::new(
r#"^\s*(?:(?:pub(?:\([^)]*\))?|default|const|async|unsafe|extern(?:\s+\"[^\"]+\")?)\s+)*fn\s+(?:r#)?[A-Za-z_]\w*|^\s*(?:async\s+)?function\s+\w+\s*\("#,
)
.expect("function regex is valid")
})
}
fn python_function_regex() -> &'static Regex {
static REGEX: OnceLock<Regex> = OnceLock::new();
REGEX.get_or_init(|| {
Regex::new(r"^\s*(?:async\s+)?def\s+\w+\s*\(").expect("Python function regex is valid")
})
}
fn brace_depth(text: &str) -> usize {
let mut depth = 0_usize;
let mut maximum = 0_usize;
for byte in text.bytes() {
match byte {
b'{' => {
depth += 1;
maximum = maximum.max(depth);
}
b'}' => depth = depth.saturating_sub(1),
_ => {}
}
}
maximum
}
fn braced_function_lengths(lines: &[&str]) -> Vec<usize> {
let mut lengths = Vec::new();
let mut index = 0;
while index < lines.len() {
if !function_regex().is_match(lines[index]) {
index += 1;
continue;
}
let start = index;
let mut depth = 0_i64;
let mut opened = false;
while index < lines.len() {
for byte in lines[index].bytes() {
if byte == b'{' {
depth += 1;
opened = true;
} else if byte == b'}' && depth > 0 {
depth -= 1;
}
}
if opened && depth == 0 {
lengths.push(index - start + 1);
break;
}
index += 1;
}
index += 1;
}
lengths
}
fn python_function_lengths(lines: &[&str]) -> Vec<usize> {
let starts = lines
.iter()
.enumerate()
.filter(|(_, line)| python_function_regex().is_match(line))
.map(|(index, line)| (index, line.len() - line.trim_start().len()))
.collect::<Vec<_>>();
starts
.iter()
.map(|(start, indentation)| {
let end = lines
.iter()
.enumerate()
.skip(start + 1)
.find(|(_, line)| {
!line.trim().is_empty() && line.len() - line.trim_start().len() <= *indentation
})
.map_or(lines.len(), |(index, _)| index);
end - start
})
.collect()
}
#[cfg(test)]
mod tests {
use super::analyze;
#[test]
fn finds_function_extent_and_controls() {
let metrics = analyze("fn main() {\n if true {\n loop {}\n }\n}\n", 5, Some("rs"));
assert_eq!(metrics.function_count, 1);
assert_eq!(metrics.max_function_lines, 5);
assert_eq!(metrics.control_tokens, 2);
assert_eq!(metrics.max_brace_depth, 3);
}
}