Skip to main content

big_code_analysis_ast/
tools.rs

1// Per-language metric and AST modules deliberately consume the macro-
2// generated tree-sitter token enums via `use crate::*` and `use Foo::*`
3// inside match expressions — explicit imports would list dozens of
4// variants per arm and obscure the per-language token sets that are the
5// point of these files. Allowed at the module level rather than per
6// function so the per-language impl blocks stay readable.
7#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
8// Metric counts (token, function, branch, argument, etc.) are stored as
9// `usize` and crossed with `f64` averages, ratios, and Halstead scores
10// across the cyclomatic / MI / Halstead computations. The `usize as f64`
11// and `f64 as usize` casts are intentional and snapshot-anchored — every
12// site is bounded by the count it came from. Allowing the lints at the
13// module level keeps the metric arithmetic legible.
14#![allow(
15    clippy::cast_precision_loss,
16    clippy::cast_possible_truncation,
17    clippy::cast_sign_loss
18)]
19
20//! Language detection and the file readers.
21
22use std::borrow::Cow;
23use std::cmp::Ordering;
24use std::collections::HashMap;
25use std::fs::{self, File};
26use std::io::{Read, Write};
27use std::path::{Component, Path, PathBuf};
28use std::sync::OnceLock;
29
30use regex::bytes::Regex;
31
32use crate::langs::*;
33
34/// Reads a file, normalising all CR-only and CRLF line endings to LF.
35///
36/// **Note for downstream consumers**: the returned buffer never contains `\r`
37/// bytes. Callers that previously observed raw `\r\n` sequences will see plain
38/// `\n` after this call. This is intentional — the metric engine requires LF-
39/// only input — but it is a behavioural difference from a plain `fs::read`.
40///
41/// # Errors
42///
43/// Returns any [`std::io::Error`] surfaced by [`File::open`] (the
44/// path is missing, lacks read permission, is a directory, …) or by
45/// [`File::read_to_end`] while reading the file contents.
46///
47/// # Examples
48///
49/// ```
50/// use std::path::Path;
51///
52/// use big_code_analysis_ast::read_file;
53///
54/// let path = Path::new("Cargo.toml");
55/// read_file(&path).unwrap();
56/// ```
57pub fn read_file(path: &Path) -> std::io::Result<Vec<u8>> {
58    let mut file = File::open(path)?;
59    let mut data = Vec::new();
60    file.read_to_end(&mut data)?;
61
62    normalize_line_endings(&mut data);
63
64    Ok(data)
65}
66
67/// Bytes from the start of the file probed to decide whether the contents
68/// look like UTF-8 before the whole file is read. A small fixed window keeps
69/// the rejection of obviously-binary files cheap; the last character of the
70/// window may be a multibyte sequence split by this boundary, which the
71/// classifier tolerates only when more file follows (see `read_file_with_eol`).
72const UTF8_PROBE_BYTES: usize = 64;
73
74/// Decides whether a file's probe prefix is decodable UTF-8 and where its
75/// real content starts. Returns the post-BOM content slice when the probe
76/// is acceptable, or the [`SkipReason`] that rejects the file.
77///
78/// A UTF-16 BE/LE BOM marks a file whose body is interleaved-NUL UTF-16,
79/// which the metric engine cannot parse: stripping the BOM and continuing
80/// would let the ASCII-dominant body pass the UTF-8 probe (each NUL is a
81/// valid single-byte UTF-8 scalar) and reach the parser as garbage (issue
82/// #803). Skip such files, mirroring `is_generated`'s documented stance
83/// that UTF-16 source is unsupported. A UTF-8 BOM, by contrast, prefixes
84/// genuine UTF-8 and is stripped so the body parses normally.
85/// `starts_with` is bounds-safe for a probe shorter than the BOM.
86///
87/// Validation is at the byte level rather than via a lossy string
88/// round-trip. The probe is only the first `UTF8_PROBE_BYTES`, so a file
89/// longer than the probe may legitimately have its last multibyte
90/// character split across the window boundary. `String::from_utf8_lossy`
91/// could not distinguish that benign truncation (issue #746) from a real
92/// encoding error, and its replacement character `U+FFFD` collided with
93/// the same scalar appearing legitimately in the source (issue #758).
94/// `probe_truncated` is true only when the file continues past the probe;
95/// when the probe is the whole file there is no more data to complete a
96/// trailing partial sequence, so such a sequence is genuine corruption.
97fn probe_decodable_prefix(
98    start: &[u8],
99    file_size: usize,
100    probe_len: usize,
101) -> Result<&[u8], SkipReason> {
102    let start = if start.starts_with(b"\xFE\xFF") || start.starts_with(b"\xFF\xFE") {
103        return Err(SkipReason::Utf16Bom);
104    } else if let Some(rest) = start.strip_prefix(b"\xEF\xBB\xBF") {
105        rest
106    } else {
107        start
108    };
109
110    let probe_truncated = file_size > probe_len;
111    match std::str::from_utf8(start) {
112        Ok(_) => {}
113        // Only a trailing incomplete multibyte sequence: the bytes before
114        // `valid_up_to()` are valid UTF-8 and the truncated tail is
115        // completed by data later in the file.
116        Err(e) if e.error_len().is_none() && probe_truncated => {}
117        Err(_) => return Err(SkipReason::NotUtf8),
118    }
119    Ok(start)
120}
121
122/// Why [`read_file_with_eol_classified`] declined to hand a file's bytes to
123/// the metric engine.
124///
125/// [`read_file_with_eol`] collapses every one of these into `Ok(None)`, which
126/// left front-ends unable to name the real cause — `bca` reported a
127/// multi-kilobyte binary and a one-byte source alike as "empty" (#1287). This
128/// enum is the classified form of that same decision; the variants map 1:1 onto
129/// the skip branches of [`read_file_with_eol_classified`].
130///
131/// Marked `#[non_exhaustive]`: a future gate (a size ceiling, a further
132/// encoding) adds a variant additively, so match on it with a wildcard arm or
133/// render it through [`Display`](std::fmt::Display).
134#[non_exhaustive]
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
136pub enum SkipReason {
137    /// The file is zero bytes long.
138    Empty,
139    /// The file holds 1–3 bytes — too little to be worth parsing — or it
140    /// shrank below the UTF-8 probe window between the `stat` and the read.
141    TooSmall,
142    /// The file opens with a UTF-16 BE or LE byte-order mark. Its
143    /// interleaved-NUL body would pass a byte-level UTF-8 check and reach the
144    /// parser as garbage, so it is skipped rather than decoded (#803).
145    Utf16Bom,
146    /// The file's leading window is not valid UTF-8 — the shape a binary file
147    /// takes here.
148    NotUtf8,
149}
150
151impl SkipReason {
152    /// Which small-file reason applies to a file of `size` bytes: zero bytes
153    /// is [`Empty`](Self::Empty), anything else under the gate is
154    /// [`TooSmall`](Self::TooSmall).
155    fn for_size(size: usize) -> Self {
156        if size == 0 {
157            Self::Empty
158        } else {
159            Self::TooSmall
160        }
161    }
162}
163
164impl std::fmt::Display for SkipReason {
165    /// Renders the reason as a noun phrase naming the skipped file, so a
166    /// caller can splice it into a diagnostic: `skipping {reason}: {path}`.
167    ///
168    /// Per the project diagnostic convention the phrase carries no severity
169    /// word — the presenting layer owns that prefix.
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        let phrase = match self {
172            Self::Empty => "empty file",
173            Self::TooSmall => "file too small to analyze (3 bytes or fewer)",
174            Self::Utf16Bom => "UTF-16 file (unsupported encoding)",
175            Self::NotUtf8 => "file with non-UTF-8 contents",
176        };
177        f.write_str(phrase)
178    }
179}
180
181/// Reads a file, normalising all CR-only and CRLF line endings to LF, and ensures
182/// the buffer ends with exactly one `\n`. Returns `None` for readable files
183/// ≤ 3 bytes or files that appear to be non-UTF-8.
184///
185/// `None` names no reason. Use [`read_file_with_eol_classified`] — of which
186/// this function is a thin projection — when the caller reports the skip to a
187/// user, so an empty file, a one-byte source, a binary blob and a UTF-16 file
188/// are not all announced as "empty" (#1287).
189///
190/// # Errors
191///
192/// Returns any [`std::io::Error`] surfaced by [`File::open`] (the
193/// path is missing, lacks read permission, is a directory, …) or by
194/// the subsequent reads from the open file handle. A clean short read
195/// during the probe (`UnexpectedEof`) yields `Ok(None)`; any other
196/// `read_exact` error kind propagates as `Err`. A non-UTF-8 head, a
197/// too-small file, or a UTF-16 BE/LE BOM is reported via `Ok(None)`,
198/// not an error — but "too small" is decided only for a file that can
199/// be opened, so an unreadable one errors instead (#1060).
200///
201/// # Examples
202///
203/// ```
204/// use std::path::Path;
205///
206/// use big_code_analysis_ast::read_file_with_eol;
207///
208/// let path = Path::new("Cargo.toml");
209/// read_file_with_eol(&path).unwrap();
210/// ```
211pub fn read_file_with_eol(path: &Path) -> std::io::Result<Option<Vec<u8>>> {
212    read_file_with_eol_classified(path).map(Result::ok)
213}
214
215/// Reads a file exactly as [`read_file_with_eol`] does, but names the reason
216/// when the file is skipped instead of collapsing every skip into `None`.
217///
218/// The outer `Result` is the I/O outcome; the inner one is the analysis
219/// outcome — `Ok(bytes)` for a file the metric engine can parse, or
220/// `Err(`[`SkipReason`]`)` for one it declines. [`read_file_with_eol`] is
221/// `read_file_with_eol_classified(path).map(Result::ok)`, so the two agree
222/// branch for branch.
223///
224/// # Errors
225///
226/// Identical to [`read_file_with_eol`]: any [`std::io::Error`] from
227/// [`File::open`] or the subsequent reads propagates. Skips are *not* errors —
228/// they arrive as `Ok(Err(reason))`.
229///
230/// # Examples
231///
232/// ```
233/// use std::path::Path;
234///
235/// use big_code_analysis_ast::{SkipReason, read_file_with_eol_classified};
236///
237/// let dir = tempfile::tempdir().unwrap();
238/// let path = dir.path().join("tiny.rs");
239/// std::fs::write(&path, b"x").unwrap();
240///
241/// assert_eq!(
242///     read_file_with_eol_classified(&path).unwrap(),
243///     Err(SkipReason::TooSmall)
244/// );
245/// ```
246pub fn read_file_with_eol_classified(path: &Path) -> std::io::Result<Result<Vec<u8>, SkipReason>> {
247    match read_gated(path) {
248        Ok(data) => Ok(Ok(data)),
249        Err(ReadStop::Skip(reason)) => Ok(Err(reason)),
250        Err(ReadStop::Io(err)) => Err(err),
251    }
252}
253
254/// The two ways [`read_gated`] stops short of returning bytes. Collapsing
255/// them into one `Err` is what lets that function spell every gate as `?`
256/// instead of hand-wrapping each early return in the public
257/// `Ok(Err(reason))` / `Err(err)` shape; the split back out happens once, in
258/// [`read_file_with_eol_classified`].
259enum ReadStop {
260    /// A genuine I/O failure, propagated to the caller as `Err`.
261    Io(std::io::Error),
262    /// The file was read far enough to decide the metric engine should not
263    /// see it. Not an error (issue #804).
264    Skip(SkipReason),
265}
266
267impl From<std::io::Error> for ReadStop {
268    fn from(err: std::io::Error) -> Self {
269        Self::Io(err)
270    }
271}
272
273impl From<SkipReason> for ReadStop {
274    fn from(reason: SkipReason) -> Self {
275        Self::Skip(reason)
276    }
277}
278
279/// Applies the pre-parse gates in order — size, readability, UTF-8 probe —
280/// and returns the EOL-normalised contents of a file that clears them all.
281fn read_gated(path: &Path) -> Result<Vec<u8>, ReadStop> {
282    let meta = fs::metadata(path);
283    let file_size = meta.as_ref().map_or(1024 * 1024, |m| m.len() as usize);
284    if file_size <= 3 {
285        // Nothing worth parsing this small — but `stat` alone must not
286        // decide it: `stat` succeeds on a file the process cannot open,
287        // so an unreadable tiny file read as empty and `bca check`
288        // exited 0 on a tree it never read (#1060). `meta` is
289        // necessarily `Ok` here; the open is a discarded readability
290        // probe, skipped for non-regular files because a FIFO blocks.
291        if meta.is_ok_and(|m| m.is_file()) {
292            File::open(path)?;
293        }
294        return Err(SkipReason::for_size(file_size).into());
295    }
296
297    let mut file = File::open(path)?;
298
299    let probe_len = UTF8_PROBE_BYTES.min(file_size);
300    let mut start = vec![0; probe_len];
301    // A clean short read (the file shrank below the probe between the
302    // `metadata` call and here) is reported as a skip, matching the
303    // too-small-file case. Any other `read_exact` failure — a real I/O
304    // fault such as a permission or hardware error — must propagate as
305    // `Err` per the documented contract (issue #804); collapsing every
306    // error to a skip would silently swallow genuine read failures.
307    match file.read_exact(&mut start) {
308        Ok(()) => {}
309        Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
310            return Err(SkipReason::TooSmall.into());
311        }
312        Err(e) => return Err(e.into()),
313    }
314
315    // Sniff the probe: reject UTF-16 / corrupt files, strip a UTF-8 BOM,
316    // and anchor the buffer at the post-BOM content. An `Err` names why
317    // the file is skipped (see `probe_decodable_prefix`).
318    let start = probe_decodable_prefix(&start, file_size, probe_len)?;
319
320    let mut data = Vec::with_capacity(file_size + 2);
321    data.extend_from_slice(start);
322
323    file.read_to_end(&mut data)?;
324
325    normalize_line_endings(&mut data);
326
327    Ok(data)
328}
329
330/// Normalises an in-memory source buffer to match the [`read_file_with_eol`]
331/// on-disk path: all CR-only and CRLF line endings become LF, and the buffer is
332/// guaranteed to end with exactly one `\n`.
333///
334/// In-memory entry points (the web server's JSON/octet-stream payloads, the
335/// Python `analyze_source` bindings) feed caller-supplied bytes straight to the
336/// parser, whereas the CLI reads files through [`read_file_with_eol`]. Without
337/// this step, identical content yields different metrics across surfaces — an
338/// editor buffer with no trailing newline reports `sloc: 0` over the wire but
339/// `sloc: 1` from the CLI on the same bytes (issue #640). Run the buffer through
340/// this helper before parsing so every surface computes the canonical numbers.
341///
342/// Returns a fresh owned buffer; the input is consumed so the common case
343/// (already-owned request body) reuses its allocation.
344///
345/// # Examples
346///
347/// ```
348/// use big_code_analysis_ast::normalize_eol;
349///
350/// // CRLF endings collapse to LF and a missing final newline is added.
351/// assert_eq!(normalize_eol(b"a\r\nb".to_vec()), b"a\nb\n");
352/// ```
353#[must_use]
354pub fn normalize_eol(mut data: Vec<u8>) -> Vec<u8> {
355    normalize_line_endings(&mut data);
356    data
357}
358
359/// Writes data to a file.
360///
361/// # Errors
362///
363/// Returns any [`std::io::Error`] surfaced by [`File::create`]
364/// (parent directory missing, lacks write permission, target is a
365/// directory, …) or by [`File::write_all`] while writing the buffer.
366///
367/// # Examples
368///
369/// ```no_run
370/// use std::path::Path;
371///
372/// use big_code_analysis_ast::write_file;
373///
374/// let path = Path::new("foo.txt");
375/// let data: [u8; 4] = [0; 4];
376/// write_file(&path, &data).unwrap();
377/// ```
378pub fn write_file(path: &Path, data: &[u8]) -> std::io::Result<()> {
379    let mut file = File::create(path)?;
380    file.write_all(data)?;
381
382    Ok(())
383}
384
385/// Detects the language of a code using
386/// the extension of a file.
387///
388/// # Examples
389///
390/// ```
391/// use std::path::Path;
392///
393/// use big_code_analysis_ast::get_language_for_file;
394///
395/// let path = Path::new("build.rs");
396/// get_language_for_file(&path).unwrap();
397/// ```
398#[must_use]
399pub fn get_language_for_file(path: &Path) -> Option<LANG> {
400    let ext = path.extension()?.to_str()?;
401    get_from_ext(&lowercase_ext(ext))
402}
403
404/// Borrows `ext` when it is already the ASCII-lowercase spelling
405/// [`get_from_ext`]'s table is keyed on, allocating only for the
406/// mixed-case minority (`foo.C`, `foo.PY`).
407///
408/// The `is_ascii` guard is load-bearing: [`str::to_lowercase`] folds
409/// `U+212A KELVIN SIGN` onto ASCII `k`, so a non-ASCII extension must
410/// keep that Unicode-aware path to leave the lookup key as it was before
411/// #1111. Past the guard the input is ASCII, hence the cheaper fold.
412fn lowercase_ext(ext: &str) -> Cow<'_, str> {
413    if !ext.is_ascii() {
414        Cow::Owned(ext.to_lowercase())
415    } else if ext.bytes().any(|b| b.is_ascii_uppercase()) {
416        Cow::Owned(ext.to_ascii_lowercase())
417    } else {
418        Cow::Borrowed(ext)
419    }
420}
421
422fn mode_to_str(mode: &[u8]) -> Option<String> {
423    std::str::from_utf8(mode).ok().map(str::to_lowercase)
424}
425
426// comment containing coding info are useful
427static RE1_EMACS: OnceLock<Regex> = OnceLock::new();
428static RE2_EMACS: OnceLock<Regex> = OnceLock::new();
429static RE1_VIM: OnceLock<Regex> = OnceLock::new();
430static RE_GENERATED: OnceLock<Regex> = OnceLock::new();
431
432// Regular expressions
433const FIRST_EMACS_EXPRESSION: &str = r"(?i)-\*-.*[^-\w]mode\s*:\s*([^:;\s]+)";
434const SECOND_EMACS_EXPRESSION: &str = r"-\*-\s*([^:;\s]+)\s*-\*-";
435const VIM_EXPRESSION: &str = r"(?i)vim\s*:.*[^\w]ft\s*=\s*([^:\s]+)";
436
437// Generated-code marker patterns. Matched against the leading window of the
438// file (see `is_generated`) so a marker phrase deep in the body does not
439// trigger a skip. Each alternative covers a widely-used convention:
440//
441// - `@generated`      — Facebook / Meta convention, also used by buck2,
442//                       rustfmt, prettier, and many code generators.
443// - `DO NOT EDIT`     — Go's `Code generated ... DO NOT EDIT.` line is
444//                       canonical, but the bare phrase appears in Bazel,
445//                       protoc, OpenAPI clients, etc. — match either.
446// - `GENERATED CODE`  — Lizard's marker; preserved for compatibility with
447//                       projects that already tag generated files this way.
448const GENERATED_EXPRESSION: &str = r"(?i)@generated\b|DO NOT EDIT|GENERATED CODE";
449
450/// Bytes from the start of the file scanned for a generated-code marker.
451/// 5 KiB is enough to cover any reasonable file header (license + autogen
452/// preamble) without paying a meaningful read cost.
453const GENERATED_SCAN_BYTES: usize = 5 * 1024;
454/// Maximum lines scanned for a generated-code marker. Caps the work on a
455/// pathological "all-on-one-line" file.
456const GENERATED_SCAN_LINES: usize = 50;
457
458/// Returns `true` when `buf` looks like generated code: its leading window
459/// (first ~50 lines or first 5 KiB, whichever is smaller) contains a known
460/// marker phrase. Matching is case-insensitive for the marker and never
461/// allocates on the negative path.
462///
463/// Recognized markers:
464///
465/// - `@generated` — Facebook / Meta convention, also used by buck2,
466///   rustfmt, and prettier.
467/// - `DO NOT EDIT` — Go's `Code generated by ... DO NOT EDIT.` is the
468///   canonical form; the bare phrase is also widely copied.
469/// - `GENERATED CODE` — Lizard's marker, preserved for compatibility.
470///
471/// Detection runs against raw bytes before parsing, so callers can discard
472/// generated files without paying tree-sitter parse cost. Non-UTF-8 input
473/// will not panic — `regex::bytes::Regex` operates on the raw byte slice.
474///
475/// # Examples
476///
477/// ```
478/// use big_code_analysis_ast::is_generated;
479///
480/// assert!(is_generated(b"// @generated\nfn x() {}\n"));
481/// assert!(is_generated(
482///     b"// Code generated by protoc. DO NOT EDIT.\npackage x\n",
483/// ));
484/// assert!(!is_generated(b"fn main() { /* not generated */ }\n"));
485/// ```
486///
487/// # Panics
488///
489/// Panics if the embedded marker regex set fails to build; the marker
490/// list is a static literal so this represents a compile-time bug, not
491/// a runtime input that can be handled.
492pub fn is_generated(buf: &[u8]) -> bool {
493    // Strip a leading UTF-8 BOM so a marker on the first line of a
494    // BOM-prefixed file still matches against the line start. UTF-16 BOMs
495    // are not handled: the byte-pattern regex cannot match the
496    // interleaved-zero encoding (`@\x00g\x00...`) that follows a UTF-16
497    // BOM, so a strip would not enable detection — it would only obscure
498    // the fact that UTF-16 source files are unsupported here.
499    let buf = buf.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(buf);
500
501    // Bound the search window: at most GENERATED_SCAN_BYTES bytes, and
502    // among those, stop after GENERATED_SCAN_LINES newlines. Scanning fewer
503    // lines avoids matching a marker phrase deep in the file body (the
504    // negative case in the issue's acceptance criteria).
505    let cap = buf.len().min(GENERATED_SCAN_BYTES);
506    let end = buf[..cap]
507        .iter()
508        .enumerate()
509        .filter_map(|(i, &b)| (b == b'\n').then_some(i + 1))
510        .nth(GENERATED_SCAN_LINES - 1)
511        .unwrap_or(cap);
512    let window = &buf[..end];
513
514    RE_GENERATED
515        .get_or_init(|| {
516            Regex::new(GENERATED_EXPRESSION).expect("GENERATED_EXPRESSION is a constant regex")
517        })
518        .is_match(window)
519}
520
521#[inline]
522fn get_regex<'a>(
523    once_lock: &OnceLock<Regex>,
524    line: &'a [u8],
525    regex: &'a str,
526) -> Option<regex::bytes::Captures<'a>> {
527    once_lock
528        .get_or_init(|| Regex::new(regex).expect("constant regex pattern must compile"))
529        .captures(line)
530}
531
532/// Resolves a language from a script's shebang line.
533///
534/// Returns `None` unless `buf` starts with `#!`. Reads up to the first `\n`,
535/// strips an optional trailing `\r`, splits on whitespace, and takes the
536/// basename of either the first token or — when that basename is `env` — the
537/// next non-flag token. Trailing version digits and dots (`python3`,
538/// `lua5.1`, `perl5.36`) are stripped before lookup. Non-UTF-8 bytes on the
539/// shebang line yield `None` (no panic).
540fn get_shebang_lang(buf: &[u8]) -> Option<LANG> {
541    // Early-out for the common case (any non-shebang buffer): no allocation,
542    // no UTF-8 decoding.
543    let rest = buf.strip_prefix(b"#!")?;
544    let line_end = rest.iter().position(|&b| b == b'\n').unwrap_or(rest.len());
545    let line = &rest[..line_end];
546    // Trim a trailing CR even though normalize_line_endings should have removed
547    // it — guess_language is on the public API and may be called with raw input.
548    let line = line.strip_suffix(b"\r").unwrap_or(line);
549    let line = std::str::from_utf8(line).ok()?;
550
551    let mut tokens = line.split_ascii_whitespace();
552    let first_base = basename(tokens.next()?);
553
554    let interpreter = if first_base == "env" {
555        skip_env_args(&mut tokens)?
556    } else {
557        first_base
558    };
559
560    get_from_interpreter(strip_version_suffix(interpreter))
561}
562
563// Walk past leading `env` arguments (`-FLAG`, `-u VAR`, `NAME=value`) and
564// return the basename of the actual interpreter token. Per `env(1)`, only
565// `-u` consumes a following argument; other short flags (`-i`, `-S`, …)
566// stand alone or carry their argument inline (e.g. `-S "node --foo"`).
567fn skip_env_args<'a>(tokens: &mut std::str::SplitAsciiWhitespace<'a>) -> Option<&'a str> {
568    loop {
569        let tok = tokens.next()?;
570        if let Some(flag) = tok.strip_prefix('-') {
571            if flag == "u" {
572                tokens.next()?;
573            }
574            continue;
575        }
576        if tok.contains('=') {
577            continue;
578        }
579        return Some(basename(tok));
580    }
581}
582
583fn basename(path: &str) -> &str {
584    path.rsplit_once('/').map_or(path, |(_, name)| name)
585}
586
587/// Strips a trailing run of digits and dots used to encode an interpreter
588/// version (`python3` → `python`, `lua5.1` → `lua`, `perl5.36` → `perl`).
589fn strip_version_suffix(name: &str) -> &str {
590    let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit() || c == '.');
591    if trimmed.is_empty() { name } else { trimmed }
592}
593
594fn get_from_interpreter(name: &str) -> Option<LANG> {
595    match name {
596        "sh" | "bash" | "dash" | "ksh" | "zsh" => Some(LANG::Bash),
597        "python" => Some(LANG::Python),
598        "perl" => Some(LANG::Perl),
599        "lua" | "luajit" => Some(LANG::Lua),
600        "php" | "php-cgi" => Some(LANG::Php),
601        "node" | "nodejs" => Some(LANG::Javascript),
602        "tclsh" | "wish" => Some(LANG::Tcl),
603        "ruby" => Some(LANG::Ruby),
604        "elixir" | "iex" => Some(LANG::Elixir),
605        _ => None,
606    }
607}
608
609// Editors place mode/file-local-variable lines near the very top or
610// very bottom of a file. Emacs honours the first non-shebang line and a
611// trailing "Local Variables:" block; Vim honours modelines in the first
612// or last few lines (`modelines` defaults to 5). Scanning this many real
613// lines at each end covers both conventions without trawling the body.
614const MODE_LINE_SCAN_WINDOW: usize = 5;
615
616// Entries into `get_emacs_mode` — the only thing able to observe #1111's
617// laziness: every assertion on what `guess_language` returns holds just as
618// well when the scan runs eagerly and throws the result away. Read by the
619// test that pins it, which carries why.
620crate::observation::counter!(modeline_scans);
621
622fn get_emacs_mode(buf: &[u8]) -> Option<String> {
623    modeline_scans::record();
624    // Forward scan: the first `MODE_LINE_SCAN_WINDOW` real lines may carry
625    // an emacs `-*- … -*-` header or a Vim modeline. `split` yields one
626    // element per line (no unbounded remainder), and `take` bounds the
627    // window precisely — the former `splitn(5)` + `i == 3` break inspected
628    // only 4 lines yet split off a 5th unbounded remainder (issue #709).
629    for line in buf.split(|c| *c == b'\n').take(MODE_LINE_SCAN_WINDOW) {
630        if let Some(cap) = get_regex(&RE1_EMACS, line, FIRST_EMACS_EXPRESSION) {
631            return mode_to_str(&cap[1]);
632        } else if let Some(cap) = get_regex(&RE2_EMACS, line, SECOND_EMACS_EXPRESSION) {
633            return mode_to_str(&cap[1]);
634        } else if let Some(cap) = get_regex(&RE1_VIM, line, VIM_EXPRESSION) {
635            return mode_to_str(&cap[1]);
636        }
637    }
638
639    // Backward scan for a trailing Vim modeline. Skip empty pieces so a
640    // trailing newline (the common case after `read_file_with_eol`) and
641    // any trailing blank lines do not consume the window before a real
642    // modeline is reached — the former `rsplitn(5)` spent its first slot
643    // on that empty piece, covering fewer than the intended real lines.
644    for line in buf
645        .rsplit(|c| *c == b'\n')
646        .filter(|line| !line.is_empty())
647        .take(MODE_LINE_SCAN_WINDOW)
648    {
649        if let Some(cap) = get_regex(&RE1_VIM, line, VIM_EXPRESSION) {
650            return mode_to_str(&cap[1]);
651        }
652    }
653
654    None
655}
656
657/// Guesses the language of a code.
658///
659/// Returns a tuple containing a [`LANG`] as first argument
660/// and the language name as a second one.
661///
662/// # Examples
663///
664/// ```
665/// use std::path::PathBuf;
666///
667/// use big_code_analysis_ast::guess_language;
668///
669/// let source_code = "int a = 42;";
670///
671/// // The path to a dummy file used to contain the source code
672/// let path = PathBuf::from("foo.c");
673/// let source_slice = source_code.as_bytes();
674///
675/// // Guess the language of a code
676/// guess_language(&source_slice, &path);
677/// ```
678///
679/// [`LANG`]: enum.LANG.html
680pub fn guess_language<P: AsRef<Path>>(buf: &[u8], path: P) -> (Option<LANG>, &'static str) {
681    // Precedence: extension, then emacs/vim modeline, then shebang. The
682    // fallbacks are lazy, so a recognised extension never pays for the
683    // modeline scan; the previous form ran it for every file and
684    // discarded it, every arm of its extension branch having returned the
685    // extension's language — the "modeline agrees" arm included (#1111).
686    let lang = get_language_for_file(path.as_ref())
687        .or_else(|| get_emacs_mode(buf).and_then(|mode| get_from_emacs_mode(&mode)))
688        .or_else(|| get_shebang_lang(buf));
689
690    lang.map_or((None, ""), |lang| (Some(lang), lang.name()))
691}
692
693/// Normalises all CR-only and CRLF line endings to LF throughout the buffer,
694/// then ensures the buffer ends with exactly one `\n`.
695pub fn normalize_line_endings(data: &mut Vec<u8>) {
696    // In-place compaction: write pointer stays ≤ read pointer, so no extra allocation.
697    let mut w = 0;
698    let mut r = 0;
699    while r < data.len() {
700        if data[r] == b'\r' {
701            data[w] = b'\n';
702            w += 1;
703            r += if data.get(r + 1).copied() == Some(b'\n') {
704                2
705            } else {
706                1
707            };
708        } else {
709            data[w] = data[r];
710            w += 1;
711            r += 1;
712        }
713    }
714    data.truncate(w);
715    let trailing = data.iter().rev().take_while(|&&c| c == b'\n').count();
716    data.truncate(data.len() - trailing);
717    data.push(b'\n');
718}
719
720pub(crate) fn normalize_path<P: AsRef<Path>>(path: P) -> PathBuf {
721    // Copied from Cargo sources: https://github.com/rust-lang/cargo/blob/master/src/cargo/util/paths.rs#L65
722    let mut components = path.as_ref().components().peekable();
723    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().copied() {
724        components.next();
725        PathBuf::from(c.as_os_str())
726    } else {
727        PathBuf::new()
728    };
729
730    for component in components {
731        match component {
732            // A `Prefix` (Windows drive / UNC) component only ever
733            // appears first; the leading peek+next above already
734            // consumed it, so it cannot recur in this loop.
735            Component::Prefix(..) => unreachable!(),
736            Component::RootDir => {
737                ret.push(component.as_os_str());
738            }
739            Component::CurDir => {}
740            Component::ParentDir => {
741                ret.pop();
742            }
743            Component::Normal(c) => {
744                ret.push(c);
745            }
746        }
747    }
748    ret
749}
750
751pub(crate) fn get_paths_dist(path1: &Path, path2: &Path) -> Option<usize> {
752    for ancestor in path1.ancestors() {
753        if path2.starts_with(ancestor) && !ancestor.as_os_str().is_empty() {
754            // `ancestor` is yielded by `path1.ancestors()`, so it is
755            // a prefix of `path1` by construction; `path2` was just
756            // verified by `starts_with` above. Both `strip_prefix`
757            // calls are therefore infallible.
758            let path1 = path1
759                .strip_prefix(ancestor)
760                .expect("ancestor is by construction a prefix of path1");
761            let path2 = path2
762                .strip_prefix(ancestor)
763                .expect("ancestor verified by starts_with above");
764            return Some(path1.components().count() + path2.components().count());
765        }
766    }
767    None
768}
769
770pub(crate) fn guess_file<S: ::std::hash::BuildHasher>(
771    current_path: &Path,
772    include_path: &str,
773    all_files: &HashMap<String, Vec<PathBuf>, S>,
774) -> Vec<PathBuf> {
775    let include_path = include_path
776        .strip_prefix("mozilla/")
777        .unwrap_or(include_path);
778
779    // Resolve the include relative to the including file's parent
780    // before normalizing. This preserves leading `..` traversal so
781    // `#include "../foo.h"` from `src/lib/file.c` targets
782    // `src/foo.h`, not the lexically-popped `foo.h` (issue #297).
783    // Lexical-only normalization is required because `current_path`
784    // and the entries in `all_files` are typically not canonicalized
785    // and the included header need not exist on disk yet.
786    let resolved_path = current_path
787        .parent()
788        .map(|parent| normalize_path(parent.join(include_path)));
789
790    let include_path = normalize_path(include_path);
791    let Some(file_name) = include_path.file_name().and_then(|n| n.to_str()) else {
792        return vec![];
793    };
794    let Some(possibilities) = all_files.get(file_name) else {
795        return vec![];
796    };
797    if possibilities.len() == 1 {
798        return possibilities.clone();
799    }
800
801    // Strategy chain: each step looks for a UNIQUE candidate that
802    // matches a progressively weaker signal (full resolved target →
803    // suffix on the normalized include → siblings of the including
804    // file). When no step yields a unique match, fall back to the
805    // closest by path distance, which may return zero or many.
806    resolve_against_resolved(possibilities, current_path, resolved_path.as_deref())
807        .or_else(|| unique_filter(possibilities, current_path, |p| p.ends_with(&include_path)))
808        .or_else(|| resolve_against_parent(possibilities, current_path))
809        .unwrap_or_else(|| min_distance_candidates(possibilities, current_path))
810}
811
812/// Filter `possibilities` to those satisfying `pred` and distinct
813/// from `current_path`, returning `Some(matched)` only when exactly
814/// one survives. The cascading caller treats `None` as "this strategy
815/// did not yield a unique resolution — try the next one."
816fn unique_filter<F>(possibilities: &[PathBuf], current_path: &Path, pred: F) -> Option<Vec<PathBuf>>
817where
818    F: Fn(&PathBuf) -> bool,
819{
820    let matched: Vec<PathBuf> = possibilities
821        .iter()
822        .filter(|p| current_path != p.as_path() && pred(p))
823        .cloned()
824        .collect();
825    (matched.len() == 1).then_some(matched)
826}
827
828/// Strongest signal: a candidate matches the fully resolved relative
829/// target. Prefer exact equality, then suffix match (so absolute
830/// `all_files` entries still match a relative resolved target like
831/// `src/foo.h`).
832fn resolve_against_resolved(
833    possibilities: &[PathBuf],
834    current_path: &Path,
835    resolved: Option<&Path>,
836) -> Option<Vec<PathBuf>> {
837    let resolved = resolved?;
838    unique_filter(possibilities, current_path, |p| p == resolved)
839        .or_else(|| unique_filter(possibilities, current_path, |p| p.ends_with(resolved)))
840}
841
842/// Candidate-in-same-directory heuristic: keep entries whose path
843/// starts with the including file's parent directory.
844fn resolve_against_parent(possibilities: &[PathBuf], current_path: &Path) -> Option<Vec<PathBuf>> {
845    let parent = current_path.parent()?;
846    unique_filter(possibilities, current_path, |p| p.starts_with(parent))
847}
848
849/// Last-chance fallback in the `guess_file` strategy chain: returns
850/// every candidate whose `get_paths_dist` from `current_path` ties
851/// the minimum, or an empty `Vec` when no candidate has a defined
852/// distance. Unlike the unique-match strategies, this may
853/// legitimately return zero or many entries — its result is the
854/// function's final answer, not a "try the next strategy" signal.
855fn min_distance_candidates(possibilities: &[PathBuf], current_path: &Path) -> Vec<PathBuf> {
856    // Hold survivors as borrows during the walk: `Less` arms clear the
857    // prior set without dropping owned `PathBuf`s, and the trailing
858    // `cloned()` runs exactly once per final survivor — never on
859    // entries that were tentatively kept and later evicted.
860    let mut dist_min = usize::MAX;
861    let mut path_min: Vec<&PathBuf> = Vec::new();
862    for p in possibilities {
863        if current_path == p {
864            continue;
865        }
866        let Some(dist) = get_paths_dist(current_path, p) else {
867            continue;
868        };
869        match dist.cmp(&dist_min) {
870            Ordering::Less => {
871                dist_min = dist;
872                path_min.clear();
873                path_min.push(p);
874            }
875            Ordering::Equal => path_min.push(p),
876            Ordering::Greater => {}
877        }
878    }
879    path_min.into_iter().cloned().collect()
880}
881
882#[cfg(test)]
883#[path = "tools_tests.rs"]
884mod tests;