prosecop 0.1.0

Checks identifiers and doc comments against a repository's house style
//! `prosecop` checks the identifiers, strings and comments of a codebase against a ruleset.

/// The value of `$init`, computed once and shared by every thread.
macro_rules! lazy {
    ($ty:ty, $init:expr) => {{
        static VALUE: std::sync::LazyLock<$ty> = std::sync::LazyLock::new(|| $init);
        &*VALUE
    }};
}

/// The regular expression of the literal `$pattern`.
macro_rules! regex {
    ($pattern:literal) => {
        lazy!(regex::Regex, regex::Regex::new($pattern).unwrap())
    };
}

mod code;
mod docs;
mod lex;
mod python;
mod rules;
mod strings;
#[cfg(test)]
mod tests;
mod walk;

use std::io::Write;

use rules::Kind;
use std::process::ExitCode;

/// What a command prints, and whether it fails.
#[derive(Default)]
pub struct Output {
    pub stdout: String,
    pub stderr: String,
    pub failed: bool,
}

/// Whether `c` is whitespace to Python's `str.isspace`, which adds the separators U+001C to U+001F to Unicode's.
pub fn py_space(c: char) -> bool {
    if c.is_ascii() { matches!(c, ' ' | '\t'..='\r' | '\x1c'..='\x1f') } else { c.is_whitespace() }
}

/// The line numbers of ascending offsets into a text.
pub struct Lines<'a> {
    text: &'a [u8],
    offset: usize,
    line: usize,
}

impl<'a> Lines<'a> {
    pub fn new(text: &'a str) -> Lines<'a> {
        Lines { text: text.as_bytes(), offset: 0, line: 1 }
    }

    /// The line of `offset`, which is at least the offset of the previous call.
    pub fn at(&mut self, offset: usize) -> usize {
        self.line += memchr::memchr_iter(b'\n', &self.text[self.offset..offset]).count();
        self.offset = offset;
        self.line
    }
}

/// The usage of the command line.
pub const USAGE: &str = "usage: prosecop RULESET [--ext .rs,.py,...] [--exclude GLOB,...] [--forbid WORD,...] \
[--allow WORD|COMPOUND,...] [PATH ...]
RULESET is a built-in, such as claude@5, a directory of rules files, or one file of either, such as claude@5/docs.txt or claude@5/docs";

/// Checks the files that `args` pick against the ruleset that the first of `args` names.
///
/// Each kind of text that the ruleset has rules for is checked, or only the kind of the rules file that it names.
pub fn run(root: &walk::Root, args: &[String]) -> Result<Output, String> {
    let first = args.first().filter(|a| !a.starts_with("--")).ok_or(USAGE)?;
    let (ruleset, picked) = rules::resolve(first)?;
    let options = walk::Options::parse(&args[1..])?;
    let words = !options.forbid.is_empty() || !options.allow.is_empty();
    let kinds: Vec<Kind> = match picked {
        Some(kind) if ruleset.rules(kind).is_none() => return Err(format!("{} has no {}", ruleset.name, kind.file())),
        Some(kind) => vec![kind],
        None => {
            Kind::ALL.into_iter().filter(|&k| ruleset.rules(k).is_some() || k == Kind::Identifiers && words).collect()
        }
    };
    if words && !kinds.contains(&Kind::Identifiers) {
        return Err("--forbid and --allow apply only to identifiers".into());
    }
    let reads = |kind| match kind {
        Kind::Identifiers => code::reads as fn(lex::Lang) -> bool,
        Kind::Docs => docs::reads,
        Kind::Strings => strings::reads,
    };
    for suffix in options.suffixes.iter().flatten() {
        if !kinds.iter().any(|&kind| walk::reads_suffix(suffix, reads(kind))) {
            return Err(format!("--ext {suffix}: {first} cannot read {suffix} files"));
        }
    }
    let mut out = Output::default();
    for kind in kinds {
        let Some(options) = options.reading(reads(kind)) else { continue };
        let found = match kind {
            Kind::Identifiers => code::run(&ruleset, root, &options)?,
            Kind::Docs => docs::run(&ruleset, root, &options)?,
            Kind::Strings => strings::run(&ruleset, root, &options)?,
        };
        out.stdout += &found.stdout;
        out.stderr += &found.stderr;
        out.failed |= found.failed;
    }
    Ok(out)
}

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let result = run(&walk::Root::default(), &args);
    let output = result.unwrap_or_else(|e| Output { stderr: e + "\n", failed: true, ..Output::default() });
    // A reader that stops early, such as `head`, has read all that it wanted.
    let _ = std::io::stdout().lock().write_all(output.stdout.as_bytes());
    let _ = std::io::stderr().lock().write_all(output.stderr.as_bytes());
    if output.failed { ExitCode::FAILURE } else { ExitCode::SUCCESS }
}