use anyhow::Result;
use regex::Regex;
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use crate::graph::Graph;
use crate::hash;
use crate::model::{Law, Location, Target};
use crate::parse::{scan_root, PointerKind, Scan};
use crate::policy::{ProjectPolicy, TestMarkers};
use crate::scheme;
use crate::span;
use crate::walk;
use crate::workspace::{LawScans, ProjectRef, Workspace};
static PROVISIONAL_DECLARE_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"§\??\s*\+([a-z0-9-]+)").expect("provisional declare regex"));
static PROVISIONAL_MARKER_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^\x{FEFF}?\s*(?://|\{/\*|#|--|<!--)\s*§\s*(?:end\s+)?\+([a-z0-9-]+)")
.expect("provisional marker regex")
});
static PROVISIONAL_NAME_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"\+([a-z0-9-]+)").expect("provisional name regex"));
pub struct CheckReport {
pub files: usize,
pub ok: BTreeMap<String, usize>,
pub errors: Vec<String>,
pub drifts: Vec<String>,
pub harness: Vec<String>,
pub warnings: Vec<String>,
pub drafts: Vec<String>,
pub named: Vec<String>,
pub doc_verified: usize,
}
impl CheckReport {
fn empty() -> Self {
Self {
files: 0,
ok: BTreeMap::new(),
errors: Vec::new(),
drifts: Vec::new(),
harness: Vec::new(),
warnings: Vec::new(),
drafts: Vec::new(),
named: Vec::new(),
doc_verified: 0,
}
}
pub fn is_closed(&self) -> bool {
self.errors.is_empty() && self.drifts.is_empty() && self.harness.is_empty()
}
}
#[derive(Default)]
pub struct Others {
pub own: String,
pub graphs: BTreeMap<String, Graph>,
}
impl Others {
pub fn from_scans(scans: &LawScans) -> Self {
Self {
own: scans.own.clone(),
graphs: scans
.scans
.iter()
.map(|(key, scan)| (key.clone(), Graph::from_scan(scan)))
.collect(),
}
}
fn projects(&self) -> String {
let mut keys: Vec<&str> = self.graphs.keys().map(String::as_str).collect();
keys.push(&self.own);
keys.sort();
keys.iter()
.map(|k| format!("`{k}`"))
.collect::<Vec<_>>()
.join(", ")
}
fn declaring(&self, id: &str) -> Vec<&str> {
self.graphs
.iter()
.filter(|(_, graph)| graph.by_id.contains_key(id))
.map(|(key, _)| key.as_str())
.collect()
}
}
pub fn validate(ws: &Workspace, projects: &[&ProjectRef], prefix: bool) -> Result<CheckReport> {
let mut report = CheckReport::empty();
for project in projects {
let one = validate_project(ws, project)?;
let tag = |text: String| {
if prefix {
format!("[{}] {text}", project.key)
} else {
text
}
};
report.files += one.files;
report.doc_verified += one.doc_verified;
for (name, count) in one.ok {
*report.ok.entry(tag(name)).or_default() += count;
}
report.errors.extend(one.errors.into_iter().map(tag));
report.drifts.extend(one.drifts.into_iter().map(tag));
report.harness.extend(one.harness.into_iter().map(tag));
report.warnings.extend(one.warnings.into_iter().map(tag));
report.drafts.extend(one.drafts.into_iter().map(tag));
}
for d in crate::harness::probe_drift(&ws.root)? {
push_drift(d, &mut report);
}
Ok(report)
}
pub fn accepted_pins(
ws: &Workspace,
projects: &[&ProjectRef],
base: &str,
prefix: bool,
) -> Result<Vec<String>> {
use crate::marker::MarkerAddr;
let short = crate::published::short(base);
let mut out = Vec::new();
for project in projects {
let root = project.dir.as_path();
let scan = scan_root(root)?;
let mut found = Vec::new();
let agents = std::fs::read_to_string(root.join("AGENTS.md")).ok();
let then = crate::published::agents_at(root, base)?;
for (attr, was, is) in crate::published::block_changes(then.as_deref(), agents.as_deref()) {
found.push(format!(
"AGENTS.md: the Silcrow block writes {}, and {short} wrote {}: the block decides what the tree is held to.",
block_attr(attr, is.as_deref()),
block_attr(attr, was.as_deref())
));
}
let alias: BTreeMap<&str, &str> = scan
.laws
.iter()
.flat_map(|law| law.aliases.iter().map(|a| (a.as_str(), law.id.as_str())))
.collect();
let touched = crate::diff::touched(root, base)?;
let changed_now: BTreeSet<&PathBuf> = touched.values().collect();
let mut bound_then = bindings_at(root, base, &touched)?;
let mut was: BTreeMap<MarkerAddr, BTreeMap<PathBuf, Vec<HeldPin>>> = BTreeMap::new();
for (mut addr, digests) in crate::published::pinned_at(root, base)? {
let written = addr.clone();
if let (None, Some(id)) = (&addr.project, alias.get(addr.id.as_str())) {
addr.id = id.to_string();
}
let held = was.entry(addr).or_default();
for (digest, paths) in digests {
for path in paths {
let binding = bound_then
.get_mut(&(path.clone(), written.clone(), digest.clone()))
.and_then(|names| (!names.is_empty()).then(|| names.remove(0)));
let at = touched.get(&path).cloned().unwrap_or(path);
held.entry(at).or_default().push(HeldPin {
digest: digest.clone(),
binding,
});
}
}
}
let folded = crate::diff::folded_pins(ws, root, base)?;
let mut now: BTreeMap<MarkerAddr, PinsByFile> = BTreeMap::new();
let mut nested = Vec::new();
for path in walk::code_files(root)? {
let text = std::fs::read_to_string(&path)?;
let rel = path.strip_prefix(root).unwrap_or(&path);
let digest_of = |pin: MarkerAddr, line: usize| match pin.clone().split_digest() {
Some((addr, digest)) => {
let folded = folded.get(&(rel.to_path_buf(), line)).cloned();
(addr, Some(folded.unwrap_or(digest)))
}
None => (pin, None),
};
let file = text
.contains('§')
.then(|| span::CodeFile::new(rel.to_path_buf(), text.clone()));
let markers = file.as_ref().map(span::CodeFile::span_markers);
let binding_at = |line: usize| {
let file = file
.as_ref()
.filter(|_| changed_now.contains(&rel.to_path_buf()))?;
let marker = markers.iter().flatten().find(|m| m.line == line)?;
file.binding(marker.start, marker.end)
};
for row in span::marker_rows(rel, &text, None) {
for pin in row.markers {
let (addr, digest) = digest_of(pin, row.idx + 1);
now.entry(addr)
.or_default()
.entry(rel.to_path_buf())
.or_default()
.push(NowPin {
line: row.idx + 1,
binding: digest.as_ref().and_then(|_| binding_at(row.idx + 1)),
digest,
});
}
}
let Some(markers) = markers else {
continue;
};
let pinned: Vec<_> = markers
.iter()
.filter(|m| m.addr.digest.is_some())
.map(|m| (m, digest_of(m.addr.clone(), m.line)))
.collect();
for (inner, (addr, _)) in &pinned {
for (outer, (around, held)) in &pinned {
if around != addr
&& span::nests_in((inner.start, inner.end), (outer.start, outer.end))
{
nested.push((
rel.to_path_buf(),
inner.line,
addr.clone(),
around.clone(),
held.clone(),
));
}
}
}
}
let active = active_addresses(&scan.laws);
let base_files = crate::published::files_at(root, base)?;
let mut new_pins: BTreeSet<(PathBuf, usize, MarkerAddr)> = BTreeSet::new();
let addrs: BTreeSet<&MarkerAddr> = was.keys().chain(now.keys()).collect();
for addr in addrs {
let mut moved_out: Vec<(&PathBuf, &String)> = Vec::new();
let mut moved_in: Vec<(&PathBuf, usize, &String)> = Vec::new();
let held = was.get(addr);
let pins = now.get(addr);
let paths: BTreeSet<&PathBuf> = held
.into_iter()
.flat_map(BTreeMap::keys)
.chain(pins.into_iter().flat_map(BTreeMap::keys))
.collect();
let a = addr.display();
let elsewhere = |path: &PathBuf, digest: &String| {
let files: Vec<String> = pins
.into_iter()
.flatten()
.filter(|(other, list)| {
*other != path && list.iter().any(|p| p.digest.as_ref() == Some(digest))
})
.map(|(other, _)| other.display().to_string())
.collect();
match files.is_empty() {
true => String::new(),
false => format!(
" {} carries that pin now, and a pin pairs only within its own file, or from a file the tree no longer holds into one {short} did not hold.",
files.join(", ")
),
}
};
for path in paths {
let mut gone: Vec<&HeldPin> = held
.and_then(|held| held.get(path))
.map(|ds| ds.iter().collect())
.unwrap_or_default();
let mut left: Vec<&NowPin> = Vec::new();
for pin in pins.and_then(|pins| pins.get(path)).into_iter().flatten() {
match gone.iter().position(|g| g.pairs(pin)) {
Some(at) => {
gone.remove(at);
}
None => left.push(pin),
}
}
if gone.is_empty() {
for pin in &left {
match &pin.digest {
Some(d) if !base_files.contains(path) => {
moved_in.push((path, pin.line, d))
}
Some(_) => {
new_pins.insert((path.clone(), pin.line, addr.clone()));
}
None => {}
}
}
continue;
}
if left.is_empty() && !root.join(path).is_file() {
moved_out.extend(gone.into_iter().map(|g| (path, &g.digest)));
continue;
}
let was_pinned = gone
.iter()
.map(|g| format!("@{}", g.digest))
.collect::<Vec<_>>()
.join(", ");
let rel = path.display();
for pin in &left {
let line = pin.line;
let twin = gone.iter().find(|g| pin.digest.as_ref() == Some(&g.digest));
found.push(match (&pin.digest, twin) {
(Some(d), Some(twin)) => format!(
"{rel}:{line}: § {a} pins {} now, and {short} pinned {} with @{d}: its marker moved to another construct that reads alike, or that construct was renamed.",
construct(pin.binding.as_deref()),
construct(twin.binding.as_deref())
),
(Some(d), None) => format!(
"{rel}:{line}: § {a} carries @{d}, and {short} pinned it here as {was_pinned}: it was re-pinned."
),
(None, _) => format!(
"{rel}:{line}: § {a} is bare, and {short} pinned it here as {was_pinned}: its span is no longer pinned."
),
});
}
if !left.is_empty() {
continue;
}
let why = if addr.project.is_none() && !active.contains(&a) {
"the address no longer exists"
} else {
"no marker of it in this file carries that pin now"
};
for g in gone {
let digest = &g.digest;
found.push(format!(
"{rel}: § {a} was pinned @{digest} at {short}, and {why}: its marker moved or its pin was removed.{}",
elsewhere(path, digest)
));
}
}
for (path, line, digest) in moved_in {
match moved_out.iter().position(|(_, d)| *d == digest) {
Some(at) => {
moved_out.remove(at);
}
None => {
new_pins.insert((path.clone(), line, addr.clone()));
}
}
}
for (path, digest) in moved_out {
let where_now = elsewhere(path, digest);
let why = match where_now.is_empty() {
true => "no file the tree holds now carries that pin",
false => "the tree no longer holds that file",
};
found.push(format!(
"{}: § {a} was pinned @{digest} at {short}, and {why}: its marker moved or its pin was removed.{where_now}",
path.display()
));
}
}
let mut named_nested = BTreeSet::new();
for (rel, line, addr, around, held) in nested {
let published = was
.get(&around)
.and_then(|held_at| held_at.get(&rel))
.is_some_and(|ds| ds.iter().any(|g| held.as_ref() == Some(&g.digest)));
let key = (rel, line, addr);
if published && new_pins.contains(&key) {
found.push(format!(
"{}:{line}: § {} is a new pin inside the span of § {}, which {short} pinned: the code it holds left that span unread.",
key.0.display(),
key.2.display(),
around.display()
));
named_nested.insert(key);
}
}
let point = crate::published::at(root, base)?;
let held_at_point = held_addresses(&scan.laws, point.laws());
for (rel, line, addr) in new_pins.difference(&named_nested) {
let a = addr.display();
if addr.project.is_some() || held_at_point.contains(&a) {
found.push(format!(
"{}:{line}: § {a} carries a pin {short} did not hold, for an address it held: it was added.",
rel.display()
));
}
}
found.extend(vanished_pins(project, base)?);
let published = &point;
let keys = published.keys();
for law in &scan.laws {
for old in law.aliases.iter().filter(|a| keys.contains(*a)) {
if keys.contains(&law.id) {
found.push(format!(
"{}:{}: § {old} was published at {short}, and the tree keeps its id only as an alias anchor of § {}, which {short} published apart: it was deleted.",
law.loc.path.display(),
law.loc.line,
law.id
));
continue;
}
found.push(format!(
"{}:{}: § {} was reminted from the published § {old}: its carrying sentence changed.",
law.loc.path.display(),
law.loc.line,
law.id
));
}
}
found.extend(reworded_laws(&scan.laws, published.laws(), short));
found.extend(drafted_laws(&scan.laws, published.laws(), short));
found.extend(added_laws(&scan.laws, published.laws(), short));
let carried: BTreeSet<&str> = scan
.laws
.iter()
.flat_map(|law| std::iter::once(&law.id).chain(&law.aliases))
.map(String::as_str)
.collect();
for law in published.laws() {
if hash::is_provisional_id(&law.id) || carried.contains(law.id.as_str()) {
continue;
}
let how = if law.struck {
"its published strike was removed"
} else {
"it was deleted without a strike"
};
found.push(format!(
"{}:{}: § {} was published at {short}, and the tree no longer declares it: {how}.",
law.loc.path.display(),
law.loc.line,
law.id
));
}
for text in found {
out.push(if prefix {
format!("[{}] {text}", project.key)
} else {
text
});
}
}
Ok(out)
}
fn reworded_laws(now: &[Law], published: &[Law], short: &str) -> Vec<String> {
let mut out = Vec::new();
for then in published
.iter()
.filter(|law| !hash::is_provisional_id(&law.id))
{
let Some(law) = now.iter().find(|law| law.id == then.id) else {
continue;
};
let mut changed = Vec::new();
if then.struck {
if law.struck {
continue;
}
if hash::pin_canon(&law.pin_text()) != hash::pin_canon(&then.pin_text()) {
changed.push("its head reads otherwise".to_string());
}
if hash::pin_canon(&law.context) != hash::pin_canon(&then.context) {
changed.push("its context reads otherwise".to_string());
}
for clause in then.clauses.iter().filter(|c| !c.struck) {
let Some(letter) = &clause.letter else {
continue;
};
let now = law
.clauses
.iter()
.find(|c| c.letter.as_ref() == Some(letter) && !c.struck);
if now.is_some_and(|c| {
hash::pin_canon(&c.pin_body()) != hash::pin_canon(&clause.pin_body())
}) {
changed.push(format!("({letter}) reads otherwise"));
}
}
if !changed.is_empty() {
out.push(format!(
"{}:{}: § {} was published struck at {short}, and the tree revives it with text it did not publish, {}: read the change in `silcrow diff`.",
law.loc.path.display(),
law.loc.line,
law.id,
changed.join(", ")
));
}
continue;
}
if law.struck {
changed.push("it is struck".to_string());
} else {
if hash::pin_canon(&law.pin_text()) != hash::pin_canon(&then.pin_text()) {
changed.push("its head reads otherwise".to_string());
}
if hash::pin_canon(&law.context) != hash::pin_canon(&then.context) {
changed.push(
"its context, the prose between its head and its clauses, reads otherwise"
.to_string(),
);
}
for clause in then.clauses.iter().filter(|c| !c.struck) {
let Some(letter) = &clause.letter else {
continue;
};
match law
.clauses
.iter()
.find(|c| c.letter.as_ref() == Some(letter))
{
None => changed.push(format!("({letter}) is deleted")),
Some(c) if c.struck => changed.push(format!("({letter}) is struck")),
Some(c)
if hash::pin_canon(&c.pin_body())
!= hash::pin_canon(&clause.pin_body()) =>
{
changed.push(format!("({letter}) reads otherwise"))
}
Some(_) => {}
}
}
}
if changed.is_empty() {
continue;
}
out.push(format!(
"{}:{}: § {} was published at {short}, and {}: read the change in `silcrow diff`.",
law.loc.path.display(),
law.loc.line,
law.id,
changed.join(", ")
));
}
out
}
fn drafted_laws(now: &[Law], published: &[Law], short: &str) -> Vec<String> {
let mut out = Vec::new();
for law in now
.iter()
.filter(|law| !law.struck && !hash::is_provisional_id(&law.id))
{
let then = published
.iter()
.find(|then| !then.struck && (then.id == law.id || law.aliases.contains(&then.id)));
let (mut made, mut new) = (Vec::new(), Vec::new());
match then {
None if law.draft => new.push(format!("§ {}", law.id)),
None => {}
Some(then) => {
let law_made = law.draft && !then.draft;
if law_made {
made.push(format!("§ {}", law.id));
}
for clause in law.clauses.iter().filter(|c| !c.struck && c.draft) {
let Some(letter) = &clause.letter else {
continue;
};
let address = format!("§ {}.{letter}", law.id);
match then
.clauses
.iter()
.find(|c| c.letter.as_ref() == Some(letter) && !c.struck)
{
None => new.push(address),
Some(held) if !held.draft && !law_made => made.push(address),
Some(_) => {}
}
}
}
}
let at = format!("{}:{}", law.loc.path.display(), law.loc.line);
if !made.is_empty() {
out.push(format!(
"{at}: {} owed its markers at {short}, and the tree makes it a draft, which owes none.",
made.join(", ")
));
}
if !new.is_empty() {
out.push(format!(
"{at}: {} is a draft {short} did not hold, a promise the tree keeps before its code.",
new.join(", ")
));
}
}
out
}
fn added_laws(now: &[Law], published: &[Law], short: &str) -> Vec<String> {
let mut out = Vec::new();
for law in now
.iter()
.filter(|law| !law.struck && !hash::is_provisional_id(&law.id))
{
let at = format!("{}:{}", law.loc.path.display(), law.loc.line);
let then = published
.iter()
.find(|then| !then.struck && (then.id == law.id || law.aliases.contains(&then.id)));
let Some(then) = then else {
let held = published.iter().any(|then| then.id == law.id);
if !law.draft && !held {
out.push(format!(
"{at}: § {} is a law {short} did not hold, a promise the tree adds.",
law.id
));
}
continue;
};
let added: Vec<String> = law
.clauses
.iter()
.filter(|c| !c.struck && !c.draft && !law.draft)
.filter_map(|c| c.letter.as_ref())
.filter(|letter| {
!then
.clauses
.iter()
.any(|c| c.letter.as_ref() == Some(*letter) && !c.struck)
})
.map(|letter| format!("§ {}.{letter}", law.id))
.collect();
if !added.is_empty() {
out.push(format!(
"{at}: {} is a clause {short} did not hold, a promise the tree adds.",
added.join(", ")
));
}
match (then.public, law.public) {
(false, true) => out.push(format!(
"{at}: § {} was a plain law at {short}, and the tree makes it a public promise, which owes a documentation marker.",
law.id
)),
(true, false) => out.push(format!(
"{at}: § {} was a public promise at {short}, and the tree makes it plain, which owes no documentation marker.",
law.id
)),
_ => {}
}
}
out
}
fn held_addresses(now: &[Law], published: &[Law]) -> BTreeSet<String> {
let mut out = BTreeSet::new();
for then in published.iter().filter(|law| !law.struck) {
let id = now
.iter()
.find(|law| law.id == then.id || law.aliases.contains(&then.id))
.map_or(&then.id, |law| &law.id);
out.insert(id.clone());
for clause in then.clauses.iter().filter(|c| !c.struck) {
if let Some(letter) = &clause.letter {
out.insert(format!("{id}.{letter}"));
}
}
}
out
}
type PinsByFile = BTreeMap<PathBuf, Vec<NowPin>>;
struct NowPin {
line: usize,
digest: Option<String>,
binding: Option<Vec<String>>,
}
struct HeldPin {
digest: String,
binding: Option<Vec<String>>,
}
impl HeldPin {
fn pairs(&self, pin: &NowPin) -> bool {
pin.digest.as_ref() == Some(&self.digest)
&& match (&self.binding, &pin.binding) {
(Some(then), Some(now)) => then == now,
_ => true,
}
}
}
fn construct(binding: Option<&[String]>) -> String {
match binding {
Some([]) => "the top level of its file".to_string(),
Some(names) => format!("`{}`", names.join("::")),
None => "a construct no grammar names".to_string(),
}
}
fn block_attr(attr: &str, value: Option<&str>) -> String {
match value {
Some(value) => format!("`{attr}=\"{value}\"`"),
None => format!("no `{attr}`"),
}
}
type HeldBindings = BTreeMap<(PathBuf, crate::marker::MarkerAddr, String), Vec<Vec<String>>>;
fn bindings_at(
root: &Path,
base: &str,
touched: &BTreeMap<PathBuf, PathBuf>,
) -> Result<HeldBindings> {
let rels: Vec<PathBuf> = touched.keys().cloned().collect();
let mut out = HeldBindings::new();
for (rel, text) in rels
.iter()
.zip(crate::published::blobs_at(root, base, &rels)?)
{
let Some(text) = text.filter(|t| t.contains('§')) else {
continue;
};
let file = span::CodeFile::new(rel.clone(), text);
for marker in file.span_markers() {
let (Some((addr, digest)), Some(names)) = (
marker.addr.clone().split_digest(),
file.binding(marker.start, marker.end),
) else {
continue;
};
out.entry((rel.clone(), addr, digest))
.or_default()
.push(names);
}
}
Ok(out)
}
fn vanished_pins(project: &ProjectRef, base: &str) -> Result<Vec<String>> {
let root = project.dir.as_path();
let short = crate::published::short(base);
let mut out = Vec::new();
for nested in crate::published::projects_at(root, base)? {
let held = nested
.ancestors()
.filter(|dir| !dir.as_os_str().is_empty())
.any(|dir| walk::is_project(&root.join(dir)));
if held {
continue;
}
let key = crate::workspace::in_workspace(&project.key, &nested);
let key = key.to_string_lossy();
for (addr, digests) in crate::published::pinned_at(&root.join(&nested), base)? {
let a = match addr.project {
Some(_) => addr.display(),
None => format!("{key}:{}", addr.display()),
};
for (digest, rel) in digests
.iter()
.flat_map(|(digest, paths)| paths.iter().map(move |rel| (digest, rel)))
{
out.push(format!(
"{}: § {a} was pinned @{digest} at {short}, and its project `{key}` no longer exists: its laws and its pins left the tree.",
nested.join(rel).display()
));
}
}
for law in crate::published::at(&root.join(&nested), base)?.laws() {
if hash::is_provisional_id(&law.id) {
continue;
}
out.push(format!(
"{}:{}: § {key}:{} was published at {short}, and its project `{key}` no longer exists: its laws left the tree.",
nested.join(&law.loc.path).display(),
law.loc.line,
law.id
));
}
}
Ok(out)
}
pub fn returned_tokens(projects: &[&ProjectRef], base: &str, prefix: bool) -> Result<Vec<String>> {
let short = crate::published::short(base);
let mut out = Vec::new();
for project in projects {
let root = project.dir.as_path();
let scan = scan_root(root)?;
let mut found = Vec::new();
let ids: BTreeSet<String> = scan
.laws
.iter()
.map(|law| law.id.clone())
.filter(|id| !hash::is_provisional_id(id))
.collect();
let removed = crate::published::removed_at(root, base, &ids)?;
for law in scan.laws.iter().filter(|law| removed.contains(&law.id)) {
found.push(format!(
"{}:{}: § {} is declared, and a removed law carried that id in the history of {short}: an id never comes back with another meaning. Reword the carrying sentence.",
law.loc.path.display(),
law.loc.line,
law.id
));
}
let published = crate::published::at(root, base)?;
let history = crate::published::held_letters(root, base)?;
for law in &scan.laws {
let base_law = published.law_of(law);
let burned = |letter: &String| {
let Some(b) = base_law else {
return false;
};
match b.clauses.iter().find(|c| c.letter.as_ref() == Some(letter)) {
Some(c) => c.struck,
None => std::iter::once(&b.id)
.chain(&b.aliases)
.any(|id| history.get(id).is_some_and(|held| held.contains(letter))),
}
};
for clause in law.clauses.iter().filter(|c| !c.struck) {
let Some(letter) = clause.letter.as_ref().filter(|l| burned(l)) else {
continue;
};
found.push(format!(
"{}:{}: § {}.{letter} is an active clause on a letter that {short} holds struck or as a tombstone, or that its history wrote: a burned letter never takes another meaning. Write ({letter}) struck or as the tombstone `- ({letter}) **Retired.**` again, and give the new clause the letter `(+)`.",
clause.loc.path.display(),
clause.loc.line,
law.id
));
}
let Some(held) = published.letters_of(law) else {
continue;
};
let written: BTreeSet<String> = law
.clauses
.iter()
.filter_map(|c| c.letter.clone())
.collect();
for letter in held.difference(&written) {
found.push(format!(
"{}:{}: § {}.{letter} was written at {short} and the tree no longer writes it: a letter stays in the tree while its law does, struck or as the tombstone `- ({letter}) **Retired.**`, so no clause is written on it again.",
law.loc.path.display(),
law.loc.line,
law.id
));
}
}
out.extend(found.into_iter().map(|text| {
if prefix {
format!("[{}] {text}", project.key)
} else {
text
}
}));
}
Ok(out)
}
fn active_addresses(laws: &[Law]) -> BTreeSet<String> {
let mut out = BTreeSet::new();
for law in laws.iter().filter(|law| !law.struck) {
out.insert(law.id.clone());
for al in law.clauses.iter().filter(|al| !al.struck) {
if let Some(letter) = &al.letter {
out.insert(format!("{}.{letter}", law.id));
}
}
}
out
}
fn push_drift(d: crate::harness::Drift, report: &mut CheckReport) {
let text = crate::harness::drift_text(&d);
let ci = crate::notice::ci_job(std::env::var("CI").ok().as_deref());
if d.versioned && !ci {
report.harness.push(text);
} else {
report.warnings.push(text);
}
}
fn validate_project(ws: &Workspace, project: &ProjectRef) -> Result<CheckReport> {
let root = project.dir.as_path();
let policy = match ProjectPolicy::explicit_at(root) {
Ok(policy) => policy,
Err(message) => {
return Ok(CheckReport {
errors: vec![message],
..CheckReport::empty()
});
}
};
std::thread::scope(|s| {
let code = crate::par::spawn(s, || {
let code = span::CodeFile::read_all(root)?;
let follow = crate::follow::FollowIndex::from_files(&code, &policy.tests);
anyhow::Ok((code, follow))
});
let provisional = s.spawn(|| scan_provisional_references(root));
let scan = scan_root(root)?;
let graph = Graph::from_scan(&scan);
let scans = ws.law_scans(&project.key)?;
let others = Others::from_scans(&scans);
let notes = walk::decision_files(root)?.len();
let files = notes + walk::code_files(root)?.len();
let (code, follow) = joined(code)?;
let mut drifts = Vec::new();
let paths = walk::Project::at(root)?;
let mut report = evaluate(&scan, &graph, files, &policy, &paths.notes, &others);
report.drafts = draft_lines(&scan, Some(root));
note_sizes(root, &policy, &mut report)?;
if let Some(error) = no_notes_matched(root, notes, &scan) {
report.errors.push(error);
}
report.errors.extend(joined(provisional)?);
if let Some(d) = crate::harness::project_drift(root)? {
push_drift(d, &mut report);
}
report.errors.extend(follow.mark_errors().iter().cloned());
let texts = span::PinTexts::for_project(&scan, &scans);
let bare: Vec<PathBuf> = code
.iter()
.filter(|file| {
file.marker_lines().any(|(_, line)| {
crate::marker::markers_in_line(line)
.iter()
.any(|m| m.digest.is_none())
})
})
.map(|file| file.rel.clone())
.collect();
let drifted: BTreeMap<(PathBuf, usize), String> = match bare.is_empty() {
true => BTreeMap::new(),
false => span::drifted_bare(root, &span::pin_bare(root, &texts, Some(&bare))?)?
.into_iter()
.map(|d| ((d.rel.clone(), d.line), d.held_digests()))
.collect(),
};
let checks = crate::par::map(
code.iter().collect(),
|f| f.text.len(),
|file| span::verify_file_follow(file, scheme::SERIALIZATION, &follow, &texts),
);
for (file, checked) in code.iter().zip(checks) {
if let Some(err) = file.too_deep() {
report.errors.push(err);
continue;
}
report.errors.extend(checked.errors);
drifts.extend(checked.drifts);
report.warnings.extend(checked.warnings);
if marker_surface(&file.rel, &paths.notes, &policy) == Some(MarkerSurface::Doc) {
report.doc_verified += checked.verified;
}
check_span_pins(
file,
&checked.unhashable,
&checked.inert,
&drifted,
&mut report,
);
}
test_code_markers(&code, &policy, &paths.notes, &mut report);
for file in &code {
check_duplicate_markers(file, &mut report.errors);
check_one_lists(file, &mut report.errors);
check_marker_form(file, &mut report);
}
report
.warnings
.extend(untracked_reads(root, &code, &follow)?);
report.drifts = drift_messages(root, &scan, code, follow, &drifts)?;
report
.warnings
.extend(walk::skipped_files(root)?.iter().map(|path| {
format!(
"{}: it is not UTF-8 text, Silcrow parses no grammar of its extension, and no line of it is shaped as a marker, so no verb reads it",
path.strip_prefix(root).unwrap_or(path).display()
)
}));
Ok(report)
})
}
fn drift_messages(
root: &Path,
scan: &Scan,
code: Vec<span::CodeFile>,
follow: crate::follow::FollowIndex,
drifts: &[span::Drift],
) -> Result<Vec<String>> {
let fallback = || drifts.iter().map(|d| d.message(None)).collect();
if drifts.is_empty() {
return Ok(Vec::new());
}
let head = crate::workspace::git(root)
.args(["rev-parse", "--verify", "-q", "HEAD"])
.output()?;
if !head.status.success() {
return Ok(fallback());
}
let then = crate::diff::Tree::at(root, "HEAD")?;
let now = crate::diff::Tree::of(code, follow, &scan.laws);
let scheme = crate::hook::recorded_scheme_at(root, "HEAD")?
.filter(|&recorded| recorded != scheme::BINARY_VERSION);
let mut out = Vec::new();
for d in drifts {
let cause = match crate::span_lang::lang_for_path(&d.path) {
None => fallback_cause(root, (&then, &now), d)?,
Some(_) => {
let aliases = scan
.laws
.iter()
.find(|law| d.pin.project.is_none() && law.id == d.pin.id)
.map_or(&[][..], |law| law.aliases.as_slice());
drift_cause(&then, &now, d, aliases, scheme)
}
};
out.push(d.message(cause.as_deref()));
}
Ok(out)
}
fn fallback_cause(
root: &Path,
(then, now): (&crate::diff::Tree, &crate::diff::Tree),
d: &span::Drift,
) -> Result<Option<String>> {
let Some(Some(old)) =
crate::published::blobs_at(root, "HEAD", std::slice::from_ref(&d.path))?.pop()
else {
return Ok(None);
};
let text = std::fs::read_to_string(root.join(&d.path))?;
let address = crate::marker::MarkerAddr {
digest: None,
..d.pin.clone()
}
.display();
let path = d.path.to_string_lossy();
let new = crate::diff::PinAt {
path: &path,
text: &text,
line: d.line,
bit: &d.bit,
};
Ok(
match crate::diff::fallback_moved(&address, (then, &old), (now, new)) {
Some((true, true)) => {
Some("its stretch and its law or clause text read otherwise".into())
}
Some((true, false)) => Some("its stretch reads otherwise".into()),
Some((false, true)) => Some("its law or clause text reads otherwise".into()),
_ => None,
},
)
}
fn drift_cause(
then: &crate::diff::Tree,
now: &crate::diff::Tree,
d: &span::Drift,
aliases: &[String],
scheme: Option<u32>,
) -> Option<String> {
let (alias, (old_path, old_line, old_bit)) = match then.pin(&d.pin, &d.path) {
Some(found) => (None, found),
None => aliases.iter().find_map(|id| {
let was = crate::marker::MarkerAddr {
id: id.clone(),
..d.pin.clone()
};
then.pin(&was, &d.path).map(|found| (Some(id), found))
})?,
};
let reminted = |text: &str| match alias {
Some(id) => text.replace(id.as_str(), &d.pin.id),
None => text.to_string(),
};
let (old_text, old_bit) = (reminted(then.text(&old_path)?), reminted(&old_bit));
let address = crate::marker::MarkerAddr {
digest: None,
..d.pin.clone()
}
.display();
let (old_rel, new_rel) = (old_path.to_string_lossy(), d.path.to_string_lossy());
let old = crate::diff::PinAt {
path: &old_rel,
text: &old_text,
line: old_line,
bit: &old_bit,
};
let new = crate::diff::PinAt {
path: &new_rel,
text: now.text(&d.path)?,
line: d.line,
bit: &d.bit,
};
let moved = crate::diff::moved(&address, (then, old), (now, new)).ok()?;
let mut parts: Vec<String> = Vec::new();
if moved.span {
parts.push("its span".to_string());
}
if moved.prefix {
parts.push("the code before it".to_string());
}
for (name, path) in &moved.callees {
parts.push(format!("the followed callee `{name}` in {path}"));
}
if moved.import {
parts.push("an import line it spells".to_string());
}
if moved.text {
parts.push("its law or clause text".to_string());
}
if let (Some(project), true) = (&d.pin.project, parts.is_empty()) {
parts.push(format!(
"its law or clause text in `{project}` or its project path"
));
}
let mut cause = match parts.as_slice() {
[] => None,
[one] => Some(format!("{one} reads otherwise")),
[rest @ .., last] => Some(format!("{} and {last} read otherwise", rest.join(", "))),
};
for (name, decl) in &moved.left {
let left = format!(
"the callee `{name}`, declared in {decl} alone, lies outside the directory of {new_rel} and its subdirectories, where an unmarked call follows, so it is followed no more"
);
cause = Some(match cause {
Some(cause) => format!("{cause}, and {left}"),
None => left,
});
}
if let Some(recorded) = scheme {
let bump = format!(
"the hashing scheme moved from {recorded} to {}",
scheme::BINARY_VERSION
);
cause = Some(match cause {
Some(cause) => format!("{cause}, and {bump}"),
None => bump,
});
}
cause
}
fn test_code_markers(
code: &[span::CodeFile],
policy: &ProjectPolicy,
notes: &walk::Notes,
report: &mut CheckReport,
) {
let (out, verdict) = match policy.test_markers {
TestMarkers::Allow => return,
TestMarkers::Warn => (
&mut report.warnings,
"the `AGENTS.md` block admits it with a warning under `test-markers=\"warn\"`",
),
TestMarkers::Error => (
&mut report.errors,
"a marker there fails `check` under `test-markers=\"error\"`, the default",
),
};
let rows = span::test_rows(code);
for file in code {
if crate::marker::is_markdown(&file.rel)
|| marker_surface(&file.rel, notes, policy) == Some(MarkerSurface::Doc)
{
continue;
}
let whole = policy.tests.holds(&file.rel);
let gated = rows.get(&file.rel).map(Vec::as_slice).unwrap_or_default();
for (idx, line) in file.marker_lines() {
if !whole && !gated.iter().any(|&(a, b)| a <= idx && idx <= b) {
continue;
}
for addr in crate::marker::markers_in_line(line) {
let project = addr.project.map(|p| format!("{p}:")).unwrap_or_default();
let letter = addr.letter.map(|l| format!(".{l}")).unwrap_or_default();
out.push(format!(
"{}:{}: § {project}{}{letter} sits in test code, and {verdict}. Move it onto the code that decides its law, or set `test-markers=\"allow\"` where a test carries a law no code of this tree decides.",
file.rel.display(),
idx + 1,
addr.id
));
}
}
}
}
fn note_sizes(root: &Path, policy: &ProjectPolicy, report: &mut CheckReport) -> Result<()> {
let out = if policy.note_words.warn {
&mut report.warnings
} else {
&mut report.errors
};
for path in walk::decision_files(root)? {
let words = std::fs::read_to_string(&path)?.split_whitespace().count();
if words <= policy.note_words.limit {
continue;
}
let rel = path.strip_prefix(root).unwrap_or(&path);
out.push(format!(
"{}: the note holds {words} words, past the limit of {} the `note-words` attribute of the `AGENTS.md` block sets. Split it by sub-topic into notes under `{}/`, a directory of the same name.",
rel.display(),
policy.note_words.limit,
rel.with_extension("").display()
));
}
Ok(())
}
fn untracked_reads(
root: &Path,
code: &[span::CodeFile],
follow: &crate::follow::FollowIndex,
) -> Result<Vec<String>> {
let untracked: BTreeSet<PathBuf> = walk::untracked_files(root)?
.into_iter()
.filter_map(|path| path.strip_prefix(root).ok().map(Path::to_path_buf))
.collect();
if untracked.is_empty() {
return Ok(Vec::new());
}
let followed = follow.followed_paths();
let read = follow.read_names();
Ok(code
.iter()
.filter(|file| untracked.contains(&file.rel))
.filter_map(|file| {
if followed.contains(&file.rel) {
return Some(format!(
"{}: git does not track it, and it holds a body a span follows: the pre-commit hook and CI read only what git holds, so a pin written through it reads otherwise there. Run `git add` on it, or ignore it.",
file.rel.display()
));
}
let names: Vec<String> = follow
.declared_in(&file.rel)
.into_iter()
.filter(|name| read.contains(name))
.map(|name| format!("`{name}`"))
.collect();
(!names.is_empty()).then(|| {
format!(
"{}: git does not track it, and it declares {}, which a span calls or reads: the pre-commit hook and CI read only what git holds, so what that call resolves to, and a pin written through it, may read otherwise there. Run `git add` on it, or ignore it.",
file.rel.display(),
names.join(", ")
)
})
})
.collect())
}
fn joined<T>(handle: std::thread::ScopedJoinHandle<'_, T>) -> T {
handle
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
}
fn check_duplicate_markers(file: &span::CodeFile, errors: &mut Vec<String>) {
let line_start: Vec<usize> = std::iter::once(0)
.chain(file.text.match_indices('\n').map(|(i, _)| i + 1))
.collect();
let inside = |outer: &span::SpanMarker, inner: &span::SpanMarker| {
(outer.start..outer.end).contains(&line_start[inner.line - 1])
};
let markers = file.span_markers();
for (i, first) in markers.iter().enumerate() {
for second in markers[i + 1..].iter().filter(|m| m.line != first.line) {
if (first.start, first.end) == (second.start, second.end) {
errors.push(format!(
"{}:{}: § {} and § {} at line {} share one span, so one pin guards nothing the other does not. Give each the code that carries it, with its own construct or a `§ end` line, or nest one strictly inside the other.",
file.rel.display(),
first.line,
first.addr.display(),
second.addr.display(),
second.line
));
continue;
}
let (a, b) = ((first.start, first.end), (second.start, second.end));
let disjoint = a.1 <= b.0 || b.1 <= a.0;
if !disjoint && !span::nests_in(a, b) && !span::nests_in(b, a) {
errors.push(format!(
"{}:{}: § {} and § {} at line {} have spans that overlap without one holding the other, so the code they share has two addresses. Close one stretch inside the other, or give each the code that carries it alone.",
file.rel.display(),
first.line,
first.addr.display(),
second.addr.display(),
second.line
));
continue;
}
if first.addr.display() != second.addr.display() {
continue;
}
if inside(first, second) || inside(second, first) {
errors.push(format!(
"{}:{}: § {} has two markers in one span, again at line {}. `silcrow fix` cannot merge them: keep the marker at the top of the construct that carries out the clause and delete the other.",
file.rel.display(),
first.line,
first.addr.display(),
second.line
));
}
}
}
}
fn check_one_lists(file: &span::CodeFile, errors: &mut Vec<String>) {
use crate::marker;
let path = file.rel.display();
for (idx, line) in file.marker_lines() {
if !marker::is_one(line) {
continue;
}
let at = idx + 1;
let list = marker::markers_in_line(line);
let mut seen = BTreeSet::new();
for addr in &list {
if !seen.insert(addr.display()) {
errors.push(format!(
"{path}:{at}: § {} appears twice in one `§ one` list. Keep one entry.",
addr.display()
));
}
let law = marker::MarkerAddr {
letter: None,
digest: None,
..addr.clone()
};
if addr.letter.is_some()
&& list.iter().any(|other| {
other.letter.is_none() && other.project == law.project && other.id == law.id
})
{
errors.push(format!(
"{path}:{at}: § {} and its own clause § {} share one `§ one` list. Keep the clause the statement carries.",
law.display(),
addr.display()
));
}
}
if file.lang.is_none() {
let ext = file.rel.extension().and_then(|e| e.to_str()).unwrap_or("?");
errors.push(format!(
"{path}:{at}: `§ one` needs a tested grammar to find the statement below it, and `.{ext}` has none. Use a marker with a `§ end` line."
));
} else if file.tree.is_some() && !file.has_span(idx) {
errors.push(format!(
"{path}:{at}: `§ one` has no statement or member after it in its construct. Place it on the line above the statement or member it pins."
));
}
}
for (idx, addr) in file.ends_on_one() {
errors.push(format!(
"{path}:{}: `§ end {addr}` closes a `§ one` marker, whose span is the statement below it. Delete the end, or make the marker a plain one.",
idx + 1
));
}
}
fn check_marker_form(file: &span::CodeFile, report: &mut CheckReport) {
use crate::marker;
let markdown = marker::is_markdown(&file.rel);
for line in marker::malformed_lines(marker::Dialect::of(&file.rel), &file.text) {
report.errors.push(format!(
"{}:{line}: this comment opens like a marker but is none: an address, and a digest after `@`, end at whitespace or at the close of the comment.",
file.rel.display()
));
}
if file.lang.is_none() {
let ext = file.rel.extension().and_then(|e| e.to_str()).unwrap_or("?");
for line in crate::fallback::undecided_lines(ext, &file.text) {
report.errors.push(format!(
"{}:{line}: this comment opens like a marker, but a quote left open above may run over it: Silcrow does not know the string rules of `.{ext}`, so it cannot tell a marker from a value there. Close the quote on its line, or move the marker above it.",
file.rel.display()
));
}
}
for line in trailing_markers(file) {
let jsx = matches!(file.lang.map(|l| l.id), Some("tsx" | "javascript"))
&& file
.text
.lines()
.nth(line - 1)
.is_some_and(|l| l.trim_start().starts_with("{/*"));
report.errors.push(match jsx {
true => format!(
"{}:{line}: a marker inside a JSX expression, `{{/* § ... */}}`, spans no construct, since Silcrow reads a marker as a comment of the code around JSX. Put it on a line of its own above the statement that returns the JSX, or move this child into a component of its own and mark that.",
file.rel.display()
),
false => format!(
"{}:{line}: this comment opens like a marker after other text on its line, and a marker opens its own line: move it to a line of its own above what it names.",
file.rel.display()
),
});
}
for line in macro_markers(file) {
report.errors.push(format!(
"{}:{line}: a marker inside the token tree of a Rust macro spans no construct, since Silcrow parses no macro arms. Close it with a `§ end` line, or move it above the macro.",
file.rel.display()
));
}
let canonical = crate::parse::canonical_pointers(markdown, &file.text);
for (idx, (was, now)) in file.text.lines().zip(canonical.lines()).enumerate() {
if was != now {
report.warnings.push(format!(
"{}:{}: a pointer is not in canonical form, it reads as `{}`. Run `silcrow fix` to write it so.",
file.rel.display(),
idx + 1,
now.trim()
));
}
}
}
fn macro_markers(file: &span::CodeFile) -> Vec<usize> {
let (Some(tree), Some("rust")) = (&file.tree, file.lang.map(|l| l.id)) else {
return Vec::new();
};
let line_start: Vec<usize> = std::iter::once(0)
.chain(file.text.match_indices('\n').map(|(i, _)| i + 1))
.collect();
let mut out: Vec<usize> = file
.span_markers()
.into_iter()
.filter(|m| !m.explicit)
.filter(|m| {
let at = line_start[m.line - 1];
let mut node = tree.root_node().descendant_for_byte_range(at, at);
while let Some(n) = node {
if n.kind() == "token_tree" {
return true;
}
node = n.parent();
}
false
})
.map(|m| m.line)
.collect();
out.dedup();
out
}
fn trailing_markers(file: &span::CodeFile) -> Vec<usize> {
let tree = match &file.tree {
Some(tree) if !crate::marker::is_markdown(&file.rel) => tree,
_ => {
let literals = crate::span::literal_ranges(&file.rel, &file.text);
return crate::marker::trailing_lines(
crate::marker::Dialect::of(&file.rel),
&file.text,
&literals,
);
}
};
let lines: Vec<&str> = file.text.lines().collect();
let mut out = Vec::new();
let mut stack = vec![tree.root_node()];
while let Some(node) = stack.pop() {
stack.extend(node.children(&mut node.walk()));
if !node.kind().contains("comment") {
continue;
}
let start = node.start_position();
let opens = node
.utf8_text(file.text.as_bytes())
.is_ok_and(crate::marker::opens_like_a_marker);
let after_code = lines
.get(start.row)
.and_then(|line| line.get(..start.column))
.is_some_and(|before| !before.trim_start_matches('\u{feff}').trim().is_empty());
if opens && after_code {
out.push(start.row + 1);
}
}
out.sort();
out
}
fn no_notes_matched(root: &Path, notes: usize, scan: &Scan) -> Option<String> {
let markers = scan
.pointers
.iter()
.filter(|ptr| ptr.kind == PointerKind::Implements && ptr.project.is_none())
.count();
if notes > 0 || markers == 0 {
return None;
}
let list = std::fs::read_to_string(root.join("AGENTS.md"))
.ok()
.and_then(|text| scheme::attr_from_agents(&text, "notes"))
.unwrap_or_else(|| walk::DEFAULT_NOTES.to_string());
Some(format!(
"AGENTS.md: the `notes` list `{list}` matches no Markdown file, yet {markers} marker(s) point to a law of this project. Name the decision notes in `notes`."
))
}
fn check_span_pins(
file: &span::CodeFile,
unhashable: &BTreeSet<usize>,
inert: &BTreeSet<usize>,
drifted: &BTreeMap<(PathBuf, usize), String>,
report: &mut CheckReport,
) {
use crate::marker;
let path = file.rel.as_path();
for (idx, line) in file.marker_lines() {
if marker::is_one(line) && !file.has_span(idx) {
continue;
}
for pin in marker::markers_in_line(line) {
if pin.digest.is_some()
|| file.is_empty_span(idx)
|| file.parse_error(idx).is_some()
|| unhashable.contains(&idx)
|| inert.contains(&idx)
{
continue;
}
if file.is_pinnable(idx) {
let held = drifted.get(&(path.to_path_buf(), idx + 1));
report.errors.push(match held {
Some(held) => format!(
"{}:{}: § {} is bare, and HEAD pinned it here as {held}, which its span no longer hashes to: it drifted. Read it against its law or clause, then run `silcrow accept {}`.",
path.display(),
idx + 1,
pin.display(),
pin.display()
),
None => format!(
"{}:{}: § {} is not pinned. Run `silcrow fix` to pin it.",
path.display(),
idx + 1,
pin.display()
),
});
continue;
}
let repair = match file.construct_below(idx) {
Some((at, None)) => {
format!("It sits above the construct at line {at}: move it into the body of that construct")
}
Some((at, Some(last))) => format!(
"It sits above the construct at line {at}, which has no body: add a `§ end {}` comment below line {last} to close a span there",
pin.display()
),
None => "Move it into the construct that carries its law".to_string(),
};
report.errors.push(format!(
"{}:{}: § {} is outside every span, so it pins nothing. {repair}, then run `silcrow fix` to pin it.",
path.display(),
idx + 1,
pin.display()
));
}
}
}
pub fn evaluate(
scan: &Scan,
graph: &Graph,
files: usize,
policy: &ProjectPolicy,
notes: &walk::Notes,
others: &Others,
) -> CheckReport {
let mut ok: BTreeMap<String, usize> = BTreeMap::new();
let mut errors = Vec::new();
let mut warnings = Vec::new();
for err in &scan.form_errors {
errors.push(format!(
"{}:{}: {}",
err.loc.path.display(),
err.loc.line,
err.message
));
}
for lint in &scan.lints {
warnings.push(format!(
"{}:{}: {}",
lint.loc.path.display(),
lint.loc.line,
lint.message
));
}
for law in &scan.laws {
if hash::is_provisional_id(&law.id) {
continue;
}
if !hash::verify_id(&law.name, &law.id) {
errors.push(format!(
"{}:{}: § {id} content-hash does not match its carrying sentence. For a change of form run `silcrow accept {id}`. For a change of sense restore it, strike it, and declare a successor.",
law.loc.path.display(),
law.loc.line,
id = law.id
));
}
}
check_text_length(scan, &mut errors, &mut warnings);
let mentions = scan.mentions.iter().map(|ptr| (ptr, true));
for (ptr, mention) in scan.pointers.iter().map(|ptr| (ptr, false)).chain(mentions) {
let at = format!("{}:{}", ptr.loc.path.display(), ptr.loc.line);
let in_graph = match ptr.project.as_deref() {
None => graph,
Some(project) if project == others.own => {
errors.push(format!(
"{at}: `{}` is qualified with its own project path. Run `silcrow fix` to strip it.",
render_ptr(ptr)
));
continue;
}
Some(project) => match others.graphs.get(project) {
Some(found) => found,
None => {
let relocate = match &ptr.target {
crate::parse::Target::Stable { id, .. } => {
others.declaring(id).len() + usize::from(graph.by_id.contains_key(id))
== 1
}
_ => false,
};
errors.push(format!(
"{at}: `{}` names no project. Projects: {}.{}",
render_ptr(ptr),
others.projects(),
if relocate {
" Run `silcrow fix` to requalify it."
} else {
""
}
));
continue;
}
},
};
let found = in_graph
.lookup(&ptr.name, &ptr.target)
.or_else(|| {
let crate::parse::Target::Stable { id, letter } = &ptr.target else {
return None;
};
let current = in_graph.aliases.get(id)?;
let node = in_graph.lookup(
&ptr.name,
&crate::parse::Target::Stable {
id: current.clone(),
letter: letter.clone(),
},
)?;
warnings.push(format!(
"{at}: `{}` names an alias anchor of § {current}. Run `silcrow fix` to rewrite it to the current id.",
render_ptr(ptr)
));
Some(node)
});
match found {
None => {
let hint = match (&ptr.project, &ptr.target) {
(None, crate::parse::Target::Stable { id, .. }) => {
match others.declaring(id)[..] {
[project] => format!(
" Project `{project}` declares it: run `silcrow fix` to write `{project}:{}`.",
render_ptr(ptr)
),
_ => String::new(),
}
}
_ => String::new(),
};
let law_declared = match &ptr.target {
crate::parse::Target::Stable { id, .. } => {
let law = crate::parse::Target::Stable {
id: in_graph.aliases.get(id).unwrap_or(id).clone(),
letter: None,
};
in_graph.lookup(&ptr.name, &law).is_some()
}
_ => false,
};
if let (
crate::parse::Target::Stable {
id,
letter: Some(letter),
},
true,
) = (&ptr.target, law_declared)
{
errors.push(format!(
"{at}: `{}` points at clause ({letter}), which § {id} never authored.{hint}",
render_ptr(ptr)
));
} else {
errors.push(format!(
"{at}: `{}` points to a target that was never declared.{hint}",
render_ptr(ptr)
));
}
}
Some(node) if !in_graph.is_live(node) && mention => {
warnings.push(format!(
"{at}: `§ {}` names a retired or struck clause. Point it at the live successor or drop it.",
render_ptr(ptr)
));
}
Some(node) if !in_graph.is_live(node) && ptr.kind == PointerKind::Implements => {
let what = match &ptr.target {
crate::parse::Target::Stable {
letter: Some(_), ..
} => "a retired clause",
_ => "a struck law",
};
let address = render_ptr(ptr);
errors.push(format!(
"{at}: `{address}` points at {what}. Run `silcrow accept {address}` to remove its markers."
));
}
Some(node) if node.draft && ptr.kind == PointerKind::Implements => {
let repair = match &ptr.project {
Some(project) => {
format!("in project `{project}`, where `silcrow fix` drops it")
}
None => "with `silcrow fix`".to_string(),
};
errors.push(format!(
"{at}: `{}` names a draft, which owes no marker and is never pinned. Implementing it drops the `?` of its law or clause at {}:{}: drop it {repair}.",
render_ptr(ptr),
node.path,
node.line
));
}
Some(_) => {
*ok.entry(render_ptr(ptr)).or_default() += 1;
}
}
}
let markers = collect_marker_markers(scan, notes, policy, graph, others, &mut errors);
check_marker_coverage(scan, graph, policy, &markers, others, &mut errors);
check_duplicate_declaration_ids(scan, graph, &mut errors);
check_similar_carrying_sentences(scan, graph, &mut warnings);
CheckReport {
files,
ok,
errors,
warnings,
drafts: draft_lines(scan, None),
..CheckReport::empty()
}
}
fn draft_lines(scan: &Scan, root: Option<&Path>) -> Vec<String> {
let drafts = crate::list::drafts(&scan.laws);
let ages = root.and_then(|root| crate::meta::draft_ages(root, &drafts));
drafts
.iter()
.enumerate()
.map(|(at, draft)| {
let loc = draft.loc();
let age = match ages.as_ref().map(|ages| &ages[at]) {
None => String::new(),
Some(Some((Some(date), Some(age)))) => format!(" (since {date}, {age})"),
Some(_) => " (not committed)".to_string(),
};
format!("{}:{}:{age} {}", loc.path.display(), loc.line, draft.line())
})
.collect()
}
#[derive(Hash, Eq, PartialEq, Clone)]
struct MarkerKey {
project: Option<String>,
id: String,
letter: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
enum MarkerSurface {
Code,
Doc,
Unread,
}
fn scan_provisional_references(root: &Path) -> Result<Vec<String>> {
let mut errors = Vec::new();
for path in walk::decision_files(root)? {
let text = std::fs::read_to_string(&path)?;
let rel = path.strip_prefix(root).unwrap_or(&path);
for (line_no, line) in text.lines().enumerate() {
for caps in PROVISIONAL_DECLARE_RE.captures_iter(line) {
let name = &caps[1];
errors.push(format!(
"{}:{}: provisional reference § +{name} must be resolved before integration. Run `silcrow fix` to mint it.",
rel.display(),
line_no + 1,
));
}
}
}
for path in walk::code_files(root)? {
let text = std::fs::read_to_string(&path)?;
if !text.contains('§') {
continue;
}
let rel = path.strip_prefix(root).unwrap_or(&path);
let unmarked = if crate::marker::is_markdown(rel) {
vec![false; text.lines().count()]
} else {
span::unmarked_lines(rel, &text, None)
};
for (line_no, line) in text.lines().enumerate() {
if unmarked[line_no] || line.contains("{name}") || line.contains("{id}") {
continue;
}
let one =
crate::marker::opens_one(line).then(|| PROVISIONAL_NAME_RE.captures_iter(line));
for caps in PROVISIONAL_MARKER_RE
.captures_iter(line)
.chain(one.into_iter().flatten())
{
let name = &caps[1];
errors.push(format!(
"{}:{}: provisional marker § +{name} must be resolved before integration. Run `silcrow fix` to mint it.",
rel.display(),
line_no + 1,
));
}
}
}
Ok(errors)
}
fn is_law_live(law: &Law, graph: &Graph) -> bool {
if hash::is_provisional_id(&law.id) || graph.retired.contains(&law.id) {
return false;
}
true
}
fn check_duplicate_declaration_ids(scan: &Scan, graph: &Graph, errors: &mut Vec<String>) {
let mut by_id: BTreeMap<String, Vec<&Law>> = BTreeMap::new();
for law in &scan.laws {
if hash::is_provisional_id(&law.id) {
continue;
}
by_id.entry(law.id.clone()).or_default().push(law);
}
for (id, laws) in by_id {
let live: Vec<_> = laws
.iter()
.copied()
.filter(|law| is_law_live(law, graph))
.collect();
if live.len() < 2 {
continue;
}
let first = live[0];
for law in &live[1..] {
errors.push(format!(
"duplicate id {id}: first at {}:{}, also at {}:{}",
first.loc.path.display(),
first.loc.line,
law.loc.path.display(),
law.loc.line,
));
}
}
}
pub const WARN_WORDS: usize = 60;
pub const FAIL_WORDS: usize = 120;
pub fn text_lengths(scan: &Scan) -> Vec<(String, &Location, usize)> {
let mut out = Vec::new();
for law in scan.laws.iter().filter(|law| !law.struck) {
out.push((
law.id.clone(),
&law.loc,
law.name.split_whitespace().count(),
));
for clause in law.clauses.iter().filter(|clause| !clause.struck) {
let addr = match &clause.letter {
Some(letter) => format!("{}.{letter}", law.id),
None => law.id.clone(),
};
out.push((addr, &clause.loc, clause.body.split_whitespace().count()));
}
}
out
}
fn check_text_length(scan: &Scan, errors: &mut Vec<String>, warnings: &mut Vec<String>) {
for (addr, loc, words) in text_lengths(scan) {
let (out, limit) = if words > FAIL_WORDS {
(&mut *errors, FAIL_WORDS)
} else if words > WARN_WORDS {
(&mut *warnings, WARN_WORDS)
} else {
continue;
};
out.push(format!(
"{}:{}: § {addr} runs {words} words, over the {limit} a clause or a carrying sentence may hold: keep one promise and move its reasons and examples to prose.",
loc.path.display(),
loc.line,
));
}
}
fn carrying_prefix(name: &str) -> String {
hash::canonicalise(name).chars().take(40).collect()
}
fn check_similar_carrying_sentences(scan: &Scan, graph: &Graph, warnings: &mut Vec<String>) {
let mut by_file: BTreeMap<String, Vec<&Law>> = BTreeMap::new();
for law in &scan.laws {
if !is_law_live(law, graph) {
continue;
}
let path = law.loc.path.display().to_string();
by_file.entry(path).or_default().push(law);
}
for laws in by_file.values() {
for i in 0..laws.len() {
for j in (i + 1)..laws.len() {
let a = laws[i];
let b = laws[j];
let prefix = carrying_prefix(a.name.as_str());
if prefix.is_empty() || prefix != carrying_prefix(b.name.as_str()) {
continue;
}
warnings.push(format!(
"{}:{}: § {} and § {} share similar carrying sentences (prefix \"{prefix}\")",
a.loc.path.display(),
a.loc.line,
a.id,
b.id,
));
}
}
}
}
fn check_marker_coverage(
scan: &Scan,
graph: &Graph,
policy: &ProjectPolicy,
markers: &Markers,
others: &Others,
errors: &mut Vec<String>,
) {
let duty = Owed {
markers,
policy,
project: None,
};
for law in &scan.laws {
if hash::is_provisional_id(&law.id) || graph.retired.contains(&law.id) || law.struck {
continue;
}
if law.draft {
continue;
}
let live_letters: Vec<_> = law
.clauses
.iter()
.filter(|al| al.letter.is_some() && !al.struck)
.filter(|al| {
let key = format!("{}.{}", law.id, al.letter.as_ref().unwrap());
!graph.retired.contains(&key)
})
.collect();
if live_letters.is_empty() {
duty.code(&law.id, None, &law.loc, errors);
} else {
for al in live_letters.into_iter().filter(|al| !al.draft) {
duty.code(&law.id, al.letter.as_deref(), &al.loc, errors);
}
}
if law.public && policy.docs.is_empty() {
errors.push(format!(
"{}:{}: § {} is a public promise, written `§!`, and the `docs` list of the block is empty, so no marker can pay its documentation duty. Name the public documentation in `docs`, such as `docs=\"website/docs/**/*.html\"`, or write the law `§` when no public page promises it.",
law.loc.path.display(),
law.loc.line,
law.id
));
} else if law.public {
duty.docs(&law.id, None, &law.loc, errors);
}
}
check_adoptions(scan, others, markers, policy, errors);
}
fn check_adoptions(
scan: &Scan,
others: &Others,
markers: &Markers,
policy: &ProjectPolicy,
errors: &mut Vec<String>,
) {
for adoption in &scan.adoptions {
let at = format!("{}:{}", adoption.loc.path.display(), adoption.loc.line);
let addr = match &adoption.letter {
Some(letter) => format!("{}:{}.{letter}", adoption.project, adoption.id),
None => format!("{}:{}", adoption.project, adoption.id),
};
if adoption.project == others.own {
errors.push(format!(
"{at}: § {addr} adopts a law of its own project. Land it instead."
));
continue;
}
let Some(origin) = others.graphs.get(&adoption.project) else {
errors.push(format!(
"{at}: § {addr} names no project. Projects: {}.",
others.projects()
));
continue;
};
let key = match &adoption.letter {
Some(letter) => format!("{}.{letter}", adoption.id),
None => adoption.id.clone(),
};
let Some(node) = origin.by_id.get(&key) else {
errors.push(format!(
"{at}: § {addr} adopts what project `{}` never declared.",
adoption.project
));
continue;
};
if !origin.is_live(node) {
errors.push(format!("{at}: § {addr} adopts a struck clause."));
continue;
}
if node.draft {
continue;
}
let duty = Owed {
markers,
policy,
project: Some(&adoption.project),
};
let letter = adoption.letter.as_deref();
if node.public {
duty.docs(&adoption.id, letter, &adoption.loc, errors);
}
if letter.is_some() {
duty.code(&adoption.id, letter, &adoption.loc, errors);
continue;
}
let live: Vec<&crate::graph::Node> = origin
.by_id
.values()
.filter(|n| n.id == adoption.id && n.letter.is_some() && origin.is_live(n))
.collect();
if live.is_empty() {
duty.code(&adoption.id, None, &adoption.loc, errors);
}
let mut letters: Vec<&str> = live
.iter()
.filter(|n| !n.draft)
.filter_map(|n| n.letter.as_deref())
.collect();
letters.sort();
for letter in letters {
duty.code(&adoption.id, Some(letter), &adoption.loc, errors);
}
}
}
struct Owed<'a> {
markers: &'a Markers,
policy: &'a ProjectPolicy,
project: Option<&'a str>,
}
impl Owed<'_> {
fn key(&self, id: &str, letter: Option<&str>) -> MarkerKey {
MarkerKey {
project: self.project.map(str::to_string),
id: id.to_string(),
letter: letter.map(str::to_string),
}
}
fn label(&self, id: &str, letter: Option<&str>) -> String {
let local = match letter {
Some(l) => format!("{id}.{l}"),
None => id.to_string(),
};
match self.project {
Some(project) => format!("{project}:{local}"),
None => local,
}
}
fn code(&self, id: &str, letter: Option<&str>, loc: &Location, errors: &mut Vec<String>) {
let key = self.key(id, letter);
if self.markers.code.contains(&key) {
return;
}
let label = self.label(id, letter);
let law = MarkerKey {
letter: None,
..key
};
let suggested = match self
.markers
.code_file
.get(&law)
.and_then(|file| crate::marker::wrapper_for(file))
{
Some((open, close)) => format!("`{open} § {label}{close}`"),
None => format!("a `§ {label}` comment"),
};
errors.push(format!(
"{}:{}: § {label} has no code marker ({suggested} in a file the `code` list `{}` matches)",
loc.path.display(),
loc.line,
self.policy.code_attr()
));
}
fn docs(&self, id: &str, letter: Option<&str>, loc: &Location, errors: &mut Vec<String>) {
if self.policy.docs.is_empty() {
return;
}
let key = self.key(id, letter);
let paid = match letter {
Some(_) => self.markers.doc.contains(&key),
None => self
.markers
.doc
.iter()
.any(|m| m.project == key.project && m.id == key.id),
};
if paid {
return;
}
let label = self.label(id, letter);
let docs = self.policy.docs_attr();
errors.push(format!(
"{}:{}: § {label} has no documentation marker ({} in a file the `docs` list `{docs}` matches)",
loc.path.display(),
loc.line,
doc_marker_forms(&self.markers.doc_files, docs, &label),
));
}
}
fn doc_marker_forms(doc_files: &[PathBuf], docs: &str, label: &str) -> String {
let patterns: Vec<PathBuf> = docs
.split_whitespace()
.filter(|glob| !glob.starts_with('!'))
.map(PathBuf::from)
.collect();
let paths = if doc_files.is_empty() {
&patterns
} else {
doc_files
};
let mut forms: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
for path in paths {
let form = match crate::marker::Dialect::of(path) {
crate::marker::Dialect::Mdx => format!("{{/* § {label} */}}"),
crate::marker::Dialect::Markdown => format!("<!-- § {label} -->"),
crate::marker::Dialect::Code => match crate::marker::wrapper_for(path) {
Some((open, close)) => format!("{open} § {label}{close}"),
None => continue,
},
};
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
forms
.entry(form)
.or_default()
.insert(ext.to_ascii_lowercase());
}
match forms.len() {
0 => format!("a `§ {label}` comment"),
1 => format!(
"`{}` or a comment",
forms.into_keys().next().unwrap_or_default()
),
_ => {
let named: Vec<String> = forms
.iter()
.map(|(form, exts)| {
let exts: Vec<String> = exts.iter().map(|ext| format!(".{ext}")).collect();
format!("`{form}` in {}", exts.join(", "))
})
.collect();
format!("{}, or a comment", named.join(", "))
}
}
}
struct Markers {
code: HashSet<MarkerKey>,
doc: HashSet<MarkerKey>,
code_file: std::collections::HashMap<MarkerKey, PathBuf>,
doc_files: Vec<PathBuf>,
}
fn collect_marker_markers(
scan: &Scan,
notes: &walk::Notes,
policy: &ProjectPolicy,
graph: &Graph,
others: &Others,
errors: &mut Vec<String>,
) -> Markers {
let mut markers = Markers {
code: HashSet::new(),
doc: HashSet::new(),
code_file: std::collections::HashMap::new(),
doc_files: scan.doc_files.clone(),
};
for ptr in &scan.pointers {
if ptr.kind != PointerKind::Implements {
continue;
}
let surface = marker_surface(&ptr.loc.path, notes, policy);
if surface == Some(MarkerSurface::Unread) {
errors.push(format!(
"{}:{}: § {} sits in Markdown that is neither a decision note nor documentation, so no duty reads it. Move it onto the code that carries its law, or name the file in `docs` when it is public documentation.",
ptr.loc.path.display(),
ptr.loc.line,
render_ptr(ptr)
));
continue;
}
let project = ptr.project.clone().filter(|project| *project != others.own);
let Some(mut key) = marker_key(project, &ptr.target) else {
continue;
};
let aliases = match &key.project {
None => Some(&graph.aliases),
Some(project) => others.graphs.get(project).map(|m| &m.aliases),
};
if let Some(current) = aliases.and_then(|a| a.get(&key.id)) {
key.id = current.clone();
}
if surface != Some(MarkerSurface::Doc) && !crate::marker::is_markdown(&ptr.loc.path) {
let law = MarkerKey {
letter: None,
..key.clone()
};
let file = markers.code_file.entry(law).or_insert(ptr.loc.path.clone());
if ptr.loc.path < *file {
*file = ptr.loc.path.clone();
}
}
match surface {
Some(MarkerSurface::Code) => {
markers.code.insert(key);
}
Some(MarkerSurface::Doc) => {
markers.doc.insert(key);
}
Some(MarkerSurface::Unread) | None => {}
}
}
markers
}
fn marker_key(project: Option<String>, target: &Target) -> Option<MarkerKey> {
match target {
Target::Stable { id, letter } => Some(MarkerKey {
project,
id: id.clone(),
letter: letter.clone(),
}),
_ => None,
}
}
fn marker_surface(
path: &Path,
notes: &walk::Notes,
policy: &ProjectPolicy,
) -> Option<MarkerSurface> {
if notes.holds(path) {
return None;
}
if policy.docs.matches(path) {
return Some(MarkerSurface::Doc);
}
if crate::marker::is_markdown(path) {
return Some(MarkerSurface::Unread);
}
policy.code.matches(path).then_some(MarkerSurface::Code)
}
fn render_ptr(ptr: &crate::parse::Pointer) -> String {
let local = render_target(ptr);
match &ptr.project {
Some(project) => format!("{project}:{local}"),
None => local,
}
}
fn render_target(ptr: &crate::parse::Pointer) -> String {
match &ptr.target {
crate::parse::Target::Stable { id, letter: None } => id.clone(),
crate::parse::Target::Stable {
id,
letter: Some(letter),
} => format!("{id}.{letter}"),
crate::parse::Target::Display {
note,
section,
clause,
letter,
} => {
let mut s = format!("{note} §{section}");
if let Some(al) = clause {
s.push_str(&format!(".{al}"));
}
if let Some(let_) = letter {
s.push_str(&format!(" let. {let_}"));
}
s
}
}
}
pub fn named_by_law(named: &[String]) -> Vec<(String, Vec<&String>)> {
let mut out: Vec<(String, Vec<&String>)> = Vec::new();
for text in named {
let tag = text
.strip_prefix('[')
.and_then(|rest| rest.split_once("] "))
.map_or(String::new(), |(tag, _)| format!("[{tag}] "));
let law = match text.split_once("§ ") {
Some((_, rest)) => {
let addr = rest
.split(|c: char| c.is_whitespace() || c == ',')
.next()
.unwrap_or_default();
let (project, local) = addr.rsplit_once(':').unwrap_or(("", addr));
let id = local.split('.').next().unwrap_or(local);
match project.is_empty() {
true => format!("{tag}§ {id}"),
false => format!("{tag}§ {project}:{id}"),
}
}
None => format!("{tag}the Silcrow block"),
};
match out.iter_mut().find(|(key, _)| *key == law) {
Some((_, list)) => list.push(text),
None => out.push((law, vec![text])),
}
}
out
}
pub fn named_summary(named: &[String]) -> String {
let laws: Vec<String> = named_by_law(named)
.into_iter()
.map(|(law, list)| format!("- {law}: {}\n", list.len()))
.collect();
format!(
"# Silcrow: {} change(s) named for the person who merges\n\n{}\n",
named.len(),
laws.concat()
)
}
pub fn print_report(report: &CheckReport, verbose: bool) -> bool {
if verbose {
println!("Scanning {} files...\n", report.files);
for (name, count) in &report.ok {
println!(" OK {name:<18} {count} pointer(s) resolved");
}
}
for err in report
.errors
.iter()
.chain(&report.harness)
.chain(&report.drifts)
{
println!(" ERR {err}");
}
for warn in &report.warnings {
println!(" WRN {warn}");
}
if !report.drafts.is_empty() {
if !report.warnings.is_empty() || !report.errors.is_empty() || !report.drifts.is_empty() {
println!();
}
println!("Not implemented, not pinned:");
for draft in &report.drafts {
println!(" {draft}");
}
}
let drafts = match report.drafts.len() {
0 => String::new(),
n => format!(", {n} draft(s)"),
};
if !report.named.is_empty() {
let above = !report.warnings.is_empty()
|| !report.errors.is_empty()
|| !report.drifts.is_empty()
|| !report.drafts.is_empty();
if above {
println!();
}
println!("Changed since the comparison point, named for the person who merges, as the packet above shows:");
for (law, named) in named_by_law(&report.named) {
println!(" {law}, {} change(s):", named.len());
for named in named {
println!(" {named}");
}
}
}
let named = match report.named.len() {
0 => String::new(),
n => format!(", {n} change(s) named"),
};
let verified = match report.doc_verified {
0 => String::new(),
n => format!(", doc {n} verified"),
};
let counts = format!(
"{} reference(s) resolved, {} error(s), {} warning(s){drafts}{named}{verified}.",
report.ok.len(),
report.errors.len() + report.harness.len() + report.drifts.len(),
report.warnings.len(),
);
let listed = verbose
|| !report.errors.is_empty()
|| !report.harness.is_empty()
|| !report.drafts.is_empty()
|| !report.named.is_empty()
|| !report.drifts.is_empty()
|| !report.warnings.is_empty();
if listed {
println!();
}
let closed = report.is_closed();
if closed {
println!("✓ Graph is closed. {counts}");
} else {
println!("✗ Graph is broken. {counts}");
}
closed
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hash;
use crate::parse::{Clause, Law, Location, Pointer, PointerKind, Scan, Target};
use std::path::PathBuf;
#[test]
fn named_changes_group_per_law_in_first_order() {
let named: Vec<String> = [
"[.] src/a.ts:3: § abcdefgh1.a carries @x, and main pinned it here as @y: it was re-pinned.",
"[.] AGENTS.md: the Silcrow block writes `code=\"src\"`, and main wrote `code=\"**/*\"`: the block decides what the tree is held to.",
"[.] docs/r.md:5: § bcdefghj2, § bcdefghj2.c is a draft main did not hold, a promise the tree keeps before its code.",
"[.] src/b.ts:9: § abcdefgh1 carries @z, and main pinned it here as @w: it was re-pinned.",
"[lib] src/c.py:2: § lib/x:cdefghjk3.b was pinned @q at main, and its project `lib/x` no longer exists: its laws and its pins left the tree.",
]
.map(String::from)
.to_vec();
let groups: Vec<(String, usize)> = named_by_law(&named)
.into_iter()
.map(|(law, list)| (law, list.len()))
.collect();
assert_eq!(
groups,
vec![
("[.] § abcdefgh1".to_string(), 2),
("[.] the Silcrow block".to_string(), 1),
("[.] § bcdefghj2".to_string(), 1),
("[lib] § lib/x:cdefghjk3".to_string(), 1),
]
);
assert!(named_summary(&named).starts_with(
"# Silcrow: 5 change(s) named for the person who merges\n\n- [.] § abcdefgh1: 2\n"
));
}
#[test]
fn a_bare_marker_over_a_parse_error_names_no_fix() {
let file = span::CodeFile::new(
"src/x.rs".into(),
"fn f() {\n // § abcdefgh1\n save(;\n}\n".into(),
);
let mut report = CheckReport::empty();
check_span_pins(
&file,
&BTreeSet::new(),
&BTreeSet::new(),
&BTreeMap::new(),
&mut report,
);
assert!(report.errors.is_empty(), "{:?}", report.errors);
let checked = span::verify_file(&file.rel, &file.text, scheme::SERIALIZATION);
assert_eq!(checked.errors.len(), 1, "{:?}", checked.errors);
assert!(checked.errors[0].contains("does not parse"));
}
#[test]
fn a_marker_comment_after_code_fails_and_a_string_that_holds_one_does_not() {
let at =
|rel: &str, text: &str| trailing_markers(&span::CodeFile::new(rel.into(), text.into()));
assert_eq!(
at(
"src/lib.rs",
"fn f(x: u8) -> bool {\n // § abcdefgh1.a\n let s = \"x // § abcdefgh1\";\n x == 0 // § hzzzzzzzz.q\n}\n"
),
[4]
);
assert_eq!(at("src/a.py", "x = 1 # § +name.b\n# § abcdefgh1\n"), [1]);
assert_eq!(at("a.yml", "x: 1 # § abcdefgh1\n# § abcdefgh1\n"), [1]);
assert_eq!(
at(
"src/i.go",
"var s = \"// § +limit\"\nx := 1 // § abcdefgh1\n// § abcdefgh1\n"
),
[2]
);
assert!(at("src/e.json", "{\n \"note\": \"// § +limit\"\n}\n").is_empty());
assert_eq!(
at(
"guide.md",
"Text <!-- § abcdefgh1 -->\n\n`a <!-- § abcdefgh1 -->`\n<!-- § abcdefgh1 -->\n"
),
[1]
);
}
#[test]
fn a_fallback_file_checks_one_marker_per_span_and_empty_spans() {
let twice = span::CodeFile::new(
"src/x.go".into(),
"package main\n// § abcdefgh1\nfunc a() {}\n// § abcdefgh1\nfunc b() {}\n".into(),
);
let mut errors = Vec::new();
check_duplicate_markers(&twice, &mut errors);
assert_eq!(errors.len(), 1, "{errors:?}");
assert!(errors[0].contains("two markers in one span"), "{errors:?}");
let ended = span::CodeFile::new(
"src/x.go".into(),
"// § abcdefgh1\nfunc a() {}\n// § end abcdefgh1\n// § abcdefgh1\nfunc b() {}\n".into(),
);
let mut errors = Vec::new();
check_duplicate_markers(&ended, &mut errors);
assert!(errors.is_empty(), "{errors:?}");
let text = "package main\nfunc a() {}\n// § abcdefgh1\n// only a comment\n";
let empty = span::verify_file(Path::new("src/x.go"), text, scheme::SERIALIZATION);
assert!(
empty
.errors
.iter()
.any(|e| e.contains("opens an empty span")),
"{:?}",
empty.errors
);
let mut report = CheckReport::empty();
check_span_pins(
&span::CodeFile::new("src/x.go".into(), text.into()),
&BTreeSet::new(),
&BTreeSet::new(),
&BTreeMap::new(),
&mut report,
);
assert!(report.errors.is_empty(), "{:?}", report.errors);
}
#[test]
fn a_qualified_doc_mention_resolves_in_its_project() {
let lib = crate::parse::scan_text(
Path::new("lib/docs/decisions/n.md"),
"**§ abcdefgh1 Rule.**\n\n- (a) Letter.\n",
);
let others = Others {
own: ".".into(),
graphs: BTreeMap::from([("lib".to_string(), Graph::from_scan(&lib))]),
};
let mut scan = Scan::default();
crate::parse::extract_mentions(
Path::new("docs/guide.md"),
"See § lib:abcdefgh1.a, § lib:abcdefgh1.z, § lib:abcdefgh2.a and § nope:abcdefgh1, not `§ lib:zzzzzzzz1`.\n",
&mut scan,
);
assert_eq!(scan.mentions.len(), 4, "{:?}", scan.mentions);
let graph = Graph::from_scan(&scan);
let report = evaluate(
&scan,
&graph,
1,
&ProjectPolicy::defaults(),
&default_notes(),
&others,
);
assert_eq!(
report.ok.get("lib:abcdefgh1.a"),
Some(&1),
"{:?}",
report.ok
);
assert!(
report
.errors
.iter()
.any(|e| e.contains("clause (z), which § abcdefgh1 never authored")),
"{:?}",
report.errors
);
assert!(
report
.errors
.iter()
.any(|e| e.contains("`lib:abcdefgh2.a` points to a target that was never declared")),
"an undeclared law is not a missing clause: {:?}",
report.errors
);
assert!(
report.errors.iter().any(|e| e.contains("names no project")),
"{:?}",
report.errors
);
}
#[test]
fn a_long_clause_or_sentence_warns_and_a_very_long_one_fails() {
let words = |n: usize| vec!["word"; n].join(" ");
let note = format!(
"**§ abcdefgh1 {}.**\n\n- (a) {}.\n\n- (b) {}.\n\n- (c) {}.\n\n- (d) ~~{}.~~\n\n**§ abcdefgh2 ~~{}.~~**\n",
words(WARN_WORDS + 1),
words(WARN_WORDS),
words(FAIL_WORDS),
words(FAIL_WORDS + 1),
words(FAIL_WORDS + 1),
words(FAIL_WORDS + 1),
);
let scan = crate::parse::scan_text(Path::new("docs/decisions/n.md"), ¬e);
let (mut errors, mut warnings) = (Vec::new(), Vec::new());
check_text_length(&scan, &mut errors, &mut warnings);
assert_eq!(
warnings,
[
"docs/decisions/n.md:1: § abcdefgh1 runs 61 words, over the 60 a clause or a carrying sentence may hold: keep one promise and move its reasons and examples to prose.",
"docs/decisions/n.md:5: § abcdefgh1.b runs 120 words, over the 60 a clause or a carrying sentence may hold: keep one promise and move its reasons and examples to prose.",
]
);
assert_eq!(
errors,
["docs/decisions/n.md:7: § abcdefgh1.c runs 121 words, over the 120 a clause or a carrying sentence may hold: keep one promise and move its reasons and examples to prose."]
);
}
fn default_notes() -> walk::Notes {
walk::Notes::parse(walk::DEFAULT_NOTES).unwrap()
}
#[test]
fn the_docs_list_and_the_decisions_list_decide_the_surface_of_a_file() {
let notes = default_notes();
let docs = policy_of("docs=\"README.md docs/guide/**\"");
let surface =
|path: &str, notes: &walk::Notes| marker_surface(Path::new(path), notes, &docs);
for doc in ["README.md", "docs/guide/pay.md", "docs/guide/pay.html"] {
assert_eq!(surface(doc, ¬es), Some(MarkerSurface::Doc), "{doc}");
}
for unread in ["docs/archive/x.md", "docs/ideation/x.md", "AGENTS.md"] {
assert_eq!(
surface(unread, ¬es),
Some(MarkerSurface::Unread),
"{unread}"
);
}
assert_eq!(surface("src/x.rs", ¬es), Some(MarkerSurface::Code));
assert_eq!(surface("docs/decisions/x.md", ¬es), None);
let custom = walk::Notes::parse("docs/**/*.md !docs/guide/**").unwrap();
assert_eq!(surface("docs/archive/x.md", &custom), None);
assert_eq!(
surface("docs/guide/pay.md", &custom),
Some(MarkerSurface::Doc)
);
}
#[test]
fn a_decisions_list_that_matches_no_note_fails_only_when_a_marker_points_to_a_law() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"notes/*.md\">\n</silcrow>\n",
)
.unwrap();
let marked = landed_at(&[("src/lib.rs", 2)]);
let err = no_notes_matched(dir.path(), 0, &marked).unwrap();
assert!(
err.contains("the `notes` list `notes/*.md` matches no Markdown file"),
"{err}"
);
assert!(err.contains("1 marker(s)"), "{err}");
assert_eq!(no_notes_matched(dir.path(), 1, &marked), None);
assert_eq!(
no_notes_matched(dir.path(), 0, &Scan::default()),
None,
"0 notes"
);
}
#[test]
fn a_marker_outside_every_span_fails_with_its_repair() {
for (text, repair) in [
(
"// § abcdefgh1
impl X {
fn f() {}
}
",
"sits above the construct at line 2: move it into the body",
),
(
"// § abcdefgh1
const X: u8 = 1;
",
"add a `§ end abcdefgh1` comment below line 2",
),
] {
let file = span::CodeFile::new("src/x.rs".into(), text.into());
let mut report = CheckReport::empty();
check_span_pins(
&file,
&BTreeSet::new(),
&BTreeSet::new(),
&BTreeMap::new(),
&mut report,
);
assert_eq!(report.errors.len(), 1, "{:?}", report.errors);
assert!(
report.errors[0].contains("§ abcdefgh1 is outside every span"),
"{:?}",
report.errors
);
assert!(report.errors[0].contains(repair), "{:?}", report.errors);
assert!(report.warnings.is_empty(), "{:?}", report.warnings);
}
}
#[test]
fn missing_id_is_an_error() {
let scan = Scan {
pointers: vec![Pointer {
kind: PointerKind::Implements,
project: None,
name: "deadbeef0".into(),
target: Target::Stable {
id: "deadbeef0".into(),
letter: None,
},
loc: Location {
path: PathBuf::from("src/main.rs"),
line: 4,
},
}],
..Scan::default()
};
let graph = Graph::from_scan(&scan);
let report = evaluate(
&scan,
&graph,
1,
&ProjectPolicy::defaults(),
&default_notes(),
&Others::default(),
);
assert_eq!(report.errors.len(), 1);
}
#[test]
fn resolved_marker_counts_ok() {
let scan = Scan {
laws: vec![Law {
draft: false,
body: String::new(),
end: 1,
context: String::new(),
aliases: Vec::new(),
id: hash::mint_id("Binding sentence."),
name: "Binding sentence.".into(),
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 1,
},
clauses: vec![Clause {
draft: false,
body: String::new(),
header: String::new(),
end: 1,
stable_id: None,
letter: Some("a".into()),
text: "First.".into(),
struck: false,
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 2,
},
}],
struck: false,
public: false,
}],
pointers: vec![
Pointer {
kind: PointerKind::Implements,
project: None,
name: "binding".into(),
target: Target::Stable {
id: hash::mint_id("Binding sentence."),
letter: Some("a".into()),
},
loc: Location {
path: PathBuf::from("src/main.rs"),
line: 1,
},
},
Pointer {
kind: PointerKind::Implements,
project: None,
name: "binding".into(),
target: Target::Stable {
id: hash::mint_id("Binding sentence."),
letter: Some("a".into()),
},
loc: Location {
path: PathBuf::from("docs/guide.md"),
line: 1,
},
},
],
..Scan::default()
};
let graph = Graph::from_scan(&scan);
let report = evaluate(
&scan,
&graph,
2,
&policy_of("docs=\"docs/guide.md\""),
&default_notes(),
&Others::default(),
);
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert_eq!(report.ok.values().sum::<usize>(), 2);
}
#[test]
fn an_empty_docs_list_owes_no_doc_marker() {
let id = hash::mint_id("Binding sentence.");
let scan = Scan {
laws: vec![Law {
draft: false,
body: String::new(),
end: 1,
context: String::new(),
aliases: Vec::new(),
id: id.clone(),
name: "Binding sentence.".into(),
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 1,
},
clauses: vec![Clause {
draft: false,
body: String::new(),
header: String::new(),
end: 1,
stable_id: None,
letter: Some("a".into()),
text: "First.".into(),
struck: false,
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 2,
},
}],
struck: false,
public: false,
}],
pointers: vec![Pointer {
kind: PointerKind::Implements,
project: None,
name: "binding".into(),
target: Target::Stable {
id: id.clone(),
letter: Some("a".into()),
},
loc: Location {
path: PathBuf::from("src/main.rs"),
line: 1,
},
}],
..Scan::default()
};
let graph = Graph::from_scan(&scan);
let report = evaluate(
&scan,
&graph,
1,
&ProjectPolicy::defaults(),
&default_notes(),
&Others::default(),
);
assert!(report.errors.is_empty(), "{:?}", report.errors);
}
#[test]
fn a_public_promise_missing_its_doc_marker_is_an_error() {
let id = hash::mint_id("Binding sentence.");
let scan = Scan {
laws: vec![Law {
draft: false,
body: String::new(),
end: 1,
context: String::new(),
aliases: Vec::new(),
id: id.clone(),
name: "Binding sentence.".into(),
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 1,
},
clauses: vec![],
struck: false,
public: true,
}],
pointers: vec![Pointer {
kind: PointerKind::Implements,
project: None,
name: "binding".into(),
target: Target::Stable { id, letter: None },
loc: Location {
path: PathBuf::from("src/main.rs"),
line: 1,
},
}],
..Scan::default()
};
let graph = Graph::from_scan(&scan);
let policy =
ProjectPolicy::from_agents(Some("<silcrow docs=\"docs/**/*.md\">\n</silcrow>\n"))
.unwrap();
let report = evaluate(
&scan,
&graph,
1,
&policy,
&default_notes(),
&Others::default(),
);
assert!(
report
.errors
.iter()
.any(|e| e.contains("no documentation marker")),
"errors: {:?}",
report.errors
);
}
#[test]
fn decision_note_is_not_a_doc_marker() {
let id = hash::mint_id("Binding sentence.");
let scan = Scan {
laws: vec![Law {
draft: false,
body: String::new(),
end: 1,
context: String::new(),
aliases: Vec::new(),
id: id.clone(),
name: "Binding sentence.".into(),
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 1,
},
clauses: vec![],
struck: false,
public: true,
}],
pointers: vec![
Pointer {
kind: PointerKind::Implements,
project: None,
name: "binding".into(),
target: Target::Stable {
id: id.clone(),
letter: None,
},
loc: Location {
path: PathBuf::from("src/main.rs"),
line: 1,
},
},
Pointer {
kind: PointerKind::Implements,
project: None,
name: "binding".into(),
target: Target::Stable { id, letter: None },
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 8,
},
},
],
..Scan::default()
};
let graph = Graph::from_scan(&scan);
let policy =
ProjectPolicy::from_agents(Some("<silcrow docs=\"docs/**/*.md\">\n</silcrow>\n"))
.unwrap();
let report = evaluate(
&scan,
&graph,
1,
&policy,
&default_notes(),
&Others::default(),
);
assert!(
report
.errors
.iter()
.any(|e| e.contains("no documentation marker")),
"errors: {:?}",
report.errors
);
}
#[test]
fn the_manifest_dir_is_the_root_project() {
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let ws = Workspace::discover(&manifest).unwrap();
assert_eq!(ws.root, manifest);
let project = ws.require(&manifest.join("src")).unwrap();
assert_eq!(project.key, ".");
assert_eq!(project.dir, manifest);
}
#[test]
fn live_laws_hash_to_inline_id() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let scan = scan_root(&root).unwrap();
for law in &scan.laws {
if hash::is_provisional_id(&law.id) {
continue;
}
assert!(
hash::verify_id(&law.name, &law.id),
"§ {} at {}:{} does not hash to its carrying sentence",
law.id,
law.loc.path.display(),
law.loc.line
);
}
}
#[test]
fn live_check_run_has_no_required_errors_from_policy() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let ws = Workspace::discover(&root).unwrap();
let project = ws.require(&root).unwrap().clone();
let report = super::validate(&ws, &[&project], false).unwrap();
let policy_errors: Vec<_> = report
.errors
.iter()
.filter(|e| e.contains("AGENTS.md:"))
.collect();
assert!(policy_errors.is_empty(), "{policy_errors:?}");
}
#[test]
fn provisional_reference_is_an_error() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("docs/decisions")).unwrap();
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\" default-branch=\"main\" code=\"**/*\" docs=\"\" tests=\"conventions\" test-markers=\"error\" note-words=\"error:3000\">\n</silcrow>\n",
)
.unwrap();
std::fs::write(
dir.path().join("docs/decisions/t.md"),
"§ +draft-law carries this sentence.\n",
)
.unwrap();
std::process::Command::new("git")
.args(["init", "-q", "-b", "main"])
.current_dir(dir.path())
.status()
.unwrap();
let ws = Workspace::discover(dir.path()).unwrap();
let project = ws.require(dir.path()).unwrap().clone();
let report = super::validate(&ws, &[&project], false).unwrap();
assert!(
report
.errors
.iter()
.any(|e| e.contains("provisional reference § +draft-law")),
"errors: {:?}",
report.errors
);
}
#[test]
fn duplicate_live_declaration_id_is_an_error() {
let id = hash::mint_id("Shared carrying sentence for duplicate test.");
let scan = Scan {
laws: vec![
Law {
draft: false,
body: String::new(),
end: 1,
context: String::new(),
aliases: Vec::new(),
id: id.clone(),
name: "Shared carrying sentence for duplicate test.".into(),
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 1,
},
clauses: vec![],
struck: false,
public: false,
},
Law {
draft: false,
body: String::new(),
end: 1,
context: String::new(),
aliases: Vec::new(),
id: id.clone(),
name: "Shared carrying sentence for duplicate test.".into(),
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 5,
},
clauses: vec![],
struck: false,
public: false,
},
],
..Scan::default()
};
let graph = Graph::from_scan(&scan);
let report = evaluate(
&scan,
&graph,
1,
&ProjectPolicy::defaults(),
&default_notes(),
&Others::default(),
);
assert!(
report
.errors
.iter()
.any(|e| e.contains(&format!("duplicate id {id}"))),
"errors: {:?}",
report.errors
);
}
#[test]
fn similar_carrying_sentence_prefix_warns() {
let sentence = "Two live laws may not contradict each other in the same decision note.";
let id_a = hash::mint_id(sentence);
let id_b = hash::mint_id(&format!("{sentence} Extra clause."));
let scan = Scan {
laws: vec![
Law {
draft: false,
body: String::new(),
end: 1,
context: String::new(),
aliases: Vec::new(),
id: id_a.clone(),
name: sentence.into(),
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 1,
},
clauses: vec![],
struck: false,
public: false,
},
Law {
draft: false,
body: String::new(),
end: 1,
context: String::new(),
aliases: Vec::new(),
id: id_b.clone(),
name: format!("{sentence} Extra clause."),
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 5,
},
clauses: vec![],
struck: false,
public: false,
},
],
..Scan::default()
};
let graph = Graph::from_scan(&scan);
let report = evaluate(
&scan,
&graph,
1,
&ProjectPolicy::defaults(),
&default_notes(),
&Others::default(),
);
assert!(
report
.warnings
.iter()
.any(|w| w.contains("share similar carrying sentences")),
"warnings: {:?}",
report.warnings
);
}
fn landed_at(markers: &[(&str, usize)]) -> Scan {
let id = hash::mint_id("Binding sentence.");
Scan {
laws: vec![Law {
draft: false,
body: String::new(),
end: 1,
context: String::new(),
aliases: Vec::new(),
id: id.clone(),
name: "Binding sentence.".into(),
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 1,
},
clauses: vec![],
struck: false,
public: false,
}],
pointers: markers
.iter()
.map(|&(path, line)| Pointer {
kind: PointerKind::Implements,
project: None,
name: "binding".into(),
target: Target::Stable {
id: id.clone(),
letter: None,
},
loc: Location {
path: PathBuf::from(path),
line,
},
})
.collect(),
..Scan::default()
}
}
fn check_landed(markers: &[(&str, usize)], policy: &ProjectPolicy) -> CheckReport {
let scan = landed_at(markers);
let graph = Graph::from_scan(&scan);
evaluate(
&scan,
&graph,
1,
policy,
&default_notes(),
&Others::default(),
)
}
fn check_public(markers: &[(&str, usize)], policy: &ProjectPolicy) -> CheckReport {
let mut scan = landed_at(markers);
scan.laws[0].public = true;
let graph = Graph::from_scan(&scan);
evaluate(
&scan,
&graph,
1,
policy,
&default_notes(),
&Others::default(),
)
}
fn policy_of(attrs: &str) -> ProjectPolicy {
ProjectPolicy::from_agents(Some(&format!("<silcrow {attrs}>\n</silcrow>\n"))).unwrap()
}
fn no_code_marker(report: &CheckReport) -> bool {
report
.errors
.iter()
.any(|e| e.contains("has no code marker"))
}
#[test]
fn a_marker_pays_the_code_duty_only_in_a_file_the_code_list_matches() {
let policy = policy_of("code=\"src/** !src/gen/**\"");
for (path, pays) in [
("src/lib.rs", true),
("src/deep/pay.py", true),
("src/gen/out.rs", false),
("scripts/run.sh", false),
] {
let report = check_landed(&[(path, 2)], &policy);
assert_eq!(report.ok.values().sum::<usize>(), 1, "{path}: it resolves");
assert_eq!(
!no_code_marker(&report),
pays,
"{path}: {:?}",
report.errors
);
}
let every = check_landed(&[("scripts/run.sh", 2)], &ProjectPolicy::defaults());
assert!(
!no_code_marker(&every),
"the default list is every file: {:?}",
every.errors
);
}
#[test]
fn a_marker_in_a_test_file_pays_the_code_duty() {
for path in ["tests/it.rs", "crates/x/tests/it.rs", "src/lib_test.py"] {
let report = check_landed(&[(path, 2)], &ProjectPolicy::defaults());
assert!(report.errors.is_empty(), "{path}: {:?}", report.errors);
}
let outside = check_landed(&[("tests/it.rs", 2)], &policy_of("code=\"src/**\""));
assert!(no_code_marker(&outside), "{:?}", outside.errors);
}
#[test]
fn markdown_never_pays_the_code_duty_and_fails_outside_docs() {
let unread = |report: &CheckReport| {
report
.errors
.iter()
.filter(|e| e.contains("neither a decision note nor documentation"))
.count()
};
for path in [
"docs/architecture.md",
"README.md",
"notes/x.markdown",
"guide.MDX",
] {
let report = check_landed(&[(path, 2)], &ProjectPolicy::defaults());
assert_eq!(unread(&report), 1, "{path}: {:?}", report.errors);
assert!(no_code_marker(&report), "{path}: {:?}", report.errors);
}
let docs = policy_of("docs=\"README.md\"");
let report = check_landed(&[("README.md", 2), ("src/lib.rs", 2)], &docs);
assert!(report.errors.is_empty(), "{:?}", report.errors);
let report = check_landed(&[("docs/architecture.md", 2), ("src/lib.rs", 2)], &docs);
assert_eq!(unread(&report), 1, "{:?}", report.errors);
}
#[test]
fn a_docs_list_owes_a_marker_of_every_public_promise_in_a_file_it_matches_of_any_type() {
let docs = policy_of("docs=\"website/docs/**/*.html\"");
let report = check_public(&[("src/lib.rs", 2)], &docs);
assert!(
report
.errors
.iter()
.any(|e| e.contains("has no documentation marker")),
"{:?}",
report.errors
);
let paid = check_public(&[("src/lib.rs", 2), ("website/docs/pay.html", 4)], &docs);
assert!(paid.errors.is_empty(), "{:?}", paid.errors);
let plain = check_landed(&[("src/lib.rs", 2)], &docs);
assert!(
plain.errors.is_empty(),
"a plain law owes code alone: {:?}",
plain.errors
);
let empty = check_public(&[("src/lib.rs", 2)], &ProjectPolicy::defaults());
assert!(
empty.errors.iter().any(|e| e.contains(
"is a public promise, written `§!`, and the `docs` list of the block is empty"
)),
"{:?}",
empty.errors
);
}
#[test]
fn a_missing_doc_marker_names_the_form_of_each_file_the_docs_list_matches() {
let docs = policy_of("docs=\"site/**/*.md site/**/*.mdx !site/old/**\"");
let hint = |doc_files: &[&str]| {
let mut scan = landed_at(&[("src/lib.rs", 2)]);
scan.laws[0].public = true;
scan.doc_files = doc_files.iter().map(PathBuf::from).collect();
let graph = Graph::from_scan(&scan);
let report = evaluate(
&scan,
&graph,
1,
&docs,
&default_notes(),
&Others::default(),
);
report
.errors
.into_iter()
.find(|e| e.contains("has no documentation marker"))
.unwrap_or_default()
};
let id = hash::mint_id("Binding sentence.");
let both = hint(&["site/a.md", "site/b.mdx", "site/c.MDX"]);
assert!(
both.contains(&format!(
"(`<!-- § {id} -->` in .md, `{{/* § {id} */}}` in .mdx, or a comment in a file"
)),
"{both}"
);
let mdx = hint(&["site/b.mdx"]);
assert!(
mdx.contains(&format!("(`{{/* § {id} */}}` or a comment in a file")),
"{mdx}"
);
let markdown = hint(&["site/a.md"]);
assert!(
markdown.contains(&format!("(`<!-- § {id} -->` or a comment in a file")),
"{markdown}"
);
assert_eq!(
hint(&[]),
both,
"the patterns name the forms of no file yet"
);
}
#[test]
fn a_file_docs_matches_is_documentation_even_when_code_matches_it() {
let docs = policy_of("docs=\"site/**\"");
let report = check_landed(&[("site/app.js", 2)], &docs);
assert!(no_code_marker(&report), "{:?}", report.errors);
assert!(
!report
.errors
.iter()
.any(|e| e.contains("no documentation marker")),
"{:?}",
report.errors
);
}
#[test]
fn the_docs_duty_is_paid_by_a_marker_of_the_law_or_of_any_clause() {
let id = hash::mint_id("Binding sentence.");
let clause = |letter: &str, line: usize| Clause {
draft: false,
stable_id: None,
letter: Some(letter.into()),
text: "A clause.".into(),
header: String::new(),
end: line,
body: "A clause.".into(),
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line,
},
struck: false,
};
let marker = |letter: &str, path: &str| Pointer {
kind: PointerKind::Implements,
project: None,
name: "binding".into(),
target: Target::Stable {
id: id.clone(),
letter: Some(letter.into()),
},
loc: Location {
path: PathBuf::from(path),
line: 1,
},
};
let scan = Scan {
laws: vec![Law {
draft: false,
body: String::new(),
end: 5,
context: String::new(),
aliases: Vec::new(),
id: id.clone(),
name: "Binding sentence.".into(),
loc: Location {
path: PathBuf::from("docs/decisions/t.md"),
line: 1,
},
clauses: vec![clause("a", 3), clause("b", 5)],
struck: false,
public: false,
}],
pointers: vec![
marker("a", "src/a.rs"),
marker("b", "src/b.rs"),
marker("b", "README.md"),
],
..Scan::default()
};
let report = evaluate(
&scan,
&Graph::from_scan(&scan),
1,
&policy_of("docs=\"README.md\""),
&default_notes(),
&Others::default(),
);
assert!(report.errors.is_empty(), "{:?}", report.errors);
}
#[test]
fn a_file_a_test_gated_path_module_names_is_test_code() {
let files = [
span::CodeFile::new(
PathBuf::from("src/lib.rs"),
"#[cfg(test)]\n#[path = \"cases/mod.rs\"]\nmod cases;\n#[path = \"other.rs\"]\nmod other;\n".to_string(),
),
span::CodeFile::new(
PathBuf::from("src/cases/mod.rs"),
"mod rust;\n// § x\npub fn f() {}\n".to_string(),
),
span::CodeFile::new(
PathBuf::from("src/cases/rust.rs"),
"fn g() {\n // § x\n}\n".to_string(),
),
span::CodeFile::new(
PathBuf::from("src/other.rs"),
"fn h() {\n // § x\n}\n".to_string(),
),
];
let rows = span::test_rows(&files);
for (path, test) in [
("src/cases/mod.rs", true),
("src/cases/rust.rs", true),
("src/other.rs", false),
] {
assert_eq!(rows.contains_key(Path::new(path)), test, "{path}: {rows:?}");
}
}
#[test]
fn every_item_compiled_only_for_tests_is_test_code() {
let gated = |text: &str| {
!span::CodeFile::new(PathBuf::from("src/lib.rs"), text.to_string())
.cfg_test_rows()
.is_empty()
};
for (gate, item) in [
("#[cfg(test)]", "impl Plan {\n fn f() {}\n}"),
("#[cfg(test)]", "struct Plan {\n a: u8,\n}"),
("#[cfg(all(test, unix))]", "fn f() {}"),
("#[cfg(all(unix, all(feature = \"a\", test)))]", "fn f() {}"),
] {
assert!(gated(&format!("{gate}\n{item}\n")), "{gate}");
}
assert!(gated("#![cfg(test)]\nfn f() {}\n"));
assert!(gated("mod checks {\n #![cfg(test)]\n fn f() {}\n}\n"));
for gate in [
"#[cfg(any(test, unix))]",
"#[cfg(not(test))]",
"#[cfg(unix)]",
] {
assert!(!gated(&format!("{gate}\nfn f() {{}}\n")), "{gate}");
}
}
}