lang-parsing-substrate 0.17.3

Shared language-parsing substrate for knots, moldy, aurora-lint, and clew
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
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
//! Cheap, **heuristic** file-type classification, so a consumer can exit early
//! before handing a file to tree-sitter.
//!
//! [`language_for_file`](crate::language_for_file) dispatches purely on the
//! extension, so today a 2 GB zip named `foo.c` goes straight to the C parser.
//! [`classify`] looks at a bounded prefix of the file's bytes (never the whole
//! file) plus its size, and answers one of:
//!
//! - [`FileClass::Empty`] — zero-length file.
//! - [`FileClass::Binary`] — a recognised magic number (zip, gzip, xz, zstd,
//!   tar, ELF, PE, Mach-O, PNG, JPEG, PDF, … — the table is the [`infer`]
//!   crate's) or a byte distribution that does not look like text (NUL bytes,
//!   C0 control bytes, a high invalid-UTF-8 ratio).
//! - [`FileClass::Oversize`] — looks like text, but is larger than the
//!   caller-supplied limit.
//! - [`FileClass::SourceText`] — looks like text, with its probable
//!   [`TextEncoding`] and language hints.
//!
//! # This is a heuristic, and it is wrong both ways
//!
//! A text file can be called binary (e.g. a source file with a run of
//! embedded NUL bytes, or UTF-16 without a BOM), and a binary file can be
//! called text (e.g. a format with no magic number `infer` knows and
//! mostly-ASCII content). Treat the result as a cheap early-exit signal, not
//! a verdict.
//!
//! ## Known limitations
//!
//! - **Prefix only.** Only the first `prefix_len` bytes are inspected. A text
//!   header followed by binary data later in the file (or vice versa) is
//!   classified by the header alone.
//! - **Calibrated on C/C++ corpora, not on every language.** The thresholds
//!   (NUL ≥ 8 and > 0.1%; other controls ≥ 8 and > 5%; invalid UTF-8 > 30%
//!   with ≥ 8 NUL/control bytes) were checked against ~201K files: the
//!   aurora-lint benchmark corpora, Juliet, aurora-lint's fixtures and
//!   other checkouts. No C-family file came back `Binary`. See
//!   `docs/classify-calibration.md`, and re-run with
//!   `cargo run --example classify_calibrate` on new corpora.
//! - **Source with many raw NUL bytes is `Binary`.** e.g. fuzz-regression
//!   tests that embed raw NULs in string literals (one Java file in the
//!   calibration set). This can't be fixed by tuning thresholds.
//! - **Tiny binaries can be `SourceText`.** Each signal needs at least 8
//!   offending bytes, so a binary of a few dozen bytes may pass as text.
//!   That costs one cheap parse; the reverse mistake would drop real source.
//! - **BOM-less UTF-16 is `Binary`.** Every other byte is NUL.
//! - **UTF-32 is `Binary`.** There is no UTF-32 variant. Its BOMs
//!   (`FF FE 00 00`, `00 00 FE FF`) are deliberately not read as UTF-16, so
//!   the NUL ratio decides.
//! - **A UTF-16 BOM skips the byte statistics.** Any file starting with
//!   `FF FE` or `FE FF` (and no strong magic number) is `SourceText`, even
//!   if what follows is not text.
//! - **`Latin1` means "not UTF-8", not "ISO-8859-1".** Windows-1252, other
//!   ISO-8859 parts, and multi-byte legacy encodings (GBK, Shift-JIS, EUC-KR)
//!   all report `Latin1`. EBCDIC is not recognised at all.
//! - **Weak signatures need binary-looking bytes.** A binary format whose
//!   `infer` signature is short and ASCII-like (`MZ`, `BM`, `GIF`, `%!`,
//!   `ustar` at 257, `%PDF-` not at offset 0, …) and whose prefix is also
//!   text-like (e.g. a tiny uncompressed PDF) is reported as `SourceText`.
//! - **`infer` decides the kind and MIME by first match.** Without its `std`
//!   feature (which this crate leaves off, to avoid the `cfb` dependency) every
//!   OLE2 compound file — `.doc`, `.xls`, `.ppt`, `.msi` — reports as
//!   `Document` / `"application/msword"`. Report `mime` as-is; it is not a
//!   stable identifier and may change with `infer` upgrades.
//! - **`Oversize` applies to text only.** A binary file is `Binary` at any
//!   size, and an empty file is `Empty` even if the limit is 0.
//! - **`classify_file` follows symlinks** and checks the size before reading,
//!   so a file that grows or shrinks between the two calls is classified with
//!   a stale size.
//! - **Language hints are shallow.** Only `#!` interpreters and a leading
//!   `<?php` are recognised. There is no content-based C-vs-C++ sniff for
//!   `.h` here (see below).
//!
//! The substrate deliberately sets **no policy**: whether a `Binary` or
//! `Oversize` result means "skip and report" or "try anyway" is the caller's
//! decision, and so is the size limit ([`ClassifyLimits::max_size`] defaults
//! to no limit).
//!
//! # Language hints
//!
//! [`FileClass::SourceText`] carries two independent hints: the language the
//! *extension* implies (via the registry) and the language the *content*
//! implies (a `#!` shebang line or a leading `<?php`). Disagreement between
//! the two is reported, never acted on — a `.c` file whose first line is
//! `#!/usr/bin/env python3` is still `SourceText`, and only the caller decides
//! what that means. Only languages compiled into this build are ever named.
//! For the `.h` C-vs-C++ question, use
//! `language_for_header_content` (with `lang-c` + `lang-cpp`) instead.

use std::fs::File;
use std::io::{self, Read};
use std::path::Path;

use crate::registry::{language_info_for_file, languages, LanguageInfo};

/// Suggested prefix length for [`classify_file`]: 8 KiB, the same window git
/// uses for its binary-file check. Callers may pass any length; longer
/// prefixes make the byte-distribution ratios more reliable.
pub const DEFAULT_PREFIX_LEN: usize = 8 * 1024;

/// What [`classify`] thinks a file is. See the [module docs](self) for why
/// this is only a hint.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum FileClass {
    /// The file is zero bytes long.
    Empty,
    /// The file looks like text but exceeds the caller's size limit.
    /// Binary files are reported as [`FileClass::Binary`] regardless of size.
    Oversize {
        /// The file's size in bytes.
        size: u64,
        /// The caller-supplied limit it exceeded.
        limit: u64,
    },
    /// The file does not look like text.
    Binary {
        /// The kind of binary; [`BinaryKind::Unknown`] if no magic number
        /// identified it.
        kind: BinaryKind,
        /// MIME type from the magic-number match (e.g. `"application/zip"`),
        /// for reporting; `None` when only the byte distribution decided.
        mime: Option<&'static str>,
    },
    /// The file looks like text.
    SourceText(SourceText),
}

impl FileClass {
    /// `true` for [`FileClass::SourceText`] — the only class worth parsing
    /// under the most conservative policy.
    pub fn is_source_text(&self) -> bool {
        matches!(self, FileClass::SourceText(_))
    }
}

/// The kind of a [`FileClass::Binary`] file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BinaryKind {
    /// Multi-file archive: zip (incl. jar/apk), tar, 7z, rar, `ar` (static
    /// libraries), deb, rpm, cab, cpio.
    Archive,
    /// Single-stream compressed data: gzip, xz, zstd, bzip2, lz4, lzip, `.Z`.
    Compressed,
    /// ELF executable, shared object, or object file.
    Elf,
    /// Windows PE/COFF (`MZ` … `PE\0\0`) executable or DLL.
    Pe,
    /// Mach-O executable (thin or fat/universal).
    MachO,
    /// Image: PNG, JPEG, GIF, WebP, TIFF, BMP, ICO, PSD, …
    Image,
    /// PDF document.
    Pdf,
    /// Office / e-book document: doc/xls/ppt, docx/xlsx/pptx, odt/ods/odp,
    /// epub, mobi.
    Document,
    /// Audio or video.
    Media,
    /// Font file: woff, woff2, ttf, otf.
    Font,
    /// Some other recognised binary (wasm, Java class, sqlite, …), or no
    /// magic number matched but the byte distribution is not text-like.
    Unknown,
}

/// The probable encoding of a [`FileClass::SourceText`] file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TextEncoding {
    /// Valid UTF-8 (which includes pure ASCII), no BOM.
    Utf8,
    /// Valid UTF-8 after a leading `EF BB BF` byte-order mark.
    Utf8Bom,
    /// UTF-16 little-endian, identified by its `FF FE` BOM. (BOM-less UTF-16
    /// is indistinguishable from binary here and classifies as `Binary`.)
    Utf16Le,
    /// UTF-16 big-endian, identified by its `FE FF` BOM.
    Utf16Be,
    /// Not valid UTF-8, but text-like: some legacy 8-bit encoding. Decoding
    /// as Latin-1 (ISO-8859-1) is lossless, though the true encoding may be
    /// Windows-1252, another ISO-8859 part, or a multi-byte legacy encoding.
    Latin1,
}

/// Details of a [`FileClass::SourceText`] result.
#[derive(Debug, Clone, Copy)]
pub struct SourceText {
    /// Probable encoding of the bytes.
    pub encoding: TextEncoding,
    /// `true` when the file starts with a UTF-8 BOM. Usually implied by
    /// [`TextEncoding::Utf8Bom`], but also set when the bytes after the BOM
    /// are not valid UTF-8 and `encoding` is therefore `Latin1`.
    pub utf8_bom: bool,
    /// The language the file's extension maps to, if any (registry lookup).
    pub by_extension: Option<&'static LanguageInfo>,
    /// The language the file's content suggests (shebang / `<?php`), if any.
    pub by_content: Option<&'static LanguageInfo>,
}

impl SourceText {
    /// Best single guess: the extension's language, else the content's.
    pub fn likely_language(&self) -> Option<&'static LanguageInfo> {
        self.by_extension.or(self.by_content)
    }

    /// `Some(true)` / `Some(false)` when both hints exist and agree /
    /// disagree; `None` when either is missing. A hint only — never a gate.
    pub fn extension_agrees(&self) -> Option<bool> {
        Some(self.by_extension?.key == self.by_content?.key)
    }
}

/// Caller policy for [`classify`] / [`classify_file`].
#[derive(Debug, Clone, Copy)]
pub struct ClassifyLimits {
    /// How many leading bytes [`classify_file`] reads. Ignored by
    /// [`classify`], which takes whatever prefix it is given.
    pub prefix_len: usize,
    /// Text files larger than this many bytes are reported as
    /// [`FileClass::Oversize`]. `None` (the default) means no limit.
    pub max_size: Option<u64>,
}

impl Default for ClassifyLimits {
    fn default() -> Self {
        Self {
            prefix_len: DEFAULT_PREFIX_LEN,
            max_size: None,
        }
    }
}

/// Classifies a file from its path, a bounded prefix of its bytes, and its
/// total size. **Heuristic** — see the [module docs](self).
///
/// `prefix` must be the file's first bytes (any length; [`DEFAULT_PREFIX_LEN`]
/// is a reasonable choice) and `file_size` its full length in bytes. `path` is
/// used only for the extension hint — no I/O happens here.
///
/// Order of checks: zero size → `Empty`; strong magic number → `Binary`;
/// byte distribution (NUL ratio, control-byte ratio, invalid-UTF-8 ratio)
/// not text-like → `Binary` (kind from a weak magic hit, else `Unknown`);
/// size above `limits.max_size` → `Oversize`; otherwise `SourceText`. A
/// UTF-16 BOM skips the byte-distribution check. Binary always wins over
/// `Oversize`, so a huge archive is reported as an archive.
///
/// Magic numbers come from the [`infer`] crate's table. Its text-format
/// matchers (HTML, XML, `#!`, PEM, RTF, PostScript) are ignored, and its
/// short ASCII-looking signatures are only trusted alongside binary-looking
/// bytes, since e.g. a source file can legitimately start with `MZ` or `BM`.
pub fn classify(path: &Path, prefix: &[u8], file_size: u64, limits: &ClassifyLimits) -> FileClass {
    if file_size == 0 {
        return FileClass::Empty;
    }
    let magic = magic(prefix);
    if let Some(m) = magic.as_ref().filter(|m| m.strong) {
        return binary(m.kind, Some(m.mime));
    }

    let (encoding, body) = split_bom(prefix);
    let stats = ByteStats::of(body, (prefix.len() as u64) < file_size);
    if stats.looks_binary() {
        return match magic {
            Some(m) => binary(m.kind, Some(m.mime)),
            None => binary(BinaryKind::Unknown, None),
        };
    }
    if let Some(limit) = limits.max_size {
        if file_size > limit {
            return FileClass::Oversize {
                size: file_size,
                limit,
            };
        }
    }
    // A UTF-8 BOM followed by invalid UTF-8 is still reported as `Latin1`
    // (the bytes after the BOM are what a decoder has to handle); the BOM
    // itself is reported separately so it isn't lost.
    let had_utf8_bom = encoding == TextEncoding::Utf8Bom;
    let encoding = if stats.invalid_utf8 == 0 {
        encoding
    } else {
        TextEncoding::Latin1
    };
    FileClass::SourceText(SourceText {
        encoding,
        utf8_bom: had_utf8_bom,
        by_extension: language_info_for_file(path),
        by_content: content_language(body),
    })
}

fn binary(kind: BinaryKind, mime: Option<&'static str>) -> FileClass {
    FileClass::Binary { kind, mime }
}

/// Splits a leading BOM off `prefix`. A UTF-16 BOM yields an empty body: the
/// byte statistics are meaningless for UTF-16, so they are skipped.
fn split_bom(prefix: &[u8]) -> (TextEncoding, &[u8]) {
    if let Some(rest) = prefix.strip_prefix(b"\xEF\xBB\xBF") {
        (TextEncoding::Utf8Bom, rest)
    } else if prefix.starts_with(b"\xFF\xFE") && !prefix.starts_with(b"\xFF\xFE\0\0") {
        // `FF FE 00 00` is the UTF-32 LE BOM, not UTF-16 LE + U+0000; it
        // falls through to the byte statistics (see "Known limitations").
        (TextEncoding::Utf16Le, &[])
    } else if prefix.starts_with(b"\xFE\xFF") {
        (TextEncoding::Utf16Be, &[])
    } else {
        (TextEncoding::Utf8, prefix)
    }
}

/// The raw byte counts behind [`classify`]'s text-vs-binary decision for one
/// prefix: `(len, nul, control, invalid_utf8)`, after BOM handling.
///
/// Not part of the stable API — it exists so `examples/classify_calibrate.rs`
/// can report the ratios a corpus actually produces.
#[doc(hidden)]
pub fn __byte_counts(prefix: &[u8], file_size: u64) -> (usize, usize, usize, usize) {
    let (_, body) = split_bom(prefix);
    let s = ByteStats::of(body, (prefix.len() as u64) < file_size);
    (s.len, s.nul, s.control, s.invalid_utf8)
}

/// Reads `path`'s metadata and at most `limits.prefix_len` leading bytes,
/// then calls [`classify`]. Never reads past the prefix.
///
/// Returns an `InvalidInput` error for anything that is not a regular file
/// (directories, FIFOs, sockets, devices), since opening or reading those can
/// block or never end. Symlinks are followed. The file type is checked with
/// `std::fs::metadata` *before* opening, because opening a FIFO blocks until a
/// writer appears. A path swapped for a FIFO between that check and the open
/// can still block; that race is not defended against.
pub fn classify_file(path: &Path, limits: &ClassifyLimits) -> io::Result<FileClass> {
    let meta = std::fs::metadata(path)?;
    if !meta.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("{} is not a regular file", path.display()),
        ));
    }
    let file = File::open(path)?;
    let mut prefix = Vec::with_capacity(limits.prefix_len.min(meta.len() as usize));
    file.take(limits.prefix_len as u64)
        .read_to_end(&mut prefix)?;
    Ok(classify(path, &prefix, meta.len(), limits))
}

// ---------------------------------------------------------------------------
// Magic numbers (via `infer`)
// ---------------------------------------------------------------------------

/// A magic-number hit from `infer`.
struct Magic {
    kind: BinaryKind,
    mime: &'static str,
    /// `true` when the bytes `infer` checks for this type include at least
    /// one NUL, C0 control, or invalid-UTF-8 byte — so no text file can
    /// match — and the hit is trusted outright. (e.g. woff/woff2 start with
    /// ASCII `wOFF`/`wOF2`, but `infer` also requires `00 01 00 00` after.)
    /// Weak hits — `infer` matches `MZ`, `BM`, `GIF`, `BZh`, `ustar` at 257,
    /// `%PDF-` anywhere in the first KiB, … — only count when the byte
    /// distribution independently looks binary.
    strong: bool,
}

/// `infer` extensions whose signatures are strong (see [`Magic::strong`]).
/// Without `infer`'s `std` feature every OLE2 file reports as `"doc"`, so
/// `xls` / `ppt` / `msi` can never be returned and are not listed.
const STRONG: &[&str] = &[
    "zip", "docx", "xlsx", "pptx", "odt", "ods", "odp", "epub", "ora", "gz", "xz", "zst", "lz4",
    "7z", "rar", "rpm", "doc", "elf", "mach", "class", "wasm", "png", "jpg", "woff", "woff2",
    "mkv", "webm",
];

fn magic(prefix: &[u8]) -> Option<Magic> {
    let t = infer::get(prefix)?;
    let ext = t.extension();
    let kind = match (t.matcher_type(), ext) {
        // Text formats `infer` also recognises (html, xml, `#!` scripts, PEM,
        // RTF, PostScript): not binary — let the byte statistics decide.
        (infer::MatcherType::Text, _) | (_, "pem" | "rtf" | "ps") => return None,
        (_, "elf") => BinaryKind::Elf,
        (_, "exe" | "dll") => BinaryKind::Pe,
        (_, "mach") => BinaryKind::MachO,
        (_, "pdf") => BinaryKind::Pdf,
        (_, "gz" | "bz2" | "bz3" | "xz" | "zst" | "lz4" | "Z" | "lz") => BinaryKind::Compressed,
        (
            _,
            "zip" | "tar" | "rar" | "7z" | "ar" | "deb" | "rpm" | "cab" | "crx" | "cpio" | "par2",
        ) => BinaryKind::Archive,
        (infer::MatcherType::Image, _) => BinaryKind::Image,
        (infer::MatcherType::Doc | infer::MatcherType::Book, _) => BinaryKind::Document,
        (infer::MatcherType::Audio | infer::MatcherType::Video, _) => BinaryKind::Media,
        (infer::MatcherType::Font, _) => BinaryKind::Font,
        _ => BinaryKind::Unknown,
    };
    // `infer` accepts `%PDF-` anywhere in the first KiB; only offset 0 is strong.
    let strong = STRONG.contains(&ext) || (ext == "pdf" && prefix.starts_with(b"%PDF-"));
    Some(Magic {
        kind,
        mime: t.mime_type(),
        strong,
    })
}

// ---------------------------------------------------------------------------
// Byte distribution
// ---------------------------------------------------------------------------

/// Minimum NUL count before the NUL ratio can make a prefix `Binary`.
const NUL_FLOOR: usize = 8;
/// Minimum C0-control count before the control ratio can make a prefix
/// `Binary`.
const CONTROL_FLOOR: usize = 8;

struct ByteStats {
    len: usize,
    nul: usize,
    /// C0 controls other than \t \n \v \f \r, ESC and SUB (DOS EOF), plus DEL.
    control: usize,
    invalid_utf8: usize,
}

impl ByteStats {
    fn of(b: &[u8], truncated: bool) -> Self {
        let mut nul = 0;
        let mut control = 0;
        for &c in b {
            match c {
                0 => nul += 1,
                b'\t' | b'\n' | 0x0B | 0x0C | b'\r' | 0x1A | 0x1B => {}
                0x01..=0x1F | 0x7F => control += 1,
                _ => {}
            }
        }
        Self {
            len: b.len(),
            nul,
            control,
            invalid_utf8: invalid_utf8_bytes(b, truncated),
        }
    }

    /// Each signal needs both an absolute floor and a ratio, so a handful
    /// of stray bytes in a small source file never makes it `Binary` (a
    /// false `Binary` silently drops real source, the worst outcome for a
    /// consumer):
    /// - NUL: at least [`NUL_FLOOR`] and more than 0.1% of the prefix.
    /// - other control bytes: at least [`CONTROL_FLOOR`] and more than 5%.
    /// - invalid UTF-8 above 30%, together with at least [`NUL_FLOOR`]
    ///   NUL-or-control bytes — legacy multi-byte text (GBK, Shift-JIS) can
    ///   be mostly invalid UTF-8 but has no control bytes.
    ///
    /// The cost is that a binary file too small to reach the floors is
    /// reported as text, which only means a cheap parse of a tiny file.
    fn looks_binary(&self) -> bool {
        let len = self.len;
        (self.nul >= NUL_FLOOR && self.nul * 1000 > len)
            || (self.control >= CONTROL_FLOOR && self.control * 100 > len * 5)
            || (self.invalid_utf8 * 100 > len * 30 && self.nul + self.control >= NUL_FLOOR)
    }
}

/// Counts bytes that are not part of a valid UTF-8 sequence. When the prefix
/// is `truncated` (shorter than the file), an incomplete sequence at the very
/// end is the cut, not an error.
fn invalid_utf8_bytes(mut b: &[u8], truncated: bool) -> usize {
    let mut invalid = 0;
    loop {
        match std::str::from_utf8(b) {
            Ok(_) => return invalid,
            Err(e) => {
                let rest = &b[e.valid_up_to()..];
                match e.error_len() {
                    Some(n) => {
                        invalid += n;
                        b = &rest[n..];
                    }
                    None => {
                        if !truncated {
                            invalid += rest.len();
                        }
                        return invalid;
                    }
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Content language hint
// ---------------------------------------------------------------------------

fn content_language(body: &[u8]) -> Option<&'static LanguageInfo> {
    let key = if body.starts_with(b"#!") {
        let line_end = body.iter().position(|&c| c == b'\n').unwrap_or(body.len());
        shebang_key(&String::from_utf8_lossy(&body[2..line_end]))?
    } else if body.trim_ascii_start().starts_with(b"<?php") {
        "php"
    } else {
        return None;
    };
    languages().iter().find(|l| l.key == key)
}

/// Maps a shebang line (without `#!`) to a registry key: takes the
/// interpreter's basename — or, for `env`, the first non-flag argument — and
/// strips trailing version digits (`python3.12` → `python`).
fn shebang_key(line: &str) -> Option<&'static str> {
    let mut words = line.split_whitespace();
    let mut interp = words.next()?.rsplit('/').next()?;
    if interp == "env" {
        interp = words.find(|w| !w.starts_with('-'))?;
    }
    let name = interp.trim_end_matches(|c: char| c.is_ascii_digit() || c == '.');
    Some(match name {
        "python" | "pypy" => "python",
        "node" | "nodejs" | "bun" => "javascript",
        "deno" | "ts-node" | "tsx" => "typescript",
        "lua" | "luajit" => "lua",
        "php" => "php",
        "swift" => "swift",
        "kotlin" | "kotlinc" | "kscript" => "kotlin",
        "scala" => "scala",
        "java" => "java",
        "rust-script" => "rust",
        "sh" | "bash" | "dash" | "ksh" => "bash",
        _ => return None,
    })
}

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

    fn class(name: &str, bytes: &[u8]) -> FileClass {
        classify(
            Path::new(name),
            bytes,
            bytes.len() as u64,
            &ClassifyLimits::default(),
        )
    }

    fn binary_kind(name: &str, bytes: &[u8]) -> Option<BinaryKind> {
        match class(name, bytes) {
            FileClass::Binary { kind, .. } => Some(kind),
            _ => None,
        }
    }

    fn text(name: &str, bytes: &[u8]) -> SourceText {
        match class(name, bytes) {
            FileClass::SourceText(t) => t,
            other => panic!("{name}: expected SourceText, got {other:?}"),
        }
    }

    /// Deterministic pseudo-random bytes (xorshift), standing in for
    /// compressed / encrypted payloads after a header.
    fn noise(n: usize) -> Vec<u8> {
        let mut x: u32 = 0x9E37_79B9;
        (0..n)
            .map(|_| {
                x ^= x << 13;
                x ^= x >> 17;
                x ^= x << 5;
                x as u8
            })
            .collect()
    }

    fn with_header(header: &[u8]) -> Vec<u8> {
        let mut v = header.to_vec();
        v.extend(noise(4096));
        v
    }

    fn tar() -> Vec<u8> {
        let mut v = vec![0u8; 512];
        v[..10].copy_from_slice(b"hello.txt\0");
        v[257..263].copy_from_slice(b"ustar\0");
        v.extend(b"hello\n");
        v
    }

    fn pe() -> Vec<u8> {
        let mut v = vec![0u8; 0x80];
        v[..2].copy_from_slice(b"MZ");
        v[0x3C] = 0x80;
        v.extend(b"PE\0\0");
        v.extend(noise(512));
        v
    }

    #[test]
    fn every_binary_kind_renamed_to_a_source_extension() {
        let cases: Vec<(Vec<u8>, BinaryKind)> = vec![
            (with_header(b"PK\x03\x04"), BinaryKind::Archive),
            (tar(), BinaryKind::Archive),
            (with_header(b"!<arch>\n"), BinaryKind::Archive),
            (with_header(b"7z\xBC\xAF\x27\x1C"), BinaryKind::Archive),
            (with_header(b"\x1F\x8B\x08\x00"), BinaryKind::Compressed),
            (with_header(b"\xFD7zXZ\x00"), BinaryKind::Compressed),
            (with_header(b"\x28\xB5\x2F\xFD"), BinaryKind::Compressed),
            (with_header(b"BZh91AY&SY"), BinaryKind::Compressed),
            (with_header(b"\x7FELF\x02\x01\x01"), BinaryKind::Elf),
            (pe(), BinaryKind::Pe),
            (with_header(b"\xCF\xFA\xED\xFE"), BinaryKind::MachO),
            (
                with_header(b"\xCA\xFE\xBA\xBE\x00\x00\x00\x02"),
                BinaryKind::MachO,
            ),
            (with_header(b"\x89PNG\r\n\x1A\n"), BinaryKind::Image),
            (with_header(b"\xFF\xD8\xFF\xE0"), BinaryKind::Image),
            (with_header(b"GIF89a"), BinaryKind::Image),
            (with_header(b"RIFF\0\0\0\0WEBPVP8 "), BinaryKind::Image),
            (with_header(b"%PDF-1.7\n"), BinaryKind::Pdf),
            (
                with_header(b"\xCA\xFE\xBA\xBE\x00\x00\x00\x41"),
                BinaryKind::Unknown,
            ),
            (noise(8192), BinaryKind::Unknown),
        ];
        for (bytes, want) in &cases {
            for name in ["evil.c", "evil.rs", "evil.py"] {
                assert_eq!(
                    binary_kind(name, bytes),
                    Some(*want),
                    "{name} with header {:02X?}",
                    &bytes[..8]
                );
            }
        }
    }

    #[test]
    fn unidentified_noise_is_binary() {
        for name in ["evil.c", "evil.rs", "evil.py"] {
            assert!(binary_kind(name, &noise(8192)).is_some(), "{name}");
        }
        assert!(matches!(
            class("x.c", &[0x7F; 64]),
            FileClass::Binary {
                kind: BinaryKind::Unknown,
                mime: None
            }
        ));
    }

    #[test]
    fn binary_reports_mime() {
        assert!(matches!(
            class("a.c", &with_header(b"PK\x03\x04")),
            FileClass::Binary {
                mime: Some("application/zip"),
                ..
            }
        ));
    }

    /// `infer` signatures that are plausible starts of real source files
    /// must not turn text into `Binary` on their own.
    #[test]
    fn weak_or_text_signatures_on_text_stay_text() {
        let cases: &[(&str, &[u8])] = &[
            ("mz.py", b"MZ = 3\nprint(MZ)\n"),                // PE "MZ"
            ("bm.py", b"BM_SIZE = 4\n"),                      // BMP "BM"
            ("bc.c", b"BC_MAX = 1;\n"),                       // LLVM bitcode "BC"
            ("g.py", b"GIF_DIR = 'x'\n"),                     // GIF "GIF"
            ("b.py", b"BZh = 1\n"),                           // bzip2 "BZh"
            ("fws.py", b"FWS = 2\n"),                         // SWF "FWS"
            ("pdf.c", b"const char *h = \"%PDF-1.4\";\n"),    // %PDF- not at 0
            ("ps.c", b"%!\n"),                                // PostScript
            ("sh.rs", b"#!/bin/sh\necho\n"),                  // shell script
            ("page.php", b"<html><?php echo 1; ?></html>\n"), // HTML
            ("x.c", b"<?xml version=\"1.0\"?>\n"),            // XML
            ("k.c", b"-----BEGIN CERTIFICATE-----\nMII\n"),   // PEM
        ];
        for (name, src) in cases {
            assert!(class(name, src).is_source_text(), "{name}");
        }
    }

    #[test]
    fn binary_beats_oversize() {
        // The motivating case: a 2 GB zip named .c, with a 1 MiB limit.
        let limits = ClassifyLimits {
            max_size: Some(1 << 20),
            ..Default::default()
        };
        let got = classify(
            Path::new("huge.c"),
            &with_header(b"PK\x03\x04"),
            2 << 30,
            &limits,
        );
        assert!(matches!(
            got,
            FileClass::Binary {
                kind: BinaryKind::Archive,
                ..
            }
        ));
    }

    #[test]
    fn weak_magic_binary_beats_oversize() {
        // "MZ" is a weak signature, but a real PE's NULs confirm it.
        let limits = ClassifyLimits {
            max_size: Some(1 << 20),
            ..Default::default()
        };
        let got = classify(Path::new("huge.c"), &pe(), 2 << 30, &limits);
        assert!(matches!(
            got,
            FileClass::Binary {
                kind: BinaryKind::Pe,
                ..
            }
        ));
    }

    #[test]
    fn utf8_source() {
        let t = text(
            "main.rs",
            "fn main() { println!(\"héllo — ✓\"); }\n".as_bytes(),
        );
        assert_eq!(t.encoding, TextEncoding::Utf8);
        #[cfg(feature = "lang-rust")]
        assert_eq!(t.likely_language().unwrap().key, "rust");
    }

    #[test]
    fn latin1_source() {
        // "/* Grüße, café */" in ISO-8859-1.
        let src = b"/* Gr\xFC\xDFe, caf\xE9 */\nint main(void) { return 0; }\n";
        assert_eq!(text("main.c", src).encoding, TextEncoding::Latin1);
    }

    #[test]
    fn legacy_multibyte_text_is_not_binary() {
        // GBK-encoded comment: mostly invalid UTF-8, but no control bytes.
        let mut src = b"// ".to_vec();
        for _ in 0..200 {
            src.extend(b"\xD6\xD0\xCE\xC4");
        }
        src.extend(b"\nint x;\n");
        assert_eq!(text("gbk.c", &src).encoding, TextEncoding::Latin1);
    }

    #[test]
    fn boms() {
        let t = text("bom.py", b"\xEF\xBB\xBFprint('hi')\n");
        assert_eq!(t.encoding, TextEncoding::Utf8Bom);
        assert!(t.utf8_bom);
        let t = text("w.c", b"\xFF\xFEi\0n\0t\0 \0x\0;\0");
        assert_eq!(t.encoding, TextEncoding::Utf16Le);
        let t = text("w.c", b"\xFE\xFF\0i\0n\0t");
        assert_eq!(t.encoding, TextEncoding::Utf16Be);
    }

    fn utf16le(s: &str) -> Vec<u8> {
        s.encode_utf16().flat_map(u16::to_le_bytes).collect()
    }

    fn utf32(s: &str, le: bool) -> Vec<u8> {
        s.chars()
            .flat_map(|c| {
                let c = c as u32;
                if le {
                    c.to_le_bytes()
                } else {
                    c.to_be_bytes()
                }
            })
            .collect()
    }

    const SNIPPET: &str = "int main(void) { return 0; }\n";

    #[test]
    fn utf32_boms_are_not_mistaken_for_utf16() {
        // UTF-32 has no variant here; the NULs decide, so it is `Binary`.
        let le = utf32(&format!("\u{FEFF}{SNIPPET}"), true);
        assert_eq!(&le[..4], b"\xFF\xFE\0\0");
        assert_eq!(binary_kind("w.c", &le), Some(BinaryKind::Unknown));
        let be = utf32(&format!("\u{FEFF}{SNIPPET}"), false);
        assert_eq!(&be[..4], b"\0\0\xFE\xFF");
        assert_eq!(binary_kind("w.c", &be), Some(BinaryKind::Unknown));
    }

    #[test]
    fn bomless_utf16_is_a_documented_false_binary() {
        assert_eq!(
            binary_kind("w.c", &utf16le(SNIPPET)),
            Some(BinaryKind::Unknown)
        );
    }

    #[test]
    fn utf8_bom_with_invalid_bytes_keeps_the_bom_flag() {
        let t = text("bom.c", b"\xEF\xBB\xBF/* caf\xE9 */\nint x;\n");
        assert_eq!(t.encoding, TextEncoding::Latin1);
        assert!(t.utf8_bom);
        assert!(!text("plain.c", b"/* caf\xE9 */\n").utf8_bom);
    }

    #[test]
    fn stray_nul_or_control_in_a_small_file_is_text() {
        // Review case: a ~500-byte .c with one NUL used to be `Binary`.
        let mut src: Vec<u8> = b"int x;\n".iter().copied().cycle().take(500).collect();
        src[100] = 0;
        assert!(class("small.c", &src).is_source_text());
        // An 18-byte file with one raw 0x01 / 0x08.
        assert!(class("tiny.c", b"int x; /*\x01*/\n").is_source_text());
        assert!(class("tiny.c", b"int y; /*\x08*/\n").is_source_text());
        // Several of each, still under the floors.
        let mut src = b"int a;\n".repeat(4);
        src.extend([0, 0, 0, 1, 2, 3, 0x08, 0x08]);
        assert!(class("few.c", &src).is_source_text());
    }

    #[test]
    fn crlf_formfeed_esc_and_sub_are_text() {
        let src = b"int a;\r\n\x0C\r\n/* \x1B[1mbold\x1B[0m */\r\nint b;\r\n\x1A";
        assert!(class("dos.c", src).is_source_text());
    }

    #[test]
    fn large_source_at_caller_limit() {
        let line = b"int f(int x) { return x + 1; }\n";
        let src: Vec<u8> = line.iter().copied().cycle().take(64 * 1024).collect();
        let size = src.len() as u64;
        let prefix = &src[..DEFAULT_PREFIX_LEN];
        let at = ClassifyLimits {
            max_size: Some(size),
            ..Default::default()
        };
        assert!(classify(Path::new("big.c"), prefix, size, &at).is_source_text());
        let under = ClassifyLimits {
            max_size: Some(size - 1),
            ..Default::default()
        };
        assert!(matches!(
            classify(Path::new("big.c"), prefix, size, &under),
            FileClass::Oversize { size: s, limit: l } if s == size && l == size - 1
        ));
        // No limit: never Oversize.
        assert!(classify(
            Path::new("big.c"),
            prefix,
            u64::MAX,
            &ClassifyLimits::default()
        )
        .is_source_text());
    }

    #[test]
    fn empty_file() {
        assert!(matches!(class("empty.c", b""), FileClass::Empty));
    }

    #[test]
    fn truncated_prefix_mid_codepoint_is_still_utf8() {
        let src = "// ✓✓✓\n".as_bytes();
        let cut = &src[..5]; // "// " + first 2 bytes of ✓
        let got = classify(Path::new("a.c"), cut, 100, &ClassifyLimits::default());
        match got {
            FileClass::SourceText(t) => assert_eq!(t.encoding, TextEncoding::Utf8),
            other => panic!("{other:?}"),
        }
        // ...but at true EOF the same bytes are invalid.
        assert_eq!(text("a.c", cut).encoding, TextEncoding::Latin1);
    }

    #[test]
    fn single_stray_nul_in_large_source_is_text() {
        let mut src: Vec<u8> = b"int x;\n".iter().copied().cycle().take(4096).collect();
        src[100] = 0;
        assert!(class("nul.c", &src).is_source_text());
    }

    #[test]
    fn shebang_hint_and_agreement() {
        let t = text("tool", b"#!/usr/bin/env python3\nprint(1)\n");
        assert!(t.by_extension.is_none());
        #[cfg(feature = "lang-python")]
        {
            assert_eq!(t.likely_language().unwrap().key, "python");
            assert_eq!(t.extension_agrees(), None);
            let t = text("tool.py", b"#!/usr/bin/python3.12 -u\nprint(1)\n");
            assert_eq!(t.extension_agrees(), Some(true));
        }
        #[cfg(all(feature = "lang-python", feature = "lang-c"))]
        {
            // Disagreement is a hint only: still SourceText, extension wins.
            let t = text("odd.c", b"#!/usr/bin/env -S python3 -u\nprint(1)\n");
            assert_eq!(t.extension_agrees(), Some(false));
            assert_eq!(t.likely_language().unwrap().key, "c");
        }
        #[cfg(feature = "lang-php")]
        assert_eq!(
            text("page", b"\n<?php echo 1;").by_content.unwrap().key,
            "php"
        );
        #[cfg(all(feature = "lang-bash", feature = "lang-c"))]
        {
            // Same invariant for a shell shebang on a C file.
            let t = text("x.c", b"#!/bin/sh\n");
            assert_eq!(t.by_content.unwrap().key, "bash");
            assert_eq!(t.extension_agrees(), Some(false));
            assert_eq!(t.likely_language().unwrap().key, "c");
        }
        #[cfg(feature = "lang-bash")]
        for line in ["#!/bin/bash\n", "#!/usr/bin/env dash\n", "#!/bin/ksh93\n"] {
            assert_eq!(text("run", line.as_bytes()).by_content.unwrap().key, "bash");
        }
        #[cfg(not(feature = "lang-bash"))]
        assert!(text("x.c", b"#!/bin/sh\n").by_content.is_none());
    }

    #[test]
    fn classify_file_reads_bounded_prefix() {
        let dir = std::env::temp_dir().join(format!("lps-classify-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let zip = dir.join("evil.c");
        std::fs::write(&zip, with_header(b"PK\x03\x04")).unwrap();
        let src = dir.join("ok.c");
        std::fs::write(&src, b"int main(void) { return 0; }\n").unwrap();
        let empty = dir.join("empty.c");
        std::fs::write(&empty, b"").unwrap();
        let limits = ClassifyLimits {
            prefix_len: 16,
            max_size: None,
        };
        assert!(matches!(
            classify_file(&zip, &limits).unwrap(),
            FileClass::Binary {
                kind: BinaryKind::Archive,
                ..
            }
        ));
        assert!(classify_file(&src, &limits).unwrap().is_source_text());
        assert!(matches!(
            classify_file(&empty, &limits).unwrap(),
            FileClass::Empty
        ));
        assert_eq!(
            classify_file(&dir, &limits).unwrap_err().kind(),
            io::ErrorKind::InvalidInput
        );
        assert_eq!(
            classify_file(&dir.join("missing.c"), &limits)
                .unwrap_err()
                .kind(),
            io::ErrorKind::NotFound
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    fn scratch_dir(tag: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("lps-classify-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[cfg(unix)]
    #[test]
    fn classify_file_follows_symlinks() {
        let dir = scratch_dir("symlink");
        let zip = dir.join("real.zip");
        std::fs::write(&zip, with_header(b"PK\x03\x04")).unwrap();
        let link = dir.join("looks_like.c");
        std::os::unix::fs::symlink(&zip, &link).unwrap();
        assert!(matches!(
            classify_file(&link, &ClassifyLimits::default()).unwrap(),
            FileClass::Binary {
                kind: BinaryKind::Archive,
                ..
            }
        ));
        let dangling = dir.join("dangling.c");
        std::os::unix::fs::symlink(dir.join("nope"), &dangling).unwrap();
        assert_eq!(
            classify_file(&dangling, &ClassifyLimits::default())
                .unwrap_err()
                .kind(),
            io::ErrorKind::NotFound
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn classify_file_rejects_a_fifo_without_blocking() {
        let dir = scratch_dir("fifo");
        let fifo = dir.join("pipe.c");
        let ok = std::process::Command::new("mkfifo")
            .arg(&fifo)
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        if !ok {
            eprintln!("mkfifo unavailable; skipping");
            return;
        }
        // Run on a thread so a regression (open() before the type check)
        // fails the test instead of hanging the suite.
        let (tx, rx) = std::sync::mpsc::channel();
        let path = fifo.clone();
        std::thread::spawn(move || {
            let _ = tx.send(classify_file(&path, &ClassifyLimits::default()).map_err(|e| e.kind()));
        });
        let got = rx
            .recv_timeout(std::time::Duration::from_secs(5))
            .expect("classify_file blocked on a FIFO");
        assert_eq!(got.unwrap_err(), io::ErrorKind::InvalidInput);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn classify_file_reports_permission_errors() {
        use std::os::unix::fs::PermissionsExt;
        let dir = scratch_dir("perm");
        let locked = dir.join("locked.c");
        std::fs::write(&locked, b"int x;\n").unwrap();
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
        // Root (or CAP_DAC_OVERRIDE) can still open it; nothing to assert then.
        if File::open(&locked).is_err() {
            assert_eq!(
                classify_file(&locked, &ClassifyLimits::default())
                    .unwrap_err()
                    .kind(),
                io::ErrorKind::PermissionDenied
            );
        }
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644)).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// `magic()` matches on `infer`'s extension strings; an `infer` upgrade
    /// that renames or drops one would silently demote it to weak.
    #[test]
    fn strong_extensions_exist_in_infer() {
        for ext in STRONG {
            assert!(infer::is_supported(ext), "infer no longer knows {ext:?}");
        }
        for ext in [
            "exe", "dll", "mach", "pdf", "tar", "ar", "deb", "cab", "crx", "cpio", "par2", "bz2",
            "bz3", "Z", "lz", "pem", "rtf", "ps",
        ] {
            assert!(infer::is_supported(ext), "infer no longer knows {ext:?}");
        }
    }
}