mod fault;
mod law;
mod lex;
mod parse;
mod plat;
mod workspace;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
pub use fault::{Fault, Span};
pub use law::Law;
pub use plat::{Parcel, anchor, discover, governing, parcels};
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,
pub inherited: bool,
}
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 workspace: Option<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> {
let tree = parse::parse(source, path)?;
let shared = workspace::enclosing(path, fallback)?;
resolve(tree, path, source, fallback, shared.as_ref())
}
#[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,
shared: Option<&workspace::Shared>,
) -> Result<Ordinance, Fault> {
let Some(pkg) = tree.package else {
let lead =
tree.workspace.as_ref().map_or_else(|| Span::head(path), |w| w.lead.span.clone());
return Err(Fault::at(
"this file holds a workspace together and governs no package of its own — \
judge its members, or add a `package` block to govern this directory too",
lead,
source,
));
};
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 => shared.and_then(|s| s.language).unwrap_or(fallback),
};
let base = plat::anchor(path);
let inherited_root = shared.and_then(|s| s.root.as_deref());
let root = match pkg.root.as_ref().map(|t| t.text.as_str()).or(inherited_root) {
Some(named) => named,
None if base.join("src").is_dir() => "src",
None => ".",
};
let module_root = base.join(root);
if !module_root.is_dir() {
let blame = pkg.root.as_ref().unwrap_or(&pkg.name).span.clone();
let message = format!("source root `{root}` is not a directory");
return Err(match shared.filter(|_| pkg.root.is_none()) {
Some(shared) => workspace::blame(shared, &message, blame, source),
None => Fault::at(message, blame, 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 = inherit(resolve_uses(&tree.uses, &zones, dialect, path, source)?, shared);
let (variances, granted) = resolve_variances(&tree.variances, path, source)?;
let facade = if pkg.facade.is_empty() {
Globs::new(shared.map(|s| s.facade.clone()).unwrap_or_default())
} else {
Globs::new(pkg.facade.iter().map(|t| &t.text))
};
Ok(Ordinance {
path: path.to_path_buf(),
workspace: shared.map(|s| s.path.clone()),
package: pkg.name.text,
dialect,
module_root,
facade,
exclude: pkg.exclude.iter().map(|t| Pattern::new(&t.text)).collect(),
zones,
seals,
keeps,
uses,
max_hops: tree.reach.map(|(n, _)| n).or_else(|| shared.and_then(|s| s.max_hops)),
variances,
granted,
})
}
fn inherit(own: Vec<Use>, shared: Option<&workspace::Shared>) -> Vec<Use> {
let Some(shared) = shared else { return own };
let mut uses: Vec<Use> = shared
.uses
.iter()
.filter(|grant| !own.iter().any(|mine| mine.module == grant.module))
.map(|grant| Use {
module: grant.module.clone(),
scope: grant.scope.clone(),
written: grant.written.clone(),
source: grant.source.clone(),
inherited: true,
})
.collect();
uses.extend(own);
uses
}
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),
inherited: false,
});
}
}
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))
}