mod fault;
mod law;
mod lex;
mod parse;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
pub use fault::{Fault, Span};
pub use law::Law;
use crate::pattern::{Globs, Pattern};
use crate::survey::Dialect;
pub struct Zone {
pub name: String,
pub rank: usize,
pub paths: Globs,
}
pub struct Seal {
pub path: String,
pub entry: String,
pub open: Globs,
}
pub struct Keep {
pub subject: Pattern,
pub importers: Globs,
}
pub struct Use {
pub module: String,
pub scope: Globs,
pub written: Vec<String>,
pub source: String,
}
impl Use {
#[must_use]
pub fn covers(&self, rel: &str) -> bool {
self.scope.is_empty() || self.scope.matches(rel)
}
}
pub struct Variance {
pub law: Law,
pub subject: String,
pub reason: String,
pub source: String,
}
pub struct Ordinance {
pub path: PathBuf,
pub package: String,
pub dialect: &'static dyn Dialect,
pub module_root: PathBuf,
pub facade: Globs,
pub exclude: Vec<Pattern>,
pub zones: Vec<Zone>,
pub seals: Vec<Seal>,
pub keeps: Vec<Keep>,
pub uses: Vec<Use>,
pub max_hops: Option<u32>,
pub variances: Vec<Variance>,
granted: HashMap<(Law, String), usize>,
}
pub struct Analysis {
pub ordinance: Option<Ordinance>,
pub faults: Vec<Fault>,
}
impl Ordinance {
pub fn read(path: &Path, fallback: &'static dyn Dialect) -> Result<Self, Fault> {
let source =
fs::read_to_string(path).map_err(|e| Fault::at(e.to_string(), Span::head(path), ""))?;
Self::from_source(path, &source, fallback)
}
pub fn from_source(
path: &Path,
source: &str,
fallback: &'static dyn Dialect,
) -> Result<Self, Fault> {
resolve(parse::parse(source, path)?, path, source, fallback)
}
#[must_use]
pub fn analyze(path: &Path, source: &str, fallback: &'static dyn Dialect) -> Analysis {
match Self::from_source(path, source, fallback) {
Ok(ordinance) => Analysis { ordinance: Some(ordinance), faults: Vec::new() },
Err(fault) => Analysis { ordinance: None, faults: vec![fault] },
}
}
#[must_use]
pub fn variance(&self, law: Law, subject: &str) -> Option<&Variance> {
self.granted.get(&(law, subject.to_owned())).map(|&i| &self.variances[i])
}
#[must_use]
pub fn grant(&self, rel: &str, module: &str) -> Option<&Use> {
self.uses.iter().find(|u| u.module == module && u.covers(rel))
}
#[must_use]
pub fn may_use(&self, rel: &str, module: &str) -> bool {
self.dialect.ambient().contains(&module) || self.grant(rel, module).is_some()
}
pub fn grants_of(&self, module: &str) -> impl Iterator<Item = &Use> {
self.uses.iter().filter(move |u| u.module == module)
}
#[must_use]
pub fn is_facade(&self, rel: &str) -> bool {
self.facade.matches(rel)
}
pub fn zones_claiming(&self, rel: &str) -> impl Iterator<Item = &Zone> {
self.zones.iter().filter(move |z| z.paths.matches(rel))
}
#[must_use]
pub fn zone_of(&self, rel: &str) -> Option<&Zone> {
let mut found = self.zones_claiming(rel);
found.next().filter(|_| found.next().is_none())
}
}
#[must_use]
pub fn cycle_subject(members: &[String]) -> String {
let mut sorted: Vec<&str> = members.iter().map(String::as_str).collect();
sorted.sort_unstable();
sorted.join(" + ")
}
fn resolve(
tree: parse::Tree,
path: &Path,
source: &str,
fallback: &'static dyn Dialect,
) -> Result<Ordinance, Fault> {
let pkg = tree.package;
let dialect = match &pkg.language {
Some(named) => crate::survey::dialect(&named.text).ok_or_else(|| {
let known: Vec<&str> = crate::survey::dialects().iter().map(|d| d.name()).collect();
Fault::at(
format!(
"no language named `{}` — this build reads {}",
named.text,
known.join(", ")
),
named.span.clone(),
source,
)
})?,
None => fallback,
};
let root = pkg.root.as_ref().map_or("src", |t| t.text.as_str());
let base = path.parent().and_then(Path::parent).unwrap_or(Path::new("."));
let module_root = base.join(root);
if !module_root.is_dir() {
let blame = pkg.root.as_ref().unwrap_or(&pkg.name);
return Err(Fault::at(
format!("source root `{root}` is not a directory"),
blame.span.clone(),
source,
));
}
let module_root = module_root.canonicalize().unwrap_or(module_root);
let zones = resolve_zones(&tree.zones, source)?;
let seals = resolve_seals(&tree.seals, &module_root, root, source)?;
let keeps = resolve_keeps(&tree.keeps, source)?;
let uses = resolve_uses(&tree.uses, &zones, dialect, path, source)?;
let (variances, granted) = resolve_variances(&tree.variances, path, source)?;
Ok(Ordinance {
path: path.to_path_buf(),
package: pkg.name.text,
dialect,
module_root,
facade: Globs::new(pkg.facade.iter().map(|t| &t.text)),
exclude: pkg.exclude.iter().map(|t| Pattern::new(&t.text)).collect(),
zones,
seals,
keeps,
uses,
max_hops: tree.reach.map(|(n, _)| n),
variances,
granted,
})
}
fn resolve_zones(declared: &[parse::Zone], source: &str) -> Result<Vec<Zone>, Fault> {
let mut zones = Vec::with_capacity(declared.len());
let mut seen: HashMap<&str, usize> = HashMap::new();
for (rank, zone) in declared.iter().enumerate() {
if let Some(line) = seen.insert(&zone.name.text, zone.name.span.line) {
return Err(Fault::at(
format!("zone `{}` was already declared on line {line}", zone.name.text),
zone.name.span.clone(),
source,
));
}
zones.push(Zone {
name: zone.name.text.clone(),
rank,
paths: Globs::new(zone.globs.iter().map(|g| &g.text)),
});
}
Ok(zones)
}
fn resolve_seals(
declared: &[parse::Seal],
module_root: &Path,
root: &str,
source: &str,
) -> Result<Vec<Seal>, Fault> {
let mut seals = Vec::with_capacity(declared.len());
for seal in declared {
let directory = &seal.path.text;
if !module_root.join(directory).is_dir() {
return Err(Fault::at(
format!("`{directory}` is not a directory under {root}/"),
seal.path.span.clone(),
source,
));
}
let inside = format!("{directory}/{}", seal.entry.text);
let beside = match directory.rsplit_once('/') {
Some((parent, _)) => format!("{parent}/{}", seal.entry.text),
None => seal.entry.text.clone(),
};
let Some(entry) = [inside, beside].into_iter().find(|c| module_root.join(c).is_file())
else {
return Err(Fault::at(
format!(
"seal entry `{}` is neither inside `{directory}/` nor beside it",
seal.entry.text
),
seal.entry.span.clone(),
source,
));
};
seals.push(Seal {
path: directory.clone(),
entry,
open: Globs::new(seal.open.iter().map(|g| &g.text)),
});
}
Ok(seals)
}
fn resolve_keeps(declared: &[parse::Keep], source: &str) -> Result<Vec<Keep>, Fault> {
let mut keeps = Vec::with_capacity(declared.len());
let mut kept: HashMap<&str, usize> = HashMap::new();
for keep in declared {
if let Some(line) = kept.insert(&keep.subject.text, keep.subject.span.line) {
return Err(Fault::at(
format!(
"`{}` is already kept on line {line} — merge the guest lists so one \
line names everyone who may reach it",
keep.subject.text
),
keep.subject.span.clone(),
source,
));
}
keeps.push(Keep {
subject: Pattern::new(&keep.subject.text),
importers: Globs::new(keep.importers.iter().map(|g| &g.text)),
});
}
Ok(keeps)
}
fn resolve_uses(
declared: &[parse::Use],
zones: &[Zone],
dialect: &'static dyn Dialect,
path: &Path,
source: &str,
) -> Result<Vec<Use>, Fault> {
let file = path.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned());
let mut uses: Vec<Use> = Vec::new();
let mut granted: HashMap<&str, usize> = HashMap::new();
for statement in declared {
let mut scope: Vec<String> = Vec::new();
let mut written: Vec<String> = Vec::new();
for word in &statement.scope {
written.push(word.text.clone());
match zones.iter().find(|z| z.name == word.text) {
Some(zone) => scope.extend(zone.paths.raw().map(str::to_owned)),
None if word.text.contains(['/', '*', '?', '[', '.']) => {
scope.push(word.text.clone());
}
None => {
let names: Vec<&str> = zones.iter().map(|z| z.name.as_str()).collect();
return Err(Fault::at(
format!(
"no zone named `{}` — a scope is a zone name or a path glob \
(zones here: {})",
word.text,
names.join(", ")
),
word.span.clone(),
source,
));
}
}
}
for module in &statement.modules {
if dialect.ambient().contains(&module.text.as_str()) {
return Err(Fault::at(
format!(
"`{}` is always available in {} and needs no grant — a `use` \
line is for a dependency this package chose to carry",
module.text,
dialect.name()
),
module.span.clone(),
source,
));
}
if let Some(&prior) = granted.get(module.text.as_str()) {
return Err(Fault::at(
format!(
"`{}` is already granted at {} — merge the scopes so one line \
names everyone who may carry it",
module.text, uses[prior].source
),
module.span.clone(),
source,
));
}
granted.insert(&module.text, uses.len());
uses.push(Use {
module: module.text.clone(),
scope: Globs::new(&scope),
written: written.clone(),
source: format!("{file}:{}", statement.lead.span.line),
});
}
}
Ok(uses)
}
type Ratified = (Vec<Variance>, HashMap<(Law, String), usize>);
fn resolve_variances(
declared: &[parse::Variance],
path: &Path,
source: &str,
) -> Result<Ratified, Fault> {
let file = path.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned());
let mut variances: Vec<Variance> = Vec::with_capacity(declared.len());
let mut granted: HashMap<(Law, String), usize> = HashMap::new();
for variance in declared {
let Some(law) = Law::parse(&variance.law.text) else {
return Err(Fault::at(
format!("`{}` is not one of the six laws", variance.law.text),
variance.law.span.clone(),
source,
));
};
let words: Vec<String> = variance.subject.iter().map(|t| t.text.clone()).collect();
let subject = if law == Law::Cycle {
cycle_subject(&words)
} else {
format!("{} -> {}", words[0], words[1])
};
if let Some(&prior) = granted.get(&(law, subject.clone())) {
return Err(Fault::at(
format!(
"a second `variance {law}` for the same subject — already ratified at {}",
variances[prior].source
),
variance.law.span.clone(),
source,
));
}
granted.insert((law, subject.clone()), variances.len());
variances.push(Variance {
law,
subject,
reason: variance.reason.text.trim().to_owned(),
source: format!("{file}:{}", variance.law.span.line),
});
}
Ok((variances, granted))
}
pub struct Parcel {
pub dir: String,
pub language: &'static str,
pub contracts: Vec<PathBuf>,
pub vendored_by: Option<String>,
}
#[must_use]
pub fn discover(repo_root: &Path, under: &[String]) -> Vec<PathBuf> {
sweep(repo_root, under).0
}
#[must_use]
pub fn parcels(repo_root: &Path, under: &[String]) -> Vec<Parcel> {
let (contracts, mut found) = sweep(repo_root, under);
let vendored = borrowed(repo_root, &found);
for parcel in &mut found {
let home = repo_root.join(&parcel.dir).join("contract");
parcel.contracts =
contracts.iter().filter(|c| c.parent() == Some(&home)).cloned().collect();
parcel.vendored_by = vendored.get(&parcel.dir).cloned();
}
found
}
fn borrowed(repo_root: &Path, found: &[Parcel]) -> HashMap<String, String> {
let mut owned = HashMap::new();
for parcel in found {
let Some(dialect) = crate::survey::dialect(parcel.language) else { continue };
let base = repo_root.join(&parcel.dir);
for manifest in dialect.manifests() {
let Ok(text) = fs::read_to_string(base.join(manifest)) else { continue };
for dir in dialect.vendored(&text) {
let rel = posix(&Path::new(&parcel.dir).join(&dir));
owned.insert(rel.trim_start_matches("./").to_owned(), parcel.dir.clone());
}
}
}
owned
}
fn sweep(repo_root: &Path, under: &[String]) -> (Vec<PathBuf>, Vec<Parcel>) {
let (mut contracts, mut parcels) = match indexed(repo_root) {
Some(paths) => sift(repo_root, paths.iter().map(String::as_str)),
None => walked(repo_root),
};
if !under.is_empty() {
let within =
|rel: &str| under.iter().any(|u| rel == u || rel.starts_with(&format!("{u}/")));
contracts.retain(|c| c.strip_prefix(repo_root).is_ok_and(|r| within(&posix(r))));
parcels.retain(|p| within(&p.dir));
}
contracts.sort();
parcels.sort_by(|a, b| a.dir.cmp(&b.dir));
parcels.dedup_by(|a, b| a.dir == b.dir);
(contracts, parcels)
}
fn indexed(repo_root: &Path) -> Option<Vec<String>> {
let mut command = Command::new("git");
command
.args(["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--"])
.arg("*.zone")
.current_dir(repo_root);
for dialect in crate::survey::dialects() {
for manifest in dialect.manifests() {
command.arg(manifest).arg(format!("*/{manifest}"));
}
}
let out = command.output().ok()?;
out.status.success().then(|| {
String::from_utf8_lossy(&out.stdout)
.split('\0')
.filter(|p| !p.is_empty())
.map(str::to_owned)
.collect()
})
}
fn sift<'a>(repo_root: &Path, paths: impl Iterator<Item = &'a str>) -> (Vec<PathBuf>, Vec<Parcel>) {
let (mut contracts, mut parcels) = (Vec::new(), Vec::new());
for rel in paths {
let (dir, name) = rel.rsplit_once('/').unwrap_or((".", rel));
if Path::new(name).extension().is_some_and(|e| e.eq_ignore_ascii_case("zone")) {
if dir.rsplit_once('/').map_or(dir, |(_, d)| d) == "contract" {
contracts.push(repo_root.join(rel));
}
} else if let Some(dialect) =
crate::survey::dialects().iter().find(|d| d.manifests().contains(&name))
{
parcels.push(Parcel {
dir: dir.to_owned(),
language: dialect.name(),
contracts: Vec::new(),
vendored_by: None,
});
}
}
(contracts, parcels)
}
fn walked(repo_root: &Path) -> (Vec<PathBuf>, Vec<Parcel>) {
let mut stack = vec![repo_root.to_path_buf()];
let mut found: Vec<String> = Vec::new();
while let Some(dir) = stack.pop() {
let Ok(entries) = fs::read_dir(&dir) else { continue };
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
let Ok(kind) = entry.file_type() else { continue };
if kind.is_dir() {
if !crate::survey::SKIP.contains(&name.as_ref()) {
stack.push(entry.path());
}
} else if let Ok(rel) = entry.path().strip_prefix(repo_root) {
found.push(posix(rel));
}
}
}
sift(repo_root, found.iter().map(String::as_str))
}
fn posix(rel: &Path) -> String {
rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/")
}