pub use microlith::Violation;
#[must_use]
pub fn check(text: &str) -> Vec<Violation> {
microlith::check_spec(text, &[])
}
pub fn fmt(text: &str) -> Result<String, String> {
microlith::format_spec(text)
}
#[must_use]
pub fn milestones(text: &str) -> Vec<(String, Vec<u32>)> {
microlith::milestones(text)
}
#[must_use]
pub fn milestone_cells(text: &str) -> Vec<(String, String)> {
text.lines()
.filter(|l| l.starts_with("| M"))
.map(|l| {
let cells = microlith::cells(l);
let at =
|n: usize| cells.get(n).map(|c| microlith::unescape(c.trim()));
(at(1).unwrap_or_default(), at(3).unwrap_or_default())
})
.collect()
}
#[must_use]
pub fn rule_depth(spec: &str) -> String {
const KEEP: [&str; 5] =
["\u{a7}G", "\u{a7}C", "\u{a7}I", "\u{a7}V", "\u{a7}T"];
let mut out = String::new();
let (mut keeping, mut tasks) = (true, false);
for line in spec.lines() {
if line.starts_with("## \u{a7}") {
keeping = KEEP.iter().any(|k| line.contains(k));
tasks = line.contains("\u{a7}T");
}
if keeping && !(tasks && finished_row(line)) {
out.push_str(line);
out.push('\n');
}
}
out
}
#[must_use]
pub fn without_tasks(spec: &str) -> String {
let mut out = String::new();
let mut tasks = false;
for line in spec.lines() {
if line.starts_with("## \u{a7}") {
tasks = line
.strip_prefix("## \u{a7}")
.and_then(|rest| rest.chars().next())
== Some('T');
}
if !tasks {
out.push_str(line);
out.push('\n');
}
}
out
}
fn finished_row(line: &str) -> bool {
let mut cells = line.split('|');
let id = cells.next().unwrap_or_default();
id.starts_with('T') && cells.next() == Some("x")
}
#[must_use]
pub fn sections(text: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
let mut cur: Option<(String, String)> = None;
for line in text.lines() {
if line.starts_with("## \u{a7}") {
if let Some(prev) = cur.take() {
out.push(prev);
}
cur = Some((line.trim().to_string(), String::new()));
} else if let Some((_, body)) = cur.as_mut() {
body.push_str(line);
body.push('\n');
}
}
out.extend(cur);
out
}
#[must_use]
pub fn unreflected_bugs(spec: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
let mut in_b = false;
for line in spec.lines() {
if line.starts_with("## \u{a7}") {
in_b = line.starts_with("## \u{a7}B");
continue;
}
if !in_b {
continue;
}
let cells: Vec<&str> = line.split('|').collect();
let [id, _date, cause, fix @ ..] = cells.as_slice() else {
continue;
};
if !id.starts_with('B') || *id == "id" {
continue;
}
let fix = fix.join("|");
let names_invariant =
fix.split(|c: char| !c.is_ascii_alphanumeric()).any(|w| {
w.len() > 1
&& w.starts_with('V')
&& w[1..].chars().all(|d| d.is_ascii_digit())
});
if !names_invariant {
out.push(((*id).to_string(), cause.chars().take(58).collect()));
}
}
out
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Citation {
pub owner: String,
pub id: String,
pub line: usize,
}
#[must_use]
pub fn citations(text: &str) -> Vec<Citation> {
let mut out = Vec::new();
for (n, line) in text.lines().enumerate() {
for (at, _) in line.match_indices(':') {
if let Some((owner, id)) = citation_at(line, at) {
out.push(Citation {
owner,
id,
line: n.saturating_add(1),
});
}
}
}
out
}
fn citation_at(line: &str, colon: usize) -> Option<(String, String)> {
let (left, right) = line.split_at(colon);
let id: String = right
.get(1..)?
.chars()
.take_while(char::is_ascii_alphanumeric)
.collect();
let mut rest = id.chars();
if !matches!(rest.next(), Some(k) if "VBTRIC".contains(k))
|| id.len() < 2
|| !rest.all(|d| d.is_ascii_digit())
{
return None;
}
let owner: String = left
.chars()
.rev()
.take_while(|c| {
c.is_ascii_lowercase()
|| c.is_ascii_digit()
|| *c == '_'
|| *c == '/'
|| *c == '.'
})
.collect::<Vec<char>>()
.into_iter()
.rev()
.collect();
(!owner.is_empty()).then_some((owner, id))
}
#[must_use]
pub fn declares(spec: &str, id: &str) -> bool {
spec.lines().any(|l| {
l.strip_prefix("- ")
.unwrap_or(l)
.strip_prefix(id)
.is_some_and(|r| r.starts_with('|') || r.starts_with(':'))
})
}
const ARCHIVE_STUB: &str = "ARCHIVED to SPEC-ARCHIVE.md";
#[must_use]
pub fn completed_tasks(spec: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
let mut in_t = false;
for line in spec.lines() {
if line.starts_with("## \u{a7}") {
in_t = line.starts_with("## \u{a7}T");
continue;
}
let cells: Vec<&str> = line.split('|').collect();
let [id, "x", task, ..] = cells.as_slice() else {
continue;
};
if in_t && id.starts_with('T') && task.trim() != ARCHIVE_STUB {
out.push(((*id).to_string(), task.chars().take(52).collect()));
}
}
out
}
#[cfg(test)]
#[path = "tests/spec.rs"]
mod tests;
fn federation_table(children: &[String]) -> String {
if children.is_empty() {
return String::new();
}
let mut s =
String::from("## \u{a7}F FEDERATION\n\ndir|owns|\u{22a5}owns|tokens\n");
for c in children {
s.push_str(&format!(
"{c}|WHAT IT OWNS|WHAT IT DOES \u{22a5} OWN, & WHERE THAT LIVES|-\n"
));
}
s.push('\n');
s
}
#[must_use]
pub fn scaffold(dir_name: &str, children: &[String]) -> String {
let mut s = String::from("# SPEC\n\n## \u{a7}G GOAL\n\n");
s.push_str(&format!(
"WHAT `{dir_name}` OWNS, in one sentence. Delete this line.\n\n"
));
s.push_str(&federation_table(children));
s.push_str(
"## \u{a7}V INVARIANTS\n\n\
WHAT MUST STAY TRUE HERE, one line each, numbered from the first id. Delete this line.\n\n\
## \u{a7}T TASKS\n\n\
id|status|task|cites\n",
);
s
}
#[cfg(test)]
#[path = "tests/scaffold.rs"]
mod scaffold_tests;
#[must_use]
pub fn upsert_section(
text: &str,
name: &str,
body: &str,
after: &str,
) -> String {
let head = format!("## \u{a7}{name}");
let anchor = format!("## \u{a7}{after}");
let preamble: String = text
.lines()
.take_while(|l| !l.starts_with("## \u{a7}"))
.map(|l| format!("{l}\n"))
.collect();
let exists = sections(text).iter().any(|(h, _)| h.starts_with(&head));
let mut kept: Vec<String> = Vec::new();
let mut placed = false;
for (heading, sec_body) in sections(text) {
if exists && heading.starts_with(&head) {
kept.push(body.trim_end().to_string());
placed = true;
continue;
}
let section = format!("{heading}\n{sec_body}");
kept.push(section.trim_end().to_string());
if !exists && heading.starts_with(&anchor) {
kept.push(body.trim_end().to_string());
placed = true;
}
}
if !placed {
return text.to_string();
}
format!("{}{}\n", preamble.trim_end_matches('\n'), {
let joined = kept.join("\n\n");
format!("\n\n{joined}")
})
}
#[cfg(test)]
#[path = "tests/upsert.rs"]
mod upsert_tests;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Row {
pub section: char,
pub id: String,
pub text: String,
pub line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unreadable {
pub line: usize,
pub text: String,
}
#[must_use]
pub fn unreadable_rows(spec: &str) -> Vec<Unreadable> {
spec.lines()
.enumerate()
.filter(|(_, line)| row_id(line).is_none())
.filter(|(_, line)| bracketed_id(line))
.map(|(n, line)| Unreadable {
line: n.saturating_add(1),
text: line.to_string(),
})
.collect()
}
fn bracketed_id(line: &str) -> bool {
let trimmed = line.trim();
let Some(body) = trimmed.strip_prefix('|') else {
return false;
};
let body = body.strip_suffix('|').unwrap_or(body);
let cells: Vec<&str> = microlith::cells(body);
let Some(first) = cells.first().map(|c| c.trim()) else {
return false;
};
cells.len() >= 3 && row_id(&format!("{first}|")).is_some()
}
#[must_use]
pub fn rows(spec: &str) -> Vec<Row> {
let mut out = Vec::new();
let mut section = ' ';
for (n, line) in spec.lines().enumerate() {
if let Some(s) = section_letter(line) {
section = s;
} else if let Some(id) = row_id(line) {
out.push(Row {
section,
id,
text: line.to_string(),
line: n.saturating_add(1),
});
}
}
out
}
#[must_use]
pub fn why_gaps(spec: &str, why: &str) -> (Vec<String>, Vec<String>) {
let rules: Vec<String> = rows(spec)
.into_iter()
.filter(|r| r.section == 'V')
.map(|r| r.id)
.collect();
let answered: Vec<String> = rows(why)
.into_iter()
.map(|r| r.id)
.filter(|id| id.starts_with('V'))
.collect();
let missing = rules
.iter()
.filter(|id| !answered.contains(id))
.cloned()
.collect();
let orphan = answered
.iter()
.filter(|id| !rules.contains(id))
.cloned()
.collect();
(missing, orphan)
}
fn section_letter(line: &str) -> Option<char> {
line.strip_prefix("## \u{a7}")?.chars().next()
}
fn row_id(line: &str) -> Option<String> {
let kind = line.chars().next().filter(|k| "VBTR".contains(*k))?;
let digits: String = line
.chars()
.skip(1)
.take_while(char::is_ascii_digit)
.collect();
let id = format!("{kind}{digits}");
let rest = line.get(id.len()..).filter(|_| !digits.is_empty())?;
(rest.starts_with('|') || rest.starts_with(':')).then_some(id)
}
#[must_use]
pub fn requalify(
line: &str,
here: &str,
homes: &std::collections::BTreeMap<String, String>,
) -> String {
let mut out = String::new();
let mut token = String::new();
let mut prev = '\0';
for c in line.chars() {
if c.is_ascii_alphanumeric() {
token.push(c);
continue;
}
out.push_str(&qualified(&token, prev, here, homes));
token.clear();
prev = c;
out.push(c);
}
out.push_str(&qualified(&token, prev, here, homes));
out
}
#[must_use]
pub fn rehome(
line: &str,
here: &str,
from: &str,
moved: &std::collections::BTreeMap<String, String>,
) -> String {
let mut out = String::new();
let mut done = 0;
for (at, _) in line.match_indices(':') {
let Some((owner, id)) = citation_at(line, at) else {
continue;
};
let Some(home) = moved.get(&id).filter(|_| owner == from) else {
continue;
};
let start = at.saturating_sub(owner.len());
let end = at.saturating_add(1).saturating_add(id.len());
let (span, with) = if home == here {
(unquoted(line, start, end), id)
} else {
((start, end), format!("{home}:{id}"))
};
out.push_str(line.get(done..span.0).unwrap_or(""));
out.push_str(&with);
done = span.1;
}
out.push_str(line.get(done..).unwrap_or(""));
out
}
fn unquoted(line: &str, start: usize, end: usize) -> (usize, usize) {
let before = start.checked_sub(1);
let quoted = before
.and_then(|b| line.get(b..start))
.is_some_and(|c| c == "`")
&& line.get(end..).is_some_and(|r| r.starts_with('`'));
match before {
Some(b) if quoted => (b, end.saturating_add(1)),
_ => (start, end),
}
}
fn qualified(
token: &str,
prev: char,
here: &str,
homes: &std::collections::BTreeMap<String, String>,
) -> String {
if matches!(prev, '\0' | ':' | '/')
|| row_id(&format!("{token}:")).is_none()
{
return token.to_string();
}
match homes.get(token) {
Some(home) if home != here && prev == '`' => format!("{home}:{token}"),
Some(home) if home != here => format!("`{home}:{token}`"),
_ => token.to_string(),
}
}
#[cfg(test)]
#[path = "tests/row.rs"]
mod row_tests;