prosecop 0.1.0

Checks identifiers and doc comments against a repository's house style
//! The check of the string literals of code against the rules of a ruleset's `strings.txt`.
//!
//! A string literal differs from a doc in ways that decide the literals checked and the rules:
//!
//! - Most literals are not prose but code, a key or a list of words, so only a literal shaped like a sentence is
//!   checked.
//! - A message is often built from fragments, so a literal may start in lower case, mid-sentence or after a comma.
//! - A placeholder or a span of code stands for a word or a clause, and is matched as one word.
//! - A message is terse by design, so a colon before a detail and a missing full stop are both sound.
//!
//! The literals of tests are skipped, because an assertion's message is read by whoever broke it rather than shown.

use std::collections::BTreeSet;

use crate::docs::{self, DocRules, Found};
use crate::lex::{self, Lang, Token};
use crate::python::docstrings;
use crate::rules::Ruleset;
use crate::walk::{self, Options, Root};
use crate::{Lines, Output};

/// Lowercase words, one of which a sentence or a clause of English nearly always has and a list of names does not.
const FUNCTION_WORDS: &[&str] = &[
    "a", "an", "the", "is", "are", "was", "were", "be", "been", "not", "no", "to", "of", "in", "on", "at", "by", "for",
    "from", "with", "without", "and", "or", "but", "if", "may", "might", "must", "can", "could", "would", "will",
    "should", "has", "have", "had", "does", "do", "did", "it", "its", "this", "that", "which", "whose", "than", "as",
    "into", "only", "each", "every",
];

/// Whether the string literals of a file of `lang` are checked.
pub fn reads(lang: Lang) -> bool {
    matches!(lang, Lang::Rust | Lang::Python | Lang::Script)
}

/// Whether the file at `path` has only tests, by its name or its folder.
fn test_file(path: &str) -> bool {
    regex!(r"(?:^|/)(?:tests?|__tests__)/|(?:^|/)(?:tests\.rs|test_[^/]*\.py|[^/]*_test\.py|conftest\.py)$")
        .is_match(path)
        || regex!(r"\.(?:test|spec)\.[cm]?[jt]sx?$").is_match(path)
}

/// The byte ranges of the Rust items under a `#[test]` or `#[cfg(test)]` attribute, each from the attribute to its
/// closing brace.
fn test_items(text: &str) -> Vec<(usize, usize)> {
    let b = text.as_bytes();
    let attributes = regex!(r"#\[\s*(?:cfg\(\s*test\s*\)|(?:\w+::)*test)\s*\]").find_iter(text);
    attributes
        .filter_map(|attribute| {
            let brace = attribute.end() + memchr::memchr2(b'{', b';', &b[attribute.end()..])?;
            // A module declared as `mod tests;` lives in a file of its own, which `test_file` skips.
            (b[brace] == b'{').then(|| (attribute.start(), lex::closing(b, brace, b"{", b"}")))
        })
        .collect()
}

/// The text of the literal `literal` of `lang`, without its prefix, its quotes and its escapes.
///
/// Each placeholder and span of code stands as the word `X`.
fn body(literal: &str, lang: Lang) -> String {
    let body = literal.trim_start_matches(|c: char| c.is_ascii_alphabetic() || c == '#');
    let body = body.trim_start_matches(['"', '\'', '`']).trim_end_matches(['"', '\'', '`', '#']);
    // A backslash before a newline continues a Rust string on the next line without its indent.
    let body = regex!(r"\\\r?\n\s*").replace_all(body, " ");
    let body = regex!(r"\\[nr]").replace_all(&body, "\n");
    let body = regex!(r"\\t").replace_all(&body, " ");
    let body = regex!(r#"\\(["'`\\])"#).replace_all(&body, "$1");
    let body = body.replace("{{", "(").replace("}}", ")");
    let body = match lang {
        Lang::Script => regex!(r"\$\{[^}]*\}").replace_all(&body, "X").into_owned(),
        Lang::Python => {
            regex!(r"%(?:\([^)]*\))?[-#0 +]*\d*(?:\.\d+)?[sdifrgexXc]").replace_all(&body, "X").into_owned()
        }
        _ => body,
    };
    let body = regex!(r"\{[^{}]*\}").replace_all(&body, "X");
    docs::without_code(&body)
}

/// Whether `text` reads as a sentence or a clause of one, rather than code, a name or a list of words.
fn sentence_shaped(text: &str) -> bool {
    // An identifier has no space, and an expression has an operator that prose does not use.
    if !text.contains(' ') || regex!(r"[=\[\]{}]|::|->|=>").is_match(text) {
        return false;
    }
    let words: Vec<&str> = regex!(r"[A-Za-z][A-Za-z'-]*").find_iter(text).map(|m| m.as_str()).collect();
    words.len() >= 3 && words.iter().any(|word| FUNCTION_WORDS.contains(word))
}

/// Whether the Python literal from `start` to `end` of `text` is a statement on its own, as a docstring is.
///
/// A value on a line of its own inside a call or a concatenation follows a line that leaves it open.
fn statement(text: &str, start: usize, end: usize) -> bool {
    let line_start = text[..start].rfind('\n').map_or(0, |k| k + 1);
    let line_end = text[end..].find('\n').map_or(text.len(), |k| end + k);
    let after = text[end..line_end].trim();
    if !text[line_start..start].trim().is_empty() || !(after.is_empty() || after.starts_with('#')) {
        return false;
    }
    let before = text[..line_start].trim_end();
    let previous = before.rsplit('\n').next().unwrap_or_default().split(" #").next().unwrap_or_default().trim_end();
    !previous.ends_with(['(', '[', '{', ',', '\\', '"', '\'', '+', '=', '%'])
}

/// The broken rules of each literal of the file at `path` that is shaped like a sentence, outside tests and
/// docstrings.
fn check(rules: &'static DocRules, path: &str, text: &str) -> Vec<Found> {
    let Some(lang) = Lang::of_suffix(path.rsplit('/').next().unwrap_or(path)).filter(|&lang| reads(lang)) else {
        return Vec::new();
    };
    if test_file(path) {
        return Vec::new();
    }
    let tests = if lang == Lang::Rust { test_items(text) } else { Vec::new() };
    let mut literals = Vec::new();
    lex::tokens(text, lang, |token| {
        if let Token::Str(start, end) = token
            && !tests.iter().any(|&(from, to)| from <= start && start < to)
        {
            literals.push((start, end));
        }
    });
    let docs: BTreeSet<usize> = match lang {
        Lang::Python => docstrings(text, &text.split('\n').collect::<Vec<_>>()).iter().map(|d| d.start).collect(),
        _ => BTreeSet::new(),
    };
    let mut lines = Lines::new(text);
    let mut found = Vec::new();
    for (start, end) in literals {
        let first = lines.at(start);
        let last = first + memchr::memchr_iter(b'\n', &text.as_bytes()[start..end]).count();
        // A docstring's start is the index of its first line of text, on the line of its quotes or the one below.
        if docs.range(first - 1..last).next().is_some() || lang == Lang::Python && statement(text, start, end) {
            continue;
        }
        let body = body(&text[start..end], lang);
        if !sentence_shaped(&body) {
            continue;
        }
        let parts: Vec<(usize, String)> = body.split('\n').map(|part| (first, part.to_string())).collect();
        docs::matches(&mut found, &parts, rules, false);
    }
    found
}

/// Checks the string literals of the files that `options` pick against the `strings.txt` of `ruleset`.
///
/// It then prints the advice of each rule found and the strings advice of `ruleset`.
pub fn run(ruleset: &Ruleset, root: &Root, options: &Options) -> Result<Output, String> {
    let rules = DocRules::parse(ruleset.strings.as_deref().unwrap_or_default(), "strings.txt")?;
    let results = root.walk(options, |path, buffer| {
        let read = Lang::of_suffix(path.rsplit('/').next().unwrap_or(path)).is_some_and(reads);
        let found = if read {
            check(rules, path, &walk::read(&root.path, path, buffer).unwrap_or_default())
        } else {
            Vec::new()
        };
        let lines: String =
            found.iter().map(|(line, rule, hit, _)| format!("{path}:{line}: reject: {rule}: {hit}\n")).collect();
        let names: BTreeSet<&'static str> = found.iter().map(|f| f.1).collect();
        (lines, names)
    })?;
    let mut out = Output::default();
    let mut names = BTreeSet::new();
    for (_, (lines, found)) in results {
        out.stdout.push_str(&lines);
        names.extend(found);
    }
    if !names.is_empty() {
        out.stderr += &format!("Strings of {} found:\n", ruleset.name);
        for name in &names {
            out.stderr += &format!("  {name}: {}\n", rules.advice(name));
        }
        out.stderr += &format!("\n{}", ruleset.strings_advice);
    }
    out.failed = !names.is_empty();
    Ok(out)
}