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
//! A scanner of Python's statements, which finds each docstring where `ast` finds it, without parsing
//! expressions.

use std::borrow::Cow;

use crate::lex::word_end;
use crate::py_space;

/// A token, and for a string literal that `ast` makes a `str`, the range of its body and whether it is raw.
#[derive(Clone, Copy)]
struct Token<'a> {
    text: &'a str,
    line: usize,
    at: usize,
    end: usize,
    body: Option<(usize, usize)>,
    raw: bool,
}

/// A statement, or a clause of one that `ast` makes a node, such as an `except` handler or an `elif`.
#[derive(Default)]
struct Node<'a> {
    kind: &'a str,
    children: Vec<usize>,
    chain: Option<usize>,
    annotated: bool,
    literal: Option<Vec<Token<'a>>>,
}

const HEADERS: &[&str] =
    &["def", "class", "if", "elif", "else", "for", "while", "try", "except", "finally", "with", "match", "case"];
const KEYWORDS: &[&str] = &[
    "return", "del", "pass", "raise", "global", "nonlocal", "assert", "import", "from", "lambda", "yield", "await",
    "break", "continue", "not", "None", "True", "False",
];

/// How much the token `t` deepens the nesting of brackets.
fn nesting(t: &str) -> i64 {
    match t {
        "(" | "[" | "{" => 1,
        ")" | "]" | "}" => -1,
        _ => 0,
    }
}

/// Whether `word` is a prefix of a string literal, such as `rb` or `f`.
fn is_prefix(word: &str) -> bool {
    matches!(
        word.to_ascii_lowercase().as_bytes(),
        [b'r' | b'b' | b'u' | b'f' | b't'] | [b'r', b'b' | b'f' | b't'] | [b'b' | b'f' | b't', b'r']
    )
}

/// The value of the body of a string literal that is not raw.
fn unescape(body: &str) -> Cow<'_, str> {
    if !body.contains('\\') {
        return Cow::Borrowed(body);
    }
    let escape = regex!(r"(?s)\\(?:([0-7]{1,3})|x([0-9a-fA-F]{2})|u([0-9a-fA-F]{4})|U([0-9a-fA-F]{8})|(.))");
    escape.replace_all(body, |caps: &regex::Captures| {
        let Some(other) = caps.get(5) else {
            let (digits, radix) = caps.get(1).map_or_else(|| ((2..=4).find_map(|k| caps.get(k)), 16), |d| (Some(d), 8));
            let value = digits.and_then(|d| u32::from_str_radix(d.as_str(), radix).ok());
            return value.and_then(char::from_u32).unwrap_or('\u{fffd}').to_string();
        };
        match "\nabfnrtv\\'\"".find(other.as_str()) {
            Some(k) => ["", "\x07", "\x08", "\x0c", "\n", "\r", "\t", "\x0b", "\\", "'", "\""][k].into(),
            None => caps[0].into(),
        }
    })
}

/// The offset after the string literal whose quotes start at `i` of `b`, an f-string where `f`.
fn string(b: &[u8], i: usize, f: bool) -> usize {
    let n = b.len();
    let width = if b[i..].starts_with(&[b[i]; 3]) { 3 } else { 1 };
    let (mut braces, mut j) = (0, i + width);
    while j < n {
        let c = b[j];
        if c == b'\\' {
            j += 1;
        } else if braces == 0 && b[j..].starts_with(&b[i..i + width]) {
            return j + width;
        } else if c == b'\n' && width == 1 && braces == 0 {
            return if f { j } else { memchr::memchr(b'\n', &b[i..]).map_or(n, |k| i + k) };
        } else if f && c == b'{' {
            if b.get(j + 1) == Some(&b'{') && braces == 0 {
                j += 1;
            } else {
                braces += 1;
            }
        } else if c == b'}' && braces > 0 {
            braces -= 1;
        } else if braces > 0 && (c == b'\'' || c == b'"') {
            j = string(b, j, false) - 1;
        }
        j += 1;
    }
    n
}

/// Each logical line of `source` as its indentation and tokens, where every string literal is a token named `string`.
fn logical_lines(source: &str) -> Vec<(usize, Vec<Token<'_>>)> {
    let b = source.as_bytes();
    let n = b.len();
    let (mut lines, mut tokens) = (Vec::new(), Vec::new());
    let (mut indent, mut depth, mut start, mut line) = (0, 0i64, true, 0);
    let mut i = 0;
    while i < n {
        if start {
            let mut column = 0;
            while i < n && matches!(b[i], b' ' | b'\t' | b'\x0c') {
                column = match b[i] {
                    b'\t' => (column & !7) + 8,
                    b'\x0c' => 0,
                    _ => column + 1,
                };
                i += 1;
            }
            if i < n && b[i] != b'\n' && b[i] != b'#' {
                (indent, start) = (column, false);
            }
            if i >= n {
                break;
            }
        }
        let c = b[i];
        if c == b'\n' {
            line += 1;
            i += 1;
            if depth == 0 && !tokens.is_empty() {
                lines.push((indent, std::mem::take(&mut tokens)));
            }
            start = depth == 0 && tokens.is_empty();
        } else if c == b'\\' && b.get(i + 1) == Some(&b'\n') {
            (i, line) = (i + 2, line + 1);
        } else if c == b'#' {
            i = memchr::memchr(b'\n', &b[i..]).map_or(n, |k| i + k);
        } else if matches!(c, b' ' | b'\t' | b'\x0c') {
            i += 1;
        } else {
            let word = word_end(source, i);
            let mut end = if word > i { word } else { i + source[i..].chars().next().map_or(1, char::len_utf8) };
            let text = &source[i..end];
            let mut token = Token { text, line, at: i, end: line, body: None, raw: false };
            let quote = |k: usize| matches!(b.get(k), Some(b'\'' | b'"'));
            if quote(i) || quote(end) && is_prefix(text) {
                let prefix = if quote(i) { String::new() } else { text.to_ascii_lowercase() };
                let body = i + prefix.len();
                end = string(b, body, prefix.contains(['f', 't']));
                line += memchr::memchr_iter(b'\n', &b[body..end]).count();
                let width = if b[body..].starts_with(&[b[body]; 3]) { 3 } else { 1 };
                token.text = "string";
                if !prefix.contains(['b', 'f', 't']) {
                    token.body = Some((body + width, end.saturating_sub(width).max(body + width)));
                    token.raw = prefix.contains('r');
                }
            } else if c == b':' && b.get(i + 1) == Some(&b'=') {
                (token.text, end) = (":=", i + 2);
            }
            token.end = line;
            depth = (depth + nesting(token.text)).max(0);
            tokens.push(token);
            i = end;
        }
    }
    if !tokens.is_empty() {
        lines.push((indent, tokens));
    }
    lines
}

/// The index of the colon that ends a clause's header in `tokens`, or `None` where it is not a header.
fn header_colon(tokens: &[Token]) -> Option<usize> {
    let first = tokens[0].text;
    let second = tokens.get(1).map(|t| t.text);
    if !HEADERS.contains(&first) && !(first == "async" && second.is_some_and(|s| HEADERS.contains(&s))) {
        return None;
    }
    if matches!(first, "match" | "case") && second.is_none_or(|s| s.starts_with([':', '=', '.']) || s == "=") {
        return None;
    }
    let (mut depth, mut lambdas) = (0i64, 0i64);
    for (k, t) in tokens.iter().enumerate() {
        match t.text {
            t if nesting(t) != 0 => depth += nesting(t),
            "lambda" if depth == 0 => lambdas += 1,
            ":" if depth == 0 => {
                if lambdas == 0 {
                    return Some(k);
                }
                lambdas -= 1;
            }
            _ => {}
        }
    }
    None
}

/// The simple statements of `tokens`, separated by semicolons outside brackets.
fn simple<'a>(tokens: &[Token<'a>]) -> Vec<Node<'a>> {
    let mut nodes = Vec::new();
    let mut depth = 0i64;
    let mut from = 0;
    for k in 0..=tokens.len() {
        let t = tokens.get(k).map(|t| t.text);
        depth += t.map_or(0, nesting);
        if t.is_some_and(|t| t != ";" || depth != 0) {
            continue;
        }
        let part = &tokens[from..k];
        from = k + 1;
        if part.is_empty() {
            continue;
        }
        let opening = part.iter().take_while(|p| p.text == "(").count();
        let strings = part[opening..].iter().take_while(|p| p.text == "string").count();
        let closing = part[opening + strings..].iter().take_while(|p| p.text == ")").count();
        let literal = strings > 0
            && opening == closing
            && opening + strings + closing == part.len()
            && part[opening..opening + strings].iter().all(|p| p.body.is_some());
        let mut annotated = !KEYWORDS.contains(&part[0].text);
        let mut level = 0i64;
        for (i, p) in part.iter().enumerate() {
            if !annotated {
                break;
            }
            level += nesting(p.text);
            if level == 0 && (p.text == "=" || p.text == "lambda") {
                annotated = false;
            } else if level == 0 && p.text == ":" {
                break;
            } else if i == part.len() - 1 {
                annotated = false;
            }
        }
        let literal = literal.then(|| part[opening..opening + strings].to_vec());
        nodes.push(Node { kind: "simple", annotated, literal, ..Node::default() });
    }
    nodes
}

/// Adds `node` to the arena `nodes` as the last child of `parent`, and returns its index.
fn add<'a>(nodes: &mut Vec<Node<'a>>, parent: usize, node: Node<'a>) -> usize {
    nodes.push(node);
    let index = nodes.len() - 1;
    nodes[parent].children.push(index);
    index
}

/// The nodes of the module of `source` in an arena, the module first, as `ast.walk` visits their tree.
fn tree(source: &str) -> Vec<Node<'_>> {
    let mut nodes = vec![Node { kind: "module", ..Node::default() }];
    // Each open block, as its indentation, its node and the last statement in it.
    let mut stack: Vec<(i64, usize, Option<usize>)> = vec![(-1, 0, None)];
    let mut pending: Option<usize> = None;
    for (indent, tokens) in logical_lines(source) {
        let indent = indent as i64;
        if tokens[0].text == "@" {
            continue;
        }
        match pending.take() {
            Some(node) => stack.push((indent, node, None)),
            None => {
                while stack.len() > 1 && stack.last().is_some_and(|b| b.0 > indent) {
                    stack.pop();
                }
            }
        }
        let top = stack.len() - 1;
        let (_, block, last) = stack[top];
        let Some(colon) = header_colon(&tokens) else {
            for node in simple(&tokens) {
                stack[top].2 = Some(add(&mut nodes, block, node));
            }
            continue;
        };
        let kind = tokens[usize::from(tokens[0].text == "async")].text;
        let owner = last.unwrap_or(block);
        let target = match kind {
            "elif" => {
                let parent = nodes[owner].chain.unwrap_or(owner);
                let target = add(&mut nodes, parent, Node { kind, ..Node::default() });
                nodes[owner].chain = Some(target);
                target
            }
            "except" => add(&mut nodes, owner, Node { kind, ..Node::default() }),
            "else" | "finally" => last.map_or(block, |l| nodes[l].chain.unwrap_or(l)),
            _ => {
                let target = add(&mut nodes, block, Node { kind, ..Node::default() });
                nodes[target].chain = (kind == "if").then_some(target);
                stack[top].2 = Some(target);
                target
            }
        };
        if colon + 1 < tokens.len() {
            for node in simple(&tokens[colon + 1..]) {
                add(&mut nodes, target, node);
            }
        } else {
            pending = Some(target);
        }
    }
    nodes
}

/// The lines of `inspect.cleandoc` of `doc`.
fn cleandoc(doc: &str) -> Vec<String> {
    let mut lines: Vec<String> = doc
        .split('\n')
        .map(|line| {
            if !line.contains('\t') {
                return line.to_string();
            }
            let (mut out, mut column) = (String::new(), 0);
            for c in line.chars() {
                if c == '\t' {
                    let width = 8 - column % 8;
                    out.extend(std::iter::repeat_n(' ', width));
                    column += width;
                } else {
                    out.push(c);
                    column += 1;
                }
            }
            out
        })
        .collect();
    let margin = lines[1..]
        .iter()
        .filter_map(|l| {
            let content = l.trim_start_matches(' ');
            (!content.is_empty()).then(|| l.len() - content.len())
        })
        .min();
    lines[0] = lines[0].trim_start_matches(' ').to_string();
    if let Some(margin) = margin {
        for line in &mut lines[1..] {
            *line = line[margin.min(line.len())..].to_string();
        }
    }
    while lines.last().is_some_and(String::is_empty) {
        lines.pop();
    }
    let blank = lines.iter().take_while(|l| l.is_empty()).count();
    lines.drain(..blank);
    if lines.is_empty() {
        lines.push(String::new());
    }
    lines
}

/// A docstring of a Python source.
///
/// - The kind is `!` for a module's docstring and `"` for any other, including a field's.
/// - The start is the index of its first line of text, and the text is the lines of `inspect.cleandoc`.
pub struct Docstring {
    pub kind: char,
    pub start: usize,
    pub text: Vec<String>,
}

/// Each docstring of `source`, whose lines are `source_lines`, in the order of `ast.walk`.
pub fn docstrings(source: &str, source_lines: &[&str]) -> Vec<Docstring> {
    let nodes = tree(source);
    let mut found: Vec<(char, Option<usize>)> = Vec::new();
    let mut queue = vec![0];
    let mut k = 0;
    while k < queue.len() {
        let node = &nodes[queue[k]];
        k += 1;
        if matches!(node.kind, "module" | "def" | "class") {
            found.push((if node.kind == "module" { '!' } else { '"' }, node.children.first().copied()));
        }
        if node.kind == "class" {
            for (i, &child) in node.children.iter().enumerate() {
                if nodes[child].annotated && i + 1 < node.children.len() {
                    found.push(('"', Some(node.children[i + 1])));
                }
            }
        }
        queue.extend(&node.children);
    }
    let mut docs = Vec::new();
    for (kind, node) in found {
        let Some(literal) = node.and_then(|n| nodes[n].literal.as_ref()) else { continue };
        let (first, last) = (literal[0], literal[literal.len() - 1]);
        let line_start = source[..first.at].rfind('\n').map_or(0, |k| k + 1);
        // The column is in bytes, as `ast` reports it, and is taken from the line in characters, as Python does.
        let opening: String = source_lines[first.line].chars().skip(first.at - line_start).collect();
        let opening = opening.trim_start_matches(['r', 'R', 'u', 'U']);
        let rest: String = opening.chars().skip(3).collect();
        let below = rest.trim_matches(py_space).is_empty() && last.end > first.line;
        let value: String = literal
            .iter()
            .map(|t| {
                let (from, to) = t.body.unwrap_or_default();
                let body = source.get(from..to).unwrap_or_default();
                if t.raw { Cow::Borrowed(body) } else { unescape(body) }
            })
            .collect();
        docs.push(Docstring { kind, start: first.line + usize::from(below), text: cleandoc(&value) });
    }
    docs
}