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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
//! Content-based syntax detection.
//!
//! No file extensions, no shelling out to a language database. One pass collects cheap
//! structural evidence — line-leading markers, balanced block delimiters, line endings,
//! shebangs, preprocessor lines, a handful of keyword shapes — and each dialect scores
//! itself against that evidence. The winner must clear [`THRESHOLD`]; otherwise the
//! result is [`Dialect::Unknown`] and comex leaves the input alone.
//!
//! The bias is deliberate: a missed comment is a cosmetic failure, a comment marker
//! hallucinated inside real code is a corrupted file. Weights follow from that. A
//! line-*leading* marker is strong evidence; the same marker mid-line is weak, because
//! `a // b` is floor division in Python and `x--` is a decrement in C.

use crate::syntax::{Dialect, Syntax};

/// Minimum winning score. Below this the input is treated as having no comment syntax.
///
/// Because a dialect's contextual bonus is capped at its own marker score, clearing this
/// takes either several comment markers or one marker plus corroborating context. A file
/// whose only evidence is a single ambiguous marker is left alone.
pub const THRESHOLD: i32 = 16;

/// How much input detection reads. Evidence saturates long before this.
const SAMPLE_LIMIT: usize = 256 * 1024;

/// The outcome of [`detect`].
#[derive(Clone, Debug)]
pub struct Detection {
    /// Best-scoring dialect, or [`Dialect::Unknown`].
    pub dialect: Dialect,
    /// Heuristic 0.0–1.0 blend of evidence strength and margin over the runner-up.
    pub confidence: f32,
    /// Every dialect's score, highest first.
    pub scores: Vec<(Dialect, i32)>,
}

impl Detection {
    /// Rules for the detected dialect.
    pub fn syntax(&self) -> Syntax {
        self.dialect.syntax()
    }
}

/// Identify the comment syntax of `src` from its content alone.
pub fn detect(src: &str) -> Detection {
    let ev = Evidence::collect(src);
    let mut scores: Vec<(Dialect, i32)> = Dialect::ALL
        .iter()
        .filter(|d| **d != Dialect::Unknown)
        .map(|&d| (d, score(d, &ev)))
        .collect();
    scores.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.name().cmp(b.0.name())));

    // A document type declaration settles it. An HTML page that is mostly inline
    // `<script>` can out-score Markup on `//` alone, but Markup is still the right
    // answer: it strips `<!-- -->` and hands script and style bodies to the C rules.
    // Fenced code blocks settle it the same way. A README's examples are
    // documentation, not code to strip - only its `<!-- -->` comments should go.
    if ev.kw_markup >= 2
        || (ev.kw_markup >= 1 && ev.ls_lt >= 2)
        || ev.md_fence >= 2
        || (ev.md_fence >= 1 && ev.kw_md >= 3)
    {
        return Detection {
            dialect: Dialect::Markup,
            confidence: 1.0,
            scores,
        };
    }

    let (best_d, best) = scores[0];
    let second = scores.get(1).map(|s| s.1).unwrap_or(0).max(0);
    if best < THRESHOLD {
        return Detection {
            dialect: Dialect::Unknown,
            confidence: 0.0,
            scores,
        };
    }
    let strength = (best as f32 / 60.0).min(1.0);
    let margin = 1.0 - (second as f32 / best as f32);
    Detection {
        dialect: best_d,
        confidence: (strength * margin).clamp(0.0, 1.0),
        scores,
    }
}

// --- evidence --------------------------------------------------------------

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum Shebang {
    #[default]
    None,
    /// `sh`, `bash`, `python`, `perl`, `ruby`, `awk`, ...
    HashLang,
    /// `node`, `deno`, `bun`
    CLang,
}

/// Structural counts gathered in a single pass. All fields are saturating-ish counts;
/// scoring caps them anyway, so a 10 MB file cannot be decided by sheer repetition.
#[derive(Debug, Default)]
struct Evidence {
    lines: u32,
    shebang: Shebang,

    // Markers at the start of a line (after indentation) - strong evidence.
    ls_slash2: u32,
    ls_star: u32,
    ls_hash: u32,
    ls_dash2: u32,
    ls_semi: u32,
    ls_percent: u32,
    ls_squote: u32,
    ls_bang: u32,
    ls_ltbang: u32,
    ls_parenstar: u32,
    ls_bracedash: u32,
    ls_hashpipe: u32,
    ls_rem: u32,
    ls_colon2: u32,
    ls_lt: u32,
    ls_paren: u32,

    // Markers elsewhere on the line - weak evidence.
    slashstar: u32,
    starslash: u32,
    trailing_slash2: u32,
    trailing_dash2: u32,
    trailing_hash: u32,
    trailing_semi: u32,
    trailing_squote: u32,
    trailing_bang: u32,
    parenstar: u32,
    starparen: u32,
    bracedash: u32,
    dashbrace: u32,
    hashpipe: u32,
    pipehash: u32,
    ltbang: u32,

    // Shape of the code.
    end_semi: u32,
    end_brace: u32,
    end_colon: u32,
    kv_lines: u32,
    preproc: u32,

    // Dialect-specific hints.
    kw_c: u32,
    kw_hash: u32,
    kw_sql: u32,
    kw_lua: u32,
    kw_hs: u32,
    kw_lisp: u32,
    kw_markup: u32,
    kw_md: u32,
    kw_ml: u32,
    kw_tex: u32,
    kw_erlang: u32,
    kw_matlab: u32,
    kw_vb: u32,
    kw_batch: u32,
    kw_fortran: u32,
    md_fence: u32,
    lua_long: u32,
    ruby_block: u32,
    ps_block: u32,
    ini_section: u32,
}

impl Evidence {
    fn collect(src: &str) -> Evidence {
        let mut e = Evidence::default();
        let sample = &src[..floor_char_boundary(src, SAMPLE_LIMIT)];
        // Prose inside a docstring or text block is not evidence about the language.
        // English is full of `--`, `%` and `#`, and a docstring full of them should not
        // outvote the code around it.
        let mut in_triple: Option<&[u8]> = None;
        for (n, raw) in sample.split('\n').enumerate() {
            let line = raw.strip_suffix('\r').unwrap_or(raw);
            e.lines += 1;
            let t = line.trim_start().as_bytes();
            if t.is_empty() {
                continue;
            }
            if let Some(delim) = in_triple {
                if odd_count(line.as_bytes(), delim) {
                    in_triple = None;
                }
                continue;
            }
            if n == 0 && t.starts_with(b"#!") {
                e.shebang = shebang_kind(line);
                continue;
            }
            e.leading(t);
            e.trailing(t);
            e.inline(t);
            for delim in [b"\"\"\"".as_slice(), b"'''".as_slice()] {
                if odd_count(line.as_bytes(), delim) {
                    in_triple = Some(delim);
                    break;
                }
            }
        }
        e
    }

    /// Classify the first token of a line.
    fn leading(&mut self, t: &[u8]) {
        match t[0] {
            b'/' => {
                if t.starts_with(b"//") {
                    self.ls_slash2 += 1;
                } else if t.starts_with(b"/*") {
                    self.kw_c += 1;
                }
            }
            b'*' => self.ls_star += 1,
            b'#' => {
                if is_preproc(t) {
                    self.preproc += 1;
                } else if t.starts_with(b"#|") {
                    self.ls_hashpipe += 1;
                } else if !t.ends_with(b"\\") {
                    // A `#` line ending in a backslash is a macro continuation
                    // (`#assertion, 0, __FILE__ \`), not a comment.
                    self.ls_hash += 1;
                    if t.starts_with(b"##") {
                        // `## Heading` is markdown far more often than shell.
                        self.kw_md += 1;
                    }
                }
            }
            b'-' => {
                if t.starts_with(b"--[") {
                    self.lua_long += 1;
                    self.ls_dash2 += 1;
                } else if is_dash_comment(t) {
                    self.ls_dash2 += 1;
                } else if t.starts_with(b"-module(") || t.starts_with(b"-export(") {
                    self.kw_erlang += 1;
                }
            }
            b';' => {
                // `;; text` is a Lisp comment. A bare `;;` ends a shell case arm and
                // `; \` continues a C macro.
                let run = t.iter().take_while(|c| **c == b';').count();
                let rest = t[run..].trim_ascii();
                if run > 2 || (!rest.is_empty() && rest != b"\\") {
                    self.ls_semi += 1;
                }
            }
            b'%' => {
                // `% note` and `%%` are comments; `%s` and `%{name}` are placeholders,
                // and a bare `%` is a pass-through line in more formats than it is a
                // comment.
                // A space, specifically: `%\tchar ut_line[8];` is a pass-through line
                // in RPC and rpcgen sources, not a TeX comment.
                if t.get(1).is_none_or(|c| matches!(c, b' ' | b'%'))
                    && !t[1..].trim_ascii().is_empty()
                {
                    self.ls_percent += 1;
                }
                // Matlab's block delimiters must stand alone on their line.
                if t == b"%{" || t == b"%}" {
                    self.kw_matlab += 1;
                }
            }
            b'\'' => self.ls_squote += 1,
            b'!' => self.ls_bang += 1,
            b'<' => {
                if t.starts_with(b"<!--") {
                    self.ls_ltbang += 1;
                } else if starts_ci(t, "<?xml")
                    || starts_ci(t, "<!doctype")
                    || starts_ci(t, "<html")
                {
                    self.kw_markup += 1;
                } else if t.starts_with(b"<#") {
                    self.ps_block += 1;
                } else {
                    self.ls_lt += 1;
                }
            }
            b'(' => {
                self.ls_paren += 1;
                if t.starts_with(b"(*") {
                    if marker_followed_by_text(t, 2, b"*") {
                        self.ls_parenstar += 1;
                    }
                } else if t.starts_with(b"(def")
                    || t.starts_with(b"(ns ")
                    || t.starts_with(b"(let")
                    || t.starts_with(b"(require")
                    || t.starts_with(b"(fn ")
                {
                    self.kw_lisp += 1;
                }
            }
            b'{' => {
                if t.starts_with(b"{-") {
                    self.ls_bracedash += 1;
                }
            }
            b'=' => {
                if t.starts_with(b"=begin") || t.starts_with(b"=end") {
                    self.ruby_block += 1;
                }
            }
            b'[' => {
                if t.ends_with(b"]") && t.len() > 2 && !t.contains(&b',') {
                    self.ini_section += 1;
                }
            }
            b'`' => {
                if t.starts_with(b"```") {
                    self.kw_md += 1;
                    self.md_fence += 1;
                }
            }
            // Any line-leading `\macro` is TeX. Nothing else starts a line with a
            // backslash followed by a letter.
            b'\\' => {
                if t.get(1).is_some_and(|c| c.is_ascii_alphabetic()) && t.contains(&b'{') {
                    self.kw_tex += 1;
                }
            }
            b'@' => {
                if starts_ci(t, "@echo") {
                    self.kw_batch += 1;
                }
            }
            b':' => {
                // `:: note` is a batch comment; `::new (p) T` is C++ global scope.
                if t.starts_with(b"::") && marker_followed_by_text(t, 2, b":") {
                    self.ls_colon2 += 1;
                }
            }
            _ => self.keywords(t),
        }
    }

    /// Word-shaped hints. Only reached for lines starting with a letter, which is where
    /// keywords live, so the common punctuation-led lines skip this entirely.
    fn keywords(&mut self, t: &[u8]) {
        if starts_ci(t, "rem") && t.get(3).is_none_or(|c| *c == b' ' || *c == b'\t') {
            self.ls_rem += 1;
        }
        for (pat, field) in [
            ("public ", 0u8),
            ("private ", 0),
            ("protected ", 0),
            ("void ", 0),
            ("int ", 0),
            ("char ", 0),
            ("struct ", 0),
            ("typedef ", 0),
            ("namespace ", 0),
            ("func ", 0),
            ("fn ", 0),
            ("impl ", 0),
            ("var ", 0),
            ("let ", 0),
            ("const ", 0),
            ("function(", 0),
            ("function ", 0),
            ("console.", 0),
            ("System.out", 0),
            ("std::", 0),
            ("def ", 1),
            ("elif ", 1),
            ("print(", 1),
            ("echo ", 1),
            ("puts ", 1),
            ("fi", 1),
            ("esac", 1),
            ("done", 1),
            ("local ", 3),
            ("elseif ", 3),
            ("then", 3),
            ("nil", 3),
            ("module ", 4),
            ("newtype ", 4),
            ("instance ", 4),
            ("data ", 4),
            ("where", 4),
            ("let rec", 5),
            ("match ", 5),
            ("type ", 5),
            ("begin", 5),
            ("implicit none", 6),
            ("subroutine ", 6),
            ("end program", 6),
            ("integer ::", 6),
            ("real ::", 6),
        ] {
            if starts_word(t, pat) {
                match field {
                    0 => self.kw_c += 1,
                    1 => self.kw_hash += 1,
                    3 => self.kw_lua += 1,
                    4 => self.kw_hs += 1,
                    5 => self.kw_ml += 1,
                    _ => self.kw_fortran += 1,
                }
                break;
            }
        }
        for pat in [
            "select ",
            "insert into",
            "update ",
            "create table",
            "alter table",
            "delete from",
        ] {
            if starts_ci(t, pat) {
                self.kw_sql += 1;
                break;
            }
        }
        for pat in [
            "dim ",
            "end sub",
            "end function",
            "option explicit",
            "private sub",
            "public sub",
        ] {
            if starts_ci(t, pat) {
                self.kw_vb += 1;
                break;
            }
        }
        for pat in ["setlocal", "if exist", "@echo", "goto :eof"] {
            if starts_ci(t, pat) {
                self.kw_batch += 1;
                break;
            }
        }
        if t.starts_with(b"program ") || t.starts_with(b"end module") {
            self.kw_fortran += 1;
        }
        // `key = value` / `key: value` with a plain identifier key - config file shape.
        if let Some(sep) = t.iter().position(|c| *c == b'=' || *c == b':') {
            let key = t[..sep].trim_ascii_end();
            let plain = !key.is_empty()
                && key
                    .iter()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.'));
            if plain {
                self.kv_lines += 1;
            }
        }
    }

    /// Classify the last non-blank byte of a line.
    fn trailing(&mut self, t: &[u8]) {
        let end = t.iter().rposition(|c| *c != b' ' && *c != b'\t');
        if let Some(i) = end {
            match t[i] {
                b';' => self.end_semi += 1,
                b'{' | b'}' => self.end_brace += 1,
                b':' => self.end_colon += 1,
                _ => {}
            }
        }
    }

    /// Two-byte markers anywhere on the line. One pass, dispatched on the first byte.
    fn inline(&mut self, t: &[u8]) {
        let mut i = 0;
        while i < t.len() {
            let (a, b) = (t[i], t.get(i + 1).copied().unwrap_or(0));
            let prev_ws = i > 0 && (t[i - 1] == b' ' || t[i - 1] == b'\t');
            match (a, b) {
                // `/* ` opens a comment; `*/Modules/*` is a shell glob.
                (b'/', b'*') => {
                    if marker_followed_by_text(t, i + 2, b"*") {
                        self.slashstar += 1;
                    }
                }
                (b'*', b'/') => self.starslash += 1,
                (b'/', b'/') => {
                    if prev_ws {
                        self.trailing_slash2 += 1;
                    }
                    i += 1;
                }
                (b'-', b'-') => {
                    if prev_ws && is_dash_comment(&t[i..]) {
                        self.trailing_dash2 += 1;
                    }
                    i += 1;
                }
                // `(* ` with a space is a comment; `(*args)` is a call.
                (b'(', b'*') => {
                    if t.get(i + 2)
                        .is_none_or(|c| matches!(c, b' ' | b'\t' | b'*'))
                    {
                        self.parenstar += 1;
                    }
                }
                (b'*', b')') => self.starparen += 1,
                (b'{', b'-') => self.bracedash += 1,
                (b'-', b'}') => self.dashbrace += 1,
                (b'#', b'|') => self.hashpipe += 1,
                (b'|', b'#') => self.pipehash += 1,
                (b'<', b'!') => {
                    if t[i..].starts_with(b"<!--") {
                        self.ltbang += 1;
                    }
                }
                (b'#', _) => {
                    if prev_ws && !is_preproc(&t[i..]) {
                        self.trailing_hash += 1;
                    }
                }
                // Trailing `;`, `'` and `!` are the comment markers of Lisp, Visual
                // Basic and Fortran. They are also ordinary punctuation everywhere
                // else, so only the dialects that clear a keyword gate consult them.
                (b';', _) if prev_ws => self.trailing_semi += 1,
                (b'\'', _) if prev_ws => self.trailing_squote += 1,
                (b'!', b'=') => {}
                (b'!', _) if prev_ws => self.trailing_bang += 1,
                (b'[', b'(') => self.kw_md += 1, // `](` from a markdown link
                _ => {}
            }
            i += 1;
        }
    }
}

/// A `--` comment marker is followed by whitespace, more dashes, or a Lua/Haskell
/// decoration. `--brand` is a CSS custom property and `--count` is a decrement, and
/// neither should be evidence for a `--` comment dialect.
fn is_dash_comment(t: &[u8]) -> bool {
    t.starts_with(b"--")
        && t.get(2)
            .is_none_or(|c| matches!(c, b' ' | b'\t' | b'[' | b'|' | b'\r'))
}

/// True when `delim` occurs an odd number of times in `line`, i.e. the line opens or
/// closes a triple-quoted region without balancing it.
fn odd_count(line: &[u8], delim: &[u8]) -> bool {
    let mut n = 0usize;
    let mut i = 0;
    while i + delim.len() <= line.len() {
        if &line[i..i + delim.len()] == delim {
            n += 1;
            i += delim.len();
        } else {
            i += 1;
        }
    }
    n % 2 == 1
}

/// True when the byte after a marker looks like the start of comment text rather than
/// more code: whitespace, end of line, or one of the marker's own repeat characters.
///
/// This one rule separates `(* note` from `(*args)`, `% note` from `%s`, and `/* note`
/// from a `*/glob/*` - the coincidences that otherwise vote for the wrong dialect.
fn marker_followed_by_text(t: &[u8], at: usize, repeats: &[u8]) -> bool {
    t.get(at)
        .is_none_or(|c| matches!(c, b' ' | b'\t' | b'\r') || repeats.contains(c))
}

/// A C preprocessor directive: `#` then optional space then a directive keyword.
///
/// The list has to be complete. A `#` line that is not recognised here is counted as a
/// `#` comment, and a header stripped of its comments would then lose its include
/// guards on a second pass.
fn is_preproc(t: &[u8]) -> bool {
    const DIRECTIVES: [&str; 21] = [
        "include_next",
        "include",
        "import",
        "define",
        "undef",
        "ifdef",
        "ifndef",
        "if",
        "elifdef",
        "elifndef",
        "elif",
        "else",
        "endif",
        "error",
        "warning",
        "pragma",
        "line",
        "assert",
        "unassert",
        "ident",
        "sccs",
    ];
    if !t.starts_with(b"#") {
        return false;
    }
    let rest = &t[1..];
    let start = rest
        .iter()
        .position(|c| *c != b' ' && *c != b'\t')
        .unwrap_or(rest.len());
    let word = &rest[start..];
    DIRECTIVES.iter().any(|d| {
        word.starts_with(d.as_bytes())
            && word
                .get(d.len())
                .is_none_or(|c| !c.is_ascii_alphanumeric() && *c != b'_')
    })
}

/// `starts_with`, but a pattern ending in a word character must be followed by a
/// non-word character - otherwise `fi` matches `final` and `nil` matches `nilpotent`.
fn starts_word(t: &[u8], pat: &str) -> bool {
    let p = pat.as_bytes();
    if !t.starts_with(p) {
        return false;
    }
    match p.last() {
        Some(c) if c.is_ascii_alphanumeric() || *c == b'_' => t
            .get(p.len())
            .is_none_or(|c| !c.is_ascii_alphanumeric() && *c != b'_'),
        _ => true,
    }
}

fn starts_ci(t: &[u8], pat: &str) -> bool {
    t.len() >= pat.len() && t[..pat.len()].eq_ignore_ascii_case(pat.as_bytes())
}

fn shebang_kind(line: &str) -> Shebang {
    let l = line.to_ascii_lowercase();
    const C_LIKE: [&str; 3] = ["node", "deno", "bun"];
    if C_LIKE.iter().any(|n| l.contains(n)) {
        return Shebang::CLang;
    }
    Shebang::HashLang
}

fn floor_char_boundary(s: &str, mut i: usize) -> usize {
    if i >= s.len() {
        return s.len();
    }
    while !s.is_char_boundary(i) {
        i -= 1;
    }
    i
}

fn cap(v: u32, max: u32) -> i32 {
    v.min(max) as i32
}

// --- scoring ---------------------------------------------------------------

/// A dialect's case, split into the three things that should not be interchangeable.
struct Case {
    /// Direct comment-marker evidence. Nothing else can substitute for it.
    markers: i32,
    /// Corroborating context: keywords, code shape, shebang.
    bonus: i32,
    /// Evidence that this dialect is the wrong answer.
    penalty: i32,
}

/// Score a dialect against the evidence.
///
/// Two rules do most of the work of keeping comex off real code:
///
/// 1. **No markers, no score.** Structure and keywords never license comment removal on
///    their own. A shell script full of braces and semicolons is not C.
/// 2. **Bonuses cannot outvote markers.** Context can at most double a dialect's marker
///    score, so a pile of keywords can never overwhelm a single opposing marker.
fn score(d: Dialect, e: &Evidence) -> i32 {
    // Dialects whose markers are ordinary punctuation elsewhere need a keyword gate
    // before their evidence counts at all.
    match d {
        // `'` and `!` are punctuation in every other language on earth, so these two
        // need to see the language itself before their markers count for anything.
        Dialect::VisualBasic if e.kw_vb < 2 => return 0,
        Dialect::Fortran if e.kw_fortran < 2 || e.ls_bang == 0 => return 0,
        Dialect::Ini if e.ini_section == 0 => return 0,
        // A line-leading `%` is a comment in TeX and Erlang - and a continuation line
        // in Python (`"fmt %s"\n    % (args)`). Require the language to show itself.
        Dialect::Percent if e.kw_tex + e.kw_erlang + e.kw_matlab == 0 => return 0,
        // `(*` opens a comment in OCaml and dereferences a pointer in C, and
        // `f(*args)` unpacks a list in Python. Real ML code puts one at a line start.
        Dialect::Ml if e.ls_parenstar == 0 => return 0,
        // A `--` dialect puts a comment on its own line somewhere. Without that, the
        // evidence is ` -- ` inside prose, which is English, not Haskell.
        Dialect::Sql if e.ls_dash2 == 0 && e.slashstar.min(e.starslash) == 0 => return 0,
        Dialect::Lua if e.ls_dash2 == 0 && e.lua_long == 0 => return 0,
        Dialect::Haskell if e.ls_dash2 == 0 && e.bracedash.min(e.dashbrace) == 0 => return 0,
        // `<!--` inside a string literal is XML embedded in some other language. Real
        // markup also has tags at the starts of lines.
        Dialect::Markup if e.ls_ltbang == 0 && e.kw_markup == 0 && e.ls_lt < 3 => return 0,
        // `::` alone is C++ scope resolution far more often than it is a batch comment.
        Dialect::Batch if e.kw_batch == 0 && e.ls_rem == 0 => return 0,
        _ => {}
    }
    let c = case(d, e);
    if c.markers == 0 {
        return 0;
    }
    c.markers + c.bonus.min(c.markers) - c.penalty
}

fn case(d: Dialect, e: &Evidence) -> Case {
    let code_shape = cap(e.end_semi + e.end_brace, 40);
    match d {
        Dialect::Unknown => Case {
            markers: 0,
            bonus: 0,
            penalty: 0,
        },

        Dialect::CFamily => Case {
            markers: 14 * cap(e.ls_slash2, 20)
                + 12 * cap(e.slashstar.min(e.starslash), 20)
                + 5 * cap(e.trailing_slash2, 10),
            // `ls_star` is the ` * ` continuation of a block comment - and also a
            // Markdown bullet, so it corroborates rather than counts.
            bonus: 4 * cap(e.ls_star, 10)
                + 2 * code_shape
                + 20 * cap(e.preproc, 3)
                + 3 * cap(e.kw_c, 15)
                + if e.shebang == Shebang::CLang { 30 } else { 0 },
            // Python and shell shape. `a // b` is floor division, and a comment-free
            // Python file must not be read as C on the strength of it.
            penalty: 5 * cap(e.kw_hash, 10)
                + 2 * cap(e.end_colon, 20)
                + if e.ls_hash > 0 && e.preproc == 0 && e.ls_slash2 == 0 && e.slashstar == 0 {
                    40
                } else {
                    0
                },
        },

        Dialect::Hash => Case {
            markers: 14 * cap(e.ls_hash, 20)
                + 5 * cap(e.trailing_hash, 10)
                + 12 * cap(e.ruby_block, 2)
                + 12 * cap(e.ps_block, 2),
            bonus: 3 * cap(e.kw_hash, 15)
                + 2 * cap(e.end_colon, 20)
                + 2 * cap(e.kv_lines, 30)
                + if e.shebang == Shebang::HashLang {
                    30
                } else {
                    0
                },
            // Braces and semicolons everywhere means `#` is a preprocessor directive or
            // a private field; Markdown structure means `#` is a heading.
            penalty: 3 * code_shape
                + 25 * cap(e.preproc, 3)
                + 20 * cap(e.kw_md, 10)
                + 6 * cap(e.ls_slash2, 10),
        },

        Dialect::Sql => Case {
            markers: 14 * cap(e.ls_dash2, 20)
                + 5 * cap(e.trailing_dash2, 10)
                + 12 * cap(e.slashstar.min(e.starslash), 10),
            bonus: 10 * cap(e.kw_sql, 10),
            penalty: 30 * cap(e.lua_long, 1) + 8 * cap(e.kw_hs, 5) + 6 * cap(e.kw_lua, 5),
        },

        Dialect::Lua => Case {
            markers: 14 * cap(e.ls_dash2, 20)
                + 5 * cap(e.trailing_dash2, 10)
                + 25 * cap(e.lua_long, 3),
            bonus: 6 * cap(e.kw_lua, 10),
            penalty: 8 * cap(e.kw_sql, 5) + 8 * cap(e.kw_hs, 5),
        },

        Dialect::Haskell => Case {
            markers: 14 * cap(e.ls_dash2, 20)
                + 5 * cap(e.trailing_dash2, 10)
                + 20 * cap(e.bracedash.min(e.dashbrace), 5),
            bonus: 6 * cap(e.kw_hs, 10),
            penalty: 8 * cap(e.kw_sql, 5) + 8 * cap(e.kw_lua, 5),
        },

        Dialect::Lisp => Case {
            // Only line-leading `;` counts. A trailing one is a statement separator
            // in shell, Makefiles and C.
            markers: 14 * cap(e.ls_semi, 20) + 15 * cap(e.hashpipe.min(e.pipehash), 5),
            bonus: 5 * cap(e.kw_lisp, 15) + 2 * cap(e.ls_paren, 20),
            penalty: 20 * cap(e.ini_section, 1) + 2 * code_shape,
        },

        Dialect::Markup => Case {
            markers: 16 * cap(e.ls_ltbang + e.ltbang, 20),
            bonus: 25 * cap(e.kw_markup, 3) + 6 * cap(e.kw_md, 10) + cap(e.ls_lt, 30),
            // `key: value` lines everywhere is YAML, not Markdown or HTML. Definitions
            // and colon-terminated lines mean the `<!-- -->` are XML inside string
            // literals of some other language.
            penalty: 2 * cap(e.kv_lines, 20) + 4 * cap(e.kw_hash, 15) + 2 * cap(e.end_colon, 20),
        },

        Dialect::Ml => Case {
            markers: 14 * cap(e.ls_parenstar, 20) + 12 * cap(e.parenstar.min(e.starparen), 10),
            bonus: 5 * cap(e.kw_ml, 10),
            // `(*p)` and `(*fn)(x)` are pointer syntax, not comments.
            penalty: if e.preproc > 0 || e.ls_slash2 > 0 || e.end_semi > 3 {
                40
            } else {
                0
            },
        },

        // Only line-leading `%` counts: a trailing one is modulo in half the languages
        // in existence.
        Dialect::Percent => Case {
            markers: 14 * cap(e.ls_percent, 20),
            bonus: 30 * cap(e.kw_tex, 3) + 30 * cap(e.kw_erlang, 3) + 15 * cap(e.kw_matlab, 3),
            penalty: if e.kw_tex == 0 && e.kw_erlang == 0 && e.end_semi + e.end_brace > 5 {
                25
            } else {
                0
            },
        },

        Dialect::VisualBasic => Case {
            markers: 10 * cap(e.ls_squote, 20)
                + 5 * cap(e.trailing_squote, 10)
                + 12 * cap(e.ls_rem, 10),
            bonus: 25 * cap(e.kw_vb, 4),
            penalty: 0,
        },

        Dialect::Batch => Case {
            markers: 12 * cap(e.ls_rem, 10) + 12 * cap(e.ls_colon2, 10),
            bonus: 20 * cap(e.kw_batch, 3),
            penalty: 0,
        },

        Dialect::Fortran => Case {
            markers: 10 * cap(e.ls_bang, 20) + 5 * cap(e.trailing_bang, 10),
            bonus: 25 * cap(e.kw_fortran, 4),
            penalty: 0,
        },

        Dialect::Ini => Case {
            markers: 10 * cap(e.ls_semi, 10)
                + 10 * cap(e.ls_hash, 10)
                + 5 * cap(e.trailing_semi + e.trailing_hash, 10),
            bonus: 12 * cap(e.ini_section, 10) + cap(e.kv_lines, 20),
            penalty: 3 * code_shape + 2 * cap(e.ls_paren, 20),
        },
    }
}

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

    fn d(src: &str) -> Dialect {
        detect(src).dialect
    }

    #[test]
    fn c_family_from_slashes_and_braces() {
        assert_eq!(
            d("int main(void) {\n  // start\n  return 0;\n}\n"),
            Dialect::CFamily
        );
        assert_eq!(
            d("#include <stdio.h>\n#define X 1\n/* note */\nint x = 3 % 2;\n"),
            Dialect::CFamily
        );
    }

    #[test]
    fn structure_alone_never_licenses_stripping() {
        // Braces, semicolons and preprocessor lines look like C, but with no comment
        // marker anywhere there is nothing to detect - and so nothing to remove.
        assert_eq!(
            d("#include <stdio.h>\n#define X 1\nint x = 3 % 2;\n"),
            Dialect::Unknown
        );
        assert_eq!(d("#!/bin/bash\nset -e\necho hi\n"), Dialect::Unknown);
    }

    #[test]
    fn python_floor_division_is_not_a_comment() {
        // A file with no comment markers scores below THRESHOLD, so `//` survives -
        // the failure mode that would matter most is deleting real code.
        let src = "def f(a, b):\n    return a // b\n";
        assert_eq!(d(src), Dialect::Unknown);
        assert_eq!(crate::strip_comments(src), src);

        // With a real `#` comment present, Hash wins and `//` still survives.
        let src = "# halve it\ndef f(a, b):\n    return a // b\n";
        assert_eq!(d(src), Dialect::Hash);
        assert_eq!(
            crate::strip_comments(src),
            "def f(a, b):\n    return a // b\n"
        );
    }

    #[test]
    fn shell_and_python_are_hash() {
        assert_eq!(
            d("#!/bin/bash\n# strict mode\nset -e\necho hi\n"),
            Dialect::Hash
        );
        assert_eq!(d("# config\nname: thing\nport: 80\n"), Dialect::Hash);
    }

    #[test]
    fn markdown_headings_are_not_shell_comments() {
        let src =
            "# Title\n\nSome text.\n\n## Section\n\n- a bullet\n- another\n\n```sh\nls\n```\n";
        assert_ne!(d(src), Dialect::Hash);
    }

    #[test]
    fn markup_wins_for_html() {
        assert_eq!(
            d("<!DOCTYPE html>\n<html>\n<!-- hi -->\n<body></body>\n</html>\n"),
            Dialect::Markup
        );
    }

    #[test]
    fn sql_lua_and_haskell_share_a_marker_but_split_on_context() {
        assert_eq!(
            d("-- fetch rows\nSELECT a, b FROM t WHERE x = 1;\n"),
            Dialect::Sql
        );
        assert_eq!(
            d("-- init\nlocal x = 1\nfunction f()\n  return x\nend\n"),
            Dialect::Lua
        );
        assert_eq!(
            d("-- | doc\nmodule Main where\n{- block -}\ndata T = T\n"),
            Dialect::Haskell
        );
    }

    #[test]
    fn empty_and_markerless_input_is_unknown() {
        assert_eq!(d(""), Dialect::Unknown);
        assert_eq!(d("just some words\nand more words\n"), Dialect::Unknown);
    }

    #[test]
    fn confidence_is_bounded() {
        for src in ["", "// x\n", "#!/bin/sh\n# y\n", "<!-- z -->"] {
            let det = detect(src);
            assert!((0.0..=1.0).contains(&det.confidence), "{src:?} -> {det:?}");
        }
    }
}