use std::fs;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
fn workspace_root() -> &'static Path {
static ROOT: LazyLock<PathBuf> = LazyLock::new(|| {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.expect("crate lives at <workspace>/crates/<name>")
.to_path_buf()
});
&ROOT
}
fn sources() -> &'static [SourceFile] {
static SOURCES: LazyLock<Vec<SourceFile>> = LazyLock::new(|| {
let mut paths = Vec::new();
let crates = fs::read_dir(workspace_root().join("crates")).expect("crates/ dir");
for entry in crates.flatten() {
collect_rs(&entry.path().join("src"), &mut paths);
}
assert!(!paths.is_empty(), "found no source files to scan");
paths.sort();
paths.iter().map(|p| SourceFile::read(p)).collect()
});
&SOURCES
}
struct SourceFile {
path: String,
lines: Vec<(usize, String)>,
}
impl SourceFile {
fn read(path: &Path) -> Self {
let text = fs::read_to_string(path)
.unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()));
let rel = path
.strip_prefix(workspace_root())
.unwrap_or(path)
.to_string_lossy()
.replace('\\', "/");
SourceFile {
path: rel,
lines: text
.lines()
.enumerate()
.map(|(i, l)| (i + 1, l.to_string()))
.filter(|(_, l)| !l.trim_start().starts_with("//"))
.collect(),
}
}
}
fn collect_rs(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_rs(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
}
fn scan(skip: impl Fn(&str) -> bool, hit: impl Fn(&str) -> bool) -> Vec<String> {
sources()
.iter()
.filter(|f| !skip(&f.path))
.flat_map(|f| {
f.lines
.iter()
.filter(|(_, l)| hit(l))
.map(move |(n, l)| format!("{}:{n} {}", f.path, l.trim()))
})
.collect()
}
#[test]
fn iou_formula_only_in_primitives_sim() {
const FORMULA_HOMES: &[&str] = &["crates/hotcoco/src/primitives/sim.rs"];
let violations = scan(
|path| FORMULA_HOMES.contains(&path),
|line| line.contains("union") && line.contains('+') && line.contains(" - "),
);
assert!(
violations.is_empty(),
"a similarity denominator may only be defined in: {}.\n\
Found what looks like another copy at:\n {}\n\n\
Call `primitives::sim` instead — it exposes matrix kernels (`bbox_iou`, \
`mask_iou`, `obb_iou`) and the scalar `bbox_iou_pair`. If this really is \
a different formula (see the panoptic note on this test), add its file to \
FORMULA_HOMES with a comment.",
FORMULA_HOMES.join(", "),
violations.join("\n ")
);
}
#[test]
fn exactly_one_min_parallel_work_constant() {
let found = scan(|_| false, |line| line.contains("const MIN_PARALLEL_WORK"));
assert_eq!(
found.len(),
1,
"expected exactly one MIN_PARALLEL_WORK declaration, found {}:\n {}\n\n\
Per-kernel copies drift. Kernels share the one in `primitives::sim`.",
found.len(),
found.join("\n ")
);
}
#[test]
fn greedy_matching_only_in_primitives() {
let violations = scan(
|path| path.contains("/primitives/"),
|line| line.contains("best_iou") || line.contains("best_gi"),
);
assert!(
violations.is_empty(),
"greedy matching belongs to `primitives::greedy::greedy_match`.\n\
Hand-rolled matcher found at:\n {}",
violations.join("\n ")
);
}