comex 1.0.0

Fast, dependency-free comment extraction and removal for source files, with content-based syntax detection (no file extensions required).
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! The scanner: one linear, allocation-light pass that classifies byte ranges.
//!
//! There is no regex and no backtracking. The hot path is
//! `while !interesting[byte] { i += 1 }` over a 256-entry lookup table built from the
//! active rule set, so bytes that cannot begin a comment, a string or a marker cost a
//! single table probe. Everything else is a bounded literal comparison.
//!
//! Strings are tracked even though callers usually do not want them, because a scanner
//! that ignores string literals will happily delete the `//` out of `"https://x"`.

use crate::syntax::{BlockRule, Dialect, LineRule, StringRule, Syntax};

/// What a [`Span`] covers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SpanKind {
    /// A comment running to the end of the line (`// x`, `# x`).
    Line,
    /// A delimited comment (`/* x */`, `<!-- x -->`), possibly multi-line.
    Block,
    /// A string literal. Only recorded when [`ScanConfig::record_strings`] is set.
    Str,
    /// A line-leading triple-quoted string treated as documentation (Python-style).
    DocString,
}

impl SpanKind {
    /// True for spans that count as comments for stripping and extraction.
    pub fn is_comment(self) -> bool {
        matches!(self, SpanKind::Line | SpanKind::Block | SpanKind::DocString)
    }
}

/// A classified byte range of the input.
///
/// `start..end` covers the whole construct including its markers; `inner_start..inner_end`
/// covers just the text between them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Span {
    /// What this range is.
    pub kind: SpanKind,
    /// Byte offset of the opening marker.
    pub start: usize,
    /// Byte offset just past the closing marker (or end of line / input).
    pub end: usize,
    /// Byte offset just past the opening marker.
    pub inner_start: usize,
    /// Byte offset of the closing marker.
    pub inner_end: usize,
}

impl Span {
    /// The full source text of the span, markers included.
    pub fn text<'a>(&self, src: &'a str) -> &'a str {
        &src[self.start..self.end]
    }
    /// The span's text with its comment markers removed.
    pub fn inner<'a>(&self, src: &'a str) -> &'a str {
        &src[self.inner_start..self.inner_end]
    }
}

/// Knobs for [`scan`].
#[derive(Clone, Copy, Debug)]
pub struct ScanConfig {
    /// Emit [`SpanKind::Str`] spans as well as comments.
    pub record_strings: bool,
    /// Report line-leading triple-quoted strings as [`SpanKind::DocString`].
    pub docstrings: bool,
    /// Never treat a leading `#!` line as a comment.
    pub keep_shebang: bool,
}

impl Default for ScanConfig {
    fn default() -> Self {
        ScanConfig {
            record_strings: false,
            docstrings: false,
            keep_shebang: true,
        }
    }
}

/// Classify `src` under `syn`, returning spans in source order and without overlap.
pub fn scan(src: &str, syn: &Syntax, cfg: ScanConfig) -> Vec<Span> {
    let mut out = Vec::new();
    if syn.is_empty() && !cfg.record_strings {
        return out;
    }
    let mut start = 0;
    if cfg.keep_shebang && syn.shebang_is_code && src.as_bytes().starts_with(b"#!") {
        start = line_end(src.as_bytes(), 0);
    }
    scan_range(src, syn, cfg, start, src.len(), &mut out);
    out
}

fn scan_range(
    src: &str,
    syn: &Syntax,
    cfg: ScanConfig,
    from: usize,
    to: usize,
    out: &mut Vec<Span>,
) {
    let b = src.as_bytes();
    let interesting = syn.interesting();
    let mut i = from;
    // True while nothing but whitespace has been seen on the current line.
    let mut at_ls = from == 0 || (from > 0 && b[from - 1] == b'\n');

    while i < to {
        let c = b[i];
        if c == b'\n' {
            i += 1;
            at_ls = true;
            continue;
        }
        if !interesting[c as usize] {
            if c != b' ' && c != b'\t' && c != b'\r' {
                at_ls = false;
            }
            i += 1;
            continue;
        }

        if let Some(next) = try_block(b, i, to, syn, at_ls, out) {
            at_ls = false;
            i = next;
            continue;
        }
        if let Some(next) = try_line(b, i, to, syn, at_ls, out) {
            i = next;
            at_ls = true; // a line comment always runs up to the newline
            continue;
        }
        if let Some(next) = try_char_prefix(b, i, to, syn) {
            at_ls = false;
            i = next;
            continue;
        }
        if let Some(next) = try_long_bracket_string(b, i, to, syn, cfg, out) {
            at_ls = false;
            i = next;
            continue;
        }
        if let Some(next) = try_string(b, i, to, syn, cfg, at_ls, out) {
            at_ls = false;
            i = next;
            continue;
        }
        if let Some(next) = try_embedded(src, i, to, syn, cfg, out) {
            at_ls = false;
            i = next;
            continue;
        }

        at_ls = false;
        i += 1;
    }
}

// --- individual rule attempts ----------------------------------------------

fn try_block(
    b: &[u8],
    i: usize,
    to: usize,
    syn: &Syntax,
    at_ls: bool,
    out: &mut Vec<Span>,
) -> Option<usize> {
    for r in syn.blocks {
        if r.anchored && !at_ls {
            continue;
        }
        if !matches_at(b, i, to, r.open, false) {
            continue;
        }
        let (end, closed) = block_end(b, i + r.open.len(), to, r);
        let inner_end = if closed { end - r.close.len() } else { end };
        out.push(Span {
            kind: SpanKind::Block,
            start: i,
            end,
            inner_start: i + r.open.len(),
            inner_end,
        });
        return Some(end);
    }
    // Lua's `--[[ ... ]]` and `--[==[ ... ]==]` are a line marker followed by a long
    // bracket; recognising them here keeps the line rule from truncating them.
    if syn.long_brackets {
        for r in syn.lines {
            if !matches_at(b, i, to, r.marker, false) {
                continue;
            }
            let after = i + r.marker.len();
            if let Some((body, level)) = long_bracket_open(b, after, to) {
                let (end, closed) = long_bracket_end(b, body, to, level);
                let inner_end = if closed { end - (level + 2) } else { end };
                out.push(Span {
                    kind: SpanKind::Block,
                    start: i,
                    end,
                    inner_start: body,
                    inner_end,
                });
                return Some(end);
            }
        }
    }
    None
}

fn try_line(
    b: &[u8],
    i: usize,
    to: usize,
    syn: &Syntax,
    at_ls: bool,
    out: &mut Vec<Span>,
) -> Option<usize> {
    for r in syn.lines {
        if !line_rule_applies(b, i, to, r, at_ls) {
            continue;
        }
        let end = line_end(b, i).min(to);
        // Keep a trailing CR out of the comment so CRLF files round-trip cleanly.
        let end = if end > i && b[end - 1] == b'\r' {
            end - 1
        } else {
            end
        };
        out.push(Span {
            kind: SpanKind::Line,
            start: i,
            end,
            inner_start: i + r.marker.len(),
            inner_end: end,
        });
        return Some(end);
    }
    None
}

fn line_rule_applies(b: &[u8], i: usize, to: usize, r: &LineRule, at_ls: bool) -> bool {
    if r.anchored && !at_ls {
        return false;
    }
    if r.boundary_before && i > 0 && !matches!(b[i - 1], b' ' | b'\t' | b'\r' | b'\n') {
        return false;
    }
    if !matches_at(b, i, to, r.marker, r.ci) {
        return false;
    }
    if i > 0 && r.not_after.contains(&b[i - 1]) {
        return false;
    }
    if let Some(allowed) = r.require_after {
        let j = i + r.marker.len();
        if j < to && b[j] != b'\n' && !allowed.contains(&b[j]) {
            return false;
        }
    }
    true
}

fn try_char_prefix(b: &[u8], i: usize, to: usize, syn: &Syntax) -> Option<usize> {
    let p = syn.char_prefix?;
    if !matches_at(b, i, to, p, false) {
        return None;
    }
    // `#\a`, `#\;`, `#\space` - consume the prefix, one character, then any name bytes.
    let mut j = i + p.len();
    if j < to {
        j += char_len(b[j]);
    }
    while j < to && (b[j].is_ascii_alphanumeric() || b[j] == b'-') {
        j += 1;
    }
    Some(j.min(to))
}

fn try_string(
    b: &[u8],
    i: usize,
    to: usize,
    syn: &Syntax,
    cfg: ScanConfig,
    at_ls: bool,
    out: &mut Vec<Span>,
) -> Option<usize> {
    for r in syn.strings {
        if !matches_at(b, i, to, r.open, false) {
            continue;
        }
        let raw = if r.raw_prefix {
            raw_prefix_hashes(b, i)
        } else {
            None
        };
        let end = match raw {
            Some(hashes) => raw_string_end(b, i + r.open.len(), to, r.close, hashes),
            None if r.char_like => match char_literal_end(b, i, to, r) {
                Some(end) => end,
                // Not a character literal: a Rust lifetime, a Matlab transpose or an
                // apostrophe. Leave it as ordinary code.
                None => continue,
            },
            None => string_end(b, i + r.open.len(), to, r),
        };
        let kind = if cfg.docstrings && r.doc_capable && at_ls {
            SpanKind::DocString
        } else {
            SpanKind::Str
        };
        if kind == SpanKind::DocString || cfg.record_strings {
            let inner_end = end.saturating_sub(r.close.len()).max(i + r.open.len());
            out.push(Span {
                kind,
                start: i,
                end,
                inner_start: i + r.open.len(),
                inner_end,
            });
        }
        return Some(end);
    }
    None
}

fn try_long_bracket_string(
    b: &[u8],
    i: usize,
    to: usize,
    syn: &Syntax,
    cfg: ScanConfig,
    out: &mut Vec<Span>,
) -> Option<usize> {
    if !syn.long_brackets || b[i] != b'[' {
        return None;
    }
    let (body, level) = long_bracket_open(b, i, to)?;
    let (end, closed) = long_bracket_end(b, body, to, level);
    if cfg.record_strings {
        let inner_end = if closed { end - (level + 2) } else { end };
        out.push(Span {
            kind: SpanKind::Str,
            start: i,
            end,
            inner_start: body,
            inner_end,
        });
    }
    Some(end)
}

fn try_embedded(
    src: &str,
    i: usize,
    to: usize,
    syn: &Syntax,
    cfg: ScanConfig,
    out: &mut Vec<Span>,
) -> Option<usize> {
    if !syn.html_embedded {
        return None;
    }
    let b = src.as_bytes();
    let (open, close) = if matches_at(b, i, to, "<script", true) {
        ("<script", "</script")
    } else if matches_at(b, i, to, "<style", true) {
        ("<style", "</style")
    } else {
        return None;
    };
    // Only a real tag: `<scriptish` does not count.
    let after = i + open.len();
    if after < to && !matches!(b[after], b'>' | b' ' | b'\t' | b'\n' | b'\r') {
        return None;
    }
    let body = find(b, after, to, ">")? + 1;
    // No closing tag means this is prose talking *about* `<script>`, not a real element.
    // Scanning the rest of the document as JavaScript would be a spectacular way to
    // mangle a README.
    let body_end = find(b, body, to, close)?;
    if body_end > body {
        let inner = Syntax::of(Dialect::CFamily);
        scan_range(src, &inner, cfg, body, body_end, out);
    }
    Some(body_end)
}

// --- primitives ------------------------------------------------------------

fn matches_at(b: &[u8], i: usize, to: usize, pat: &str, ci: bool) -> bool {
    let p = pat.as_bytes();
    if i + p.len() > to {
        return false;
    }
    if ci {
        b[i..i + p.len()].eq_ignore_ascii_case(p)
    } else {
        &b[i..i + p.len()] == p
    }
}

fn find(b: &[u8], from: usize, to: usize, pat: &str) -> Option<usize> {
    let p = pat.as_bytes();
    if p.is_empty() || to < p.len() {
        return None;
    }
    let first = p[0];
    let ci = p.iter().any(|c| c.is_ascii_alphabetic());
    let mut i = from;
    while i + p.len() <= to {
        if (b[i] == first || (ci && b[i].eq_ignore_ascii_case(&first)))
            && matches_at(b, i, to, pat, ci)
        {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Index just past the end of the line containing `i`, excluding the newline.
fn line_end(b: &[u8], i: usize) -> usize {
    let mut j = i;
    while j < b.len() && b[j] != b'\n' {
        j += 1;
    }
    j
}

fn char_len(first: u8) -> usize {
    match first {
        0x00..=0x7f => 1,
        0xc0..=0xdf => 2,
        0xe0..=0xef => 3,
        _ => 4,
    }
}

/// Scan a block comment body. Returns `(end_index, closed)`.
fn block_end(b: &[u8], from: usize, to: usize, r: &BlockRule) -> (usize, bool) {
    let mut depth = 1usize;
    let mut j = from;
    let mut at_ls = false;
    while j < to {
        if b[j] == b'\n' {
            j += 1;
            at_ls = true;
            continue;
        }
        if (!r.close_anchored || at_ls) && matches_at(b, j, to, r.close, false) {
            depth -= 1;
            j += r.close.len();
            if depth == 0 {
                return (j, true);
            }
            continue;
        }
        if r.nestable && (!r.anchored || at_ls) && matches_at(b, j, to, r.open, false) {
            depth += 1;
            j += r.open.len();
            continue;
        }
        if b[j] != b' ' && b[j] != b'\t' && b[j] != b'\r' {
            at_ls = false;
        }
        j += 1;
    }
    (to, false)
}

/// A Lua long bracket `[==[`. Returns `(body_index, level)` where level is the `=` count.
fn long_bracket_open(b: &[u8], i: usize, to: usize) -> Option<(usize, usize)> {
    if i >= to || b[i] != b'[' {
        return None;
    }
    let mut j = i + 1;
    while j < to && b[j] == b'=' {
        j += 1;
    }
    if j < to && b[j] == b'[' {
        Some((j + 1, j - i - 1))
    } else {
        None
    }
}

fn long_bracket_end(b: &[u8], from: usize, to: usize, level: usize) -> (usize, bool) {
    let mut j = from;
    while j < to {
        if b[j] == b']' {
            let mut k = j + 1;
            while k < to && b[k] == b'=' {
                k += 1;
            }
            if k - j - 1 == level && k < to && b[k] == b']' {
                return (k + 1, true);
            }
        }
        j += 1;
    }
    (to, false)
}

fn string_end(b: &[u8], from: usize, to: usize, r: &StringRule) -> usize {
    let close = r.close.as_bytes();
    let mut j = from;
    while j < to {
        let c = b[j];
        if let Some(esc) = r.escape {
            if c == esc {
                j += 2;
                continue;
            }
        }
        if c == close[0] && matches_at(b, j, to, r.close, false) {
            let after = j + close.len();
            if r.doubling && matches_at(b, after, to, r.close, false) {
                j = after + close.len();
                continue;
            }
            return after;
        }
        if c == b'\n' && !r.multiline {
            // Unterminated: stop at the newline so one stray quote cannot swallow the
            // rest of the file (and with it every comment in between).
            return j;
        }
        j += 1;
    }
    to
}

fn raw_string_end(b: &[u8], from: usize, to: usize, close: &str, hashes: usize) -> usize {
    let mut j = from;
    while j < to {
        if matches_at(b, j, to, close, false) {
            let mut k = j + close.len();
            let mut seen = 0;
            while k < to && b[k] == b'#' && seen < hashes {
                k += 1;
                seen += 1;
            }
            if seen == hashes {
                return k;
            }
        }
        j += 1;
    }
    to
}

/// If the quote at `i` is preceded by a raw-string prefix (`r"`, `br"`, `r##"`),
/// return the number of `#` characters that the closing delimiter must repeat.
fn raw_prefix_hashes(b: &[u8], i: usize) -> Option<usize> {
    let mut p = i;
    while p > 0 && b[p - 1] == b'#' {
        p -= 1;
    }
    let hashes = i - p;
    let mut q = p;
    while q > 0 && b[q - 1].is_ascii_alphabetic() && p - q < 3 {
        q -= 1;
    }
    if q == p {
        return None;
    }
    let prefix = &b[q..p];
    if !prefix.iter().any(|c| c.eq_ignore_ascii_case(&b'r')) {
        return None;
    }
    if q > 0 && (b[q - 1].is_ascii_alphanumeric() || b[q - 1] == b'_') {
        return None;
    }
    Some(hashes)
}

/// Accept `'a'`, `'\n'`, `'\u{1f600}'`, `'é'` but reject Rust lifetimes (`'a`),
/// Matlab transposes (`A'`) and prose apostrophes.
fn char_literal_end(b: &[u8], i: usize, to: usize, r: &StringRule) -> Option<usize> {
    let close = r.close.as_bytes()[0];
    let mut j = i + r.open.len();
    if j >= to {
        return None;
    }
    if Some(b[j]) == r.escape {
        j += 1;
        let limit = (j + 12).min(to);
        while j < limit {
            if b[j] == b'\n' {
                return None;
            }
            if b[j] == close {
                return Some(j + 1);
            }
            j += 1;
        }
        return None;
    }
    if b[j] == b'\n' || b[j] == close {
        return None;
    }
    let end = j + char_len(b[j]);
    if end < to && b[end] == close {
        Some(end + 1)
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::syntax::Dialect;

    fn comments(src: &str, d: Dialect) -> Vec<&str> {
        scan(src, &d.syntax(), ScanConfig::default())
            .iter()
            .filter(|s| s.kind.is_comment())
            .map(|s| s.text(src))
            .collect()
    }

    #[test]
    fn urls_inside_strings_are_not_comments() {
        assert!(comments("let u = \"https://example.com/#x\";", Dialect::CFamily).is_empty());
        assert!(comments("u = 'https://example.com/#x'", Dialect::Hash).is_empty());
    }

    #[test]
    fn nested_block_comments() {
        let src = "a /* x /* y */ z */ b";
        assert_eq!(comments(src, Dialect::CFamily), ["/* x /* y */"]);
        assert_eq!(comments(src, Dialect::Sql), ["/* x /* y */ z */"]);
    }

    #[test]
    fn rust_lifetimes_do_not_open_a_string() {
        let src = "fn f<'a>(x: &'a str) { // note\n}";
        assert_eq!(comments(src, Dialect::CFamily), ["// note"]);
    }

    #[test]
    fn rust_raw_strings_swallow_quotes_and_slashes() {
        let src = "let s = r#\"a \" // b\"#; // real\n";
        assert_eq!(comments(src, Dialect::CFamily), ["// real"]);
    }

    #[test]
    fn unterminated_quote_only_damages_its_own_line() {
        let src = "echo don't\n# real comment\n";
        assert_eq!(comments(src, Dialect::Hash), ["# real comment"]);
    }

    #[test]
    fn lua_long_bracket_comment() {
        let src = "--[==[ hi\nstill ]==]\nx = 1 -- tail\n";
        assert_eq!(
            comments(src, Dialect::Lua),
            ["--[==[ hi\nstill ]==]", "-- tail"]
        );
    }

    #[test]
    fn html_script_bodies_use_c_rules() {
        let src = "<!-- x -->\n<script>\n// js\nvar a = \"<!-- not -->\";\n</script>\n";
        assert_eq!(comments(src, Dialect::Markup), ["<!-- x -->", "// js"]);
    }

    #[test]
    fn shebang_is_kept_as_code() {
        assert!(comments("#!/bin/sh\n", Dialect::Hash).is_empty());
        assert_eq!(comments("#!/bin/sh\n# c\n", Dialect::Hash), ["# c"]);
    }

    #[test]
    fn tex_escaped_percent_is_not_a_comment() {
        assert_eq!(comments("50\\% off % note\n", Dialect::Percent), ["% note"]);
    }

    #[test]
    fn word_markers_need_a_boundary() {
        assert!(comments("REMOVE x\n", Dialect::Batch).is_empty());
        assert_eq!(comments("rem gone\n", Dialect::Batch), ["rem gone"]);
    }

    #[test]
    fn spans_are_ordered_and_disjoint() {
        let src = "/* a */ x // b\n\"s\" /* c */\n";
        let spans = scan(
            src,
            &Dialect::CFamily.syntax(),
            ScanConfig {
                record_strings: true,
                ..Default::default()
            },
        );
        let mut prev = 0;
        for s in &spans {
            assert!(s.start >= prev, "{:?}", spans);
            assert!(s.end >= s.start);
            prev = s.end;
        }
    }

    #[test]
    fn unterminated_block_comment_reaches_end_of_input() {
        let src = "x /* never closed\nmore\n";
        assert_eq!(comments(src, Dialect::CFamily), ["/* never closed\nmore\n"]);
    }
}