use std::sync::OnceLock;
use aho_corasick::AhoCorasick;
use fancy_regex::Regex as Fancy;
use regex::Regex;
use crate::lex::Lang;
use crate::python::docstrings;
use crate::rules::Ruleset;
use crate::walk::{self, Options, Root};
use crate::{Lines, Output, py_space};
const SENTENCE_WORDS: usize = 30;
const SUMMARY_WORDS: usize = 25;
#[derive(Default)]
struct Rule {
name: String,
rejects: bool,
markdown: bool,
pattern: String,
words: Vec<String>,
advice: String,
superset: Option<Regex>,
exact: OnceLock<Fancy>,
}
pub struct DocRules {
rules: Vec<Rule>,
search: AhoCorasick,
groups: Vec<usize>,
masks: Vec<u64>,
}
impl DocRules {
pub fn parse(text: &str, file: &str) -> Result<&'static DocRules, String> {
let (mut rules, mut values) = (Vec::<Rule>::new(), Vec::<(String, String)>::new());
for (n, line) in text.lines().enumerate().map(|(n, l)| (n + 1, l.trim_start())) {
let error = |message: &str| format!("{file}:{n}: {message}");
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some(name) = line.strip_prefix('[').and_then(|l| l.trim_end().strip_suffix(']')) {
rules.push(Rule { name: name.to_string(), rejects: true, ..Rule::default() });
continue;
}
let (key, value) = line.split_once(" = ").ok_or_else(|| error("expected `KEY = VALUE`"))?;
let value = value.trim_end();
let value = value.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(value);
let value = substitute(value, &values).map_err(|e| error(&e))?;
if let Some(name) = key.strip_prefix("let ") {
values.push((name.trim().to_string(), value));
continue;
}
let rule = rules.last_mut().ok_or_else(|| error("a field must follow a `[NAME]`"))?;
match (key.trim(), value.as_str()) {
("verdict", "reject" | "warn") => rule.rejects = value == "reject",
("markdown", "true" | "false") => rule.markdown = value == "true",
("pattern", _) => rule.pattern = value,
("words", _) => rule.words.push(value),
("advice", _) => rule.advice = value,
(key, _) => return Err(error(&format!("unknown field or value: {key} = {value}"))),
}
}
for rule in &mut rules {
let error = |e: &dyn std::fmt::Display| format!("{file}: [{}]: {e}", rule.name);
if rule.pattern.is_empty() || rule.words.is_empty() {
return Err(error(&"a rule needs a pattern and words"));
}
rule.superset = Some(Regex::new(&without_lookahead(&rule.pattern)).map_err(|e| error(&e))?);
if rule.pattern.contains("(?!") {
fancy_regex::Expr::parse_tree(&rule.pattern).map_err(|e| error(&e))?;
}
}
let groups: Vec<&str> = rules.iter().flat_map(|r| r.words.iter().map(String::as_str)).collect();
if groups.len() > 64 {
return Err(format!("{file}: {} groups of words, past the most of 64", groups.len()));
}
let words: Vec<(&str, usize)> =
groups.iter().enumerate().flat_map(|(g, w)| w.split('|').map(move |w| (w, g))).collect();
let search = AhoCorasick::builder().ascii_case_insensitive(true).build(words.iter().map(|w| w.0));
let mut first = 0;
let masks = rules.iter().map(|r| {
first += r.words.len();
((1u64 << r.words.len()) - 1) << (first - r.words.len())
});
let masks = masks.collect();
let search = search.map_err(|e| format!("{file}: {e}"))?;
let groups = words.iter().map(|w| w.1).collect();
Ok(Box::leak(Box::new(DocRules { rules, search, groups, masks })))
}
}
impl DocRules {
pub fn advice(&self, name: &str) -> &str {
self.rules.iter().find(|rule| rule.name == name).map_or("", |rule| rule.advice.as_str())
}
}
fn substitute(value: &str, values: &[(String, String)]) -> Result<String, String> {
let mut out = String::new();
let mut rest = value;
while let Some(at) = rest.find('{') {
out.push_str(&rest[..at]);
let name = rest[at + 1..].split('}').next().filter(|n| n.starts_with(|c: char| c.is_ascii_alphabetic()));
match name.filter(|_| rest[at + 1..].contains('}')) {
Some(name) => {
let (_, text) = values.iter().find(|(n, _)| n == name).ok_or(format!("{{{name}}} is not defined"))?;
out.push_str(text);
rest = &rest[at + name.len() + 2..];
}
None => {
out.push('{');
rest = &rest[at + 1..];
}
}
}
Ok(out + rest)
}
fn without_lookahead(pattern: &str) -> String {
let mut out = String::new();
let mut rest = pattern;
while let Some(at) = rest.find("(?!") {
out.push_str(&rest[..at]);
let mut depth = 0;
let end = rest[at..]
.char_indices()
.find(|&(_, c)| {
depth += match c {
'(' => 1,
')' => -1,
_ => 0,
};
depth == 0
})
.map_or(rest.len(), |(k, _)| at + k + 1);
rest = &rest[end..];
}
out + rest
}
pub type Found = (usize, &'static str, String, bool);
pub fn matches(found: &mut Vec<Found>, lines: &[(usize, String)], rules: &'static DocRules, markdown: bool) {
let DocRules { rules, search, groups, masks } = rules;
for (k, line) in lines {
let plain = line.bytes().all(|b| b.is_ascii() && (b == b' ' || !b.is_ascii_whitespace() && b > 0x1f))
&& memchr::memmem::find(line.as_bytes(), b" ").is_none();
let mut present = 0u64;
for hit in search.find_overlapping_iter(line.as_str()) {
present |= 1 << groups[hit.pattern().as_usize()];
}
for (r, rule) in rules.iter().enumerate() {
let superset = rule.superset.as_ref().unwrap();
if markdown && !rule.markdown || plain && present & masks[r] != masks[r] || !superset.is_match(line) {
continue;
}
let hits: Vec<&str> = match rule.pattern.contains("(?!") {
true => {
let exact = rule.exact.get_or_init(|| Fancy::new(&rule.pattern).unwrap());
exact.find_iter(line).filter_map(Result::ok).map(|m| m.as_str()).collect()
}
false => superset.find_iter(line).map(|m| m.as_str()).collect(),
};
found.extend(hits.into_iter().map(|hit| (*k, rule.name.as_str(), format!("\"{hit}\""), rule.rejects)));
}
}
}
fn list_item(line: &str) -> Option<usize> {
regex!(r"^\s*(?:[-*]|\d+\.)\s+").find(line).map(|m| m.end())
}
fn strip(s: &str) -> &str {
s.trim_matches(py_space)
}
fn doc_line(line: &str) -> Option<(char, &str)> {
let rest = line.trim_start_matches(py_space).strip_prefix("//")?;
let kind = rest.chars().next().filter(|c| matches!(c, '/' | '!'))?;
let after = &rest[1..];
if after.starts_with(['/', '!']) {
return None;
}
Some((kind, after.strip_prefix(' ').unwrap_or(after)))
}
type Block<'a> = (char, usize, Vec<&'a str>, &'a str, Vec<&'a str>);
fn line_at(text: &str, at: usize) -> Option<(&str, usize)> {
let end = at + memchr::memchr(b'\n', text.as_bytes().get(at..)?).unwrap_or(text.len() - at);
Some((&text[at..end], end + 1))
}
fn blocks(text: &str) -> Vec<Block<'_>> {
let b = text.as_bytes();
let (mut found, mut from, mut numbers) = (Vec::new(), 0, Lines::new(text));
while let Some(k) = b.get(from..).and_then(|rest| memchr::memmem::find(rest, b"//")) {
let mut at = memchr::memrchr(b'\n', &b[..from + k]).map_or(0, |i| i + 1);
let Some((first, next)) = line_at(text, at) else { break };
let Some((kind, _)) = doc_line(first) else {
from = next;
continue;
};
let line = numbers.at(at) - 1;
let mut lines = Vec::new();
while let Some((doc, next)) = line_at(text, at).and_then(|(l, n)| Some((doc_line(l)?, n)))
&& doc.0 == kind
{
lines.push(doc.1);
at = next;
}
from = at;
let (mut attributes, mut depth, mut item) = (Vec::new(), 0i64, "");
while let Some((l, next)) = line_at(text, at) {
let stripped = strip(l);
if depth == 0 && !stripped.starts_with("#[") && !stripped.is_empty() && !stripped.starts_with("//") {
item = stripped;
break;
}
if stripped.starts_with("#[") || depth != 0 {
attributes.push(stripped);
depth += stripped.matches('[').count() as i64 - stripped.matches(']').count() as i64;
}
at = next;
}
found.push((kind, line, lines, item, attributes));
}
found
}
fn classify(kind: char, item: &str, attributes: &[&str]) -> &'static str {
if kind == '!' {
return "module";
}
if attributes.iter().any(|a| regex!(r"#\[(?:[\w:]+::)?test\]").is_match(a)) && regex!(r"\bfn\b").is_match(item) {
return "test";
}
"item"
}
fn prose<S: AsRef<str>>(text: &[S]) -> Vec<Vec<(usize, &str)>> {
let (mut paragraphs, mut current, mut fenced) = (Vec::new(), Vec::new(), false);
for (k, line) in text.iter().enumerate() {
let line = line.as_ref();
let stripped = strip(line);
if stripped.starts_with("```") {
fenced = !fenced;
continue;
}
let in_item = current.first().is_some_and(|&(_, first)| list_item(first).is_some());
let code = fenced || line.starts_with(" ") && !in_item || stripped.starts_with('|');
if stripped.is_empty() || code || list_item(line).is_some() && !current.is_empty() {
if !current.is_empty() {
paragraphs.push(std::mem::take(&mut current));
}
if stripped.is_empty() || code {
continue;
}
}
current.push((k, stripped));
}
if !current.is_empty() {
paragraphs.push(current);
}
paragraphs
}
pub fn without_code(s: &str) -> String {
let s = regex!(r"`[^`]*`").replace_all(s, "X");
let s = regex!(r"\]\([^)]*\)").replace_all(&s, "]");
regex!(r"(?i)\b(?:e\.g|i\.e|etc|vs|cf)\.").replace_all(&s, "eg").into_owned()
}
fn sentences(joined: &str) -> Vec<&str> {
let mut found = Vec::new();
let (mut from, mut i) = (0, 0);
let b = joined.as_bytes();
while let Some(k) = memchr::memchr3(b'.', b'!', b'?', &b[i..]) {
let end = i + k + 1;
let next = joined[end..].trim_start_matches(py_space);
let after = joined.len() - next.len();
if after > end && next.starts_with(|c: char| c.is_ascii_uppercase() || c.is_ascii_digit() || "[(\"".contains(c))
{
found.push(&joined[from..end]);
from = after;
}
i = after.max(end);
}
found.push(&joined[from..]);
found.retain(|s| !strip(s).is_empty());
found
}
fn head(s: &str) -> String {
format!("\"{}…\"", s.chars().take(60).collect::<String>())
}
fn check_block<S: AsRef<str>>(
rules: &'static DocRules,
kind: char,
text: &[S],
item: &str,
attributes: &[&str],
) -> Vec<Found> {
let what = classify(kind, item, attributes);
if what == "test" {
return vec![(0, "test doc", "a #[test] function may not have a doc comment".into(), true)];
}
let mut found = Vec::new();
for (n, paragraph) in prose(text).iter().enumerate() {
let first = paragraph[0].0;
let mut parts: Vec<&str> = paragraph.iter().map(|p| p.1).collect();
parts[0] = list_item(parts[0]).map_or(parts[0], |end| &parts[0][end..]);
let joined = without_code(&parts.join(" "));
let all = sentences(&joined);
if n == 0 && all.len() > 1 && !list_item(paragraph[0].1).is_some() {
found.push((first, "summary", "the first paragraph must be one sentence".into(), true));
}
for (m, s) in all.iter().enumerate() {
let words = s.split(py_space).filter(|w| !w.is_empty()).count();
if n == 0 && m == 0 && what != "module" && words > SUMMARY_WORDS {
let message = format!("the first sentence must be at most {SUMMARY_WORDS} words, not {words}");
found.push((first, "summary", message, true));
} else if words > SENTENCE_WORDS {
let message = format!("a sentence must be at most {SENTENCE_WORDS} words, not {words}: {}", head(s));
found.push((first, "long sentence", message, true));
}
if regex!(r"(?i)\beach\b").find_iter(s).count() > 1 {
let message = format!("a sentence may not repeat \"each\": {}", head(s));
found.push((first, "each chain", message, true));
}
}
let lines: Vec<(usize, String)> =
paragraph.iter().map(|&(k, l)| (k, regex!(r"`[^`]*`").replace_all(l, "X").into_owned())).collect();
matches(&mut found, &lines, rules, false);
}
found
}
fn sections(text: &[String]) -> Vec<(usize, String)> {
let mut lines = Vec::new();
let mut section: Option<&str> = None;
for (k, line) in text.iter().enumerate() {
if let Some(heading) =
line.strip_suffix(':').filter(|h| matches!(*h, "Parameters" | "Returns" | "Notes" | "References"))
{
section = Some(heading);
lines.push((k, String::new()));
} else if section.is_none() {
lines.push((k, line.clone()));
} else if section == Some("References") {
continue;
} else if let Some(entry) =
regex!(r"^ \*{0,2}\w+:(?: (.*))?$").captures(line).filter(|_| section != Some("Notes"))
{
lines.push((k, String::new()));
lines.push((k, entry.get(1).map_or("", |m| m.as_str()).to_string()));
} else {
lines.push((k, strip(line).to_string()));
}
}
lines
}
fn check_python(rules: &'static DocRules, path: &str, source: &str) -> Vec<Found> {
let mut found = Vec::new();
let test_module = regex!(r"(^|/)(tests?/|test_[^/]*\.py$|tests\.py$)").is_match(path);
let source_lines: Vec<&str> = source.split('\n').collect();
for doc in docstrings(source, &source_lines) {
if doc.kind == '!' && test_module {
let message = "a test module may not have a module docstring".into();
found.push((doc.start + 1, "test module doc", message, true));
continue;
}
let prose = sections(&doc.text);
let lines: Vec<&str> = prose.iter().map(|p| p.1.as_str()).collect();
for (offset, rule, message, rejects) in check_block(rules, doc.kind, &lines, "", &[]) {
found.push((doc.start + prose[offset].0 + 1, rule, message, rejects));
}
}
found
}
fn check_markdown(rules: &'static DocRules, text: &str) -> Vec<Found> {
let lines: Vec<&str> = text.split('\n').map(|l| if l.starts_with('#') { "" } else { l }).collect();
let mut found = Vec::new();
for paragraph in prose(&lines) {
let lines: Vec<(usize, String)> = paragraph
.iter()
.map(|&(k, l)| (k + 1, regex!(r#""[^"]*""#).replace_all(&without_code(l), "X").into_owned()))
.collect();
matches(&mut found, &lines, rules, true);
}
found
}
fn check_rust(rules: &'static DocRules, path: &str, text: &str) -> Vec<Found> {
let test_module = format!("/{path}").contains("/tests/") || path.ends_with("tests.rs");
let mut found = Vec::new();
for (kind, start, block, item, attributes) in blocks(text) {
if kind == '!' && test_module {
found.push((start + 1, "test module doc", "a test module may not have a module doc".into(), true));
continue;
}
for (offset, rule, message, rejects) in check_block(rules, kind, &block, item, &attributes) {
found.push((start + offset + 1, rule, message, rejects));
}
}
found
}
fn check(rules: &'static DocRules, path: &str, text: &str) -> (String, bool) {
let found = match Lang::of_suffix(path.rsplit('/').next().unwrap_or(path)) {
Some(Lang::Python) => check_python(rules, path, text),
Some(Lang::Prose) => check_markdown(rules, text),
Some(Lang::Rust) => check_rust(rules, path, text),
_ => return (String::new(), false),
};
let mut out = String::new();
for (line, rule, message, rejects) in &found {
let verdict = if *rejects { "reject" } else { "warn" };
out.push_str(&format!("{path}:{line}: {verdict}: {rule}: {message}\n"));
}
(out, found.iter().any(|f| f.3))
}
pub fn reads(lang: Lang) -> bool {
matches!(lang, Lang::Rust | Lang::Python | Lang::Prose)
}
pub fn run(ruleset: &Ruleset, root: &Root, options: &Options) -> Result<Output, String> {
let rules = DocRules::parse(ruleset.docs.as_deref().unwrap_or_default(), "docs.txt")?;
let results = root.walk(options, |path, buffer| {
match Lang::of_suffix(path.rsplit('/').next().unwrap_or(path)).is_some_and(reads) {
true => check(rules, path, &walk::read(&root.path, path, buffer).unwrap_or_default()),
false => (String::new(), false),
}
})?;
let mut out = Output::default();
for (_, (lines, rejects)) in results {
out.stdout.push_str(&lines);
out.failed |= rejects;
}
Ok(out)
}