use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt::Write as _;
use crate::judge::{condensation, dir_of, tangles};
use crate::pattern::Globs;
use crate::survey::Survey;
#[must_use]
pub fn contract(survey: &Survey, package: &str, root: &str, nested: &[String]) -> String {
let facade = facade(survey);
let zones = stack(survey, package, facade.as_deref());
let mut out = format!(
"// {package} — import topology, drafted by `zone draft` from the real\n\
// import graph. Every line below is TRUE of the tree as it stands: this is\n\
// a description, not a wish. Read it once, then start tightening it —\n\
// merging two zones or sealing a directory is where the value is.\n\
\n\
package {package} {{\n\
\x20 root {root}\n\
\x20 language {}\n",
survey.dialect.name()
);
if let Some(face) = &facade {
let _ = writeln!(out, " facade {face}");
}
if !nested.is_empty() {
let _ = writeln!(
out,
" exclude {}\n\
\x20 // ^ these declare their own package, so they are not this one's code",
nested.join(" ")
);
}
out.push_str("}\n\n// Zones, low to high: an import may not point up the page. The order is a\n\
// topological sort of what imports what today, so nothing points up yet.\nzones {\n");
let width = zones.iter().map(|(name, _)| name.len()).max().unwrap_or(4);
for (name, globs) in &zones {
if globs.len() > 1 {
let _ = writeln!(
out,
" // these {} directories import each other, so no order separates them:\n\
\x20 // one zone until somebody untangles them, and then it splits.",
globs.len()
);
}
let _ = writeln!(out, " {name:<width$} {}", globs.join(" "));
}
out.push_str("}\n");
let grants = grants(survey, &zones);
if !grants.is_empty() {
out.push_str("\n// Outside modules, and who carries them.\n");
for (module, scopes) in &grants {
if scopes.is_empty() {
let _ = writeln!(out, "use {module}");
} else {
let _ = writeln!(out, "use {module} by {}", scopes.join(" "));
}
}
}
let hops = survey.edges.iter().map(|e| e.hops).max().unwrap_or(0);
let _ = write!(
out,
"\n// Structural laws. The reach ceiling is what the tree needs today — lower it\n\
// when a file moves nearer what it depends on; never raise it to go green.\n\
limit reach to {hops} hop{}\n\
forbid cycles across directories\n",
if hops == 1 { "" } else { "s" }
);
let facade_globs = Globs::new(facade.as_deref());
let tangled = tangles(survey, &facade_globs);
if tangled.is_empty() {
out.push_str(
"\n// Nothing else to declare: this graph is already a stack. `zone status`\n\
// lists the directories that could be sealed next.\n",
);
return out;
}
let _ = write!(
out,
"\n// {} import cycle(s) cross a directory boundary. Zoning cannot describe these\n\
// away — a cycle means the directories are one unit. Untangle them, or write the\n\
// reason each one stays: these stanzas do NOT parse until you do.\n",
tangled.len()
);
for component in &tangled {
out.push_str("variance cycle {\n");
for member in component {
let _ = writeln!(out, " {member}");
}
out.push_str("} because \"\"\n");
}
out
}
fn facade(survey: &Survey) -> Option<String> {
let extension = survey.dialect.extensions().first().copied().unwrap_or_default();
let package = survey
.module_root
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let imported: BTreeSet<&str> = survey.edges.iter().map(|e| e.dst.as_str()).collect();
["root", "lib", "main", "mod", package.as_str()]
.into_iter()
.map(|stem| format!("{stem}.{extension}"))
.find(|name| survey.files.iter().any(|f| f == name) && !imported.contains(name.as_str()))
}
fn stack(survey: &Survey, package: &str, facade: Option<&str>) -> Vec<(String, Vec<String>)> {
let mine = |file: &String| Some(file.as_str()) != facade;
let mut homes: BTreeSet<&str> =
survey.files.iter().filter(|f| mine(f)).map(|f| dir_of(f)).collect();
homes.insert(".");
let mut linked: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
for edge in survey.edges.iter().filter(|e| mine(&e.src)) {
let (from, to) = (dir_of(&edge.src), dir_of(&edge.dst));
if from != to {
linked.entry(from).or_default().insert(to);
}
}
let adjacency: HashMap<&str, Vec<&str>> = homes
.iter()
.map(|dir| {
let next = linked.get(dir).map(|to| to.iter().copied().collect()).unwrap_or_default();
(*dir, next)
})
.collect();
let groups: Vec<Vec<String>> = condensation(&adjacency)
.into_iter()
.filter(|group| group.iter().any(|dir| holds(survey, dir, facade)))
.collect();
let mut names: Vec<String> = vec![String::new(); groups.len()];
let mut taken: BTreeSet<String> = BTreeSet::from([package.replace('-', "_")]);
if let Some(at) = groups.iter().position(|g| g.as_slice() == ["."]) {
names[at] = package.replace('-', "_");
}
for (name, group) in names.iter_mut().zip(&groups) {
if name.is_empty() {
*name = distinct(group, package, &mut taken);
}
}
let extension = survey.dialect.extensions().first().copied().unwrap_or_default();
names
.into_iter()
.zip(groups)
.map(|(name, group)| (name, group.iter().map(|dir| claim(dir, extension)).collect()))
.collect()
}
fn claim(dir: &str, extension: &str) -> String {
if dir == "." { format!("*.{extension}") } else { format!("{dir}/*.{extension}") }
}
fn holds(survey: &Survey, dir: &str, facade: Option<&str>) -> bool {
survey.files.iter().any(|f| dir_of(f) == dir && Some(f.as_str()) != facade)
}
fn distinct(group: &[String], package: &str, taken: &mut BTreeSet<String>) -> String {
let name = match group {
[one] => (1..=3)
.map(|depth| name_for(one, package, depth))
.find(|candidate| !taken.contains(candidate))
.unwrap_or_else(|| free(&name_for(one, package, 3), taken)),
_ => free("tangle", taken),
};
taken.insert(name.clone());
name
}
fn free(stem: &str, taken: &BTreeSet<String>) -> String {
if !taken.contains(stem) {
return stem.to_owned();
}
(2..=taken.len() + 2)
.map(|n| format!("{stem}{n}"))
.find(|candidate| !taken.contains(candidate))
.unwrap_or_else(|| stem.to_owned())
}
fn name_for(dir: &str, package: &str, depth: usize) -> String {
if dir == "." {
return package.replace('-', "_");
}
let mut parts: Vec<&str> = dir.rsplit('/').take(depth).collect();
parts.reverse();
parts.join("_").replace(['.', '-'], "_")
}
fn grants(survey: &Survey, zones: &[(String, Vec<String>)]) -> Vec<(String, Vec<String>)> {
let ambient = survey.dialect.ambient();
let claims: Vec<(&str, Globs)> =
zones.iter().map(|(name, globs)| (name.as_str(), Globs::new(globs))).collect();
let mut wanted: BTreeMap<&str, BTreeSet<Option<&str>>> = BTreeMap::new();
for outside in &survey.outside {
if ambient.contains(&outside.spec.as_str()) {
continue;
}
let zone =
claims.iter().find(|(_, globs)| globs.matches(&outside.src)).map(|(name, _)| *name);
wanted.entry(&outside.spec).or_default().insert(zone);
}
wanted
.into_iter()
.map(|(module, zones)| {
let scope = if zones.iter().all(Option::is_some) {
zones.into_iter().flatten().map(str::to_owned).collect()
} else {
Vec::new()
};
(module.to_owned(), scope)
})
.collect()
}