use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use super::ungoverned::FileHunks;
use super::{
byte_line, extract_punched, json_escape, line_span, lost_pin, nest_changes, pair_spans,
parse_files, pin_lines, punched_in, qualify, BlockRow, CalleeDiff, Callers, Change, FileMap,
FollowIndex, Kind, ParsedMap, Shown,
};
use crate::span;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum Status {
Deleted,
Retired,
Removed,
Drafted,
Plain,
Accepted,
New,
Reminted,
TextChanged,
ContextChanged,
Public,
Changed,
}
impl Status {
pub(super) fn status_key(self) -> &'static str {
match self {
Status::Deleted => "deleted",
Status::Retired => "retired",
Status::Removed => "removed",
Status::Drafted => "drafted",
Status::Plain => "plain",
Status::Accepted => "accepted",
Status::New => "new",
Status::Reminted => "reminted",
Status::TextChanged => "text-changed",
Status::ContextChanged => "context-changed",
Status::Public => "public",
Status::Changed => "changed",
}
}
fn status_label(self) -> &'static str {
match self {
Status::Deleted => "deleted without a strike",
Status::Retired => "retired",
Status::Removed => "removed after a published strike",
Status::Drafted => "made a draft",
Status::Plain => "made plain",
Status::Accepted => "behaviour change accepted",
Status::New => "new",
Status::Reminted => "reminted",
Status::TextChanged => "text changed",
Status::ContextChanged => "context changed",
Status::Public => "made a public promise",
Status::Changed => "code changed",
}
}
fn status_check(self, what: &str) -> String {
match self {
Status::Deleted => format!("was {what} meant to go with no strike, and does nothing still rely on it?"),
Status::Retired | Status::Removed => format!("does nothing still rely on {what}, and does its successor, if any, carry what still holds?"),
Status::Drafted => format!("was {what} meant to owe no marker until it is implemented, and does nothing still rely on the code its markers covered?"),
Status::Accepted | Status::Changed => format!("does the code below still do what {what} says?"),
Status::New => format!("does the code below do what {what} says, and does every place that carries it hold a marker?"),
Status::Reminted => format!("does the new text of {what} state the same decision, and does the code below still do what it says?"),
Status::TextChanged => format!("does the code below still do what the new text of {what} says?"),
Status::ContextChanged => format!("does the new context of {what} leave its text meaning what it says, and does nothing the context adds need a law or a clause?"),
Status::Plain => format!("was {what} meant to leave the public documentation, and does no public page still promise it?"),
Status::Public => format!("does the public documentation carry {what}, with a marker in a file the `docs` list matches?"),
}
}
}
fn status_of(change: &Change) -> Option<Status> {
Some(match change.kind {
Kind::Deleted => Status::Deleted,
Kind::Retired => Status::Retired,
Kind::Reminted => Status::Reminted,
Kind::Removed => Status::Removed,
Kind::Draft if change.why.as_deref() == Some(super::DRAFT_MADE) => Status::Drafted,
Kind::Draft if change.why.as_deref() == Some(super::DRAFT_DROPPED) => Status::New,
Kind::Draft => return None,
Kind::Public if change.why.as_deref() == Some(super::PUBLIC_DROPPED) => Status::Plain,
Kind::Public => Status::Public,
Kind::Accepted => Status::Accepted,
Kind::Marker if lost_pin(change) => Status::Accepted,
Kind::Declared | Kind::Reused => Status::New,
Kind::Clause if change.old_text.is_none() => Status::New,
Kind::Amended | Kind::Clause => Status::TextChanged,
Kind::Context => Status::ContextChanged,
Kind::Recall => return None,
Kind::Marker if stable(change) => return None,
Kind::Moved | Kind::Cite | Kind::Marker | Kind::Drift => Status::Changed,
})
}
fn stable(change: &Change) -> bool {
change.lines == [None, None] && change.old_text == change.new_text
}
pub(super) struct Rule {
pub(super) id: String,
pub(super) status: Status,
pub(super) note: String,
pub(super) head: Part,
pub(super) clauses: Vec<Part>,
pub(super) span_moved: bool,
pub(super) reminted_from: Option<String>,
}
impl Rule {
fn label(&self) -> String {
match &self.reminted_from {
Some(was) if self.status == Status::Reminted => {
format!("reminted from {was} to {}", self.id)
}
Some(was) => format!(
"reminted from {was} to {}, {}",
self.id,
self.status.status_label()
),
None => self.status.status_label().to_string(),
}
}
}
pub(super) struct Part {
pub(super) address: String,
pub(super) letter: Option<String>,
pub(super) status: Option<Status>,
pub(super) text: [Option<String>; 2],
pub(super) draft: [bool; 2],
pub(super) public: [bool; 2],
pub(super) changes: Vec<Change>,
pub(super) locations: Vec<Location>,
}
pub(super) struct Location {
pub(super) path: String,
pub(super) doc: bool,
pub(super) exists: [bool; 2],
pub(super) pins: Vec<Pin>,
pub(super) reads: Vec<Body>,
pub(super) callees: Vec<Body>,
}
pub(super) struct Pin {
pub(super) kind: &'static str,
pub(super) lines: [Option<usize>; 2],
pub(super) starts: [usize; 2],
pub(super) old: Option<String>,
pub(super) new: Option<String>,
pub(super) why: Option<String>,
pub(super) callers: Vec<String>,
pub(super) kept: Option<usize>,
}
impl Pin {
fn hunks(&self, exists: [bool; 2], label: &str) -> String {
let starts = [0, 1].map(|side| self.starts[side] * usize::from(exists[side]));
match self.kept {
Some(at) => unmarked_hunks(
self.old.as_deref(),
self.old.as_deref(),
[starts[0], at],
label,
),
None => unmarked_hunks(self.old.as_deref(), self.new.as_deref(), starts, label),
}
}
}
pub(super) struct Body {
pub(super) diff: CalleeDiff,
pub(super) starts: [usize; 2],
}
pub(super) struct Review {
pub(super) base: String,
pub(super) laws: Vec<String>,
pub(super) folded: usize,
pub(super) block: Vec<BlockRow>,
pub(super) rules: Vec<Rule>,
pub(super) ungoverned: Vec<FileHunks>,
}
impl Review {
pub(super) fn gather(
base: String,
laws: Vec<String>,
folded: usize,
block: Vec<BlockRow>,
mut rules: Vec<Rule>,
ungoverned: Vec<FileHunks>,
) -> Self {
rules.sort_by(|a, b| {
(a.status, !a.span_moved, &a.id).cmp(&(b.status, !b.span_moved, &b.id))
});
Self {
base,
laws,
folded,
block,
rules,
ungoverned,
}
}
pub(super) fn holds_nothing(&self) -> bool {
self.rules.is_empty()
&& self.folded == 0
&& self.block.is_empty()
&& self.ungoverned.is_empty()
}
}
pub(super) fn law_entries(
changes: &[Change],
files: &FileMap,
follow: &FollowIndex,
callers: &Callers,
shown: &Shown,
) -> Vec<Rule> {
let parsed = parse_files(files);
let at = Places {
files,
parsed: &parsed,
follow,
callers,
shown,
};
let mut out = Vec::new();
for (id, law) in nest_changes(changes) {
let reminted_from = law
.changes
.iter()
.filter(|c| c.kind == Kind::Reminted)
.find_map(|c| c.why.as_deref()?.strip_prefix(super::REMINTED_FROM))
.map(|was| qualify(shown.key, was.trim_end_matches('.')));
let reminted = reminted_from.is_some();
let head = at.place_part(&id, None, &law.changes, &law.markers, reminted);
let clauses: Vec<Part> = law
.clauses
.iter()
.map(|(letter, clause)| {
at.place_part(
&format!("{id}.{letter}"),
Some(letter),
&clause.changes,
&clause.markers,
reminted,
)
})
.filter(|part| part.status.is_some() || !part.locations.is_empty())
.collect();
let Some(status) = head
.status
.into_iter()
.chain(clauses.iter().filter_map(|part| part.status))
.min()
else {
continue;
};
let note = law
.changes
.iter()
.chain(law.clauses.values().flat_map(|clause| &clause.changes))
.find_map(|change| change.new_path.as_ref().or(change.old_path.as_ref()))
.map_or(String::new(), |path| format!("{}{path}", shown.prefix));
let span_moved = law
.markers
.iter()
.chain(law.clauses.values().flat_map(|clause| &clause.markers))
.filter(|c| matches!(c.kind, Kind::Drift | Kind::Accepted))
.any(|c| {
c.old_text.as_deref().map(super::strip_digests)
!= c.new_text.as_deref().map(super::strip_digests)
});
out.push(Rule {
id: qualify(shown.key, &id),
status,
note,
head,
clauses,
span_moved,
reminted_from,
});
}
out
}
struct Places<'a> {
files: &'a FileMap,
parsed: &'a ParsedMap,
follow: &'a FollowIndex,
callers: &'a Callers,
shown: &'a Shown<'a>,
}
impl Places<'_> {
fn place_part(
&self,
address: &str,
letter: Option<&String>,
changes: &[Change],
markers: &[Change],
reminted: bool,
) -> Part {
let status = changes
.iter()
.chain(markers)
.filter_map(|c| match status_of(c) {
Some(Status::Accepted)
if reminted && c.why.as_deref() == Some(super::TEXT_MOVE) =>
{
Some(Status::Reminted)
}
status => status,
})
.min();
let recall = changes.iter().find(|c| {
matches!(
c.kind,
Kind::Declared
| Kind::Retired
| Kind::Reminted
| Kind::Removed
| Kind::Deleted
| Kind::Moved
| Kind::Amended
| Kind::Clause
| Kind::Reused
| Kind::Recall
| Kind::Draft
| Kind::Public
)
});
let mut kept: Vec<Change> = changes
.iter()
.filter(|c| c.kind != Kind::Recall)
.cloned()
.collect();
for change in &mut kept {
change.address = qualify(self.shown.key, &change.address);
for path in [&mut change.old_path, &mut change.new_path]
.into_iter()
.flatten()
{
*path = format!("{}{path}", self.shown.prefix);
}
}
Part {
address: qualify(self.shown.key, address),
letter: letter.cloned(),
status,
text: [
recall.and_then(|c| c.old_text.clone()),
recall.and_then(|c| c.new_text.clone()),
],
draft: changes.iter().find(|c| c.kind == Kind::Draft).map_or(
[false, false],
|c| match c.why.as_deref() {
Some(super::DRAFT_MADE) => [false, true],
Some(super::DRAFT_DROPPED) => [true, false],
_ => [false, true],
},
),
public: changes
.iter()
.find(|c| c.kind == Kind::Public)
.map_or([false, false], |c| match c.why.as_deref() {
Some(super::PUBLIC_DROPPED) => [true, false],
_ => [false, true],
}),
changes: kept,
locations: self.place_locations(address, markers),
}
}
fn place_locations(&self, address: &str, markers: &[Change]) -> Vec<Location> {
let paths: BTreeSet<&str> = markers.iter().map(change_path).collect();
let mut out = Vec::new();
for path in paths {
let here: Vec<&Change> = markers.iter().filter(|c| change_path(c) == path).collect();
let callee_moved: BTreeSet<usize> = here
.iter()
.filter(|c| !c.callees.is_empty())
.filter_map(|c| c.lines[1])
.collect();
let exists = self
.files
.get(path)
.map_or([true, true], |(old, new)| [old.is_some(), new.is_some()]);
let spans = match self.files.get(path) {
Some((old, new)) => span_pins(
path,
address,
[old.as_deref(), new.as_deref()],
self.parsed.get(path),
(self.follow, &callee_moved),
),
None => Vec::new(),
};
let mut pins: Vec<Pin> = if spans.is_empty() {
here.iter()
.map(|change| self.raw_pin(change, address, &callee_moved))
.collect()
} else {
spans
.into_iter()
.map(|mut pin| {
let change = here.iter().find(|c| {
(pin.lines[1].is_some() && c.lines[1] == pin.lines[1])
|| (pin.lines[0].is_some() && c.lines[0] == pin.lines[0])
});
pin.kind = pin_kind(change.copied(), &pin.old, &pin.new);
pin.why =
super::joined_notes(change.and_then(|c| c.why.clone()), pin.why.take());
pin
})
.collect()
};
for pin in &mut pins {
if let Some(line) = pin.lines[1] {
pin.callers = self
.callers
.get(&(path.to_string(), line))
.cloned()
.unwrap_or_default();
}
}
let bodies: BTreeSet<&CalleeDiff> = here.iter().flat_map(|c| &c.callees).collect();
let (mut reads, callees): (Vec<&CalleeDiff>, Vec<&CalleeDiff>) =
bodies.into_iter().partition(|body| body.read.is_some());
reads.sort_by_key(|body| body.read);
let body = |diff: &CalleeDiff| {
let mut diff = diff.clone();
let starts = [0, 1].map(|side| {
let text = self
.files
.get(&diff.path)
.and_then(|t| [&t.0, &t.1][side].as_deref());
let shown = [&diff.old, &diff.new][side].as_deref();
text.zip(shown)
.and_then(|(text, shown)| opening_line(text, shown))
.unwrap_or(1)
});
diff.path = format!("{}{}", self.shown.prefix, diff.path);
Body { diff, starts }
};
out.push(Location {
exists,
doc: self.shown.docs.matches(Path::new(path)),
path: format!("{}{path}", self.shown.prefix),
pins,
reads: reads.into_iter().map(body).collect(),
callees: callees.into_iter().map(body).collect(),
});
}
out
}
fn raw_pin(&self, change: &Change, address: &str, callee_moved: &BTreeSet<usize>) -> Pin {
let notice = change.lines[1]
.filter(|line| callee_moved.contains(line))
.and_then(|line| {
self.follow
.drift_notice(Path::new(change_path(change)), line, address)
});
Pin {
kind: pin_kind(Some(change), &change.old_text, &change.new_text),
lines: change.lines,
starts: [change.lines[0].unwrap_or(1), change.lines[1].unwrap_or(1)],
old: change.old_text.clone(),
new: change.new_text.clone(),
why: super::joined_notes(change.why.clone(), notice),
callers: Vec::new(),
kept: None,
}
}
}
fn change_path(change: &Change) -> &str {
change
.new_path
.as_deref()
.or(change.old_path.as_deref())
.unwrap_or("?")
}
fn opening_line(text: &str, shown: &str) -> Option<usize> {
if let Some(at) = text.find(shown) {
return Some(byte_line(text, at));
}
let first = shown.lines().next()?;
text.lines()
.position(|line| line == first)
.map(|idx| idx + 1)
}
fn pin_kind(change: Option<&Change>, old: &Option<String>, new: &Option<String>) -> &'static str {
match change.map(|c| c.kind) {
Some(Kind::Accepted) => "accepted",
Some(Kind::Drift) => "drift",
_ if old.is_none() => "added",
_ if new.is_none() => "removed",
Some(_) if change.is_some_and(|c| !stable(c)) => "changed",
_ => "unchanged",
}
}
fn span_pins(
path: &str,
address: &str,
texts: [Option<&str>; 2],
parsed: Option<&[Option<Vec<span::SpanMarker>>; 2]>,
(follow, callee_moved): (&FollowIndex, &BTreeSet<usize>),
) -> Vec<Pin> {
let [old, new] = texts;
let rel = Path::new(path);
let pins = [
pin_lines(rel, old.unwrap_or(""), address),
pin_lines(rel, new.unwrap_or(""), address),
];
if pins.iter().all(Vec::is_empty) {
return Vec::new();
}
let markers = |side: usize| parsed.and_then(|sides| sides[side].as_deref());
let punched = |side: usize, text: &str, line: usize| match markers(side) {
Some(markers) => punched_in(text, markers, line).map(|(span, _, _)| span),
None => extract_punched(rel, text, line),
};
let opens = |side: usize, text: &str, line: usize| {
let start = match markers(side) {
Some(markers) => markers
.iter()
.find(|m| m.line == line)
.map(|m| byte_line(text, m.start)),
None => line_span(rel, text, line).map(|(start, _)| start),
};
start.map_or(line, |start| start.min(line))
};
let bodies = |side: usize| -> Vec<Option<String>> {
pins[side]
.iter()
.map(|line| texts[side].and_then(|text| punched(side, text, *line)))
.collect()
};
let (old_bodies, new_bodies) = (bodies(0), bodies(1));
let mut out = Vec::new();
for (i, j) in pair_spans(&old_bodies, &new_bodies) {
let old_body = i.and_then(|i| old_bodies[i].clone());
let new_body = j.and_then(|j| new_bodies[j].clone());
if old_body.is_none() && new_body.is_none() {
continue;
}
let lines = [i.map(|i| pins[0][i]), j.map(|j| pins[1][j])];
let why = match (&old_body, &new_body, lines[1]) {
(Some(o), Some(n), Some(line)) if o != n || callee_moved.contains(&line) => {
follow.drift_notice(rel, line, address)
}
_ => None,
};
let start = |side: usize| {
lines[side]
.zip(texts[side])
.map_or(1, |(line, text)| opens(side, text, line))
};
let kept = match (lines, texts, &new_body) {
([Some(line), None], [Some(old), Some(new)], None) => {
let region = match markers(0) {
Some(markers) => markers.iter().find(|m| m.line == line).map(|m| {
let end = byte_line(old, m.end.saturating_sub(1).max(m.start));
(byte_line(old, m.start).min(line), end)
}),
None => line_span(rel, old, line).map(|(from, to)| (from.min(line), to)),
};
region.and_then(|region| kept_at(old, region, new))
}
_ => None,
};
out.push(Pin {
kind: "unchanged",
lines,
starts: [start(0), start(1)],
old: old_body,
new: new_body,
why: match kept {
Some(_) => super::joined_notes(why, Some(KEPT.to_string())),
None => why,
},
callers: Vec::new(),
kept,
});
}
out
}
const KEPT: &str = "Only its marker went: the code it spanned stands unchanged.";
fn kept_at(old: &str, (from, to): (usize, usize), new: &str) -> Option<usize> {
let want: Vec<&str> = old
.lines()
.skip(from.checked_sub(1)?)
.take((to + 1).saturating_sub(from))
.filter(|line| !is_marker_line(line))
.collect();
if want.iter().all(|line| line.trim().is_empty()) {
return None;
}
let have: Vec<(usize, &str)> = new
.lines()
.enumerate()
.filter(|(_, line)| !is_marker_line(line))
.collect();
have.windows(want.len())
.find(|window| {
window
.iter()
.map(|(_, line)| *line)
.eq(want.iter().copied())
})
.map(|window| window[0].0 + 1)
}
fn judged(rule: &Rule) -> String {
let moved: Vec<&str> = std::iter::once(&rule.head)
.chain(&rule.clauses)
.filter(|part| part.status.is_some())
.map(|part| part.address.as_str())
.collect();
match moved.as_slice() {
[] => rule.id.clone(),
[one] => one.to_string(),
[rest @ .., last] => format!("{} and {last}", rest.join(", ")),
}
}
const HOW: &str = "Each section is one law. Read its text, then each place under it: the spans, the code before them, the followed callees and the doc sections that changed. Judge whether they still do what the text says. Then judge whether a change under no law carries a rule that lacks a law or a marker.";
const UNGOVERNED: &str = "Changes under no law";
const UNGOVERNED_WHY: &str = "No marker covers these lines and no pin reads them. Check: does any of them carry a rule that lacks a law or a marker?";
pub(super) fn review_markdown(review: &Review) -> String {
let mut out = format!("# Silcrow review against {}\n\n", review.base);
if review.holds_nothing() {
match review.laws.is_empty() {
false => out.push_str(&format!(
"No updated references for {}.\n",
review.laws.join(", ")
)),
true => out.push_str("No updated references.\n"),
}
return out;
}
out.push_str(&format!("{}\n\n", summary(review)));
if review.laws.is_empty() {
out.push_str(&format!("{HOW}\n\n"));
}
if review.folded > 0 {
out.push_str(&format!("{}\n\n", super::remint_line(review.folded).trim()));
}
if !review.block.is_empty() {
out.push_str(&format!("## {}\n\n", super::BLOCK_HEADING));
out.push_str(&fence(&block_diff(&review.block)));
}
for rule in &review.rules {
out.push_str(&rule_markdown(rule));
}
if !review.ungoverned.is_empty() {
out.push_str(&format!("## {UNGOVERNED}\n\n{UNGOVERNED_WHY}\n\n"));
for file in &review.ungoverned {
out.push_str(&format!("* `{}`: {}\n", file.path, file.counts()));
}
out.push('\n');
let patch: String = review.ungoverned.iter().map(FileHunks::patch).collect();
if !patch.is_empty() {
out.push_str(&fence(&patch));
}
}
out
}
pub(super) fn review_tty(review: &Review) -> String {
let mut out = String::new();
if review.folded > 0 {
out.push_str(&format!("{}\n\n", super::remint_line(review.folded).trim()));
}
if !review.block.is_empty() {
out.push_str(&block_diff(&review.block));
}
for rule in &review.rules {
out.push_str(&rule_tty(rule));
}
for file in &review.ungoverned {
out.push_str(&file.patch());
}
out
}
fn rule_tty(rule: &Rule) -> String {
let parts: Vec<&Part> = std::iter::once(&rule.head).chain(&rule.clauses).collect();
let context = |at: usize| -> String {
rule.head
.changes
.iter()
.filter(|c| c.kind == Kind::Context)
.filter_map(|c| [&c.old_text, &c.new_text][at].as_deref())
.map(|text| format!("\n{text}\n"))
.collect()
};
let side = |at: usize| -> String {
parts
.iter()
.enumerate()
.map(|(i, part)| {
let line = part.text[at].as_deref().map(|text| {
let draft = part.draft[at];
match &part.letter {
Some(letter) => format!("({letter}){} {text}\n", crate::list::mark(draft)),
None => match (part.public[at], draft) {
(true, true) => format!("§!? {text}\n"),
(true, false) => format!("§! {text}\n"),
(false, true) => format!("§? {text}\n"),
(false, false) => format!("{text}\n"),
},
}
});
let under = match i {
0 => context(at),
_ => String::new(),
};
line.unwrap_or_default() + &under
})
.collect()
};
let (old, new) = (side(0), side(1));
let note = match rule.note.is_empty() {
true => rule.id.as_str(),
false => rule.note.as_str(),
};
let mut out = match old.is_empty() && new.is_empty() {
true => String::new(),
false => file_patch(note, [true, true], &[hunk(&old, &new, [1, 1], &rule.id)]),
};
let mut files: Vec<(String, [bool; 2], Vec<String>)> = Vec::new();
let mut add = |path: &str, exists: [bool; 2], hunks: String| {
if hunks.is_empty() {
return;
}
match files.iter_mut().find(|(p, _, _)| p == path) {
Some((_, _, all)) if all.contains(&hunks) => {}
Some((_, _, all)) => all.push(hunks),
None => files.push((path.to_string(), exists, vec![hunks])),
}
};
for part in &parts {
for location in &part.locations {
for pin in &location.pins {
let label = part
.letter
.as_ref()
.map_or(String::new(), |letter| format!("({letter})"));
add(
&location.path,
location.exists,
pin.hunks(location.exists, &label),
);
}
for body in location.reads.iter().chain(&location.callees) {
let hunks = unmarked_hunks(
body.diff.old.as_deref(),
body.diff.new.as_deref(),
body.starts,
&body.diff.name,
);
add(&body.diff.path, [true, true], hunks);
}
}
}
for (path, exists, hunks) in files {
out.push_str(&file_patch(&path, exists, &hunks));
}
out
}
fn summary(review: &Review) -> String {
let mut counts: BTreeMap<Status, usize> = BTreeMap::new();
for rule in &review.rules {
*counts.entry(rule.status).or_default() += 1;
}
let laws = match review.rules.len() {
1 => "1 law".to_string(),
n => format!("{n} laws"),
};
let by: Vec<String> = counts
.iter()
.map(|(status, n)| format!("{n} {}", status.status_label()))
.collect();
let mut line = match by.is_empty() {
true => format!("{laws}."),
false => format!("{laws}: {}.", by.join(", ")),
};
if review.laws.is_empty() {
line.push_str(&match review.ungoverned.len() {
0 => " Nothing changed under no law.".to_string(),
1 => " 1 file changed under no law.".to_string(),
n => format!(" {n} files changed under no law."),
});
}
line
}
fn rule_markdown(rule: &Rule) -> String {
let mut out = format!("## § {}: {}\n\n", rule.id, rule.label());
if !rule.note.is_empty() {
out.push_str(&format!("Decision note `{}`.\n\n", rule.note));
}
out.push_str(&format!(
"Check: {}\n\n",
rule.status.status_check(&judged(rule))
));
out.push_str(&part_markdown(&rule.head, &rule.note));
for clause in &rule.clauses {
let heading = match clause.status {
Some(status) => format!("### {}: {}\n\n", clause.address, status.status_label()),
None => format!("### {}\n\n", clause.address),
};
out.push_str(&heading);
out.push_str(&part_markdown(clause, &rule.note));
}
out
}
fn part_markdown(part: &Part, note: &str) -> String {
let mut out = String::new();
match &part.text {
[None, None] => {}
[old, new] if old == new => {
if let Some(text) = new {
out.push_str("e_lines(&super::structure::plain(text)));
}
}
[old, new] => {
out.push_str(&super::structure::view(old.as_deref(), new.as_deref()));
let label = format!("text of {}", part.address);
let hunk = hunk_of(old.as_deref(), new.as_deref(), [1, 1], &label);
out.push_str(&format!(
"<details>\n<summary>Patch of {}</summary>\n\n{}</details>\n\n",
part.address,
fence(&file_patch(note, [true, true], &[hunk]))
));
}
}
for change in part.changes.iter().filter(|c| c.kind == Kind::Context) {
let (old, new) = (change.old_text.as_deref(), change.new_text.as_deref());
out.push_str(&format!("{}\n\n", super::CONTEXT_MOVED));
out.push_str(&super::structure::view(old, new));
let label = format!("context of {}", part.address);
out.push_str(&format!(
"<details>\n<summary>Patch of the context of {}</summary>\n\n{}</details>\n\n",
part.address,
fence(&file_patch(
note,
[true, true],
&[hunk_of(old, new, [1, 1], &label)]
))
));
}
for change in &part.changes {
if let Some(line) = other_change(change) {
out.push_str(&format!("* {line}\n"));
}
}
if part.changes.iter().any(|c| other_change(c).is_some()) {
out.push('\n');
}
for location in &part.locations {
out.push_str(&location_markdown(
location,
&part.address,
part.text[0] == part.text[1],
));
}
out
}
fn other_change(change: &Change) -> Option<String> {
let at = |path: &Option<String>| path.clone().unwrap_or_default();
match change.kind {
Kind::Moved => Some(format!(
"Moved from `{}` to `{}`.",
at(&change.old_path),
at(&change.new_path)
)),
Kind::Cite if change.old_text.is_none() => {
Some(format!("Cited in `{}`.", at(&change.new_path)))
}
Kind::Cite => Some(format!("No longer cited in `{}`.", at(&change.old_path))),
Kind::Draft => change.why.clone(),
Kind::Public => change.why.clone(),
_ => None,
}
}
fn location_markdown(location: &Location, address: &str, text_kept: bool) -> String {
let what = match location.doc {
true => "doc section",
false => "span",
};
let mut said = Vec::new();
let mut sections: Vec<(&str, String)> = Vec::new();
for pin in &location.pins {
let line = pin.lines[1]
.or(pin.lines[0])
.map_or(String::new(), |l| format!(":{l}"));
let pins = [pin.old.as_deref(), pin.new.as_deref()].map(|text| digest_of(text, address));
let moved = match pins {
[Some(old), Some(new)] if old != new => format!(" (@{old} → @{new})"),
_ => String::new(),
};
let mut line = format!(
"`{}{line}`: {what} of {address}, {}{moved}.",
location.path, pin.kind
);
if let Some(why) = &pin.why {
line.push_str(&format!(" {}", why.replace('\n', " ")));
}
if !pin.callers.is_empty() {
line.push_str(&format!(" Callers carry {}.", pin.callers.join(", ")));
}
said.push(line);
if text_kept && pin.old == pin.new {
continue;
}
let label = format!("{what} of {address}, {}", pin.kind);
sections.push((&location.path, pin.hunks(location.exists, &label)));
}
for body in location.reads.iter().chain(&location.callees) {
let label = match body.diff.read {
Some(_) => body.diff.name.clone(),
None => format!("followed callee {}", body.diff.name),
};
if let Some(why) = &body.diff.why {
said.push(format!("`{}`: {label}. {why}", body.diff.path));
}
let hunk = unmarked_hunks(
body.diff.old.as_deref(),
body.diff.new.as_deref(),
body.starts,
&label,
);
sections.push((&body.diff.path, hunk));
}
let mut out: String = said.iter().map(|line| format!("* {line}\n")).collect();
out.push('\n');
let mut patch = String::new();
let mut at = 0;
while at < sections.len() {
let path = sections[at].0;
let run: Vec<String> = sections[at..]
.iter()
.take_while(|(p, _)| *p == path)
.map(|(_, hunk)| hunk.clone())
.collect();
at += run.len();
let exists = match path == location.path {
true => location.exists,
false => [true, true],
};
patch.push_str(&file_patch(path, exists, &run));
}
if !patch.is_empty() {
out.push_str(&fence(&patch));
}
out
}
fn is_marker_line(line: &str) -> bool {
!crate::marker::markers_in_line(line).is_empty() || crate::marker::end_in_line(line).is_some()
}
fn unmarked_hunks(old: Option<&str>, new: Option<&str>, starts: [usize; 2], label: &str) -> String {
let split = |text: Option<&str>| -> Vec<String> {
text.map_or_else(Vec::new, |t| t.lines().map(str::to_string).collect())
};
let ops = super::aligned_lines(&split(old), &split(new));
let mut at = starts;
let mut run_at = None;
let mut run: [String; 2] = Default::default();
let mut pending: Vec<[bool; 2]> = Vec::new();
for op in &ops {
let (sign, line) = op.split_at(1);
let sides = match sign {
"-" => [true, false],
"+" => [false, true],
_ => [true, true],
};
if is_marker_line(line) {
if run_at.is_some() {
pending.push(sides);
}
} else {
run_at.get_or_insert(at);
let count = |want: [bool; 2]| pending.iter().filter(|s| **s == want).count();
let both = count([true, true]) + count([true, false]).min(count([false, true]));
pending.clear();
for side in [0, 1] {
run[side].push_str(&"\n".repeat(both));
}
for side in [0, 1] {
if sides[side] {
run[side].push_str(line);
run[side].push('\n');
}
}
}
for side in [0, 1] {
if sides[side] && at[side] > 0 {
at[side] += 1;
}
}
}
match run_at {
Some(run_at) => hunk(&run[0], &run[1], run_at, label),
None => String::new(),
}
}
fn digest_of(text: Option<&str>, address: &str) -> Option<String> {
text?
.lines()
.flat_map(crate::marker::markers_in_line)
.find(|marker| marker.display() == address)
.and_then(|marker| marker.digest)
}
fn quote_lines(text: &str) -> String {
let mut out = String::new();
for line in text.lines() {
match line.is_empty() {
true => out.push_str(">\n"),
false => out.push_str(&format!("> {line}\n")),
}
}
out.push('\n');
out
}
pub(super) fn file_patch(path: &str, exists: [bool; 2], hunks: &[String]) -> String {
let side = |at: usize, name: &str| match exists[at] {
true => format!("{name}/{path}"),
false => "/dev/null".to_string(),
};
let mut out = format!(
"diff --git a/{path} b/{path}\n--- {}\n+++ {}\n",
side(0, "a"),
side(1, "b")
);
for hunk in hunks {
out.push_str(hunk);
}
out
}
fn hunk_of(old: Option<&str>, new: Option<&str>, starts: [usize; 2], label: &str) -> String {
hunk(old.unwrap_or(""), new.unwrap_or(""), starts, label)
}
pub(super) fn hunk(old: &str, new: &str, starts: [usize; 2], label: &str) -> String {
let split = |text: &str| -> Vec<String> {
match text.is_empty() {
true => Vec::new(),
false => text.lines().map(str::to_string).collect(),
}
};
let (old, new) = (split(old), split(new));
let ops = super::aligned_lines(&old, &new);
let count = |side: char| {
ops.iter()
.filter(|l| l.starts_with(side) || l.starts_with(' '))
.count()
};
let (o, n) = (count('-'), count('+'));
let start = |side: usize, len: usize| match len {
_ if starts[side] == 0 => 0,
0 => starts[1 - side].saturating_sub(1),
_ => starts[side],
};
let mut out = format!("@@ -{},{o} +{},{n} @@ {label}\n", start(0, o), start(1, n));
for line in ops {
out.push_str(&line);
out.push('\n');
}
out
}
fn block_diff(rows: &[BlockRow]) -> String {
let mut paths: Vec<&str> = rows.iter().map(|row| row.path.as_str()).collect();
paths.dedup();
let mut out = String::new();
for path in paths {
let side = |value: fn(&BlockRow) -> &Option<String>| -> String {
rows.iter()
.filter(|row| row.path == path)
.filter_map(|row| {
value(row)
.as_ref()
.map(|v| format!("{}=\"{v}\"\n", row.attr))
})
.collect()
};
let (old, new) = (side(|row| &row.old), side(|row| &row.new));
out.push_str(&file_patch(
path,
[true, true],
&[hunk(&old, &new, [1, 1], "block")],
));
}
out
}
pub(super) fn fence(body: &str) -> String {
let longest = body
.lines()
.map(|line| line.trim_start().chars().take_while(|&c| c == '`').count())
.max()
.unwrap_or(0);
let ticks = "`".repeat(longest.max(2) + 1);
format!("{ticks}diff\n{body}{ticks}\n\n")
}
enum J {
Null,
Bool(bool),
Num(usize),
Str(String),
Arr(Vec<J>),
Obj(Vec<(&'static str, J)>),
}
impl J {
fn maybe(value: Option<&str>) -> J {
value.map_or(J::Null, |v| J::Str(v.to_string()))
}
fn sides(value: &[Option<String>; 2]) -> J {
J::Obj(vec![
("old", J::maybe(value[0].as_deref())),
("new", J::maybe(value[1].as_deref())),
])
}
fn is_scalar(&self) -> bool {
!matches!(self, J::Arr(_) | J::Obj(_))
}
fn render(&self, indent: usize, out: &mut String) {
let pad = " ".repeat(indent + 1);
match self {
J::Null => out.push_str("null"),
J::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
J::Num(n) => out.push_str(&n.to_string()),
J::Str(s) => out.push_str(&json_escape(s)),
J::Arr(items) if items.iter().all(J::is_scalar) => {
let items: Vec<String> = items
.iter()
.map(|item| {
let mut one = String::new();
item.render(indent, &mut one);
one
})
.collect();
out.push_str(&format!("[{}]", items.join(", ")));
}
J::Arr(items) => {
out.push_str("[\n");
for (i, item) in items.iter().enumerate() {
out.push_str(&pad);
item.render(indent + 1, out);
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
}
out.push_str(&" ".repeat(indent));
out.push(']');
}
J::Obj(fields) => {
out.push_str("{\n");
for (i, (key, value)) in fields.iter().enumerate() {
out.push_str(&format!("{pad}{}: ", json_escape(key)));
value.render(indent + 1, out);
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
}
out.push_str(&" ".repeat(indent));
out.push('}');
}
}
}
}
pub(super) fn review_json(
review: &Review,
declared: &BTreeMap<String, crate::meta::Declared>,
) -> String {
let mut fields = vec![("base", J::Str(review.base.clone()))];
if review.folded > 0 {
fields.push(("remint", J::Bool(true)));
fields.push(("pinned", J::Num(review.folded)));
}
let block = review
.block
.iter()
.map(|row| {
J::Obj(vec![
("path", J::Str(row.path.clone())),
("attribute", J::Str(row.attr.to_string())),
("old", J::maybe(row.old.as_deref())),
("new", J::maybe(row.new.as_deref())),
])
})
.collect();
fields.push(("block", J::Arr(block)));
let laws = review
.rules
.iter()
.map(|rule| {
let mut law = vec![
("id", J::Str(rule.id.clone())),
("status", J::Str(rule.status.status_key().to_string())),
("note", J::Str(rule.note.clone())),
];
if let Some(was) = &rule.reminted_from {
law.push(("reminted_from", J::Str(was.clone())));
}
if let Some((Some(date), _)) = declared.get(super::local_id(&rule.id)) {
law.push(("declared_on", J::Str(date.clone())));
}
law.push(("check", J::Str(rule.status.status_check(&judged(rule)))));
law.push(("sentence", J::Obj(part_json(&rule.head))));
law.push((
"clauses",
J::Arr(rule.clauses.iter().map(|c| J::Obj(part_json(c))).collect()),
));
J::Obj(law)
})
.collect();
fields.push(("laws", J::Arr(laws)));
let ungoverned = review
.ungoverned
.iter()
.map(FileHunks::hunks_json)
.collect();
fields.push(("ungoverned", J::Arr(ungoverned)));
let mut out = String::new();
J::Obj(fields).render(0, &mut out);
out.push('\n');
out
}
fn part_json(part: &Part) -> Vec<(&'static str, J)> {
let mut out = vec![("address", J::Str(part.address.clone()))];
if let Some(letter) = &part.letter {
out.push(("letter", J::Str(letter.clone())));
}
out.push(("status", J::maybe(part.status.map(Status::status_key))));
out.push(("text", J::sides(&part.text)));
let changes = part
.changes
.iter()
.map(|change| {
let mut fields = vec![
("kind", J::Str(change.kind_name().to_string())),
("path", J::Str(change_path(change).to_string())),
("address", J::Str(change.address.clone())),
("old", J::maybe(change.old_text.as_deref())),
("new", J::maybe(change.new_text.as_deref())),
];
if let Some(why) = &change.why {
fields.push(("why", J::Str(why.clone())));
}
J::Obj(fields)
})
.collect();
out.push(("changes", J::Arr(changes)));
let locations = part
.locations
.iter()
.map(|location| {
let pins = location
.pins
.iter()
.map(|pin| {
let mut fields = vec![
("kind", J::Str(pin.kind.to_string())),
(
"lines",
J::Arr(
pin.lines
.iter()
.map(|l| l.map_or(J::Null, J::Num))
.collect(),
),
),
("old", J::maybe(pin.old.as_deref())),
("new", J::maybe(pin.new.as_deref())),
];
if let Some(why) = &pin.why {
fields.push(("why", J::Str(why.clone())));
}
if !pin.callers.is_empty() {
fields.push((
"callers",
J::Arr(pin.callers.iter().map(|c| J::Str(c.clone())).collect()),
));
}
J::Obj(fields)
})
.collect();
let body = |body: &Body| {
let mut fields = Vec::new();
if let Some(read) = body.diff.read {
fields.push(("read", J::Str(super::read_key(read).to_string())));
}
fields.push(("name", J::Str(body.diff.name.clone())));
fields.push(("path", J::Str(body.diff.path.clone())));
fields.push(("old", J::maybe(body.diff.old.as_deref())));
fields.push(("new", J::maybe(body.diff.new.as_deref())));
if let Some(why) = &body.diff.why {
fields.push(("why", J::Str(why.clone())));
}
J::Obj(fields)
};
J::Obj(vec![
("path", J::Str(location.path.clone())),
("doc", J::Bool(location.doc)),
("pins", J::Arr(pins)),
("reads", J::Arr(location.reads.iter().map(body).collect())),
(
"callees",
J::Arr(location.callees.iter().map(body).collect()),
),
])
})
.collect();
out.push(("locations", J::Arr(locations)));
out
}
impl FileHunks {
fn hunks_json(&self) -> J {
let hunks = self
.hunks
.iter()
.map(|h| {
J::Obj(vec![
("old", J::Arr(vec![J::Num(h.old.0), J::Num(h.old.1)])),
("new", J::Arr(vec![J::Num(h.new.0), J::Num(h.new.1)])),
(
"lines",
J::Arr(h.lines.iter().map(|l| J::Str(l.clone())).collect()),
),
])
})
.collect();
let mut fields = vec![("path", J::Str(self.path.clone()))];
if self.old_path.as_ref() != Some(&self.path) {
fields.push(("old_path", J::maybe(self.old_path.as_deref())));
}
fields.push(("added", J::Num(self.added())));
fields.push(("removed", J::Num(self.removed())));
fields.push(("binary", J::Bool(self.binary)));
fields.push(("hunks", J::Arr(hunks)));
J::Obj(fields)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_side_without_the_file_reads_as_dev_null_at_line_zero() {
let doc = hunk("", "## Title\nBody.", [0, 3], "doc section of x, added");
let patch = file_patch("docs/guide.md", [false, true], &[doc]);
assert_eq!(
patch,
"diff --git a/docs/guide.md b/docs/guide.md\n--- /dev/null\n+++ b/docs/guide.md\n\
@@ -0,0 +3,2 @@ doc section of x, added\n+## Title\n+Body.\n"
);
let added = hunk("", "fn f() {}", [7, 7], "span of x, added");
assert!(added.starts_with("@@ -6,0 +7,1 @@"), "{added}");
}
#[test]
fn a_patch_holds_no_marker_and_numbers_each_line_where_it_stands() {
let old =
"fn f() {\n // § c09206qct.a@cnxg2\n run();\n // § end c09206qct.a\n done();\n}\n";
let new = old.replace("cnxg2", "ghxv4").replace("done", "stop");
let patch = unmarked_hunks(Some(old), Some(&new), [10, 10], "x");
assert!(!patch.contains('§'), "{patch}");
assert_eq!(
patch,
"@@ -10,6 +10,6 @@ x\n fn f() {\n \n run();\n \n- done();\n+ stop();\n }\n"
);
let repinned = old.replace("cnxg2", "ghxv4");
let patch = unmarked_hunks(Some(old), Some(&repinned), [1, 1], "x");
assert!(!patch.lines().any(|l| l.starts_with(['-', '+'])), "{patch}");
assert_eq!(
digest_of(Some(old), "c09206qct.a").as_deref(),
Some("cnxg2")
);
assert_eq!(digest_of(Some(old), "c09206qct"), None);
}
#[test]
fn a_marker_line_one_side_drops_shows_as_no_line() {
let old = "fn f() {\n // § c09206qct@w1wb7\n run();\n}\n";
let new = "fn f() {\n run();\n}\n";
let patch = unmarked_hunks(Some(old), Some(new), [1, 1], "x");
assert!(!patch.lines().any(|l| l.starts_with(['-', '+'])), "{patch}");
assert!(!patch.contains('§'), "{patch}");
}
#[test]
fn code_a_removed_pin_spanned_is_kept_only_when_it_stands_unchanged() {
let old = "a\nfn f() {\n // § c09206qct@w1wb7\n run();\n}\n";
assert_eq!(
kept_at(old, (2, 5), "a\nb\nfn f() {\n run();\n}\n"),
Some(3)
);
assert_eq!(kept_at(old, (2, 5), "a\nfn f() {\n stop();\n}\n"), None);
assert_eq!(kept_at(old, (3, 3), "a\n"), None);
}
}