prosecop 0.1.0

Checks identifiers and doc comments against a repository's house style
//! The language of a file, and a lexer for each that `code` reads, which finds identifiers and test attributes.
//!
//! It loops over bytes and tries a literal only where one can start.

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Lang {
    Rust,
    Python,
    Script,
    C,
    /// Markdown or plain text.
    Prose,
}

impl Lang {
    /// The language of a file by its suffix, as `pathlib` finds the suffix.
    pub fn of_suffix(name: &str) -> Option<Lang> {
        let stem = name.trim_start_matches('.');
        match stem.rfind('.').map(|i| &stem[i..]) {
            Some(".rs") => Some(Lang::Rust),
            Some(".py") => Some(Lang::Python),
            Some(".ts" | ".tsx" | ".js" | ".jsx" | ".mjs") => Some(Lang::Script),
            Some(".c" | ".h") => Some(Lang::C),
            Some(".md" | ".txt") => Some(Lang::Prose),
            _ => None,
        }
    }
}

pub enum Token {
    /// An identifier, by its byte range.
    Ident(usize, usize),
    /// A `#[test]` attribute or one of a test framework, such as `#[tokio::test]`.
    Test,
    /// A string literal, by the byte range of its quotes and any prefix.
    Str(usize, usize),
}

/// Whether `c` matches Python's `\w`, and whether it matches `\d`.
fn class(c: char) -> (bool, bool) {
    if c.is_ascii() {
        return (c.is_ascii_alphanumeric() || c == '_', c.is_ascii_digit());
    }
    let mut buffer = [0; 4];
    match regex!(r"^(?:(\p{Nd})|[\p{L}\p{N}_])").captures(c.encode_utf8(&mut buffer)) {
        Some(caps) => (true, caps.get(1).is_some()),
        None => (false, false),
    }
}

/// The character at `i` of `text`, which is a character boundary, and its length.
fn char_at(text: &str, i: usize) -> (char, usize) {
    let c = text[i..].chars().next().unwrap_or('\0');
    (c, c.len_utf8())
}

/// Whether each ASCII byte is a word character.
const WORD: [bool; 128] = {
    let mut table = [false; 128];
    let mut c = 0;
    while c < 128 {
        table[c] = (c as u8).is_ascii_alphanumeric() || c == b'_' as usize;
        c += 1;
    }
    table
};

/// Whether each byte is one that no token of any language starts with.
const PLAIN: [bool; 256] = {
    let mut table = [false; 256];
    let mut c = 0;
    while c < 128 {
        table[c] = !WORD[c] && !matches!(c as u8, b'/' | b'"' | b'\'' | b'#' | b'`');
        c += 1;
    }
    table
};

/// The end of the run of word characters of `text` from `i`.
pub fn word_end(text: &str, mut i: usize) -> usize {
    let b = text.as_bytes();
    while i < b.len() {
        if b[i] < 0x80 {
            if !WORD[usize::from(b[i])] {
                break;
            }
            i += 1;
        } else {
            let (c, len) = char_at(text, i);
            if !class(c).0 {
                break;
            }
            i += len;
        }
    }
    i
}

/// The offset after the delimiter that closes the one at `start`, counting nested pairs of `open` and `close`.
pub fn closing(b: &[u8], start: usize, open: &[u8], close: &[u8]) -> usize {
    let mut depth = 0i64;
    let mut i = start;
    while i < b.len() {
        if b[i..].starts_with(open) {
            depth += 1;
            i += open.len();
        } else if b[i..].starts_with(close) {
            depth -= 1;
            i += close.len();
            if depth == 0 {
                return i;
            }
        } else {
            i += 1;
        }
    }
    b.len()
}

/// The end of a quoted literal whose quote is at `q`, where a backslash escapes any character.
///
/// It is `None` where the literal is not closed, or where it reaches a newline that `newline` does not allow.
fn quoted(b: &[u8], q: usize, newline: bool) -> Option<usize> {
    let quote = b[q];
    let mut i = q + 1;
    while i < b.len() {
        match b[i] {
            b'\\' => i += 2,
            c if c == quote => return Some(i + 1),
            b'\n' if !newline => return None,
            _ => i += 1,
        }
    }
    None
}

/// The end of the Rust character literal whose quote is at `q`, matching `'(?:\\.[^'\n]*|[^'\\\n])'`.
fn rust_char(text: &str, q: usize) -> Option<usize> {
    let b = text.as_bytes();
    match *b.get(q + 1)? {
        b'\\' => {
            b.get(q + 2)?;
            let (c, len) = char_at(text, q + 2);
            if c == '\n' {
                return None;
            }
            let from = q + 2 + len;
            let end = from + memchr::memchr2(b'\'', b'\n', &b[from..])?;
            (b[end] == b'\'').then_some(end + 1)
        }
        b'\'' | b'\n' => None,
        _ => {
            let (_, len) = char_at(text, q + 1);
            (b.get(q + 1 + len) == Some(&b'\'')).then_some(q + 2 + len)
        }
    }
}

/// The end of the Rust raw string whose `r` is at `r`, matching `r(#*)"[\s\S]*?"\1`.
fn rust_raw(b: &[u8], r: usize) -> Option<usize> {
    let hashes = b[r + 1..].iter().take_while(|&&c| c == b'#').count();
    let open = r + 1 + hashes;
    if b.get(open) != Some(&b'"') {
        return None;
    }
    let mut close = vec![b'"'];
    close.resize(1 + hashes, b'#');
    Some(open + 1 + memchr::memmem::find(&b[open + 1..], &close)? + close.len())
}

/// The end of the attribute at `at`, where it matches `#\[\s*(?:\w+::)*test\b[^\]]*\]`.
fn test_attribute(text: &str, at: usize) -> Option<usize> {
    let b = text.as_bytes();
    if b.get(at + 1) != Some(&b'[') {
        return None;
    }
    let mut i = at + 2;
    while i < b.len() {
        let (c, len) = char_at(text, i);
        if !crate::py_space(c) {
            break;
        }
        i += len;
    }
    // A longer run of segments ends at the same `]`, so the first `test` decides the match.
    loop {
        let end = word_end(text, i);
        if &text[i..end] == "test" {
            return Some(end + memchr::memchr(b']', &b[end..])? + 1);
        }
        if end == i || !b[end..].starts_with(b"::") {
            return None;
        }
        i = end + 2;
    }
}

/// The end of the Python string literal whose first quote is at `q`, in one quote or in three.
fn python_string(b: &[u8], q: usize) -> Option<usize> {
    let quote = b[q];
    if b[q..].starts_with(&[quote; 3]) {
        let mut i = q + 3;
        while i < b.len() {
            if b[i..].starts_with(&[quote; 3]) {
                return Some(i + 3);
            }
            i += if b[i] == b'\\' { 2 } else { 1 };
        }
    }
    quoted(b, q, false)
}

/// Calls `f` with every identifier and test attribute of `text` outside comments and string literals, and with every
/// string literal, in order.
pub fn tokens(text: &str, lang: Lang, mut f: impl FnMut(Token)) {
    let b = text.as_bytes();
    let n = b.len();
    let mut i = 0;
    while i < n {
        let c = b[i];
        if PLAIN[usize::from(c)] {
            i += 1;
            continue;
        }
        match (lang, c) {
            (Lang::Python, b'#') => i = memchr::memchr(b'\n', &b[i..]).map_or(n, |k| i + k),
            (Lang::Python, b'\'' | b'"') => i = string(&mut f, i, python_string(b, i)),
            (_, b'/') if lang != Lang::Python && b.get(i + 1) == Some(&b'/') => {
                i = memchr::memchr(b'\n', &b[i..]).map_or(n, |k| i + k);
            }
            (Lang::Rust, b'/') if b.get(i + 1) == Some(&b'*') => i = closing(b, i, b"/*", b"*/"),
            (_, b'/') if lang != Lang::Python && b.get(i + 1) == Some(&b'*') => {
                match memchr::memmem::find(&b[i + 2..], b"*/") {
                    Some(k) => i += 2 + k + 2,
                    None => i += 1,
                }
            }
            (Lang::Rust, b'"') => i = string(&mut f, i, quoted(b, i, true)),
            (Lang::Rust, b'\'') => i = rust_char(text, i).unwrap_or(i + 1),
            (Lang::Rust, b'#') => match test_attribute(text, i) {
                Some(end) => {
                    f(Token::Test);
                    i = end;
                }
                None => i += 1,
            },
            (Lang::Script | Lang::C, b'"' | b'\'') | (Lang::Script, b'`') => {
                i = string(&mut f, i, quoted(b, i, c == b'`'));
            }
            (_, b'A'..=b'Z' | b'a'..=b'z' | b'_') => {
                let end = word_end(text, i);
                // A prefix of a literal is always followed by a quote or, in a raw string, by `#`.
                if matches!(b.get(end), Some(b'"' | b'\'' | b'#'))
                    && let Some(stop) = prefixed(text, lang, i, end)
                {
                    i = string(&mut f, i, Some(stop));
                    continue;
                }
                f(Token::Ident(i, end));
                i = end;
            }
            (_, b'0'..=b'9') => i = word_end(text, i),
            (_, 0x80..) => {
                let (ch, len) = char_at(text, i);
                i = if class(ch).1 { word_end(text, i) } else { i + len };
            }
            _ => i += 1,
        }
    }
}

/// The offset after the string literal from `start` to `end`, after calling `f` with it, or after its quote alone
/// where it is not closed.
fn string(f: &mut impl FnMut(Token), start: usize, end: Option<usize>) -> usize {
    match end {
        Some(end) => {
            f(Token::Str(start, end));
            end
        }
        None => start + 1,
    }
}

/// The end of a string literal that starts with the prefix of letters from `i` to `end`.
fn prefixed(text: &str, lang: Lang, i: usize, end: usize) -> Option<usize> {
    let b = text.as_bytes();
    let prefix = &b[i..end];
    match lang {
        Lang::Python => {
            let letters = prefix.iter().all(|c| b"rbufRBUF".contains(c));
            if prefix.len() > 2 || !letters || !matches!(b.get(end), Some(b'\'' | b'"')) {
                return None;
            }
            python_string(b, end)
        }
        Lang::Rust => {
            let r = if prefix[0] == b'b' { i + 1 } else { i };
            if b.get(r) == Some(&b'r')
                && let Some(stop) = rust_raw(b, r)
            {
                return Some(stop);
            }
            if prefix[0] != b'b' {
                return None;
            }
            match b.get(i + 1) {
                Some(b'"') => quoted(b, i + 1, true),
                Some(b'\'') => rust_char(text, i + 1),
                _ => None,
            }
        }
        Lang::Script | Lang::C | Lang::Prose => None,
    }
}