use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::cell::LazyCell;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use tree_sitter::Tree;
use crate::fallback;
use crate::follow::FollowIndex;
use crate::hash;
use crate::marker::{self, MarkerAddr};
use crate::model::Scan;
use crate::span_lang::{self, LangSpec};
use crate::write::WritePlan;
#[derive(Debug, Default)]
pub struct PinTexts(BTreeMap<String, String>);
impl PinTexts {
pub fn for_project(own: &Scan, projects: &crate::workspace::LawScans) -> Self {
let mut texts = PinTexts::default();
texts.add(&projects.own, false, own);
for (key, scan) in &projects.scans {
texts.add(key, true, scan);
}
texts.add(&projects.own, true, own);
texts
}
fn add(&mut self, project: &str, qualified: bool, scan: &Scan) {
let key = |addr: String| {
if qualified {
format!("{project}:{addr}")
} else {
addr
}
};
for law in &scan.laws {
let law_text = format!("{project}:{}\n{}", law.id, hash::pin_canon(&law.pin_text()));
let sentence = hash::pin_canon(&law.pin_text());
let clause_texts: Vec<(&String, String)> = law
.clauses
.iter()
.filter_map(|al| al.letter.as_ref().map(|letter| (letter, al)))
.map(|(letter, al)| {
let text = format!(
"{project}:{}.{letter}\n{sentence}\n§\n{}",
law.id,
hash::pin_canon(&al.pin_body())
);
(letter, text)
})
.collect();
for id in std::iter::once(&law.id).chain(&law.aliases) {
self.0.insert(key(id.clone()), law_text.clone());
for (letter, text) in &clause_texts {
self.0.insert(key(format!("{id}.{letter}")), text.clone());
}
}
}
}
pub fn with_sentences(
own: &Scan,
projects: &crate::workspace::LawScans,
project: &str,
sentences: &BTreeMap<String, String>,
) -> Self {
let mut own = own.clone();
let mut scans = projects.scans.clone();
let scan = if project == projects.own {
Some(&mut own)
} else {
scans.get_mut(project)
};
for law in scan.into_iter().flat_map(|scan| scan.laws.iter_mut()) {
if let Some(sentence) = sentences.get(&law.id) {
law.name = sentence.clone();
}
}
let projects = crate::workspace::LawScans {
own: projects.own.clone(),
scans,
};
Self::for_project(&own, &projects)
}
fn of(&self, pin: &MarkerAddr) -> Option<&str> {
self.0.get(&pin.display()).map(String::as_str)
}
#[cfg(test)]
pub fn empty_for(src: &str) -> Self {
PinTexts(
marker::markers_in_text(src)
.into_iter()
.map(|p| (p.display(), String::new()))
.collect(),
)
}
}
#[derive(Clone)]
pub struct CodeFile {
pub rel: PathBuf,
pub text: String,
pub lang: Option<&'static LangSpec>,
tree: OnceLock<Option<Tree>>,
entry: Option<Arc<crate::cache::Entry>>,
ends: marker::Ends,
extents: BTreeMap<usize, (usize, usize)>,
empty: std::collections::BTreeSet<usize>,
cfg_test: Vec<(usize, usize)>,
cfg_other: Vec<(usize, usize)>,
mods: Vec<(usize, String, Option<String>)>,
fenced: Vec<bool>,
deep: bool,
}
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Facts {
ends: marker::Ends,
extents: BTreeMap<usize, (usize, usize)>,
empty: std::collections::BTreeSet<usize>,
cfg_test: Vec<(usize, usize)>,
cfg_other: Vec<(usize, usize)>,
mods: Vec<(usize, String, Option<String>)>,
fenced: Vec<bool>,
deep: bool,
}
pub static PARSES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn parse(lang: Option<&LangSpec>, text: &str) -> Option<Tree> {
static TREES: crate::par::Shared<Option<Tree>> = OnceLock::new();
let lang = lang?;
let derive = || {
PARSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
span_lang::parse_source(lang, text)
};
if !text.contains('§') {
return derive();
}
let mut key = blake3::Hasher::new();
key.update(&(std::ptr::from_ref(lang) as usize).to_le_bytes());
key.update(text.as_bytes());
crate::par::shared(&TREES, key.finalize(), derive)
}
impl CodeFile {
pub fn new(rel: PathBuf, text: String) -> Self {
let lang = span_lang::lang_for_path(&rel);
let tree = OnceLock::new();
let entry = crate::cache::entry(&rel, &text);
let derive = || {
Facts::of(
&rel,
&text,
lang,
tree.get_or_init(|| parse(lang, &text)).as_ref(),
)
};
let facts = match &entry {
Some(entry) => entry.memo(&"file", derive),
None => derive(),
};
Self {
rel,
text,
lang,
tree,
entry,
ends: facts.ends,
extents: facts.extents,
empty: facts.empty,
cfg_test: facts.cfg_test,
cfg_other: facts.cfg_other,
mods: facts.mods,
fenced: facts.fenced,
deep: facts.deep,
}
}
pub fn tree(&self) -> Option<&Tree> {
self.tree
.get_or_init(|| parse(self.lang, &self.text))
.as_ref()
}
pub fn memo<Q, T>(&self, query: &Q, derive: impl FnOnce() -> T) -> T
where
Q: Serialize + std::fmt::Debug,
T: Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
{
match &self.entry {
Some(entry) => entry.memo(query, derive),
None => derive(),
}
}
}
impl Facts {
fn of(rel: &Path, text: &str, lang: Option<&'static LangSpec>, tree: Option<&Tree>) -> Self {
let deep = lang.is_some() && tree.is_none();
let fenced = unmarked_lines(rel, text, tree);
let ends = marker::explicit_ends_in(&fenced, text);
let extents = match (lang, &tree) {
(Some(lang), Some(tree)) => span_lang::marker_extents(lang, text, tree, &ends, &fenced),
(Some(_), None) => BTreeMap::new(),
(None, _) => fallback_extents(text, &ends, &fenced),
};
let empty = match (lang, &tree) {
(Some(lang), Some(tree)) => extents
.iter()
.filter(|&(_, &(start, end))| {
let nested: Vec<(usize, usize)> = extents
.values()
.copied()
.filter(|&inner| nests_in(inner, (start, end)))
.collect();
span_lang::span_is_empty(lang, text, tree, (start, end), &nested)
})
.map(|(&idx, _)| idx)
.collect(),
(Some(_), None) => Default::default(),
(None, _) => {
let lines: Vec<&str> = text.lines().collect();
let spans: BTreeMap<usize, (usize, usize)> = extents
.keys()
.map(|&idx| (idx, fallback_span(&lines, &ends, idx)))
.collect();
spans
.iter()
.filter(|&(&idx, &(start, end))| {
let nested: Vec<(usize, usize)> = spans
.iter()
.filter(|&(&other, &(_, e))| {
other != idx && other + 1 >= start && e <= end
})
.map(|(&other, &(_, e))| (other + 1, e))
.collect();
fallback::is_empty(extension(rel), text, (start, end), &nested)
})
.map(|(&idx, _)| idx)
.collect()
}
};
let mut cfg_test = Vec::new();
let mut cfg_other = Vec::new();
let mut mods = Vec::new();
if let (Some(lang), Some(tree)) = (lang, &tree) {
if lang.id == "rust" {
let (root, src) = (tree.root_node(), text.as_bytes());
collect_cfg(root, src, (&mut cfg_test, &mut cfg_other), &mut mods);
}
}
Self {
ends,
extents,
empty,
cfg_test,
cfg_other,
mods,
fenced,
deep,
}
}
}
impl CodeFile {
pub fn marker_lines(&self) -> impl Iterator<Item = (usize, &str)> {
self.text
.lines()
.enumerate()
.filter(|(idx, _)| !self.fenced[*idx])
}
pub fn read_all(root: &Path) -> Result<Vec<Self>> {
let mut read = Vec::new();
for path in crate::walk::code_files(root)? {
let text = std::fs::read_to_string(&path)?;
let rel = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
read.push((rel, text));
}
Ok(crate::par::map(
read,
|(_, text)| text.len(),
|(rel, text)| Self::new(rel, text),
))
}
pub fn span_markers(&self) -> Vec<SpanMarker> {
let mut out = Vec::new();
for (idx, line) in self.text.lines().enumerate() {
let Some(&(start, end)) = self.extents.get(&idx) else {
continue;
};
for addr in marker::markers_in_line(line) {
out.push(SpanMarker {
addr,
line: idx + 1,
start,
end,
explicit: self.ends.pairs.contains_key(&idx),
});
}
}
out
}
pub fn binding(&self, start: usize, end: usize) -> Option<Vec<String>> {
if !self.parsed() {
return None;
}
self.memo(&("binding", start, end), || self.binding_of(start, end))
}
fn binding_of(&self, start: usize, end: usize) -> Option<Vec<String>> {
let tree = self.tree()?;
let at = end.saturating_sub(1).max(start);
let mut node = tree.root_node().descendant_for_byte_range(at, at);
let mut names = Vec::new();
while let Some(n) = node {
if let Some(name) = n.child_by_field_name("name") {
names.push(
self.text
.get(name.start_byte()..name.end_byte())?
.to_string(),
);
}
node = n.parent();
}
names.reverse();
Some(names)
}
pub fn prefix(&self, start: usize, end: usize) -> Vec<span_lang::Stretch> {
let Some(lang) = self.lang.filter(|_| self.parsed()) else {
return Vec::new();
};
self.memo(&("prefix", (start, end)), || match self.tree() {
Some(tree) => span_lang::prefix_stretches(lang, &self.text, tree, (start, end)),
None => Vec::new(),
})
}
pub fn above(&self, start: usize, end: usize) -> Vec<span_lang::Stretch> {
match (self.lang, self.tree()) {
(Some(lang), Some(tree)) => span_lang::above_stretches(lang, tree, (start, end)),
_ => Vec::new(),
}
}
pub fn has_span(&self, idx: usize) -> bool {
self.extents.contains_key(&idx)
}
pub fn ends_on_one(&self) -> &[(usize, String)] {
&self.ends.on_one
}
pub fn is_pinnable(&self, idx: usize) -> bool {
self.lang.is_none() || self.extents.contains_key(&idx)
}
pub fn construct_below(&self, idx: usize) -> Option<(usize, Option<usize>)> {
if self.extents.contains_key(&idx) || marker::is_markdown(&self.rel) {
return None;
}
span_lang::construct_below(self.lang?, &self.text, self.tree()?, idx + 1)
}
pub fn is_empty_span(&self, idx: usize) -> bool {
self.empty.contains(&idx)
}
pub fn too_deep(&self) -> Option<String> {
self.deep.then(|| {
format!(
"{}: its syntax tree nests deeper than {} levels, which Silcrow does not read, so no pin in it or through it can be hashed. Flatten the code.",
self.rel.display(),
span_lang::MAX_DEPTH
)
})
}
pub fn parse_error(&self, idx: usize) -> Option<usize> {
let &(start, end) = self.extents.get(&idx)?;
self.hiding_error(start, end)
}
pub fn hiding_error(&self, start: usize, end: usize) -> Option<usize> {
if !self.memo(&"parse errors", || {
self.tree().is_some_and(|t| t.root_node().has_error())
}) {
return None;
}
self.memo(&("hiding error", start, end), || {
span_lang::hiding_error_line(&self.text, self.tree()?, start, end)
})
}
pub fn swallowing_items(&self) -> Vec<(usize, usize, usize)> {
if !self.memo(&"parse errors", || {
self.tree().is_some_and(|t| t.root_node().has_error())
}) {
return Vec::new();
}
self.memo(&"swallowing items", || {
self.tree()
.map(|tree| span_lang::swallowing_items(&self.text, tree))
.unwrap_or_default()
})
}
pub fn parsed(&self) -> bool {
self.lang.is_some() && !self.deep
}
fn pinned_lines(&self) -> Vec<usize> {
self.marker_lines()
.filter(|&(_, line)| line.contains('§'))
.filter(|&(_, line)| {
marker::markers_in_line(line)
.iter()
.any(|a| a.digest.is_some())
})
.map(|(idx, _)| idx)
.collect()
}
pub fn cfg_test_rows(&self) -> Vec<(usize, usize)> {
self.cfg_test.clone()
}
}
pub fn unmarked_lines(rel: &Path, text: &str, tree: Option<&Tree>) -> Vec<bool> {
let dialect = marker::Dialect::of(rel);
let markdown = dialect.is_markdown();
let mut out = marker::unmarked_lines(dialect, text);
if markdown || !text.contains('§') {
return out;
}
let literal = match span_lang::lang_for_path(rel) {
Some(lang) => match tree {
Some(tree) => span_lang::literal_lines(lang, text, tree),
None => {
let derive = || {
parse(Some(lang), text)
.map(|tree| span_lang::literal_lines(lang, text, &tree))
.unwrap_or_default()
};
crate::cache::memo(rel, text, &"literal lines", derive)
}
},
None => fallback::literal_lines(extension(rel), text),
};
for (line, literal) in out.iter_mut().zip(literal) {
*line |= literal;
}
out
}
pub struct MarkerRow<'a> {
pub idx: usize,
pub line: &'a str,
pub markers: Vec<MarkerAddr>,
pub end: Option<MarkerAddr>,
}
pub fn marker_rows<'a>(rel: &Path, text: &'a str, tree: Option<&Tree>) -> Vec<MarkerRow<'a>> {
if !text.contains('§') {
return Vec::new();
}
let unmarked = unmarked_lines(rel, text, tree);
text.lines()
.enumerate()
.filter(|&(idx, line)| !unmarked[idx] && line.contains('§'))
.filter_map(|(idx, line)| {
let markers = marker::markers_in_line(line);
let end = marker::end_in_line(line);
(!markers.is_empty() || end.is_some()).then_some(MarkerRow {
idx,
line,
markers,
end,
})
})
.collect()
}
pub fn literal_ranges(rel: &Path, text: &str) -> Vec<(usize, usize)> {
if marker::is_markdown(rel) {
return Vec::new();
}
match span_lang::lang_for_path(rel) {
Some(lang) => parse(Some(lang), text)
.map(|tree| span_lang::literal_ranges(lang, &tree))
.unwrap_or_default(),
None => fallback::literal_ranges(extension(rel), text),
}
}
pub fn lines_opening_in(text: &str, ranges: &[(usize, usize)]) -> Vec<bool> {
let mut at = 0;
text.split_inclusive('\n')
.map(|line| {
let opens = at + line.len() - line.trim_start().len();
at += line.len();
ranges.iter().any(|&(s, e)| s <= opens && opens < e)
})
.collect()
}
pub fn file_ends(rel: &Path, text: &str) -> marker::Ends {
marker::explicit_ends_in(&unmarked_lines(rel, text, None), text)
}
fn tested_extents(
lang: &LangSpec,
rel: &Path,
text: &str,
tree: &Tree,
) -> BTreeMap<usize, (usize, usize)> {
let unmarked = unmarked_lines(rel, text, Some(tree));
let ends = marker::explicit_ends_in(&unmarked, text);
span_lang::marker_extents(lang, text, tree, &ends, &unmarked)
}
pub fn test_rows(files: &[CodeFile]) -> BTreeMap<PathBuf, Vec<(usize, usize)>> {
let mut rows: BTreeMap<PathBuf, Vec<(usize, usize)>> = files
.iter()
.map(|file| (file.rel.clone(), file.cfg_test_rows()))
.filter(|(_, rows)| !rows.is_empty())
.collect();
let mut queue: Vec<(PathBuf, bool)> = Vec::new();
for file in files {
let gated = rows.get(&file.rel).cloned().unwrap_or_default();
for (row, name, attr) in mod_files(file) {
if gated.iter().any(|&(a, b)| a <= row && row <= b) {
queue.extend(mod_candidates(&file.rel, false, &name, attr));
}
}
}
whole_files(files, &mut rows, queue);
rows
}
pub fn cfg_rows(files: &[CodeFile]) -> BTreeMap<PathBuf, Vec<(usize, usize)>> {
let mut rows: BTreeMap<PathBuf, Vec<(usize, usize)>> = files
.iter()
.map(|file| (file.rel.clone(), file.cfg_other.clone()))
.filter(|(_, rows)| !rows.is_empty())
.collect();
let mut queue: Vec<(PathBuf, bool)> = Vec::new();
for file in files {
let gated = rows.get(&file.rel).cloned().unwrap_or_default();
for (row, name, attr) in mod_files(file) {
if gated.iter().any(|&(a, b)| a <= row && row <= b) {
queue.extend(mod_candidates(&file.rel, false, &name, attr));
}
}
}
whole_files(files, &mut rows, queue);
rows
}
fn mod_candidates(
path: &Path,
by_attr: bool,
name: &str,
attr: Option<String>,
) -> Vec<(PathBuf, bool)> {
let Some(dir) = path.parent() else {
return Vec::new();
};
if let Some(attr) = attr {
return vec![(normal(&dir.join(attr)), true)];
}
let root = path
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| ["mod.rs", "lib.rs", "main.rs"].contains(&n));
let children = if by_attr || root {
dir.to_path_buf()
} else {
dir.join(path.file_stem().unwrap_or_default())
};
vec![
(children.join(format!("{name}.rs")), false),
(children.join(name).join("mod.rs"), false),
]
}
fn whole_files(
files: &[CodeFile],
rows: &mut BTreeMap<PathBuf, Vec<(usize, usize)>>,
mut queue: Vec<(PathBuf, bool)>,
) {
let by_path: BTreeMap<&Path, &CodeFile> = files.iter().map(|f| (f.rel.as_path(), f)).collect();
let mut whole = std::collections::BTreeSet::new();
while let Some((path, by_attr)) = queue.pop() {
let Some(file) = by_path.get(path.as_path()) else {
continue;
};
if !whole.insert(path.clone()) {
continue;
}
for (_, name, attr) in mod_files(file) {
queue.extend(mod_candidates(&path, by_attr, &name, attr));
}
}
for path in whole {
let lines = by_path[path.as_path()].text.lines().count();
rows.insert(path, vec![(0, lines)]);
}
}
fn mod_files(file: &CodeFile) -> Vec<(usize, String, Option<String>)> {
file.mods.clone()
}
fn mod_item(node: tree_sitter::Node, src: &[u8]) -> Option<(usize, String, Option<String>)> {
if node.kind() != "mod_item" || node.child_by_field_name("body").is_some() {
return None;
}
let name = node
.child_by_field_name("name")
.and_then(|n| n.utf8_text(src).ok())?;
let mut attr = None;
let mut prev = node.prev_named_sibling();
while let Some(a) = prev.filter(|a| a.kind() == "attribute_item") {
let text: String = a
.utf8_text(src)
.unwrap_or("")
.chars()
.filter(|c| !c.is_whitespace())
.collect();
if let Some(path) = text
.strip_prefix("#[path=\"")
.and_then(|t| t.strip_suffix("\"]"))
{
attr = Some(path.to_string());
}
prev = a.prev_named_sibling();
}
Some((node.start_position().row, name.to_string(), attr))
}
fn normal(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for part in path.components() {
match part {
std::path::Component::CurDir => {}
std::path::Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
type Rows = Vec<(usize, usize)>;
fn collect_cfg(
node: tree_sitter::Node,
src: &[u8],
rows: (&mut Rows, &mut Rows),
mods: &mut Vec<(usize, String, Option<String>)>,
) {
let (test, other) = rows;
let children: Vec<_> = node.named_children(&mut node.walk()).collect();
for (i, child) in children.iter().enumerate() {
mods.extend(mod_item(*child, src));
let into = |predicate: String| match requires_test(&predicate) {
true => 0,
false => 1,
};
if child.kind() == "attribute_item" {
let side = cfg_predicate(child, src)
.map(into)
.or(is_test_attribute(child, src).then_some(0));
if let Some(side) = side {
let item = children[i + 1..].iter().find(|n| {
!matches!(
n.kind(),
"attribute_item" | "line_comment" | "block_comment"
)
});
if let Some(item) = item {
let rows = (child.start_position().row, item.end_position().row);
[&mut *test, &mut *other][side].push(rows);
}
}
}
if child.kind() == "inner_attribute_item" {
if let Some(side) = cfg_predicate(child, src).map(into) {
let gated = match node.parent() {
Some(item) if node.kind() == "declaration_list" => item,
_ => node,
};
let rows = (gated.start_position().row, gated.end_position().row);
[&mut *test, &mut *other][side].push(rows);
}
}
collect_cfg(*child, src, (&mut *test, &mut *other), mods);
}
}
fn is_test_attribute(attr: &tree_sitter::Node, src: &[u8]) -> bool {
let Some(text) = attr.utf8_text(src).ok() else {
return false;
};
let path: String = text
.trim_start_matches("#[")
.chars()
.take_while(|&c| c != '(' && c != ']')
.filter(|c| !c.is_whitespace())
.collect();
path == "test" || path.ends_with("::test")
}
fn cfg_predicate(attr: &tree_sitter::Node, src: &[u8]) -> Option<String> {
let text: String = attr
.utf8_text(src)
.ok()?
.chars()
.filter(|c| !c.is_whitespace())
.collect();
text.strip_prefix("#[cfg(")
.or_else(|| text.strip_prefix("#![cfg("))
.and_then(|rest| rest.strip_suffix(")]"))
.map(str::to_string)
}
fn requires_test(predicate: &str) -> bool {
if predicate == "test" {
return true;
}
let Some(terms) = predicate
.strip_prefix("all(")
.and_then(|rest| rest.strip_suffix(')'))
else {
return false;
};
let mut depth = 0usize;
let mut start = 0;
let mut found = false;
for (at, c) in terms.char_indices() {
match c {
'(' => depth += 1,
')' => depth = depth.saturating_sub(1),
',' if depth == 0 => {
found |= requires_test(&terms[start..at]);
start = at + 1;
}
_ => {}
}
}
found || requires_test(&terms[start..])
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SpanMarker {
pub addr: MarkerAddr,
pub line: usize,
pub start: usize,
pub end: usize,
pub explicit: bool,
}
#[derive(Debug, Default)]
pub struct FileCheck {
pub errors: Vec<String>,
pub drifts: Vec<Drift>,
pub warnings: Vec<String>,
pub verified: usize,
pub unhashable: std::collections::BTreeSet<usize>,
pub inert: std::collections::BTreeSet<usize>,
pub blocked: Vec<Blocked>,
}
#[cfg(test)]
impl FileCheck {
pub fn reported(&self) -> Vec<String> {
self.errors
.iter()
.cloned()
.chain(self.blocked.iter().map(|b| b.message.clone()))
.collect()
}
}
#[derive(Debug, Clone)]
pub struct Blocked {
pub at: PathBuf,
pub line: usize,
pub pin: String,
pub name: Option<String>,
pub message: String,
}
#[derive(Debug, Clone)]
pub struct Drift {
pub path: PathBuf,
pub line: usize,
pub pin: MarkerAddr,
pub bit: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PinnedMarker {
pub addr: MarkerAddr,
pub line: usize,
}
pub fn pinned_in_text(rel: &Path, text: &str, tree: Option<&Tree>) -> Vec<PinnedMarker> {
let mut out = Vec::new();
for row in marker_rows(rel, text, tree) {
for addr in row.markers {
if addr.digest.is_some() {
out.push(PinnedMarker {
addr,
line: row.idx + 1,
});
}
}
}
out
}
#[cfg(test)]
pub fn verify_file(path: &Path, text: &str, serialization: &str) -> FileCheck {
verify_file_follow(
&CodeFile::new(path.to_path_buf(), text.to_string()),
serialization,
&FollowIndex::default(),
&PinTexts::empty_for(text),
)
}
pub fn verify_file_follow(
file: &CodeFile,
serialization: &str,
follow: &FollowIndex,
texts: &PinTexts,
) -> FileCheck {
let path = file.rel.as_path();
let mut out = FileCheck::default();
if serialization != span_lang::SERIALIZATION {
out.errors.push(format!(
"{}: unknown span serialization `{serialization}`",
path.display()
));
return out;
}
for (idx, addr) in &file.ends.orphans {
out.errors.push(format!(
"{}:{}: `§ end {addr}` closes no marker of {addr} above it",
path.display(),
idx + 1
));
}
if let Some(lang) = file.lang {
verify_tested(file, lang, follow, texts, &mut out);
} else {
verify_fallback(file, texts, &mut out);
}
out
}
pub fn fallback_notices(root: &Path) -> anyhow::Result<Vec<String>> {
let mut out = Vec::new();
for path in crate::walk::code_files(root)? {
if span_lang::lang_for_path(&path).is_some() {
continue;
}
let text = std::fs::read_to_string(&path)?;
let rel = path.strip_prefix(root).unwrap_or(&path);
if marker_rows(rel, &text, None)
.iter()
.all(|row| row.markers.is_empty())
{
continue;
}
out.push(fallback::notice(rel, extension(rel)));
}
Ok(out)
}
fn extension(path: &Path) -> &str {
path.extension().and_then(|e| e.to_str()).unwrap_or("?")
}
fn verify_tested(
code: &CodeFile,
lang: &LangSpec,
follow: &FollowIndex,
texts: &PinTexts,
out: &mut FileCheck,
) {
let path = code.rel.as_path();
let pinned = code.pinned_lines();
let file = FileSpans {
source: &code.text,
tree: Parse::File(code),
extents: &code.extents,
pinned: &pinned,
shift: None,
};
if lang.id == "yaml" {
let duplicates = code.memo(&"yaml duplicate keys", || match code.tree() {
Some(tree) => {
let extents = code.extents.values().copied();
span_lang::yaml_duplicate_keys(lang, &code.text, tree, extents)
}
None => Vec::new(),
});
for (first, repeat, key) in duplicates {
out.errors.push(format!(
"{}:{repeat}: the key `{key}` repeats the one at line {first} in a mapping that holds or encloses a span, and YAML readers disagree on which one wins, most keeping the last: keep one.",
path.display()
));
}
}
for (idx, line) in code.marker_lines() {
if marker::is_one(line) && !code.has_span(idx) {
continue;
}
for pin in marker::markers_in_line(line) {
if let Some(blocked) = span_blocked(code, idx, &pin) {
out.blocked.push(blocked);
continue;
}
if code.is_empty_span(idx) {
out.errors.push(empty_span(path, idx, &pin));
continue;
}
if guards_nothing(code, lang, idx, &pin, follow)
&& callee_unparsed(path, &file, idx, &pin, follow).is_none()
{
out.errors.push(inert_span(path, idx, &pin));
out.inert.insert(idx);
continue;
}
if pin.digest.is_none() {
if texts.of(&pin).is_some() {
if let Some(blocked) = callee_blocked(path, &file, idx, &pin, follow) {
out.blocked.push(blocked);
out.unhashable.insert(idx);
}
}
continue;
}
let Some(addr_text) = texts.of(&pin) else {
out.errors.push(unknown_clause(path, idx, &pin));
continue;
};
if let Some(blocked) = callee_blocked(path, &file, idx, &pin, follow) {
out.blocked.push(blocked);
continue;
}
let Some(actual) = mint_pin_digests(lang, path, &file, idx, addr_text, follow) else {
out.errors.push(format!(
"{}:{}: could not delimit span for § {}",
path.display(),
idx + 1,
pin.display()
));
continue;
};
if let Some(expected) = &pin.digest {
if &actual != expected {
out.drifts.push(Drift::at(path, idx, line, &pin));
out.warnings
.extend(follow.drift_notice(path, idx + 1, &pin.display()));
} else {
out.verified += 1;
}
}
}
}
}
impl Drift {
fn at(path: &Path, idx: usize, line: &str, pin: &MarkerAddr) -> Self {
Self {
path: path.to_path_buf(),
line: idx + 1,
pin: pin.clone(),
bit: line.trim().to_string(),
}
}
pub fn message(&self, cause: Option<&str>) -> String {
self.message_since(cause, "the last commit that held this pin")
}
pub fn message_since(&self, cause: Option<&str>, since: &str) -> String {
let addr = self.pin.display();
let pinned = self.pin.digest.as_deref().unwrap_or_default();
let reads = match cause {
Some(cause) => format!("{cause} since {since}. "),
None if span_lang::lang_for_path(&self.path).is_some_and(|l| l.id == "yaml") => {
"its span, the keys or entries above it, its law or clause text or its project path reads otherwise. ".to_string()
}
None => "its span, a followed callee, its law or clause text or its project path reads otherwise. ".to_string(),
};
format!(
concat!(
"{}:{}: § {addr} changed since its pin @{pinned}: {reads}",
"Read it against its law or clause with `silcrow diff --law {addr}`, then accept it with the other drifts you read, in one `silcrow accept <address>...`.",
),
self.path.display(),
self.line,
addr = addr,
pinned = pinned,
reads = reads,
)
}
}
fn empty_span(path: &Path, idx: usize, pin: &MarkerAddr) -> String {
format!(
"{}:{}: § {} opens an empty span: no statement carries out its law or clause. Move the marker into the construct that does.",
path.display(),
idx + 1,
pin.display()
)
}
fn guards_nothing(
code: &CodeFile,
lang: &LangSpec,
idx: usize,
pin: &MarkerAddr,
follow: &FollowIndex,
) -> bool {
let Some(&(start, end)) = code.extents.get(&idx) else {
return false;
};
if !code.parsed() {
return false;
}
let nested: Vec<(usize, usize)> = code
.extents
.iter()
.filter(|&(&other, &inner)| other != idx && nests_in(inner, (start, end)))
.map(|(_, &inner)| inner)
.collect();
let names = code.memo(&("only called names", start, end, &nested), || {
let tree = code.tree()?;
span_lang::only_called_names(lang, &code.text, tree, (start, end), &nested)
});
names.is_some_and(|names| names.iter().all(|name| follow.declares(lang, name)))
&& !follow.follows_any(&code.rel, start, end, &nested)
&& !follow.calls_boundary_of(&code.rel, start, end, &nested, pin)
}
fn inert_span(path: &Path, idx: usize, pin: &MarkerAddr) -> String {
format!(
"{}:{}: § {} guards nothing: every statement of its span is a call its pin does not follow, to a name the project declares, with only names as its receivers and arguments, so an edit of the code that acts moves no pin. Move the marker onto the code that acts, or put `// silcrow:follow` on the line above the call so the pin reads its body.",
path.display(),
idx + 1,
pin.display()
)
}
fn unknown_clause(path: &Path, idx: usize, pin: &MarkerAddr) -> String {
format!(
"{}:{}: § {} pins an address no note declares",
path.display(),
idx + 1,
pin.display()
)
}
fn verify_fallback(file: &CodeFile, texts: &PinTexts, out: &mut FileCheck) {
let (path, text) = (file.rel.as_path(), file.text.as_str());
if file
.marker_lines()
.all(|(_, line)| marker::markers_in_line(line).is_empty())
{
return;
}
out.warnings.push(fallback::notice(path, extension(path)));
let lines: Vec<&str> = text.lines().collect();
for (idx, line) in file.marker_lines() {
if marker::is_one(line) {
continue;
}
for pin in marker::markers_in_line(line) {
if file.is_empty_span(idx) {
out.errors.push(empty_span(path, idx, &pin));
continue;
}
let Some(expected) = &pin.digest else {
continue;
};
let Some(addr_text) = texts.of(&pin) else {
out.errors.push(unknown_clause(path, idx, &pin));
continue;
};
let Some(actual) = mint_fallback_digest(path, text, &lines, idx, addr_text) else {
out.errors.push(format!(
"{}:{}: could not delimit span for § {}",
path.display(),
idx + 1,
pin.display()
));
continue;
};
if &actual != expected {
out.drifts.push(Drift::at(path, idx, line, &pin));
}
}
}
}
type LazyFollow = LazyCell<Arc<FollowIndex>, Box<dyn FnOnce() -> Arc<FollowIndex>>>;
fn lazy_follow(root: &Path) -> Result<LazyFollow> {
let sources = FollowIndex::sources(root)?;
let tests = crate::policy::TestPaths::at(root)?;
Ok(LazyCell::new(Box::new(move || {
shared_follow(sources, tests)
})))
}
fn shared_follow(
sources: Vec<(PathBuf, String)>,
tests: crate::policy::TestPaths,
) -> Arc<FollowIndex> {
type Built = (
Vec<(PathBuf, String)>,
crate::policy::TestPaths,
Arc<FollowIndex>,
);
static LAST: Mutex<Option<Built>> = Mutex::new(None);
let mut last = LAST.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some((s, t, index)) = last.as_ref() {
if *s == sources && *t == tests {
return Arc::clone(index);
}
}
let index = Arc::new(FollowIndex::from_sources(&sources, &tests));
*last = Some((sources, tests, Arc::clone(&index)));
index
}
fn any_marker(text: &str, want: impl Fn(&MarkerAddr) -> bool) -> bool {
text.lines()
.flat_map(marker::markers_in_line)
.any(|pin| want(&pin))
}
pub type PinTokens = BTreeMap<(usize, String), String>;
pub struct TreeTokens {
follow: FollowIndex,
texts: PinTexts,
}
impl TreeTokens {
pub fn new(root: &Path, texts: PinTexts) -> Result<Self> {
Ok(Self {
follow: FollowIndex::from_sources(
&FollowIndex::sources(root)?,
&crate::policy::TestPaths::at(root)?,
),
texts,
})
}
pub fn tokens(&self, rel: &Path, text: &str) -> PinTokens {
self.tokens_of_staged(rel, text, text)
}
fn tokens_of_staged(&self, rel: &Path, text: &str, indexed: &str) -> PinTokens {
let lines: Vec<&str> = text.lines().collect();
let mut out = PinTokens::new();
let Some(lang) = span_lang::lang_for_path(rel) else {
let unmarked = unmarked_lines(rel, text, None);
for (idx, line) in lines.iter().enumerate() {
if unmarked[idx] {
continue;
}
for pin in marker::markers_in_line(line) {
let digest = self
.texts
.of(&pin)
.and_then(|t| mint_fallback_digest(rel, text, &lines, idx, t));
if let Some(digest) = digest {
out.insert((idx, pin.display()), digest);
}
}
}
return out;
};
let Some(tree) = parse(Some(lang), text) else {
return out;
};
let extents = tested_extents(lang, rel, text, &tree);
let pinned = pinned_lines(rel, text, Some(&tree));
let shift = Shift::between(indexed, text);
let file = FileSpans {
source: text,
tree: Parse::Tree(Some(&tree)),
extents: &extents,
pinned: &pinned,
shift: shift.as_ref(),
};
for (idx, line) in lines.iter().enumerate() {
for pin in marker::markers_in_line(line) {
let token = self
.texts
.of(&pin)
.and_then(|t| mint_pin_digests(lang, rel, &file, idx, t, &self.follow));
if let Some(token) = token {
out.insert((idx, pin.display()), token);
}
}
}
out
}
pub fn followed_files(
&self,
rel: &Path,
text: &str,
) -> BTreeMap<(usize, String), std::collections::BTreeSet<PathBuf>> {
let mut out = BTreeMap::new();
let Some(lang) = span_lang::lang_for_path(rel) else {
return out;
};
let Some(tree) = parse(Some(lang), text) else {
return out;
};
let extents = tested_extents(lang, rel, text, &tree);
let pinned = pinned_lines(rel, text, Some(&tree));
let file = FileSpans {
source: text,
tree: Parse::Tree(Some(&tree)),
extents: &extents,
pinned: &pinned,
shift: None,
};
for (idx, line) in text.lines().enumerate() {
let Some(&(start, end)) = extents.get(&idx) else {
continue;
};
let punch = inner_punch_ranges(&extents, &pinned, idx);
let prefix = file.indexed_prefix(lang, (start, end));
let paths: std::collections::BTreeSet<PathBuf> = self
.follow
.followed_callees(rel, start, end, &punch, &prefix)
.into_iter()
.map(|callee| callee.path)
.collect();
for pin in marker::markers_in_line(line) {
out.insert((idx, pin.display()), paths.clone());
}
}
out
}
}
pub type HeldSince<'a> =
dyn Fn(&Path, &str, &str, &std::collections::BTreeSet<PathBuf>) -> Result<bool> + 'a;
pub type Remint = (WritePlan, Vec<(String, String)>, Vec<String>);
pub fn remint_digests(
root: &Path,
head: &Path,
at_head: &TreeTokens,
now: &TreeTokens,
reads_moved: &dyn Fn(&Path) -> bool,
held_since: &HeldSince<'_>,
) -> Result<Remint> {
let mut writes = Vec::new();
let mut drifted = Vec::new();
let mut reminted = Vec::new();
for path in crate::walk::code_files(root)? {
let rel = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
if !reads_moved(&rel) {
continue;
}
let text = std::fs::read_to_string(&path)?;
let was = match std::fs::read_to_string(head.join(&rel)) {
Ok(was) => was,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(e.into()),
};
let followed = at_head.followed_files(&rel, &was);
let none = std::collections::BTreeSet::new();
let (next, held, rewritten) = remint_file(
&text,
&now.tokens(&rel, &text),
&was,
&at_head.tokens(&rel, &was),
&|idx, addr, written| {
let files = followed.get(&(idx, addr.to_string())).unwrap_or(&none);
held_since(&rel, addr, written, files)
},
)?;
for (idx, addr) in held {
let at = format!("{}:{}: § {addr}", rel.display(), idx + 1);
drifted.push((at, addr));
}
let file = CodeFile::new(rel.clone(), text.clone());
for (idx, addr) in rewritten {
let extent = crate::stats::extent_at(&file, &now.follow, idx + 1);
reminted.push(reminted_line(&rel, idx + 1, &addr, extent));
}
if let Some(next) = next {
writes.push((rel, next));
}
}
Ok((WritePlan { writes }, drifted, reminted))
}
pub fn reminted_line(
rel: &Path,
line: usize,
addr: &str,
extent: Option<(usize, usize)>,
) -> String {
let reads = match extent {
Some((bytes, bodies)) => {
format!(", and it reads {bytes} byte(s) and {bodies} followed body(ies) now")
}
None => String::new(),
};
format!(
"{}:{line}: § {addr} was reminted: the hashing scheme reads its span, the code before it or a body it follows otherwise{reads}. Read it against its law or clause.",
rel.display()
)
}
type Reminted = (Option<String>, Vec<(usize, String)>, Vec<(usize, String)>);
fn remint_file(
text: &str,
now: &PinTokens,
head: &str,
at_head: &PinTokens,
held_at_head: &dyn Fn(usize, &str, &str) -> Result<bool>,
) -> Result<Reminted> {
let was = ranked_pins(head, at_head);
let mut rewrite = BTreeMap::new();
let mut held = Vec::new();
for (key, (idx, written, token)) in ranked_pins(text, now) {
let Some(token) = token else {
continue;
};
if token == written {
continue;
}
match was.get(&key) {
Some((at, w, Some(t)))
if *w == written && *t == token && held_at_head(*at, &key.0, w)? =>
{
rewrite.insert((idx, key.0), token);
}
_ => held.push((idx, key.0)),
}
}
held.sort();
let next = remint_lines(text, |_, idx, pin| {
rewrite
.get(&(idx, pin.display()))
.map(|token| format!("@{token}"))
});
Ok((next, held, rewrite.into_keys().collect()))
}
fn ranked_pins(
text: &str,
tokens: &PinTokens,
) -> BTreeMap<(String, usize), (usize, String, Option<String>)> {
let mut out = BTreeMap::new();
let mut rank: BTreeMap<String, usize> = BTreeMap::new();
for (idx, line) in text.lines().enumerate() {
for pin in marker::markers_in_line(line) {
let Some((addr, written)) = pin.split_digest() else {
continue;
};
let addr = addr.display();
let n = rank.entry(addr.clone()).or_default();
let token = tokens.get(&(idx, addr.clone())).cloned();
out.insert((addr, *n), (idx, written, token));
*n += 1;
}
}
out
}
fn remint_tested_text(
lang: &LangSpec,
path: &Path,
text: &str,
indexed: &str,
follow: &LazyFollow,
texts: &PinTexts,
only: &dyn Fn(&MarkerAddr) -> bool,
) -> Option<String> {
if !any_marker(text, |pin| {
pin.digest.is_some() && only(pin) && texts.of(pin).is_some()
}) {
return None;
}
let tree = parse(Some(lang), text)?;
let extents = tested_extents(lang, path, text, &tree);
let pinned = pinned_lines(path, text, Some(&tree));
let shift = Shift::between(indexed, text);
let file = FileSpans {
source: text,
tree: Parse::Tree(Some(&tree)),
extents: &extents,
pinned: &pinned,
shift: shift.as_ref(),
};
remint_lines(text, |_, idx, pin| {
if !only(pin) {
return None;
}
let addr_text = texts.of(pin)?;
let follow = LazyCell::force(follow);
let shape = mint_pin_digests(lang, path, &file, idx, addr_text, follow)?;
Some(format!("@{shape}"))
})
}
fn remint_fallback_text(
path: &Path,
text: &str,
texts: &PinTexts,
only: &dyn Fn(&MarkerAddr) -> bool,
) -> Option<String> {
remint_lines(text, |lines, idx, pin| {
if !only(pin) || marker::is_one(lines[idx]) {
return None;
}
let addr_text = texts.of(pin)?;
let digest = mint_fallback_digest(path, text, lines, idx, addr_text)?;
Some(format!("@{digest}"))
})
}
const PLACEHOLDER: &str = "00000";
pub fn pin_bare(
root: &Path,
texts: &PinTexts,
only: Option<&[std::path::PathBuf]>,
) -> Result<WritePlan> {
let mut writes = Vec::new();
let follow = lazy_follow(root)?;
for path in crate::walk::code_files(root)? {
let lang = span_lang::lang_for_path(&path);
let rel = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
if only.is_some_and(|paths| !paths.contains(&rel)) {
continue;
}
let text = std::fs::read_to_string(&path)?;
if let Some(next) = pin_bare_text(lang, &rel, &text, &follow, texts, &|_| true) {
writes.push((rel, next));
}
}
Ok(WritePlan { writes })
}
pub struct DriftedBare {
pub rel: PathBuf,
pub line: usize,
pub addr: MarkerAddr,
pub held: Vec<String>,
pub now: String,
}
impl DriftedBare {
pub fn held_digests(&self) -> String {
let held: Vec<String> = self.held.iter().map(|d| format!("@{d}")).collect();
held.join(", ")
}
}
pub fn drifted_bare(root: &Path, plan: &WritePlan) -> Result<Vec<DriftedBare>> {
if plan.writes.is_empty() {
return Ok(Vec::new());
}
let head = crate::workspace::git(root)
.args(["rev-parse", "--verify", "-q", "HEAD"])
.output()
.is_ok_and(|out| out.status.success());
if !head {
return Ok(Vec::new());
}
let held = crate::published::pinned_at(root, "HEAD")?;
let renamed = crate::diff::touched(root, "HEAD")?;
let mut out = Vec::new();
for (rel, next) in &plan.writes {
let was = std::fs::read_to_string(root.join(rel))?;
let mut kept: BTreeMap<MarkerAddr, Vec<String>> = BTreeMap::new();
let mut bare_at: BTreeMap<usize, Vec<MarkerAddr>> = BTreeMap::new();
for row in marker_rows(rel, &was, None) {
for pin in row.markers {
match pin.clone().split_digest() {
Some((addr, digest)) => kept.entry(addr).or_default().push(digest),
None => bare_at.entry(row.idx).or_default().push(pin),
}
}
}
let mut pinned: BTreeMap<MarkerAddr, Vec<(usize, String)>> = BTreeMap::new();
for row in marker_rows(rel, next, None) {
let Some(bare) = bare_at.get(&row.idx) else {
continue;
};
for (addr, now) in row.markers.into_iter().filter_map(|m| m.split_digest()) {
if bare.contains(&addr) {
pinned.entry(addr).or_default().push((row.idx, now));
}
}
}
for (addr, bare) in pinned {
let mut lost: Vec<String> = held
.get(&addr)
.into_iter()
.flatten()
.flat_map(|(digest, paths)| {
paths
.iter()
.filter(|p| renamed.get(*p).unwrap_or(p) == rel)
.map(move |_| digest.clone())
})
.collect();
for digest in kept.get(&addr).into_iter().flatten() {
if let Some(at) = lost.iter().position(|d| d == digest) {
lost.remove(at);
}
}
let mut unmatched = Vec::new();
for (idx, now) in bare {
match lost.iter().position(|d| *d == now) {
Some(at) => {
lost.remove(at);
}
None => unmatched.push((idx, now)),
}
}
if lost.is_empty() {
continue;
}
for (idx, now) in unmatched {
out.push(DriftedBare {
rel: rel.clone(),
line: idx + 1,
addr: addr.clone(),
held: lost.clone(),
now,
});
}
}
}
Ok(out)
}
pub fn leave_bare(root: &Path, plan: WritePlan, drifted: &[DriftedBare]) -> Result<WritePlan> {
let mut writes = Vec::new();
for (rel, next) in plan.writes {
let mut lines: Vec<String> = next.lines().map(str::to_string).collect();
for d in drifted.iter().filter(|d| d.rel == rel) {
let pinned = format!("{}@{}", d.addr.display(), d.now);
if let Some(line) = lines.get_mut(d.line - 1) {
*line = line.replacen(&pinned, &d.addr.display(), 1);
}
}
let mut text = lines.join("\n");
if next.ends_with('\n') {
text.push('\n');
}
if text != std::fs::read_to_string(root.join(&rel))? {
writes.push((rel, text));
}
}
Ok(WritePlan { writes })
}
fn pin_bare_text(
lang: Option<&LangSpec>,
path: &Path,
text: &str,
follow: &LazyFollow,
texts: &PinTexts,
pin_it: &dyn Fn(&MarkerAddr) -> bool,
) -> Option<String> {
if !any_marker(text, |pin| {
pin.digest.is_none() && texts.of(pin).is_some() && pin_it(pin)
}) {
return None;
}
let lines: Vec<&str> = text.lines().collect();
let tree = parse(lang, text);
let extents = match (lang, &tree) {
(Some(lang), Some(tree)) => tested_extents(lang, path, text, tree),
_ => BTreeMap::new(),
};
let unmarked = unmarked_lines(path, text, tree.as_ref());
let pinnable = |idx: usize| {
(lang.is_none() && !unmarked[idx] && !marker::is_one(lines[idx]))
|| extents.get(&idx).is_some_and(|&(start, end)| {
tree.as_ref().is_some_and(|tree| {
span_lang::hiding_error_line(text, tree, start, end).is_none()
})
})
};
let joined = stage_bare(text, |idx, pin| {
texts.of(pin).is_some() && pinnable(idx) && pin_it(pin)
})?;
let minted = match lang {
Some(lang) => remint_tested_text(lang, path, &joined, text, follow, texts, &is_staged),
None => remint_fallback_text(path, &joined, texts, &is_staged),
}
.unwrap_or(joined);
unstage(&minted, text)
}
fn stage_bare(text: &str, stage: impl Fn(usize, &MarkerAddr) -> bool) -> Option<String> {
let mut changed = false;
let mut staged = Vec::new();
for (idx, line) in text.lines().enumerate() {
let mut next = line.to_string();
for pin in marker::markers_in_line(line) {
if pin.digest.is_some() || !stage(idx, &pin) {
continue;
}
if let Some(n) = insert_at_token(&next, &pin, PLACEHOLDER) {
next = n;
changed = true;
}
}
staged.push(next);
}
if !changed {
return None;
}
let mut joined = staged.join("\n");
if text.ends_with('\n') {
joined.push('\n');
}
Some(joined)
}
fn is_staged(pin: &MarkerAddr) -> bool {
pin.digest.as_deref() == Some(PLACEHOLDER)
}
fn unstage(minted: &str, text: &str) -> Option<String> {
let tag = format!("@{PLACEHOLDER}");
let mut kept = false;
let mut out: Vec<String> = Vec::new();
for (now, was) in minted.lines().zip(text.lines()) {
let left = marker::markers_in_line(now).iter().any(is_staged) && !was.contains(&tag);
let line = match left {
true => now.replace(&tag, ""),
false => now.to_string(),
};
kept |= line != was;
out.push(line);
}
if !kept {
return None;
}
let mut out = out.join("\n");
if text.ends_with('\n') {
out.push('\n');
}
Some(out)
}
fn insert_at_token(line: &str, pin: &MarkerAddr, tok: &str) -> Option<String> {
let w = marker::written(line)
.into_iter()
.find(|w| w.addr.digest.is_none() && w.addr.display() == pin.display())?;
Some(format!("{}@{tok}{}", &line[..w.at], &line[w.at..]))
}
pub fn held_pins(
root: &Path,
texts: PinTexts,
of: &dyn Fn(&MarkerAddr) -> bool,
) -> Result<std::collections::BTreeSet<(PathBuf, usize)>> {
let mut out = std::collections::BTreeSet::new();
let files: Vec<(PathBuf, String)> = crate::walk::code_files(root)?
.into_iter()
.map(|path| {
let text = std::fs::read_to_string(&path)?;
Ok((path.strip_prefix(root).unwrap_or(&path).to_path_buf(), text))
})
.collect::<Result<_>>()?;
if !files.iter().any(|(_, text)| any_marker(text, of)) {
return Ok(out);
}
let tree = TreeTokens::new(root, texts)?;
for (rel, text) in &files {
if !any_marker(text, of) {
continue;
}
let tokens = tree.tokens(rel, text);
for (idx, line) in text.lines().enumerate() {
for pin in marker::markers_in_line(line).into_iter().filter(|p| of(p)) {
let written = pin.clone().split_digest().map(|(_, d)| d);
if written.is_some() && tokens.get(&(idx, pin.display())) == written.as_ref() {
out.insert((rel.clone(), idx));
}
}
}
}
Ok(out)
}
pub fn repin_at(
root: &Path,
texts: PinTexts,
at: &std::collections::BTreeSet<(PathBuf, usize)>,
of: &dyn Fn(&MarkerAddr) -> bool,
) -> Result<WritePlan> {
let mut writes = Vec::new();
if at.is_empty() {
return Ok(WritePlan { writes });
}
let tree = TreeTokens::new(root, texts)?;
let files: std::collections::BTreeSet<&PathBuf> = at.iter().map(|(rel, _)| rel).collect();
for rel in files {
let text = std::fs::read_to_string(root.join(rel))?;
let taken = |idx: usize, pin: &MarkerAddr| at.contains(&(rel.clone(), idx)) && of(pin);
let staged = stage_bare(&text, taken).unwrap_or_else(|| text.clone());
let tokens = tree.tokens_of_staged(rel, &staged, &text);
let minted = remint_lines(&staged, |_, idx, pin| {
if !taken(idx, pin) {
return None;
}
tokens.get(&(idx, pin.display())).map(|t| format!("@{t}"))
})
.unwrap_or(staged);
if let Some(next) = unstage(&minted, &text) {
writes.push((rel.clone(), next));
}
}
Ok(WritePlan { writes })
}
pub fn unpinned(
root: &Path,
texts: &PinTexts,
of: &dyn Fn(&MarkerAddr) -> bool,
) -> Result<Vec<(PathBuf, usize, String)>> {
let mut out = Vec::new();
for (rel, next) in repin_where(root, texts, of)?.writes {
let text = std::fs::read_to_string(root.join(&rel))?;
for (idx, (was, now)) in text.lines().zip(next.lines()).enumerate() {
let now = marker::markers_in_line(now);
for (old, new) in marker::markers_in_line(was).iter().zip(&now) {
if of(old) && old.digest != new.digest {
out.push((rel.clone(), idx + 1, old.display()));
}
}
}
}
Ok(out)
}
pub fn repin_where(
root: &Path,
texts: &PinTexts,
of_addr: &dyn Fn(&MarkerAddr) -> bool,
) -> Result<WritePlan> {
let mut writes = Vec::new();
let follow = lazy_follow(root)?;
for path in crate::walk::code_files(root)? {
let text = std::fs::read_to_string(&path)?;
let rel = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
let lang = span_lang::lang_for_path(&path);
let pinned = pin_bare_text(lang, &rel, &text, &follow, texts, of_addr);
let base = pinned.as_deref().unwrap_or(&text);
let reminted = match lang {
Some(lang) => remint_tested_text(lang, &rel, base, &text, &follow, texts, of_addr),
None => remint_fallback_text(&rel, base, texts, of_addr),
};
if let Some(next) = reminted.or(pinned) {
writes.push((rel, next));
}
}
Ok(WritePlan { writes })
}
fn remint_lines(
text: &str,
mint_tok: impl Fn(&[&str], usize, &MarkerAddr) -> Option<String>,
) -> Option<String> {
let lines: Vec<&str> = text.lines().collect();
let mut changed = false;
let mut out = Vec::new();
for (idx, line) in lines.iter().enumerate() {
let mut next_line = line.to_string();
for pin in marker::markers_in_line(line) {
if pin.digest.is_none() {
continue;
}
let Some(new_tok) = mint_tok(&lines, idx, &pin) else {
continue;
};
if let Some(replaced) = replace_at_token(&next_line, &pin, &new_tok) {
next_line = replaced;
changed = true;
}
}
out.push(next_line);
}
if !changed {
return None;
}
let mut joined = out.join("\n");
if text.ends_with('\n') {
joined.push('\n');
}
Some(joined)
}
fn replace_at_token(line: &str, pin: &MarkerAddr, new_tok: &str) -> Option<String> {
pin.digest.as_ref()?;
let w = marker::written(line).into_iter().find(|w| w.addr == *pin)?;
let digest = w.digest?;
let at = digest.start - 1;
if line[at..digest.end] == *new_tok {
return None;
}
let mut out = String::with_capacity(line.len());
out.push_str(&line[..at]);
out.push_str(new_tok);
out.push_str(&line[digest.end..]);
Some(out)
}
struct FileSpans<'a> {
source: &'a str,
tree: Parse<'a>,
extents: &'a BTreeMap<usize, (usize, usize)>,
pinned: &'a [usize],
shift: Option<&'a Shift>,
}
#[derive(Clone, Copy)]
enum Parse<'a> {
Tree(Option<&'a Tree>),
File(&'a CodeFile),
}
impl<'a> Parse<'a> {
fn tree(self) -> Option<&'a Tree> {
match self {
Parse::Tree(tree) => tree,
Parse::File(file) => file.tree(),
}
}
fn parsed(self) -> bool {
match self {
Parse::Tree(tree) => tree.is_some(),
Parse::File(file) => file.parsed(),
}
}
fn memo<Q, T>(self, query: &Q, derive: impl FnOnce(&Tree) -> T) -> Option<T>
where
Q: Serialize + std::fmt::Debug,
T: Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
{
match self {
Parse::Tree(tree) => tree.map(derive),
Parse::File(file) => {
file.parsed()
.then(|| file.memo(query, || derive(file.tree().expect("a parsed file"))))
}
}
}
}
impl FileSpans<'_> {
fn hiding_error(&self, (start, end): (usize, usize)) -> Option<usize> {
match self.tree {
Parse::Tree(tree) => span_lang::hiding_error_line(self.source, tree?, start, end),
Parse::File(file) => file.hiding_error(start, end),
}
}
fn indexed_prefix(&self, lang: &LangSpec, extent: (usize, usize)) -> Vec<span_lang::Stretch> {
let to_index = |at: usize| self.shift.map_or(at, |shift| shift.map(at));
self.tree
.memo(&("prefix", extent), |tree| {
span_lang::prefix_stretches(lang, self.source, tree, extent)
})
.unwrap_or_default()
.into_iter()
.map(|(s, e, holes)| {
let holes = holes
.into_iter()
.map(|(a, b)| (to_index(a), to_index(b)))
.collect();
(to_index(s), to_index(e), holes)
})
.collect()
}
}
struct Shift {
lines: Vec<(usize, usize, usize, isize)>,
}
impl Shift {
fn between(original: &str, rewritten: &str) -> Option<Self> {
if original == rewritten {
return None;
}
let (old, new): (Vec<&str>, Vec<&str>) = (
original.split_inclusive('\n').collect(),
rewritten.split_inclusive('\n').collect(),
);
assert_eq!(
old.len(),
new.len(),
"a marker rewrite keeps the line count"
);
let (mut at_old, mut at_new) = (0, 0);
let mut lines = Vec::with_capacity(new.len());
for (o, n) in old.iter().zip(&new) {
let prefix = o.bytes().zip(n.bytes()).take_while(|(a, b)| a == b).count();
lines.push((at_new, at_old, prefix, n.len() as isize - o.len() as isize));
at_old += o.len();
at_new += n.len();
}
Some(Self { lines })
}
fn map(&self, at: usize) -> usize {
let row = self.lines.partition_point(|&(start, ..)| start <= at);
let Some(&(new_start, old_start, prefix, delta)) =
row.checked_sub(1).map(|r| &self.lines[r])
else {
return at;
};
let col = at - new_start;
if col <= prefix {
old_start + col
} else {
(old_start as isize + col as isize - delta) as usize
}
}
}
fn pinned_lines(rel: &Path, text: &str, tree: Option<&Tree>) -> Vec<usize> {
pinned_in_text(rel, text, tree)
.iter()
.map(|p| p.line - 1)
.collect()
}
fn mint_pin_digests(
lang: &LangSpec,
path: &Path,
file: &FileSpans<'_>,
marker_idx: usize,
addr_text: &str,
follow: &FollowIndex,
) -> Option<String> {
let punch = inner_punch_ranges(file.extents, file.pinned, marker_idx);
let &(start, end) = file.extents.get(&marker_idx)?;
if !file.tree.parsed() || file.hiding_error((start, end)).is_some() {
return None;
}
let to_index = |at: usize| file.shift.map_or(at, |shift| shift.map(at));
let indexed: Vec<(usize, usize)> = punch
.iter()
.map(|&(s, e)| (to_index(s), to_index(e)))
.collect();
let (from, to) = (to_index(start), to_index(end));
let prefix = file.indexed_prefix(lang, (start, end));
if follow
.broken_callee(path, from, to, &indexed, &prefix)
.is_some()
{
return None;
}
let names = follow.name_tokens(path, from, to, &indexed, &prefix);
let shape_of = |tree: &Tree| {
span_lang::pin_shape(lang, file.source, tree, (start, end), &punch, &|at| {
names.get(&to_index(at)).cloned()
})
};
let shape = match (file.shift, file.tree) {
(None, parse) => {
let mut named: Vec<(&usize, &String)> = names.iter().collect();
named.sort();
parse.memo(&("pin shape", (start, end), &punch, &named), shape_of)?
}
(Some(_), parse) => parse.tree().map(shape_of)?,
};
let blob = follow.pin_blob(path, from, to, &indexed, &prefix);
Some(span_lang::encode_digest(&format!(
"{shape}{blob}\n§{addr_text}"
)))
}
fn span_unparsed(code: &CodeFile, idx: usize, pin: &MarkerAddr) -> Option<String> {
span_blocked(code, idx, pin).map(|b| b.message)
}
fn span_blocked(code: &CodeFile, idx: usize, pin: &MarkerAddr) -> Option<Blocked> {
let at = code.parse_error(idx)?;
Some(Blocked {
at: code.rel.clone(),
line: at,
pin: format!("{}:{}: § {}", code.rel.display(), idx + 1, pin.display()),
name: None,
message: format!(
"{}:{}: § {} cannot be hashed: its file does not parse with the tree-sitter grammar at line {at} (a syntax error, or syntax the grammar does not know), which can hide a declaration the span reads.",
code.rel.display(),
idx + 1,
pin.display()
),
})
}
fn callee_unparsed(
path: &Path,
file: &FileSpans<'_>,
idx: usize,
pin: &MarkerAddr,
follow: &FollowIndex,
) -> Option<String> {
callee_blocked(path, file, idx, pin, follow).map(|b| b.message)
}
fn callee_blocked(
path: &Path,
file: &FileSpans<'_>,
idx: usize,
pin: &MarkerAddr,
follow: &FollowIndex,
) -> Option<Blocked> {
let broken = broken_callee(path, file, idx, follow)?;
let (at, line) = (broken.path.display(), broken.line);
let message = match &broken.name {
None => format!(
"{}:{}: § {} cannot be hashed: it follows a body whose file does not parse with the tree-sitter grammar at {at}:{line} (a syntax error, or syntax the grammar does not know), which can hide a declaration the body reads.",
path.display(),
idx + 1,
pin.display(),
),
Some(name) => format!(
"{}:{}: § {} cannot be hashed: it reads `{name}`, which denotes no declaration, and {at} does not parse with the tree-sitter grammar at line {line} (a syntax error, or syntax the grammar does not know), where error recovery may have swallowed a declaration of `{name}`.",
path.display(),
idx + 1,
pin.display(),
),
};
Some(Blocked {
pin: format!("{}:{}: § {}", path.display(), idx + 1, pin.display()),
at: broken.path,
line: broken.line,
name: broken.name,
message,
})
}
pub fn spanless(root: &Path) -> Result<Vec<String>> {
let mut out = Vec::new();
for path in crate::walk::code_files(root)? {
let text = std::fs::read_to_string(&path)?;
let rel = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
if span_lang::lang_for_path(&rel).is_none() || !any_marker(&text, |_: &MarkerAddr| true) {
continue;
}
let code = CodeFile::new(rel, text);
if code.tree().is_none() {
continue;
}
for (idx, line) in code.marker_lines() {
if code.has_span(idx) {
continue;
}
for pin in marker::markers_in_line(line) {
out.push(format!(
"{}:{}: § {} is outside every span, so it pins nothing: move it onto the line above the construct it carries.",
code.rel.display(),
idx + 1,
pin.display()
));
}
}
}
Ok(out)
}
pub fn unhashable(root: &Path, of: &dyn Fn(&MarkerAddr) -> bool) -> Result<Vec<String>> {
let mut files = Vec::new();
for path in crate::walk::code_files(root)? {
let text = std::fs::read_to_string(&path)?;
let rel = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
if span_lang::lang_for_path(&rel).is_some() && any_marker(&text, of) {
files.push(CodeFile::new(rel, text));
}
}
let mut out = Vec::new();
if files.is_empty() {
return Ok(out);
}
let follow = shared_follow(
FollowIndex::sources(root)?,
crate::policy::TestPaths::at(root)?,
);
for code in &files {
if let Some(err) = code.too_deep() {
out.push(err);
continue;
}
let pinned = code.pinned_lines();
let file = FileSpans {
source: &code.text,
tree: Parse::File(code),
extents: &code.extents,
pinned: &pinned,
shift: None,
};
for (idx, line) in code.marker_lines() {
for pin in marker::markers_in_line(line).into_iter().filter(|p| of(p)) {
let err = span_unparsed(code, idx, &pin)
.or_else(|| callee_unparsed(&code.rel, &file, idx, &pin, &follow));
out.extend(err);
}
}
}
Ok(out)
}
fn broken_callee(
path: &Path,
file: &FileSpans<'_>,
marker_idx: usize,
follow: &FollowIndex,
) -> Option<crate::follow::Broken> {
let to_index = |at: usize| file.shift.map_or(at, |shift| shift.map(at));
let punch: Vec<(usize, usize)> = inner_punch_ranges(file.extents, file.pinned, marker_idx)
.iter()
.map(|&(s, e)| (to_index(s), to_index(e)))
.collect();
let &(start, end) = file.extents.get(&marker_idx)?;
let prefix = match span_lang::lang_for_path(path) {
Some(lang) => file.indexed_prefix(lang, (start, end)),
None => Vec::new(),
};
follow.broken_callee(path, to_index(start), to_index(end), &punch, &prefix)
}
fn mint_fallback_digest(
path: &Path,
source: &str,
lines: &[&str],
marker_idx: usize,
addr_text: &str,
) -> Option<String> {
let unmarked = unmarked_lines(path, source, None);
if unmarked[marker_idx] {
return None;
}
let ends = marker::explicit_ends_in(&unmarked, source);
let (start, end) = fallback_span(lines, &ends, marker_idx);
let punch = fallback_inner_punches(lines, &ends, &unmarked, marker_idx, start, end);
Some(fallback::mint_clause(
extension(path),
source,
start,
end,
&punch,
addr_text,
))
}
fn fallback_extents(
text: &str,
ends: &marker::Ends,
unmarked: &[bool],
) -> BTreeMap<usize, (usize, usize)> {
let lines: Vec<&str> = text.lines().collect();
let byte = |line: usize| span_lang::line_to_byte(text, line).unwrap_or(text.len());
lines
.iter()
.enumerate()
.filter(|&(idx, line)| {
!unmarked[idx] && !marker::is_one(line) && !marker::markers_in_line(line).is_empty()
})
.map(|(idx, _)| {
let (_, end) = fallback_span(&lines, ends, idx);
(idx, (byte(idx + 1), byte(end)))
})
.collect()
}
fn fallback_span(lines: &[&str], ends: &marker::Ends, marker_idx: usize) -> (usize, usize) {
match ends.pairs.get(&marker_idx) {
Some(&end_idx) => (marker_idx + 2, end_idx + 1),
None => (marker_idx + 2, lines.len() + 1),
}
}
fn fallback_inner_punches(
lines: &[&str],
ends: &marker::Ends,
unmarked: &[bool],
outer_idx: usize,
outer_start: usize,
outer_end: usize,
) -> Vec<(usize, usize)> {
let mut ranges = Vec::new();
for (idx, line) in lines.iter().enumerate() {
if idx == outer_idx || unmarked[idx] || marker::is_one(line) {
continue;
}
for inner in marker::markers_in_line(line) {
if inner.digest.is_none() {
continue;
}
let (_start, end) = fallback_span(lines, ends, idx);
let inclusive_start = idx + 1;
if inclusive_start >= outer_start && end <= outer_end {
ranges.push((inclusive_start, end));
}
}
}
ranges
}
fn inner_punch_ranges(
extents: &BTreeMap<usize, (usize, usize)>,
pinned: &[usize],
outer_idx: usize,
) -> Vec<(usize, usize)> {
let Some(&(outer_start, outer_end)) = extents.get(&outer_idx) else {
return Vec::new();
};
let mut ranges = Vec::new();
for &idx in pinned {
if idx == outer_idx {
continue;
}
if let Some(&inner) = extents.get(&idx) {
if nests_in(inner, (outer_start, outer_end)) {
ranges.push(inner);
}
}
}
ranges
}
pub(crate) fn nests_in(inner: (usize, usize), outer: (usize, usize)) -> bool {
inner != outer && inner.0 >= outer.0 && inner.1 <= outer.1
}
pub(crate) fn punch_of(markers: &[SpanMarker], line: usize) -> Vec<(usize, usize)> {
let Some(outer) = markers.iter().find(|m| m.line == line) else {
return Vec::new();
};
markers
.iter()
.filter(|m| m.line != line && m.addr.digest.is_some())
.map(|m| (m.start, m.end))
.filter(|&inner| nests_in(inner, (outer.start, outer.end)))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn no_follow() -> LazyFollow {
LazyCell::new(Box::new(Arc::default))
}
fn remint_src(src: &str) -> String {
remint_tested_text(
&span_lang::RUST,
Path::new("src/x.rs"),
src,
src,
&no_follow(),
&PinTexts::empty_for(src),
&|_| true,
)
.unwrap_or_else(|| src.to_string())
}
fn remint_md(src: &str) -> String {
remint_tested_text(
&span_lang::MARKDOWN,
Path::new("docs/guide.md"),
src,
src,
&no_follow(),
&PinTexts::empty_for(src),
&|_| true,
)
.unwrap_or_else(|| src.to_string())
}
const GUIDE: &str = "# Guide\n\n## Billing\n\n<!-- § abcdefgh1@00000 -->\n\nAn invoice is final.\n\n### Detail\n\nMore.\n\n## Other\n\nUnrelated.\n";
#[test]
fn doc_pin_binds_its_section() {
let pinned = remint_md(GUIDE);
assert_eq!(remint_md(&pinned), pinned, "the pin is stable");
let digest = pin_digest(&pinned, "abcdefgh1");
let prose = remint_md(&GUIDE.replace("is final", "is draft"));
assert_ne!(pin_digest(&prose, "abcdefgh1"), digest, "prose is hashed");
let sub = remint_md(&GUIDE.replace("More.", "Less."));
assert_ne!(
pin_digest(&sub, "abcdefgh1"),
digest,
"a subsection belongs"
);
let outside = remint_md(&GUIDE.replace("Unrelated", "Changed"));
assert_eq!(
pin_digest(&outside, "abcdefgh1"),
digest,
"the next section does not"
);
}
fn remint_mdx(src: &str) -> String {
remint_tested_text(
&span_lang::MDX,
Path::new("docs/guide.mdx"),
src,
src,
&no_follow(),
&PinTexts::empty_for(src),
&|_| true,
)
.unwrap_or_else(|| src.to_string())
}
#[test]
fn an_mdx_comment_marker_binds_its_section() {
let guide = GUIDE.replace("<!-- § abcdefgh1@00000 -->", "{/* § abcdefgh1@00000 */}");
let pinned = remint_mdx(&guide);
assert!(pinned.contains("{/* § abcdefgh1@"), "{pinned}");
assert_eq!(remint_mdx(&pinned), pinned, "the pin is stable");
let digest = pin_digest(&pinned, "abcdefgh1");
assert_eq!(digest, pin_digest(&remint_md(GUIDE), "abcdefgh1"));
let prose = remint_mdx(&guide.replace("is final", "is draft"));
assert_ne!(pin_digest(&prose, "abcdefgh1"), digest, "prose is hashed");
let outside = remint_mdx(&guide.replace("Unrelated", "Changed"));
assert_eq!(pin_digest(&outside, "abcdefgh1"), digest);
let body = |body: &str| {
let src = format!("# Guide\n\n{{/* § abcdefgh1@00000 */}}\n\n{body}\n");
pin_digest(&remint_mdx(&src), "abcdefgh1")
};
assert_eq!(
body("Write {/* keep */} here."),
body("Write {/* drop */} here.")
);
assert_ne!(
body("Write `{/* keep */}` here."),
body("Write `{/* drop */}` here.")
);
let ended =
"# Guide\n\n{/* § abcdefgh1@00000 */}\n\nFinal.\n\n{/* § end abcdefgh1 */}\n\nAfter.\n";
let ended = remint_mdx(ended);
let digest = pin_digest(&ended, "abcdefgh1");
assert_eq!(
pin_digest(&remint_mdx(&ended.replace("After", "Later")), "abcdefgh1"),
digest,
"the end closes the span"
);
assert_ne!(
pin_digest(&remint_mdx(&ended.replace("Final", "Draft")), "abcdefgh1"),
digest
);
}
#[test]
fn an_mdx_comment_in_markdown_is_prose() {
let src = "# Guide\n\n{/* § abcdefgh1 */}\n\nProse.\n";
let file = CodeFile::new(PathBuf::from("docs/guide.md"), src.to_string());
assert!(file.span_markers().is_empty());
assert!(marker_rows(Path::new("docs/guide.md"), src, None).is_empty());
assert_eq!(marker_rows(Path::new("docs/guide.mdx"), src, None).len(), 1);
}
#[test]
fn a_doc_pin_reads_a_comment_in_inline_code_and_the_whitespace_of_pre() {
let guide = |body: &str| {
remint_md(&format!(
"# Guide\n\n<!-- § abcdefgh1@00000 -->\n\n{body}\n"
))
};
let digest = |body: &str| pin_digest(&guide(body), "abcdefgh1");
assert_ne!(
digest("Write `<!-- keep -->` here."),
digest("Write `<!-- drop -->` here.")
);
assert_eq!(
digest("Write <!-- keep --> here."),
digest("Write <!-- drop --> here.")
);
assert_ne!(digest("<pre>\na b\n</pre>"), digest("<pre>\na b\n</pre>"));
assert_eq!(digest("<div>\na b\n</div>"), digest("<div>\na b\n</div>"));
}
#[test]
fn a_heading_or_a_string_that_reads_like_a_marker_is_none() {
let heading = "# Guide\n\n# § abcdefgh1.a\n\nProse.\n";
let file = CodeFile::new(PathBuf::from("docs/guide.md"), heading.to_string());
assert!(file
.marker_lines()
.all(|(_, line)| !line.starts_with("# §")));
assert!(file.span_markers().is_empty());
assert_eq!(remint_md(heading), heading);
let next = pin_bare_text(
Some(&span_lang::MARKDOWN),
Path::new("docs/guide.md"),
heading,
&no_follow(),
&PinTexts::empty_for(heading),
&|_| true,
);
assert!(next.is_none(), "{next:?}");
for (path, src) in [
(
"src/a.py",
"def f():\n return 1\n\nDOC = \"\"\"\n# § abcdefgh1.a\n\"\"\"\n",
),
(
"src/a.rs",
"const DOC: &str = r#\"\n// § abcdefgh1.a\n// § end abcdefgh1.a\n\"#;\n",
),
("src/a.kt", "val doc = \"\"\"\n// § abcdefgh1.a\n\"\"\"\n"),
] {
let unmarked = unmarked_lines(Path::new(path), src, None);
for (idx, line) in src.lines().enumerate() {
if line.contains('§') {
assert!(unmarked[idx], "{path}:{line}");
}
}
let file = CodeFile::new(PathBuf::from(path), src.to_string());
assert!(file.ends.orphans.is_empty(), "{path}");
assert!(file.span_markers().is_empty(), "{path}");
assert!(marker_rows(Path::new(path), src, None).is_empty(), "{path}");
assert!(
pinned_in_text(Path::new(path), src, None).is_empty(),
"{path}"
);
assert!(file_ends(Path::new(path), src).orphans.is_empty(), "{path}");
}
let real = "fn f() {\n // § abcdefgh1.a\n go();\n}\n";
assert!(!unmarked_lines(Path::new("src/a.rs"), real, None)[1]);
let rows = marker_rows(Path::new("src/a.rs"), real, None);
assert_eq!(rows.len(), 1);
assert_eq!(
(rows[0].idx, rows[0].markers[0].display()),
(1, "abcdefgh1.a".into())
);
}
#[test]
fn literal_ranges_cover_a_string_and_no_comment() {
let src = "// \"§ +a\"\nfn f() -> &'static str {\n \"§ +b\"\n}\n";
let ranges = literal_ranges(Path::new("src/a.rs"), src);
let held: Vec<&str> = ranges.iter().map(|&(s, e)| &src[s..e]).collect();
assert_eq!(held, vec!["\"§ +b\""]);
let ruby = "# \"§ +a\"\ny = \"§ +b\"\n";
let ranges = literal_ranges(Path::new("src/a.rb"), ruby);
let held: Vec<&str> = ranges.iter().map(|&(s, e)| &ruby[s..e]).collect();
assert_eq!(held, vec!["\"§ +b\""]);
assert!(literal_ranges(Path::new("docs/a.md"), "\"§ +b\"\n").is_empty());
}
#[test]
fn a_marker_above_a_construct_names_the_construct() {
for (path, src, line) in [
(
"src/a.rs",
"// § abcdefgh1\n#[derive(Debug)]\nimpl S {\n fn f() {}\n}\n",
3,
),
(
"src/a.py",
"# § abcdefgh1\n@dataclass\nclass C:\n a = 1\n",
2,
),
(
"src/a.tf",
"# § abcdefgh1\nresource \"a\" \"b\" {\n x = 1\n}\n",
2,
),
(
"src/a.ts",
"// § abcdefgh1\nexport class C {\n a = 1;\n}\n",
2,
),
] {
let file = CodeFile::new(PathBuf::from(path), src.to_string());
assert_eq!(file.construct_below(0), Some((line, None)), "{path}");
}
for (path, src, last) in [
("src/a.rs", "// § abcdefgh1\nconst RATE: u32 =\n 7;\n", 3),
("src/a.rs", "// § abcdefgh1\npub static RATE: u32 = 7;\n", 2),
("src/a.py", "# § abcdefgh1\nRATE = 7\n", 2),
("src/a.py", "# § abcdefgh1\nRATE += 7\n", 2),
("src/a.js", "// § abcdefgh1\nconst RATE = 7;\n", 2),
("src/a.js", "// § abcdefgh1\nvar RATE = 7;\n", 2),
("src/a.js", "// § abcdefgh1\nmodule.exports = 7;\n", 2),
("src/a.ts", "// § abcdefgh1\nexport const RATE = 7;\n", 2),
("src/a.tsx", "// § abcdefgh1\nlet RATE = 7;\n", 2),
("src/a.sh", "# § abcdefgh1\nRATE=7\n", 2),
("src/a.sh", "# § abcdefgh1\nreadonly RATE=7\n", 2),
("src/a.tf", "# § abcdefgh1\nrate = 7\n", 2),
] {
let file = CodeFile::new(PathBuf::from(path), src.to_string());
assert_eq!(
file.construct_below(0),
Some((2, Some(last))),
"{path}: {src}"
);
}
let inside = CodeFile::new(
PathBuf::from("src/a.rs"),
"fn f() {\n // § abcdefgh1\n act();\n}\n".to_string(),
);
assert_eq!(inside.construct_below(1), None);
let loose = CodeFile::new(
PathBuf::from("src/a.rs"),
"// § abcdefgh1\nuse a::b;\n".to_string(),
);
assert_eq!(loose.construct_below(0), None);
}
#[test]
fn a_plus_separated_pin_is_no_marker_and_fails() {
let src = "fn f() {\n // § abcdefgh1@aaaaa+bbbbb\n save(x);\n}\n";
let file = CodeFile::new(PathBuf::from("src/x.rs"), src.to_string());
assert!(file
.marker_lines()
.all(|(_, line)| marker::markers_in_line(line).is_empty()));
assert!(marker::looks_like_a_marker(
" // § abcdefgh1@aaaaa+bbbbb"
));
}
#[test]
fn block_comment_marker_pins_like_a_line_comment() {
let line = "fn f() {\n // § abcdefgh1@00000\n save(x);\n}\n";
let block = line.replace("// § abcdefgh1@00000", "/* § abcdefgh1@00000 */");
let digest = pin_digest(&remint_src(line), "abcdefgh1");
let pinned = remint_src(&block);
assert!(
pinned.contains(&format!("/* § abcdefgh1@{digest} */")),
"{pinned}"
);
}
#[test]
fn a_fenced_doc_marker_is_neither_pinned_nor_checked() {
let bare =
"# Guide\n\n```\n<!-- § abcdefgh1.a -->\n<!-- § end abcdefgh2 -->\n```\n\nProse.\n";
let pinned = bare.replace("abcdefgh1.a", "abcdefgh1.a@zzzzz");
let file = CodeFile::new(PathBuf::from("docs/guide.md"), pinned.clone());
assert!(file.span_markers().is_empty());
assert!(file
.marker_lines()
.all(|(_, line)| marker::markers_in_line(line).is_empty()));
let check = verify_file_follow(
&file,
span_lang::SERIALIZATION,
&FollowIndex::default(),
&PinTexts::empty_for(&pinned),
);
assert!(
check.errors.is_empty() && check.drifts.is_empty(),
"{check:?}"
);
assert_eq!(remint_md(&pinned), pinned);
let next = pin_bare_text(
Some(&span_lang::MARKDOWN),
Path::new("docs/guide.md"),
bare,
&no_follow(),
&PinTexts::empty_for(bare),
&|_| true,
);
assert!(next.is_none());
}
#[test]
fn remint_rewrites_only_the_pins_unchanged_since_head() {
let head = "fn f() {\n // § abcdefgh1.a@aaaaa\n one();\n}\n\nfn g() {\n // § abcdefgh1.b@bbbbb\n two();\n}\n";
let text = format!("// moved down\n{head}");
let tokens = |at: usize, a: &str, b: &str| {
PinTokens::from([
((at + 1, "abcdefgh1.a".to_string()), a.to_string()),
((at + 6, "abcdefgh1.b".to_string()), b.to_string()),
])
};
let (next, held, reminted) = remint_file(
&text,
&tokens(1, "ddddd", "eeeee"),
head,
&tokens(0, "ddddd", "ccccc"),
&|_, _, _| Ok(true),
)
.unwrap();
assert_eq!(held, vec![(7, "abcdefgh1.b".to_string())]);
assert_eq!(reminted, vec![(2, "abcdefgh1.a".to_string())]);
let next = next.unwrap();
assert!(next.contains("abcdefgh1.a@ddddd"), "{next}");
assert!(next.contains("abcdefgh1.b@bbbbb"), "{next}");
}
#[test]
fn remint_holds_a_pin_head_lacks_or_wrote_another_digest() {
let text = "fn f() {\n // § abcdefgh1.a@aaaaa\n one();\n}\n";
let now = PinTokens::from([((1, "abcdefgh1.a".to_string()), "ddddd".to_string())]);
let held = vec![(1, "abcdefgh1.a".to_string())];
let always = |_: usize, _: &str, _: &str| Ok(true);
let remint = |text: &str, head: &str, at_head: &PinTokens| {
remint_file(text, &now, head, at_head, &always).unwrap()
};
assert_eq!(
remint(text, "", &PinTokens::new()),
(None, held.clone(), Vec::new())
);
let other = text.replace("@aaaaa", "@zzzzz");
assert_eq!(remint(text, &other, &now), (None, held.clone(), Vec::new()));
let current = text.replace("@aaaaa", "@ddddd");
assert_eq!(remint(¤t, text, &now), (None, Vec::new(), Vec::new()));
assert_eq!(
remint_file(text, &now, text, &now, &|at, addr, written| {
assert_eq!((at, addr, written), (1, "abcdefgh1.a", "aaaaa"));
Ok(false)
})
.unwrap(),
(None, held, Vec::new())
);
}
#[test]
fn tree_tokens_read_the_token_a_pin_is_minted_with() {
let src = "fn f() {\n // § abcdefgh1@00000\n one();\n}\n// § abcdefgh2@00000\n";
let current = TreeTokens {
follow: FollowIndex::default(),
texts: PinTexts::empty_for(src),
};
let lang = span_lang::lang_for_path(Path::new("x.rs")).unwrap();
let pinned = remint_tested_text(
lang,
Path::new("x.rs"),
src,
src,
&no_follow(),
¤t.texts,
&|_| true,
)
.unwrap();
let tokens = current.tokens(Path::new("x.rs"), &pinned);
assert_eq!(
tokens.get(&(1, "abcdefgh1".to_string())),
Some(&pin_digest(&pinned, "abcdefgh1"))
);
let go = remint_go(src);
let fallback = current.tokens(Path::new("x.go"), &go);
let pin = pin_addr(&go, "abcdefgh2");
assert_eq!(
fallback.get(&(4, "abcdefgh2".to_string())),
pin.digest.as_ref()
);
}
#[test]
fn a_setext_heading_bounds_a_doc_section() {
let doc = "Guide\n=====\n\nBilling\n-------\n\n<!-- § abcdefgh1@00000 -->\n\nAn invoice is final.\n\n### Detail\n\nMore.\n\nOther\n-----\n\nUnrelated.\n";
let pinned = remint_md(doc);
let digest = pin_digest(&pinned, "abcdefgh1");
let prose = remint_md(&doc.replace("is final", "is draft"));
assert_ne!(pin_digest(&prose, "abcdefgh1"), digest, "its own prose");
let sub = remint_md(&doc.replace("More.", "Less."));
assert_ne!(
pin_digest(&sub, "abcdefgh1"),
digest,
"a subsection belongs"
);
let outside = remint_md(&doc.replace("Unrelated", "Changed"));
assert_eq!(
pin_digest(&outside, "abcdefgh1"),
digest,
"the next section does not"
);
let above = remint_md(&doc.replace("Guide\n=====", "Manual\n======"));
assert_eq!(
pin_digest(&above, "abcdefgh1"),
digest,
"the heading above does not"
);
}
#[test]
fn doc_pin_honours_an_explicit_end() {
let src = GUIDE.replace("final.\n", "final.\n<!-- § end abcdefgh1 -->\n");
let digest = pin_digest(&remint_md(&src), "abcdefgh1");
let sub = remint_md(&src.replace("More.", "Less."));
assert_eq!(pin_digest(&sub, "abcdefgh1"), digest);
}
fn remint_go(src: &str) -> String {
remint_fallback_text(
Path::new("main.go"),
src,
&PinTexts::empty_for(src),
&|_| true,
)
.unwrap_or_else(|| src.to_string())
}
fn pin_addr(src: &str, display: &str) -> MarkerAddr {
marker::markers_in_text(src)
.into_iter()
.find(|p| p.display() == display)
.unwrap_or_else(|| panic!("missing pin {display} in {src}"))
}
fn pin_digest(src: &str, display: &str) -> String {
pin_addr(src, display)
.digest
.unwrap_or_else(|| panic!("missing digest {display}"))
}
fn pin(id: &str) -> String {
format!("// § {id}@00000")
}
fn pinned_fn(ty: &str, stmt: &str) -> String {
format!(
"fn f() {{\n {}\n let x: {ty} = 1;\n {stmt}\n}}\n",
pin("abcdefgh1")
)
}
fn outer_fn(inner: Option<(&str, &str)>) -> String {
let mut out = format!(
"fn outer() {{\n {}\n let a = silcrow();\n",
pin("abcdefgh1")
);
if let Some((marker, body)) = inner {
out.push_str(&format!(
" {{\n {marker}\n let b = {body}\n }}\n"
));
}
out.push_str("}\n");
out
}
fn outer_fn_flat() -> String {
format!(
"fn outer() {{\n {}\n let a = silcrow();\n let b = lade();\n}}\n",
pin("abcdefgh1")
)
}
fn go_src(body: &str) -> String {
format!(
"package main\nfunc main() {{\n {}\n {body}\n}}\n",
pin("abcdefgh1")
)
}
#[test]
fn pin_outside_construct_cannot_delimit() {
let src = format!("{}\nimpl Foo {{}}\n", pin("abcdefgh1"));
let errs = verify_file(Path::new("src/x.rs"), &src, span_lang::SERIALIZATION);
assert!(
errs.errors.iter().any(|e| e.contains("could not delimit")),
"{errs:?}"
);
}
fn unparsed_outside(path: &str, src: &str, m: &str) -> Vec<String> {
let code = CodeFile::new(path.into(), src.to_string());
let idx = src.lines().position(|l| l.contains(m)).unwrap();
let &(start, end) = code.extents.get(&idx).expect("a span");
assert_eq!(
span_lang::parse_error_line(code.tree().unwrap(), start, end),
None,
"{path}: the error lies outside the span"
);
verify_file_follow(
&code,
span_lang::SERIALIZATION,
&FollowIndex::from_sources(
&[(PathBuf::from(path), src.to_string())],
&crate::policy::TestPaths::conventions(),
),
&PinTexts::empty_for(src),
)
.reported()
}
#[test]
fn a_parse_error_outside_the_span_fails_its_pin() {
let m = "§ abcdefgh1@00000";
for (path, src) in [
(
"src/x.rs",
format!("fn g() {{\n save(;\n}}\nfn f() {{\n // {m}\n g();\n}}\n"),
),
(
"src/x.rs",
format!("fn f() {{\n // {m}\n g();\n}}\nfn h() {{\n let a = (1,\n}}\nfn g() {{\n save();\n}}\n"),
),
(
"src/x.js",
format!("function f() {{\n // {m}\n return g();\n}}\nfunction h(x) {{\n if (x) {{\n return 1;\n}}\nfunction g() {{\n return 2;\n}}\n"),
),
(
"src/x.py",
format!("def g():\n return [1\ndef k():\n return 2\ndef f():\n # {m}\n return k()\n"),
),
(
"src/x.py",
format!("def g():\n return [1\ndef f():\n # {m}\n return g()\n"),
),
(
"src/x.js",
format!("function f() {{\n // {m}\n return g();\n}}\nfunction g() {{\n return (1;\n}}\n"),
),
(
"src/x.ts",
format!("function f() {{\n // {m}\n return g();\n}}\nfunction g() {{\n return [1;\n}}\n"),
),
(
"src/x.tsx",
format!("function f() {{\n // {m}\n return g();\n}}\nfunction g() {{\n return [1;\n}}\n"),
),
(
"src/x.sh",
format!("f() {{\n # {m}\n g\n}}\ng() {{\n echo 1 )\n}}\n"),
),
(
"src/x.css",
format!("a {{\n /* {m} */\n color: red;\n}}\nb {{ color: red; }} }}\n"),
),
(
"src/x.hcl",
format!("a {{\n # {m}\n x = 1\n}}\nb {{\n y = \n}}\n"),
),
(
"src/x.html",
format!("<div>\n<!-- {m} -->\n<p>x</p>\n</div>\n<p <\n"),
),
] {
let errs = unparsed_outside(path, &src, m);
assert!(
errs.iter().any(|e| e.contains("cannot be hashed")),
"{path}: {src}: {errs:?}"
);
}
}
#[test]
fn a_parse_error_closed_in_another_item_leaves_a_pin_hashable() {
let m = "§ abcdefgh1@00000";
for (path, src) in [
(
"src/x.rs",
format!("fn g() {{\n save(;\n}}\nfn f() {{\n // {m}\n k();\n}}\nfn k() {{}}\n"),
),
(
"src/x.py",
format!("def g():\n x = foo(1,\n 2\n return x\n\ndef f():\n # {m}\n return 1\n"),
),
(
"src/x.js",
format!("function f() {{\n // {m}\n return 1;\n}}\nfunction g() {{\n return (1;\n}}\n"),
),
(
"src/x.ts",
format!("async function walk(): Promise<void> {{\n let entries: import(\"node:fs\").Dirent[];\n entries = [];\n}}\nfunction f() {{\n // {m}\n return 1;\n}}\n"),
),
] {
let errs = unparsed_outside(path, &src, m);
assert!(errs.is_empty(), "{path}: {src}: {errs:?}");
}
}
#[test]
fn a_span_that_does_not_parse_fails() {
for src in [
format!("fn outer() {{\n {}\n save(;\n}}\n", pin("abcdefgh1")),
"fn outer() {\n // § abcdefgh1\n let x = 1\n}\n".to_string(),
] {
let errs = verify_file(Path::new("src/x.rs"), &src, span_lang::SERIALIZATION);
assert!(
errs.reported().iter().any(|e| e.contains("does not parse")),
"{src}: {errs:?}"
);
}
}
#[test]
fn a_marker_in_an_empty_block_fails() {
for src in [
"fn outer(x: u32) {\n // § abcdefgh1\n}\n".to_string(),
format!("fn outer() {{\n {}\n // note\n}}\n", pin("abcdefgh1")),
"fn outer() {\n // § abcdefgh1\n // § end abcdefgh1\n go();\n}\n".to_string(),
] {
let errs = verify_file(Path::new("src/x.rs"), &src, span_lang::SERIALIZATION);
assert!(
errs.errors
.iter()
.any(|e| e.contains("opens an empty span")),
"{src}: {errs:?}"
);
}
let errs = verify_file(
Path::new("src/x.rs"),
&outer_fn_flat(),
span_lang::SERIALIZATION,
);
assert!(
!errs.errors.iter().any(|e| e.contains("empty span")),
"{errs:?}"
);
}
#[test]
fn a_doc_section_that_is_only_its_heading_is_empty() {
let empty = |src: &str| {
let file = CodeFile::new(PathBuf::from("docs/guide.md"), src.to_string());
let idx = src.lines().position(|l| l.contains("<!-- §")).unwrap();
file.is_empty_span(idx)
};
assert!(empty(
"# G\n\n## R\n\n<!-- § abcdefgh1 -->\n\n## N\n\nMore.\n"
));
assert!(empty(
"# G\n\n## R\n\n<!-- § abcdefgh1 -->\n\n### Sub\n\n## N\n"
));
assert!(!empty(
"# G\n\n## R\n\n<!-- § abcdefgh1 -->\n\nRetries stop.\n\n## N\n"
));
assert!(!empty(
"# G\n\n## R\n\n<!-- § abcdefgh1 -->\n\n### Sub\n\nText.\n"
));
}
#[test]
fn a_span_holding_only_a_nested_span_is_empty() {
let src = "fn outer() {\n // § abcdefgh1\n {\n // § abcdefgh2\n let a = go();\n }\n}\n";
let errs = verify_file(Path::new("src/x.rs"), src, span_lang::SERIALIZATION);
assert!(
errs.errors
.iter()
.any(|e| e.contains("2: § abcdefgh1 opens an empty span")),
"{errs:?}"
);
assert!(
!errs.errors.iter().any(|e| e.contains("abcdefgh2 opens")),
"{errs:?}"
);
let more = src.replace(" }\n}", " }\n let b = 1;\n}");
let errs = verify_file(Path::new("src/x.rs"), &more, span_lang::SERIALIZATION);
assert!(
!errs.errors.iter().any(|e| e.contains("empty span")),
"{errs:?}"
);
}
#[test]
fn first_class_rust_type_change_moves() {
let before = remint_src(&pinned_fn("i32", "save(x);"));
let after = remint_src(&pinned_fn("i64", "save(x);"));
assert_ne!(
pin_digest(&before, "abcdefgh1"),
pin_digest(&after, "abcdefgh1")
);
let moved = before.replace("i32", "i64");
let errs = verify_file(Path::new("src/x.rs"), &moved, span_lang::SERIALIZATION);
assert!(!errs.drifts.is_empty(), "{errs:?}");
}
#[test]
fn first_class_effect_change_moves() {
let before = remint_src(&pinned_fn("i32", "save(x);"));
let after = remint_src(&pinned_fn("i32", "save(x + 1);"));
assert_ne!(
pin_digest(&before, "abcdefgh1"),
pin_digest(&after, "abcdefgh1")
);
let drifted = before.replace("save(x);", "save(x + 1);");
let errs = verify_file(Path::new("src/x.rs"), &drifted, span_lang::SERIALIZATION);
assert!(
errs.drifts
.iter()
.any(|e| e.message(None).contains("changed since its pin")),
"{errs:?}"
);
}
#[test]
fn grouping_block_reads_the_code_before_it_and_not_after() {
let inner = pin("abcdefgh1");
let quote = |fee: &str, price: &str, tail: &str| {
format!(
"fn quote(x: i32) -> i32 {{\n let fee = {fee};\n {{\n {inner}\n let p = x * {price};\n p\n }}\n fee{tail}\n}}\n"
)
};
let digest = |src: String| pin_digest(&remint_src(&src), "abcdefgh1");
let before = digest(quote("1", "2", ""));
assert_ne!(before, digest(quote("9", "2", "")));
assert_ne!(before, digest(quote("1", "3", "")));
assert_eq!(before, digest(quote("1", "2", " + 1")));
}
#[test]
fn first_class_remint_is_five_chars() {
let reminted = remint_src("fn f() {\n // § abcdefgh1@aaaaa\n let y = save(x);\n}\n");
let pin = pin_addr(&reminted, "abcdefgh1");
assert_eq!(pin.digest.as_ref().map(String::len), Some(5));
let errs = verify_file(Path::new("src/x.rs"), &reminted, span_lang::SERIALIZATION);
assert!(errs.errors.is_empty() && errs.drifts.is_empty(), "{errs:?}");
}
#[test]
fn fallback_remint_is_five_chars() {
let reminted = remint_go(&go_src("save()"));
let pin = pin_addr(&reminted, "abcdefgh1");
assert_eq!(pin.digest.as_ref().map(String::len), Some(5));
let errs = verify_file(Path::new("main.go"), &reminted, span_lang::SERIALIZATION);
assert!(errs.errors.is_empty() && errs.drifts.is_empty(), "{errs:?}");
assert!(
errs.warnings
.iter()
.any(|w| w.contains("fallback heuristic") && w.contains("github.com/zifeo/silcrow")),
"{errs:?}"
);
}
#[test]
fn a_marker_only_inside_a_string_warns_no_fallback() {
let src = "package a\n\nvar s = `\n// § abcdefgh1\n`\n";
let errs = verify_file(Path::new("a.go"), src, span_lang::SERIALIZATION);
assert!(errs.warnings.is_empty(), "{errs:?}");
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n",
)
.unwrap();
std::fs::write(dir.path().join("a.go"), src).unwrap();
std::fs::write(dir.path().join("b.go"), "// § abcdefgh1\n").unwrap();
let notices = fallback_notices(dir.path()).unwrap();
assert_eq!(notices.len(), 1, "{notices:?}");
assert!(notices[0].contains("b.go"), "{notices:?}");
}
#[test]
fn fallback_pin_fails_when_its_token_moved() {
let reminted = remint_go(&go_src("save()"));
let drifted = reminted.replace("save()", "save(x)");
let report = verify_file(Path::new("main.go"), &drifted, span_lang::SERIALIZATION);
assert!(
report
.drifts
.iter()
.any(|e| e.message(None).contains("changed since its pin")),
"{report:?}"
);
}
#[test]
fn nested_span_as_new_code_at_the_end_leaves_outer_unchanged() {
let outer = remint_src(&outer_fn(None));
let nested = remint_src(&outer_fn(Some((&pin("abcdefgh2"), "lade();"))));
assert_eq!(
pin_digest(&outer, "abcdefgh1"),
pin_digest(&nested, "abcdefgh1"),
"nothing of the outer span follows the hole"
);
let errs = verify_file(Path::new("src/x.rs"), &nested, span_lang::SERIALIZATION);
assert!(errs.errors.is_empty() && errs.drifts.is_empty(), "{errs:?}");
let inner = remint_src(&outer_fn(Some((&pin("abcdefgh2"), "load();"))));
assert_eq!(
pin_digest(&nested, "abcdefgh1"),
pin_digest(&inner, "abcdefgh1"),
"the nested body is not the outer's"
);
}
#[test]
fn code_moved_across_a_hole_moves_the_outer_pin() {
let explicit = |before: &str, after: &str| {
remint_src(&format!(
"fn handle(ok: bool) {{\n {}\n {before}\n {}\n check(ok);\n // § end abcdefgh2\n {after}\n}}\n",
pin("abcdefgh1"),
pin("abcdefgh2")
))
};
let below = explicit("", "act();");
let above = explicit("act();", "");
assert_ne!(
pin_digest(&below, "abcdefgh1"),
pin_digest(&above, "abcdefgh1")
);
let plain = remint_src(&format!(
"fn handle(ok: bool) {{\n {}\n act();\n}}\n",
pin("abcdefgh1")
));
assert_ne!(
pin_digest(&plain, "abcdefgh1"),
pin_digest(&below, "abcdefgh1"),
"a nested span stacked before outer code opens a hole"
);
}
#[test]
fn nested_span_carved_from_outer_moves() {
let outer = remint_src(&outer_fn_flat());
let carved = remint_src(&outer_fn(Some((&pin("abcdefgh2"), "lade();"))));
assert_ne!(
pin_digest(&outer, "abcdefgh1"),
pin_digest(&carved, "abcdefgh1")
);
}
fn remint_py(src: &str) -> String {
remint_tested_text(
&span_lang::PYTHON,
Path::new("src/x.py"),
src,
src,
&no_follow(),
&PinTexts::empty_for(src),
&|_| true,
)
.unwrap_or_else(|| src.to_string())
}
#[test]
fn a_nested_span_closing_on_the_outer_line_is_punched() {
let py = |body: &str| {
format!("def f(x):\n # § abcdefgh1@00000\n go(x)\n if x:\n # § abcdefgh2@00000\n {body}\n")
};
let before = remint_py(&py("lade(x)"));
let after = remint_py(&py("lade(x, 1)"));
assert_eq!(
pin_digest(&before, "abcdefgh1"),
pin_digest(&after, "abcdefgh1")
);
assert_ne!(
pin_digest(&before, "abcdefgh2"),
pin_digest(&after, "abcdefgh2")
);
let own = remint_py(&py("lade(x)").replace("go(x)", "go(x, 2)"));
assert_ne!(
pin_digest(&before, "abcdefgh1"),
pin_digest(&own, "abcdefgh1")
);
let md = |body: &str| {
format!("# Guide\n\n<!-- § abcdefgh1@00000 -->\n\nTop.\n\n## Sub\n\n<!-- § abcdefgh2@00000 -->\n\n{body}\n")
};
let before = remint_md(&md("More."));
let after = remint_md(&md("Less."));
assert_eq!(
pin_digest(&before, "abcdefgh1"),
pin_digest(&after, "abcdefgh1")
);
assert_ne!(
pin_digest(&before, "abcdefgh2"),
pin_digest(&after, "abcdefgh2")
);
}
fn remint_followed(src: &str) -> String {
remint_followed_in(&span_lang::RUST, "src/x.rs", src)
}
fn remint_followed_in(lang: &LangSpec, path: &str, src: &str) -> String {
let sources = vec![(PathBuf::from(path), src.to_string())];
let follow: LazyFollow = LazyCell::new(Box::new(move || {
FollowIndex::from_sources(&sources, &crate::policy::TestPaths::conventions()).into()
}));
remint_tested_text(
lang,
Path::new(path),
src,
src,
&follow,
&PinTexts::empty_for(src),
&|_| true,
)
.unwrap_or_else(|| src.to_string())
}
#[test]
fn a_followed_body_that_does_not_parse_fails_the_caller() {
let src = "fn main() {\n // § abcdefgh1@00000\n helper(1);\n}\n\nfn helper(x: u32) {\n save(x;\n}\n";
let pinned = remint_followed(src);
assert_eq!(
pin_digest(&pinned, "abcdefgh1"),
"00000",
"no digest is minted"
);
let verify = |sources: &[(PathBuf, String)]| {
let file = CodeFile::new(sources[0].0.clone(), sources[0].1.clone());
verify_file_follow(
&file,
span_lang::SERIALIZATION,
&FollowIndex::from_sources(sources, &crate::policy::TestPaths::conventions()),
&PinTexts::empty_for(&sources[0].1),
)
.reported()
};
let errors = verify(&[(PathBuf::from("src/x.rs"), src.to_string())]);
assert!(
errors.iter().any(|e| e.contains(
"follows a body whose file does not parse with the tree-sitter grammar at src/x.rs:7 (a syntax error, or syntax the grammar does not know)"
)),
"{errors:?}"
);
let (caller, callee) = src.split_at(src.find("fn helper").unwrap());
let sources = [
(PathBuf::from("src/x.rs"), caller.to_string()),
(PathBuf::from("src/y.rs"), callee.to_string()),
];
let follow: LazyFollow = {
let sources = sources.to_vec();
LazyCell::new(Box::new(move || {
FollowIndex::from_sources(&sources, &crate::policy::TestPaths::conventions()).into()
}))
};
let minted = remint_tested_text(
&span_lang::RUST,
Path::new("src/x.rs"),
caller,
caller,
&follow,
&PinTexts::empty_for(caller),
&|_| true,
)
.unwrap_or_else(|| caller.to_string());
assert_eq!(
pin_digest(&minted, "abcdefgh1"),
"00000",
"no digest is minted"
);
let errors = verify(&sources);
assert!(
errors.iter().any(|e| e.contains(
"follows a body whose file does not parse with the tree-sitter grammar at src/y.rs:2"
)),
"{errors:?}"
);
}
#[test]
fn a_pin_hashes_the_canonical_address_it_names() {
let note = "**§ abcdefgh1 One.**\n\n- (a) Only within one hour.\n\n- (b) Only within one hour.\n\n**§ abcdefgh2<a id=\"abcdefgh3\"></a> Two.**\n\n- (a) Only within one hour.\n";
let scan = crate::parse::scan_text(Path::new("docs/decisions/x.md"), note);
let scans = crate::workspace::LawScans {
own: "lib".to_string(),
scans: BTreeMap::new(),
};
let texts = PinTexts::for_project(&scan, &scans);
let of = |display: &str| texts.of(&marker::markers_in_line(&format!("// § {display}"))[0]);
assert_ne!(of("abcdefgh1.a"), of("abcdefgh1.b"));
assert_ne!(of("abcdefgh1.a"), of("abcdefgh2.a"));
assert_eq!(
of("abcdefgh3.a"),
of("abcdefgh2.a"),
"an alias names the current id"
);
assert_eq!(of("lib:abcdefgh1.a"), of("abcdefgh1.a"));
assert!(of("abcdefgh2.a").is_some_and(|t| t.starts_with("lib:abcdefgh2.a\n")));
}
#[test]
fn a_call_in_a_nested_span_is_not_followed_by_the_outer_pin() {
let audit = |body: &str| format!("fn audit() {{\n {body}\n}}\n");
let plain = format!("{}{}", outer_fn(None), audit("log(1);"));
let stacked = format!(
"{}{}",
outer_fn(Some((&pin("abcdefgh2"), "audit();"))),
audit("log(1);")
);
let edited = stacked.replace("log(1);", "log(2);");
let (plain, stacked, edited) = (
remint_followed(&plain),
remint_followed(&stacked),
remint_followed(&edited),
);
assert_eq!(
pin_digest(&plain, "abcdefgh1"),
pin_digest(&stacked, "abcdefgh1"),
"stacking a nested span that calls a helper leaves the outer pin"
);
assert_eq!(
pin_digest(&stacked, "abcdefgh1"),
pin_digest(&edited, "abcdefgh1"),
"a helper only the nested span calls is not the outer pin's"
);
assert_ne!(
pin_digest(&stacked, "abcdefgh2"),
pin_digest(&edited, "abcdefgh2"),
"the nested pin follows it"
);
}
#[test]
fn a_sibling_pin_in_one_construct_is_not_punched() {
let py = |body: &str| {
format!("def f(x):\n # § abcdefgh1@00000\n go(x)\n # § abcdefgh2@00000\n {body}\n")
};
let before = remint_py(&py("lade(x)"));
let after = remint_py(&py("lade(x, 1)"));
assert_ne!(
pin_digest(&before, "abcdefgh1"),
pin_digest(&after, "abcdefgh1")
);
}
#[test]
fn a_python_stretch_at_the_edge_of_its_block_reads_what_is_around_it() {
let open = "# § abcdefgh1@00000";
let close = "# § end abcdefgh1";
let moved = [
(
format!("LIMIT = 10\n\ndef a(x, limit=LIMIT):\n {open}\n y = x + limit\n {close}\n return y\n"),
"limit=LIMIT",
"limit=OTHER",
),
(
format!("def a(x, limit=10):\n {open}\n y = x + limit\n {close}\n return y\n"),
"limit=10",
"limit=99",
),
(
format!("def a(x, limit=10):\n go(x)\n {open}\n y = x + limit\n {close}\n"),
"limit=10",
"limit=99",
),
(
format!("def a(x):\n if x > 0:\n {open}\n y = x\n {close}\n go(y)\n"),
"x > 0",
"x > 9",
),
(
format!("def a(x):\n if x > 0:\n go(x)\n {open}\n y = x\n {close}\n return 1\n"),
"x > 0",
"x > 9",
),
(
format!("def a(x):\n try:\n if x:\n raise ValueError()\n go(x)\n except ValueError:\n {open}\n y = 1\n {close}\n log(y)\n"),
"raise ValueError()",
"raise TypeError()",
),
(
format!("def a(xs):\n for x in xs:\n if x < 0:\n break\n else:\n {open}\n y = 1\n {close}\n"),
"x < 0",
"x < 9",
),
(
format!("def a(x):\n try:\n go(x)\n finally:\n {open}\n y = 1\n {close}\n"),
"go(x)",
"os._exit(1)",
),
(
format!("def a(x):\n if x:\n return 0\n {open}\n y = 1\n {close}\n"),
"if x:",
"if not x:",
),
];
let pin = |src: &str| {
pin_digest(
&remint_followed_in(&span_lang::PYTHON, "src/x.py", src),
"abcdefgh1",
)
};
for (src, from, to) in &moved {
assert_ne!(pin(src), pin(&src.replace(from, to)), "{src}");
}
let src = &moved[0].0;
assert_ne!(pin(src), pin(&src.replace("LIMIT = 10", "LIMIT = 99")));
let quiet = [
(moved[1].0.clone(), "return y", "return y + 1"),
(moved[3].0.clone(), "go(y)", "go(y, 2)"),
];
for (src, from, to) in &quiet {
assert_eq!(pin(src), pin(&src.replace(from, to)), "{src}");
}
}
#[test]
fn a_rust_macro_string_keeps_its_bytes_and_the_locals_it_names_their_text() {
let pin = |src: &str| pin_digest(&remint_followed(src), "abcdefgh1");
let report = |body: &str| {
format!("const LIMIT: u32 = 5;\nconst W: usize = 8;\n\npub fn report(a: u32, b: u32, f: &mut String) -> String {{\n // § abcdefgh1@00000\n let total = a + b;\n let fee = a * 2;\n {body}\n}}\n")
};
let swap = |src: &str| {
src.replace(
"let total = a + b;\n let fee = a * 2;",
"let fee = a + b;\n let total = a * 2;",
)
};
let rename = |src: &str| src.replace("total", "sum").replace("fee", "cost");
for body in [
"format!(\"charge {total}, fee {fee}\")",
"format!(\"charge {total:>5}, fee {fee:?}\")",
"println!(\"{}\", format!(\"{total} {fee}\")); String::new()",
"write!(f, \"{total} {fee}\").ok(); String::new()",
"assert!(a > 0, \"{total} {fee}\"); String::new()",
"info!(\"{total} {fee}\"); String::new()",
"std::format!(\"{total} {fee}\")",
] {
let src = report(body);
assert_ne!(pin(&src), pin(&swap(&src)), "swap: {body}");
}
let edit = |src: &str| {
src.replace("LIMIT: u32 = 5", "LIMIT: u32 = 6")
.replace("W: usize = 8", "W: usize = 9")
};
for body in [
"format!(\"cap {}\", LIMIT)",
"format!(\"cap {:w$}\", total, w = W)",
] {
let src = report(body);
assert_ne!(pin(&src), pin(&edit(&src)), "constant: {body}");
}
for body in ["format!(\"cap {LIMIT}\")", "format!(\"cap {total:>W$}\")"] {
let src = report(body);
assert_eq!(pin(&src), pin(&edit(&src)), "constant: {body}");
}
for body in [
"format!(\"charge {total}, then {fee}\")",
"info!(\"{total} {fee}\"); String::new()",
] {
let src = report(body);
assert_ne!(pin(&src), pin(&rename(&src)), "rename: {body}");
}
let plain = report("format!(\"{}\", total + fee)");
assert_eq!(
pin(&plain),
pin(&rename(&plain)),
"a plain read renames freely"
);
}
#[test]
fn a_lowercase_rust_constant_in_a_pattern_is_read() {
let pin = |src: &str| pin_digest(&remint_followed(src), "abcdefgh1");
let src = "#[allow(non_upper_case_globals)]\nconst limit: u32 = 5;\n\nfn grade(n: u32) -> u32 {\n // § abcdefgh1@00000\n match n {\n limit => 1,\n _ => 0,\n }\n}\n";
assert_ne!(pin(src), pin(&src.replace("= 5;", "= 6;")));
let binding = "fn grade(n: u32) -> u32 {\n // § abcdefgh1@00000\n match n {\n limit => limit + 1,\n }\n}\n";
assert_eq!(
pin(binding),
pin(&binding.replace("limit", "cap")),
"a lowercase binding with no constant of its name renames freely"
);
let used = "use crate::m::limit;\n\nfn grade(n: u32) -> u32 {\n // § abcdefgh1@00000\n match n {\n limit => 1,\n _ => 0,\n }\n}\n";
assert_ne!(
pin(used),
pin(&used.replace("limit => 1", "lim => 1")),
"a name a `use` brings in may be a constant"
);
let if_let = "#[allow(non_upper_case_globals)]\nconst limit: u32 = 5;\n\nfn grade(n: u32) -> u32 {\n // § abcdefgh1@00000\n if let limit = n { 1 } else { 0 }\n}\n";
assert_ne!(
pin(if_let),
pin(&if_let.replace("= 5;", "= 6;")),
"an `if let` pattern is refutable"
);
let param = "use crate::m::limit;\n\nfn grade(limit: u32) -> u32 {\n // § abcdefgh1@00000\n limit + 1\n}\n";
assert_eq!(
pin(param),
pin(¶m.replace("limit", "cap")),
"a parameter binds even when a `use` brings in its name"
);
}
#[test]
fn inner_span_edit_leaves_outer_unchanged() {
let before = remint_src(&outer_fn(Some((&pin("abcdefgh2"), "lade();"))));
let after = remint_src(&outer_fn(Some((&pin("abcdefgh2"), "lade(x);"))));
assert_eq!(
pin_digest(&before, "abcdefgh1"),
pin_digest(&after, "abcdefgh1")
);
assert_ne!(
pin_digest(&before, "abcdefgh2"),
pin_digest(&after, "abcdefgh2")
);
}
#[test]
fn nested_spans_reordered_among_themselves_move_no_outer_pin() {
let src = |first: &str, second: &str| {
remint_src(&format!(
"fn handle(ok: bool) {{\n {}\n act();\n {}\n {first}\n // § end abcdefgh2\n {}\n {second}\n // § end abcdefgh3\n done();\n}}\n",
pin("abcdefgh1"),
pin("abcdefgh2"),
pin("abcdefgh3")
))
};
assert_eq!(
pin_digest(&src("lade();", "ship();"), "abcdefgh1"),
pin_digest(&src("ship();", "lade();"), "abcdefgh1")
);
}
#[test]
fn the_fallback_reads_nothing_above_its_marker() {
let src = |above: &str| {
format!(
"package main\nfunc main() {{\n {above}\n {}\n save()\n}}\n",
pin("abcdefgh1")
)
};
assert_eq!(
pin_digest(&remint_go(&src("load()")), "abcdefgh1"),
pin_digest(&remint_go(&src("drop()")), "abcdefgh1")
);
}
#[test]
fn a_draft_mark_moves_no_pin_text_of_its_own_project_or_another() {
let texts = |note: &str| {
let lib = crate::parse::scan_text(Path::new("docs/decisions/n.md"), note);
let scans = crate::workspace::LawScans {
own: ".".to_string(),
scans: [("libs/money".to_string(), lib.clone())].into(),
};
PinTexts::for_project(&lib, &scans).0
};
let plain = "**§ <a id=\"abcdefgh1\">abcdefgh1</a> A rule holds, `x > 1`.**\nUnder the head.\n\n- (a) One.\n\n | k | v |\n | - | - |\n\n- (b) Two.\n";
let drafts = [
plain.replace("**§ <a", "**§? <a"),
plain.replace("- (a) One.", "- (a)? One."),
plain
.replace("**§ <a", "**§? <a")
.replace("- (b) Two.", "- (b)? Two."),
];
let want = texts(plain);
assert!(want.contains_key("libs/money:abcdefgh1.a"));
for draft in &drafts {
assert_eq!(texts(draft), want, "{draft}");
let law = &crate::parse::scan_text(Path::new("n.md"), draft).laws[0];
assert_eq!(
hash::mint_id(&law.name),
hash::mint_id("A rule holds, `x > 1`.")
);
}
}
}