prosecop 0.1.0

Checks identifiers and doc comments against a repository's house style
//! The check of identifiers, which fails where an identifier or a file name has a forbidden word of a [`Ruleset`].

use std::collections::{BTreeSet, HashMap, HashSet};

use crate::lex::{self, Lang, Token};
use crate::rules::Ruleset;
use crate::walk::{self, Options, Root};
use crate::{Lines, Output};

/// Where a forbidden word is allowed: under the path prefixes in `paths` and inside the compounds in `compounds`.
#[derive(Default)]
struct Scope {
    paths: Vec<String>,
    compounds: Vec<Vec<String>>,
    reason: String,
}

impl Scope {
    /// Whether the word at `index` of the identifier split into `parts` is allowed in the file at `path`.
    fn allows(&self, path: &str, parts: &[String], index: usize) -> bool {
        self.paths.iter().any(|p| path.starts_with(p.as_str()))
            || self.compounds.iter().any(|compound| {
                let first = index.saturating_sub(compound.len() - 1);
                (first..=index).any(|start| parts.get(start..start + compound.len()) == Some(compound))
            })
    }
}

/// The forbidden words, with a lookup by length and first letter that needs no allocation.
struct Forbidden {
    scopes: HashMap<String, Scope>,
    buckets: Vec<Vec<String>>,
}

impl Forbidden {
    /// The words of the word list `text`, with the words of `forbid` added, then the words of `allow` taken out.
    ///
    /// An entry of `allow` with an underscore, such as `held_kib`, is a compound that allows each word inside it.
    fn parse(text: &str, forbid: &[String], allow: &[String]) -> Forbidden {
        let mut scopes = HashMap::new();
        for line in text.lines() {
            let (body, reason) = line.split_once('#').unwrap_or((line, ""));
            let mut tokens = body.split_whitespace();
            let Some(word) = tokens.next() else { continue };
            let mut scope = Scope { reason: reason.trim().to_string(), ..Scope::default() };
            let mut target = None;
            for token in tokens {
                match token {
                    "except" | "allow" => target = Some(token == "except"),
                    path if target == Some(true) => scope.paths.push(path.to_string()),
                    compound if target == Some(false) => {
                        scope.compounds.push(compound.to_lowercase().split('_').map(String::from).collect())
                    }
                    _ => {}
                }
            }
            scopes.insert(word.to_string(), scope);
        }
        for word in forbid {
            let reason = "The word is forbidden by --forbid.".to_string();
            scopes.entry(word.to_lowercase()).or_insert(Scope { reason, ..Scope::default() });
        }
        for entry in allow {
            let compound: Vec<String> = entry.to_lowercase().split('_').map(String::from).collect();
            if compound.len() == 1 {
                scopes.remove(&compound[0]);
            } else {
                for word in &compound {
                    if let Some(scope) = scopes.get_mut(word) {
                        scope.compounds.push(compound.clone());
                    }
                }
            }
        }
        let mut buckets = vec![Vec::new(); 26 * 26];
        for word in scopes.keys() {
            if let Some(bucket) = Self::bucket(word.as_bytes()) {
                buckets[bucket].push(word.clone());
            }
        }
        Forbidden { scopes, buckets }
    }

    /// The bucket of the words that start with the first two letters of `word`.
    fn bucket(word: &[u8]) -> Option<usize> {
        let letter = |c: &u8| c.to_ascii_lowercase().checked_sub(b'a').filter(|&c| c < 26).map(usize::from);
        Some(letter(word.first()?)? * 26 + letter(word.get(1)?)?)
    }

    /// Whether `word`, a run of ASCII letters compared without case, is forbidden.
    fn has(&self, word: &[u8]) -> bool {
        Self::bucket(word).is_some_and(|b| self.buckets[b].iter().any(|w| w.as_bytes().eq_ignore_ascii_case(word)))
    }
}

/// Calls `f` with each word of an identifier or a file name, split as `[A-Z]+(?![a-z])|[A-Z]?[a-z]+` finds them.
fn words<'a>(name: &'a [u8], mut f: impl FnMut(&'a [u8]) -> bool) -> bool {
    let run = |mut q: usize, class: fn(&u8) -> bool| {
        while name.get(q).is_some_and(class) {
            q += 1;
        }
        q
    };
    let mut p = 0;
    while p < name.len() {
        let mut q = p + 1;
        if name[p].is_ascii_uppercase() {
            q = run(q, u8::is_ascii_uppercase);
            if name.get(q).is_some_and(u8::is_ascii_lowercase) {
                if q - p >= 2 && f(&name[p..q - 1]) {
                    return true;
                }
                (p, q) = (q - 1, run(q, u8::is_ascii_lowercase));
            }
        } else if name[p].is_ascii_lowercase() {
            q = run(q, u8::is_ascii_lowercase);
        } else {
            p = q;
            continue;
        }
        if f(&name[p..q]) {
            return true;
        }
        p = q;
    }
    false
}

/// An identifier that has a forbidden word, by its line, its name and the macros whose invocations enclose it.
///
/// The macros are listed only after `fn` outside a test, since a macro that another file defines may make a test.
type Ident = (usize, String, Option<Vec<String>>);

/// What one file contributes to the report.
#[derive(Default)]
struct Scan {
    lexed: bool,
    idents: Vec<Ident>,
    macros: Vec<String>,
}

fn scan(path: &str, text: &str, forbidden: &Forbidden) -> Scan {
    let name = path.rsplit('/').next().unwrap_or(path);
    let shebang = text.starts_with("#!/usr/bin/env python");
    let lang = Lang::of_suffix(name).filter(|&lang| lang != Lang::Prose);
    let Some(lang) = lang.or(shebang.then_some(Lang::Python)) else {
        return Scan::default();
    };
    let keyword = if lang == Lang::Python { "def" } else { "fn" };
    let mut idents = Vec::new();
    let (mut after_test, mut previous) = (false, false);
    lex::tokens(text, lang, |token| match token {
        Token::Test => after_test = true,
        Token::Str(..) => {}
        Token::Ident(start, end) => {
            let ident = &text[start..end];
            let exempt = previous && if lang == Lang::Python { ident.starts_with("test") } else { after_test };
            if !exempt && words(ident.as_bytes(), |w| forbidden.has(w)) {
                idents.push((start, ident, previous && lang != Lang::Python));
            }
            after_test &= !exempt;
            previous = ident == keyword;
        }
    });
    let mut lines = Lines::new(text);
    let idents = idents
        .into_iter()
        .map(|(offset, name, after_fn)| {
            (lines.at(offset), name.to_string(), after_fn.then(|| invocations(text, offset)))
        })
        .collect();
    let macros = if lang == Lang::Rust { test_macros(text) } else { Vec::new() };
    Scan { lexed: true, idents, macros }
}

/// The names of the macros that `text` defines with a `#[test]` in their body.
fn test_macros(text: &str) -> Vec<String> {
    if memchr::memmem::find(text.as_bytes(), b"macro_rules!").is_none() {
        return Vec::new();
    }
    let b = text.as_bytes();
    regex!(r"macro_rules!\s+(\w+)\s*\{")
        .captures_iter(text)
        .filter_map(|caps| {
            let body = caps.get(0)?.end();
            let end = lex::closing(b, body - 1, b"{", b"}");
            memchr::memmem::find(&b[body..end], b"#[test]").map(|_| caps[1].to_string())
        })
        .collect()
}

/// The names of the macros whose invocations `name! {` in `text` enclose `offset`.
fn invocations(text: &str, offset: usize) -> Vec<String> {
    let b = text.as_bytes();
    let mut names = Vec::new();
    for bang in memchr::memchr_iter(b'!', &b[..offset]) {
        let start = text[..bang]
            .char_indices()
            .rev()
            .take_while(|&(i, _)| lex::word_end(text, i) == bang)
            .last()
            .map_or(bang, |(i, _)| i);
        let brace = bang + 1 + text[bang + 1..].len() - text[bang + 1..].trim_start_matches(crate::py_space).len();
        if start < bang && b.get(brace) == Some(&b'{') {
            let end = lex::closing(b, brace, b"{", b"}");
            if brace < offset && offset < end {
                names.push(text[start..bang].to_string());
            }
        }
    }
    names
}

/// The heading and a line for each of `keys` with its reason.
fn reasons<'a>(heading: &str, keys: &BTreeSet<String>, reason: impl Fn(&str) -> &'a str) -> String {
    keys.iter().fold(format!("{heading}\n"), |out, key| out + &format!("  {key}: {}\n", reason(key)))
}

/// Whether the identifiers of a file of `lang` are checked, which is every language except prose.
pub fn reads(lang: Lang) -> bool {
    lang != Lang::Prose
}

/// Checks the identifiers and the file names of the files that `options` pick against the word list of `ruleset`.
pub fn run(ruleset: &Ruleset, root: &Root, options: &Options) -> Result<Output, String> {
    let list = ruleset.identifiers.as_deref().unwrap_or_default();
    let forbidden = Forbidden::parse(list, &options.forbid, &options.allow);
    let scans = root.walk(options, |path, buffer| {
        let name = path.rsplit('/').next().unwrap_or(path);
        if Lang::of_suffix(name).map_or(name.contains('.'), |lang| lang == Lang::Prose) {
            return Scan::default();
        }
        walk::read(&root.path, path, buffer).map_or_else(Scan::default, |t| scan(path, &t, &forbidden))
    })?;
    let macros: HashSet<&str> = scans.iter().flat_map(|(_, s)| &s.macros).map(String::as_str).collect();
    let mut out = Output::default();
    let mut found = BTreeSet::new();
    for (path, scan) in &scans {
        let mut parts: Vec<&str> = path.split('/').collect();
        if !scan.lexed {
            parts.pop();
        }
        let idents = scan.idents.iter().filter(|(_, _, invoked)| {
            !invoked.as_ref().is_some_and(|names| names.iter().any(|m| macros.contains(m.as_str())))
        });
        let names = parts.into_iter().map(|p| (1, p)).chain(idents.map(|(l, n, _)| (*l, n.as_str())));
        for (line, name) in names {
            let mut lowered = Vec::new();
            words(name.as_bytes(), |w| {
                lowered.push(String::from_utf8_lossy(w).to_lowercase());
                false
            });
            for (index, word) in lowered.iter().enumerate() {
                if let Some(scope) = forbidden.scopes.get(word)
                    && !scope.allows(path, &lowered, index)
                {
                    out.stdout += &format!("{path}:{line}: {word} in {name}\n");
                    found.insert(word.as_str().to_owned());
                }
            }
        }
    }
    if !found.is_empty() {
        out.stderr += &reasons(&format!("Forbidden words of {} found:", ruleset.name), &found, |word| {
            &forbidden.scopes[word].reason
        });
        out.stderr += &format!("\n{}", ruleset.identifiers_advice);
    }
    out.failed = !out.stdout.is_empty();
    Ok(out)
}