Skip to main content

blyte_cli/
comment_lint.rs

1//! Finds non-documentation, non-directive comments in source files and unified diffs.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::Path;
5
6#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
7pub struct Comment {
8    pub file: String,
9    pub line: usize,
10    pub text: String,
11}
12
13pub const DIRECTIVES: &[&str] = &[
14    "noqa",
15    "type:",
16    "pragma",
17    "pylint:",
18    "mypy:",
19    "pyright:",
20    "ruff:",
21    "flake8:",
22    "fmt:",
23    "isort:",
24    "yapf:",
25    "nosec",
26    "coding:",
27    "-*-",
28    "eslint",
29    "@ts-",
30    "prettier-",
31    "biome-",
32    "istanbul",
33    "c8 ",
34    "v8 ",
35    "webpack",
36    "@vite-ignore",
37    "@jsx",
38    "<reference",
39    "jshint",
40    "global ",
41    "globals ",
42    "rustfmt::",
43    "clippy::",
44    "SAFETY:",
45    "SPDX-",
46    "Copyright",
47];
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50enum Lang {
51    Rust,
52    Python,
53    JsTs,
54}
55
56fn lang_for_path(path: &str) -> Option<Lang> {
57    let ext = Path::new(path).extension().and_then(|s| s.to_str())?;
58    match ext {
59        "rs" => Some(Lang::Rust),
60        "py" => Some(Lang::Python),
61        "js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" => Some(Lang::JsTs),
62        _ => None,
63    }
64}
65
66/// True when `path` has a supported source-file extension.
67pub fn is_supported(path: &str) -> bool {
68    lang_for_path(path).is_some()
69}
70
71/// Lexes `source` and returns every comment that counts, in file order.
72pub fn comments_in(path: &str, source: &str) -> Vec<Comment> {
73    let Some(lang) = lang_for_path(path) else {
74        return Vec::new();
75    };
76    match lang {
77        Lang::Rust => lex_rust(path, source),
78        Lang::Python => lex_python(path, source),
79        Lang::JsTs => lex_js_ts(path, source),
80    }
81}
82
83fn next_char(source: &str, i: &mut usize, line: &mut usize) -> char {
84    let ch = source[*i..].chars().next().expect("valid byte index");
85    *i += ch.len_utf8();
86    if ch == '\n' {
87        *line += 1;
88    }
89    ch
90}
91
92fn raw_string_hashes(bytes: &[u8], i: usize) -> Option<usize> {
93    if bytes.get(i) != Some(&b'r') {
94        return None;
95    }
96    let mut j = i + 1;
97    while j < bytes.len() && bytes[j] == b'#' {
98        j += 1;
99    }
100    if j < bytes.len() && bytes[j] == b'"' {
101        Some(j - (i + 1))
102    } else {
103        None
104    }
105}
106
107fn lex_rust(path: &str, source: &str) -> Vec<Comment> {
108    let bytes = source.as_bytes();
109    let mut i = 0usize;
110    let mut line = 1usize;
111    let mut out = Vec::new();
112
113    while i < bytes.len() {
114        if let Some(hashes) = raw_string_hashes(bytes, i) {
115            i += 2 + hashes;
116            while i < bytes.len() {
117                if bytes[i] == b'"'
118                    && i + 1 + hashes <= bytes.len()
119                    && bytes[i + 1..i + 1 + hashes].iter().all(|&b| b == b'#')
120                {
121                    i += 1 + hashes;
122                    break;
123                }
124                next_char(source, &mut i, &mut line);
125            }
126            continue;
127        }
128
129        if bytes[i] == b'"' {
130            i += 1;
131            while i < bytes.len() {
132                let ch = next_char(source, &mut i, &mut line);
133                if ch == '\\' {
134                    if i < bytes.len() {
135                        next_char(source, &mut i, &mut line);
136                    }
137                } else if ch == '"' {
138                    break;
139                }
140            }
141            continue;
142        }
143
144        if bytes[i] == b'\'' {
145            let mut look = source[i + 1..].chars();
146            match (look.next(), look.next()) {
147                (Some('\\'), _) => {
148                    i += 1;
149                    while i < bytes.len() {
150                        let ch = next_char(source, &mut i, &mut line);
151                        if ch == '\\' {
152                            if i < bytes.len() {
153                                next_char(source, &mut i, &mut line);
154                            }
155                        } else if ch == '\'' {
156                            break;
157                        }
158                    }
159                }
160                (Some(c1), Some('\'')) => {
161                    i += 1 + c1.len_utf8() + 1;
162                    if c1 == '\n' {
163                        line += 1;
164                    }
165                }
166                _ => {
167                    i += 1;
168                }
169            }
170            continue;
171        }
172
173        if source[i..].starts_with("//") {
174            let start_byte = i;
175            let start_line = line;
176            i += 2;
177            while i < bytes.len() && bytes[i] != b'\n' {
178                let ch = source[i..].chars().next().expect("valid byte index");
179                i += ch.len_utf8();
180            }
181            let raw = &source[start_byte..i];
182            maybe_push(path, start_byte, start_line, raw, Lang::Rust, &mut out);
183            continue;
184        }
185
186        if source[i..].starts_with("/*") {
187            let start_byte = i;
188            let start_line = line;
189            i += 2;
190            let mut depth = 1usize;
191            while i < bytes.len() && depth > 0 {
192                if source[i..].starts_with("/*") {
193                    depth += 1;
194                    i += 2;
195                } else if source[i..].starts_with("*/") {
196                    depth -= 1;
197                    i += 2;
198                } else {
199                    next_char(source, &mut i, &mut line);
200                }
201            }
202            let raw = &source[start_byte..i];
203            maybe_push(path, start_byte, start_line, raw, Lang::Rust, &mut out);
204            continue;
205        }
206
207        next_char(source, &mut i, &mut line);
208    }
209
210    out
211}
212
213fn lex_js_ts(path: &str, source: &str) -> Vec<Comment> {
214    let bytes = source.as_bytes();
215    let mut i = 0usize;
216    let mut line = 1usize;
217    let mut out = Vec::new();
218
219    while i < bytes.len() {
220        if matches!(bytes[i], b'"' | b'\'' | b'`') {
221            let quote = next_char(source, &mut i, &mut line);
222            while i < bytes.len() {
223                let ch = next_char(source, &mut i, &mut line);
224                if ch == '\\' {
225                    if i < bytes.len() {
226                        next_char(source, &mut i, &mut line);
227                    }
228                } else if ch == quote {
229                    break;
230                }
231            }
232            continue;
233        }
234
235        if source[i..].starts_with("//") && !(i > 0 && bytes[i - 1] == b'\\') {
236            let start_byte = i;
237            let start_line = line;
238            i += 2;
239            while i < bytes.len() && bytes[i] != b'\n' {
240                let ch = source[i..].chars().next().expect("valid byte index");
241                i += ch.len_utf8();
242            }
243            let raw = &source[start_byte..i];
244            maybe_push(path, start_byte, start_line, raw, Lang::JsTs, &mut out);
245            continue;
246        }
247
248        if source[i..].starts_with("/*") {
249            let start_byte = i;
250            let start_line = line;
251            i += 2;
252            while i < bytes.len() {
253                if source[i..].starts_with("*/") {
254                    i += 2;
255                    break;
256                }
257                next_char(source, &mut i, &mut line);
258            }
259            let raw = &source[start_byte..i];
260            maybe_push(path, start_byte, start_line, raw, Lang::JsTs, &mut out);
261            continue;
262        }
263
264        next_char(source, &mut i, &mut line);
265    }
266
267    out
268}
269
270fn lex_python(path: &str, source: &str) -> Vec<Comment> {
271    let bytes = source.as_bytes();
272    let mut i = 0usize;
273    let mut line = 1usize;
274    let mut out = Vec::new();
275
276    while i < bytes.len() {
277        if source[i..].starts_with("'''") || source[i..].starts_with("\"\"\"") {
278            let delim = &source[i..i + 3];
279            i += 3;
280            while i < bytes.len() {
281                if source[i..].starts_with(delim) {
282                    i += 3;
283                    break;
284                }
285                let ch = next_char(source, &mut i, &mut line);
286                if ch == '\\' && i < bytes.len() {
287                    next_char(source, &mut i, &mut line);
288                }
289            }
290            continue;
291        }
292
293        if matches!(bytes[i], b'"' | b'\'') {
294            let quote = next_char(source, &mut i, &mut line);
295            while i < bytes.len() {
296                let ch = next_char(source, &mut i, &mut line);
297                if ch == '\\' {
298                    if i < bytes.len() {
299                        next_char(source, &mut i, &mut line);
300                    }
301                } else if ch == quote || ch == '\n' {
302                    break;
303                }
304            }
305            continue;
306        }
307
308        if bytes[i] == b'#' {
309            let start_byte = i;
310            let start_line = line;
311            i += 1;
312            while i < bytes.len() && bytes[i] != b'\n' {
313                let ch = source[i..].chars().next().expect("valid byte index");
314                i += ch.len_utf8();
315            }
316            let raw = &source[start_byte..i];
317            maybe_push(path, start_byte, start_line, raw, Lang::Python, &mut out);
318            continue;
319        }
320
321        next_char(source, &mut i, &mut line);
322    }
323
324    out
325}
326
327fn maybe_push(
328    path: &str,
329    start_byte: usize,
330    start_line: usize,
331    raw: &str,
332    lang: Lang,
333    out: &mut Vec<Comment>,
334) {
335    if start_byte == 0 && raw.starts_with("#!") {
336        return;
337    }
338    if is_doc_comment(raw, lang) || is_directive(raw) {
339        return;
340    }
341    let first_line = raw.lines().next().unwrap_or("").trim();
342    let text: String = first_line.chars().take(120).collect();
343    out.push(Comment {
344        file: path.to_string(),
345        line: start_line,
346        text,
347    });
348}
349
350fn is_doc_comment(raw: &str, lang: Lang) -> bool {
351    match lang {
352        Lang::Rust => {
353            (raw.starts_with("///") && !raw.starts_with("////"))
354                || raw.starts_with("//!")
355                || (raw.starts_with("/**") && !raw.starts_with("/***") && raw != "/**/")
356                || raw.starts_with("/*!")
357        }
358        Lang::JsTs => raw.starts_with("/**") && !raw.starts_with("/***") && raw != "/**/",
359        Lang::Python => false,
360    }
361}
362
363fn is_directive(raw: &str) -> bool {
364    let body = raw
365        .strip_prefix("//")
366        .or_else(|| raw.strip_prefix("/*"))
367        .or_else(|| raw.strip_prefix('#'))
368        .unwrap_or(raw)
369        .trim_start();
370    DIRECTIVES.iter().any(|&d| {
371        body.starts_with(d)
372            || (d == "Copyright" && (body.starts_with("copyright") || body.starts_with("(c)")))
373    })
374}
375
376/// Maps each new path in a unified diff to the 1-based line numbers of its added lines.
377pub fn added_lines(diff: &str) -> BTreeMap<String, BTreeSet<usize>> {
378    let mut out: BTreeMap<String, BTreeSet<usize>> = BTreeMap::new();
379    let mut current_file: Option<String> = None;
380    let mut current_line = 0usize;
381    let mut in_hunk = false;
382
383    for raw_line in diff.lines() {
384        if let Some(rest) = raw_line.strip_prefix("+++ ") {
385            in_hunk = false;
386            current_line = 0;
387            if rest == "/dev/null" {
388                current_file = None;
389            } else {
390                let path = rest.strip_prefix("b/").unwrap_or(rest).to_string();
391                out.entry(path.clone()).or_default();
392                current_file = Some(path);
393            }
394            continue;
395        }
396
397        if let Some(after_at) = raw_line.strip_prefix("@@ ") {
398            if let Some((coords, _)) = after_at.split_once("@@") {
399                if let Some(plus_part) = coords.split_whitespace().find_map(|t| t.strip_prefix('+'))
400                {
401                    let c_str = plus_part.split(',').next().unwrap_or(plus_part);
402                    if let Ok(c) = c_str.parse::<usize>() {
403                        current_line = c;
404                        in_hunk = true;
405                    }
406                }
407            }
408            continue;
409        }
410
411        let Some(ref path) = current_file else {
412            continue;
413        };
414        if !in_hunk {
415            continue;
416        }
417
418        if raw_line.starts_with(' ') {
419            current_line += 1;
420        } else if raw_line.starts_with('+') {
421            if let Some(set) = out.get_mut(path) {
422                set.insert(current_line);
423            }
424            current_line += 1;
425        }
426    }
427
428    out
429}
430
431/// Finds comments on lines added by `diff`, reading each supported file with `read`.
432pub fn added_comments(
433    diff: &str,
434    read: &dyn Fn(&str) -> Result<String, String>,
435) -> Result<Vec<Comment>, String> {
436    let mut out = Vec::new();
437    for (path, lines) in added_lines(diff) {
438        if !is_supported(&path) {
439            continue;
440        }
441        let source = read(&path).map_err(|e| format!("cannot read {path}: {e}"))?;
442        for comment in comments_in(&path, &source) {
443            if lines.contains(&comment.line) {
444                out.push(comment);
445            }
446        }
447    }
448    Ok(out)
449}
450
451/// Formats a review flag for added comments, or `None` when none were found.
452pub fn flag(found: &[Comment]) -> Option<String> {
453    if found.is_empty() {
454        return None;
455    }
456    let n = found.len();
457    let listed: Vec<String> = found
458        .iter()
459        .take(3)
460        .map(|c| format!("{}:{}", c.file, c.line))
461        .collect();
462    let more = if n > 3 {
463        format!(" and {} more", n - 3)
464    } else {
465        String::new()
466    };
467    Some(format!(
468        "comments added ({n}): {}{more}: remove them, and check what each one was covering for",
469        listed.join(", ")
470    ))
471}