prosecop 0.1.0

Checks identifiers and doc comments against a repository's house style
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! The check of Rust doc comments, Python docstrings, and Markdown and plain text against the rules of a ruleset's
//! `docs.txt`.
//!
//! Each violation is reported with the name of its rule.
//!
//! A Rust doc and a Python docstring are checked for the rules of prose and shape, and Markdown and plain text for
//! house style. A warning never rejects.

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;

/// A rule found by pattern, which rejects or only warns.
///
/// - A rule that only warns finds a broken rule often enough to look at, but too loosely to reject.
/// - A match of a rule has a word of each of its groups of `words`, separated by `|`, in ASCII without case,
///   wherever its whitespace is single spaces. A line that has other whitespace, or a character outside ASCII, which
///   case folding could match, is matched by every rule.
#[derive(Default)]
struct Rule {
    name: String,
    rejects: bool,
    /// Whether Markdown and plain text are checked for this rule, and not only docs.
    markdown: bool,
    pattern: String,
    words: Vec<String>,
    /// What to do about a match, which a check that reports advice prints once for the rule.
    advice: String,
    /// The pattern without its lookaheads, which finds a line worth matching faster.
    superset: Option<Regex>,
    /// The pattern, where it has a lookahead, compiled where a line first needs it.
    ///
    /// Compiling one takes longer than checking most files.
    exact: OnceLock<Fancy>,
}

/// The rules of a `docs.txt`, with the search for every word of their groups.
pub struct DocRules {
    rules: Vec<Rule>,
    /// The search for the words of all groups, the group of every word, and the groups of every rule.
    search: AhoCorasick,
    groups: Vec<usize>,
    masks: Vec<u64>,
}

impl DocRules {
    /// The rules of `text`, in the format that `claude@5/docs.txt` describes, kept for the rest of the process.
    ///
    /// A rule's name lives as long as each broken rule found, which outlives one file's check.
    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))?);
            // Only the syntax of a pattern with a lookahead is checked here, since compiling it takes longer than
            // checking most files, and the superset compiles the rest of it.
            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 {
    /// The advice of the rule named `name`, which is empty where the rule gives none.
    pub fn advice(&self, name: &str) -> &str {
        self.rules.iter().find(|rule| rule.name == name).map_or("", |rule| rule.advice.as_str())
    }
}

/// `value` with each `{NAME}` of `values` replaced by its value.
///
/// A brace before a letter cannot start a repetition of a regular expression, so a `{NAME}` stands for a value.
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)
}

/// `pattern` without its negative lookaheads, which matches wherever `pattern` matches.
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
}

/// A broken rule, as its line, the rule, the message and whether it rejects.
pub type Found = (usize, &'static str, String, bool);

/// Adds to `found` every hit of `rules` in `lines`, which pair a line number with its text.
///
/// Where `markdown`, only the rules that Markdown is checked for are matched.
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)));
        }
    }
}

/// The end of the marker of a list item that starts `line`.
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)
}

/// The text of a doc comment line, as its kind, `/` or `!`, and its text after one optional 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)))
}

/// A doc comment block, as its kind, the index of its first line, its text lines, the item and its attributes.
type Block<'a> = (char, usize, Vec<&'a str>, &'a str, Vec<&'a str>);

/// The line of `text` that starts at `at`, and the offset of the next line, as `str.split("\n")` splits them.
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))
}

/// Each doc comment block of `text`, found by searching for `//` rather than by reading lines, since most have none.
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"
}

/// The paragraphs of `text` as lists of (line offset, text), without code, tables and fenced blocks, and each
/// list item its own paragraph.
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()
}

/// The sentences of `joined`, split as `(?<=[.!?])\s+(?=[A-Z\[("X0-9])` splits it.
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
}

/// The first sixty characters of `s`, quoted.
fn head(s: &str) -> String {
    format!("\"{}…\"", s.chars().take(60).collect::<String>())
}

/// Each broken rule of one doc block, by its offset in the block.
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
}

/// The prose of docstring lines `text` as (line offset, line), without section headings and references, and an
/// entry's name dropped from its first line.
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
}

/// The lines that report each broken rule of the file at `path`, and whether one of them rejects it.
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))
}

/// Whether the docs of a file of `lang` are checked: a Rust doc comment, a Python docstring, or prose.
pub fn reads(lang: Lang) -> bool {
    matches!(lang, Lang::Rust | Lang::Python | Lang::Prose)
}

/// Checks the docs of the files that `options` pick against the rules of `ruleset`.
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| {
        // Only a file of a language that this check reads is opened.
        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)
}