use std::fmt::Write as _;
use super::Ink;
use crate::judge::{self, dir_of};
use crate::ordinance::{Law, Ordinance};
use crate::survey::{Edge, Survey};
const FIELD: usize = 13;
const WIDTH: usize = 78;
pub struct Answer {
pub text: String,
pub clean: bool,
}
#[must_use]
pub fn file(rel: &str, ordinance: &Ordinance, survey: &Survey, ink: &Ink) -> Answer {
let Ink { dim, reset, red, green, .. } = *ink;
let mut out = format!("{rel}\n");
let _ = writeln!(
out,
" package {} {dim}({}, {}){reset}",
ordinance.package,
tail(&ordinance.path),
ordinance.dialect.name()
);
if ordinance.is_facade(rel) {
let _ = writeln!(
out,
" facade {green}yes{reset} {dim}— the module's public face: it may reach \
anything, and every law steps aside for it{reset}"
);
}
tenancy(&mut out, rel, ordinance, ink);
let granted: Vec<&str> =
ordinance.uses.iter().filter(|u| u.covers(rel)).map(|u| u.module.as_str()).collect();
field(
&mut out,
"may use",
"",
&granted,
&format!(
"plus the {} modules ambient in {}",
ordinance.dialect.ambient().len(),
ordinance.dialect.name()
),
ink,
);
for seal in ordinance.seals.iter().filter(|s| rel.starts_with(&format!("{}/", s.path))) {
let role = if seal.entry == rel { "this file is the door" } else { "reach it via" };
let _ = writeln!(out, " sealed {} {dim}({role}: {}){reset}", seal.path, seal.entry);
}
for keep in ordinance.keeps.iter().filter(|k| k.subject.matches(rel)) {
let guests = if keep.importers.is_empty() {
"nobody".to_owned()
} else {
keep.importers.to_string()
};
let _ = writeln!(out, " kept {} {dim}(open to {guests}){reset}", keep.subject);
}
let out_edges: Vec<&Edge> = survey.edges.iter().filter(|e| e.src == rel).collect();
let in_edges: Vec<&Edge> = survey.edges.iter().filter(|e| e.dst == rel).collect();
let outs = out_edges.len().to_string();
let ins = in_edges.len().to_string();
field(&mut out, "imports", &outs, &ends(&out_edges, |e| &e.dst), "", ink);
field(&mut out, "imported", &ins, &ends(&in_edges, |e| &e.src), "", ink);
let verdict = judge::judge(survey, ordinance);
let here = survey.rel(rel);
let mine: Vec<&judge::Finding> = verdict.findings.iter().filter(|f| f.path == here).collect();
let clean = mine.is_empty();
if clean {
let _ = writeln!(out, " standing {green}clean{reset}");
} else {
let _ = writeln!(out, " standing {red}{} finding(s){reset}", mine.len());
for finding in mine {
let _ = writeln!(out, " {} {dim}·{reset} {}", finding.law, finding.message);
}
}
Answer { text: out, clean }
}
#[must_use]
pub fn edge(from: &str, to: &str, ordinance: &Ordinance, survey: &Survey, ink: &Ink) -> Answer {
let Ink { dim, reset, red, green, yellow, .. } = *ink;
let real: Vec<&Edge> = survey.edges.iter().filter(|e| e.src == from && e.dst == to).collect();
let mut out = format!("{from} -> {to}\n");
let _ = writeln!(
out,
" today {}",
match real.first() {
Some(edge) => format!(
"imported at {from}:{} as `{}`{dim} ({} hop{}){reset}",
edge.line,
edge.spec,
edge.hops,
if edge.hops == 1 { "" } else { "s" }
),
None => format!("{dim}no such import — judging it as a hypothetical{reset}"),
}
);
let probe = real.first().map_or_else(|| spelled(from, to), |edge| (*edge).clone());
let verdict = judge::judge(&survey.hypothetically(probe), ordinance);
let against: Vec<&judge::Finding> =
verdict.findings.iter().filter(|f| f.subject == format!("{from} -> {to}")).collect();
if against.is_empty() {
let _ = writeln!(out, " allowed {green}yes{reset}");
if let (Some(src), Some(dst)) = (ordinance.zone_of(from), ordinance.zone_of(to)) {
let _ = writeln!(
out,
" because zone `{}` (rank {}) may import zone `{}` (rank {})",
src.name,
src.rank + 1,
dst.name,
dst.rank + 1
);
}
if let Some(granted) = ordinance.variance(Law::Zone, &format!("{from} -> {to}")) {
let _ =
writeln!(out, " variance {} {dim}({}){reset}", granted.reason, granted.source);
}
return Answer { text: out, clean: true };
}
let _ = writeln!(out, " allowed {red}no{reset}");
for finding in &against {
let _ = writeln!(out, " law {red}{}{reset} — {}", finding.law, finding.message);
let _ = writeln!(out, " remedy {yellow}{}{reset}", finding.law.remedy());
}
if against.iter().any(|f| f.law == Law::Seal)
&& let Some(seal) = ordinance.seals.iter().find(|s| to.starts_with(&format!("{}/", s.path)))
&& seal.entry != to
{
let _ = writeln!(out, " instead import {} {dim}(the seal's door){reset}", seal.entry);
}
Answer { text: out, clean: false }
}
pub(super) fn spelled(from: &str, to: &str) -> Edge {
let (here, there) = (dir_of(from), dir_of(to));
let shared = here
.split('/')
.zip(there.split('/'))
.take_while(|(a, b)| a == b)
.filter(|(a, _)| !a.is_empty())
.count();
let depth = if here == "." { 0 } else { here.split('/').count() };
let hops = u32::try_from(depth.saturating_sub(shared)).unwrap_or(u32::MAX);
let spec = format!("{}{to}", "../".repeat(hops as usize));
Edge { src: from.to_owned(), dst: to.to_owned(), line: 0, col: 1, width: 1, hops, spec }
}
fn tenancy(out: &mut String, rel: &str, ordinance: &Ordinance, ink: &Ink) {
let Ink { dim, reset, red, .. } = *ink;
let Some(zone) = ordinance.zone_of(rel) else {
if !ordinance.is_facade(rel) {
let _ = writeln!(
out,
" zone {red}none{reset} {dim}— no zone claims this file, which is \
itself a violation{reset}"
);
}
return;
};
let _ = writeln!(
out,
" zone {} {dim}(rank {} of {}){reset}",
zone.name,
zone.rank + 1,
ordinance.zones.len()
);
if let Some(glob) = zone.paths.claiming(rel) {
let total = zone.paths.raw().len();
let of = if total == 1 {
"the zone's only path".to_owned()
} else {
format!("1 of the zone's {total} paths")
};
let _ = writeln!(out, " claimed {glob} {dim}({of}){reset}");
}
let below: Vec<&str> =
ordinance.zones.iter().filter(|z| z.rank <= zone.rank).map(|z| z.name.as_str()).collect();
field(out, "may import", "", &below, "its own zone and everything under it", ink);
}
fn ends<'a>(edges: &[&'a Edge], pick: impl Fn(&'a Edge) -> &'a String) -> Vec<&'a str> {
let mut names: Vec<&str> = edges.iter().map(|e| pick(e).as_str()).collect();
names.sort_unstable();
names.dedup();
names
}
fn field(out: &mut String, name: &str, lead: &str, names: &[&str], gloss: &str, ink: &Ink) {
let Ink { dim, reset, .. } = *ink;
let note = if gloss.is_empty() { String::new() } else { format!(" {dim}({gloss}){reset}") };
let head = format!(" {name:<10}{}{lead}", if lead.is_empty() { "" } else { " " });
let rows = wrapped(names);
match rows.as_slice() {
[] if !lead.is_empty() => {
let _ = writeln!(out, "{head}{note}");
}
[] => {
let _ = writeln!(out, "{head} {dim}—{reset}{note}");
}
[only] if FIELD + only.chars().count() + gloss.chars().count() + 3 <= WIDTH => {
let _ = writeln!(out, "{head} {only}{note}");
}
rows => {
let _ = writeln!(out, "{head}{note}");
for row in rows {
let _ = writeln!(out, "{}{row}", " ".repeat(FIELD));
}
}
}
}
fn wrapped(names: &[&str]) -> Vec<String> {
let mut rows: Vec<String> = Vec::new();
for name in names {
match rows.last_mut() {
Some(row) if FIELD + row.chars().count() + 3 + name.chars().count() <= WIDTH => {
row.push_str(" · ");
row.push_str(name);
}
_ => rows.push((*name).to_owned()),
}
}
rows
}
fn tail(path: &std::path::Path) -> String {
let parts: Vec<String> = path
.components()
.rev()
.take(2)
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
parts.into_iter().rev().collect::<Vec<_>>().join("/")
}