use anyhow::{bail, Context, Result};
use regex::Regex;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
use std::sync::LazyLock;
use crate::hash;
use crate::marker::{DIGEST, ID, PROJECTPATH};
use crate::parse;
use crate::walk;
use crate::workspace::{self, LawScans, ProjectRef, Workspace};
use crate::write::{self, WritePlan};
static QREF_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!(
r"(ยง\s*(?:end\s+)?|\[(?:ยง\s*)?)({PROJECTPATH}):({ID})\b"
))
.expect("qualified reference")
});
static UREF_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!(r"(ยง\s*(?:end\s+)?|\[(?:ยง\s*)?)({ID})\b(:?)"))
.expect("unqualified reference")
});
static QREF_ONE_RE: LazyLock<Regex> = LazyLock::new(|| on_one_line(&QREF_RE));
static UREF_ONE_RE: LazyLock<Regex> = LazyLock::new(|| on_one_line(&UREF_RE));
fn on_one_line(re: &Regex) -> Regex {
let lead = r"ยง\s*(?:end\s+)?|";
assert!(
re.as_str().contains(lead),
"a pointer regex opens with a marker lead"
);
Regex::new(
&re.as_str()
.replacen(lead, r"ยง\s*(?:end\s+|one\s+)?|,\s*|", 1),
)
.expect("one-line pointer regex")
}
static QCITE_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!(r"^(?:ยง\s*)?({PROJECTPATH}):({ID})")).expect("qualified cite text")
});
static ADOPT_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!(
r"^\s*\*\*ยง\s*{PROJECTPATH}:{ID}(?:\.[a-z]+)?\*\*\s*$"
))
.expect("adoption line")
});
pub struct Around<'a> {
pub own: &'a str,
pub own_ids: BTreeSet<String>,
pub others: BTreeMap<String, BTreeMap<String, PathBuf>>,
}
impl<'a> Around<'a> {
fn new(own: &'a str, scan: &parse::Scan, scans: &LawScans) -> Self {
Self {
own,
own_ids: scan
.laws
.iter()
.flat_map(|law| std::iter::once(&law.id).chain(&law.aliases))
.cloned()
.collect(),
others: scans
.scans
.iter()
.map(|(key, scan)| {
let ids = scan
.laws
.iter()
.map(|law| (law.id.clone(), law.loc.path.clone()))
.collect();
(key.clone(), ids)
})
.collect(),
}
}
fn declaring(&self, id: &str) -> Vec<&str> {
let mut projects: Vec<&str> = self
.others
.iter()
.filter(|(_, ids)| ids.contains_key(id))
.map(|(key, _)| key.as_str())
.collect();
if self.own_ids.contains(id) {
projects.push(self.own);
}
projects.sort();
projects
}
}
static CITE_LINK_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!(
r"\[([^\]]*)\]\(([^)#]*)(#({ID})(?:\.([a-z]+))?(?:@{DIGEST})?)\)"
))
.expect("cite link regex")
});
static BARE_ID_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(&format!(r"\b({ID})((?:\.[a-z]+)?)\b")).expect("bare id"));
static NOT_BARE_RES: LazyLock<Vec<Regex>> = LazyLock::new(|| {
[
r"`[^`]*`",
r"\[[^\]]*\]\([^)]*\)",
r"<a\s[^>]*>[^<]*</a>",
r"<[^>]+>",
r"ยง\s*\S+",
]
.iter()
.map(|re| Regex::new(re).expect("not bare"))
.collect()
});
static HEAD_PREFIX_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!(
r#"^\s*\*\*ยง!?\??\s*(?:<a\s+id="{ID}">{ID}</a>|{ID}\b)(?:<a\s+id="{ID}"></a>)*"#
))
.expect("head prefix regex")
});
static HEAD_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!(
r#"^\s*\*\*ยง!?\??\s*(?:<a\s+id="({ID})">|(\+[a-z0-9-]+)|({ID})\b)"#
))
.expect("law head")
});
static PROVISIONAL_CLAUSE_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^(\s*(?:[-*+]\s+|\d+\.\s+)?)\(\+\)(\??)(\s+)").expect("provisional clause")
});
static PROVISIONAL_ROW_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^(\s*\|\s*)\(\+\)(\s+)").expect("provisional row"));
static LETTERED_ROW_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*\|\s*\((?:[a-z]+|\+)\)(?:\s|$)").expect("lettered row"));
static LETTERED_ITEM_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*- \([a-z]+\)\??(?:\s|$)").expect("lettered item"));
static SECTION_BREAK_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^##\s+").expect("section break"));
pub struct ResolvePlan {
pub writes: WritePlan,
pub actions: Vec<String>,
pub warnings: Vec<String>,
}
pub fn plan(ws: &Workspace, project: &ProjectRef, scheme_remint: bool) -> Result<ResolvePlan> {
if scheme_remint {
return plan_scheme_remint(&project.dir, ws.base_ref("HEAD")?.as_deref());
}
plan_scoped(ws, project, None)
}
pub fn plan_scoped(
ws: &Workspace,
project: &ProjectRef,
staged_only: Option<&[PathBuf]>,
) -> Result<ResolvePlan> {
let mut actions = Vec::new();
let mut warnings = Vec::new();
let mut name_to_id: BTreeMap<String, String> = BTreeMap::new();
let root = project.dir.as_path();
let scan = parse::scan_root(root)?;
let scans = ws.law_scans(&project.key)?;
let around = Around::new(&project.key, &scan, &scans);
let mut id_owners: BTreeMap<String, String> = BTreeMap::new();
for law in &scan.laws {
if hash::is_provisional_id(&law.id) {
continue;
}
if let Some(first) = id_owners.get(&law.id) {
bail!(
"duplicate id {}: first at {}, also at {}:{}",
law.id,
first,
law.loc.path.display(),
law.loc.line
);
}
id_owners.insert(
law.id.clone(),
format!("{}:{}", law.loc.path.display(), law.loc.line),
);
if !hash::verify_id(&law.name, &law.id) {
warnings.push(format!(
"HASH {} at {}:{} does not match its carrying sentence (use accept)",
law.id,
law.loc.path.display(),
law.loc.line
));
}
}
let aliases = alias_pointer_re(&scan)?;
let one_line = aliases.as_ref().map(|(re, _)| on_one_line(re));
let scope: Vec<PathBuf> = decision_paths_for_scope(root, staged_only)?
.into_iter()
.map(|p| p.strip_prefix(root).unwrap_or(&p).to_path_buf())
.collect();
let declared_paths = build_id_to_path(&scan, &BTreeMap::new());
let mut name_heads: BTreeMap<&str, String> = BTreeMap::new();
for law in &scan.laws {
let Some(name) = law.id.strip_prefix('+') else {
continue;
};
if !scope.contains(&law.loc.path) {
continue;
}
let here = format!("{}:{}", law.loc.path.display(), law.loc.line);
if let Some(first) = name_heads.get(name) {
bail!(
"{here}: ยง +{name} is also the provisional name of the head at {first}: a name is unique within the change. Rename one of the two."
);
}
name_heads.insert(name, here.clone());
let carrying = link_bare_ids(
¤t_ids(&law.name.replace(&format!("ยง +{name}"), ""), &aliases),
&law.loc.path,
&declared_paths,
&BTreeSet::new(),
);
if hash::canonicalise(&carrying).is_empty() {
bail!(
"{}:{}: provisional ยง +{name} has no carrying sentence",
law.loc.path.display(),
law.loc.line
);
}
let id = hash::mint_id(&carrying);
if let Some(first) = id_owners.get(&id) {
bail!(
"{here}: ยง +{name} mints {id}, which the law at {first} already carries: a duplicate id is refused. Reword one of the two carrying sentences."
);
}
id_owners.insert(id.clone(), here);
actions.push(format!("MINT +{name} -> {id}"));
name_to_id.insert(name.to_string(), id);
}
refuse_taken_ids(ws, root, &scan, &name_to_id)?;
let id_to_path = build_id_to_path(&scan, &name_to_id);
let mut letters = letters_per_law(&scan, &name_to_id);
if has_provisional_clause(root)? {
burn_published_letters(ws, root, &scan, &mut letters)?;
}
let paths = collect_rewrite_paths(root)?;
let paths_of = walk::Project::at(root)?;
let implemented = named_drafts(&scan, &project.key);
let mut writes = Vec::new();
let bodies = crate::par::map_many(paths.iter().collect(), |rel| {
let body = std::fs::read_to_string(root.join(rel)).ok()?;
crate::cache::preload(rel, &body);
Some(body)
});
for (rel, body) in paths.iter().zip(bodies) {
let Some(body) = body else {
continue;
};
let note = paths_of.is_note(rel);
let drafted = match implemented.get(rel).filter(|_| note && scope.contains(rel)) {
Some(lines) => implement_drafts(&body, lines, &mut actions),
None => body.clone(),
};
let (mut next, file_actions) = rewrite_file(
rel,
note,
&drafted,
&name_to_id,
&id_to_path,
&mut letters,
&around,
)?;
if let (Some((re, current)), Some(one)) = (&aliases, &one_line) {
let minted: BTreeSet<&String> = name_to_id.values().collect();
let mut lines = Vec::new();
for (idx, line) in next.split('\n').enumerate() {
let re = match crate::marker::opens_one(line) {
true => one,
false => re,
};
let head = HEAD_RE
.captures(line)
.and_then(|c| c.get(1).or(c.get(3)))
.map(|m| m.as_str().to_string())
.filter(|id| !minted.contains(id));
if let (Some(id), Some(caps)) = (&head, re.captures(line)) {
warnings.push(format!(
"ALIAS {}:{}: the carrying sentence of ยง {id} cites {}, an alias of ยง {}. Rewriting it would remint ยง {id}: edit the cite, then run `silcrow accept {id}`.",
rel.display(),
idx + 1,
&caps[2],
current[&caps[2]]
));
lines.push(line.to_string());
continue;
}
let rewritten = re.replace_all(line, |caps: ®ex::Captures| {
let id = ¤t[&caps[2]];
actions.push(format!("CURRENT {} -> {id} in {}", &caps[2], rel.display()));
format!("{}{id}", &caps[1])
});
lines.push(rewritten.into_owned());
}
next = lines.join("\n");
}
actions.extend(file_actions);
if next != body {
writes.push((rel.clone(), next));
warnings.push(format!("REWRITE {}", rel.display()));
}
}
let lettered = |err: &parse::FormError| {
parse::names_provisional_letter(&err.message)
&& writes
.iter()
.find(|(rel, _)| *rel == err.loc.path)
.is_some_and(|(_, next)| {
next.split('\n').nth(err.loc.line - 1).is_some_and(|line| {
!PROVISIONAL_CLAUSE_RE.is_match(line) && !PROVISIONAL_ROW_RE.is_match(line)
})
})
};
let form: Vec<String> = scan
.form_errors
.iter()
.filter(|err| !lettered(err))
.map(|err| {
format!(
"FORM {}:{}: {}",
err.loc.path.display(),
err.loc.line,
err.message
)
})
.collect();
warnings.splice(0..0, form);
Ok(ResolvePlan {
writes: WritePlan { writes },
actions,
warnings,
})
}
type DraftLines = BTreeMap<PathBuf, BTreeMap<usize, (bool, String)>>;
fn named_drafts(scan: &parse::Scan, own: &str) -> DraftLines {
let aliases: BTreeMap<&str, &str> = scan
.laws
.iter()
.flat_map(|law| law.aliases.iter().map(|a| (a.as_str(), law.id.as_str())))
.collect();
let named: BTreeSet<(&str, Option<&str>)> = scan
.pointers
.iter()
.filter(|p| p.kind == parse::PointerKind::Implements)
.filter(|p| p.project.as_deref().is_none_or(|key| key == own))
.filter_map(|p| match &p.target {
parse::Target::Stable { id, letter } => Some((
aliases.get(id.as_str()).copied().unwrap_or(id.as_str()),
letter.as_deref(),
)),
parse::Target::Display { .. } => None,
})
.collect();
let mut out = DraftLines::new();
for law in scan.laws.iter().filter(|law| !law.struck) {
let clauses: Vec<(&parse::Clause, &str, bool)> = law
.clauses
.iter()
.filter(|c| !c.struck)
.filter_map(|c| {
let letter = c.letter.as_deref()?;
Some((c, letter, named.contains(&(law.id.as_str(), Some(letter)))))
})
.collect();
let lines = out.entry(law.loc.path.clone()).or_default();
if law.draft {
if !named.contains(&(law.id.as_str(), None)) && !clauses.iter().any(|c| c.2) {
continue;
}
lines.insert(law.loc.line, (false, law.id.clone()));
}
for (clause, letter, named) in clauses {
if clause.draft && (named || law.draft) {
lines.insert(clause.loc.line, (!named, format!("{}.{letter}", law.id)));
}
}
}
out
}
fn implement_drafts(
body: &str,
lines: &BTreeMap<usize, (bool, String)>,
actions: &mut Vec<String>,
) -> String {
let mut out: Vec<String> = Vec::new();
for (idx, line) in body.split('\n').enumerate() {
let next = match (lines.get(&(idx + 1)), parse::undraft(line)) {
(Some((false, address)), Some(plain)) => {
actions.push(format!("IMPLEMENT {address}"));
plain
}
(Some((true, address)), None) => {
actions.push(format!("DRAFT {address}"));
parse::redraft(line)
}
_ => line.to_string(),
};
out.push(next);
}
out.join("\n")
}
fn refuse_taken_ids(
ws: &Workspace,
root: &Path,
scan: &parse::Scan,
name_to_id: &BTreeMap<String, String>,
) -> Result<()> {
let keepers: BTreeMap<&String, &parse::Law> = scan
.laws
.iter()
.flat_map(|law| law.aliases.iter().map(move |alias| (alias, law)))
.collect();
let taken: Vec<String> = name_to_id
.iter()
.filter_map(|(name, id)| {
let keeper = keepers.get(id)?;
Some(format!(
"ยง +{name} mints {id}, an alias anchor of ยง {} at {}:{}",
keeper.id,
keeper.loc.path.display(),
keeper.loc.line
))
})
.collect();
if !taken.is_empty() {
bail!(
"{}: an alias anchor is a taken id, and a marker or a cite of it resolves to the law that keeps it. Reword the carrying sentence.",
taken.join(", ")
);
}
let minted: BTreeSet<String> = name_to_id.values().cloned().collect();
let declared: BTreeSet<String> = scan
.laws
.iter()
.map(|law| law.id.clone())
.filter(|id| !hash::is_provisional_id(id))
.collect();
let frozen = ws.frozen(root, &minted.union(&declared).cloned().collect())?;
if !frozen.is_empty() {
let mut named: Vec<String> = name_to_id
.iter()
.filter(|(_, id)| frozen.contains(*id))
.map(|(name, id)| format!("ยง +{name} mints {id}"))
.collect();
named.extend(
scan.laws
.iter()
.filter(|law| frozen.contains(&law.id))
.map(|law| {
format!(
"{}:{}: ยง {} is declared",
law.loc.path.display(),
law.loc.line,
law.id
)
}),
);
bail!(
"{}: a removed law carried that id in the published history, and an id never comes back with another meaning. Reword the carrying sentence.",
named.join(", ")
);
}
Ok(())
}
fn rewrite_file(
rel: &Path,
anchor: bool,
body: &str,
name_to_id: &BTreeMap<String, String>,
id_to_path: &BTreeMap<String, PathBuf>,
letters: &mut BTreeMap<String, BTreeSet<String>>,
around: &Around<'_>,
) -> Result<(String, Vec<String>)> {
let mut actions = Vec::new();
let body = if anchor {
body.to_string()
} else {
crate::cache::memo(rel, body, &"canonical pointers", || {
parse::canonical_pointers(crate::marker::is_markdown(rel), body)
})
};
let (mut next, qualifier_actions) = repair_qualifiers(rel, &body, around)?;
actions.extend(qualifier_actions);
let mut cites = Vec::new();
for (name, id) in name_to_id {
let cite = Regex::new(&format!(
r"\[(ยง\s*)?\+{name}((?:\.[a-z]+)?)\]\(([^)#]*)#\+?{name}\)",
name = regex::escape(name)
))?;
cites.push((cite, format!("[${{1}}{id}${{2}}](${{3}}#{id})")));
}
let named = name_to_id
.keys()
.any(|name| next.contains(&format!("+{name}")));
if named {
next = outside_literals(rel, &next, |mut code: String| {
for (cite, to) in &cites {
code = cite.replace_all(&code, to.as_str()).into_owned();
}
for (name, id) in name_to_id {
for (from, to) in replacement_pairs(name, id, anchor) {
if code.contains(&from) {
code = replace_name(&code, &from, &to);
}
}
}
code.split_inclusive('\n')
.map(|line| match crate::marker::opens_one(line.trim_end()) {
true => name_to_id
.iter()
.fold(line.to_string(), |line, (name, id)| {
replace_name(&line, &format!("+{name}"), id)
}),
false => line.to_string(),
})
.collect()
});
}
if anchor {
let (assigned, letter_actions) =
assign_provisional_letters(rel, &next, name_to_id, letters)?;
next = assigned;
actions.extend(letter_actions);
}
let rewritten = rewrite_cite_paths(&next, rel, id_to_path);
if rewritten != next {
next = rewritten;
}
next = rewrite_qualified_cite_paths(&next, rel, around);
if anchor {
let minted: BTreeSet<&String> = name_to_id.values().collect();
next = link_bare_ids(&next, rel, id_to_path, &minted);
}
if anchor {
let formed = parse::rewrite_parse_form(&next);
if formed != next {
next = formed;
}
}
Ok((next, actions))
}
fn repair_qualifiers(rel: &Path, body: &str, around: &Around<'_>) -> Result<(String, Vec<String>)> {
let mut actions = Vec::new();
let mut out = Vec::new();
let markdown = crate::marker::is_markdown(rel);
let fenced = crate::cache::memo(rel, body, &"fenced lines", || {
crate::marker::fenced_lines(markdown, body)
});
for (idx, line) in body.split('\n').enumerate() {
if fenced.get(idx).copied().unwrap_or(false) {
out.push(line.to_string());
continue;
}
let adoption = ADOPT_LINE_RE.is_match(line);
let mut failure = None;
let (qref, uref): (&Regex, &Regex) = match crate::marker::opens_one(line) {
true => (&QREF_ONE_RE, &UREF_ONE_RE),
false => (&QREF_RE, &UREF_RE),
};
let next = replace_outside_code(markdown, line, qref, |caps: ®ex::Captures| {
let (lead, project, id) = (&caps[1], &caps[2], &caps[3]);
if project == around.own {
if !adoption && around.own_ids.contains(id) {
actions.push(format!("STRIP {project}:{id} in {}", rel.display()));
return format!("{lead}{id}");
}
return caps[0].to_string();
}
if around.others.contains_key(project) {
return caps[0].to_string();
}
match around.declaring(id)[..] {
[] => caps[0].to_string(),
[found] if found == around.own && adoption => caps[0].to_string(),
[found] if found == around.own => {
actions.push(format!("STRIP {project}:{id} in {}", rel.display()));
format!("{lead}{id}")
}
[found] => {
actions.push(format!(
"RELOCATE {project}:{id} -> {found}:{id} in {}",
rel.display()
));
format!("{lead}{found}:{id}")
}
ref several => {
failure = Some(format!(
"{}:{}: `{project}:{id}` names no project, and the id is declared in several: {}. Write the project path by hand.",
rel.display(),
idx + 1,
several
.iter()
.map(|k| format!("`{k}`"))
.collect::<Vec<_>>()
.join(", ")
));
caps[0].to_string()
}
}
});
if let Some(message) = failure {
bail!(message);
}
let next = replace_outside_code(markdown, &next, uref, |caps: ®ex::Captures| {
let (lead, id) = (&caps[1], &caps[2]);
if !caps[3].is_empty() || around.own_ids.contains(id) {
return caps[0].to_string();
}
match around.declaring(id)[..] {
[found] => {
actions.push(format!("QUALIFY {id} -> {found}:{id} in {}", rel.display()));
format!("{lead}{found}:{id}")
}
_ => caps[0].to_string(),
}
});
out.push(next);
}
Ok((out.join("\n"), actions))
}
fn replace_outside_code(
markdown: bool,
line: &str,
re: &Regex,
mut with: impl FnMut(®ex::Captures) -> String,
) -> String {
let masked = if markdown {
parse::mask_inline_code(line)
} else {
line.to_string()
};
let mut out = String::with_capacity(line.len());
let mut last = 0;
for caps in re.captures_iter(&masked) {
let m = caps.get(0).expect("whole match");
out.push_str(&line[last..m.start()]);
out.push_str(&with(&caps));
last = m.end();
}
out.push_str(&line[last..]);
out
}
fn rewrite_qualified_cite_paths(body: &str, source_rel: &Path, around: &Around<'_>) -> String {
let source = workspace::in_workspace(around.own, source_rel);
CITE_LINK_RE
.replace_all(body, |caps: ®ex::Captures| {
let Some(q) = QCITE_RE.captures(caps[1].trim()) else {
return caps[0].to_string();
};
let (project, id) = (&q[1], &q[2]);
if id != &caps[4] {
return caps[0].to_string();
}
let Some(target) = around.others.get(project).and_then(|ids| ids.get(id)) else {
return caps[0].to_string();
};
let current = relative_link_path(&source, &workspace::in_workspace(project, target));
if caps[2].trim() == current {
return caps[0].to_string();
}
let anchor = caps.get(3).map(|m| m.as_str()).unwrap_or("");
format!("[{}]({current}{anchor})", &caps[1])
})
.into_owned()
}
fn decision_paths_for_scope(root: &Path, staged_only: Option<&[PathBuf]>) -> Result<Vec<PathBuf>> {
match staged_only {
None => walk::decision_files(root),
Some(staged) => {
let project = walk::Project::at(root)?;
Ok(staged
.iter()
.filter(|rel| project.is_note(rel) && root.join(rel).is_file())
.map(|rel| root.join(rel))
.collect())
}
}
}
fn print_fallback_logs(root: &Path) -> Result<()> {
for notice in crate::span::fallback_notices(root)? {
crate::say!(" WRN {notice}");
}
Ok(())
}
pub fn resolve_staged(
ws: &Workspace,
project: &ProjectRef,
staged: &[PathBuf],
dry_run: bool,
) -> Result<Option<Vec<PathBuf>>> {
let root = project.dir.as_path();
print_fallback_logs(root)?;
let plan = plan_scoped(ws, project, Some(staged))?;
apply_planned(ws, project, staged, dry_run, plan)
}
pub fn independent_plans(
ws: &Workspace,
projects: &[(&ProjectRef, Option<Vec<PathBuf>>)],
) -> Option<Vec<ResolvePlan>> {
let plans = crate::par::map(
projects.iter().collect(),
|_| 1,
|(project, staged)| {
let plan = plan_scoped(ws, project, staged.as_deref()).ok()?;
let notes = walk::Project::at(&project.dir).ok()?;
let own = plan
.writes
.writes
.iter()
.all(|(rel, _)| !notes.is_note(rel));
own.then_some(plan)
},
);
plans.into_iter().collect()
}
pub fn resolve_planned(
ws: &Workspace,
project: &ProjectRef,
staged: &[PathBuf],
dry_run: bool,
plan: ResolvePlan,
) -> Result<Option<Vec<PathBuf>>> {
print_fallback_logs(&project.dir)?;
apply_planned(ws, project, staged, dry_run, plan)
}
fn apply_planned(
ws: &Workspace,
project: &ProjectRef,
staged: &[PathBuf],
dry_run: bool,
plan: ResolvePlan,
) -> Result<Option<Vec<PathBuf>>> {
let root = project.dir.as_path();
for action in &plan.actions {
crate::say!(" {action}");
}
for warn in &plan.warnings {
crate::say!(" {warn}");
}
write::apply(&plan.writes, root, dry_run)?;
let texts = project_pin_texts(ws, project)?;
let pins = crate::span::pin_bare(root, &texts, Some(staged))?;
let (pins, drifted) = leave_drifted_bare(root, pins)?;
write::apply(&pins, root, dry_run)?;
fail_on_drifted_bare(drifted)?;
let rewritten: Vec<PathBuf> = plan
.writes
.writes
.iter()
.chain(&pins.writes)
.map(|(rel, _)| rel.clone())
.collect();
if dry_run || rewritten.is_empty() {
Ok(None)
} else {
Ok(Some(rewritten))
}
}
fn leave_drifted_bare(root: &Path, pins: write::WritePlan) -> Result<(write::WritePlan, usize)> {
let drifted = crate::span::drifted_bare(root, &pins)?;
if drifted.is_empty() {
return Ok((pins, 0));
}
for d in &drifted {
crate::say!(
" ERR {}:{}: ยง {} carried {} at HEAD, and its span hashes to @{} now: it drifted, and `fix` pins no drift. 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>...`.",
d.rel.display(),
d.line,
d.addr.display(),
d.held_digests(),
d.now,
d.addr.display()
);
}
let addrs: Vec<String> = drifted.iter().map(|d| d.addr.display()).collect();
crate::say!("{}", one_accept(&addrs));
Ok((
crate::span::leave_bare(root, pins, &drifted)?,
drifted.len(),
))
}
fn fail_on_drifted_bare(drifted: usize) -> Result<()> {
if drifted > 0 {
bail!("{drifted} bare marker(s) drifted since HEAD and stay bare: run `silcrow accept` on each address above");
}
Ok(())
}
pub fn project_pin_texts(ws: &Workspace, project: &ProjectRef) -> Result<crate::span::PinTexts> {
let scan = parse::scan_root(&project.dir)?;
Ok(crate::span::PinTexts::for_project(
&scan,
&ws.law_scans(&project.key)?,
))
}
pub fn run(ws: &Workspace, project: &ProjectRef, dry_run: bool, scheme_remint: bool) -> Result<()> {
let root = project.dir.as_path();
print_fallback_logs(root)?;
if scheme_remint {
let recorded = crate::hook::recorded_scheme_at(&ws.root, "HEAD")?;
let has_history = crate::check::has_history(&ws.root);
if let Some(recorded) = recorded
.as_ref()
.filter(|n| **n != crate::scheme::Scheme::binary())
{
return run_remint_digests(ws, project, dry_run, Some(recorded.clone()));
}
if recorded.is_none() && has_history && plan(ws, project, true)?.writes.writes.is_empty() {
return run_remint_digests(ws, project, dry_run, None);
}
}
let plan = plan(ws, project, scheme_remint)?;
run_plan(ws, project, dry_run, scheme_remint, plan)
}
pub fn run_planned(
ws: &Workspace,
project: &ProjectRef,
dry_run: bool,
plan: ResolvePlan,
) -> Result<()> {
print_fallback_logs(&project.dir)?;
run_plan(ws, project, dry_run, false, plan)
}
fn run_plan(
ws: &Workspace,
project: &ProjectRef,
dry_run: bool,
scheme_remint: bool,
plan: ResolvePlan,
) -> Result<()> {
let root = project.dir.as_path();
for action in &plan.actions {
crate::say!(" {action}");
}
for warn in &plan.warnings {
crate::say!(" {warn}");
}
let reminted: BTreeSet<String> = if scheme_remint && !plan.writes.writes.is_empty() {
parse::scan_root(root)?
.laws
.iter()
.filter(|law| !hash::is_provisional_id(&law.id) && hash::mint_id(&law.name) != law.id)
.map(|law| law.id.clone())
.collect()
} else {
BTreeSet::new()
};
let held = if reminted.is_empty() {
BTreeSet::new()
} else {
let scan = parse::scan_root(root)?;
let old = crate::accept::head_sentences(
root,
scan.laws.iter().filter(|law| reminted.contains(&law.id)),
)?;
crate::accept::sentence_held(ws, project, project, &old, &|p| {
p.project.is_none() && reminted.contains(&p.id)
})?
};
write::apply(&plan.writes, root, dry_run)?;
if !dry_run && !held.is_empty() {
let repins = crate::span::repin_at(root, project_pin_texts(ws, project)?, &held, &|p| {
p.project.is_none()
})?;
for (rel, _) in &repins.writes {
crate::say!(" REPIN {}: the id it names was reminted", rel.display());
}
write::apply(&repins, root, dry_run)?;
}
let texts = project_pin_texts(ws, project)?;
let pins = crate::span::pin_bare(root, &texts, None)?;
let (pins, drifted) = leave_drifted_bare(root, pins)?;
for (rel, _) in &pins.writes {
crate::say!(" PIN {}", rel.display());
}
write::apply(&pins, root, dry_run)?;
fail_on_drifted_bare(drifted)?;
let unhashable = crate::span::unhashable(root, &|_| true)?;
if !unhashable.is_empty() {
for err in &unhashable {
crate::say!(" {err}");
}
bail!(
"{} pin(s) cannot be hashed: write the code each line above names so the grammar parses it, then run `silcrow fix` again",
unhashable.len()
);
}
let spanless = crate::span::spanless(root)?;
if !spanless.is_empty() {
for err in &spanless {
crate::say!(" {err}");
}
bail!(
"{} marker(s) pin nothing: move each above the construct it carries, then run `silcrow fix` again",
spanless.len()
);
}
let wrote = !(plan.writes.writes.is_empty() && pins.writes.is_empty());
if !wrote {
crate::say!("\nโ Nothing to fix.");
} else if dry_run {
crate::say!("\nRun with --write to apply. Pins are planned on the tree as it is now.");
} else {
crate::say!("\nโ Fixed. Run `silcrow check`.");
}
Ok(())
}
fn run_remint_digests(
ws: &Workspace,
project: &ProjectRef,
dry_run: bool,
recorded: Option<crate::scheme::Scheme>,
) -> Result<()> {
let root = project.dir.as_path();
let binary = crate::scheme::Scheme::binary();
if let Some(recorded) = &recorded {
crate::say!(
" The hashing scheme moved for {}: only the pins that read a part that moved are reminted.",
crate::scheme::describe(&recorded.moved_all(&binary))
);
}
let reads_moved = |rel: &Path| {
recorded.as_ref().is_none_or(|recorded| {
!recorded
.moved(&binary, &crate::scheme::parts_of(rel))
.is_empty()
})
};
let scan = parse::scan_root(root)?;
let scans = ws.law_scans(&project.key)?;
let now =
crate::span::TreeTokens::new(root, crate::span::PinTexts::for_project(&scan, &scans))?;
crate::published::require_history(&ws.root)?;
let head = tempfile::tempdir()?;
crate::published::write_tree(&ws.root, "HEAD", head.path())?;
let head_ws = Workspace::at(head.path().to_path_buf())?;
let head_root = head.path().join(root.strip_prefix(&ws.root)?);
let mut head_scans = scans;
for (key, scan) in head_ws.law_scans(&project.key)?.scans {
head_scans.scans.insert(key, scan);
}
let head_scan = parse::scan_root(&head_root)?;
let at_head = crate::span::TreeTokens::new(
&head_root,
crate::span::PinTexts::for_project(&head_scan, &head_scans),
)?;
let note_of = |addr: &str| -> Option<PathBuf> {
let (key, local) = match addr.split_once(':') {
Some((key, local)) => (key, local),
None => (project.key.as_str(), addr),
};
let id = local.split('.').next()?;
let scan = match key == project.key {
true => &head_scan,
false => head_scans.scans.get(key)?,
};
let law = scan
.laws
.iter()
.find(|law| law.id == id || law.aliases.iter().any(|a| a == id))?;
Some(crate::workspace::in_workspace(key, &law.loc.path))
};
let held_since = |rel: &Path, addr: &str, written: &str, followed: &BTreeSet<PathBuf>| {
let Some(note) = note_of(addr) else {
return Ok(false);
};
let mut reads: Vec<PathBuf> = std::iter::once(rel)
.chain(followed.iter().map(PathBuf::as_path))
.map(|path| crate::workspace::in_workspace(&project.key, path))
.collect();
reads.push(note);
crate::published::written_last(&ws.root, &reads, &format!("{addr}@{written}"))
};
let (plan, drifted, reminted) =
crate::span::remint_digests(root, &head_root, &at_head, &now, &reads_moved, &held_since)?;
let scheme = match &recorded {
Some(recorded) => format!("scheme {recorded}"),
None => "another scheme".to_string(),
};
for (pin, _) in &drifted {
crate::say!(
" DRIFT {pin}: its span, a callee or its clause changed since HEAD, or a file it reads changed after the commit that wrote its digest, so nothing shows that {scheme} pinned it as it stands. Its code moved, which no remint settles: it keeps its digest."
);
}
let addrs: Vec<String> = drifted.iter().map(|(_, addr)| addr.clone()).collect();
let next = match addrs.is_empty() {
true => String::new(),
false => format!("\n{}", one_accept(&addrs)),
};
if plan.writes.is_empty() {
match addrs.is_empty() {
true => crate::say!("\nโ No pinned span digests to remint."),
false => crate::say!(
"\nNo digest to remint: every pin above drifted because its code moved, not the scheme.{next}"
),
}
return Ok(());
}
for (rel, _) in &plan.writes {
crate::say!(" REMINT-DIGEST {}", rel.display());
}
for line in &reminted {
crate::say!(" REMINT {line}");
}
write::apply(&plan, root, dry_run)?;
if dry_run {
crate::say!("\nRun with --write to apply.{next}");
} else {
crate::say!("\nโ Span digest remint complete.{next}");
}
Ok(())
}
pub fn one_accept(addrs: &[String]) -> String {
let mut seen = BTreeSet::new();
let once: Vec<&str> = addrs
.iter()
.map(String::as_str)
.filter(|addr| seen.insert(*addr))
.collect();
format!(
"Read each with `silcrow diff --law <address>`, then accept them in one call: `silcrow accept {}`, or `silcrow accept --drifted` once every drift is read.",
once.join(" ")
)
}
fn current_ids(text: &str, aliases: &Option<(Regex, BTreeMap<String, String>)>) -> String {
let Some((re, current)) = aliases else {
return text.to_string();
};
re.replace_all(text, |caps: ®ex::Captures| {
format!("{}{}", &caps[1], current[&caps[2]])
})
.into_owned()
}
fn alias_pointer_re(scan: &parse::Scan) -> Result<Option<(Regex, BTreeMap<String, String>)>> {
let current: BTreeMap<String, String> = scan
.laws
.iter()
.filter(|law| !hash::is_provisional_id(&law.id))
.flat_map(|law| law.aliases.iter().map(|a| (a.clone(), law.id.clone())))
.collect();
if current.is_empty() {
return Ok(None);
}
let ids: Vec<String> = current.keys().map(|a| regex::escape(a)).collect();
let re = Regex::new(&format!(
r"(\[ยง\s*|\[|ยง\s*(?:end\s+)?|\]\([^)#\s]*#)({})\b",
ids.join("|")
))?;
Ok(Some((re, current)))
}
fn anchored_marker(id: &str) -> String {
format!("ยง <a id=\"{id}\">{id}</a>")
}
fn replacement_pairs(name: &str, id: &str, anchor: bool) -> Vec<(String, String)> {
let (declare, declare_tight) = if anchor {
(anchored_marker(id), format!("ยง<a id=\"{id}\">{id}</a>"))
} else {
(format!("ยง {id}"), format!("ยง{id}"))
};
vec![
(format!("ยง? +{name}"), declare.replacen('ยง', "ยง?", 1)),
(format!("ยง!? +{name}"), declare.replacen('ยง', "ยง!?", 1)),
(format!("ยง?! +{name}"), declare.replacen('ยง', "ยง!?", 1)),
(format!("ยง! +{name}"), declare.replacen('ยง', "ยง!", 1)),
(format!("ยง +{name}"), declare),
(format!("ยง+{name}"), declare_tight),
(format!("// ยง +{name}"), format!("// ยง {id}")),
(format!("<!-- ยง +{name}"), format!("<!-- ยง {id}")),
(format!("ยง end +{name}"), format!("ยง end {id}")),
(format!("#+{name}"), format!("#{id}")),
(format!("[+{name}"), format!("[{id}")),
]
}
fn outside_literals(rel: &Path, text: &str, rewrite: impl Fn(String) -> String) -> String {
let mut out = String::with_capacity(text.len());
let mut at = 0;
for (start, end) in crate::span::literal_ranges(rel, text) {
if start < at {
continue;
}
out.push_str(&rewrite(text[at..start].to_string()));
out.push_str(&text[start..end]);
at = end;
}
out.push_str(&rewrite(text[at..].to_string()));
out
}
fn replace_name(text: &str, from: &str, to: &str) -> String {
let is_name = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-';
let bounded = from.ends_with(is_name);
let mut out = String::with_capacity(text.len());
let mut at = 0;
for (start, _) in text.match_indices(from) {
let end = start + from.len();
if bounded && text[end..].starts_with(is_name) {
continue;
}
out.push_str(&text[at..start]);
out.push_str(to);
at = end;
}
out.push_str(&text[at..]);
out
}
fn build_id_to_path(
scan: &parse::Scan,
name_to_id: &BTreeMap<String, String>,
) -> BTreeMap<String, PathBuf> {
let mut map = BTreeMap::new();
for law in &scan.laws {
let id = resolve_law_id(&law.id, name_to_id);
if hash::is_provisional_id(&id) {
continue;
}
map.insert(id, law.loc.path.clone());
}
map
}
fn letters_per_law(
scan: &parse::Scan,
name_to_id: &BTreeMap<String, String>,
) -> BTreeMap<String, BTreeSet<String>> {
let mut map = BTreeMap::new();
for law in &scan.laws {
let id = resolve_law_id(&law.id, name_to_id);
let entry = map.entry(id).or_insert_with(BTreeSet::new);
for al in &law.clauses {
if let Some(letter) = &al.letter {
entry.insert(letter.clone());
}
}
}
map
}
fn has_provisional_clause(root: &Path) -> Result<bool> {
for path in walk::decision_files(root)? {
let text = std::fs::read_to_string(&path)?;
let lines: Vec<&str> = text.lines().collect();
let fence = parse::fence_mask(&lines);
if lines.iter().zip(fence).any(|(line, fenced)| {
!fenced && (PROVISIONAL_CLAUSE_RE.is_match(line) || PROVISIONAL_ROW_RE.is_match(line))
}) {
return Ok(true);
}
}
Ok(false)
}
fn burn_published_letters(
ws: &Workspace,
root: &Path,
scan: &parse::Scan,
letters: &mut BTreeMap<String, BTreeSet<String>>,
) -> Result<()> {
let held = ws.base_ref("HEAD").and_then(|base| match base {
Some(base) => Ok(Some((
crate::published::at(root, &base)?,
ws.held_letters(root)?,
))),
None => Ok(None),
});
let held = held.context(
"`fix` gives a `(+)` clause a letter the published history never held for its law, so it reads that history",
)?;
let Some((published, history)) = held else {
return Ok(());
};
for law in &scan.laws {
let used = letters.entry(law.id.clone()).or_default();
if let Some(burned) = published.letters_of(law) {
used.extend(burned);
}
for id in std::iter::once(&law.id).chain(&law.aliases) {
used.extend(history.get(id).into_iter().flatten().cloned());
}
}
Ok(())
}
fn resolve_law_id(token: &str, name_to_id: &BTreeMap<String, String>) -> String {
if let Some(name) = token.strip_prefix('+') {
name_to_id
.get(name)
.cloned()
.unwrap_or_else(|| format!("+{name}"))
} else {
token.to_string()
}
}
pub fn next_free_letter(used: &BTreeSet<String>) -> Option<String> {
let last = used.iter().filter_map(|l| l.bytes().next()).max();
let first = last.map_or(b'a', |b| b + 1);
(first..=b'z').next().map(|b| (b as char).to_string())
}
fn assign_provisional_letters(
rel: &Path,
body: &str,
name_to_id: &BTreeMap<String, String>,
letters: &mut BTreeMap<String, BTreeSet<String>>,
) -> Result<(String, Vec<String>)> {
let mut actions = Vec::new();
let mut current_law: Option<String> = None;
let ended_nl = body.ends_with('\n');
let mut out: Vec<String> = Vec::new();
let lines: Vec<&str> = body.lines().collect();
let fence = parse::fence_mask(&lines);
let mut head_owned = false;
let mut rows_letter: Option<bool> = None;
let mut prev_blank = false;
for (idx, line) in lines.into_iter().enumerate() {
if fence[idx] {
out.push(line.to_string());
continue;
}
if SECTION_BREAK_RE.is_match(line) {
current_law = None;
out.push(line.to_string());
continue;
}
if let Some(caps) = HEAD_RE.captures(line) {
let token = caps
.get(1)
.or(caps.get(2))
.or(caps.get(3))
.unwrap()
.as_str();
current_law = Some(resolve_law_id(token, name_to_id));
(head_owned, rows_letter, prev_blank) = (true, None, false);
out.push(line.to_string());
continue;
}
let row = line.trim_start().starts_with('|');
if !row {
rows_letter = None;
}
let item = PROVISIONAL_CLAUSE_RE.is_match(line) || LETTERED_ITEM_RE.is_match(line);
let letters_rows = row && *rows_letter.get_or_insert(head_owned);
if line.trim().is_empty() {
prev_blank = true;
} else {
let indent = line.len() - line.trim_start().len();
let lettering = item || (letters_rows && LETTERED_ROW_RE.is_match(line));
if lettering || line.starts_with('#') || (prev_blank && !row && indent < 2) {
head_owned = false;
}
prev_blank = false;
}
let provisional = if letters_rows {
PROVISIONAL_ROW_RE.captures(line)
} else if row {
None
} else {
PROVISIONAL_CLAUSE_RE.captures(line)
};
if let Some(target) = ¤t_law {
if let Some(caps) = provisional {
let used = letters.entry(target.clone()).or_default();
let Some(letter) = next_free_letter(used) else {
bail!(
"{}:{}: ยง {target} has no single letter left for a `(+)` clause: it writes or burned (z), and a `(+)` takes the letter after the last. Declare a successor law, or write the clause as a compound under the letter it narrows.",
rel.display(),
idx + 1
);
};
used.insert(letter.clone());
actions.push(format!("LETTER {target}.{letter}"));
let prefix = caps.get(1).map(|m| m.as_str()).unwrap_or("");
let (draft, space) = match caps.len() {
4 => (&caps[2], caps.get(3).map(|m| m.as_str()).unwrap_or(" ")),
_ => ("", caps.get(2).map(|m| m.as_str()).unwrap_or(" ")),
};
let rest = line[caps.get(0).unwrap().end()..].trim_start();
out.push(format!("{prefix}({letter}){draft}{space}{rest}"));
continue;
}
}
out.push(line.to_string());
}
let mut text = out.join("\n");
if ended_nl {
text.push('\n');
}
Ok((text, actions))
}
fn rewrite_cite_paths(
body: &str,
source_rel: &Path,
id_to_path: &BTreeMap<String, PathBuf>,
) -> String {
CITE_LINK_RE
.replace_all(body, |caps: ®ex::Captures| {
let text = &caps[1];
let link_path = caps[2].trim();
let anchor = caps.get(3).map(|m| m.as_str()).unwrap_or("");
let id = &caps[4];
if QCITE_RE.is_match(text.trim()) {
return caps[0].to_string();
}
let Some(target) = id_to_path.get(id) else {
return caps[0].to_string();
};
let current = relative_link_path(source_rel, target);
if link_path.is_empty() {
if normalize_path(source_rel) == normalize_path(target) {
return caps[0].to_string();
}
return format!("[{text}]({current}{anchor})");
}
let resolved = resolve_link_path(source_rel, link_path);
if normalize_path(&resolved) == normalize_path(target) && link_path == current {
return caps[0].to_string();
}
format!("[{text}]({current}{anchor})")
})
.into_owned()
}
fn link_bare_ids(
body: &str,
source_rel: &Path,
id_to_path: &BTreeMap<String, PathBuf>,
minted: &BTreeSet<&String>,
) -> String {
let ended_nl = body.ends_with('\n');
let mut in_fence = false;
let mut out = Vec::new();
for line in body.lines() {
if line.trim_start().starts_with("```") {
in_fence = !in_fence;
}
let settled = HEAD_RE
.captures(line)
.and_then(|c| c.get(1).or(c.get(3)))
.is_some_and(|id| !minted.contains(&id.as_str().to_string()));
if in_fence || settled || line.trim_start().starts_with("```") {
out.push(line.to_string());
continue;
}
let masked: Vec<(usize, usize)> = NOT_BARE_RES
.iter()
.flat_map(|re| re.find_iter(line).map(|m| (m.start(), m.end())))
.collect();
let mut next = String::with_capacity(line.len());
let mut last = 0;
for caps in BARE_ID_RE.captures_iter(line) {
let m = caps.get(0).unwrap();
if masked.iter().any(|(a, b)| m.start() < *b && m.end() > *a) {
continue;
}
let id = &caps[1];
let Some(target) = id_to_path.get(id) else {
continue;
};
let path = if normalize_path(source_rel) == normalize_path(target) {
String::new()
} else {
relative_link_path(source_rel, target)
};
next.push_str(&line[last..m.start()]);
next.push_str(&format!("[{id}{}]({path}#{id})", &caps[2]));
last = m.end();
}
next.push_str(&line[last..]);
out.push(next);
}
let mut text = out.join("\n");
if ended_nl {
text.push('\n');
}
text
}
fn resolve_link_path(source_rel: &Path, link_path: &str) -> PathBuf {
let base = source_rel.parent().unwrap_or_else(|| Path::new(""));
normalize_path(&base.join(link_path))
}
fn normalize_path(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for comp in path.components() {
match comp {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
Component::Normal(part) => out.push(part),
Component::RootDir | Component::Prefix(_) => out.push(comp.as_os_str()),
}
}
out
}
fn relative_link_path(from_file: &Path, to_file: &Path) -> String {
let from_dir = from_file.parent().unwrap_or_else(|| Path::new(""));
let from = from_dir.components().collect::<Vec<_>>();
let to = to_file.components().collect::<Vec<_>>();
let mut common = 0usize;
while common < from.len() && common < to.len() && from[common] == to[common] {
common += 1;
}
let mut rel = PathBuf::new();
for _ in common..from.len() {
rel.push("..");
}
for comp in to.iter().skip(common) {
rel.push(comp.as_os_str());
}
rel.to_string_lossy().replace('\\', "/")
}
fn plan_scheme_remint(root: &Path, base: Option<&str>) -> Result<ResolvePlan> {
let scan = parse::scan_root(root)?;
let published = match base {
Some(base) => crate::published::at(root, base)?.keys(),
None => BTreeSet::new(),
};
let mut actions = Vec::new();
let warnings = Vec::new();
let mut remap: BTreeMap<String, String> = BTreeMap::new();
let mut owners: BTreeMap<String, String> = BTreeMap::new();
for law in &scan.laws {
if hash::is_provisional_id(&law.id) {
continue;
}
let new_id = hash::mint_id(&law.name);
if new_id == law.id {
continue;
}
if let Some(loc) = owners.get(&new_id) {
bail!(
"scheme remint collision: {loc} and {}:{} both mint to {new_id}",
law.loc.path.display(),
law.loc.line
);
}
owners.insert(
new_id.clone(),
format!("{}:{}", law.loc.path.display(), law.loc.line),
);
actions.push(format!("REMINT {} -> {new_id} ({})", law.id, law.name));
remap.insert(law.id.clone(), new_id);
}
if remap.is_empty() {
return Ok(ResolvePlan {
writes: WritePlan { writes: Vec::new() },
actions,
warnings,
});
}
let Remap { mut plan, kept } = plan_remap(root, remap.clone())?;
let mut warnings = warnings;
warnings.extend(
plan.warnings
.iter()
.filter(|w| w.starts_with("CITE "))
.cloned(),
);
for law in &scan.laws {
let Some(new_id) = remap.get(&law.id) else {
continue;
};
if !published.contains(&law.id) && !kept.contains(&law.id) {
continue;
}
let Some((_, text)) = plan
.writes
.writes
.iter_mut()
.find(|(rel, _)| *rel == law.loc.path)
else {
bail!(
"{}: the remint of ยง {} rewrote no head",
law.loc.path.display(),
law.id
);
};
*text = crate::accept::add_alias(text, law.loc.line, new_id, &law.id)?;
actions.push(format!(
"ALIAS {} keeps #{}",
law.loc.path.display(),
law.id
));
}
plan.actions = actions;
plan.warnings = warnings;
Ok(plan)
}
pub fn plan_remap(root: &Path, remap: BTreeMap<String, String>) -> Result<Remap> {
let mut actions: Vec<String> = remap
.iter()
.map(|(old, new)| format!("REMAP {old} -> {new}"))
.collect();
actions.sort();
let mut remap = rewrite_project(root, &remap, &|text: &str, old: &str, new: &str| {
replace_token(text, old, new, |c| c != ':')
})?;
remap.plan.actions = actions;
Ok(remap)
}
pub struct Remap {
pub plan: ResolvePlan,
pub kept: BTreeSet<String>,
}
type Rewrite<'a> = &'a dyn Fn(&str, &str, &str) -> String;
fn rewrite_project(
root: &Path,
remap: &BTreeMap<String, String>,
rewrite: Rewrite<'_>,
) -> Result<Remap> {
let mut writes = Vec::new();
let mut warnings = Vec::new();
let mut kept = BTreeSet::new();
let all = |text: &str| {
remap
.iter()
.fold(text.to_string(), |acc, (old, new)| rewrite(&acc, old, new))
};
let project = walk::Project::at(root)?;
for rel in collect_rewrite_paths(root)? {
let Ok(body) = std::fs::read_to_string(root.join(&rel)) else {
continue;
};
let markdown = crate::marker::is_markdown(&rel);
let fenced = crate::marker::fenced_lines(markdown, &body);
let literal = if markdown {
Vec::new()
} else {
crate::span::unmarked_lines(&rel, &body, None)
};
let heads: BTreeMap<usize, String> = if project.is_note(&rel) {
parse::scan_text(&rel, &body)
.laws
.into_iter()
.map(|law| (law.loc.line - 1, law.id))
.collect()
} else {
BTreeMap::new()
};
let mut lines = Vec::new();
for (idx, line) in body.split('\n').enumerate() {
let Some(law) = heads.get(&idx) else {
let pointer = if markdown {
!fenced.get(idx).copied().unwrap_or(false)
} else {
!literal.get(idx).copied().unwrap_or(false)
&& crate::marker::is_pointer_line(line)
};
lines.push(if pointer {
outside_inline_code(line, &all)
} else {
line.to_string()
});
continue;
};
let split = HEAD_PREFIX_RE.find(line).map_or(0, |m| m.end());
let (head, sentence) = line.split_at(split);
for (old, new) in remap {
if rewrite(sentence, old, new) != sentence {
kept.insert(old.clone());
warnings.push(format!(
"CITE {}:{}: the carrying sentence of ยง {law} cites {old}, left as written: rewriting it would remint ยง {law}. The law now ยง {new} keeps #{old} as an alias anchor: edit the cite, then run `silcrow accept {law}`.",
rel.display(),
idx + 1,
));
}
}
lines.push(format!("{}{sentence}", all(head)));
}
let next = lines.join("\n");
if next != body {
warnings.push(format!("REWRITE {}", rel.display()));
writes.push((rel, next));
}
}
Ok(Remap {
plan: ResolvePlan {
writes: WritePlan { writes },
actions: Vec::new(),
warnings,
},
kept,
})
}
fn outside_inline_code(line: &str, rewrite: &dyn Fn(&str) -> String) -> String {
let mut out = String::with_capacity(line.len());
let mut start = 0;
let mut in_code = false;
for (at, c) in line.char_indices() {
if c != '`' {
continue;
}
let part = &line[start..at];
out.push_str(&if in_code {
part.to_string()
} else {
rewrite(part)
});
out.push('`');
start = at + 1;
in_code = !in_code;
}
let rest = &line[start..];
out.push_str(&if in_code {
rest.to_string()
} else {
rewrite(rest)
});
out
}
fn replace_token(text: &str, from: &str, to: &str, before: impl Fn(char) -> bool) -> String {
let mut out = String::with_capacity(text.len());
let mut last = 0;
for (at, _) in text.match_indices(from) {
let prev = text[..at].chars().next_back();
let next = text[at + from.len()..].chars().next();
let whole = prev.is_none_or(|c| !c.is_ascii_alphanumeric() && before(c))
&& next.is_none_or(|c| !c.is_ascii_alphanumeric());
if whole && at >= last {
out.push_str(&text[last..at]);
out.push_str(to);
last = at + from.len();
}
}
out.push_str(&text[last..]);
out
}
pub fn plan_remap_qualified(
root: &Path,
origin: &str,
remap: &BTreeMap<String, String>,
) -> Result<Remap> {
let project = regex::escape(origin);
let rewrite = |text: &str, old: &str, new: &str| {
let cite = Regex::new(&format!(
r"\[((?:ยง\s*)?){project}:{old}((?:\.[a-z]+)?)\]\(([^)#]*)#{old}\b"
))
.expect("qualified cite regex");
let text = cite.replace_all(text, format!("[${{1}}{origin}:{new}${{2}}](${{3}}#{new}"));
replace_token(
&text,
&format!("{origin}:{old}"),
&format!("{origin}:{new}"),
|c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '/' | '-')),
)
};
rewrite_project(root, remap, &rewrite)
}
pub fn collect_rewrite_paths(root: &Path) -> Result<Vec<PathBuf>> {
let mut paths = Vec::new();
for path in walk::decision_files(root)? {
paths.push(path.strip_prefix(root).unwrap_or(&path).to_path_buf());
}
for path in walk::code_files(root)? {
paths.push(path.strip_prefix(root).unwrap_or(&path).to_path_buf());
}
for path in walk::doc_files(root)? {
paths.push(path.strip_prefix(root).unwrap_or(&path).to_path_buf());
}
if root.join("AGENTS.md").is_file() {
paths.push(PathBuf::from("AGENTS.md"));
}
paths.sort();
paths.dedup();
Ok(paths)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_remap_rewrites_pointer_positions_only() {
let x = hash::mint_id("Rule x holds.");
let new = hash::mint_id("Rule x holds now.");
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
)
.unwrap();
std::fs::create_dir_all(dir.path().join("docs/decisions")).unwrap();
let note = format!(
"# N\n\n**ยง <a id=\"{x}\">{x}</a> Rule x holds now.**\n\n- (a) See [{x}](#{x}), not `{x}`.\n\n```\n// ยง {x}.a\n```\n"
);
std::fs::write(dir.path().join("docs/decisions/n.md"), ¬e).unwrap();
std::fs::write(
dir.path().join("lib.rs"),
format!(
"fn f() {{\n // ยง {x}.a\n log(\"REJECT {x} now\");\n // ยง end {x}.a\n}}\n"
),
)
.unwrap();
std::fs::write(
dir.path().join("guide.md"),
format!("Read ยง {x}, written `ยง {x}`.\n\n<!-- ยง {x} -->\n"),
)
.unwrap();
let remap = BTreeMap::from([(x.clone(), new.clone())]);
let Remap { plan, .. } = plan_remap(dir.path(), remap).unwrap();
let written: BTreeMap<_, _> = plan.writes.writes.into_iter().collect();
assert_eq!(
written[Path::new("docs/decisions/n.md")],
format!(
"# N\n\n**ยง <a id=\"{new}\">{new}</a> Rule x holds now.**\n\n- (a) See [{new}](#{new}), not `{x}`.\n\n```\n// ยง {x}.a\n```\n"
)
);
assert_eq!(
written[Path::new("lib.rs")],
format!("fn f() {{\n // ยง {new}.a\n log(\"REJECT {x} now\");\n // ยง end {new}.a\n}}\n")
);
assert_eq!(
written[Path::new("guide.md")],
format!("Read ยง {new}, written `ยง {x}`.\n\n<!-- ยง {new} -->\n")
);
}
#[test]
fn a_remap_leaves_other_carrying_sentences_valid() {
let x = hash::mint_id("Rule x holds.");
let new = hash::mint_id("Rule x holds now.");
let y_sentence = format!("Rule y builds on {x}.");
let y = hash::mint_id(&y_sentence);
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
)
.unwrap();
std::fs::create_dir_all(dir.path().join("docs/decisions")).unwrap();
let note = format!(
"# N\n\n**ยง <a id=\"{x}\">{x}</a> Rule x holds now.**\n\n**ยง <a id=\"{y}\">{y}</a> {y_sentence}**\n\n- (a) See [{x}](#{x}).\n"
);
std::fs::write(dir.path().join("docs/decisions/n.md"), ¬e).unwrap();
std::fs::write(
dir.path().join("lib.rs"),
format!("// ยง {x}\n// ยง lib:{x}\n"),
)
.unwrap();
let remap = BTreeMap::from([(x.clone(), new.clone())]);
let Remap { plan, kept } = plan_remap(dir.path(), remap).unwrap();
assert_eq!(kept, BTreeSet::from([x.clone()]));
let written: BTreeMap<_, _> = plan.writes.writes.into_iter().collect();
let note = &written[Path::new("docs/decisions/n.md")];
let scan = parse::scan_text(Path::new("docs/decisions/n.md"), note);
for law in &scan.laws {
assert_eq!(hash::mint_id(&law.name), law.id, "{note}");
}
assert!(note.contains(&format!("See [{new}](#{new})")), "{note}");
assert!(
plan.warnings.iter().any(|w| w.starts_with("CITE ")),
"{:?}",
plan.warnings
);
assert_eq!(
written[Path::new("lib.rs")],
format!("// ยง {new}\n// ยง lib:{x}\n"),
"a qualified pointer names another project"
);
}
#[test]
fn qualifier_repair_skips_inline_code_and_fences() {
let around = Around {
own: ".",
own_ids: BTreeSet::from(["abcdefgh1".to_string()]),
others: BTreeMap::from([(
"lib".to_string(),
BTreeMap::from([(
"zzzzzzzz1".to_string(),
PathBuf::from("docs/decisions/n.md"),
)]),
)]),
};
let body = "See ยง zzzzzzzz1 and ยง .:abcdefgh1, not `ยง zzzzzzzz1` or `ยง .:abcdefgh1`.\n\n```\nยง zzzzzzzz1 ยง .:abcdefgh1\n```\n";
let (out, actions) = repair_qualifiers(Path::new("docs/guide.md"), body, &around).unwrap();
assert_eq!(
out,
"See ยง lib:zzzzzzzz1 and ยง abcdefgh1, not `ยง zzzzzzzz1` or `ยง .:abcdefgh1`.\n\n```\nยง zzzzzzzz1 ยง .:abcdefgh1\n```\n"
);
assert_eq!(actions.len(), 2, "{actions:?}");
}
#[test]
fn a_qualified_remap_rewrites_only_that_project_path() {
let out = replace_token(
"ยง lib:abcdefgh1 ยง corelib:abcdefgh1 ยง a/lib:abcdefgh1 (ยง lib:abcdefgh1)",
"lib:abcdefgh1",
"lib:zzzzzzzz1",
|c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '/' | '-')),
);
assert_eq!(
out,
"ยง lib:zzzzzzzz1 ยง corelib:abcdefgh1 ยง a/lib:abcdefgh1 (ยง lib:zzzzzzzz1)"
);
}
#[test]
fn replacement_pairs_cover_markers() {
let pairs = replacement_pairs("runtime", "abcdefgh1", false);
let marker = pairs
.iter()
.find(|(from, _)| from.starts_with("// "))
.map(|(f, _)| f.as_str())
.unwrap();
assert!(marker.contains("+runtime"));
assert!(!marker.contains("abcdefgh1"));
}
#[test]
fn replacement_pairs_cover_explicit_ends() {
let pairs = replacement_pairs("runtime", "abcdefgh1", false);
assert!(pairs.contains(&("ยง end +runtime".into(), "ยง end abcdefgh1".into())));
}
#[test]
fn replacement_pairs_use_anchor_in_decisions() {
let pairs = replacement_pairs("runtime", "abcdefgh1", true);
let declare = pairs
.iter()
.find(|(from, _)| from == "ยง +runtime")
.map(|(_, to)| to.clone())
.unwrap();
assert!(declare.contains("<a id=\"abcdefgh1\">"));
}
#[test]
fn rewrite_stops_at_the_end_of_a_name() {
let names = BTreeMap::from([
("p1".to_string(), "aaaaaaaa1".to_string()),
("p10".to_string(), "bbbbbbbb1".to_string()),
("cache".to_string(), "cccccccc1".to_string()),
("cache-ttl".to_string(), "dddddddd1".to_string()),
]);
let body = "fn f() {\n // ยง +p1.a\n // ยง +p10.a\n // ยง +cache\n // ยง +cache-ttl\n // ยง end +p1.a\n // ยง end +p10.a\n}\n";
let mut next = body.to_string();
for (name, id) in &names {
for (from, to) in replacement_pairs(name, id, false) {
next = replace_name(&next, &from, &to);
}
}
assert_eq!(
next,
"fn f() {\n // ยง aaaaaaaa1.a\n // ยง bbbbbbbb1.a\n // ยง cccccccc1\n // ยง dddddddd1\n // ยง end aaaaaaaa1.a\n // ยง end bbbbbbbb1.a\n}\n"
);
let note = "**ยง +p1 One.**\n\n**ยง +p10 Ten, see [+p1.a](#+p1) and [+p10](#+p10).**\n\n**ยง +cache Cache.**\n\n**ยง +cache-ttl Ttl.**\n";
let mut next = note.to_string();
for (name, id) in &names {
for (from, to) in replacement_pairs(name, id, true) {
next = replace_name(&next, &from, &to);
}
}
assert_eq!(
next,
"**ยง <a id=\"aaaaaaaa1\">aaaaaaaa1</a> One.**\n\n**ยง <a id=\"bbbbbbbb1\">bbbbbbbb1</a> Ten, see [aaaaaaaa1.a](#aaaaaaaa1) and [bbbbbbbb1](#bbbbbbbb1).**\n\n**ยง <a id=\"cccccccc1\">cccccccc1</a> Cache.**\n\n**ยง <a id=\"dddddddd1\">dddddddd1</a> Ttl.**\n"
);
}
#[test]
fn next_free_letter_skips_used() {
let used = BTreeSet::from(["a".into(), "aa".into(), "b".into(), "c".into()]);
assert_eq!(next_free_letter(&used).as_deref(), Some("d"));
}
#[test]
fn next_free_letter_never_fills_a_gap() {
let used = BTreeSet::from(["a".into(), "c".into(), "f".into()]);
assert_eq!(next_free_letter(&used).as_deref(), Some("g"));
assert_eq!(next_free_letter(&BTreeSet::new()).as_deref(), Some("a"));
}
#[test]
fn no_letter_is_free_after_z() {
let used: BTreeSet<String> = (b'a'..=b'z').map(|b| (b as char).to_string()).collect();
assert_eq!(next_free_letter(&used), None);
let mut letters = BTreeMap::from([("abcdefgh1".to_string(), used)]);
let body = "**ยง abcdefgh1 A law.**\n\n- (+) New obligation.\n";
let err =
assign_provisional_letters(Path::new("n.md"), body, &BTreeMap::new(), &mut letters)
.unwrap_err();
assert!(err.to_string().contains("no single letter left"), "{err}");
}
#[test]
fn a_provisional_clause_in_a_fence_is_not_lettered() {
let mut letters = BTreeMap::new();
let body = "**ยง abcdefgh1 A law.**\n\n```\n- (+) Example.\n```\n\n- (+) Real.\n";
let (out, actions) =
assign_provisional_letters(Path::new("n.md"), body, &BTreeMap::new(), &mut letters)
.unwrap();
assert!(out.contains("```\n- (+) Example.\n```"), "{out}");
assert!(out.contains("- (a) Real."), "{out}");
assert_eq!(actions.len(), 1, "{actions:?}");
}
#[test]
fn bare_id_becomes_a_link() {
let id_to_path = BTreeMap::from([(
"abcdefgh1".to_string(),
PathBuf::from("docs/decisions/cli/list.md"),
)]);
let source = PathBuf::from("docs/decisions/verbs.md");
let body = "See abcdefgh1.a and `abcdefgh1`, [abcdefgh1](cli/list.md#abcdefgh1), ยง abcdefgh1, standards.\n";
assert_eq!(
link_bare_ids(body, &source, &id_to_path, &BTreeSet::new()),
"See [abcdefgh1.a](cli/list.md#abcdefgh1) and `abcdefgh1`, [abcdefgh1](cli/list.md#abcdefgh1), ยง abcdefgh1, standards.\n"
);
let head = "**ยง <a id=\"abcdefgh2\">abcdefgh2</a> It logs abcdefgh1.**\n";
assert_eq!(
link_bare_ids(head, &source, &id_to_path, &BTreeSet::new()),
head
);
}
#[test]
fn rewrite_cite_paths_updates_stale_location() {
let id = "abcdefgh1";
let id_to_path = BTreeMap::from([(
id.to_string(),
PathBuf::from("docs/decisions/cli/resolve.md"),
)]);
let source = PathBuf::from("docs/decisions/silcrow-design.md");
let body = format!("[resolve](old/resolve.md#{id})");
let out = rewrite_cite_paths(&body, &source, &id_to_path);
assert!(out.contains("cli/resolve.md#abcdefgh1"));
assert!(!out.contains("old/resolve.md"));
}
#[test]
fn rewrite_cite_paths_leaves_correct_path() {
let id = "abcdefgh1";
let id_to_path = BTreeMap::from([(
id.to_string(),
PathBuf::from("docs/decisions/cli/resolve.md"),
)]);
let source = PathBuf::from("docs/decisions/silcrow-design.md");
let body = format!("[resolve](cli/resolve.md#{id})");
let out = rewrite_cite_paths(&body, &source, &id_to_path);
assert_eq!(out, body);
}
#[test]
fn a_provisional_row_of_a_lettered_table_is_lettered_and_a_label_row_is_not() {
let mut letters = BTreeMap::from([("abcdefgh1".to_string(), BTreeSet::from(["a".into()]))]);
let body = "**ยง abcdefgh1 A law.**\n\n| Clause | Rule |\n| --- | --- |\n| (a) | One. |\n| (+) | Refunds below 10 are free. |\n\n- (+) An item.\n\n | Row | Text |\n | --- | --- |\n | (+) | A label. |\n";
let (out, actions) =
assign_provisional_letters(Path::new("n.md"), body, &BTreeMap::new(), &mut letters)
.unwrap();
assert!(
out.contains("| (b) | Refunds below 10 are free. |"),
"{out}"
);
assert!(out.contains("- (c) An item."), "{out}");
assert!(out.contains("| (+) | A label. |"), "{out}");
assert_eq!(actions.len(), 2, "{actions:?}");
let scan = parse::scan_text(Path::new("n.md"), &out);
assert!(
scan.laws[0]
.clauses
.iter()
.any(|c| c.letter.as_deref() == Some("b") && c.text.contains("Refunds below 10")),
"{:?}",
scan.laws[0].clauses
);
assert!(scan.form_errors.is_empty(), "{:?}", scan.form_errors);
let left = parse::scan_text(Path::new("n.md"), body);
let lines: Vec<usize> = left.form_errors.iter().map(|e| e.loc.line).collect();
assert_eq!(lines, [6, 8], "{:?}", left.form_errors);
}
#[test]
fn assign_provisional_letters_under_the_law() {
let mut letters = BTreeMap::from([(
"abcdefgh1".to_string(),
BTreeSet::from(["a".into(), "b".into()]),
)]);
let body = "**ยง abcdefgh1 A law.**\n\n- (a) One.\n\n- (+) New obligation.\n";
let (out, actions) =
assign_provisional_letters(Path::new("n.md"), body, &BTreeMap::new(), &mut letters)
.unwrap();
assert!(out.contains("(c) New obligation."));
assert!(actions.iter().any(|a| a.contains("abcdefgh1.c")));
}
mod props {
use super::super::*;
use crate::note_gen;
use proptest::prelude::*;
const NOTE: &str = "docs/decisions/note.md";
fn prop_project(text: &str) -> tempfile::TempDir {
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\">\nGraph: silcrow check.\n</silcrow>\n",
)
.unwrap();
std::fs::write(dir.path().join(NOTE), text).unwrap();
dir
}
fn prop_fix(dir: &Path) -> Vec<(PathBuf, String)> {
let ws = Workspace::discover(dir).unwrap();
let project = ws.get(".").unwrap();
let plan = plan_scoped(&ws, project, None).unwrap();
for (rel, text) in &plan.writes.writes {
std::fs::write(dir.join(rel), text).unwrap();
}
plan.writes.writes
}
fn prop_sentence(law: &parse::Law) -> String {
let name = if hash::is_provisional_id(&law.id) {
law.name.replace(&format!("ยง {}", law.id), "")
} else {
law.name.clone()
};
hash::canonicalise(&name)
}
type PinTexts = Vec<(String, String, bool, Vec<(String, String, bool)>)>;
fn prop_texts(text: &str) -> PinTexts {
parse::scan_text(Path::new(NOTE), text)
.laws
.iter()
.map(|law| {
let clauses = law
.clauses
.iter()
.map(|al| {
(
al.letter.clone().unwrap(),
hash::pin_canon(&al.pin_body()),
al.struck,
)
})
.collect();
(
prop_sentence(law),
hash::pin_canon(&law.body),
law.struck,
clauses,
)
})
.collect()
}
proptest! {
#![proptest_config(ProptestConfig {
cases: 64,
failure_persistence: None,
..ProptestConfig::default()
})]
#[test]
fn fix_is_idempotent(note in note_gen::gen_note(true, false)) {
let dir = prop_project(¬e.render().text);
prop_fix(dir.path());
let again = prop_fix(dir.path());
prop_assert!(again.is_empty(), "second pass rewrote {:?}", again);
}
#[test]
fn fix_keeps_canonical_clause_text(note in note_gen::gen_note(true, false)) {
let text = note.render().text;
let dir = prop_project(&text);
prop_fix(dir.path());
let fixed = std::fs::read_to_string(dir.path().join(NOTE)).unwrap();
prop_assert_eq!(prop_texts(&fixed), prop_texts(&text), "\n{}\n---\n{}", text, fixed);
}
}
}
}