use std::collections::{HashSet, VecDeque};
use std::path::{Path, PathBuf};
const CRATES: &[(&str, &[&str])] = &[
(
"ironbridge-rust",
&["src/lib.rs", "src/main.rs", "src/mcp/main.rs"],
),
("ironbridge-sso", &["src/lib.rs"]),
("ironbridge-desktop", &["src/main.rs"]),
];
const KNOWN_ORPHANS: &[&str] = &[];
fn repo_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("ironbridge-rust has a parent directory")
.to_path_buf()
}
fn strip_noise(source: &str) -> String {
let mut out = String::with_capacity(source.len());
for line in source.lines() {
let mut in_string = false;
let mut prev = '\0';
for (i, c) in line.char_indices() {
if c == '"' && prev != '\\' {
in_string = !in_string;
}
if !in_string && c == '/' && line[i..].starts_with("//") {
break;
}
out.push(c);
prev = c;
}
out.push('\n');
}
out
}
fn declared_mods(source: &str) -> Vec<String> {
let cleaned = strip_noise(source);
let mut names = Vec::new();
for stmt in cleaned.split(';') {
let Some(idx) = stmt.rfind("mod ") else {
continue;
};
let before = stmt[..idx].chars().next_back().unwrap_or(' ');
if before.is_alphanumeric() || before == '_' || before == ':' {
continue;
}
let rest = stmt[idx + 4..].trim();
if rest.is_empty() || !rest.chars().all(|c| c.is_alphanumeric() || c == '_') {
continue;
}
if stmt.contains("use ") {
continue;
}
names.push(rest.to_string());
}
names
}
fn resolve(parent: &Path, name: &str) -> Option<PathBuf> {
let dir = if parent.file_name()? == "lib.rs"
|| parent.file_name()? == "main.rs"
|| parent.file_name()? == "mod.rs"
{
parent.parent()?.to_path_buf()
} else {
parent.with_extension("")
};
let flat = dir.join(format!("{name}.rs"));
if flat.is_file() {
return Some(flat);
}
let nested = dir.join(name).join("mod.rs");
if nested.is_file() {
return Some(nested);
}
None
}
fn reachable_files() -> HashSet<PathBuf> {
let repo = repo_root();
let mut seen: HashSet<PathBuf> = HashSet::new();
let mut queue: VecDeque<PathBuf> = VecDeque::new();
for (krate, roots) in CRATES {
for root in *roots {
let path = repo.join(krate).join(root);
assert!(
path.is_file(),
"declared root {krate}/{root} does not exist; \
CRATES is out of step with {krate}/Cargo.toml"
);
queue.push_back(path);
}
}
while let Some(file) = queue.pop_front() {
if !seen.insert(file.clone()) {
continue;
}
let source = std::fs::read_to_string(&file)
.unwrap_or_else(|e| panic!("reading {}: {e}", file.display()));
for name in declared_mods(&source) {
if let Some(child) = resolve(&file, &name) {
queue.push_back(child);
}
}
}
seen
}
fn files_on_disk() -> HashSet<PathBuf> {
fn walk(dir: &Path, out: &mut HashSet<PathBuf>) {
for entry in std::fs::read_dir(dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())) {
let path = entry.expect("readable dir entry").path();
if path.is_dir() {
walk(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.insert(path);
}
}
}
let repo = repo_root();
let mut out = HashSet::new();
for (krate, _) in CRATES {
walk(&repo.join(krate).join("src"), &mut out);
}
out
}
fn display_path(path: &Path) -> String {
path.strip_prefix(repo_root())
.unwrap_or(path)
.display()
.to_string()
.replace('\\', "/")
}
#[test]
fn every_source_file_is_compiled() {
let reachable = reachable_files();
let on_disk = files_on_disk();
let known: HashSet<&str> = KNOWN_ORPHANS.iter().copied().collect();
let mut orphans: Vec<String> = on_disk
.difference(&reachable)
.map(|p| display_path(p))
.filter(|p| !known.contains(p.as_str()))
.collect();
orphans.sort();
assert!(
orphans.is_empty(),
"{} source file(s) are never compiled -- no `mod` declaration reaches them, \
so rustc has never checked a line of them:\n {}\n\n\
Either declare them in the parent module or delete them. A file the compiler \
cannot see will drift out of sync with the code around it and nothing will say so.",
orphans.len(),
orphans.join("\n ")
);
}
#[test]
fn the_holding_pen_does_not_outlive_its_contents() {
let repo = repo_root();
let reachable = reachable_files();
for entry in KNOWN_ORPHANS {
let path = repo.join(entry);
assert!(
path.is_file(),
"{entry} is listed in KNOWN_ORPHANS but no longer exists -- remove the entry"
);
assert!(
!reachable.contains(&path),
"{entry} is listed in KNOWN_ORPHANS but is now compiled -- remove the entry"
);
}
}
#[test]
fn the_walker_finds_something_to_walk() {
let on_disk = files_on_disk();
assert!(
on_disk.len() > 100,
"only {} source files found; the directory walk is broken",
on_disk.len()
);
let reachable = reachable_files();
assert!(
reachable.len() > 100,
"only {} reachable files found; the module walk is broken",
reachable.len()
);
}
#[test]
fn a_commented_out_declaration_does_not_count() {
assert_eq!(declared_mods("// mod ghost;\nmod real;"), vec!["real"]);
}
#[test]
fn an_inline_module_is_not_a_file() {
let source = "mod real;\n#[cfg(test)]\nmod tests {\n fn helper() {}\n}\n";
assert_eq!(declared_mods(source), vec!["real"]);
}
#[test]
fn attributes_and_visibility_do_not_hide_a_declaration() {
let source =
"#[cfg(feature = \"enterprise\")]\npub mod gated;\n#[allow(dead_code)]\nmod plain;";
assert_eq!(declared_mods(source), vec!["gated", "plain"]);
}
#[test]
fn a_use_path_is_not_a_declaration() {
let source = "use crate::mod_helper::thing;\nuse std::fmt;\nmod real;";
assert_eq!(declared_mods(source), vec!["real"]);
}