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, Verdict};
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>,
/// Pins whose span moved. They fail `check` like errors, but `diff` still reads them.
pub drifts: Vec<String>,
/// A drifted `AGENTS.md` block or skill pointer. It fails `check` like an error, but it is
/// not the graph, so `diff` and `log` still read.
pub harness: Vec<String>,
pub warnings: Vec<String>,
/// One line per draft address, with its text: neither an error nor a warning.
pub drafts: Vec<String>,
/// Each change a comparing check names for the person who merges: it fails nothing.
pub named: Vec<String>,
/// Documentation markers whose pin matched.
pub doc_verified: usize,
/// The files each drift of `drifts`, by its text, reads, as absolute paths: its own, each
/// body it follows and the note of its law.
pub reads: BTreeMap<String, Vec<PathBuf>>,
/// The pin of each drift of `drifts`, by its text.
pub pins: BTreeMap<String, DriftPin>,
/// How many pins held, fewer than drift once a scheme change moved most of them.
pub held: usize,
/// The drifts that held at the fork point and read no file the change edited: a file it
/// added, deleted or renamed, or a block it edited, moved them.
pub structural: BTreeSet<String>,
/// The files added, deleted or renamed and the `AGENTS.md` edited since the fork point,
/// which a structural drift counts as read.
pub structure_paths: Vec<PathBuf>,
}
/// Where a drifted pin sits: its project's directory, its file there, its address and digest.
#[derive(Clone, Debug)]
pub struct DriftPin {
pub dir: PathBuf,
pub rel: PathBuf,
pub addr: String,
pub digest: String,
}
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,
reads: BTreeMap::new(),
pins: BTreeMap::new(),
held: 0,
structural: BTreeSet::new(),
structure_paths: Vec::new(),
}
}
pub fn is_closed(&self) -> bool {
self.errors.is_empty() && self.drifts.is_empty() && self.harness.is_empty()
}
}
/// The graphs of the other projects of the workspace, keyed by project path, for qualified
/// references. `own` is the path of the project being checked.
#[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()
}
}
/// Check each project on its own and merge the reports. With `prefix`, every finding names its
/// project path.
pub fn validate(ws: &Workspace, projects: &[&ProjectRef], prefix: bool) -> Result<CheckReport> {
// § egfcsmhyg.b@atnya
let mut report = CheckReport::empty();
// Projects share no code, so each is checked beside the others and merged in order.
let reports: Vec<Result<CheckReport>> = std::thread::scope(|s| {
let runs: Vec<_> = projects
.iter()
.map(|project| crate::par::spawn(s, || validate_project(ws, project)))
.collect();
runs.into_iter().map(joined).collect()
});
for (project, one) in projects.iter().zip(reports) {
let one = one?;
let tag = |text: String| {
if prefix {
format!("[{}] {text}", project.key)
} else {
text
}
};
report.files += one.files;
report.doc_verified += one.doc_verified;
report.held += one.held;
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));
report
.reads
.extend(one.reads.into_iter().map(|(text, read)| (tag(text), read)));
report
.pins
.extend(one.pins.into_iter().map(|(text, pin)| (tag(text), pin)));
}
for d in crate::harness::probe_drift(&ws.root)? {
push_drift(d, &mut report);
}
Ok(report)
}
/// Every way a pin `base` held can have moved without a marker failing `check`, each named where
/// it sits now, or where `base` held it when nothing carries it: an address that carries a digest
/// `base` never held there while a digest it held is gone, an address `base` pinned that is now
/// bare, gone or struck, a published id reminted, and a published law the tree no longer
/// declares. The pins of an address are paired file by file, a renamed file at its new path. An
/// address `base` published under an alias anchor is matched under the id that carries it now.
pub fn accepted_pins(
ws: &Workspace,
projects: &[&ProjectRef],
base: &str,
prefix: bool,
) -> Result<Vec<String>> {
// § j44p1s9z8@j3dps
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();
// § j44p1s9z8.d@nr8fe
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())
));
}
// § end j44p1s9z8.d
let alias: BTreeMap<&str, &str> = scan
.laws
.iter()
.flat_map(|law| law.aliases.iter().map(|a| (a.as_str(), law.id.as_str())))
.collect();
// § j44p1s9z8.a@rypfm
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,
});
}
}
}
// § end j44p1s9z8.a
// § j44p1s9z8.e@6xjt3
let folded = crate::diff::folded_pins(ws, root, base)?;
let mut now: BTreeMap<MarkerAddr, PinsByFile> = BTreeMap::new();
// Each pin nested in a pin of another address: where it sits, its address, and the outer
// address and digest.
let mut nested = Vec::new();
for path in walk::code_files(root)? {
// § j44p1s9z8.b@r4zh8
let text = std::fs::read_to_string(&path)?;
let rel = path.strip_prefix(root).unwrap_or(&path);
// A pin `diff` folds as a scheme remint carries the digest it held, for this
// comparison.
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(),
));
}
}
}
}
// § end j44p1s9z8.e
// § j44p1s9z8.a@q4kz4
let active = active_addresses(&scan.laws);
let base_files = crate::published::files_at(root, base)?;
// The pins no published pin of their address in their file pairs with, while every
// published one there is paired: new pins, not accepts.
let mut new_pins: BTreeSet<(PathBuf, usize, MarkerAddr)> = BTreeSet::new();
let addrs: BTreeSet<&MarkerAddr> = was.keys().chain(now.keys()).collect();
for addr in addrs {
// A published pin of a file the tree no longer holds, and a pin of a file `base`
// did not hold: git reads no rename of an untracked file, so they pair by digest.
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();
// The other files that carry `digest` for this address now, to name beside a pin
// its own file lost.
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();
// § j44p1s9z8.b@3xr9p
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);
}
}
// § end j44p1s9z8.b
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)?);
found.extend(reminted_pins(root, &folded)?);
// § end j44p1s9z8.a
// § j44p1s9z8.c@4hwmh
let published = &point;
let keys = published.keys();
for law in &scan.laws {
for old in law.aliases.iter().filter(|a| keys.contains(*a)) {
// A remint mints the id of its new sentence, so a host the base already
// published under its own id is another law: the anchor grafts a deletion.
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
));
}
// § end j44p1s9z8.c
for text in found {
out.push(if prefix {
format!("[{}] {text}", project.key)
} else {
text
});
}
}
Ok(out)
}
/// Each law active at the published tree that the tree still declares under its id, with the
/// canonical text of its head or of an active clause changed, struck or deleted since, named at
/// its head: no pin need move for it, so a comparing check sends the reviewer to `diff`. A law struck
/// there that the tree revives is named when its head or a clause it held reads otherwise. A
/// law reminted to another id is named by (e) instead.
fn reworded_laws(now: &[Law], published: &[Law], short: &str) -> Vec<String> {
// § j44p1s9z8.c@1fstb
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 {
// A revival brings back the text the law last published, or it is a change to it.
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
}
/// Each draft of the tree that a person has not approved: an address active and owed at the
/// published tree that the tree makes a draft, since the `?` waives its duty, and a draft law or
/// clause the published tree did not hold, a promise the tree keeps without code.
fn drafted_laws(now: &[Law], published: &[Law], short: &str) -> Vec<String> {
// § j44p1s9z8.g@an4ep
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
}
/// Each law and clause of the tree, owed and active, that the published tree did not hold, a
/// draft aside since (g) names it, and each law whose head the tree makes a public promise or
/// makes plain: a promise added or a documentation duty taken up or dropped.
fn added_laws(now: &[Law], published: &[Law], short: &str) -> Vec<String> {
// § j44p1s9z8.l@xzs89
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
}
/// Every address the published tree declares unstruck, a draft included, under the id the tree
/// carries it by now when a remint keeps the published id as an alias anchor.
fn held_addresses(now: &[Law], published: &[Law]) -> BTreeSet<String> {
// § j44p1s9z8.a@1f5zc
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
}
/// The pins of one address by file: the 1-based line and the digest of each, `None` when bare.
type PinsByFile = BTreeMap<PathBuf, Vec<NowPin>>;
/// A pin of the tree: its 1-based line, its digest, `None` when bare, and the names of the
/// constructs around its span when its file changed since the published tree.
struct NowPin {
line: usize,
digest: Option<String>,
binding: Option<Vec<String>>,
}
/// A pin the published tree held, with the names of the constructs around its span when its
/// file changed since.
struct HeldPin {
digest: String,
binding: Option<Vec<String>>,
}
impl HeldPin {
/// Whether `pin` is this pin: the same digest over a span in constructs of the same names,
/// when both sides read them.
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,
}
}
}
/// The constructs a span sits in, as a message names them.
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(),
}
}
/// An attribute of the Silcrow block as it is written, or its absence.
fn block_attr(attr: &str, value: Option<&str>) -> String {
match value {
Some(value) => format!("`{attr}=\"{value}\"`"),
None => format!("no `{attr}`"),
}
}
/// The names of the constructs around the span of each pin `base` held, keyed by the path
/// there, the address as written and the digest, in file order.
type HeldBindings = BTreeMap<(PathBuf, crate::marker::MarkerAddr, String), Vec<Vec<String>>>;
/// The `HeldBindings` of the files of `touched`.
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)
}
/// Every pin of a project nested in `project` at `base` that the tree no longer holds as a
/// project: its laws left with it, so no marker carries those pins now. A vanished project
/// inside one that still exists is that one's to name.
fn vanished_pins(project: &ProjectRef, base: &str) -> Result<Vec<String>> {
// § j44p1s9z8.a@77b23
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)? {
// § j44p1s9z8.c@4173m
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)
}
/// What the published history at `base` holds against the tree: a law declared under an id a
/// removed law carried, and a letter `base` wrote for a law the tree still declares and no
/// longer writes, which only the tree's own tombstone could keep from being written again.
pub fn returned_tokens(projects: &[&ProjectRef], base: &str, prefix: bool) -> Result<Vec<String>> {
// § cmx8g7zp2.b@95a1r
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 {
// § s6aqqwvmc.c@yfxrp
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)
}
/// The active laws and clauses, as a marker addresses them.
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) {
// § fgbh1bkcj.b@xcjqt
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);
}
}
/// One project, held to its own policy and its own markers.
fn validate_project(ws: &Workspace, project: &ProjectRef) -> Result<CheckReport> {
// § xs2e8kj86.d@7cdzw
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()
});
}
};
// § end xs2e8kj86.d
// The code parse and its follow index and the provisional scan do not depend on the note
// scan, so they run beside it. Errors still surface in the order of the sequential steps.
std::thread::scope(|s| {
// § r4dndth75.f@6hq9m
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 read = siblings_read(ws, &project.key, &scan, &graph);
let scans = ws.law_scans_of(&project.key, |key| read.contains(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 drifted: BTreeMap<(PathBuf, usize), String> = bare_drifts(root, &code, &texts)?
.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),
);
let mut blocked = Vec::new();
for (file, checked) in code.iter().zip(checks) {
// Its spans cannot be delimited: the one error names why.
if let Some(err) = file.too_deep() {
report.errors.push(err);
continue;
}
report.errors.extend(checked.errors);
blocked.extend(checked.blocked);
drifts.extend(checked.drifts);
report.held += checked.verified;
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,
);
}
report.errors.extend(blocked_errors(&code, blocked));
// § wwam5ewba@e10ev
let wide = crate::par::map(
code.iter()
.filter(|f| f.too_deep().is_none() && f.text.contains('§'))
.collect(),
|f| f.text.len(),
|file| crate::stats::wide_pins(file, &follow),
);
report.warnings.extend(wide.into_iter().flatten());
// § end wwam5ewba
test_code_markers(&code, &policy, &paths.notes, &mut report);
let forms = crate::par::map(
code.iter().collect(),
|f| f.text.len(),
|file| {
let mut part = CheckReport::empty();
check_duplicate_markers(file, &mut part.errors);
check_one_lists(file, &mut part.errors);
check_marker_form(file, &mut part);
check_code_above(file, &mut part.warnings);
part
},
);
for part in forms {
report.errors.extend(part.errors);
report.warnings.extend(part.warnings);
}
report
.warnings
.extend(untracked_reads(root, &code, &follow)?);
let reads = drift_reads(ws, root, &code, &follow, &scan, &scans, &drifts);
let messages = drift_messages(root, &scan, code, follow, &drifts)?;
for pin in report.pins.values_mut() {
pin.dir = root.to_path_buf();
}
report
.pins
.extend(messages.iter().cloned().zip(drifts.iter().map(|d| {
DriftPin {
dir: root.to_path_buf(),
rel: d.path.clone(),
addr: crate::marker::MarkerAddr {
digest: None,
..d.pin.clone()
}
.display(),
digest: d.pin.digest.clone().unwrap_or_default(),
}
})));
report.drifts = messages;
report.reads = report.drifts.iter().cloned().zip(reads).collect();
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)
})
}
/// The other projects whose notes a check of the project `own` reads: each one a reference of
/// `scan` names, and every one when a reference asks which project declares its id, an
/// unqualified one `graph` does not resolve or one qualified with a path no project has.
fn siblings_read<'a>(
ws: &'a Workspace,
own: &str,
scan: &Scan,
graph: &Graph,
) -> BTreeSet<&'a str> {
let siblings: BTreeSet<&str> = ws
.projects
.iter()
.map(|project| project.key.as_str())
.filter(|key| *key != own)
.collect();
let references = scan.pointers.iter().chain(&scan.mentions);
let asks = references.clone().any(|ptr| {
let Target::Stable { id, letter } = &ptr.target else {
return false;
};
match ptr.project.as_deref() {
None => {
graph.lookup(&ptr.name, &ptr.target).is_none()
&& graph
.aliases
.get(id)
.and_then(|current| {
let target = Target::Stable {
id: current.clone(),
letter: letter.clone(),
};
graph.lookup(&ptr.name, &target)
})
.is_none()
}
Some(project) => project != own && !siblings.contains(project),
}
});
if asks {
return siblings;
}
let named: BTreeSet<&str> = references
.filter_map(|ptr| ptr.project.as_deref())
.chain(
scan.adoptions
.iter()
.map(|adoption| adoption.project.as_str()),
)
.collect();
siblings
.into_iter()
.filter(|key| named.contains(key))
.collect()
}
/// Each pin of the project whose digest differs from what its inputs hash to now, as `check`
/// reads it, with the files it reads as `drift_reads` names them.
pub fn drifted_pins(
ws: &Workspace,
project: &ProjectRef,
) -> Result<Vec<(span::Drift, Vec<PathBuf>)>> {
// § xnsbksxv6.h@s3wvc
let root = project.dir.as_path();
let policy = ProjectPolicy::from_root(root).map_err(anyhow::Error::msg)?;
let code = span::CodeFile::read_all(root)?;
let follow = crate::follow::FollowIndex::from_files(&code, &policy.tests);
let scan = scan_root(root)?;
let scans = ws.law_scans(&project.key)?;
let texts = span::PinTexts::for_project(&scan, &scans);
let checks = crate::par::map(
code.iter()
.filter(|file| file.too_deep().is_none())
.collect(),
|f| f.text.len(),
|file| span::verify_file_follow(file, scheme::SERIALIZATION, &follow, &texts),
);
let bare = bare_drifts(root, &code, &texts)?.into_iter().map(|d| {
let file = code.iter().find(|file| file.rel == d.rel);
let bit = file.and_then(|file| file.text.lines().nth(d.line - 1));
span::Drift {
bit: bit.unwrap_or_default().trim().to_string(),
path: d.rel,
line: d.line,
pin: d.addr,
}
});
let drifts: Vec<span::Drift> = checks
.into_iter()
.flat_map(|checked| checked.drifts)
.chain(bare)
.collect();
let reads = drift_reads(ws, root, &code, &follow, &scan, &scans, &drifts);
Ok(drifts.into_iter().zip(reads).collect())
}
/// Each bare marker of `code` whose span no longer hashes to a pin `HEAD` held for it there: a
/// drift whose digest a merge or a hand removed.
fn bare_drifts(
root: &Path,
code: &[span::CodeFile],
texts: &span::PinTexts,
) -> Result<Vec<span::DriftedBare>> {
// § jed5hb8sa.b@ns1tx
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();
match bare.is_empty() {
true => Ok(Vec::new()),
false => span::drifted_bare(root, &span::pin_bare(root, texts, Some(&bare))?),
}
}
/// The files each drift reads, as absolute paths, in the order of `drifts`: the file of its
/// marker, each body its pin follows, and the note that declares its law, in whatever project.
fn drift_reads(
ws: &Workspace,
root: &Path,
code: &[span::CodeFile],
follow: &crate::follow::FollowIndex,
scan: &Scan,
scans: &LawScans,
drifts: &[span::Drift],
) -> Vec<Vec<PathBuf>> {
// § kv22y3ap6.k@wzzx9
let mut markers: BTreeMap<&Path, (&span::CodeFile, Vec<span::SpanMarker>)> = BTreeMap::new();
drifts
.iter()
.map(|d| {
let mut read = vec![root.join(&d.path)];
if let Some(file) = code.iter().find(|file| file.rel == d.path) {
let (file, all) = markers
.entry(file.rel.as_path())
.or_insert_with(|| (file, file.span_markers()));
let found = all.iter().find(|m| {
m.line == d.line
&& m.addr.project == d.pin.project
&& m.addr.id == d.pin.id
&& m.addr.letter == d.pin.letter
});
if let Some(m) = found {
let punch = span::punch_of(all, m.line);
let prefix = file.prefix(m.start, m.end);
read.extend(
follow
.followed_callees(&file.rel, m.start, m.end, &punch, &prefix)
.into_iter()
.map(|callee| root.join(callee.path)),
);
}
}
let declared = match &d.pin.project {
None => Some((root, &scan.laws)),
Some(key) => ws
.get(key)
.zip(scans.scans.get(key))
.map(|(project, scan)| (project.dir.as_path(), &scan.laws)),
};
if let Some((dir, laws)) = declared {
read.extend(
laws.iter()
.filter(|law| law.id == d.pin.id || law.aliases.contains(&d.pin.id))
.map(|law| dir.join(&law.loc.path)),
);
}
read.sort();
read.dedup();
read
})
.collect()
}
/// The error of each drift, naming what moved since the last commit that holds its pin as it
/// stands, read as `diff` reads a drift: its span first, then the code before it, a followed
/// callee, an import line, its law or clause text, and a scheme the binary moved. A drift that
/// commit does not hold, or under which nothing it reads moved, is read since the commit that
/// wrote its digest when the history last records this binary's scheme, and names every input
/// when that commit holds nothing either.
fn drift_messages(
root: &Path,
scan: &Scan,
code: Vec<span::CodeFile>,
follow: crate::follow::FollowIndex,
drifts: &[span::Drift],
) -> Result<Vec<String>> {
// § z0xqn70bp.a@44wg7
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 now = crate::diff::Tree::of(code, follow, &scan.laws);
let then = crate::diff::Tree::at_reusing(root, "HEAD", Some(&now))?;
let recorded = crate::hook::recorded_scheme_at(root, "HEAD")?;
let binary = scheme::Scheme::binary();
let bump = |recorded: Option<&scheme::Scheme>, path: &Path| {
let moved = recorded?.moved(&binary, &scheme::parts_of(path));
(!moved.is_empty())
.then(|| format!("the hashing scheme moved for {}", scheme::describe(&moved)))
};
// One git read for the old text of every file with no tested grammar, not one per pin.
let untested: Vec<PathBuf> = drifts
.iter()
.filter(|d| crate::span_lang::lang_for_path(&d.path).is_none())
.map(|d| d.path.clone())
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
let held: BTreeMap<PathBuf, Option<String>> = untested
.iter()
.cloned()
.zip(crate::published::blobs_at(root, "HEAD", &untested)?)
.collect();
let aliases_of = |d: &span::Drift| {
scan.laws
.iter()
.find(|law| d.pin.project.is_none() && law.id == d.pin.id)
.map_or(&[][..], |law| law.aliases.as_slice())
};
let causes = crate::par::map_many(drifts.iter().collect(), |d| {
let found = match crate::span_lang::lang_for_path(&d.path) {
None => fallback_cause(root, (&then, &now), d, held[&d.path].as_deref())?,
Some(_) => drift_cause(&then, &now, d, aliases_of(d), None),
};
anyhow::Ok(found.map(|cause| match bump(recorded.as_ref(), &d.path) {
Some(bump) => format!("{cause}, and {bump}"),
None => cause,
}))
});
// A pin under which nothing moved since HEAD drifted before it: a commit that skipped the
// hooks, or one that reminted the other pins around it. Its cause is what moved since the
// commit that wrote its digest, read once per such commit. While the history records
// another version of a part a pin reads, that pin drifts, so it reads that part as its cause
// instead.
let mut earlier: BTreeMap<String, crate::diff::Tree> = BTreeMap::new();
let mut out = Vec::new();
for (d, found) in drifts.iter().zip(causes) {
let tested = crate::span_lang::lang_for_path(&d.path).is_some();
let moved = bump(recorded.as_ref(), &d.path);
let found = found?;
let writer = match (&found, tested && recorded.is_some()) {
(None, true) => digest_writer(root, d)?,
_ => None,
};
let written = match &writer {
Some(rev) => crate::hook::recorded_scheme_at(root, rev)?,
None => None,
};
// § z0xqn70bp.f@czc8z
// A merge can bring a digest that a commit wrote under this binary's scheme while the
// history of `HEAD` records another: the scheme then moved nothing under it.
let current = written.is_some() && bump(written.as_ref(), &d.path).is_none();
// § end z0xqn70bp.f
let message = match found {
Some(cause) => d.message(Some(&cause)),
None if moved.is_some() && !current => d.message(moved.as_deref()),
// § one z0xqn70bp.e@vrmh2
None if tested && recorded.is_some() => match writer {
Some(rev) => {
if !earlier.contains_key(&rev) {
let tree = crate::diff::Tree::at_reusing(root, &rev, Some(&now))?;
earlier.insert(rev.clone(), tree);
}
let then_scheme = bump(written.as_ref(), &d.path);
let since = match current {
true => format!(
"{}, the commit that wrote its digest under this binary's scheme",
crate::published::short(&rev)
),
false => format!(
"{}, the commit that wrote its digest",
crate::published::short(&rev)
),
};
let block = Path::new("AGENTS.md");
let tag = |text: Option<String>| {
text.and_then(|text| {
let start = text.find("<silcrow")?;
let end = text[start..].find('>')?;
Some(text[start..start + end].to_string())
})
};
let block_moved = tag(crate::published::blobs_at(root, &rev, &[block.into()])?
.pop()
.flatten())
!= tag(std::fs::read_to_string(root.join(block)).ok());
match drift_cause(&earlier[&rev], &now, d, aliases_of(d), then_scheme) {
Some(cause) => d.message_since(Some(&cause), &since),
None if block_moved => d.message_since(
Some("the `<silcrow>` block of `AGENTS.md` reads otherwise"),
&since,
),
None => d.message(None),
}
}
None => d.message(None),
},
None => d.message(None),
};
out.push(message);
}
Ok(out)
}
/// Each pin of the project at `root` that `diff` folds as a scheme remint, by its file and
/// 1-based line in `folded`, named with what it reads now: the scheme reads it otherwise.
fn reminted_pins(root: &Path, folded: &BTreeMap<(PathBuf, usize), String>) -> Result<Vec<String>> {
// § d1bc2zca5.i@x2fdd
if folded.is_empty() {
return Ok(Vec::new());
}
let code = span::CodeFile::read_all(root)?;
let tests = crate::policy::TestPaths::at(root)?;
let follow = crate::follow::FollowIndex::from_files(&code, &tests);
let mut out = Vec::new();
for (path, line) in folded.keys() {
let Some(file) = code.iter().find(|file| &file.rel == path) else {
continue;
};
let text = file.text.lines().nth(line - 1).unwrap_or_default();
let extent = crate::stats::extent_at(file, &follow, *line);
for pin in crate::marker::markers_in_line(text) {
let addr = crate::marker::MarkerAddr {
digest: None,
..pin
};
out.push(span::reminted_line(path, *line, &addr.display(), extent));
}
}
Ok(out)
}
/// One `accept` per project of every drift of `drifts`, by its text in `pins`, so a reader
/// approves them in one call each and never loops: `-C <dir>` names a project the working
/// directory does not sit in.
fn one_accept_lines<'a>(
drifts: impl Iterator<Item = &'a String>,
pins: &BTreeMap<String, DriftPin>,
) -> Vec<String> {
// § z0xqn70bp.b@sd670
let mut by_dir: BTreeMap<&Path, Vec<&str>> = BTreeMap::new();
for pin in drifts.filter_map(|text| pins.get(text)) {
let addrs = by_dir.entry(pin.dir.as_path()).or_default();
if !addrs.contains(&pin.addr.as_str()) {
addrs.push(&pin.addr);
}
}
let cwd = std::env::current_dir().ok();
let single = by_dir.len() == 1;
by_dir
.into_iter()
.map(|(dir, addrs)| {
let here = cwd
.as_deref()
.is_some_and(|cwd| cwd == dir || (single && cwd.starts_with(dir)));
let at = match here {
true => String::new(),
false => format!("-C {} ", dir.display()),
};
format!(
"Read each drift with `silcrow diff --law <address>`, then accept them in one call: `silcrow {at}accept {}`.",
addrs.join(" ")
)
})
.collect()
}
/// The last commit in the history of `HEAD` that wrote the pin of `d` as it stands, `None`
/// outside git or when no commit holds it.
fn digest_writer(root: &Path, d: &span::Drift) -> Result<Option<String>> {
let Some(digest) = &d.pin.digest else {
return Ok(None);
};
let needle = format!("{}@{digest}", d.pin.display());
let out = crate::workspace::git(root)
.args(["log", "-1", "--format=%H", "-S", &needle, "HEAD", "--"])
.arg(&d.path)
.output()?;
let rev = String::from_utf8_lossy(&out.stdout).trim().to_string();
Ok((out.status.success() && !rev.is_empty()).then_some(rev))
}
/// One error per parse error that keeps pins from being hashed, at its file and line, naming
/// merge conflict markers in that file, then the count of those pins and each pin on a line.
fn blocked_errors(code: &[span::CodeFile], blocked: Vec<span::Blocked>) -> Vec<String> {
// § cd5y5pa34.c@z4brf
let mut by_cause: BTreeMap<(String, usize), Vec<span::Blocked>> = BTreeMap::new();
for b in blocked {
let key = (b.at.to_string_lossy().replace('\\', "/"), b.line);
by_cause.entry(key).or_default().push(b);
}
by_cause
.into_iter()
.map(|((at, line), pins)| {
// § fcknw57x1.d@s7rnf
let conflict = code
.iter()
.find(|f| f.rel.to_string_lossy().replace('\\', "/") == at)
.and_then(|f| conflict_line(&f.text));
let cause = match conflict {
Some(first) => format!(
"{at}:{line}: holds merge conflict markers at line {first}: resolve them first. It does not parse with the tree-sitter grammar at line {line}"
),
None => format!(
"{at}:{line}: does not parse with the tree-sitter grammar at line {line} (a syntax error, or syntax the grammar does not know), which can hide a declaration"
),
};
// § end fcknw57x1.d
let mut out = format!(
"{cause}, so {} pin(s) that read it cannot be hashed:",
pins.len()
);
for b in pins {
out.push_str("\n ");
out.push_str(&b.pin);
if let Some(name) = &b.name {
out.push_str(&format!(
", which reads `{name}`, a name that denotes no declaration"
));
}
}
out
})
.collect()
}
/// The 1-based line of the first git merge conflict marker of `text`.
fn conflict_line(text: &str) -> Option<usize> {
text.lines()
.position(crate::span_lang::is_conflict_marker)
.map(|idx| idx + 1)
}
/// What moved under the pin of `d`, in a file with no tested grammar, from `HEAD` to the tree:
/// its stretch or the text of its address, the only things such a pin reads.
fn fallback_cause(
root: &Path,
(then, now): (&crate::diff::Tree, &crate::diff::Tree),
d: &span::Drift,
old: Option<&str>,
) -> Result<Option<String>> {
// § z0xqn70bp.a@86dnw
let Some(old) = old 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,
},
)
}
/// What moved under the pin of `d` from `then` to `now`, as a clause of its message.
fn drift_cause(
then: &crate::diff::Tree,
now: &crate::diff::Tree,
d: &span::Drift,
aliases: &[String],
bump: Option<String>,
) -> Option<String> {
// § z0xqn70bp.c@xpygr
// A remint the commit does not hold yet left the pin there under an id the law keeps as
// an alias anchor.
// Its old text reads under the new id, so the rewrite of the remint alone moves nothing.
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,
};
// A side that cannot be read here fails on its own line, so the drift keeps its own message.
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());
}
if moved.above {
parts.push("a key or an entry above 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());
}
// A qualified address hashes the text of another project, which these trees do not key.
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(bump) = bump {
cause = Some(match cause {
Some(cause) => format!("{cause}, and {bump}"),
None => bump,
});
}
cause
}
/// Each marker in test code, outside Markdown and documentation, as an error where
/// `test-markers` reads `error` for its file and as a warning where it reads `warn`.
fn test_code_markers(
code: &[span::CodeFile],
policy: &ProjectPolicy,
notes: &walk::Notes,
report: &mut CheckReport,
) {
// § xs2e8kj86.k@8zdc7
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;
}
// § xs2e8kj86.l@4774z
let (out, verdict) = match policy.test_markers.at(&file.rel) {
(Verdict::Allow, _) => continue,
(Verdict::Warn, None) => (
&mut report.warnings,
"the `AGENTS.md` block admits it with a warning under `test-markers=\"warn\"`"
.to_string(),
),
(Verdict::Warn, Some(rule)) => (
&mut report.warnings,
format!("the `AGENTS.md` block admits it with a warning under the `test-markers` rule `{rule}`"),
),
(Verdict::Error, None) => (
&mut report.errors,
"a marker there fails `check` under `test-markers=\"error\"`, the default"
.to_string(),
),
(Verdict::Error, Some(rule)) => (
&mut report.errors,
format!("a marker there fails `check` under the `test-markers` rule `{rule}`"),
),
};
// § end xs2e8kj86.l
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\"`, or a rule `<glob>:allow` for its path, where a test carries a law no code of this tree decides.",
file.rel.display(),
idx + 1,
addr.id
));
}
}
}
}
/// Each decision note of the project that holds more words than its `note-words` limit, as an
/// error or as a warning as the limit says.
fn note_sizes(root: &Path, policy: &ProjectPolicy, report: &mut CheckReport) -> Result<()> {
// § ht00zbbhg@fvhsc
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;
}
// § ht00zbbhg.a@1ke8j
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()
));
// § end ht00zbbhg.a
}
Ok(())
}
/// A warning for each file git neither tracks nor ignores that holds a body a span follows: a
/// run by hand reads it, and the hook, which reads the index, and a CI checkout do not, so a pin
/// written through it reads otherwise there. A marker in such a file is not named: its own pin
/// reads alike in the hook once the file is staged, and the hook names a law it leaves uncovered.
fn untracked_reads(
root: &Path,
code: &[span::CodeFile],
follow: &crate::follow::FollowIndex,
) -> Result<Vec<String>> {
// § pga7yfvm9.d@5875w
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()
));
}
// A declaration there is a homonym that every span calling or reading the name reads.
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>) {
// § rr512n5e2.d@t7940
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() {
// The addresses of one `§ one` list count as one marker.
for second in markers[i + 1..].iter().filter(|m| m.line != first.line) {
// § rr512n5e2.f@mjaye
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;
}
// § end rr512n5e2.f
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
));
}
}
}
}
/// A `§ one` list names each address once and never a law beside its own clause, needs a tested
/// grammar and a statement or member below it, and takes no `§ end`.
fn check_one_lists(file: &span::CodeFile, errors: &mut Vec<String>) {
// § xs2e8kj86.h@ax05h
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()
));
}
}
// § rr512n5e2.h@31ara
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.parsed() && !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."
));
}
// § end rr512n5e2.h
}
// § rr512n5e2.j@39548
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
));
}
// § end rr512n5e2.j
}
/// A line that opens like a marker and is none fails. A pointer read through case or a
/// Crockford homoglyph resolves, and warns until `fix` writes it in canonical form.
fn check_marker_form(file: &span::CodeFile, report: &mut CheckReport) {
use crate::marker;
let markdown = marker::is_markdown(&file.rel);
// § xs2e8kj86.b@s3wmr
let malformed = file.memo(&"malformed lines", || {
marker::malformed_lines(marker::Dialect::of(&file.rel), &file.text)
});
for line in malformed {
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()
));
}
// § end xs2e8kj86.b
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 literal_markers(file) {
report.errors.push(format!(
"{}:{line}: this line opens like a marker inside a string, a heredoc or a block scalar, and a marker inside a string is text to the grammar of `.{}`: it pins nothing. Move it out of the string, onto a comment line above the code it names.",
file.rel.display(),
file.rel.extension().and_then(|e| e.to_str()).unwrap_or("?"),
));
}
for line in trailing_markers(file) {
report.errors.push(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()
));
}
// § n71fgy5xw.b@dzmp8
let canonical = file.memo(&"canonical pointers", || {
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()
));
}
}
// § end n71fgy5xw.b
}
/// A warning for each bare marker with no `§ end` whose span, the construct that holds it, holds
/// statements or members above it that its pin reads only because the span holds them.
fn check_code_above(file: &span::CodeFile, warnings: &mut Vec<String>) {
// § rr512n5e2.p@872dv
if file.lang.is_none() || !file.text.contains('§') {
return;
}
let markers = file.span_markers();
let counts: Vec<usize> = file.memo(&"code above markers", || {
let (Some(lang), Some(tree)) = (file.lang, file.tree()) else {
return Vec::new();
};
markers
.iter()
.map(|m| {
if m.explicit {
return 0;
}
let cut: Vec<(usize, usize)> = markers
.iter()
.filter(|o| o.addr.digest.is_some() && (o.start, o.end) != (m.start, m.end))
.filter(|o| m.start <= o.start && o.end <= m.end)
.map(|o| (o.start, o.end))
.collect();
crate::span_lang::code_above(lang, &file.text, tree, m.line, &cut)
})
.collect()
});
for (m, above) in markers.iter().zip(counts) {
if above > 0 {
warnings.push(format!(
"{}:{}: § {} spans the whole construct that holds it, and its pin reads the {above} statement(s) or member(s) above the marker only because that span holds them. Write it `§ one` on the line above the code it carries, close it with a `§ end`, or move it to the top of the construct.",
file.rel.display(),
m.line,
crate::marker::MarkerAddr {
digest: None,
..m.addr.clone()
}
.display()
));
}
}
}
/// The 1-based lines of a file in a tested grammar, Markdown aside, that open like a marker
/// inside a string, a heredoc or a block scalar, where the grammar reads them as a value.
fn literal_markers(file: &span::CodeFile) -> Vec<usize> {
// § xs2e8kj86.n@rbp33
if crate::marker::is_markdown(&file.rel) || !file.text.contains('§') {
return Vec::new();
}
file.memo(&"literal markers", || {
let (Some(lang), Some(tree)) = (file.lang, file.tree()) else {
return Vec::new();
};
let literal = crate::span_lang::literal_lines(lang, &file.text, tree);
file.text
.lines()
.zip(literal)
.enumerate()
.filter(|(_, (line, literal))| *literal && crate::marker::shaped_as_marker(line))
.map(|(idx, _)| idx + 1)
.collect()
})
}
/// The 1-based lines of `file` where a comment that opens like a marker follows code. A parsed
/// file reads its comments from the grammar, so a string that holds `// §` is not one.
fn trailing_markers(file: &span::CodeFile) -> Vec<usize> {
file.memo(&"trailing markers", || trailing_markers_of(file))
}
fn trailing_markers_of(file: &span::CodeFile) -> Vec<usize> {
// § xs2e8kj86.b@4yen3
let tree = match file.tree() {
Some(tree) if !crate::marker::is_markdown(&file.rel) => tree,
_ => {
// A wrapper inside a string the fallback reads is a value, as in a parsed file.
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 before = lines
.get(start.row)
.and_then(|line| line.get(..start.column))
.map(|before| before.trim_start_matches('\u{feff}').trim());
// § xs2e8kj86.m@amrqm
let jsx_container = before == Some("{")
&& crate::marker::Dialect::of(&file.rel) == crate::marker::Dialect::Jsx
&& node.parent().is_some_and(|p| p.kind() == "jsx_expression");
// § end xs2e8kj86.m
let after_code = before.is_some_and(|before| !before.is_empty()) && !jsx_container;
if opens && after_code {
out.push(start.row + 1);
}
}
out.sort();
out
}
/// The error of a `notes` list that matches no note while a marker of the project points to
/// a law, so a list that misses its notes names itself rather than only the markers it orphans.
/// A project with no marker and no note is new, and reads 0 notes.
fn no_notes_matched(root: &Path, notes: usize, scan: &Scan) -> Option<String> {
// § r40mp2y8s.d@kgbhp
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`."
))
}
/// Every file the project walks for code is one `fix` pins, so a bare marker that a span can
/// hold fails here wherever it sits, and one outside every span fails too.
fn check_span_pins(
file: &span::CodeFile,
unhashable: &BTreeSet<usize>,
inert: &BTreeSet<usize>,
drifted: &BTreeMap<(PathBuf, usize), String>,
report: &mut CheckReport,
) {
// § d1bc2zca5.e@4x79m
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) {
// § rr512n5e2.e@va3j3
// An empty span and a span whose closure cannot be hashed already fail on their
// own line, and `fix` cannot pin either.
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) {
// § z0xqn70bp@edse6
let held = drifted.get(&(path.to_path_buf(), idx + 1));
let text = match held {
// § jed5hb8sa.b@s83gg
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 with `silcrow diff --law {}`, then accept it with the other drifts you read, in one `silcrow accept <address>...`.",
path.display(),
idx + 1,
pin.display(),
pin.display()
),
// § end jed5hb8sa.b
None => format!(
"{}:{}: § {} is not pinned. Run `silcrow fix` to pin it.",
path.display(),
idx + 1,
pin.display()
),
};
if held.is_some() {
// Its project directory is set where the drifts of the project are read.
let pin = DriftPin {
dir: PathBuf::new(),
rel: path.to_path_buf(),
addr: pin.display(),
digest: String::new(),
};
report.pins.insert(text.clone(), pin);
}
report.errors.push(text);
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 {
// § xs2e8kj86.d@ee8g1
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 {
// § h36xkjqaa.a@2nwer
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);
// § szrkbrw70.a@jmzw3
let in_graph = match ptr.project.as_deref() {
// § szrkbrw70.b@8k8pe
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 => {
// § z0xqn70bp@1qxfg
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;
}
},
};
// § end szrkbrw70.a
let found = in_graph
.lookup(&ptr.name, &ptr.target)
.or_else(|| {
// § b73qzqyt9.b@ec0te
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 => {
// § mwneg21bd.a@jpe7z
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)
{
// § nth5nbchz@hvgad
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 => {
// § mwneg21bd.b@1pegf
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 => {
// § zrj8yeg6g.c@w6wxb
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 => {
// § wy8jqnvbm.a@7vpba
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(_) => {
// § nth5nbchz.b@9xv7x
*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()
}
}
/// Each draft address of the tree, with its text and, when `root` reads a history, its age: the
/// draft laws and the active clauses that are drafts, their own or their law's.
fn draft_lines(scan: &Scan, root: Option<&Path>) -> Vec<String> {
// § cd5y5pa34.b@a53zn
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 {
/// `None` for a law of the current project.
project: Option<String>,
id: String,
letter: Option<String>,
}
/// Where a marker sits, for the duties it pays.
#[derive(Debug, PartialEq, Eq)]
enum MarkerSurface {
Code,
Doc,
/// Markdown that is neither a decision note nor documentation.
Unread,
}
fn scan_provisional_references(root: &Path) -> Result<Vec<String>> {
// § fxas3vhge.e@vnk7q
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) {
// § z0xqn70bp@n0te3
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);
// A provisional reference in a manual is one `fix` mints wherever it sits, so only a
// string of code is no marker here.
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 {
!hash::is_provisional_id(&law.id) && !graph.retired.contains(&law.id)
}
fn check_duplicate_declaration_ids(scan: &Scan, graph: &Graph, errors: &mut Vec<String>) {
// § cmx8g7zp2.a@j7zdn
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;
/// The address, the location and the word count of each active clause and carrying sentence.
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>) {
// § wqhsnrn8a.h@5aj45
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>) {
// § jnxf0eakp.b@gfc7g
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>,
) {
// § cheh1xt61@k9njc
// § p9e62dtvr.c@ydz1y
let duty = Owed {
markers,
policy,
project: None,
};
// § end p9e62dtvr.c
// § xs2e8kj86.d@1zwms
for law in &scan.laws {
if hash::is_provisional_id(&law.id) || graph.retired.contains(&law.id) || law.struck {
continue;
}
// § wy8jqnvbm@f5ek9
if law.draft {
continue;
}
// § end wy8jqnvbm
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 {
// § wy8jqnvbm@ybzpc
for al in live_letters.into_iter().filter(|al| !al.draft) {
duty.code(&law.id, al.letter.as_deref(), &al.loc, errors);
}
// § end wy8jqnvbm
}
// § xs2e8kj86.j@2q71p
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);
}
// § end xs2e8kj86.j
}
// § end xs2e8kj86.d
// silcrow:follow
check_adoptions(scan, others, markers, policy, errors);
}
/// Each adopted clause owes the adopter a qualified marker, under the adopter's policy.
fn check_adoptions(
scan: &Scan,
others: &Others,
markers: &Markers,
policy: &ProjectPolicy,
errors: &mut Vec<String>,
) {
// § v8b14v6pn.b@tbhm5
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),
};
// § v8b14v6pn.c@xgwqc
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;
}
// § end v8b14v6pn.c
// § wy8jqnvbm.b@vq72y
if node.draft {
continue;
}
// § end wy8jqnvbm.b
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);
}
// § wy8jqnvbm.b@g59wy
let mut letters: Vec<&str> = live
.iter()
.filter(|n| !n.draft)
.filter_map(|n| n.letter.as_deref())
.collect();
// § end wy8jqnvbm.b
letters.sort();
for letter in letters {
duty.code(&adoption.id, Some(letter), &adoption.loc, errors);
}
}
}
/// The markers one project owes, for its own laws (`project` is `None`) or for one it adopted.
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,
}
}
/// The law or clause owes a marker in a file `code` matches.
fn code(&self, id: &str, letter: Option<&str>, loc: &Location, errors: &mut Vec<String>) {
// § z0xqn70bp@bah7x
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()
));
}
/// The law owes a marker of itself or of any of its clauses in a file `docs` matches, and an
/// adopted clause one of itself, when `docs` names any file.
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),
));
}
}
/// The marker forms the files the `docs` list matches take, each named with the extensions that
/// take it when they differ, or those of its patterns while it matches no file.
fn doc_marker_forms(doc_files: &[PathBuf], docs: &str, label: &str) -> String {
// § z0xqn70bp@n88g6
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 | crate::marker::Dialect::Jsx => {
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(", "))
}
}
}
/// Markers by surface: those that pay the code duty and those that pay the docs duty.
struct Markers {
code: HashSet<MarkerKey>,
doc: HashSet<MarkerKey>,
/// The first file of code, in path order, that holds a marker of each law, whatever `code`
/// matches, keyed as `MarkerKey` with no letter.
code_file: std::collections::HashMap<MarkerKey, PathBuf>,
/// The files the `docs` list matches, whose forms a missing documentation marker names.
doc_files: Vec<PathBuf>,
}
fn collect_marker_markers(
scan: &Scan,
notes: &walk::Notes,
policy: &ProjectPolicy,
graph: &Graph,
others: &Others,
errors: &mut Vec<String>,
) -> Markers {
// § xs2e8kj86.c@0kwdb
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,
}
}
/// A file `docs` matches is documentation whatever `code` says, and Markdown never pays the code
/// duty. A file neither list matches pays nothing.
fn marker_surface(
path: &Path,
notes: &walk::Notes,
policy: &ProjectPolicy,
) -> Option<MarkerSurface> {
// § xs2e8kj86.f@pw45w
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
}
}
}
/// The named changes of a comparing check grouped by the law each first names, its project tag
/// kept and its letter dropped, in the order the laws first appear. A change that names no law
/// is one of the block.
pub fn named_by_law(named: &[String]) -> Vec<(String, Vec<&String>)> {
// § j44p1s9z8.k@331vd
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
}
/// The steps that move a workspace from the scheme its history records to `binary`, or `None`
/// when it records none or this one. `several` adds `--all` where a workspace holds more than one
/// project.
pub fn scheme_steps(
recorded: Option<&scheme::Scheme>,
binary: &scheme::Scheme,
several: bool,
) -> Option<String> {
// § dfkjbzska.a@68qv5
let recorded = recorded.filter(|&recorded| recorded != binary)?;
// § dfkjbzska.f@g49cy
let moved = scheme::describe(&recorded.moved_all(binary));
let all = if several { " --all" } else { "" };
Some(format!(
"The history of HEAD records hashing scheme {recorded}, and this binary hashes with scheme {binary}: the scheme moved for {moved}, so a pin that reads a part that moved and held reads as drifted. Move to scheme {binary} in this order:\n 1. `silcrow fix --remint{all}` rewrites each pin that held under scheme {recorded} and reads a part that moved, and names every other such pin.\n 2. Commit that change alone, before any other edit.\n 3. Read each drift left with `silcrow diff --law <address>`, then accept them all in one call, `silcrow accept <address> <address>...`, or with `silcrow accept --drifted{all}` once every drift is read.\n\n"
))
// § end dfkjbzska.f
}
/// The steps for a workspace whose history records no scheme while more pins drift than hold,
/// as a scheme change leaves them.
pub fn unrecorded_scheme_steps(several: bool) -> String {
// § dfkjbzska.e@ggmjx
let all = if several { " --all" } else { "" };
format!(
"No commit in the history of HEAD records a hashing scheme, as the hooks do with `Silcrow-Scheme`, and more pins drift than hold, as a scheme change leaves them, so another release may have pinned this project. To move it to this binary's scheme:\n 1. `silcrow fix --remint{all}` rewrites each pin nothing it reads moved since the commit that wrote its digest, and names every other.\n 2. Commit that change alone, before any other edit.\n 3. Read each drift left with `silcrow diff --law <address>`, then accept them all in one call, `silcrow accept <address> <address>...`.\n\n"
)
}
/// Whether the repository at `root` has a commit.
pub fn has_history(root: &Path) -> bool {
crate::workspace::git(root)
.args(["rev-parse", "--verify", "-q", "HEAD"])
.output()
.is_ok_and(|out| out.status.success())
}
/// The summary a comparing check prints above its packet: how many changes it names, counted per
/// law.
pub fn named_summary(named: &[String]) -> String {
// § j44p1s9z8.k@g3861
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()
)
}
/// Prints the report and answers whether the graph is closed. `verbose` adds the scan count,
/// every resolved reference, and every absent optional marker.
pub fn print_report(
report: &CheckReport,
verbose: bool,
filter: Option<&str>,
warned: bool,
owned: &Owned,
) -> bool {
// § cd5y5pa34.a@fc8yd
if verbose {
println!("Scanning {} files...\n", report.files);
for (name, count) in &report.ok {
println!(" OK {name:<18} {count} pointer(s) resolved");
}
}
// § pga7yfvm9.e@j8sfq
let (err_tag, err_count) = match warned {
true => ("WRN", 0),
false => (
"ERR",
report.errors.len() + report.harness.len() + report.drifts.len(),
),
};
// § end pga7yfvm9.e
let findings: Vec<(&str, &String)> = report
.errors
.iter()
.chain(&report.harness)
.chain(&report.drifts)
.map(|err| (err_tag, err))
.chain(report.warnings.iter().map(|warn| ("WRN", warn)))
.collect();
// § j7vy53sbp@798gp
match owned {
Owned::By { point, own } => {
let (mine, before): (Vec<_>, Vec<_>) =
findings.iter().partition(|(_, text)| own.contains(*text));
for (tag, text) in &mine {
println!(" {tag} {text}");
}
if !before.is_empty() {
if !mine.is_empty() {
println!();
}
println!("Already there at {point}, in files this change left as they were:");
for (tag, text) in &before {
println!(" {tag} {text}");
}
}
}
Owned::Unread(why) if !findings.is_empty() => {
println!("Findings not grouped by change: {why}.");
for (tag, text) in &findings {
println!(" {tag} {text}");
}
}
_ => {
for (tag, text) in &findings {
println!(" {tag} {text}");
}
}
}
// § end j7vy53sbp
let yours = |text: &String| match owned {
Owned::By { own, .. } => own.contains(text),
_ => true,
};
let drifted = report.errors.iter().chain(&report.drifts);
let accepts = one_accept_lines(drifted.filter(|d| yours(d)), &report.pins);
if !accepts.is_empty() {
println!();
for line in accepts {
println!("{line}");
}
}
// § cd5y5pa34.b@esgsb
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)"),
};
// § end cd5y5pa34.b
// § j44p1s9z8@jeaff
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"),
};
// § end j44p1s9z8
let verified = match report.doc_verified {
0 => String::new(),
n => format!(", doc {n} verified"),
};
let counts = format!(
"{} reference(s) resolved, {err_count} error(s), {} warning(s){drafts}{named}{verified}.",
report.ok.len(),
report.errors.len() + report.harness.len() + report.drifts.len() + report.warnings.len()
- err_count,
);
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();
// § awnw08yp4.b@mxyb9
let filtered = filter.map_or(String::new(), |filter| {
format!(" Filtered by `{filter}`: a finding outside it is neither printed, counted nor failed on.")
});
// § end awnw08yp4.b
match (closed, warned) {
(true, _) => println!("✓ Graph is closed. {counts}{filtered}"),
(false, false) => println!("✗ Graph is broken. {counts}{filtered}"),
(false, true) => {
println!("✗ Graph is broken, each error reported as a warning. {counts}{filtered}")
}
}
closed
}
/// The first address a finding names after `§`: a minted id or a provisional name, with its
/// project qualifier and its letter.
static ADDRESS_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"§ ((?:[^\s:§`]+:)?(?:\+[a-z0-9-]+|[0-9a-hjkmnp-tv-z]{9})(?:\.[a-z]+)?)")
.expect("finding address regex")
});
/// What moved under a drifted pin, as its message names it.
static CAUSE_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"changed since its pin @\w*: (.+?) since the last commit that held this pin\.")
.expect("drift cause regex")
});
static LOCATION_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^(?:\[(?P<project>[^\]]+)\] )?(?:(?P<path>[^:\n]+?):(?P<line>\d+):|(?P<file>[^\s:]+):\s)?")
.expect("finding location regex")
});
/// Where a finding points, read from the line it prints: the project its tag names, and the
/// file and line it opens with.
#[derive(Debug, PartialEq, Eq)]
pub struct Located<'a> {
pub project: Option<&'a str>,
pub path: Option<&'a str>,
pub line: Option<usize>,
}
pub fn locate(text: &str) -> Located<'_> {
let Some(caps) = LOCATION_RE.captures(text) else {
return Located {
project: None,
path: None,
line: None,
};
};
Located {
project: caps.name("project").map(|m| m.as_str()),
path: caps.name("path").or(caps.name("file")).map(|m| m.as_str()),
line: caps.name("line").and_then(|m| m.as_str().parse().ok()),
}
}
/// What a filtered `check` keeps: the findings in one of `paths`, absolute.
pub struct Filter {
pub paths: Vec<PathBuf>,
/// The flags as given, which the summary line names.
pub label: String,
}
impl Filter {
/// Whether the finding `text` is kept, a path it names read from the directory of its
/// project, or from `untagged` when it names none. `reads` are the files a drift reads.
fn keeps(&self, ws: &Workspace, untagged: &Path, text: &str, reads: &[PathBuf]) -> bool {
// § awnw08yp4@mqws3
let at = locate(text);
// § awnw08yp4.c@25jdr
located_file(ws, untagged, &at).is_some_and(|path| self.paths.contains(&path))
|| reads.iter().any(|read| self.paths.contains(read))
// § end awnw08yp4.c
}
}
/// The absolute path of the file a finding names, read from the directory of its project, or
/// from `untagged` when it names none.
fn located_file(ws: &Workspace, untagged: &Path, at: &Located<'_>) -> Option<PathBuf> {
let dir = match at.project {
Some(key) => ws.get(key)?.dir.as_path(),
None => untagged,
};
at.path.map(|path| normalize(&dir.join(path)))
}
/// Which findings a change owns, read against its fork point with the default branch.
pub enum Owned {
/// No grouping: the hooks print one list.
Off,
/// The point the change is read against, as the heading names it, and the text of each
/// finding of the change.
By {
point: String,
own: BTreeSet<String>,
},
/// Why no fork point was read.
Unread(String),
}
/// The point a change is read against: the comparison point of a comparing check, else the
/// fork point of `HEAD` with the default branch, with how a heading names it. `Err` says why
/// none was read.
pub fn fork_point(
ws: &Workspace,
compared: Option<&str>,
) -> std::result::Result<(String, String), String> {
// § j7vy53sbp.b@fe5t1
if let Some(point) = compared {
return Ok((
point.to_string(),
format!("the comparison point {}", crate::published::short(point)),
));
}
match ws.base_ref("HEAD") {
Ok(Some(base)) => {
let label = format!(
"the fork point with the default branch, {}",
crate::published::short(&base)
);
Ok((base, label))
}
Ok(None) => Err("no commit holds a fork point yet".to_string()),
Err(e) => Err(format!("{e:#}")),
}
}
/// The absolute paths of the files changed since `base`, in a commit, the index or the worktree,
/// untracked files included.
fn changed_since(root: &Path, base: &str) -> std::result::Result<BTreeSet<PathBuf>, String> {
// § j7vy53sbp.a@mxpjp
let lines = |args: &[&str]| -> std::result::Result<Vec<String>, String> {
let out = crate::workspace::git(root)
.args(args)
.output()
.map_err(|e| format!("git {}: {e}", args.join(" ")))?;
if !out.status.success() {
return Err(format!(
"git {} failed: {}",
args.join(" "),
String::from_utf8_lossy(&out.stderr).trim()
));
}
Ok(String::from_utf8_lossy(&out.stdout)
.lines()
.filter(|line| !line.is_empty())
.map(str::to_string)
.collect())
};
let mut changed = lines(&["diff", "--name-only", "--no-renames", "-z", base])?;
changed.extend(lines(&[
"ls-files",
"--others",
"--exclude-standard",
"-z",
])?);
Ok(changed
.iter()
.flat_map(|line| line.split('\0'))
.filter(|path| !path.is_empty())
.map(|path| normalize(&root.join(path)))
.collect())
}
/// The files added or deleted since `base`, renames counting as both, the untracked files, and
/// each `AGENTS.md` edited since then, as absolute paths.
fn structure_changes(root: &Path, base: &str) -> Result<Vec<PathBuf>> {
let lines = |args: &[&str]| -> Result<Vec<String>> {
let out = crate::workspace::git(root).args(args).output()?;
if !out.status.success() {
anyhow::bail!(
"git {}: {}",
args.join(" "),
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&out.stdout)
.lines()
.map(str::to_string)
.collect())
};
let mut paths: Vec<PathBuf> = Vec::new();
for line in lines(&["diff", "--name-status", "--no-renames", base])? {
let Some((status, path)) = line.split_once('\t') else {
continue;
};
let block = path == "AGENTS.md" || path.ends_with("/AGENTS.md");
if matches!(status, "A" | "D") || block {
paths.push(normalize(&root.join(path)));
}
}
for path in lines(&["ls-files", "--others", "--exclude-standard"])? {
paths.push(normalize(&root.join(path)));
}
Ok(paths)
}
/// Each pin of `pins` that held at `base`: its digest there is the one it carries now, and the
/// tree at `base` hashes to it.
fn held_at(ws: &Workspace, base: &str, pins: &[(&String, &DriftPin)]) -> Result<BTreeSet<String>> {
let tree = tempfile::tempdir()?;
crate::published::write_tree(&ws.root, base, tree.path())?;
let then_ws = Workspace::at(tree.path().to_path_buf())?;
let mut by_dir: BTreeMap<&Path, Vec<(&String, &DriftPin)>> = BTreeMap::new();
for &(text, pin) in pins {
by_dir
.entry(pin.dir.as_path())
.or_default()
.push((text, pin));
}
let mut held = BTreeSet::new();
for (dir, pins) in by_dir {
let Some(project) = ws.local().into_iter().find(|p| p.dir == dir) else {
continue;
};
let then_root = tree.path().join(dir.strip_prefix(&ws.root)?);
if !then_root.join("AGENTS.md").exists() {
continue;
}
let mut scans = ws.law_scans(&project.key)?;
for (key, scan) in then_ws.law_scans(&project.key)?.scans {
scans.scans.insert(key, scan);
}
let scan = scan_root(&then_root)?;
let tokens = span::TreeTokens::new(&then_root, span::PinTexts::for_project(&scan, &scans))?;
for (text, pin) in pins {
let Ok(source) = std::fs::read_to_string(then_root.join(&pin.rel)) else {
continue;
};
let then = tokens.tokens(&pin.rel, &source);
let holds = source.lines().enumerate().any(|(idx, line)| {
crate::marker::markers_in_line(line).into_iter().any(|m| {
m.split_digest().is_some_and(|(addr, digest)| {
addr.display() == pin.addr
&& digest == pin.digest
&& then.get(&(idx, pin.addr.clone())) == Some(&digest)
})
})
});
if holds {
held.insert((*text).clone());
}
}
}
Ok(held)
}
/// Fills the structural drifts of `report`: those that read no file changed since the fork
/// point and held there, when the change added, deleted or renamed a file or edited a block.
pub fn read_structure(
ws: &Workspace,
fork: &std::result::Result<(String, String), String>,
untagged: &Path,
report: &mut CheckReport,
) {
// § j7vy53sbp.e@pfwz9
let Ok((base, _)) = fork else {
return;
};
let (Ok(paths), Ok(changed)) = (
structure_changes(&ws.root, base),
changed_since(&ws.root, base),
) else {
return;
};
if paths.is_empty() {
return;
}
let candidates: Vec<(&String, &DriftPin)> = report
.drifts
.iter()
.filter(|text| {
let named = located_file(ws, untagged, &locate(text));
!named.is_none_or(|path| changed.contains(&path))
&& !report
.reads
.get(*text)
.is_some_and(|read| read.iter().any(|path| changed.contains(&normalize(path))))
})
.filter_map(|text| report.pins.get(text).map(|pin| (text, pin)))
.collect();
if candidates.is_empty() {
return;
}
// A tree that cannot be read at the fork point leaves the drifts as they read.
if let Ok(held) = held_at(ws, base, &candidates) {
report.structural = held;
report.structure_paths = paths;
}
}
/// Which findings of `report` its change owns: one that names a file changed since the fork
/// point, a drift that reads one, or a drift the change's added, deleted or renamed files or
/// edited block moved.
pub fn owned(
ws: &Workspace,
fork: &std::result::Result<(String, String), String>,
untagged: &Path,
report: &CheckReport,
) -> Owned {
// § j7vy53sbp@tgbft
let changed = fork
.clone()
.and_then(|(base, label)| Ok((changed_since(&ws.root, &base)?, label)));
let (changed, point) = match changed {
Ok(found) => found,
Err(why) => return Owned::Unread(why),
};
let own = report
.errors
.iter()
.chain(&report.harness)
.chain(&report.drifts)
.chain(&report.warnings)
.chain(&report.drafts)
.chain(&report.named)
.filter(|text| {
let named = located_file(ws, untagged, &locate(text));
named.is_none_or(|path| changed.contains(&path))
|| report.structural.contains(*text)
|| report
.reads
.get(*text)
.is_some_and(|read| read.iter().any(|path| changed.contains(&normalize(path))))
})
.cloned()
.collect();
Owned::By { point, own }
}
/// `path` with each `.` and `..` segment resolved by its text, as a path that may no longer
/// exist reads.
pub fn normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for part in path.components() {
match part {
std::path::Component::CurDir => {}
std::path::Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
impl CheckReport {
/// Drops every finding `filter` does not keep.
pub fn keep(&mut self, filter: &Filter, ws: &Workspace, untagged: &Path) {
// § awnw08yp4.b@kehx6
let reads = &self.reads;
let (structural, structure) = (&self.structural, &self.structure_paths);
for list in [
&mut self.errors,
&mut self.drifts,
&mut self.harness,
&mut self.warnings,
&mut self.drafts,
&mut self.named,
] {
list.retain(|text| {
let mut read = reads.get(text).cloned().unwrap_or_default();
if structural.contains(text) {
read.extend(structure.iter().cloned());
}
filter.keeps(ws, untagged, text, &read)
});
}
}
}
/// Prints the report as one JSON object and answers whether the graph is closed. A finding
/// with no project tag is of `untagged`, the one project checked, or of none.
pub fn print_json(
report: &CheckReport,
filter: Option<&str>,
untagged: Option<&str>,
owned: &Owned,
) -> Result<bool> {
// § gbcb9abtz@05g4x
let finding = |kind: &str, text: &String| {
let at = locate(text);
// § j7vy53sbp.c@2m5s0
let own = match owned {
Owned::By { own, .. } => Some(own.contains(text)),
Owned::Off | Owned::Unread(_) => None,
};
// § end j7vy53sbp.c
let capture = |re: &Regex| re.captures(text).map(|caps| caps[1].to_string());
serde_json::json!({
"kind": kind,
"project": at.project.or(untagged),
"path": at.path,
"line": at.line,
"address": capture(&ADDRESS_RE),
"cause": capture(&CAUSE_RE),
"text": text,
"own": own,
})
};
// § gbcb9abtz.a@pgv11
let findings: Vec<serde_json::Value> = report
.errors
.iter()
.chain(&report.harness)
.chain(&report.drifts)
.map(|text| finding("error", text))
.chain(report.warnings.iter().map(|text| finding("warning", text)))
.chain(report.drafts.iter().map(|text| finding("draft", text)))
.chain(report.named.iter().map(|text| finding("named", text)))
.collect();
// § end gbcb9abtz.a
let closed = report.is_closed();
// § gbcb9abtz.c@fyqr6
let object = serde_json::json!({
"closed": closed,
"filter": filter,
"counts": {
"resolved": report.ok.len(),
"errors": report.errors.len() + report.harness.len() + report.drifts.len(),
"warnings": report.warnings.len(),
"drafts": report.drafts.len(),
"named": report.named.len(),
},
"findings": findings,
});
println!("{}", serde_json::to_string(&object)?);
// § end gbcb9abtz.c
Ok(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 a_finding_is_located_by_its_tag_file_and_line() {
let at = |text| {
let at = locate(text);
(at.project, at.path, at.line)
};
assert_eq!(
at("[lib/a] src/my file.rs:12: § abcdefgh1 changed"),
(Some("lib/a"), Some("src/my file.rs"), Some(12))
);
assert_eq!(
at("docs/r.md:5: (since 2026-11-01, 3 days) § bcdefghj2"),
(None, Some("docs/r.md"), Some(5))
);
assert_eq!(
at("AGENTS.md: the Silcrow block omits `code`"),
(None, Some("AGENTS.md"), None)
);
assert_eq!(
at("duplicate id abcdefgh1: first at a.md:1, also at b.md:2"),
(None, None, None)
);
assert_eq!(
at("[.] /tmp/x/AGENTS.md differs from this binary. Run `silcrow install`."),
(Some("."), None, None)
);
}
#[test]
fn scheme_steps_name_the_remint_its_commit_and_the_reading_in_order() {
let s = |value: &str| scheme::Scheme::parse(value).unwrap();
let (old, now) = (s("24"), s("25"));
assert_eq!(scheme_steps(None, &now, false), None);
assert_eq!(scheme_steps(Some(&now), &now, true), None);
let one = scheme_steps(Some(&old), &now, false).unwrap();
assert!(
one.contains("the scheme moved for every part from 24 to 25,"),
"{one}"
);
let remint = one.find("`silcrow fix --remint` rewrites").unwrap();
let commit = one.find("Commit that change alone").unwrap();
let read = one.find("`silcrow diff --law <address>`").unwrap();
assert!(remint < commit && commit < read, "{one}");
assert!(!one.contains("--all"), "{one}");
let parts = scheme_steps(Some(&s("25 md=24 yaml=23")), &s("25 yaml=26"), false).unwrap();
assert!(
parts.starts_with("The history of HEAD records hashing scheme 25 md=24 yaml=23, and this binary hashes with scheme 25 yaml=26: the scheme moved for md from 24 to 25 and yaml from 23 to 26,"),
"{parts}"
);
let several = scheme_steps(Some(&old), &now, true).unwrap();
assert!(
several.contains("`silcrow fix --remint --all`"),
"{several}"
);
assert!(
several.contains("`silcrow accept --drifted --all`"),
"{several}"
);
}
#[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).reported();
assert_eq!(checked.len(), 1, "{checked:?}");
assert!(checked[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]);
// A fallback file reads its strings as the fallback does: a wrapper inside one is a
// value, and a comment after code still fails.
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(),
)
}
/// `check_landed` of the law written as a public promise.
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
);
}
/// The hint names the form of each file the list matches, so a list of Markdown and MDX
/// pages names both, and a list that matches no file yet names the form of its patterns.
#[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:?}");
}
}
/// A `mod tests;` under `#[cfg(test)]` loads `tests.rs` or `tests/mod.rs` as Rust does, beside
/// a `mod.rs`, `lib.rs` or `main.rs` and under the directory of any other file's stem.
#[test]
fn a_file_a_test_gated_module_loads_without_a_path_is_test_code() {
let file = |path: &str, text: &str| span::CodeFile::new(PathBuf::from(path), text.into());
let test_fn = "#[test]\nfn t() {\n // § x\n}\n";
let files = [
file(
"src/kcl/mod.rs",
"pub fn f() {}\n\n#[cfg(test)]\nmod tests;\n",
),
file("src/kcl/tests.rs", test_fn),
file(
"src/svid.rs",
"pub fn g() {}\n#[cfg(test)]\nmod tests;\nmod plain;\n",
),
file("src/svid/tests/mod.rs", "mod deep;\n"),
file("src/svid/tests/deep.rs", test_fn),
file("src/svid/plain.rs", "pub fn h() {}\n"),
];
let rows = span::test_rows(&files);
for (path, test) in [
("src/kcl/tests.rs", true),
("src/svid/tests/mod.rs", true),
("src/svid/tests/deep.rs", true),
("src/svid/plain.rs", false),
] {
assert_eq!(rows.contains_key(Path::new(path)), test, "{path}: {rows:?}");
}
}
#[test]
fn a_test_function_is_test_code_wherever_it_sits() {
let rows = |text: &str| {
span::CodeFile::new(PathBuf::from("src/lib.rs"), text.to_string()).cfg_test_rows()
};
for attr in [
"#[test]",
"#[tokio::test]",
"#[tokio::test(flavor = \"multi_thread\")]",
] {
let text = format!("pub fn f() {{}}\n\n{attr}\nfn t() {{\n f();\n}}\n");
assert_eq!(rows(&text), vec![(2, 5)], "{attr}");
}
assert!(rows("#[inline]\nfn f() {}\n#[testing]\nfn g() {}\n").is_empty());
}
#[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}");
}
}
}