use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::path::Path;
use std::time::Duration;
use super::HookInput;
use crate::extract::{extract_structure, language_for_extension};
use crate::graph::{reachable_over, CodeGraph, Dir};
use crate::policy::BlastRadius;
use crate::types::Symbol;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Sizing {
Measured(BlastRadius),
NoGrammar { ext: String },
NoAnchors,
Deadline,
Unreadable,
}
impl Sizing {
#[must_use]
pub fn kind_tag(&self) -> &'static str {
match self {
Self::Measured(_) => "measured",
Self::NoGrammar { .. } => "no-grammar",
Self::NoAnchors => "no-anchors",
Self::Deadline => "deadline",
Self::Unreadable => "unreadable",
}
}
#[must_use]
pub fn unmeasured_reason(&self) -> Option<String> {
match self {
Self::Measured(_) => None,
Self::NoGrammar { ext } => Some(format!(
"this build has no grammar for `.{ext}`, so the edit's reach is UNKNOWN"
)),
Self::NoAnchors => Some(
"no symbols could be located in the edited file, so there was \
nothing to size the change from"
.to_string(),
),
Self::Deadline => Some(
"the measurement budget (policy.deadline_ms) expired before the \
graph answered"
.to_string(),
),
Self::Unreadable => Some("the edited file could not be read".to_string()),
}
}
}
pub fn measure_within(
root: &Path,
file: &Path,
rel: &str,
input: &HookInput,
max_hops: u32,
budget: Duration,
) -> Sizing {
if budget.is_zero() {
return Sizing::Deadline;
}
let (tx, rx) = std::sync::mpsc::channel();
let (root, file, rel) = (root.to_path_buf(), file.to_path_buf(), rel.to_string());
let anchors: Vec<String> = input
.replaced_texts()
.into_iter()
.map(str::to_string)
.collect();
std::thread::spawn(move || {
let _ = tx.send(measure(&root, &file, &rel, &anchors, max_hops));
});
rx.recv_timeout(budget).unwrap_or(Sizing::Deadline)
}
enum Touched {
Ok {
language: &'static str,
touched: Vec<String>,
},
Unmeasurable(Sizing),
}
fn edit_touch(file: &Path, anchors: &[String]) -> Touched {
let ext = file
.extension()
.and_then(OsStr::to_str)
.unwrap_or_default()
.to_string();
let Some(language) = language_for_extension(&ext) else {
return Touched::Unmeasurable(Sizing::NoGrammar { ext });
};
let Ok(source) = std::fs::read_to_string(file) else {
return Touched::Unmeasurable(Sizing::Unreadable);
};
let Ok(structure) = extract_structure(&source, language) else {
return Touched::Unmeasurable(Sizing::NoGrammar { ext });
};
let touched = touched_symbols(&structure.symbols, &source, anchors);
if touched.is_empty() {
return Touched::Unmeasurable(Sizing::NoAnchors);
}
Touched::Ok { language, touched }
}
fn walk_blast(
graph: &CodeGraph,
touched: &[String],
rel: &str,
language: &str,
max_hops: u32,
) -> BlastRadius {
let mut symbols: BTreeSet<String> = BTreeSet::new();
let mut files: BTreeSet<String> = BTreeSet::new();
for name in touched {
for reached in reachable_over(graph, name, Dir::Callers, max_hops) {
if reached.file == rel {
continue;
}
let reached_language = Path::new(&reached.file)
.extension()
.and_then(OsStr::to_str)
.and_then(language_for_extension);
if reached_language != Some(language) {
continue;
}
symbols.insert(reached.name);
files.insert(reached.file);
}
}
BlastRadius {
symbols: symbols.len(),
files: files.len(),
}
}
fn measure(root: &Path, file: &Path, rel: &str, anchors: &[String], max_hops: u32) -> Sizing {
let (language, touched) = match edit_touch(file, anchors) {
Touched::Ok { language, touched } => (language, touched),
Touched::Unmeasurable(sizing) => return sizing,
};
let Ok(graph) = CodeGraph::build(root) else {
return Sizing::Unreadable;
};
Sizing::Measured(walk_blast(&graph, &touched, rel, language, max_hops))
}
pub(crate) fn measure_with_graph(
graph: &CodeGraph,
file: &Path,
rel: &str,
anchors: &[String],
max_hops: u32,
) -> Sizing {
let (language, touched) = match edit_touch(file, anchors) {
Touched::Ok { language, touched } => (language, touched),
Touched::Unmeasurable(sizing) => return sizing,
};
Sizing::Measured(walk_blast(graph, &touched, rel, language, max_hops))
}
fn touched_symbols(symbols: &[Symbol], source: &str, anchors: &[String]) -> Vec<String> {
let all = || symbols.iter().map(|s| s.name.clone()).collect::<Vec<_>>();
if anchors.is_empty() {
return all();
}
let mut lines: Vec<(usize, usize)> = Vec::new();
for anchor in anchors {
let Some(offset) = source.find(anchor.as_str()) else {
return all(); };
let start = source[..offset].lines().count().max(1);
let end = start + anchor.lines().count().saturating_sub(1);
lines.push((start, end));
}
let touched: Vec<String> = symbols
.iter()
.filter(|symbol| {
lines
.iter()
.any(|(start, end)| symbol.start_line <= *end && symbol.end_line >= *start)
})
.map(|symbol| symbol.name.clone())
.collect();
if touched.is_empty() {
all()
} else {
touched
}
}
pub fn relative(file: &Path, root: &Path) -> String {
file.strip_prefix(root)
.unwrap_or(file)
.display()
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_edit_is_sized_by_the_function_it_lands_in() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("lib.rs"), "fn quiet() {}\nfn loud() {}\n").unwrap();
let source = std::fs::read_to_string(dir.path().join("lib.rs")).unwrap();
let symbols = crate::extract::extract_symbols(&source, "rust").unwrap();
let touched = touched_symbols(&symbols, &source, &["fn quiet() {}".to_string()]);
assert_eq!(touched, vec!["quiet".to_string()]);
assert_eq!(touched_symbols(&symbols, &source, &[]).len(), 2);
}
#[test]
fn an_unfindable_anchor_falls_back_to_the_whole_file() {
let source = "fn a() {}\nfn b() {}\n";
let symbols = crate::extract::extract_symbols(source, "rust").unwrap();
let touched = touched_symbols(&symbols, source, &["fn nowhere() {}".to_string()]);
assert_eq!(touched.len(), 2);
}
#[test]
fn measures_transitive_callers_excluding_the_edited_file() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("leaf.rs"), "fn leaf() {}\n").unwrap();
std::fs::write(dir.path().join("mid.rs"), "fn mid() { leaf(); }\n").unwrap();
std::fs::write(dir.path().join("top.rs"), "fn top() { mid(); }\n").unwrap();
let radius = measure(
dir.path(),
&dir.path().join("leaf.rs"),
"leaf.rs",
&["fn leaf() {}".to_string()],
5,
);
let Sizing::Measured(radius) = radius else {
panic!("a Rust edit with callers must MEASURE, got {radius:?}")
};
assert_eq!(
radius,
BlastRadius {
symbols: 2,
files: 2
}
);
}
#[test]
fn a_zero_budget_measures_nothing() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("leaf.rs"), "fn leaf() {}\n").unwrap();
let input = HookInput::parse(
&serde_json::json!({ "tool_input": { "file_path": "leaf.rs" } }).to_string(),
)
.unwrap();
assert_eq!(
measure_within(
dir.path(),
&dir.path().join("leaf.rs"),
"leaf.rs",
&input,
5,
Duration::ZERO,
),
Sizing::Deadline
);
}
#[test]
fn a_file_with_no_grammar_reports_no_grammar_not_a_clean_radius() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("notes.md"), "# hi\n").unwrap();
let sizing = measure(dir.path(), &dir.path().join("notes.md"), "notes.md", &[], 5);
assert_eq!(
sizing,
Sizing::NoGrammar {
ext: "md".to_string()
}
);
assert!(sizing.unmeasured_reason().unwrap().contains("UNKNOWN"));
}
#[test]
fn a_leaf_with_callers_is_measured_in_every_compiled_language() {
#[cfg(feature = "langs-extra")]
{
let cases: &[(&str, &str, &str, &str)] = &[
(
"py",
"def leaf():\n return 1\n",
"from leaf import leaf\ndef one():\n return leaf()\n",
"def leaf():",
),
(
"ts",
"export function leaf(): number { return 1; }\n",
"import { leaf } from \"./leaf\";\nexport function one() { return leaf(); }\n",
"export function leaf(): number { return 1; }",
),
(
"go",
"package main\nfunc leaf() int { return 1 }\n",
"package main\nfunc one() int { return leaf() }\n",
"func leaf() int { return 1 }",
),
];
for (ext, leaf_src, caller_src, anchor) in cases {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join(format!("leaf.{ext}")), leaf_src).unwrap();
std::fs::write(dir.path().join(format!("one.{ext}")), caller_src).unwrap();
let sizing = measure(
dir.path(),
&dir.path().join(format!("leaf.{ext}")),
&format!("leaf.{ext}"),
&[(*anchor).to_string()],
5,
);
match sizing {
Sizing::Measured(radius) => assert!(
radius.files >= 1 && radius.symbols >= 1,
".{ext}: measured a radius of {radius:?} — a caller in \
another file was not seen"
),
other => panic!(
".{ext}: NOT MEASURED ({other:?}) — a blast-radius rule \
would silently not apply to this language"
),
}
}
}
}
}