use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use regex::Regex;
pub const MAX_PROBLEMS: usize = 40;
const SLACK: usize = 5;
const EXAMPLES_PER_BLOCK: usize = 3;
const MAX_SUFFIX_MATCHES: usize = 20;
pub struct Sources<'a> {
pub workspace: &'a Path,
pub read_roots: &'a [PathBuf],
pub listing: &'a [PathBuf],
pub read: &'a dyn Fn(&Path) -> Result<String, String>,
}
struct Citation {
path: String,
ranges: Vec<(usize, usize)>,
named: bool,
}
enum Resolved {
Files(Vec<(PathBuf, Vec<String>)>),
Skip,
Missing(String),
}
fn citation_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(&format!(
r"((?:[\w./~-]*\.[A-Za-z][A-Za-z0-9_]*)|(?:[\w./~-]*/)?(?:{BARE_NAMES})):(\d+(?:-\d+)?(?:, ?\d+(?:-\d+)?)*)"
))
.expect("citation regex")
})
}
const BARE_NAMES: &str =
"Makefile|Dockerfile|Containerfile|Justfile|Gemfile|Rakefile|Procfile|Jenkinsfile|Vagrantfile";
const CODE_EXTENSIONS: &[&str] = &[
"py", "pyi", "rs", "go", "ts", "tsx", "js", "jsx", "mjs", "java", "kt", "scala", "rb", "php",
"cs", "c", "h", "cc", "cpp", "hpp", "swift", "lua", "sh", "tf", "hcl", "sql", "yaml", "yml",
"toml", "json", "ipynb",
];
const NOT_QUOTE_TAGS: &[&str] = &[
"proposed",
"diff",
"patch",
"bash",
"sh",
"shell",
"zsh",
"console",
"terminal",
"text",
"txt",
"plain",
"plaintext",
"output",
"log",
"csv",
"tsv",
"mermaid",
"markdown",
"md",
];
fn path_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(&format!(
r"(?:^|[\s`(\[])((?:[\w.~-]+/)*(?:[\w.-]*\.[A-Za-z][A-Za-z0-9_]*|{BARE_NAMES}))(?:$|[\s`):,\]])"
))
.expect("path regex")
})
}
fn lines_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"(?i)\blines?\s+(\d+)(?:\s*[-–]\s*(\d+))?").expect("lines regex"))
}
fn numbered_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(r"^\s*(\d+)(?:\t|: |:$|\s*\|\s?|\s{2,}|\s*→)(.*)$").expect("numbered regex")
})
}
fn citations(line: &str) -> Vec<Citation> {
let mut out = Vec::new();
for caps in citation_re().captures_iter(line) {
let m = caps.get(0).expect("whole match");
let path = caps[1].trim_start_matches("./").to_string();
let before = &line[..m.start()];
if before.ends_with(':') || before.ends_with(|c: char| c.is_alphanumeric() || c == '_') {
continue;
}
if path.is_empty() || path.starts_with('~') || path.starts_with("..") {
continue;
}
let mut ranges = Vec::new();
for part in caps[2].split(',') {
let part = part.trim();
let (a, b) = match part.split_once('-') {
Some((a, b)) => (a.parse().unwrap_or(0), b.parse().unwrap_or(0)),
None => {
let n = part.parse().unwrap_or(0);
(n, n)
}
};
if a > 0 {
ranges.push((a, b.max(a)));
}
}
if !ranges.is_empty() {
out.push(Citation {
path,
ranges,
named: false,
});
}
}
out
}
fn normalize(s: &str) -> String {
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn is_elision(line: &str) -> bool {
let t = line
.trim()
.trim_start_matches(['#', '/', '-', '*', ';'])
.trim_end_matches("*/")
.trim();
t.starts_with("...") || t.starts_with('…') || t.starts_with("[...]") || t.starts_with("[…]")
}
struct Resolver<'a> {
src: &'a Sources<'a>,
cache: HashMap<String, Resolved>,
}
impl<'a> Resolver<'a> {
fn lines_of(&self, p: &Path) -> Option<Vec<String>> {
(self.src.read)(p)
.ok()
.map(|t| t.lines().map(str::to_string).collect())
}
fn resolve(&mut self, path: &str) -> &Resolved {
if !self.cache.contains_key(path) {
let r = self.lookup(path);
self.cache.insert(path.to_string(), r);
}
&self.cache[path]
}
fn lookup(&self, path: &str) -> Resolved {
let p = Path::new(path);
if p.is_absolute() {
return match (self.src.read)(p) {
Ok(t) => Resolved::Files(vec![(
p.to_path_buf(),
t.lines().map(str::to_string).collect(),
)]),
Err(e) => Resolved::Missing(format!("cannot read {path}: {e}")),
};
}
let bases = std::iter::once(self.src.workspace)
.chain(self.src.read_roots.iter().map(|r| r.as_path()))
.chain(self.src.read_roots.iter().filter_map(|r| r.parent()));
for base in bases {
let candidate = base.join(p);
if let Some(lines) = self.lines_of(&candidate) {
return Resolved::Files(vec![(candidate, lines)]);
}
}
let suffix = format!("/{path}");
let mut hits: Vec<&PathBuf> = self
.src
.listing
.iter()
.filter(|f| f.to_string_lossy().ends_with(&suffix))
.collect();
hits.dedup();
if !hits.is_empty() && hits.len() <= MAX_SUFFIX_MATCHES {
let files: Vec<_> = hits
.into_iter()
.filter_map(|f| self.lines_of(f).map(|l| (f.clone(), l)))
.collect();
if !files.is_empty() {
return Resolved::Files(files);
}
} else if !hits.is_empty() {
return Resolved::Skip;
}
let ext = path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
if path.contains('/') || ext.is_some_and(|e| CODE_EXTENSIONS.contains(&e.as_str())) {
Resolved::Missing(format!("no such file: {path}"))
} else {
Resolved::Skip
}
}
}
fn excerpt(s: &str) -> String {
let t = s.trim();
if t.chars().count() > 100 {
format!("{}…", t.chars().take(100).collect::<String>())
} else {
t.to_string()
}
}
fn cite_text(c: &Citation) -> String {
let ranges: Vec<String> = c
.ranges
.iter()
.map(|&(a, b)| {
if a == b {
a.to_string()
} else {
format!("{a}-{b}")
}
})
.collect();
if ranges.is_empty() {
c.path.clone()
} else {
format!("{}:{}", c.path, ranges.join(","))
}
}
fn find_line(lines: &[String], text: &str) -> Option<usize> {
lines
.iter()
.position(|l| normalize(l) == text)
.map(|i| i + 1)
}
fn matches_line(file_line: &str, quoted: &str) -> bool {
let f = normalize(file_line);
if f == quoted || (quoted.chars().count() >= 12 && f.contains(quoted)) {
return true;
}
if !quoted.contains("...") && !quoted.contains('…') {
return false;
}
let mut rest = f.as_str();
for part in quoted.split('…').flat_map(|p| p.split("...")) {
let part = part.trim();
if part.is_empty() {
continue;
}
match rest.find(part) {
Some(at) => rest = &rest[at + part.len()..],
None => return false,
}
}
true
}
fn check_quoted_line(
files: &[(PathBuf, Vec<String>)],
windows: &[(usize, usize)],
raw: &str,
) -> Option<String> {
let whole = normalize(raw);
let numbered = numbered_re()
.captures(raw)
.and_then(|c| Some((c[1].parse::<usize>().ok()?, normalize(&c[2]))));
let near = |lines: &[String], text: &str| {
windows.iter().any(|&(lo, hi)| {
lines
.iter()
.enumerate()
.skip(lo - 1)
.take(hi + 1 - lo)
.any(|(_, l)| matches_line(l, text))
})
};
for (_, lines) in files {
if let Some((n, text)) = &numbered {
if lines
.get(n.wrapping_sub(1))
.is_some_and(|l| matches_line(l, text))
{
return None;
}
}
if near(lines, &whole) {
return None;
}
}
let (_, lines) = &files[0];
match &numbered {
Some((n, text)) => {
let actual = match lines.get(n.wrapping_sub(1)) {
Some(l) => format!("line {n} is `{}`", excerpt(l)),
None => format!("the file has {} lines", lines.len()),
};
let elsewhere = find_line(lines, text)
.map(|at| format!("; the quoted text is at line {at}"))
.unwrap_or_else(|| "; the quoted text is not in the file".to_string());
Some(format!("quoted `{}`: {actual}{elsewhere}", excerpt(raw)))
}
None => {
let elsewhere = find_line(lines, &whole)
.map(|at| format!("it is at line {at}, outside the cited lines"))
.unwrap_or_else(|| "it is not in the file".to_string());
Some(format!("quoted `{}`: {elsewhere}", excerpt(raw)))
}
}
}
pub fn check(report: &str, src: &Sources<'_>) -> Vec<String> {
let mut resolver = Resolver {
src,
cache: HashMap::new(),
};
let mut problems = Vec::new();
let mut last_text: Option<(usize, String)> = None;
let mut last_cite: Option<Citation> = None;
let lines: Vec<&str> = report.lines().collect();
let mut i = 0;
while i < lines.len() {
let line = lines[i];
let trimmed = line.trim_start();
let fence = if trimmed.starts_with("```") {
"```"
} else if trimmed.starts_with("~~~") {
"~~~"
} else {
""
};
if fence.is_empty() {
if !line.trim().is_empty() {
check_prose(&mut resolver, i + 1, line, &mut problems);
if let Some(c) = citations(line).pop() {
last_cite = Some(c);
}
last_text = Some((i + 1, line.to_string()));
}
i += 1;
continue;
}
let marker_len = trimmed
.chars()
.take_while(|&c| c == fence.chars().next().unwrap())
.count();
let info = trimmed[marker_len..].trim().to_lowercase();
let close = fence.chars().next().unwrap().to_string().repeat(marker_len);
let start = i + 1;
let mut end = start;
while end < lines.len() && !lines[end].trim_start().starts_with(&close) {
end += 1;
}
let mut body = &lines[start..end.min(lines.len())];
let lang = info.split_whitespace().next().unwrap_or("");
let lead_in = last_text.take().map(|(_, t)| t);
let mut anchor = lead_in.as_deref().and_then(|t| citations(t).pop());
let first = body.iter().position(|l| !l.trim().is_empty());
if let Some(f) = first {
let head = body[f].trim_start();
if ["#", "//", "--", "/*"].iter().any(|c| head.starts_with(c)) {
if let Some(c) = citations(head).pop() {
anchor = Some(c);
body = &body[f + 1..];
}
}
}
if anchor.is_none() {
anchor = lead_in.as_deref().and_then(named_path);
}
if anchor.is_none() {
if let (Some(t), Some(prev)) = (lead_in.as_deref(), &last_cite) {
if let Some(ranges) = lead_in_lines(t) {
anchor = Some(Citation {
path: prev.path.clone(),
ranges,
named: true,
});
}
}
}
let numbered = mostly_numbered(body);
let anchor = match anchor {
Some(c) => Some(c),
None if numbered => last_cite.take(),
None => None,
};
let is_quote = !NOT_QUOTE_TAGS.contains(&lang) && (!lang.is_empty() || numbered);
match &anchor {
Some(cite) if !matches!(lang, "diff" | "patch" | "proposed") => {
check_block(&mut resolver, start, cite, body, &mut problems)
}
None if is_quote && body.iter().any(|l| !l.trim().is_empty()) => {
let tag = if lang.is_empty() { "numbered" } else { lang };
problems.push(format!(
"report.md:{start}: {tag} code block with no citation: put `path:N-M` on the \
line before it if it is quoted from a file, or tag it ```proposed if it is \
not in the repository"
));
}
_ => {}
}
if anchor.is_some() {
last_cite = anchor;
}
i = end + 1;
}
problems
}
fn named_path(line: &str) -> Option<Citation> {
let path = path_re()
.captures_iter(line)
.map(|c| c[1].trim_start_matches("./").to_string())
.filter(|p| !p.starts_with('~') && !p.starts_with(".."))
.filter(|p| p.contains('/') || line.contains(&format!("`{p}`")) || p.ends_with("file"))
.last()?;
let ranges = lead_in_lines(line).unwrap_or_default();
Some(Citation {
path,
ranges,
named: true,
})
}
fn lead_in_lines(line: &str) -> Option<Vec<(usize, usize)>> {
let c = lines_re().captures(line)?;
let a: usize = c[1].parse().ok()?;
let b = c.get(2).and_then(|m| m.as_str().parse().ok()).unwrap_or(a);
(a > 0).then_some(vec![(a, b.max(a))])
}
fn mostly_numbered(body: &[&str]) -> bool {
let lines: Vec<&&str> = body
.iter()
.filter(|l| !l.trim().is_empty() && !is_elision(l))
.collect();
let numbered = lines.iter().filter(|l| numbered_re().is_match(l)).count();
!lines.is_empty() && numbered * 2 >= lines.len()
}
fn check_prose(resolver: &mut Resolver<'_>, at: usize, line: &str, problems: &mut Vec<String>) {
for cite in citations(line) {
match resolver.resolve(&cite.path) {
Resolved::Skip => {}
Resolved::Missing(why) => {
problems.push(format!("report.md:{at}: {}: {why}", cite_text(&cite)))
}
Resolved::Files(files) => {
let last = cite.ranges.iter().map(|&(_, b)| b).max().unwrap_or(0);
if files.iter().all(|(_, l)| last > l.len()) {
let (p, l) = &files[0];
problems.push(format!(
"report.md:{at}: {}: line {last} is past the end of {} ({} lines)",
cite_text(&cite),
p.display(),
l.len()
));
}
}
}
}
}
fn check_block(
resolver: &mut Resolver<'_>,
start: usize,
cite: &Citation,
body: &[&str],
problems: &mut Vec<String>,
) {
let files = match resolver.resolve(&cite.path) {
Resolved::Files(f) => f,
Resolved::Missing(why) if cite.named => {
let why = why.clone();
problems.push(format!(
"report.md:{start}: code block quoting {}: {why}; tag the block ```proposed if \
it is a file you propose",
cite.path
));
return;
}
_ => return,
};
let quoted: Vec<&str> = body
.iter()
.copied()
.filter(|l| !l.trim().is_empty() && !is_elision(l))
.collect();
if quoted.is_empty() {
return;
}
let windows: Vec<(usize, usize)> = if cite.ranges.is_empty() {
vec![(1, usize::MAX / 2)]
} else {
cite.ranges
.iter()
.map(|&(a, b)| {
(
a.saturating_sub(SLACK).max(1),
b.max(a + body.len()) + SLACK,
)
})
.collect()
};
let bad: Vec<String> = quoted
.iter()
.filter_map(|l| check_quoted_line(files, &windows, l))
.collect();
if bad.is_empty() {
return;
}
let mut msg = format!(
"report.md:{start}: code block quoting {}: {} of {} lines do not match the file",
cite_text(cite),
bad.len(),
quoted.len()
);
for b in bad.iter().take(EXAMPLES_PER_BLOCK) {
msg.push_str("\n ");
msg.push_str(b);
}
problems.push(msg);
}
pub fn render(problems: &[String]) -> String {
let mut out = format!(
"report.md quote check: {} problem(s). A code block right after a `path:line` citation \
must be copied from that file, and cited lines must exist.\n",
problems.len()
);
for p in problems.iter().take(MAX_PROBLEMS) {
out.push_str("- ");
out.push_str(p);
out.push('\n');
}
if problems.len() > MAX_PROBLEMS {
out.push_str(&format!(
"- ... and {} more\n",
problems.len() - MAX_PROBLEMS
));
}
out.push_str(
"Re-read each cited file with the read tool and quote it exactly, correct the line \
numbers, or remove the claim. Mark code you propose rather than quote as ```proposed.",
);
out
}