ailint-extractor 1.1.0

Logos-based comment extractor: pulls line and block comments from Rust, TypeScript, JavaScript, Python, Go, Java, and C# source files as virtual documents for ailint.
Documentation
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! Logos-based lexers that identify comment spans while ignoring strings.
//!
//! Each language exposes one function returning [`RawComment`]s in source
//! order. Non-comment tokens are consumed to skip past string literals so
//! `//` or `#` inside a string does not turn into a false-positive comment.
//!
//! Nested block comments (`/* /* */ */`) are **not** handled — the outer
//! `*/` closes the first `/*`. Rust allows nesting but it is rare in
//! practice; we accept the limitation rather than growing the lexer.

use logos::{Lexer, Logos};

use crate::{CommentKind, RawComment};

// -------- Rust --------

#[derive(Logos, Debug, PartialEq)]
enum RustTok {
    // Line comment — Doc vs Line resolved after lex.
    #[regex(r"//[^\n]*")]
    LineComment,

    // Block comment; callback advances past `*/`.
    #[token("/*", block_comment)]
    BlockComment,

    // Cook, byte, and c strings all share the same escape rules for our
    // purposes (we only care about consuming them).
    #[regex(r#""([^"\\]|\\.)*""#)]
    #[regex(r#"b"([^"\\]|\\.)*""#)]
    String,

    // Char / byte-char literals: skip so `'/' '/'` never confuses us.
    #[regex(r"'([^'\\]|\\.)'")]
    #[regex(r"b'([^'\\]|\\.)'")]
    Char,

    // Raw and byte-raw strings: r"…", r#"…"#, r##"…"##, br"…", etc.
    #[token("r\"", raw_string)]
    #[token("r#", raw_hash_string)]
    #[token("br\"", raw_string)]
    #[token("br#", raw_hash_string)]
    RawString,
}

fn block_comment(lex: &mut Lexer<RustTok>) -> Option<()> {
    let rem = lex.remainder();
    let end = rem.find("*/")?;
    lex.bump(end + 2);
    Some(())
}

fn raw_string(lex: &mut Lexer<RustTok>) -> Option<()> {
    let rem = lex.remainder();
    let end = rem.find('"')?;
    lex.bump(end + 1);
    Some(())
}

fn raw_hash_string(lex: &mut Lexer<RustTok>) -> Option<()> {
    // Count leading `#`s (we already ate one via the `r#` / `br#` token).
    let rem = lex.remainder();
    let extra_hashes = rem.bytes().take_while(|b| *b == b'#').count();
    // Skip the extra hashes plus the opening `"`.
    let after_hashes = &rem[extra_hashes..];
    if !after_hashes.starts_with('"') {
        return None;
    }
    let total_hashes = 1 + extra_hashes;
    let terminator: String = std::iter::once('"')
        .chain(std::iter::repeat('#').take(total_hashes))
        .collect();
    let body = &after_hashes[1..];
    let end = body.find(&terminator)?;
    lex.bump(extra_hashes + 1 + end + terminator.len());
    Some(())
}

pub(crate) fn rust_comments(source: &str) -> Vec<RawComment> {
    let mut out = Vec::new();
    let mut lex = RustTok::lexer(source);
    while let Some(tok) = lex.next() {
        match tok {
            Ok(RustTok::LineComment) => {
                let span = lex.span();
                let raw = source[span.clone()].to_string();
                let kind = if raw.starts_with("////") {
                    // Four+ slashes is not a doc comment in Rust.
                    CommentKind::Line
                } else if raw.starts_with("///") || raw.starts_with("//!") {
                    CommentKind::Doc
                } else {
                    CommentKind::Line
                };
                out.push(RawComment {
                    raw,
                    kind,
                    byte_range: span,
                });
            }
            Ok(RustTok::BlockComment) => {
                let span = lex.span();
                let raw = source[span.clone()].to_string();
                let is_outer_doc = raw.starts_with("/**") && !raw.starts_with("/***");
                let is_inner_doc = raw.starts_with("/*!");
                let kind = if is_outer_doc || is_inner_doc {
                    CommentKind::Doc
                } else {
                    CommentKind::Block
                };
                out.push(RawComment {
                    raw,
                    kind,
                    byte_range: span,
                });
            }
            _ => {}
        }
    }
    out
}

// -------- JavaScript / TypeScript --------

#[derive(Logos, Debug, PartialEq)]
enum JsTok {
    #[regex(r"//[^\n]*")]
    LineComment,

    #[token("/*", block_comment_js)]
    BlockComment,

    #[regex(r#""([^"\\\n]|\\.)*""#)]
    #[regex(r"'([^'\\\n]|\\.)*'")]
    String,

    // Template literals. We do not descend into `${…}` expressions, so a `//`
    // inside a `${}` interpolation could be missed. Accepted tradeoff.
    #[token("`", template_string)]
    Template,
}

fn block_comment_js(lex: &mut Lexer<JsTok>) -> Option<()> {
    let rem = lex.remainder();
    let end = rem.find("*/")?;
    lex.bump(end + 2);
    Some(())
}

fn template_string(lex: &mut Lexer<JsTok>) -> Option<()> {
    let rem = lex.remainder();
    let mut i = 0;
    let bytes = rem.as_bytes();
    while i < bytes.len() {
        match bytes[i] {
            b'\\' if i + 1 < bytes.len() => i += 2,
            b'`' => {
                lex.bump(i + 1);
                return Some(());
            }
            _ => i += 1,
        }
    }
    None
}

pub(crate) fn js_comments(source: &str) -> Vec<RawComment> {
    let mut out = Vec::new();
    let mut lex = JsTok::lexer(source);
    while let Some(tok) = lex.next() {
        match tok {
            Ok(JsTok::LineComment) => {
                let span = lex.span();
                let raw = source[span.clone()].to_string();
                out.push(RawComment {
                    raw,
                    kind: CommentKind::Line,
                    byte_range: span,
                });
            }
            Ok(JsTok::BlockComment) => {
                let span = lex.span();
                let raw = source[span.clone()].to_string();
                let kind = if raw.starts_with("/**") && !raw.starts_with("/***") && raw != "/**/" {
                    CommentKind::Doc
                } else {
                    CommentKind::Block
                };
                out.push(RawComment {
                    raw,
                    kind,
                    byte_range: span,
                });
            }
            _ => {}
        }
    }
    out
}

// -------- Python --------

#[derive(Logos, Debug, PartialEq)]
enum PyTok {
    #[regex(r"#[^\n]*")]
    LineComment,

    // Triple-quoted strings come before regular strings so they win on length.
    #[token("\"\"\"", triple_double)]
    #[token("'''", triple_single)]
    TripleString,

    #[regex(r#""([^"\\\n]|\\.)*""#)]
    #[regex(r"'([^'\\\n]|\\.)*'")]
    String,
}

fn triple_double(lex: &mut Lexer<PyTok>) -> Option<()> {
    let rem = lex.remainder();
    let end = rem.find("\"\"\"")?;
    lex.bump(end + 3);
    Some(())
}

fn triple_single(lex: &mut Lexer<PyTok>) -> Option<()> {
    let rem = lex.remainder();
    let end = rem.find("'''")?;
    lex.bump(end + 3);
    Some(())
}

pub(crate) fn py_comments(source: &str) -> Vec<RawComment> {
    let mut out = Vec::new();
    let mut lex = PyTok::lexer(source);
    while let Some(tok) = lex.next() {
        match tok {
            Ok(PyTok::LineComment) => {
                let span = lex.span();
                let raw = source[span.clone()].to_string();
                out.push(RawComment {
                    raw,
                    kind: CommentKind::Line,
                    byte_range: span,
                });
            }
            Ok(PyTok::TripleString) => {
                let span = lex.span();
                let raw = source[span.clone()].to_string();
                out.push(RawComment {
                    raw,
                    kind: CommentKind::Docstring,
                    byte_range: span,
                });
            }
            _ => {}
        }
    }
    out
}

// -------- Go --------

#[derive(Logos, Debug, PartialEq)]
enum GoTok {
    #[regex(r"//[^\n]*")]
    LineComment,

    #[token("/*", block_comment_go)]
    BlockComment,

    #[regex(r#""([^"\\\n]|\\.)*""#)]
    String,

    // Raw string literals: `…` — no escapes, may contain newlines.
    #[token("`", raw_string_go)]
    RawString,

    // Rune literal: single-quoted character with optional escape.
    #[regex(r"'([^'\\]|\\.)*'")]
    Rune,
}

fn block_comment_go(lex: &mut Lexer<GoTok>) -> Option<()> {
    let rem = lex.remainder();
    let end = rem.find("*/")?;
    lex.bump(end + 2);
    Some(())
}

fn raw_string_go(lex: &mut Lexer<GoTok>) -> Option<()> {
    let rem = lex.remainder();
    let end = rem.find('`')?;
    lex.bump(end + 1);
    Some(())
}

pub(crate) fn go_comments(source: &str) -> Vec<RawComment> {
    let mut out = Vec::new();
    let mut lex = GoTok::lexer(source);
    while let Some(tok) = lex.next() {
        match tok {
            Ok(GoTok::LineComment) => {
                let span = lex.span();
                out.push(RawComment {
                    raw: source[span.clone()].to_string(),
                    kind: CommentKind::Line,
                    byte_range: span,
                });
            }
            Ok(GoTok::BlockComment) => {
                let span = lex.span();
                out.push(RawComment {
                    raw: source[span.clone()].to_string(),
                    kind: CommentKind::Block,
                    byte_range: span,
                });
            }
            _ => {}
        }
    }
    out
}

// -------- Java --------

#[derive(Logos, Debug, PartialEq)]
enum JavaTok {
    #[regex(r"//[^\n]*")]
    LineComment,

    #[token("/*", block_comment_java)]
    BlockComment,

    // Text blocks come before regular strings so they win on length.
    #[token("\"\"\"", text_block_java)]
    TextBlock,

    #[regex(r#""([^"\\\n]|\\.)*""#)]
    String,

    #[regex(r"'([^'\\]|\\.)'")]
    Char,
}

fn block_comment_java(lex: &mut Lexer<JavaTok>) -> Option<()> {
    let rem = lex.remainder();
    let end = rem.find("*/")?;
    lex.bump(end + 2);
    Some(())
}

fn text_block_java(lex: &mut Lexer<JavaTok>) -> Option<()> {
    let rem = lex.remainder();
    let end = rem.find("\"\"\"")?;
    lex.bump(end + 3);
    Some(())
}

pub(crate) fn java_comments(source: &str) -> Vec<RawComment> {
    let mut out = Vec::new();
    let mut lex = JavaTok::lexer(source);
    while let Some(tok) = lex.next() {
        match tok {
            Ok(JavaTok::LineComment) => {
                let span = lex.span();
                out.push(RawComment {
                    raw: source[span.clone()].to_string(),
                    kind: CommentKind::Line,
                    byte_range: span,
                });
            }
            Ok(JavaTok::BlockComment) => {
                let span = lex.span();
                let raw = source[span.clone()].to_string();
                let kind = if raw.starts_with("/**") && !raw.starts_with("/***") && raw != "/**/" {
                    CommentKind::Doc
                } else {
                    CommentKind::Block
                };
                out.push(RawComment {
                    raw,
                    kind,
                    byte_range: span,
                });
            }
            _ => {}
        }
    }
    out
}

// -------- C# --------

#[derive(Logos, Debug, PartialEq)]
enum CsTok {
    #[regex(r"//[^\n]*")]
    LineComment,

    #[token("/*", block_comment_cs)]
    BlockComment,

    // Raw string literals (C# 11+): `"""…"""`. Must come before regular strings.
    #[token("\"\"\"", raw_string_cs)]
    RawString,

    // Verbatim string: `@"…"` with `""` as escape for a literal quote.
    #[token("@\"", verbatim_string_cs)]
    Verbatim,

    // Interpolated verbatim: `$@"…"` / `@$"…"`. Treated like a verbatim string
    // — we don't descend into `{…}` interpolations.
    #[token("$@\"", verbatim_string_cs)]
    #[token("@$\"", verbatim_string_cs)]
    InterpVerbatim,

    // Regular and interpolated strings share the same escape rules for our
    // purposes (we don't parse `{expr}` in `$"…"`).
    #[regex(r#""([^"\\\n]|\\.)*""#)]
    #[regex(r#"\$"([^"\\\n]|\\.)*""#)]
    String,

    #[regex(r"'([^'\\]|\\.)'")]
    Char,
}

fn block_comment_cs(lex: &mut Lexer<CsTok>) -> Option<()> {
    let rem = lex.remainder();
    let end = rem.find("*/")?;
    lex.bump(end + 2);
    Some(())
}

fn raw_string_cs(lex: &mut Lexer<CsTok>) -> Option<()> {
    let rem = lex.remainder();
    let end = rem.find("\"\"\"")?;
    lex.bump(end + 3);
    Some(())
}

fn verbatim_string_cs(lex: &mut Lexer<CsTok>) -> Option<()> {
    // `""` inside a verbatim string is an escaped quote, not a terminator.
    let rem = lex.remainder();
    let bytes = rem.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'"' {
            if i + 1 < bytes.len() && bytes[i + 1] == b'"' {
                i += 2;
                continue;
            }
            lex.bump(i + 1);
            return Some(());
        }
        i += 1;
    }
    None
}

pub(crate) fn cs_comments(source: &str) -> Vec<RawComment> {
    let mut out = Vec::new();
    let mut lex = CsTok::lexer(source);
    while let Some(tok) = lex.next() {
        match tok {
            Ok(CsTok::LineComment) => {
                let span = lex.span();
                let raw = source[span.clone()].to_string();
                // `////` and more are not XML doc, per Roslyn.
                let kind = if raw.starts_with("////") {
                    CommentKind::Line
                } else if raw.starts_with("///") {
                    CommentKind::Doc
                } else {
                    CommentKind::Line
                };
                out.push(RawComment {
                    raw,
                    kind,
                    byte_range: span,
                });
            }
            Ok(CsTok::BlockComment) => {
                let span = lex.span();
                out.push(RawComment {
                    raw: source[span.clone()].to_string(),
                    kind: CommentKind::Block,
                    byte_range: span,
                });
            }
            _ => {}
        }
    }
    out
}