Skip to main content

lang_parsing_substrate/
classify.rs

1//! Cheap, **heuristic** file-type classification, so a consumer can exit early
2//! before handing a file to tree-sitter.
3//!
4//! [`language_for_file`](crate::language_for_file) dispatches purely on the
5//! extension, so today a 2 GB zip named `foo.c` goes straight to the C parser.
6//! [`classify`] looks at a bounded prefix of the file's bytes (never the whole
7//! file) plus its size, and answers one of:
8//!
9//! - [`FileClass::Empty`] — zero-length file.
10//! - [`FileClass::Binary`] — a recognised magic number (zip, gzip, xz, zstd,
11//!   tar, ELF, PE, Mach-O, PNG, JPEG, PDF, … — the table is the [`infer`]
12//!   crate's) or a byte distribution that does not look like text (NUL bytes,
13//!   C0 control bytes, a high invalid-UTF-8 ratio).
14//! - [`FileClass::Oversize`] — looks like text, but is larger than the
15//!   caller-supplied limit.
16//! - [`FileClass::SourceText`] — looks like text, with its probable
17//!   [`TextEncoding`] and language hints.
18//!
19//! # This is a heuristic, and it is wrong both ways
20//!
21//! A text file can be called binary (e.g. a source file with a run of
22//! embedded NUL bytes, or UTF-16 without a BOM), and a binary file can be
23//! called text (e.g. a format with no magic number `infer` knows and
24//! mostly-ASCII content). Treat the result as a cheap early-exit signal, not
25//! a verdict.
26//!
27//! ## Known limitations
28//!
29//! - **Prefix only.** Only the first `prefix_len` bytes are inspected. A text
30//!   header followed by binary data later in the file (or vice versa) is
31//!   classified by the header alone.
32//! - **Calibrated on C/C++ corpora, not on every language.** The thresholds
33//!   (NUL ≥ 8 and > 0.1%; other controls ≥ 8 and > 5%; invalid UTF-8 > 30%
34//!   with ≥ 8 NUL/control bytes) were checked against ~201K files: the
35//!   aurora-lint benchmark corpora, Juliet, aurora-lint's fixtures and
36//!   other checkouts. No C-family file came back `Binary`. See
37//!   `docs/classify-calibration.md`, and re-run with
38//!   `cargo run --example classify_calibrate` on new corpora.
39//! - **Source with many raw NUL bytes is `Binary`.** e.g. fuzz-regression
40//!   tests that embed raw NULs in string literals (one Java file in the
41//!   calibration set). This can't be fixed by tuning thresholds.
42//! - **Tiny binaries can be `SourceText`.** Each signal needs at least 8
43//!   offending bytes, so a binary of a few dozen bytes may pass as text.
44//!   That costs one cheap parse; the reverse mistake would drop real source.
45//! - **BOM-less UTF-16 is `Binary`.** Every other byte is NUL.
46//! - **UTF-32 is `Binary`.** There is no UTF-32 variant. Its BOMs
47//!   (`FF FE 00 00`, `00 00 FE FF`) are deliberately not read as UTF-16, so
48//!   the NUL ratio decides.
49//! - **A UTF-16 BOM skips the byte statistics.** Any file starting with
50//!   `FF FE` or `FE FF` (and no strong magic number) is `SourceText`, even
51//!   if what follows is not text.
52//! - **`Latin1` means "not UTF-8", not "ISO-8859-1".** Windows-1252, other
53//!   ISO-8859 parts, and multi-byte legacy encodings (GBK, Shift-JIS, EUC-KR)
54//!   all report `Latin1`. EBCDIC is not recognised at all.
55//! - **Weak signatures need binary-looking bytes.** A binary format whose
56//!   `infer` signature is short and ASCII-like (`MZ`, `BM`, `GIF`, `%!`,
57//!   `ustar` at 257, `%PDF-` not at offset 0, …) and whose prefix is also
58//!   text-like (e.g. a tiny uncompressed PDF) is reported as `SourceText`.
59//! - **`infer` decides the kind and MIME by first match.** Without its `std`
60//!   feature (which this crate leaves off, to avoid the `cfb` dependency) every
61//!   OLE2 compound file — `.doc`, `.xls`, `.ppt`, `.msi` — reports as
62//!   `Document` / `"application/msword"`. Report `mime` as-is; it is not a
63//!   stable identifier and may change with `infer` upgrades.
64//! - **`Oversize` applies to text only.** A binary file is `Binary` at any
65//!   size, and an empty file is `Empty` even if the limit is 0.
66//! - **`classify_file` follows symlinks** and checks the size before reading,
67//!   so a file that grows or shrinks between the two calls is classified with
68//!   a stale size.
69//! - **Language hints are shallow.** Only `#!` interpreters and a leading
70//!   `<?php` are recognised. There is no content-based C-vs-C++ sniff for
71//!   `.h` here (see below).
72//!
73//! The substrate deliberately sets **no policy**: whether a `Binary` or
74//! `Oversize` result means "skip and report" or "try anyway" is the caller's
75//! decision, and so is the size limit ([`ClassifyLimits::max_size`] defaults
76//! to no limit).
77//!
78//! # Language hints
79//!
80//! [`FileClass::SourceText`] carries two independent hints: the language the
81//! *extension* implies (via the registry) and the language the *content*
82//! implies (a `#!` shebang line or a leading `<?php`). Disagreement between
83//! the two is reported, never acted on — a `.c` file whose first line is
84//! `#!/usr/bin/env python3` is still `SourceText`, and only the caller decides
85//! what that means. Only languages compiled into this build are ever named.
86//! For the `.h` C-vs-C++ question, use
87//! `language_for_header_content` (with `lang-c` + `lang-cpp`) instead.
88
89use std::fs::File;
90use std::io::{self, Read};
91use std::path::Path;
92
93use crate::registry::{language_info_for_file, languages, LanguageInfo};
94
95/// Suggested prefix length for [`classify_file`]: 8 KiB, the same window git
96/// uses for its binary-file check. Callers may pass any length; longer
97/// prefixes make the byte-distribution ratios more reliable.
98pub const DEFAULT_PREFIX_LEN: usize = 8 * 1024;
99
100/// What [`classify`] thinks a file is. See the [module docs](self) for why
101/// this is only a hint.
102#[derive(Debug, Clone, Copy)]
103#[non_exhaustive]
104pub enum FileClass {
105    /// The file is zero bytes long.
106    Empty,
107    /// The file looks like text but exceeds the caller's size limit.
108    /// Binary files are reported as [`FileClass::Binary`] regardless of size.
109    Oversize {
110        /// The file's size in bytes.
111        size: u64,
112        /// The caller-supplied limit it exceeded.
113        limit: u64,
114    },
115    /// The file does not look like text.
116    Binary {
117        /// The kind of binary; [`BinaryKind::Unknown`] if no magic number
118        /// identified it.
119        kind: BinaryKind,
120        /// MIME type from the magic-number match (e.g. `"application/zip"`),
121        /// for reporting; `None` when only the byte distribution decided.
122        mime: Option<&'static str>,
123    },
124    /// The file looks like text.
125    SourceText(SourceText),
126}
127
128impl FileClass {
129    /// `true` for [`FileClass::SourceText`] — the only class worth parsing
130    /// under the most conservative policy.
131    pub fn is_source_text(&self) -> bool {
132        matches!(self, FileClass::SourceText(_))
133    }
134}
135
136/// The kind of a [`FileClass::Binary`] file.
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
138#[non_exhaustive]
139pub enum BinaryKind {
140    /// Multi-file archive: zip (incl. jar/apk), tar, 7z, rar, `ar` (static
141    /// libraries), deb, rpm, cab, cpio.
142    Archive,
143    /// Single-stream compressed data: gzip, xz, zstd, bzip2, lz4, lzip, `.Z`.
144    Compressed,
145    /// ELF executable, shared object, or object file.
146    Elf,
147    /// Windows PE/COFF (`MZ` … `PE\0\0`) executable or DLL.
148    Pe,
149    /// Mach-O executable (thin or fat/universal).
150    MachO,
151    /// Image: PNG, JPEG, GIF, WebP, TIFF, BMP, ICO, PSD, …
152    Image,
153    /// PDF document.
154    Pdf,
155    /// Office / e-book document: doc/xls/ppt, docx/xlsx/pptx, odt/ods/odp,
156    /// epub, mobi.
157    Document,
158    /// Audio or video.
159    Media,
160    /// Font file: woff, woff2, ttf, otf.
161    Font,
162    /// Some other recognised binary (wasm, Java class, sqlite, …), or no
163    /// magic number matched but the byte distribution is not text-like.
164    Unknown,
165}
166
167/// The probable encoding of a [`FileClass::SourceText`] file.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
169#[non_exhaustive]
170pub enum TextEncoding {
171    /// Valid UTF-8 (which includes pure ASCII), no BOM.
172    Utf8,
173    /// Valid UTF-8 after a leading `EF BB BF` byte-order mark.
174    Utf8Bom,
175    /// UTF-16 little-endian, identified by its `FF FE` BOM. (BOM-less UTF-16
176    /// is indistinguishable from binary here and classifies as `Binary`.)
177    Utf16Le,
178    /// UTF-16 big-endian, identified by its `FE FF` BOM.
179    Utf16Be,
180    /// Not valid UTF-8, but text-like: some legacy 8-bit encoding. Decoding
181    /// as Latin-1 (ISO-8859-1) is lossless, though the true encoding may be
182    /// Windows-1252, another ISO-8859 part, or a multi-byte legacy encoding.
183    Latin1,
184}
185
186/// Details of a [`FileClass::SourceText`] result.
187#[derive(Debug, Clone, Copy)]
188pub struct SourceText {
189    /// Probable encoding of the bytes.
190    pub encoding: TextEncoding,
191    /// `true` when the file starts with a UTF-8 BOM. Usually implied by
192    /// [`TextEncoding::Utf8Bom`], but also set when the bytes after the BOM
193    /// are not valid UTF-8 and `encoding` is therefore `Latin1`.
194    pub utf8_bom: bool,
195    /// The language the file's extension maps to, if any (registry lookup).
196    pub by_extension: Option<&'static LanguageInfo>,
197    /// The language the file's content suggests (shebang / `<?php`), if any.
198    pub by_content: Option<&'static LanguageInfo>,
199}
200
201impl SourceText {
202    /// Best single guess: the extension's language, else the content's.
203    pub fn likely_language(&self) -> Option<&'static LanguageInfo> {
204        self.by_extension.or(self.by_content)
205    }
206
207    /// `Some(true)` / `Some(false)` when both hints exist and agree /
208    /// disagree; `None` when either is missing. A hint only — never a gate.
209    pub fn extension_agrees(&self) -> Option<bool> {
210        Some(self.by_extension?.key == self.by_content?.key)
211    }
212}
213
214/// Caller policy for [`classify`] / [`classify_file`].
215#[derive(Debug, Clone, Copy)]
216pub struct ClassifyLimits {
217    /// How many leading bytes [`classify_file`] reads. Ignored by
218    /// [`classify`], which takes whatever prefix it is given.
219    pub prefix_len: usize,
220    /// Text files larger than this many bytes are reported as
221    /// [`FileClass::Oversize`]. `None` (the default) means no limit.
222    pub max_size: Option<u64>,
223}
224
225impl Default for ClassifyLimits {
226    fn default() -> Self {
227        Self {
228            prefix_len: DEFAULT_PREFIX_LEN,
229            max_size: None,
230        }
231    }
232}
233
234/// Classifies a file from its path, a bounded prefix of its bytes, and its
235/// total size. **Heuristic** — see the [module docs](self).
236///
237/// `prefix` must be the file's first bytes (any length; [`DEFAULT_PREFIX_LEN`]
238/// is a reasonable choice) and `file_size` its full length in bytes. `path` is
239/// used only for the extension hint — no I/O happens here.
240///
241/// Order of checks: zero size → `Empty`; strong magic number → `Binary`;
242/// byte distribution (NUL ratio, control-byte ratio, invalid-UTF-8 ratio)
243/// not text-like → `Binary` (kind from a weak magic hit, else `Unknown`);
244/// size above `limits.max_size` → `Oversize`; otherwise `SourceText`. A
245/// UTF-16 BOM skips the byte-distribution check. Binary always wins over
246/// `Oversize`, so a huge archive is reported as an archive.
247///
248/// Magic numbers come from the [`infer`] crate's table. Its text-format
249/// matchers (HTML, XML, `#!`, PEM, RTF, PostScript) are ignored, and its
250/// short ASCII-looking signatures are only trusted alongside binary-looking
251/// bytes, since e.g. a source file can legitimately start with `MZ` or `BM`.
252pub fn classify(path: &Path, prefix: &[u8], file_size: u64, limits: &ClassifyLimits) -> FileClass {
253    if file_size == 0 {
254        return FileClass::Empty;
255    }
256    let magic = magic(prefix);
257    if let Some(m) = magic.as_ref().filter(|m| m.strong) {
258        return binary(m.kind, Some(m.mime));
259    }
260
261    let (encoding, body) = split_bom(prefix);
262    let stats = ByteStats::of(body, (prefix.len() as u64) < file_size);
263    if stats.looks_binary() {
264        return match magic {
265            Some(m) => binary(m.kind, Some(m.mime)),
266            None => binary(BinaryKind::Unknown, None),
267        };
268    }
269    if let Some(limit) = limits.max_size {
270        if file_size > limit {
271            return FileClass::Oversize {
272                size: file_size,
273                limit,
274            };
275        }
276    }
277    // A UTF-8 BOM followed by invalid UTF-8 is still reported as `Latin1`
278    // (the bytes after the BOM are what a decoder has to handle); the BOM
279    // itself is reported separately so it isn't lost.
280    let had_utf8_bom = encoding == TextEncoding::Utf8Bom;
281    let encoding = if stats.invalid_utf8 == 0 {
282        encoding
283    } else {
284        TextEncoding::Latin1
285    };
286    FileClass::SourceText(SourceText {
287        encoding,
288        utf8_bom: had_utf8_bom,
289        by_extension: language_info_for_file(path),
290        by_content: content_language(body),
291    })
292}
293
294fn binary(kind: BinaryKind, mime: Option<&'static str>) -> FileClass {
295    FileClass::Binary { kind, mime }
296}
297
298/// Splits a leading BOM off `prefix`. A UTF-16 BOM yields an empty body: the
299/// byte statistics are meaningless for UTF-16, so they are skipped.
300fn split_bom(prefix: &[u8]) -> (TextEncoding, &[u8]) {
301    if let Some(rest) = prefix.strip_prefix(b"\xEF\xBB\xBF") {
302        (TextEncoding::Utf8Bom, rest)
303    } else if prefix.starts_with(b"\xFF\xFE") && !prefix.starts_with(b"\xFF\xFE\0\0") {
304        // `FF FE 00 00` is the UTF-32 LE BOM, not UTF-16 LE + U+0000; it
305        // falls through to the byte statistics (see "Known limitations").
306        (TextEncoding::Utf16Le, &[])
307    } else if prefix.starts_with(b"\xFE\xFF") {
308        (TextEncoding::Utf16Be, &[])
309    } else {
310        (TextEncoding::Utf8, prefix)
311    }
312}
313
314/// The raw byte counts behind [`classify`]'s text-vs-binary decision for one
315/// prefix: `(len, nul, control, invalid_utf8)`, after BOM handling.
316///
317/// Not part of the stable API — it exists so `examples/classify_calibrate.rs`
318/// can report the ratios a corpus actually produces.
319#[doc(hidden)]
320pub fn __byte_counts(prefix: &[u8], file_size: u64) -> (usize, usize, usize, usize) {
321    let (_, body) = split_bom(prefix);
322    let s = ByteStats::of(body, (prefix.len() as u64) < file_size);
323    (s.len, s.nul, s.control, s.invalid_utf8)
324}
325
326/// Reads `path`'s metadata and at most `limits.prefix_len` leading bytes,
327/// then calls [`classify`]. Never reads past the prefix.
328///
329/// Returns an `InvalidInput` error for anything that is not a regular file
330/// (directories, FIFOs, sockets, devices), since opening or reading those can
331/// block or never end. Symlinks are followed. The file type is checked with
332/// `std::fs::metadata` *before* opening, because opening a FIFO blocks until a
333/// writer appears. A path swapped for a FIFO between that check and the open
334/// can still block; that race is not defended against.
335pub fn classify_file(path: &Path, limits: &ClassifyLimits) -> io::Result<FileClass> {
336    let meta = std::fs::metadata(path)?;
337    if !meta.is_file() {
338        return Err(io::Error::new(
339            io::ErrorKind::InvalidInput,
340            format!("{} is not a regular file", path.display()),
341        ));
342    }
343    let file = File::open(path)?;
344    let mut prefix = Vec::with_capacity(limits.prefix_len.min(meta.len() as usize));
345    file.take(limits.prefix_len as u64)
346        .read_to_end(&mut prefix)?;
347    Ok(classify(path, &prefix, meta.len(), limits))
348}
349
350// ---------------------------------------------------------------------------
351// Magic numbers (via `infer`)
352// ---------------------------------------------------------------------------
353
354/// A magic-number hit from `infer`.
355struct Magic {
356    kind: BinaryKind,
357    mime: &'static str,
358    /// `true` when the bytes `infer` checks for this type include at least
359    /// one NUL, C0 control, or invalid-UTF-8 byte — so no text file can
360    /// match — and the hit is trusted outright. (e.g. woff/woff2 start with
361    /// ASCII `wOFF`/`wOF2`, but `infer` also requires `00 01 00 00` after.)
362    /// Weak hits — `infer` matches `MZ`, `BM`, `GIF`, `BZh`, `ustar` at 257,
363    /// `%PDF-` anywhere in the first KiB, … — only count when the byte
364    /// distribution independently looks binary.
365    strong: bool,
366}
367
368/// `infer` extensions whose signatures are strong (see [`Magic::strong`]).
369/// Without `infer`'s `std` feature every OLE2 file reports as `"doc"`, so
370/// `xls` / `ppt` / `msi` can never be returned and are not listed.
371const STRONG: &[&str] = &[
372    "zip", "docx", "xlsx", "pptx", "odt", "ods", "odp", "epub", "ora", "gz", "xz", "zst", "lz4",
373    "7z", "rar", "rpm", "doc", "elf", "mach", "class", "wasm", "png", "jpg", "woff", "woff2",
374    "mkv", "webm",
375];
376
377fn magic(prefix: &[u8]) -> Option<Magic> {
378    let t = infer::get(prefix)?;
379    let ext = t.extension();
380    let kind = match (t.matcher_type(), ext) {
381        // Text formats `infer` also recognises (html, xml, `#!` scripts, PEM,
382        // RTF, PostScript): not binary — let the byte statistics decide.
383        (infer::MatcherType::Text, _) | (_, "pem" | "rtf" | "ps") => return None,
384        (_, "elf") => BinaryKind::Elf,
385        (_, "exe" | "dll") => BinaryKind::Pe,
386        (_, "mach") => BinaryKind::MachO,
387        (_, "pdf") => BinaryKind::Pdf,
388        (_, "gz" | "bz2" | "bz3" | "xz" | "zst" | "lz4" | "Z" | "lz") => BinaryKind::Compressed,
389        (
390            _,
391            "zip" | "tar" | "rar" | "7z" | "ar" | "deb" | "rpm" | "cab" | "crx" | "cpio" | "par2",
392        ) => BinaryKind::Archive,
393        (infer::MatcherType::Image, _) => BinaryKind::Image,
394        (infer::MatcherType::Doc | infer::MatcherType::Book, _) => BinaryKind::Document,
395        (infer::MatcherType::Audio | infer::MatcherType::Video, _) => BinaryKind::Media,
396        (infer::MatcherType::Font, _) => BinaryKind::Font,
397        _ => BinaryKind::Unknown,
398    };
399    // `infer` accepts `%PDF-` anywhere in the first KiB; only offset 0 is strong.
400    let strong = STRONG.contains(&ext) || (ext == "pdf" && prefix.starts_with(b"%PDF-"));
401    Some(Magic {
402        kind,
403        mime: t.mime_type(),
404        strong,
405    })
406}
407
408// ---------------------------------------------------------------------------
409// Byte distribution
410// ---------------------------------------------------------------------------
411
412/// Minimum NUL count before the NUL ratio can make a prefix `Binary`.
413const NUL_FLOOR: usize = 8;
414/// Minimum C0-control count before the control ratio can make a prefix
415/// `Binary`.
416const CONTROL_FLOOR: usize = 8;
417
418struct ByteStats {
419    len: usize,
420    nul: usize,
421    /// C0 controls other than \t \n \v \f \r, ESC and SUB (DOS EOF), plus DEL.
422    control: usize,
423    invalid_utf8: usize,
424}
425
426impl ByteStats {
427    fn of(b: &[u8], truncated: bool) -> Self {
428        let mut nul = 0;
429        let mut control = 0;
430        for &c in b {
431            match c {
432                0 => nul += 1,
433                b'\t' | b'\n' | 0x0B | 0x0C | b'\r' | 0x1A | 0x1B => {}
434                0x01..=0x1F | 0x7F => control += 1,
435                _ => {}
436            }
437        }
438        Self {
439            len: b.len(),
440            nul,
441            control,
442            invalid_utf8: invalid_utf8_bytes(b, truncated),
443        }
444    }
445
446    /// Each signal needs both an absolute floor and a ratio, so a handful
447    /// of stray bytes in a small source file never makes it `Binary` (a
448    /// false `Binary` silently drops real source, the worst outcome for a
449    /// consumer):
450    /// - NUL: at least [`NUL_FLOOR`] and more than 0.1% of the prefix.
451    /// - other control bytes: at least [`CONTROL_FLOOR`] and more than 5%.
452    /// - invalid UTF-8 above 30%, together with at least [`NUL_FLOOR`]
453    ///   NUL-or-control bytes — legacy multi-byte text (GBK, Shift-JIS) can
454    ///   be mostly invalid UTF-8 but has no control bytes.
455    ///
456    /// The cost is that a binary file too small to reach the floors is
457    /// reported as text, which only means a cheap parse of a tiny file.
458    fn looks_binary(&self) -> bool {
459        let len = self.len;
460        (self.nul >= NUL_FLOOR && self.nul * 1000 > len)
461            || (self.control >= CONTROL_FLOOR && self.control * 100 > len * 5)
462            || (self.invalid_utf8 * 100 > len * 30 && self.nul + self.control >= NUL_FLOOR)
463    }
464}
465
466/// Counts bytes that are not part of a valid UTF-8 sequence. When the prefix
467/// is `truncated` (shorter than the file), an incomplete sequence at the very
468/// end is the cut, not an error.
469fn invalid_utf8_bytes(mut b: &[u8], truncated: bool) -> usize {
470    let mut invalid = 0;
471    loop {
472        match std::str::from_utf8(b) {
473            Ok(_) => return invalid,
474            Err(e) => {
475                let rest = &b[e.valid_up_to()..];
476                match e.error_len() {
477                    Some(n) => {
478                        invalid += n;
479                        b = &rest[n..];
480                    }
481                    None => {
482                        if !truncated {
483                            invalid += rest.len();
484                        }
485                        return invalid;
486                    }
487                }
488            }
489        }
490    }
491}
492
493// ---------------------------------------------------------------------------
494// Content language hint
495// ---------------------------------------------------------------------------
496
497fn content_language(body: &[u8]) -> Option<&'static LanguageInfo> {
498    let key = if body.starts_with(b"#!") {
499        let line_end = body.iter().position(|&c| c == b'\n').unwrap_or(body.len());
500        shebang_key(&String::from_utf8_lossy(&body[2..line_end]))?
501    } else if body.trim_ascii_start().starts_with(b"<?php") {
502        "php"
503    } else {
504        return None;
505    };
506    languages().iter().find(|l| l.key == key)
507}
508
509/// Maps a shebang line (without `#!`) to a registry key: takes the
510/// interpreter's basename — or, for `env`, the first non-flag argument — and
511/// strips trailing version digits (`python3.12` → `python`).
512fn shebang_key(line: &str) -> Option<&'static str> {
513    let mut words = line.split_whitespace();
514    let mut interp = words.next()?.rsplit('/').next()?;
515    if interp == "env" {
516        interp = words.find(|w| !w.starts_with('-'))?;
517    }
518    let name = interp.trim_end_matches(|c: char| c.is_ascii_digit() || c == '.');
519    Some(match name {
520        "python" | "pypy" => "python",
521        "node" | "nodejs" | "bun" => "javascript",
522        "deno" | "ts-node" | "tsx" => "typescript",
523        "lua" | "luajit" => "lua",
524        "php" => "php",
525        "swift" => "swift",
526        "kotlin" | "kotlinc" | "kscript" => "kotlin",
527        "scala" => "scala",
528        "java" => "java",
529        "rust-script" => "rust",
530        "sh" | "bash" | "dash" | "ksh" => "bash",
531        _ => return None,
532    })
533}
534
535#[cfg(test)]
536mod tests {
537    use super::*;
538
539    fn class(name: &str, bytes: &[u8]) -> FileClass {
540        classify(
541            Path::new(name),
542            bytes,
543            bytes.len() as u64,
544            &ClassifyLimits::default(),
545        )
546    }
547
548    fn binary_kind(name: &str, bytes: &[u8]) -> Option<BinaryKind> {
549        match class(name, bytes) {
550            FileClass::Binary { kind, .. } => Some(kind),
551            _ => None,
552        }
553    }
554
555    fn text(name: &str, bytes: &[u8]) -> SourceText {
556        match class(name, bytes) {
557            FileClass::SourceText(t) => t,
558            other => panic!("{name}: expected SourceText, got {other:?}"),
559        }
560    }
561
562    /// Deterministic pseudo-random bytes (xorshift), standing in for
563    /// compressed / encrypted payloads after a header.
564    fn noise(n: usize) -> Vec<u8> {
565        let mut x: u32 = 0x9E37_79B9;
566        (0..n)
567            .map(|_| {
568                x ^= x << 13;
569                x ^= x >> 17;
570                x ^= x << 5;
571                x as u8
572            })
573            .collect()
574    }
575
576    fn with_header(header: &[u8]) -> Vec<u8> {
577        let mut v = header.to_vec();
578        v.extend(noise(4096));
579        v
580    }
581
582    fn tar() -> Vec<u8> {
583        let mut v = vec![0u8; 512];
584        v[..10].copy_from_slice(b"hello.txt\0");
585        v[257..263].copy_from_slice(b"ustar\0");
586        v.extend(b"hello\n");
587        v
588    }
589
590    fn pe() -> Vec<u8> {
591        let mut v = vec![0u8; 0x80];
592        v[..2].copy_from_slice(b"MZ");
593        v[0x3C] = 0x80;
594        v.extend(b"PE\0\0");
595        v.extend(noise(512));
596        v
597    }
598
599    #[test]
600    fn every_binary_kind_renamed_to_a_source_extension() {
601        let cases: Vec<(Vec<u8>, BinaryKind)> = vec![
602            (with_header(b"PK\x03\x04"), BinaryKind::Archive),
603            (tar(), BinaryKind::Archive),
604            (with_header(b"!<arch>\n"), BinaryKind::Archive),
605            (with_header(b"7z\xBC\xAF\x27\x1C"), BinaryKind::Archive),
606            (with_header(b"\x1F\x8B\x08\x00"), BinaryKind::Compressed),
607            (with_header(b"\xFD7zXZ\x00"), BinaryKind::Compressed),
608            (with_header(b"\x28\xB5\x2F\xFD"), BinaryKind::Compressed),
609            (with_header(b"BZh91AY&SY"), BinaryKind::Compressed),
610            (with_header(b"\x7FELF\x02\x01\x01"), BinaryKind::Elf),
611            (pe(), BinaryKind::Pe),
612            (with_header(b"\xCF\xFA\xED\xFE"), BinaryKind::MachO),
613            (
614                with_header(b"\xCA\xFE\xBA\xBE\x00\x00\x00\x02"),
615                BinaryKind::MachO,
616            ),
617            (with_header(b"\x89PNG\r\n\x1A\n"), BinaryKind::Image),
618            (with_header(b"\xFF\xD8\xFF\xE0"), BinaryKind::Image),
619            (with_header(b"GIF89a"), BinaryKind::Image),
620            (with_header(b"RIFF\0\0\0\0WEBPVP8 "), BinaryKind::Image),
621            (with_header(b"%PDF-1.7\n"), BinaryKind::Pdf),
622            (
623                with_header(b"\xCA\xFE\xBA\xBE\x00\x00\x00\x41"),
624                BinaryKind::Unknown,
625            ),
626            (noise(8192), BinaryKind::Unknown),
627        ];
628        for (bytes, want) in &cases {
629            for name in ["evil.c", "evil.rs", "evil.py"] {
630                assert_eq!(
631                    binary_kind(name, bytes),
632                    Some(*want),
633                    "{name} with header {:02X?}",
634                    &bytes[..8]
635                );
636            }
637        }
638    }
639
640    #[test]
641    fn unidentified_noise_is_binary() {
642        for name in ["evil.c", "evil.rs", "evil.py"] {
643            assert!(binary_kind(name, &noise(8192)).is_some(), "{name}");
644        }
645        assert!(matches!(
646            class("x.c", &[0x7F; 64]),
647            FileClass::Binary {
648                kind: BinaryKind::Unknown,
649                mime: None
650            }
651        ));
652    }
653
654    #[test]
655    fn binary_reports_mime() {
656        assert!(matches!(
657            class("a.c", &with_header(b"PK\x03\x04")),
658            FileClass::Binary {
659                mime: Some("application/zip"),
660                ..
661            }
662        ));
663    }
664
665    /// `infer` signatures that are plausible starts of real source files
666    /// must not turn text into `Binary` on their own.
667    #[test]
668    fn weak_or_text_signatures_on_text_stay_text() {
669        let cases: &[(&str, &[u8])] = &[
670            ("mz.py", b"MZ = 3\nprint(MZ)\n"),                // PE "MZ"
671            ("bm.py", b"BM_SIZE = 4\n"),                      // BMP "BM"
672            ("bc.c", b"BC_MAX = 1;\n"),                       // LLVM bitcode "BC"
673            ("g.py", b"GIF_DIR = 'x'\n"),                     // GIF "GIF"
674            ("b.py", b"BZh = 1\n"),                           // bzip2 "BZh"
675            ("fws.py", b"FWS = 2\n"),                         // SWF "FWS"
676            ("pdf.c", b"const char *h = \"%PDF-1.4\";\n"),    // %PDF- not at 0
677            ("ps.c", b"%!\n"),                                // PostScript
678            ("sh.rs", b"#!/bin/sh\necho\n"),                  // shell script
679            ("page.php", b"<html><?php echo 1; ?></html>\n"), // HTML
680            ("x.c", b"<?xml version=\"1.0\"?>\n"),            // XML
681            ("k.c", b"-----BEGIN CERTIFICATE-----\nMII\n"),   // PEM
682        ];
683        for (name, src) in cases {
684            assert!(class(name, src).is_source_text(), "{name}");
685        }
686    }
687
688    #[test]
689    fn binary_beats_oversize() {
690        // The motivating case: a 2 GB zip named .c, with a 1 MiB limit.
691        let limits = ClassifyLimits {
692            max_size: Some(1 << 20),
693            ..Default::default()
694        };
695        let got = classify(
696            Path::new("huge.c"),
697            &with_header(b"PK\x03\x04"),
698            2 << 30,
699            &limits,
700        );
701        assert!(matches!(
702            got,
703            FileClass::Binary {
704                kind: BinaryKind::Archive,
705                ..
706            }
707        ));
708    }
709
710    #[test]
711    fn weak_magic_binary_beats_oversize() {
712        // "MZ" is a weak signature, but a real PE's NULs confirm it.
713        let limits = ClassifyLimits {
714            max_size: Some(1 << 20),
715            ..Default::default()
716        };
717        let got = classify(Path::new("huge.c"), &pe(), 2 << 30, &limits);
718        assert!(matches!(
719            got,
720            FileClass::Binary {
721                kind: BinaryKind::Pe,
722                ..
723            }
724        ));
725    }
726
727    #[test]
728    fn utf8_source() {
729        let t = text(
730            "main.rs",
731            "fn main() { println!(\"héllo — ✓\"); }\n".as_bytes(),
732        );
733        assert_eq!(t.encoding, TextEncoding::Utf8);
734        #[cfg(feature = "lang-rust")]
735        assert_eq!(t.likely_language().unwrap().key, "rust");
736    }
737
738    #[test]
739    fn latin1_source() {
740        // "/* Grüße, café */" in ISO-8859-1.
741        let src = b"/* Gr\xFC\xDFe, caf\xE9 */\nint main(void) { return 0; }\n";
742        assert_eq!(text("main.c", src).encoding, TextEncoding::Latin1);
743    }
744
745    #[test]
746    fn legacy_multibyte_text_is_not_binary() {
747        // GBK-encoded comment: mostly invalid UTF-8, but no control bytes.
748        let mut src = b"// ".to_vec();
749        for _ in 0..200 {
750            src.extend(b"\xD6\xD0\xCE\xC4");
751        }
752        src.extend(b"\nint x;\n");
753        assert_eq!(text("gbk.c", &src).encoding, TextEncoding::Latin1);
754    }
755
756    #[test]
757    fn boms() {
758        let t = text("bom.py", b"\xEF\xBB\xBFprint('hi')\n");
759        assert_eq!(t.encoding, TextEncoding::Utf8Bom);
760        assert!(t.utf8_bom);
761        let t = text("w.c", b"\xFF\xFEi\0n\0t\0 \0x\0;\0");
762        assert_eq!(t.encoding, TextEncoding::Utf16Le);
763        let t = text("w.c", b"\xFE\xFF\0i\0n\0t");
764        assert_eq!(t.encoding, TextEncoding::Utf16Be);
765    }
766
767    fn utf16le(s: &str) -> Vec<u8> {
768        s.encode_utf16().flat_map(u16::to_le_bytes).collect()
769    }
770
771    fn utf32(s: &str, le: bool) -> Vec<u8> {
772        s.chars()
773            .flat_map(|c| {
774                let c = c as u32;
775                if le {
776                    c.to_le_bytes()
777                } else {
778                    c.to_be_bytes()
779                }
780            })
781            .collect()
782    }
783
784    const SNIPPET: &str = "int main(void) { return 0; }\n";
785
786    #[test]
787    fn utf32_boms_are_not_mistaken_for_utf16() {
788        // UTF-32 has no variant here; the NULs decide, so it is `Binary`.
789        let le = utf32(&format!("\u{FEFF}{SNIPPET}"), true);
790        assert_eq!(&le[..4], b"\xFF\xFE\0\0");
791        assert_eq!(binary_kind("w.c", &le), Some(BinaryKind::Unknown));
792        let be = utf32(&format!("\u{FEFF}{SNIPPET}"), false);
793        assert_eq!(&be[..4], b"\0\0\xFE\xFF");
794        assert_eq!(binary_kind("w.c", &be), Some(BinaryKind::Unknown));
795    }
796
797    #[test]
798    fn bomless_utf16_is_a_documented_false_binary() {
799        assert_eq!(
800            binary_kind("w.c", &utf16le(SNIPPET)),
801            Some(BinaryKind::Unknown)
802        );
803    }
804
805    #[test]
806    fn utf8_bom_with_invalid_bytes_keeps_the_bom_flag() {
807        let t = text("bom.c", b"\xEF\xBB\xBF/* caf\xE9 */\nint x;\n");
808        assert_eq!(t.encoding, TextEncoding::Latin1);
809        assert!(t.utf8_bom);
810        assert!(!text("plain.c", b"/* caf\xE9 */\n").utf8_bom);
811    }
812
813    #[test]
814    fn stray_nul_or_control_in_a_small_file_is_text() {
815        // Review case: a ~500-byte .c with one NUL used to be `Binary`.
816        let mut src: Vec<u8> = b"int x;\n".iter().copied().cycle().take(500).collect();
817        src[100] = 0;
818        assert!(class("small.c", &src).is_source_text());
819        // An 18-byte file with one raw 0x01 / 0x08.
820        assert!(class("tiny.c", b"int x; /*\x01*/\n").is_source_text());
821        assert!(class("tiny.c", b"int y; /*\x08*/\n").is_source_text());
822        // Several of each, still under the floors.
823        let mut src = b"int a;\n".repeat(4);
824        src.extend([0, 0, 0, 1, 2, 3, 0x08, 0x08]);
825        assert!(class("few.c", &src).is_source_text());
826    }
827
828    #[test]
829    fn crlf_formfeed_esc_and_sub_are_text() {
830        let src = b"int a;\r\n\x0C\r\n/* \x1B[1mbold\x1B[0m */\r\nint b;\r\n\x1A";
831        assert!(class("dos.c", src).is_source_text());
832    }
833
834    #[test]
835    fn large_source_at_caller_limit() {
836        let line = b"int f(int x) { return x + 1; }\n";
837        let src: Vec<u8> = line.iter().copied().cycle().take(64 * 1024).collect();
838        let size = src.len() as u64;
839        let prefix = &src[..DEFAULT_PREFIX_LEN];
840        let at = ClassifyLimits {
841            max_size: Some(size),
842            ..Default::default()
843        };
844        assert!(classify(Path::new("big.c"), prefix, size, &at).is_source_text());
845        let under = ClassifyLimits {
846            max_size: Some(size - 1),
847            ..Default::default()
848        };
849        assert!(matches!(
850            classify(Path::new("big.c"), prefix, size, &under),
851            FileClass::Oversize { size: s, limit: l } if s == size && l == size - 1
852        ));
853        // No limit: never Oversize.
854        assert!(classify(
855            Path::new("big.c"),
856            prefix,
857            u64::MAX,
858            &ClassifyLimits::default()
859        )
860        .is_source_text());
861    }
862
863    #[test]
864    fn empty_file() {
865        assert!(matches!(class("empty.c", b""), FileClass::Empty));
866    }
867
868    #[test]
869    fn truncated_prefix_mid_codepoint_is_still_utf8() {
870        let src = "// ✓✓✓\n".as_bytes();
871        let cut = &src[..5]; // "// " + first 2 bytes of ✓
872        let got = classify(Path::new("a.c"), cut, 100, &ClassifyLimits::default());
873        match got {
874            FileClass::SourceText(t) => assert_eq!(t.encoding, TextEncoding::Utf8),
875            other => panic!("{other:?}"),
876        }
877        // ...but at true EOF the same bytes are invalid.
878        assert_eq!(text("a.c", cut).encoding, TextEncoding::Latin1);
879    }
880
881    #[test]
882    fn single_stray_nul_in_large_source_is_text() {
883        let mut src: Vec<u8> = b"int x;\n".iter().copied().cycle().take(4096).collect();
884        src[100] = 0;
885        assert!(class("nul.c", &src).is_source_text());
886    }
887
888    #[test]
889    fn shebang_hint_and_agreement() {
890        let t = text("tool", b"#!/usr/bin/env python3\nprint(1)\n");
891        assert!(t.by_extension.is_none());
892        #[cfg(feature = "lang-python")]
893        {
894            assert_eq!(t.likely_language().unwrap().key, "python");
895            assert_eq!(t.extension_agrees(), None);
896            let t = text("tool.py", b"#!/usr/bin/python3.12 -u\nprint(1)\n");
897            assert_eq!(t.extension_agrees(), Some(true));
898        }
899        #[cfg(all(feature = "lang-python", feature = "lang-c"))]
900        {
901            // Disagreement is a hint only: still SourceText, extension wins.
902            let t = text("odd.c", b"#!/usr/bin/env -S python3 -u\nprint(1)\n");
903            assert_eq!(t.extension_agrees(), Some(false));
904            assert_eq!(t.likely_language().unwrap().key, "c");
905        }
906        #[cfg(feature = "lang-php")]
907        assert_eq!(
908            text("page", b"\n<?php echo 1;").by_content.unwrap().key,
909            "php"
910        );
911        #[cfg(all(feature = "lang-bash", feature = "lang-c"))]
912        {
913            // Same invariant for a shell shebang on a C file.
914            let t = text("x.c", b"#!/bin/sh\n");
915            assert_eq!(t.by_content.unwrap().key, "bash");
916            assert_eq!(t.extension_agrees(), Some(false));
917            assert_eq!(t.likely_language().unwrap().key, "c");
918        }
919        #[cfg(feature = "lang-bash")]
920        for line in ["#!/bin/bash\n", "#!/usr/bin/env dash\n", "#!/bin/ksh93\n"] {
921            assert_eq!(text("run", line.as_bytes()).by_content.unwrap().key, "bash");
922        }
923        #[cfg(not(feature = "lang-bash"))]
924        assert!(text("x.c", b"#!/bin/sh\n").by_content.is_none());
925    }
926
927    #[test]
928    fn classify_file_reads_bounded_prefix() {
929        let dir = std::env::temp_dir().join(format!("lps-classify-{}", std::process::id()));
930        std::fs::create_dir_all(&dir).unwrap();
931        let zip = dir.join("evil.c");
932        std::fs::write(&zip, with_header(b"PK\x03\x04")).unwrap();
933        let src = dir.join("ok.c");
934        std::fs::write(&src, b"int main(void) { return 0; }\n").unwrap();
935        let empty = dir.join("empty.c");
936        std::fs::write(&empty, b"").unwrap();
937        let limits = ClassifyLimits {
938            prefix_len: 16,
939            max_size: None,
940        };
941        assert!(matches!(
942            classify_file(&zip, &limits).unwrap(),
943            FileClass::Binary {
944                kind: BinaryKind::Archive,
945                ..
946            }
947        ));
948        assert!(classify_file(&src, &limits).unwrap().is_source_text());
949        assert!(matches!(
950            classify_file(&empty, &limits).unwrap(),
951            FileClass::Empty
952        ));
953        assert_eq!(
954            classify_file(&dir, &limits).unwrap_err().kind(),
955            io::ErrorKind::InvalidInput
956        );
957        assert_eq!(
958            classify_file(&dir.join("missing.c"), &limits)
959                .unwrap_err()
960                .kind(),
961            io::ErrorKind::NotFound
962        );
963        std::fs::remove_dir_all(&dir).unwrap();
964    }
965
966    fn scratch_dir(tag: &str) -> std::path::PathBuf {
967        let dir = std::env::temp_dir().join(format!("lps-classify-{tag}-{}", std::process::id()));
968        let _ = std::fs::remove_dir_all(&dir);
969        std::fs::create_dir_all(&dir).unwrap();
970        dir
971    }
972
973    #[cfg(unix)]
974    #[test]
975    fn classify_file_follows_symlinks() {
976        let dir = scratch_dir("symlink");
977        let zip = dir.join("real.zip");
978        std::fs::write(&zip, with_header(b"PK\x03\x04")).unwrap();
979        let link = dir.join("looks_like.c");
980        std::os::unix::fs::symlink(&zip, &link).unwrap();
981        assert!(matches!(
982            classify_file(&link, &ClassifyLimits::default()).unwrap(),
983            FileClass::Binary {
984                kind: BinaryKind::Archive,
985                ..
986            }
987        ));
988        let dangling = dir.join("dangling.c");
989        std::os::unix::fs::symlink(dir.join("nope"), &dangling).unwrap();
990        assert_eq!(
991            classify_file(&dangling, &ClassifyLimits::default())
992                .unwrap_err()
993                .kind(),
994            io::ErrorKind::NotFound
995        );
996        std::fs::remove_dir_all(&dir).unwrap();
997    }
998
999    #[cfg(unix)]
1000    #[test]
1001    fn classify_file_rejects_a_fifo_without_blocking() {
1002        let dir = scratch_dir("fifo");
1003        let fifo = dir.join("pipe.c");
1004        let ok = std::process::Command::new("mkfifo")
1005            .arg(&fifo)
1006            .status()
1007            .map(|s| s.success())
1008            .unwrap_or(false);
1009        if !ok {
1010            eprintln!("mkfifo unavailable; skipping");
1011            return;
1012        }
1013        // Run on a thread so a regression (open() before the type check)
1014        // fails the test instead of hanging the suite.
1015        let (tx, rx) = std::sync::mpsc::channel();
1016        let path = fifo.clone();
1017        std::thread::spawn(move || {
1018            let _ = tx.send(classify_file(&path, &ClassifyLimits::default()).map_err(|e| e.kind()));
1019        });
1020        let got = rx
1021            .recv_timeout(std::time::Duration::from_secs(5))
1022            .expect("classify_file blocked on a FIFO");
1023        assert_eq!(got.unwrap_err(), io::ErrorKind::InvalidInput);
1024        std::fs::remove_dir_all(&dir).unwrap();
1025    }
1026
1027    #[cfg(unix)]
1028    #[test]
1029    fn classify_file_reports_permission_errors() {
1030        use std::os::unix::fs::PermissionsExt;
1031        let dir = scratch_dir("perm");
1032        let locked = dir.join("locked.c");
1033        std::fs::write(&locked, b"int x;\n").unwrap();
1034        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
1035        // Root (or CAP_DAC_OVERRIDE) can still open it; nothing to assert then.
1036        if File::open(&locked).is_err() {
1037            assert_eq!(
1038                classify_file(&locked, &ClassifyLimits::default())
1039                    .unwrap_err()
1040                    .kind(),
1041                io::ErrorKind::PermissionDenied
1042            );
1043        }
1044        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644)).unwrap();
1045        std::fs::remove_dir_all(&dir).unwrap();
1046    }
1047
1048    /// `magic()` matches on `infer`'s extension strings; an `infer` upgrade
1049    /// that renames or drops one would silently demote it to weak.
1050    #[test]
1051    fn strong_extensions_exist_in_infer() {
1052        for ext in STRONG {
1053            assert!(infer::is_supported(ext), "infer no longer knows {ext:?}");
1054        }
1055        for ext in [
1056            "exe", "dll", "mach", "pdf", "tar", "ar", "deb", "cab", "crx", "cpio", "par2", "bz2",
1057            "bz3", "Z", "lz", "pem", "rtf", "ps",
1058        ] {
1059            assert!(infer::is_supported(ext), "infer no longer knows {ext:?}");
1060        }
1061    }
1062}