Skip to main content

latexml_core/binding/
content.rs

1use std::{borrow::Cow, collections::VecDeque, path::Path, rc::Rc, sync::LazyLock};
2
3use regex::Regex;
4use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
5
6// use crate::util::pathname::PathnameFindOptions;
7use crate::Digested;
8use crate::{
9  binding::def::dialect::def_macro,
10  common::{
11    BindingSource, arena,
12    arena::SymStr,
13    error::{emit_error, *},
14    font::{self, Font, Fontmap},
15    model,
16  },
17  definition::{Definition, ExpansionBody, argument::ArgWrap, expandable::ExpandableOptions},
18  document::{
19    resource::*,
20    tag::{TagOptionName, TagOptions},
21  },
22  gullet,
23  gullet::do_expand,
24  mouth::{Mouth, MouthOptions},
25  parameter::{Parameter, Parameters},
26  pin,
27  state::{let_i, *},
28  stomach::*,
29  token::*,
30  tokens::{TeXString, Tokens},
31  util::pathname::{self, PathnameFindOptions},
32};
33
34/// Maximum nesting depth for package/class loading to prevent infinite recursion.
35/// Perl LaTeXML has no explicit limit but rarely exceeds 20 levels in practice.
36const MAX_INPUT_DEPTH: usize = 500;
37
38thread_local! {
39  /// Current nesting depth of input_definitions calls.
40  static INPUT_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
41  /// Classes a binding read raw itself (`InputDefinitions!(noltxml)` of a `.cls`, without the class-load options
42  /// handling) that no class load has yet given to K11: the enclosing class load claims them at its end
43  /// (`input_definitions_impl`). A Rust local count, so nested loads pair by the call stack.
44  static UNCLAIMED_RAW_CLASS_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
45  /// The stand-in bindings loading now, innermost last (`StandInBindingName`; a renamed elsarticle.cls copy's natbib
46  /// load, 1811.10063).
47  static STAND_IN_BINDINGS: std::cell::RefCell<Vec<String>> =
48    const { std::cell::RefCell::new(Vec::new()) };
49  /// The standard-class derivatives read now, innermost last, each with the names its standard class's binding
50  /// assigned in its own load ([`reading_standard_class_derivative`], [`standard_class_binding_assigned`]; aip-cp.cls,
51  /// 1506.04050).
52  static STANDARD_CLASS_DERIVATIVE: std::cell::RefCell<Vec<HashSet<SymStr>>> =
53    const { std::cell::RefCell::new(Vec::new()) };
54  /// Current nesting depth of [`load_class`] calls: above 0, a class is loading,
55  /// and a class it loads is nested.
56  static CLASS_LOAD_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
57  /// Stack of each active input_definitions frame's `grandparent_in_expl3` flag.
58  /// A native binding that force-raw-loads its own `\ProvidesExplPackage` .sty via
59  /// `InputDefinitions!(noltxml => true)` (e.g. derivative_sty.rs, #630) re-enters
60  /// input_definitions AFTER the outer `\@pushfilename` already ran `\ExplSyntaxOff`
61  /// (`_` -> SUB). A fresh snapshot then reads false, so the exit cleanup over-fires
62  /// `\ExplSyntaxOff` and corrupts `\l__expl_status_stack_tl`. The inner frame
63  /// inherits the outer's flag instead. Witness arXiv:2605.21946 (pomegranate.sty
64  /// -> `\RequirePackage{derivative}`).
65  static INPUT_DEF_EXPL3: std::cell::RefCell<Vec<bool>> =
66    const { std::cell::RefCell::new(Vec::new()) };
67}
68
69/// a configuration for loading LaTeX definition files (such as .sty, .cls, and their bindings)
70pub struct InputDefinitionOptions {
71  /// an optional extension (such as "sty")
72  pub extension:        Option<Cow<'static, str>>,
73  /// package options to pass into the loaded library, appended to `\opt@<name>.<ext>` (`pass_options`). A binding that
74  /// reads its own raw file passes none: the `\usepackage` that loaded the binding recorded them already, and passing
75  /// them again runs every option twice (`\opt@<name>.<ext>` read `noautomatic,noautomatic`).
76  pub options:          Vec<String>,
77  /// Tokens to process after the definition is loaded
78  pub after:            Tokens,
79  /// flag to forbid raw TeX sources
80  pub notex:            bool,
81  /// flag to forbid errors ?
82  pub noerror:          bool,
83  /// flag to forbid binding dispatch
84  pub noltxml:          bool,
85  /// collection of (package) options to process when loading the dependency
86  pub withoptions:      Option<Vec<String>>,
87  /// flag to handle options, or ignore them
88  pub handleoptions:    bool,
89  /// flag to process in .cls mode (default: false)
90  pub as_class:         bool,
91  /// flag to indicate reading the file raw in Gullet
92  pub raw:              bool,
93  /// flag to allow reloading a previously loaded definitions file
94  pub reloadable:       bool,
95  /// `\input` of a raw file already read while reading definitions: TeX
96  /// reads it again. Forbids binding dispatch like `noltxml`, without the
97  /// `\@currname` directory resolution `noltxml` also implies (see `input`).
98  pub reread:           bool,
99  /// flag: set @ catcode to LETTER during loading (default true).
100  /// Set to false for packages like xy.tex that need @ to stay as OTHER.
101  pub at_letter:        bool,
102  /// When set, raw-file lookup is restricted to the user-supplied
103  /// SEARCHPATHS (SOURCEDIRECTORY + graphicspaths), skipping the
104  /// kpsewhich fallback into system texmf. Matches Perl Package.pm's
105  /// `searchpaths_only => 1` — enabled by the `localrawstyles` option
106  /// to latexml.sty. Perl ref: Package.pm L2135, L2674.
107  pub searchpaths_only: bool,
108  /// A class loaded while another class loads (`\LoadClass`): its options are
109  /// its own (`\opt@<name>.cls`), never the global options. latex.ltx sets
110  /// `\@classoptionslist` only at the first class load, `\documentclass`
111  /// (latex.ltx:18716-18718; KPE #304).
112  pub nested_class:     bool,
113  /// The binding's own raw file is a module the LaTeX format holds: while the format holds it, the read takes the TeX
114  /// tree's file, not a paper's copy (`format_module_path`).
115  pub format_module:    Option<FormatModule>,
116}
117
118/// A module the LaTeX format holds (OXIDIZED_DESIGN_DIVERGENCES #1142): `marker` is a control sequence the format
119/// defines while it does (`\bbl@version` from babel's hyphen.cfg, `\c__kernel_expl_date_tl` from expl3-code.tex),
120/// `tree_dir` the module's directory in the TeX tree (`babel`, `l3kernel`), which finds the tree's file past a copy in
121/// the current directory (kpathsea's `.` comes first).
122#[derive(Clone, Copy, Debug)]
123pub struct FormatModule {
124  /// The control sequence the format's dump defines for the module.
125  pub marker:   &'static str,
126  /// The module's directory under the tree's `tex/` (kpathsea matches it as a path suffix).
127  pub tree_dir: &'static str,
128}
129impl Default for InputDefinitionOptions {
130  fn default() -> Self {
131    InputDefinitionOptions {
132      extension:        None,
133      options:          Vec::new(),
134      after:            Tokens!(),
135      notex:            false,
136      noerror:          false,
137      noltxml:          false,
138      raw:              false,
139      reloadable:       false,
140      reread:           false,
141      withoptions:      None,
142      handleoptions:    false,
143      as_class:         false,
144      at_letter:        true,
145      searchpaths_only: false,
146      nested_class:     false,
147      format_module:    None,
148    }
149  }
150}
151
152/// PLANS P16 xii: fire the kernel's generic package/class load hooks around a
153/// load that bypasses `\@onefilewithoptions` (a binding or a raw read).
154/// latex.ltx:18843-18850 runs `\UseHook{package/before}` +
155/// `\UseOneTimeHook{package/<name>/before}` (or `class/…`) before the file
156/// and :18867-18875 `\UseOneTimeHook{package/<name>/after}` +
157/// `\UseHook{package/after}` after its `-h@@k`; `\InputIfFileExists`'
158/// `\@input@file@exists@with@hooks` adds `file/<name>.<ext>/before|after`
159/// and `file/before|after`, plain `\UseHook`s whose `after` pair runs ahead of
160/// the `-h@@k` (`when` = `file/after`). Perl fires none of them (Package.pm L2620-2655),
161/// so `\AddToHook{class/scrbook/after}{…}` (tudapub.cls hooking scrbook's
162/// `\addchap`, DEMO-TUDaPhD) never ran. Only when lthooks is loaded
163/// (`\UseHook` defined) and only for package/class loads. Guard:
164/// `perfect_kernel_batch54::package_after_hook_fires_for_a_binding_load`.
165///
166/// The load is bracketed, as in `\@onefilewithoptions` (latex.ltx:18772/18789)
167/// and `\InputIfFileExists` (:19649/19655), by ltfilehook's file-name stack
168/// (`push_load_file_stack` before, `…@pop@@` after the hooks), which packages
169/// read to learn which files are open: scrlfile-hook.sty:146-158 seeds its own
170/// stack from it and pops once per `file/after`, so with the kernel stack left
171/// empty every file already open when it loaded underflowed ("More file names
172/// popped from stack than put to", 983 corpus manuals, 5 per nomencl load).
173/// Guard: `perfect_kernel_batch56::file_hooks_keep_the_file_name_stack`.
174fn use_load_hooks(name: &str, as_type: &str, when: &str) -> Result<()> {
175  if !load_hooks_active(name)? {
176    return Ok(());
177  }
178  let kind = if as_type == "cls" { "class" } else { "package" };
179  // The file hooks are plain `\UseHook`s (latex.ltx:19668-19673), the package/class ones one-time (:18843-18848)
180  let code = match when {
181    "before" => vec![
182      use_hook(&s!("{kind}/before"), false),
183      use_hook(&s!("{kind}/{name}/before"), true),
184      use_hook("file/before", false),
185      use_hook(&s!("file/{name}.{as_type}/before"), false),
186    ],
187    // `\InputIfFileExists`' end, ahead of the load's `-h@@k` (:18865)
188    "file/after" => vec![
189      use_hook(&s!("file/{name}.{as_type}/after"), false),
190      use_hook("file/after", false),
191    ],
192    _ => vec![
193      use_hook(&s!("{kind}/{name}/after"), true),
194      use_hook(&s!("{kind}/after"), false),
195    ],
196  }
197  .concat();
198  digest(crate::mouth::tokenize_internal(TeXString::assembled(code)))?;
199  Ok(())
200}
201
202/// `\UseHook{hook}` (`once`: `\UseOneTimeHook`) as `\lx@usehook` reads it where it runs (sect11.rs,
203/// `hook_use_tokens`): an empty hook passes without the 1-3M instructions lthooks' preamble mode costs a use (QAB1b).
204fn use_hook(hook: &str, once: bool) -> String {
205  let fast = crate::binding::def::dialect::is_defined_token(&T_CS!("\\lx@usehook"));
206  match (fast, once) {
207    (true, false) => s!("\\lx@usehook{{{hook}}}"),
208    (true, true) => s!("\\lx@useonetimehook{{{hook}}}"),
209    (false, false) => s!("\\UseHook{{{hook}}}"),
210    (false, true) => s!("\\UseOneTimeHook{{{hook}}}"),
211  }
212}
213
214/// Push the load onto ltfilehook's file-name stack, outermost as in latex.ltx
215/// (before the `before` hooks); true when pushed. The caller pops exactly when
216/// this pushed, whether or not the file was found: the decision is taken once,
217/// before the load, since the load itself can define the kernel (the
218/// `latexml.sty` preload brings in LaTeX.pool).
219fn push_load_file_stack(name: &str) -> Result<bool> {
220  let active = load_hooks_active(name)?
221    && lookup_definition(&T_CS!("\\@expl@@@filehook@file@push@@"))?.is_some();
222  if active {
223    digest(T_CS!("\\@expl@@@filehook@file@push@@"))?;
224  }
225  Ok(active)
226}
227
228/// Whether `use_load_hooks` runs for this load: lthooks is loaded, and the
229/// name is a file name.
230fn load_hooks_active(name: &str) -> Result<bool> {
231  if lookup_definition(&T_CS!("\\UseHook"))?.is_none() {
232    return Ok(false);
233  }
234  // latex.ltx:18766-18827 runs no hooks for a file that does not exist
235  // (`\@missing@onefilewithoptions`); a request whose name is a control
236  // sequence (frankenstein lips/slemph/blkcntrl/achicago `\usepackage{…}`
237  // reached with `\aftergroup` as the name — already a `missing_file`
238  // error) would otherwise put that CS inside every `\csname __hook…` label,
239  // 12 more errors per document.
240  Ok(!name.contains('\\'))
241}
242
243/// TODO: Flesh out with the full infrastructure, incremental functionality for now.
244pub fn input_definitions(raw_file: &str, options: InputDefinitionOptions) -> Result<()> {
245  // K1 provenance: what this load defines is a pool (`.pool`), a raw format
246  // file, or a raw file the document loaded. A compiled binding found by the
247  // dispatch below narrows its own code to `Binding` (latexml_package /
248  // latexml_contrib `dispatch`), and its `InputDefinitions!(noltxml)` re-enters
249  // here as `File` for the real package's definitions. A file a fallback class requires while it guesses (OmniBus's
250  // `inst_support`, `aas_macros`) is part of that guess: it stays `Fallback`, so the document's own `\newcommand` of
251  // one of its names wins as it does over the class's (2603.21740 `\newcommand{\inst}{\mathcal I}`; OXIDIZED_DESIGN
252  // #408).
253  use crate::definition::origin::{DefinitionOrigin, OriginGuard, current_origin};
254  let requested_by_fallback = current_origin() == DefinitionOrigin::Fallback;
255  // (and a file a borrowed binding requires is borrowed with it: amsthm's amsgen, `require_package_borrowed`)
256  let requested_by_borrow = current_origin() == DefinitionOrigin::Borrowed;
257  // (a compiled binding's own code requests it — its `RequirePackage!`: `<file>:requested_by_binding`, which a repeat
258  // load's options read, `apply_new_options_on_reload`)
259  let requested_by_binding = current_origin() == DefinitionOrigin::Binding;
260  // (a raw file's own request — a copy's `\RequirePackage{natbib}`, neurips_2024.sty:71: the load TeX sees, which a
261  // binding's early load of the package only anticipated; `apply_new_options_on_reload`)
262  let requested_by_file = current_origin() == DefinitionOrigin::File;
263  // (a stand-in's copy's own request, read before its provides-mode is suspended for the load below — by the stand-in
264  // binding it is read after: `apply_repeat_options`; an elsarticle.cls copy's `\RequirePackage[square,…]{natbib}`,
265  // 1811.10063)
266  let requested_by_copy = copy_provides_binding();
267  let base = raw_file
268    .trim()
269    .rsplit(['/', '\\'])
270    .next()
271    .unwrap_or("")
272    .to_string();
273  let origin = if options.extension.as_deref() == Some("pool") || base.ends_with(".pool") {
274    DefinitionOrigin::Pool
275  } else if requested_by_fallback {
276    DefinitionOrigin::Fallback
277  } else if requested_by_borrow {
278    DefinitionOrigin::Borrowed
279  } else if matches!(
280    base.as_str(),
281    "latex.ltx" | "plain.tex" | "expl3-code.tex" | "latex" | "plain" | "expl3-code"
282  ) {
283    DefinitionOrigin::Format
284  } else {
285    DefinitionOrigin::File
286  };
287  let _origin = OriginGuard::new(origin);
288  // A class load is a frame whose definitions are the class's (`state::ClassLoadFrame`); one a stand-in's copy requests
289  // — its `\LoadClass`, or a class loaded while that is open — is a base class of the copy, whose names the real class
290  // has (the reviewer's probes newcmd_base, nc_chain).
291  let class = options.extension.as_deref() == Some("cls") || raw_file.ends_with(".cls");
292  let _class_frame = (class && options.handleoptions).then(|| {
293    let copy = crate::definition::origin::copy_provides();
294    ClassLoadFrame::enter(
295      raw_file,
296      if copy != 0 {
297        Some(copy)
298      } else {
299        open_copy_class_load()
300      },
301    )
302  });
303  // A package or class a stand-in's copy loads (`\RequirePackage`, `\usepackage`, `\LoadClass`) is a real load, read
304  // whole as TeX reads it: the copy's provides-mode is suspended for it (`read_stand_in_copy`). A file the copy pulls
305  // in by `\input` (`\@input`, `\InputIfFileExists`: the `.clo`/`.cfg` it ships) is part of the copy and follows its
306  // rule (main-session ruling 2026-10-18): svepj.clo:280-284's `\AtEndOfClass{\let\maketitle=\epj@maketitle}` and
307  // svepjc3.clo:57/:71's `\def\maketitle`, read through svjour.cls:86's `\InputIfFileExists{sv\CurrentOption.clo}`,
308  // replaced the binding's `\maketitle`, the affiliations lost to "Address(es) of author(s) should be given" (0901.1015,
309  // 1012.5412, 1111.3868, 1512.01957, 2411.18962, 2107.02119). (a binding the `\input` reaches is a load of its own:
310  // the binding branch of `input_definitions_impl`)
311  let _suspended = (crate::definition::origin::copy_provides() != 0 && options.handleoptions)
312    .then(|| crate::definition::origin::CopyProvidesGuard::new(0));
313  // A file a stand-in binding loads is not part of the binding's command set (`StandInLoadGuard::suspend`); a
314  // stand-in it loads records its own (`input_definitions_impl`).
315  // (the files a stand-in binding's own code loads are the files it is built on, which the paper's copy may declare
316  // itself: `copy_is_the_stood_in_file`)
317  if crate::definition::origin::stand_in_loading() && crate::definition::origin::stand_in_own_code()
318  {
319    note_stand_in_file(raw_file);
320  }
321  // (a class it loads is its base class, whose text defaults are not its own: `StandInLoadGuard::suspend_for`)
322  let _nested = crate::definition::origin::stand_in_loading()
323    .then(|| crate::definition::origin::StandInLoadGuard::suspend_for(class));
324  input_definitions_impl(
325    raw_file,
326    options,
327    requested_by_binding,
328    requested_by_file,
329    requested_by_copy,
330  )
331}
332
333/// Is the file now being read one the author shipped: under the document's own source directory
334/// (`SOURCEDIRECTORY`), not the TeX Live tree? K22's ownership rule — the author's files outrank our guesses — reads
335/// it for a fallback meaning (`is_definable_latex`): a `\newcommand` in the paper's own `.sty` replaces a binding's
336/// guess as the document's does (0901.4335's `mn2e_journal_style.sty` `\newcommand{\araa}{ARAA}`).
337pub fn reading_author_file() -> bool {
338  let dir = lookup_string("SOURCEDIRECTORY");
339  if dir.is_empty() {
340    return false;
341  }
342  let source = arena::to_string(gullet::get_locator().get_source());
343  if source.is_empty() {
344    return false;
345  }
346  let canonical = |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| Path::new(p).to_path_buf());
347  canonical(&source).starts_with(canonical(&dir))
348}
349
350fn input_definitions_impl(
351  raw_file: &str,
352  mut options: InputDefinitionOptions,
353  requested_by_binding: bool,
354  requested_by_file: bool,
355  requested_by_copy: String,
356) -> Result<()> {
357  let trimmed = raw_file.trim();
358  // A compiled binding keyed by BASENAME raw-loads its own name (`noltxml`), but
359  // the dispatch dropped any directory the user wrote — so `\usepackage{DIR/pkg}`
360  // would raw-load a bare `pkg.sty` and miss the author's bundled `DIR/pkg.sty`.
361  // `\@currname` still holds the full request (`DIR/pkg`) from the OUTER load
362  // (set at `before_input_handle_options`, later than here), so load the file the
363  // user actually asked for — exactly as Perl does (it has no such binding and
364  // raw-loads the dir-prefixed path directly, 0 errors; witness 2510.09534,
365  // `\usepackage[preprint]{AISTATS/aistats2026}`). Scoped to `noltxml` + a bare
366  // basename that matches `\@currname`'s basename, so an unrelated `\input` in the
367  // package is NOT auto-resolved in the subdir (stock LaTeX does not do that —
368  // that is what the `import` package is for). This replaces the former
369  // SearchPathGuard, which injected the subdir into SEARCHPATHS instead.
370  let currname_request: Option<String> = if options.noltxml && !trimmed.contains(['/', '\\']) {
371    do_expand(T_CS!("\\@currname"))
372      .ok()
373      .map(|toks| toks.to_string())
374      .filter(|currname| {
375        currname
376          .rsplit_once(['/', '\\'])
377          .is_some_and(|(dir, base)| base == trimmed && !dir.is_empty())
378      })
379  } else {
380    None
381  };
382  // (a request for the file a shipped copy is read in place of, made while it is read, reads the real file raw:
383  // [`SubstitutedRead`])
384  let real_file = options
385    .extension
386    .as_deref()
387    .is_some_and(|ext| !options.reread && substituting_for(&s!("{}.{ext}", file_stem(trimmed))));
388  if real_file && !options.noltxml {
389    Info!(
390      "provide",
391      trimmed,
392      s!(
393        "{trimmed} is requested while a copy is read in its place: its own file is read, not its binding"
394      )
395    );
396    options.noltxml = true;
397  }
398  // (and a binding a shipped copy's declaration routed its request to reads that copy as its own file:
399  // [`routed_copy_request`])
400  let routed_copy = (options.noltxml && requested_by_binding && !options.reread && !real_file)
401    .then(|| routed_copy_request(trimmed, options.extension.as_deref()))
402    .flatten();
403  // (a module the format holds reads the tree's file, whichever copy the request found: [`format_module_path`])
404  let format_module = options.format_module.filter(format_holds).map(|module| {
405    (
406      module,
407      s!(
408        "{}.{}",
409        file_stem(trimmed),
410        options.extension.as_deref().unwrap_or_default()
411      ),
412    )
413  });
414  let _substituted = routed_copy.as_ref().map(|_| {
415    let ext = options.extension.as_deref().unwrap_or_default();
416    SubstitutedRead::enter(s!("{}.{ext}", file_stem(trimmed)))
417  });
418  let name: &str = routed_copy
419    .as_deref()
420    .or(currname_request.as_deref())
421    .unwrap_or(trimmed);
422  // A re-read (`input`) is raw-only, but not a binding loading its own name.
423  if options.reread {
424    options.noltxml = true;
425  }
426
427  // Guard: prevent infinite recursion from circular or runaway package loading.
428  // When a binding is missing, raw TeX loading can trigger macro loops.
429  let depth = INPUT_DEPTH.with(|d| {
430    let current = d.get();
431    d.set(current + 1);
432    current + 1
433  });
434  if depth > MAX_INPUT_DEPTH {
435    INPUT_DEPTH.with(|d| d.set(d.get() - 1));
436    Fatal!(
437      Stomach,
438      Recursion,
439      s!(
440        "Package loading depth exceeded {} (loading '{}').\
441        This usually means a missing binding causes infinite recursion.",
442        MAX_INPUT_DEPTH,
443        name
444      )
445    );
446  }
447
448  // Ensure depth cleanup on all exit paths via a guard
449  struct InputDepthGuard;
450  impl Drop for InputDepthGuard {
451    fn drop(&mut self) { INPUT_DEPTH.with(|d| d.set(d.get() - 1)); }
452  }
453  let _guard = InputDepthGuard;
454
455  // (A directory-prefixed package name — `\usepackage{DIR/pkg}` — that dispatches
456  // to a basename-keyed binding is resolved above by rewriting `name` to the
457  // `\@currname` request, so the binding's own raw-load targets `DIR/pkg`
458  // directly, as Perl does. No SEARCHPATHS injection is needed.)
459
460  // Note: we always need a gullet to expand, and we sometimes need a stomach to load_definitions...
461  // so let's make stomach a mandatory option.
462  //
463  // Snapshot \@currname/\@currext only when handleoptions=true. Perl
464  // Package.pm:2549-2550 does the same — both prevname and prevext are
465  // gated on options{handleoptions}. The handleoptions=false branch
466  // does NOT mutate \@currname/\@currext (mirrors plain LaTeX `\input`
467  // semantics; Perl L2580 likewise only mutates them inside its
468  // handleoptions=true branch).
469  let prevname = if options.handleoptions && lookup_definition(&T_CS!("\\@currname"))?.is_some() {
470    do_expand(T_CS!("\\@currname"))?.to_string()
471  } else {
472    String::new()
473  };
474  let prevext = if options.handleoptions && lookup_definition(&T_CS!("\\@currext"))?.is_some() {
475    do_expand(T_CS!("\\@currext"))?.to_string()
476  } else {
477    String::new()
478  };
479  // This file will be treated somewhat as if it were a class
480  // IF as_class is true
481  // OR if it is loaded by such a class, and has withoptions true!!! (yikes)
482  if options.handleoptions && options.withoptions.is_some() {
483    with_vecdeque("@masquerading@as@class", |vdq_opt| {
484      if let Some(vdq) = vdq_opt
485        && vdq.iter().any(|x| {
486          if let Stored::String(v) = x {
487            arena::with(*v, |str| str == prevname)
488          } else {
489            false
490          }
491        })
492      {
493        options.as_class = true;
494      }
495    });
496  }
497  if options.noltxml {
498    options.raw = true; // so it will be read as raw by Gullet.
499  }
500  let as_type = if options.as_class {
501    Cow::Borrowed("cls")
502  } else {
503    options
504      .extension
505      .as_ref()
506      .cloned()
507      .unwrap_or(Cow::Borrowed(""))
508  };
509
510  // If loading the document class, record its options as the global ones
511  // (Perl Package.pm:2578-2581). latex.ltx sets `\@classoptionslist` and
512  // `\@raw@classoptionslist` only while `\@classoptionslist` is `\relax`
513  // (latex.ltx:18716-18718): at the first class load, `\documentclass`. A class
514  // that class loads keeps its options to itself (`\opt@<name>.cls`).
515  //
516  // DIVERGENCE from Perl (#334, KPE #304): Rust models "first" as the
517  // outermost `load_class` (`nested_class`). Perl pushes every cls load's
518  // options, so a class's `\LoadClass[fleqn]{article}` handed amsmath a global
519  // `fleqn` and replaced `\@classoptionslist` (webofc 2605.12407, USG
520  // 2605.00042; pdflatex centres their equations and keeps the document's
521  // list). A binding's base class (amsart → ams_core, loaded with no options)
522  // is nested as well, so it cannot empty the list either: babel reads a
523  // global language from it (`\bbl@foreach`, babel.sty L4270; witness
524  // 1911.07001, `[oneside,french,titlepage]{amsart}` + bare
525  // `\usepackage{babel}` → french.ldf must load).
526  //
527  // DIVERGENCE retained from Perl: still define `\@classoptionslist` as EMPTY
528  // for an option-less document class so babel's
529  // `\csname\ds@\@classoptionslist\endcsname` doesn't run away (the kernel
530  // default `\let\@classoptionslist\relax`; witness 2504.00009). The "no class
531  // options recorded yet" gate keeps a later outermost load without options
532  // (an unbound class's alternate, a class after a `--preload`ed one) from
533  // emptying a populated list.
534  if as_type == "cls" && !options.nested_class {
535    for opt in &options.options {
536      push_value("class_options", arena::pin(opt))?;
537    }
538    let class_opts_str = options.options.join(",");
539    let have_recorded_opts = lookup_vecdeque("class_options")
540      .map(|v| !v.is_empty())
541      .unwrap_or(false);
542    // Both lists are STRING-tokenized with standard catcodes (letters 11),
543    // as Perl's `DefMacroI('\@classoptionslist', undef, join(',', …))`
544    // (Package.pm L2564 → TokenizeInternal) and as `\documentclass`'s real
545    // argument read. `Explode!` (every char OTHER) broke every `\ifx` value
546    // match downstream: tudapub.cls L173/L358 forwards an unknown class
547    // option (`parskip=half-`) verbatim to `\KOMAoption`, and scrbase.sty
548    // L2354 `\FamilySetNumerical` `\ifx`-compares it against the literal
549    // `half-` from scrbook.cls L825 → "unknown value" (witness
550    // DEMO-TUDaPhD/TUDaThesis; guard
551    // `perfect_kernel_batch53::classoptionslist_has_letter_catcodes`).
552    if !class_opts_str.is_empty() || !have_recorded_opts {
553      def_macro(
554        T_CS!("\\@classoptionslist"),
555        None,
556        crate::mouth::tokenize_internal(TeXString::assembled(class_opts_str.clone())),
557        None,
558      )?;
559    }
560    // OXIDIZED_DESIGN #164 (class half): the kernel ALSO records the raw,
561    // unprocessed option text of the DOCUMENT class in
562    // `\@raw@classoptionslist` (latex.ltx L18718, guarded to the first
563    // `\documentclass` via `\ifx\@classoptionslist\relax`). Modern babel
564    // (babel.sty L4199 `\bbl@foreach\@raw@classoptionslist`) reads THAT — not
565    // `\@classoptionslist` — to pick up global language options, so without
566    // it `\documentclass[french]{article}` + `\usepackage{babel}` loads
567    // nil.ldf and every French shorthand (`\og`/`\fg`) is undefined (TL doc
568    // corpus: 4+ French bundles; Perl 0.8.8 records it nowhere either).
569    // (`class_options` was pushed just above, so `have_recorded_opts` cannot
570    // gate this — use a dedicated once-flag for the kernel's
571    // first-`\documentclass`-only semantics.)
572    if options.handleoptions && !lookup_bool("@raw@classoptionslist_recorded") {
573      assign_value("@raw@classoptionslist_recorded", true, Some(Scope::Global));
574      def_macro(
575        T_CS!("\\@raw@classoptionslist"),
576        None,
577        crate::mouth::tokenize_internal(TeXString::assembled(class_opts_str.clone())),
578        Some(ExpandableOptions {
579          scope: Some(Scope::Global),
580          ..ExpandableOptions::default()
581        }),
582      )?;
583    }
584  }
585
586  // Compute the exact name based on the type
587  let filename = match &options.extension {
588    None => name.to_string(),
589    Some(ext) => s!("{}.{}", name, ext),
590  };
591  // Store the document class filename for xkeyval's isInClassFile check
592  if as_type == "cls" && options.handleoptions {
593    assign_value(
594      "document_class_filename",
595      filename.clone(),
596      Some(Scope::Global),
597    );
598  }
599  let current_options = options.options.join(",");
600  if !current_options.is_empty()
601    && !lookup_bool(&s!("{filename}_unmarks_itself"))
602    && let Some(Stored::String(prevoptions)) = lookup_value(&s!("{filename}_loaded_with_options"))
603    && arena::with(prevoptions, |prev_str| current_options != prev_str)
604  {
605    let message = s!(
606      "Option clash for file {} with options {:?}, previously loaded with {:?}",
607      filename,
608      current_options,
609      arena::to_string(prevoptions)
610    );
611    Info!("unexpected", "options", message);
612  }
613
614  // TODO: This needs reorganization, bindings are not found as "files" in rust,
615  // we need to have a registry (we don't yet)
616
617  // Perl: early-stop if already loaded (checks request_loaded, name_loaded, etc.)
618  // This prevents double-loading and breaks circular loading chains.
619  // IMPORTANT: check BEFORE printing "Loading..." message to avoid spurious output.
620  //
621  // Per OXIDIZED_DESIGN #23: gate on the flag matching the load path
622  // we'll actually take. CRITICAL invariant: a binding `<file>.rs` is
623  // allowed to call `InputDefinitions(noltxml=>1)` for its same-named
624  // raw .sty/.cls/.def AFTER its own `_loaded` flag was set — the raw
625  // load gates on `_raw_loaded`, not `_loaded`. Examples: babel_sty
626  // → raw babel.sty; cite_sty → raw cite.sty.
627  let opt_noltxml = options.noltxml;
628  let opt_notex = options.notex;
629  // Rust-only `_load_attempted` flag: set in the miss-handler below to
630  // prevent retry loops while keeping `_loaded` reserved for genuine
631  // binding success. Without this split the `_loaded`-on-miss hack
632  // shadowed `require_package`'s `!_loaded && !_raw_loaded`
633  // post-call check, disabling `maybe_require_dependencies` for any
634  // package that had no binding (e.g. paper-local `jinstpub.sty`).
635  let already_handled = |fkey: &str| -> bool {
636    // A file that un-marks itself loaded at its end (fontenc.sty tail:
637    // `\global\let\ver@fontenc.sty\relax`, `\let\opt@fontenc.sty\relax`)
638    // is loaded afresh by every request, each time with the new options —
639    // its binding declares that with `<file>_unmarks_itself` (fontenc_sty.rs).
640    if lookup_bool(&s!("{fkey}_unmarks_itself")) {
641      return false;
642    }
643    if opt_noltxml {
644      lookup_bool(&s!("{fkey}_raw_loaded"))
645    } else if opt_notex {
646      lookup_bool(&s!("{fkey}_loaded")) || lookup_bool(&s!("{fkey}_load_attempted"))
647    } else {
648      lookup_bool(&s!("{fkey}_loaded"))
649        || lookup_bool(&s!("{fkey}_raw_loaded"))
650        || lookup_bool(&s!("{fkey}_load_attempted"))
651    }
652  };
653  // Modern-kernel repeat-load option semantics (OXIDIZED_DESIGN #43).
654  // Classic \DeclareOption packages: after ProcessOptions the `\ds@<opt>`
655  // handlers are \relax, so digesting them on a repeat load is a NO-OP —
656  // i.e. LaTeX's own clash-and-drop outcome (and Perl's silent skip; the
657  // Info above is the shared diagnostic). Packages using the key-value
658  // option processor (\ProcessKeyOptions, LaTeX kernel 2022-06+; e.g.
659  // xcolor v3.02 whose `table` key loads colortbl) raise NO clash in real
660  // LaTeX — the repeat load PROCESSES the new keys. A binding models that
661  // by re-asserting a durable `\ds@<opt>` after ProcessOptions! (first
662  // adopter: xcolor's `table`; witness 2605.00310 — \usepackage{xcolor}
663  // then \usepackage[table]{xcolor} builds cleanly under pdflatex, and a
664  // ~483-paper \cellcolor error cluster in sandbox-arxiv-2605). For each
665  // option of a repeat load that the first load did not have, digest the
666  // surviving handler.
667  //
668  // A key-value package whose binding names its setter in `<file>_keyval_setter` (hyperref's
669  // `\hypersetup`) takes the new options of a repeat load through that setter, as its keys. This is the
670  // load a document makes after a class binding has loaded the package where the real class does not:
671  // revtex4_support, elsarticle, PoS, jmlr and sagej load hyperref, so the author's
672  // `\usepackage[colorlinks]{hyperref}` is the first hyperref load real LaTeX sees, and colorlinks loads
673  // color (hyperref.sty:4532-4537). Witnesses 2609.24844, 2609.13110, 1711.02465 (`\textcolor`).
674  let apply_repeat_options = |fkey: &str| -> Result<()> {
675    if options.options.is_empty() || !options.handleoptions {
676      return Ok(());
677    }
678    let mut prev: HashSet<String> =
679      if let Some(Stored::String(prevoptions)) = lookup_value(&s!("{fkey}_loaded_with_options")) {
680        arena::with(prevoptions, |p| {
681          p.split(',').map(|o| o.trim().to_string()).collect()
682        })
683      } else {
684        HashSet::default()
685      };
686    // (and, for the classic clash test, latex.ltx `\@onefilewithoptions@clashchk`, the options passed to it after the
687    // load, `pass_options_with_raw`: a key-value package, one with an `\opt@handler@<file>`, takes a repeat's options
688    // with no such test, latex.ltx:18752-18762 — `\PassOptionsToPackage{table}{xcolor}` after the load, then
689    // `\usepackage[table]{xcolor}`, loads colortbl)
690    if lookup_bool(&s!("{fkey}_repeat_clash")) {
691      prev.extend(
692        lookup_string(&s!("{fkey}_passed_after_load"))
693          .split(',')
694          .map(|o| o.trim().to_string())
695          .filter(|o| !o.is_empty()),
696      );
697    }
698    // (and the options passed to it, `\opt@<file>`, which LaTeX's clash test reads, latex.ltx `\@if@ptions`:
699    // 2110.14346's `\PassOptionsToPackage{numbers, compress}{natbib}` before neurips_2020.sty's load, then
700    // `\usepackage[numbers]{natbib}` — no clash in pdflatex)
701    if let Ok(Some(defn)) = lookup_definition(&T_CS!(s!("\\opt@{fkey}")))
702      && let Some(ExpansionBody::Tokens(body)) = defn.get_expansion()
703    {
704      prev.extend(
705        body
706          .to_string()
707          .split(',')
708          .map(|o| o.trim().to_string())
709          .filter(|o| !o.is_empty()),
710      );
711    }
712    if let Some(Stored::String(setter)) = lookup_value(&s!("{fkey}_keyval_setter")) {
713      let new_options: Vec<&str> = options
714        .options
715        .iter()
716        .map(|opt| opt.trim())
717        .filter(|opt| !opt.is_empty() && !prev.contains(*opt))
718        .collect();
719      // A package with classic options whose binding opts in (`<file>_repeat_clash`, natbib) takes a repeat load's
720      // new options only where TeX would see them: the first load was a compiled binding's own (`<file>:requested_by_
721      // binding`; a class binding loading natbib where the real class loads it later with options, jheppub.sty:37's
722      // `[numbers,sort&compress]`: 2112.14648, 2607.20603), or the request carries a renamed copy's own options
723      // (`<file>:options_of_a_renamed_copy`: NJDnatbib, whose own `\ProcessOptions` runs in TeX; 2506.14995). Otherwise
724      // the first load was the document's world's, and LaTeX keeps its options and stops with "Option clash"
725      // (latex.ltx `\@onefilewithoptions` → `\@if@ptions`), an Error here as there; the new options are dropped.
726      // A class binding that loads the package where the real class does too (jmlr.cls:150, acmart.cls:300,
727      // elsarticle.cls:1243, jheppub.sty:37) records its load as the class's own (`<file>:requested_by_binding` false,
728      // `record_load_as_the_files_own`: not where the paper ships a copy loading it otherwise);
729      // a raw file's own repeat ends the early-load state (`apply_new_options_on_reload` below).
730      // A stand-in's copy that loads the package its binding loaded on the copy's behalf (`<file>:loaded_by_stand_in`,
731      // the first load made while a stand-in binding loaded) makes the load the binding stands in for: TeX sees the
732      // copy's only, so its options apply (a renamed elsarticle.cls copy's `\RequirePackage[square]{natbib}`,
733      // 1811.10063).
734      let copys_own_load = !requested_by_copy.is_empty()
735        && lookup_string(&s!("{fkey}:loaded_by_stand_in")).eq_ignore_ascii_case(&requested_by_copy);
736      let clash = !new_options.is_empty()
737        && lookup_bool(&s!("{fkey}_repeat_clash"))
738        && !lookup_bool(&s!("{fkey}:requested_by_binding"))
739        && !lookup_bool(&s!("{fkey}:options_of_a_renamed_copy"))
740        && !copys_own_load;
741      // A compiled binding's own repeat is no load TeX sees, only the binding's guess at what its file loads: no clash,
742      // its options dropped; the file read raw after it decides (cvpr_sty.rs's `[numbers,sort&compress]` after the
743      // document's `\usepackage[numbers]{natbib}`, where the paper's cvpr.sty loads no natbib: 2109.08809, 2408.02054).
744      if clash && requested_by_binding {
745        Info!(
746          "unexpected",
747          "options",
748          s!(
749            "Options '{}' of a binding's repeat load of {fkey} dropped: the document loaded it first",
750            new_options.join(",")
751          )
752        );
753        return Ok(());
754      }
755      if clash {
756        let package = fkey.rsplit_once('.').map_or(fkey, |(stem, _)| stem);
757        Error!(
758          "latex",
759          "options",
760          s!(
761            "Option clash for package {package}: options '{}' of a repeat load dropped, as LaTeX keeps the first \
762             load's",
763            new_options.join(",")
764          )
765        );
766        return Ok(());
767      }
768      if !new_options.is_empty() {
769        let keyvals = new_options.join(",");
770        Info!(
771          "unexpected",
772          "options",
773          s!(
774            "Applying options '{}' from a repeat load of {}",
775            keyvals,
776            fkey
777          )
778        );
779        let mut tokens = vec![T_CS!(arena::to_string(setter)), T_BEGIN!()];
780        tokens.extend(crate::mouth::tokenize_internal(TeXString::assembled(keyvals)).unlist());
781        tokens.push(T_END!());
782        digest(Tokens::new(tokens))?;
783      }
784      return Ok(());
785    }
786    for opt in &options.options {
787      let opt = opt.trim();
788      if opt.is_empty() || prev.contains(opt) {
789        continue;
790      }
791      // A binding's handler of its own, for a package whose options are keys that outlive its load (xcolor,
792      // `\lx@repeat@xcolor@<opt>`), before the classic `\ds@<opt>`, which `\ProcessOptions` clears and which is any
793      // package's name.
794      let package = fkey.rsplit_once('.').map_or(fkey, |(stem, _)| stem);
795      let own_handler = T_CS!(s!("\\lx@repeat@{package}@{opt}"));
796      let handler = if lookup_definition(&own_handler)?.is_some() {
797        own_handler
798      } else {
799        T_CS!(s!("\\ds@{}", opt))
800      };
801      if lookup_definition(&handler)?.is_some() {
802        Info!(
803          "unexpected",
804          "options",
805          s!("Applying option '{}' from a repeat load of {}", opt, fkey)
806        );
807        digest(Tokens!(handler))?;
808      }
809    }
810    Ok(())
811  };
812  // A raw file's own repeat of a package whose binding opts in (`<file>_repeat_clash`, natbib) after a compiled
813  // binding's early load is the load TeX sees: a stand-in's copy that loads natbib itself (neurips_2024.sty:71
814  // `\RequirePackage{natbib}`, icml2024.sty:95; the reviewer's probes neurips_rep, icml_rep). Its options apply as
815  // above and join the first load's, and the early-load state ends (`<file>:requested_by_binding` false): a later
816  // `\usepackage[numbers]{natbib}` of the document is LaTeX's "Option clash", as pdflatex reports it, while a copy that
817  // comments its load out leaves the binding's early load in place (2506.00573, 2506.01987, 2506.08967, 2506.17103,
818  // 2506.18071, 2506.22567: the document's options apply).
819  let apply_new_options_on_reload = |fkey: &str| -> Result<()> {
820    let file_repeat = options.handleoptions
821      && requested_by_file
822      && lookup_bool(&s!("{fkey}_repeat_clash"))
823      && lookup_bool(&s!("{fkey}:requested_by_binding"));
824    apply_repeat_options(fkey)?;
825    if file_repeat {
826      let key = s!("{fkey}_loaded_with_options");
827      let mut loaded: Vec<String> = match lookup_value(&key) {
828        Some(Stored::String(prev)) => arena::with(prev, |p| {
829          p.split(',')
830            .map(|o| o.trim().to_string())
831            .filter(|o| !o.is_empty())
832            .collect()
833        }),
834        _ => Vec::new(),
835      };
836      for opt in &options.options {
837        let opt = opt.trim();
838        if !opt.is_empty() && !loaded.iter().any(|o| o == opt) {
839          loaded.push(opt.to_string());
840        }
841      }
842      if !loaded.is_empty() {
843        assign_value(&key, loaded.join(","), Some(Scope::Global));
844      }
845      assign_value(
846        &s!("{fkey}:requested_by_binding"),
847        false,
848        Some(Scope::Global),
849      );
850    }
851    Ok(())
852  };
853  // A file a class binding marked loaded on its class's behalf (`<file>:class_marked`, amsart's amsthm) and the
854  // document then unloaded (`\let\ver@<file>\relax`, `state::unmarked_by_document`) loads afresh, as LaTeX's
855  // `\@ifl@aded` finds it not loaded; from then on it is the document's load, no longer the class's mark.
856  if options.handleoptions && unmarked_by_document(&filename) {
857    mark_unloaded(&filename);
858    assign_value(&s!("{filename}:class_marked"), false, Some(Scope::Global));
859  }
860  if !options.reloadable && already_handled(&filename) {
861    // A request our records skip leaves the file loaded, as LaTeX's load would: a mark the document took back since
862    // (`\let\ver@<file>\relax`) is restored, so `state::file_loaded` answers as the loader did (OD #1015).
863    if options.handleoptions && load_recorded(&filename) && !file_loaded(&filename) {
864      mark_version(&filename)?;
865    }
866    apply_new_options_on_reload(&filename)?;
867    return Ok(());
868  }
869  // Also check without extension (Perl checks name_loaded too)
870  if !options.reloadable && name != filename && already_handled(name) {
871    apply_new_options_on_reload(&filename)?;
872    return Ok(());
873  }
874
875  // LaTeX kernel package disablement: \disable@package@load{<name>}{<action>}
876  // stores the action in `\@pkg-disable@<name>.<ext>` (latex.ltx:18771, 19829-19837).
877  // If defined, execute the action (warning/error) and ignore the load request.
878  let disable_cs = T_CS!(s!("\\@pkg-disable@{}", filename));
879  let fallback_cs = T_CS!(s!("\\@pkg-disable@{}", name));
880  let target = if lookup_definition(&disable_cs)?.is_some() {
881    Some(disable_cs)
882  } else if lookup_definition(&fallback_cs)?.is_some() {
883    Some(fallback_cs)
884  } else {
885    None
886  };
887  if let Some(cs) = target {
888    digest(Tokens!(cs))?;
889    Info!(
890      "latex",
891      "disable@package",
892      s!("Package '{filename}' has been disabled. Load request ignored")
893    );
894    // latex.ltx:18771 skips the load without setting `\ver@<file>`, so the
895    // package stays NOT loaded (`\@ifpackageloaded` false; `\reenable@package@load`
896    // + a later request loads it). The hook itself answers every repeat request.
897    return Ok(());
898  }
899
900  // The per-file load note is emitted ONLY when a load is attempted, so
901  // CorTeX's `loaded_file` extraction (which parses the log) counts genuine
902  // loads and nothing else — a binding whose load then fails (a `.rhai` with a
903  // syntax error) keeps its note, as Perl's `Binding->new` prints before `do`:
904  //   * a NATIVE BINDING load announces `(Loading <name>…` around its load
905  //     (`_load_binding`; Perl loadLTXML "(Loading <path>…)" analog);
906  //   * a RAW .sty/.cls/.def load is announced by its Mouth's
907  //     `(Processing definitions <path>…)` (fires only on a real read);
908  //   * the early-return paths — already-loaded skip and missing-file — reach
909  //     NEITHER, so they emit no note (matching Perl, whose loadLTXML returns
910  //     before its note when the binding was already loaded).
911  // (Previously a `(Loading …)` banner was emitted unconditionally here,
912  // before those early-returns — over-reporting already-loaded/missing files.)
913
914  // Snapshot options.after / options.options BEFORE handleoptions consumes
915  // them so the fallback-binding recursive call (Step 3 below) can forward
916  // both to the fallback. Without this snapshot, mn1 → mn.cls.ltxml fallback
917  // ran with empty options/after and the user's `[epsfig]` was lost (see
918  // astro-ph0002213 root cause).
919  let original_after = options.after.clone();
920  let original_options = options.options.clone();
921  // Snapshot the GRANDPARENT's expl3 state BEFORE `\@pushfilename`'s
922  // `\ExplSyntaxOff` flips `_` to SUB. The post-load cleanup hook in
923  // load_tex_definitions uses this to know whether the calling context
924  // was in expl3 mode (so it can skip the `\ExplSyntaxOff` cleanup that
925  // would otherwise stick post-`\@popfilename`). Witness cluster:
926  // arXiv:2509.05997 / .07893 / .02344, 2510.13206/.13942/.17317
927  // (xsavebox + sys_load_backend + l3backend-dvips.def chain — minimal
928  // repro: \usepackage{xsavebox}).
929  let self_snapshot = lookup_catcode('_') == Some(Catcode::LETTER);
930  // Inherit the immediate parent frame's flag only when the parent WAS in expl3 but
931  // our own fresh read is false — the double-nested same-file case (an outer
932  // `\RequirePackage{X}` whose X-binding force-raw-loads its own expl3 .sty, so this
933  // inner call snapshots after the outer `\@pushfilename` already flipped `_` to SUB).
934  // Never overrides a correct fresh read, so xsavebox/tcolorbox/lipsum are unaffected.
935  let grandparent_in_expl3 = INPUT_DEF_EXPL3
936    .with(|s| {
937      s.borrow()
938        .last()
939        .copied()
940        .filter(|&parent| parent && !self_snapshot)
941    })
942    .unwrap_or(self_snapshot);
943  INPUT_DEF_EXPL3.with(|s| s.borrow_mut().push(grandparent_in_expl3));
944  struct Expl3FrameGuard;
945  impl Drop for Expl3FrameGuard {
946    fn drop(&mut self) {
947      INPUT_DEF_EXPL3.with(|s| {
948        s.borrow_mut().pop();
949      });
950    }
951  }
952  let _expl3_frame = Expl3FrameGuard;
953  // Strict-LaTeX-kernel order (latex.ltx `\@onefilewithoptions`, L15518-L15519):
954  //   \@pushfilename                        % capture OLD \@currname / \@currext
955  //   \xdef\@currname{ <new name> }         % then update to NEW
956  //
957  // We previously set \@currname/\@currext to the new file's name BEFORE
958  // calling `before_input_handle_options` (which performs the push). That
959  // captured the NEW name in the pushed triple, so `\@currnamestack` never
960  // held the empty `{}{}{<catcode>}` initial-state triple that
961  // expl3-code.tex's `\__file_tmp:w` recursion uses as its termination
962  // sentinel. Result: under raw expl3-code.tex load (LATEXML_NODUMP=1),
963  // the recursion ate past `\group_end:` into subsequent
964  // `\seq_new:N` / `\cs_new:Npn …` lines, producing the cs_end:
965  // cascade documented in .investigation/cs_end_bisect_round22/.
966  //
967  // Now: push first (uses current/OLD \@currname), then update inside
968  // before_input_handle_options (line 756-757). For the
969  // `handleoptions == false` path no push happens, so set the names
970  // directly here.
971  // Perl Package.pm:2578 computes `$pushpop` ONCE, before the push, and reuses it
972  // for the pop (:2637). A load that itself brings in the LaTeX pool + dump (a
973  // `--preload` package, `expl3_sty.rs`'s `LoadPool!("LaTeX")`) pushes with the
974  // native `\lx@pushfilename` (no `\@pushfilename` yet) but, re-checked after the
975  // load, would pop with the dump's `\@popfilename` → `\__hook_curr_name_pop:` on
976  // an empty `\g__hook_name_stack_seq` → "Extra \PopDefaultHookLabel" (counted
977  // `\errmessage` since batch 56g). Witness: every `[luatex]` profile run.
978  // Guard: `perfect_kernel_batch56::preload_that_pulls_in_the_format_pops_with_the_native_stack`.
979  let mut pushpop = false;
980  let mut file_stack_pushed = false;
981  // A package or class read in the body (Perl's recovery, a binding's load) reads latex.ltx's preamble commands,
982  // `\@pushfilename` first; they are `\@notprerr` again after it (latex.ltx:9521).
983  let _reopened = options
984    .handleoptions
985    .then(crate::binding::preamble_commands::ReopenedForLoad::new);
986  if options.handleoptions {
987    pushpop = before_input_handle_options(&mut options, &prevname, &prevext, name, &as_type)?;
988    def_macro(
989      T_CS!(s!("\\{}.{}-h@@k", name, as_type)),
990      None,
991      options.after,
992      None,
993    )?;
994    // `\@raw@opt@<name>.<ext>` (OXIDIZED_DESIGN #164) is written by
995    // `pass_options`, which `before_input_handle_options` just called for the
996    // explicit `[…]` list, as the kernel's `\load@onefile@withoptions` calls
997    // `\@pass@ptions` (latex.ltx:18832).
998    file_stack_pushed = push_load_file_stack(name)?;
999    use_load_hooks(name, &as_type, "before")?;
1000  }
1001  // No `else` branch: Perl Package.pm L2580-2611 only mutates
1002  // \@currname/\@currext inside the handleoptions=true block. The
1003  // handleoptions=false path mirrors plain LaTeX `\input`, which leaves
1004  // them untouched. Mutating them here breaks \@currnamestack
1005  // discipline: a subsequent inner \RequirePackage's \@pushfilename
1006  // captures the leaked name instead of the empty initial-state value,
1007  // and expl3-code.tex's \__file_tmp:w stack walk over-reads.
1008  // Witnesses: 0805.4519 (inputenc+ansinew), 1705.00041
1009  // (\usetikzlibrary{calligraphy}+spath3+expl3).
1010
1011  if !current_options.is_empty() {
1012    assign_value(
1013      &s!("{}_loaded_with_options", filename),
1014      current_options,
1015      Some(Scope::Global),
1016    );
1017  }
1018  if options.handleoptions {
1019    // Who asked for the first load: a compiled binding's own code (its `RequirePackage!`, where the real class may load
1020    // the package later, or with options, or not at all) or the document's world (a raw file, the document). A repeat
1021    // load's options read it (`apply_new_options_on_reload`).
1022    assign_value(
1023      &s!("{filename}:requested_by_binding"),
1024      requested_by_binding,
1025      Some(Scope::Global),
1026    );
1027    // (and which stand-in binding was loading, the innermost: its copy's own load of the package is that load, and
1028    // no other copy's, `apply_repeat_options`)
1029    let stand_in = if crate::definition::origin::stand_in_loading() {
1030      STAND_IN_BINDINGS.with(|names| names.borrow().last().cloned().unwrap_or_default())
1031    } else {
1032      String::new()
1033    };
1034    assign_value(
1035      &s!("{filename}:loaded_by_stand_in"),
1036      stand_in,
1037      Some(Scope::Global),
1038    );
1039  }
1040
1041  // Track loaded files in \@filelist BEFORE loading (Perl: Package.pm calls
1042  // \@addtofilelist before reading the file, so \@filelist is available inside)
1043  //
1044  // OXIDIZED_DESIGN #166: latex.ltx's `\string@makeletter` (L1784-1795) stores the name's ASCII letters as LETTER,
1045  // which hep-font.sty's `\def\hepfont@get@class#1.cls#2\relax` over `\@filelist` needs (the hep-* `expected:\fi` cluster).
1046  if options.handleoptions && lookup_definition(&T_CS!("\\@addtofilelist"))?.is_some() {
1047    let name_tokens = ExplodeText!(filename);
1048    digest(Tokens!(
1049      T_CS!("\\@addtofilelist"),
1050      T_BEGIN!(),
1051      name_tokens,
1052      T_END!()
1053    ))?;
1054  }
1055
1056  // Skip loading entirely if already loaded (unless reloadable)
1057  // This prevents double-loading when e.g. smfart calls load_class("amsart")
1058  // after the binding already set the _loaded flag.
1059  // Per OXIDIZED_DESIGN #23: gate by the load path's flag — same
1060  // path-aware logic as the early-skip above. Allows a binding to
1061  // load its same-named raw counterpart via `noltxml=>1`.
1062  if !options.reloadable && already_handled(&filename) {
1063    // Already-loaded early return: emit no load note (nothing was loaded).
1064    if options.handleoptions {
1065      pop_load_frame(pushpop, file_stack_pushed, &prevname, &prevext)?;
1066    }
1067    return Ok(());
1068  }
1069
1070  // Catch Fatal errors during binding loading (e.g., token limit exceeded during
1071  // expl3 kernel loading). Convert to non-fatal so document processing continues.
1072  // `Some(source)` = a binding was loaded, carrying its on-disk source path
1073  // when it is a runtime file binding (`.rhai`) or `None` for a compiled-in one;
1074  // outer `None` = no binding loaded. The two `_load_binding` attempts (extra
1075  // slot, then the main resolving chain) short-circuit on the first that loads.
1076  // K11 (`latexml_engine/src/frontmatter_stores.rs`) tells a binding's own title-page setters from
1077  // a raw class's stores by what changed during the binding's load (`store_setters`).
1078  let setters_before = if options.noltxml {
1079    None
1080  } else {
1081    Some(crate::binding::store_setters::snapshot()?)
1082  };
1083  // (the classes a binding loaded now reads raw itself, for K11 at this load's end)
1084  let raw_class_reads_before = UNCLAIMED_RAW_CLASS_READS.get();
1085  let loading_mark = (options.handleoptions && !options.noltxml)
1086    .then(|| mark_loading(&filename))
1087    .flatten();
1088  // (a copy is read after this binding: a stand-in's, or the paper's own copy of a file on `PAPER_COPIES_READ` — asked
1089  // once, here, for the binding's ownership below and the copy's read after it)
1090  let reads_papers_copy = crate::binding::author_files::reads_the_papers_copy(&filename);
1091  let loaded = if options.noltxml {
1092    None
1093  } else {
1094    // (what a binding standing in for an author's file defines is its own, which the paper's copy read after it only
1095    // provides: `read_stand_in_copy`)
1096    // (and so does the binding a shipped copy's declaration routed its request to, `provided_binding`, or a binding on
1097    // `PAPER_COPIES_READ` whose file the paper ships; where it ships none, the load is the binding's alone)
1098    let stands_in = reads_papers_copy || loading_for_a_provides_route(name);
1099    let _stand_in = stands_in.then(|| {
1100      crate::definition::origin::StandInLoadGuard::loaded_by(
1101        crate::definition::origin::stand_in_loader_own_code(),
1102      )
1103    });
1104    // (its name, for the packages its load loads first: `<file>:loaded_by_stand_in`)
1105    let _stand_in_name = stands_in.then(|| StandInBindingName::enter(file_stem(&filename)));
1106    // (a binding a stand-in's copy reaches by `\input` is a load of its own, not the copy's code: `input_definitions`)
1107    let _copy_suspended = (crate::definition::origin::copy_provides() != 0)
1108      .then(|| crate::definition::origin::CopyProvidesGuard::new(0));
1109    // (a binding is LaTeXML's, whichever file requires it: xkeyval_sty.rs under acmcopyright.sty, whose `\XKV@s@tkeys` a
1110    // `\setcopyright{acmlicensed}` calls, 2105.13838; a raw file it reads says for itself)
1111    let _not_own_file = OwnFileGuard::new(false);
1112    match _load_binding(false, &filename, options.reloadable).and_then(|ext| match ext {
1113      Some(source) => Ok(Some(source)),
1114      None => _load_binding(true, &filename, options.reloadable),
1115    }) {
1116      Ok(v) => v,
1117      Err(e) if get_status(LogStatus::Fatal) > 0 => {
1118        // A binding that raised a Fatal (ajmacros.sty's pTeX bail, a
1119        // resource cap) aborts the conversion; the top level logs it once.
1120        return Err(e);
1121      },
1122      // (a runtime binding names its own failure: `Error:script:<file>.rhai`, located in that file)
1123      Err(e) if matches!(e.target, ErrorTarget::Named(_)) => {
1124        Error!(
1125          e.target.log_name(),
1126          e.category.log_name(),
1127          e.message.clone()
1128        );
1129        assign_value(&s!("{filename}_loaded"), true, Some(Scope::Global));
1130        None
1131      },
1132      Err(e) => {
1133        Error!(
1134          "unexpected",
1135          &filename,
1136          s!("Error loading binding for '{}': {}", filename, e)
1137        );
1138        // Mark as loaded even on error to prevent re-loading via raw path
1139        assign_value(&s!("{filename}_loaded"), true, Some(Scope::Global));
1140        None
1141      },
1142    }
1143  };
1144  if let Some(before) = setters_before {
1145    crate::binding::store_setters::mark_bound(&before)?;
1146  }
1147  // (no binding: the raw read below marks its own)
1148  if loaded.is_none() && still_loading_mark(&filename, &loading_mark) {
1149    let was = loading_mark.as_ref().and_then(|(_, was)| was.clone());
1150    assign_meaning(
1151      &T_CS!(s!("\\ver@{filename}")),
1152      was.unwrap_or(Stored::None),
1153      Some(Scope::Global),
1154    );
1155  }
1156  let mut is_found_raw = false;
1157  // Retain the "a binding loaded" fact for the later hook-firing check.
1158  let is_binding = loaded.is_some();
1159  if is_binding {
1160    // (its `(Loading …` note was logged around the load: `_load_binding`)
1161    // We found and loaded a binding successfully, mark it as such.
1162    // Perl Package.pm::loadLTXML L2315-2316 sets TWO flags: `$request`_loaded
1163    // (e.g. `color.sty_loaded`) AND `$ltxname`_loaded (`color.sty.ltxml_loaded`),
1164    // where `.ltxml` is the suffix of the Perl binding file. Rust's port
1165    // keeps only the former — `.ltxml` is not a suffix in the Rust world, so
1166    // binding-vs-raw-tex distinction is queryable via `*_loaded` directly.
1167    // See OXIDIZED_DESIGN.md. Callers of the legacy `.ltxml_loaded` form
1168    // must be migrated to `_loaded`.
1169    // Per OXIDIZED_DESIGN #23: binding success → `<filename>_loaded`.
1170    // Raw load tracks separately via `<filename>_raw_loaded` (see
1171    // load_tex_definitions). The `_found_loaded` Rust-only flag is
1172    // dropped — read sites check `_loaded || _raw_loaded` instead.
1173    let loaded_flag = format!("{filename}_loaded");
1174    assign_value(&loaded_flag, true, Some(Scope::Global));
1175    // Also set the Perl-equivalent `<filename>.ltxml_loaded` flag —
1176    // some callers (e.g. require_package's deps-scan gate) need to
1177    // distinguish binding-loaded from raw-loaded. Without this,
1178    // paper-bundled .sty files that load natbib (which has a
1179    // binding) re-trigger deps-scan on natbib.sty, which re-finds
1180    // \usepackage{natbib} in natbib.sty's own warning text, looping
1181    // infinitely. Witness 2111.01269 (TIMEOUT from natbib deps loop).
1182    assign_value(&s!("{filename}.ltxml_loaded"), true, Some(Scope::Global));
1183    // Perl L2326: Let(T_CS('\ver@'.$trequest), T_CS('\fmtversion'), 'global');
1184    // Set \ver@name.ext to \fmtversion so LaTeX's \RequirePackage guard works.
1185    // Without this, \RequirePackage date checks fail and packages get re-loaded.
1186    // OXIDIZED_DESIGN #169 sibling: a BINDING declares no version, but the
1187    // real file's `\ProvidesPackage{x}[<date> <version> <info>]` is what
1188    // documents read back — setspace-doc.tex:60-64
1189    // `\def\pkginfo#1 #2 #3\relax{…}` `\expandafter\pkginfo\csname
1190    // ver@setspace.sty\endcsname\relax` splits it at spaces (a
1191    // space-free `\fmtversion` ran to EOF: `Until:\relax`), `\@ifpackagelater`
1192    // compares its date. Read it from the installed file when there is one
1193    // (`provides_version_of`); `\fmtversion` stays the fallback.
1194    if options.handleoptions {
1195      let ver_cs = T_CS!(s!("\\ver@{}", filename));
1196      // (`\relax` is not loaded: a query before the load leaves it, `\ifx\csname ver@X.sty\endcsname\relax`)
1197      if !file_loaded(&filename) || still_loading_mark(&filename, &loading_mark) {
1198        mark_version(&filename)?;
1199      }
1200      // fontenc.sty:tail `\global\let\ver@fontenc.sty\relax` — the file
1201      // reports itself NOT loaded (`\@ifpackageloaded{fontenc}` is false in
1202      // real LaTeX), so the next request loads it again.
1203      if lookup_bool(&s!("{filename}_unmarks_itself")) {
1204        let_i(&ver_cs, &T_CS!("\\relax"), Some(Scope::Global));
1205      }
1206    }
1207    // A stand-in binding is followed by the paper's copy of the file it stands in for, which only provides
1208    // (OXIDIZED_DESIGN_DIVERGENCES #731): inside this load, so the copy's `\AtEndOfClass`/`\AtEndOfPackage` code runs
1209    // at its end with the binding's. So is the binding a shipped copy's declaration routed its request to
1210    // (`provided_binding`), and a TeX Live file's binding whose paper ships its own copy (`PAPER_COPIES_READ`).
1211    if reads_papers_copy || loading_for_a_provides_route(name) {
1212      read_stand_in_copy(
1213        &stand_in_copy_request(name),
1214        name,
1215        &as_type,
1216        grandparent_in_expl3,
1217      )?;
1218    }
1219  } else {
1220    // We're inverting the control flow, because it is near-instant to check whether we have an
1221    // available binding dispatcher, in both contributed and core binding names
1222    // Now that we have ensured there is no compiled target of this name, we can start the file
1223    // system search dance, call to kpsewhich, etc.
1224    //
1225    // Perl Package.pm FindFile search order (L2109-2139):
1226    //   1. .ltxml binding (handled above by load_binding/load_external_binding)
1227    //   2. Raw TeX in search paths, BUT only if INTERPRETING_DEFINITIONS is true (i.e. we're inside
1228    //      recursive loading from another raw TeX file)
1229    //   3. FindFile_fallback — strip version suffixes, find generic .ltxml binding (e.g.
1230    //      icml2024.sty → icml.sty.ltxml)
1231    //   4. Raw TeX in search paths (without INTERPRETING_DEFINITIONS gate)
1232    //   5. kpsewhich
1233    //
1234    // This ordering ensures versioned-package fallback bindings take priority
1235    // over raw .sty files that may contain layout checks (like ICML's \ifdim
1236    // page-margin checks) that produce spurious warnings.
1237    let interpreting = lookup_bool_sym(crate::pin!("INTERPRETING_DEFINITIONS"));
1238    // Perl Package.pm:FindFile_aux L2107: `$interpretable =
1239    // LookupMapping('INTERPRETABLE_SOURCES', $file)`. A binding may
1240    // register specific raw sources (keyed by `name.ext`) that MUST be
1241    // raw-loaded directly rather than version-stripped to a fallback
1242    // binding. Driver: xparse.sty.ltxml registers `xparse-2018-04-12.sty`
1243    // so the rollback `\file_input` from the real xparse.sty loads the
1244    // actual definitions (`\NewDocumentCommand`) — WITHOUT this, the
1245    // version-suffix fallback strips `xparse-2018-04-12` → `xparse`, which
1246    // re-enters the in-progress xparse binding (short-circuited) and the
1247    // rollback file is never loaded (`\NewDocumentCommand` undefined →
1248    // xparse/l3 cascade; canvas witness 2309.17288, tests xparse/regex_match).
1249    let interpretable = lookup_mapping("INTERPRETABLE_SOURCES", &filename).is_some();
1250
1251    // Step 2: If we're interpreting raw TeX definitions (or this file is
1252    // explicitly INTERPRETABLE), look for the file directly.
1253    // Perl L2115: `(!notex && ($interpreting || $interpretable) && pathname_find)`.
1254    // Perl Package.pm L2117-2119: `pathname_find($file, paths => $paths)` —
1255    // LOCAL PATHS ONLY, no kpsewhich. Rust must mirror this: kpsewhich
1256    // here would short-circuit Step 3 (fallback ltxml) for any TeX-Live-
1257    // shipped raw file. Witness: `\RequirePackage{caption3}` from raw
1258    // floatrow.sty — Perl finds caption3.sty NOT in user paths, falls
1259    // through to Step 3 → caption.sty.ltxml. Rust with kpsewhich here
1260    // returned the real caption3.sty from TL, raw-loading it and
1261    // triggering the `\DeclareCaptionFormat{hang}[#1#2#3\par]{...}`
1262    // PARAM-leak cascade (arXiv:2506.19291: Rust=30 vs Perl=2).
1263    // A shipped file declaring itself a bound file is that binding's request, read after it as its stand-in's copy
1264    // ([`provided_binding`]; OXIDIZED_DESIGN_DIVERGENCES #731): ahead of every raw read, as a binding always wins over
1265    // a shipped copy (user rulings 2026-10-17, 2026-10-20), and of the versioned fallback, which reads no copy.
1266    // (a file that loads what it declares is an extension of that file, read raw as itself, never routed to a fallback)
1267    let (provides, extension) = match (!options.noltxml && !interpretable)
1268      .then(|| provided_binding(name, &as_type))
1269      .flatten()
1270    {
1271      Some(DeclaredFile::Copy(binding, declared)) => (Some((binding, declared)), false),
1272      Some(DeclaredFile::Extension) => (None, true),
1273      None => (None, false),
1274    };
1275    let found_raw =
1276      if provides.is_none() && (interpreting || interpretable || extension) && !options.notex {
1277        find_file(
1278          &filename,
1279          Some(FindFileOptions {
1280            forbid_ltxml:      options.noltxml,
1281            notex:             false,
1282            ext_type:          options.extension.as_ref().cloned(),
1283            search_paths_only: true,
1284          }),
1285        )
1286      } else {
1287        None
1288      };
1289
1290    // Step 3: Try fallback (strip version suffixes / dir prefix) before raw TeX.
1291    // Perl Package.pm L2118-2121: FindFile_fallback.
1292    //
1293    // Design policy: bindings ALWAYS win over local raw .sty/.cls files.
1294    // The `.rs` bindings are hand-tuned for the conversion, so if a
1295    // fallback name resolves to a registered binding we dispatch there
1296    // unconditionally. Raw TeX is the last-resort path (Step 4).
1297    //
1298    // Two flavors are recorded via [`FallbackKind`] for informational
1299    // log messages only — both always fire when the binding exists:
1300    //   - Versioned: suffix/prefix actually stripped (Perl-faithful). Drivers: 1206.0536 (mysvjour3
1301    //     → svjour3), astro-ph0005021 (./aaspp4 → ./aaspp — aaspp4.sty ships locally with plain-TeX
1302    //     `\startdata`; the engine's alignment-aware binding still wins, matching Perl).
1303    //   - BasenameOnly: only directory prefix removed. Rust-specific extension keyed to our
1304    //     contrib-binding registry. Drivers: 2105.02087 (misc/ieeetran → IEEEtran binding);
1305    //     2405.18387 (assets/equations → equations binding, because we ship a tuned binding for
1306    //     this name).
1307    let found_raw = if found_raw.is_some() {
1308      found_raw
1309    } else if !options.noltxml && !interpretable {
1310      // Perl L2119: `(!noltxml && !$interpretable && FindFile_fallback)` —
1311      // an INTERPRETABLE source must NOT be version-stripped to a fallback
1312      // binding; it falls through to the raw-TeX/kpsewhich path below.
1313      let route = match &provides {
1314        Some((binding, declared)) => {
1315          let fallback = s!("{binding}.{as_type}");
1316          // (where the binding reads its file raw, the copy is read there: `routed_copy_request`'s Info)
1317          let action = if lookup_bool(&s!("{fallback}_loaded")) {
1318            s!("the {fallback} binding is loaded already, not loaded again; the copy is read")
1319          } else {
1320            s!("loading the {fallback} binding")
1321          };
1322          Info!(
1323            "fallback",
1324            name,
1325            s!("The paper's {filename} declares itself {declared}: {action}")
1326          );
1327          Some(fallback)
1328        },
1329        None => find_file_fallback(name, &as_type).map(|(fallback, _kind)| {
1330          Info!(
1331            "fallback",
1332            name,
1333            s!("Interpreted as versioned package, falling back to {fallback}")
1334          );
1335          fallback
1336        }),
1337      };
1338      if let Some(fallback) = route {
1339        // Load the fallback binding once: a binding the document already loaded under its own name is not run again
1340        // (Perl `loadLTXML`, Package.pm:2328-2330).
1341        let ext_suffix = if as_type == "sty" { ".sty" } else { ".cls" };
1342        let fallback_name = fallback.trim_end_matches(ext_suffix).to_string();
1343        // The request the fallback answers, for a binding that reads its version from its name: Perl's `\@currname`
1344        // holds the request while the fallback loads (Package.pm:2618 defines it from `$name`), ours the fallback's
1345        // name. neurips_sty.rs reads the year of `Styles/neurips_2026` here (2609.20831).
1346        // `fallback_target`: the binding answering it, so a binding tells its own request from an outer load's
1347        // (shipped_class.rs).
1348        // `fallback_provides`: the binding a shipped copy's declaration routed to, which reads the copy after it
1349        // (`loading_for_a_provides_route`); with the copy's options, which its own `\ProcessOptions` takes in TeX, even
1350        // after the binding loaded already (`<file>:options_of_a_renamed_copy`, `apply_repeat_options`)
1351        let outer_request = lookup_string("fallback_request");
1352        let outer_target = lookup_string("fallback_target");
1353        let outer_provides = lookup_string("fallback_provides");
1354        assign_value("fallback_request", name.to_string(), Some(Scope::Global));
1355        assign_value(
1356          "fallback_target",
1357          fallback_name.clone(),
1358          Some(Scope::Global),
1359        );
1360        let renamed_copy_key = s!("{fallback}:options_of_a_renamed_copy");
1361        let outer_renamed_copy = lookup_bool(&renamed_copy_key);
1362        if provides.is_some() {
1363          assign_value("fallback_provides", fallback.clone(), Some(Scope::Global));
1364          assign_value(&renamed_copy_key, true, Some(Scope::Global));
1365        } else {
1366          assign_value("fallback_provides", String::new(), Some(Scope::Global));
1367        }
1368        // Forward the original options + after-hook so fallback bindings see
1369        // user-supplied class/package options (Perl-faithful: in Perl FindFile
1370        // returns a path and the caller's options/after stay attached to the
1371        // ORIGINAL `\@currname`-frame). Without this, `\documentstyle[epsfig]{mn1}`
1372        // fell back to mn.cls.ltxml with empty options → mn.cls's option-handler
1373        // never saw `epsfig` → `\compat@loadpackages` after-hook never fired
1374        // → `\psfig` undefined. Witness: astro-ph0002213.
1375        let fb_result = input_definitions(&fallback_name, InputDefinitionOptions {
1376          extension: Some(Cow::Borrowed(if as_type == "sty" { "sty" } else { "cls" })),
1377          options: original_options,
1378          after: original_after,
1379          handleoptions: options.handleoptions,
1380          noerror: true,
1381          reloadable: false,
1382          ..InputDefinitionOptions::default()
1383        });
1384        // (a binding loaded already, or a file of its name read raw, is not loaded again, but the copy is still read
1385        // whole, as TeX reads it: 2304.14243's packages/pictures.sty `\ProvidesPackage{packages/graphics}` after
1386        // graphicx, its commands lost silently; a copy the binding's load read is not read again)
1387        if provides.is_some() && fb_result.is_ok() {
1388          read_stand_in_copy(name, &fallback_name, &as_type, grandparent_in_expl3)?;
1389        }
1390        assign_value("fallback_request", outer_request, Some(Scope::Global));
1391        assign_value("fallback_target", outer_target, Some(Scope::Global));
1392        assign_value("fallback_provides", outer_provides, Some(Scope::Global));
1393        if provides.is_some() {
1394          assign_value(&renamed_copy_key, outer_renamed_copy, Some(Scope::Global));
1395        }
1396        if fb_result.is_ok() {
1397          assign_value(&s!("{filename}_loaded"), true, Some(Scope::Global));
1398          // latex.ltx:18484-18486 `\@pr@videpackage`: the requested name takes the
1399          // loaded file's version (`\ver@\@currpkg@reqd`), so a date test on it
1400          // reads the substitute's: floatrow.sty:40 `\@ifpackagelater{caption3}
1401          // {2007/04/11 v3.0q}` after caption3 fell back to caption (iaria,
1402          // iaria-lite, langscibook, letgut; TeX Live class census 2026-09-24).
1403          // (not where the paper's copy recorded its own version under the request, `\ProvidesPackage`)
1404          if !file_loaded(&filename) {
1405            let_i(
1406              &T_CS!(s!("\\ver@{filename}")),
1407              &T_CS!(s!("\\ver@{fallback_name}.{as_type}")),
1408              Some(Scope::Global),
1409            );
1410          }
1411          // NOTE: do NOT set `{filename}.ltxml_loaded` here. The
1412          // fallback name is a DIFFERENT binding (e.g. article for
1413          // myclass); the original `{filename}` (myclass.cls) has
1414          // no binding. Setting it would suppress the downstream
1415          // deps-scan check that picks up myclass's
1416          // \RequirePackage{caption}.
1417        }
1418        None // fallback handled the loading; no raw file to load
1419      } else {
1420        None
1421      }
1422    } else {
1423      None
1424    };
1425
1426    // Step 4: Raw TeX in search paths (without INTERPRETING_DEFINITIONS gate)
1427    // Perl Package.pm L2122-2125
1428    //
1429    // Per OXIDIZED_DESIGN #23: gate by `_raw_loaded` only — when a binding
1430    // explicitly loads its raw counterpart via `noltxml=>1`, the binding's
1431    // own `_loaded` flag is already set, but we MUST still proceed.
1432    //
1433    // EXCEPTION: if Step 3 (fallback ltxml binding) just succeeded, Perl's
1434    // `if/elsif` flow (Package.pm:2118-2125) RETURNS on success and skips
1435    // the raw-tex branch entirely. Rust's port uses sequential `let`
1436    // bindings, so we must explicitly check `_loaded` here. Without this
1437    // gate, `\RequirePackage{caption2}` (before caption2_sty.rs bound it by
1438    // name) loaded `caption.sty.ltxml` via
1439    // `find_file_fallback` (caption2 → caption strips trailing digit) AND
1440    // then ALSO loads raw `caption2.sty`, which fires its
1441    // `\@ifpackageloaded{caption}` mutual-exclusivity error. Same pattern
1442    // applies to any package whose name ends in `[vV]?[-_.\d]+` and whose
1443    // unsuffixed form has its own .ltxml binding.
1444    let found_raw = if found_raw.is_some() {
1445      found_raw
1446    } else if lookup_bool(&s!("{filename}_loaded")) {
1447      // Fallback ltxml binding already loaded — don't double-load the raw.
1448      None
1449    } else if !options.notex && (options.reloadable || !lookup_bool(&s!("{filename}_raw_loaded"))) {
1450      // Perl Package.pm L2121-2125 + L2131-2136: combined raw-search
1451      // step. Tries local paths first, then kpsewhich. Mirrors Perl's
1452      // Step 4 (`!interpreting` local raw) PLUS Step 5 (kpsewhich
1453      // unconditionally — note Perl's kpsewhich block lacks the
1454      // interpreting gate). The previous `!interpreting` guard here
1455      // was wrong: Step 2 now uses `search_paths_only=true`, so
1456      // under interpreting=true we still need kpsewhich for raw
1457      // files that have no fallback ltxml binding.
1458      find_file(
1459        &filename,
1460        Some(FindFileOptions {
1461          forbid_ltxml:      options.noltxml,
1462          notex:             false,
1463          ext_type:          options.extension.as_ref().cloned(),
1464          search_paths_only: options.searchpaths_only,
1465        }),
1466      )
1467    } else {
1468      None
1469    };
1470
1471    let found_raw = match &format_module {
1472      Some((module, file)) => {
1473        found_raw.map(|path| format_module_path(&filename, file, path, module))
1474      },
1475      None => found_raw,
1476    };
1477    if let Some(file) = found_raw {
1478      is_found_raw = true;
1479      // The raw load itself sets `<filename>_raw_loaded` via
1480      // load_tex_definitions (per OXIDIZED_DESIGN #23). Read sites
1481      // check `_loaded || _raw_loaded` to detect "any load happened".
1482      // The title-page setters the file defines are its own, even when a binding reads it
1483      // (`store_setters::mark_raw`).
1484      let setters_before = crate::binding::store_setters::snapshot()?;
1485      let class_read = (as_type == "cls").then(crate::binding::store_setters::RawClassRead::begin);
1486      // (a binding's own raw read of a file is a request of its own, which TeX's `\RequirePackage` would make)
1487      let own_request =
1488        options.noltxml && requested_by_binding && !options.handleoptions && !options.reread;
1489      load_tex_definitions(
1490        &filename,
1491        &file,
1492        options.reloadable,
1493        options.at_letter,
1494        grandparent_in_expl3,
1495        options.handleoptions,
1496        own_request,
1497      )?;
1498      drop(class_read);
1499      crate::binding::store_setters::mark_raw(&setters_before)?;
1500      if as_type == "cls" && !options.handleoptions {
1501        UNCLAIMED_RAW_CLASS_READS.set(UNCLAIMED_RAW_CLASS_READS.get() + 1);
1502      }
1503    } else if options.reloadable
1504      && options.notex
1505      && options.noerror
1506      && !lookup_bool(&s!("{filename}_loaded"))
1507    {
1508      // A binding-only (`notex`) RELOADABLE probe that loaded nothing in THIS
1509      // call: the file is `_raw_loaded` from an earlier `\usepackage`, so the
1510      // not-loaded branch below is skipped (a Step-3 fallback binding loaded
1511      // in this call sets `_loaded`, so it is excluded) — but a silent `Ok` made
1512      // `\input{pkg.sty}` (`input()`, the only such caller) a no-op for any
1513      // already-loaded package, where real TeX's `\input` always reads the
1514      // file and Perl (Package.pm:2270 `loadTeXDefinitions(reloadable=>1)`)
1515      // re-reads it too. tikzlings-doc.tex:69-70 `\tex_input:D` re-reads each
1516      // animal `.sty` under `\c_other_cctab` to harvest its comment lines;
1517      // the skipped read left `\__tikzlings_process_line:w #1^^M` scanning
1518      // the enclosing document to its end. Guard:
1519      // `perfect_kernel_batch52::input_rereads_loaded_sty`.
1520      if options.handleoptions {
1521        pop_load_frame(pushpop, file_stack_pushed, &prevname, &prevext)?;
1522      }
1523      return Err(s!("Not loaded by this call: {}", filename).into());
1524    } else if !lookup_bool(&s!("{filename}_loaded")) && !lookup_bool(&s!("{filename}_raw_loaded")) {
1525      if options.noerror {
1526        // With noerror: don't mark as loaded and return Err so callers can
1527        // try fallback names (e.g. tikzlibrary → pgflibrary). Matches Perl's
1528        // InputDefinitions which returns undef on not-found even with noerror=>1.
1529        // Nothing loaded → emit no load note; undo the push (a missing class's OmniBus fallback kept `\@currext` `cls`).
1530        if options.handleoptions {
1531          pop_load_frame(pushpop, file_stack_pushed, &prevname, &prevext)?;
1532        }
1533        return Err(s!("File not found: {}", filename).into());
1534      }
1535      // Perl Package.pm L2679 / L2715: maybeRequireDependencies($name, $type)
1536      // is invoked when InputDefinitions returned undef ($success false).
1537      // We mirror that here in the miss-handler, which is the only point
1538      // where we know neither binding nor raw load occurred. Doing the
1539      // dependency-scan BEFORE marking `_load_attempted` keeps the call
1540      // exactly once-per-package and lets paper-local `.sty` files
1541      // (e.g. jinstpub.sty bundling natbib + amsmath dependencies) wire
1542      // up their transitively-bound prerequisites even when raw .sty
1543      // loading is disabled (`INCLUDE_STYLES=false`, the default).
1544      let scan_type =
1545        options
1546          .extension
1547          .as_deref()
1548          .unwrap_or(if options.as_class { "cls" } else { "sty" });
1549      maybe_require_dependencies(name, scan_type);
1550      // Rust-only retry guard: prevents re-attempting a missing file in
1551      // a loop (raw TeX repeatedly calling \RequirePackage). Use a
1552      // dedicated `_load_attempted` flag — NOT `_loaded` — so the
1553      // post-input_definitions success check in `require_package`
1554      // remains honest about whether anything actually loaded.
1555      //
1556      // Gate the guard on raw-loading having actually been POSSIBLE
1557      // (INCLUDE_STYLES on, or noltxml forced). A miss while raw `.sty` loading
1558      // was OFF is a deliberate DEFERRAL, not a genuine "file absent" — and must
1559      // NOT block a later load once INCLUDE_STYLES turns on (e.g. inside another
1560      // package's raw read). Otherwise a bare `\RequirePackage{pgfcore}` (no
1561      // binding, INCLUDE_STYLES off) permanently STARVES tcolorbox's `skins`
1562      // library, which raw-loads pgfcore under INCLUDE_STYLES=true — whereas
1563      // pdflatex loads pgfcore fine in any order. The guard still fires exactly
1564      // where it is needed: the loop it prevents happens DURING a raw read,
1565      // which is itself INCLUDE_STYLES=true. Witness: nicematrix-then-
1566      // tcolorbox[most] (fairmeta.cls, ar5iv #520/#567/#576): 49 → 0 pgf errors.
1567      if lookup_bool("INCLUDE_STYLES") || options.noltxml {
1568        assign_value(&s!("{filename}_load_attempted"), true, Some(Scope::Global));
1569      }
1570      // Say which of the two things actually happened. `notex` (the DEFAULT
1571      // whenever `INCLUDE_STYLES` is off — see `require_package`, Perl
1572      // `Package.pm` L2671-2672) gates the raw-search branch above, so in that
1573      // case NO disk lookup was performed at all. Claiming "no raw file found
1574      // on disk" there asserts a search that never ran, and the package is
1575      // usually installed and findable: `\usepackage{xstring}` on arXiv
1576      // 2607.21760 warned exactly that while `kpsewhich xstring.sty` resolved
1577      // it fine, sending a reader hunting a file-resolution bug that does not
1578      // exist. A diagnostic must not overclaim what it checked.
1579      let why = if options.notex {
1580        "no dispatcher entry, and raw TeX loading is off (latexml.sty's rawstyles turns it on)"
1581      } else {
1582        "no dispatcher entry, and no raw file found on disk"
1583      };
1584      Warn!(
1585        "missing_file",
1586        name,
1587        s!("Can't find binding or file for '{filename}'. {why}.")
1588      );
1589    }
1590  }
1591
1592  if options.handleoptions {
1593    if is_binding || is_found_raw {
1594      // latex.ltx:18856 runs `\<name>.<ext>-h@@k` inside `\@onefilewithoptions`,
1595      // BEFORE `\@popfilename` (L18801) restores `\catcode`\@`, so
1596      // `\AtEndOfPackage` code sees `@` as a letter: europecv.cls:27
1597      // `\AtEndOfPackage{\InputIfFileExists{ecven.def}…}` reads `\ecv@utf`
1598      // names from the .def, and a `\ecv` + `@utf` split loops the title
1599      // row to the pushback limit (europecv manual, KNOWN_PERL_ERRORS #132 —
1600      // Perl digests the hook after the raw Mouth's catcode restore too).
1601      // Guard: `perfect_kernel_batch54::at_end_of_package_hook_runs_with_at_letter`.
1602      let saved_at = lookup_catcode('@');
1603      assign_catcode('@', Catcode::LETTER, None);
1604      let hook = use_load_hooks(name, &as_type, "file/after")
1605        .and_then(|_| digest(T_CS!(s!("\\{name}.{as_type}-h@@k"))))
1606        .and_then(|_| unprocessed_options(name, &as_type))
1607        .and_then(|_| use_load_hooks(name, &as_type, "after"));
1608      assign_catcode('@', saved_at.unwrap_or(Catcode::OTHER), None);
1609      hook?;
1610      // K11 (`latexml_engine/src/frontmatter_stores.rs`): a class loaded RAW
1611      // keeps its title page in stores that only its discarded `\@maketitle`
1612      // reads; the kernel reroutes the ones it knows to the frontmatter API.
1613      // One rule for every class read raw on the class-load path: the class
1614      // itself (the rawclasses lever, a raw `\LoadClass`), or the class a
1615      // binding reads raw (apa6.cls, apa.cls, beilstein.cls, lni.cls, memoir.cls,
1616      // …), whose stores reach the frontmatter as under the lever (68u: lni
1617      // lost `\subtitle`; apa6 its `\shorttitle`/`\affiliation`/`\authornote`).
1618      // A binding's read is rerouted here, after the binding loaded: a setter
1619      // the binding defined after its read, or before it and the class left
1620      // alone, is the binding's (`store_setters::mark_bound` above), never a
1621      // store; one the raw class redefined after the binding defined it is the
1622      // class's, and rerouted as the class's store.
1623      let binding_read_a_class =
1624        is_binding && UNCLAIMED_RAW_CLASS_READS.get() > raw_class_reads_before;
1625      if binding_read_a_class {
1626        UNCLAIMED_RAW_CLASS_READS.set(raw_class_reads_before);
1627      }
1628      if ((is_found_raw && !is_binding) || binding_read_a_class)
1629        && as_type == "cls"
1630        && lookup_definition(&T_CS!("\\lx@class@loaded@raw"))?.is_some()
1631      {
1632        digest(crate::mouth::tokenize_internal(TeXString::assembled(s!(
1633          "\\lx@class@loaded@raw{{{name}}}"
1634        ))))?;
1635      }
1636      // A package loaded raw: its in-place contact setters reach the frontmatter API as a raw class's do
1637      // (`frontmatter_stores.rs` `reroute_in_place_contact_setters`; 11lomcon.sty, hep-ph0312288).
1638      if is_found_raw
1639        && !is_binding
1640        && as_type == "sty"
1641        && lookup_definition(&T_CS!("\\lx@package@loaded@raw"))?.is_some()
1642      {
1643        digest(crate::mouth::tokenize_internal(TeXString::assembled(s!(
1644          "\\lx@package@loaded@raw{{{name}}}"
1645        ))))?;
1646      }
1647    }
1648    pop_load_frame(pushpop, file_stack_pushed, &prevname, &prevext)?;
1649    reset_options()?;
1650  }
1651  // No handleoptions=false cleanup needed: we never mutated
1652  // \@currname/\@currext on that path (matching Perl).
1653  Ok(())
1654}
1655
1656/// The end of a `handleoptions` load (Package.pm:2652-2654): pop what `before_input_handle_options` pushed and restore
1657/// `\@currname`/`\@currext`, also when the load found nothing to read (Perl pushes only once the file is found; TeX pops a
1658/// missing file too, latex.ltx:18363 and :18801).
1659fn pop_load_frame(
1660  pushpop: bool,
1661  file_stack_pushed: bool,
1662  prevname: &str,
1663  prevext: &str,
1664) -> Result<()> {
1665  if file_stack_pushed {
1666    digest(T_CS!("\\@expl@@@filehook@file@pop@@"))?;
1667  }
1668  // Perl-faithful: Package.pm:2654 —
1669  //   Digest(($pushpop ? T_CS('\@popfilename') : T_CS('\lx@popfilename')));
1670  // Pair with the dispatched push above: the SAME `$pushpop` decision, taken
1671  // before the push (see the declaration at the `handleoptions` branch), so a
1672  // load that defines `\@popfilename` mid-way still pops the stack it pushed.
1673  if pushpop {
1674    digest(T_CS!("\\@popfilename"))?;
1675  } else {
1676    digest(T_CS!("\\lx@popfilename"))?;
1677  }
1678  // Restore @currname/@currext as a FALLBACK — AFTER the pop above, since
1679  // latex.ltx's `\@popfilename` (and a package's patched copy, e.g.
1680  // afterpackage.sty:20-28 firing `\<pkg>.sty-@dd` hooks) reads
1681  // `\@currname` as the file being FINISHED and restores from its own
1682  // stack. Restoring first made a nested load's hook look up the PARENT's
1683  // name (ncclatex → nccsect: ncc's `\openrightorany` never defined).
1684  // Guard: `perfect_kernel_batch54::afterpackage_hook_fires_for_a_nested_load`.
1685  if !prevname.is_empty() {
1686    def_macro(
1687      T_CS!("\\@currname"),
1688      None,
1689      Tokens!(ExplodeText!(prevname)),
1690      None,
1691    )?;
1692  }
1693  if !prevext.is_empty() {
1694    def_macro(
1695      T_CS!("\\@currext"),
1696      None,
1697      Tokens!(ExplodeText!(prevext)),
1698      None,
1699    )?;
1700  }
1701  // Verify @currname was correctly restored, and force-fix if not
1702  let restored_name = if lookup_definition(&T_CS!("\\@currname"))?.is_some() {
1703    do_expand(T_CS!("\\@currname"))?.to_string()
1704  } else {
1705    String::new()
1706  };
1707  if !prevname.is_empty() && restored_name != prevname {
1708    // @popfilename may have popped a stale entry; force correct value
1709    def_macro(
1710      T_CS!("\\@currname"),
1711      None,
1712      Tokens!(ExplodeText!(prevname)),
1713      Some(ExpandableOptions {
1714        scope: Some(Scope::Global),
1715        ..ExpandableOptions::default()
1716      }),
1717    )?;
1718  }
1719  if !prevext.is_empty() {
1720    let restored_ext = if lookup_definition(&T_CS!("\\@currext"))?.is_some() {
1721      do_expand(T_CS!("\\@currext"))?.to_string()
1722    } else {
1723      String::new()
1724    };
1725    if restored_ext != prevext {
1726      def_macro(
1727        T_CS!("\\@currext"),
1728        None,
1729        Tokens!(ExplodeText!(prevext)),
1730        Some(ExpandableOptions {
1731          scope: Some(Scope::Global),
1732          ..ExpandableOptions::default()
1733        }),
1734      )?;
1735    }
1736  }
1737  Ok(())
1738}
1739
1740/// loads a binding from the main binding dispatcher, if available+found.
1741/// `Ok(Some(source))` on load — `source` is the on-disk path for a runtime
1742/// `.rhai` file binding, `None` for a compiled-in one; `Ok(None)` = not loaded.
1743pub fn load_binding(file: &str) -> Result<Option<BindingSource>> {
1744  _load_binding(true, file, false)
1745}
1746/// loads a binding from an external binding dispatcher, if available+found
1747pub fn load_external_binding(file: &str) -> Result<Option<BindingSource>> {
1748  _load_binding(false, file, false)
1749}
1750/// The binding a `(Loading …` note names. A runtime `.rhai` file binding is named by its on-disk path (`source`,
1751/// threaded through the dispatch result: converter.rs `rhai_dispatch`, #560), as Perl names the `.ltxml` file. A
1752/// compiled-in one has no file, so it is named by its module proxy — `tcolorbox.sty` → `tcolorbox_sty.rs`, `aa.cls` →
1753/// `aa_cls.rs` — which keeps it apart from the raw twin's `(Processing definitions <path>…` when a binding raw-loads its
1754/// same-named file, so cortex's `loaded_file` stats count two artifacts, not one file twice (user, 2026-07-04).
1755fn binding_note_name(request: &str, source: Option<&String>) -> String {
1756  if let Some(path) = source {
1757    path.clone()
1758  } else if let Some(stem) = request.strip_suffix(".sty") {
1759    s!("{stem}_sty.rs")
1760  } else if let Some(stem) = request.strip_suffix(".cls") {
1761    s!("{stem}_cls.rs")
1762  } else {
1763    request.to_string()
1764  }
1765}
1766
1767/// Name the binding now loading by the file a dispatcher found (a runtime `.rhai` binding), before it runs: its
1768/// `(Loading …` note names that path even when the binding logs inside it (#560, #945).
1769pub fn name_loading_binding(path: &str) { rename_deferred_note(&s!("Loading {path}")); }
1770
1771// in the spirit of Perl's Package::loadLTXML
1772fn _load_binding(internal: bool, request: &str, reloadable: bool) -> Result<Option<BindingSource>> {
1773  // Perl loadLTXML L2311-2313: skip if already loaded, unless reloadable
1774  // (e.g. `\inputencoding{cp1251}` re-invokes cp1251.def to re-register
1775  // DeclareInputText mappings after `set_input_encoding` reset them).
1776  // OXIDIZED_DESIGN #23: binding load gates ONLY on the binding-specific
1777  // `_loaded` flag (set on success below). A prior raw load
1778  // (`_raw_loaded`) does NOT preclude the binding from loading — they
1779  // are independent paths. Mirrors Perl `loadLTXML` (Package.pm L2311).
1780  let loaded_key = s!("{request}_loaded");
1781  // A file that un-marks itself loaded (fontenc.sty tail; see `already_handled`)
1782  // is loaded afresh on every request.
1783  let unmarks_itself = lookup_bool(&s!("{request}_unmarks_itself"));
1784  if !reloadable && !unmarks_itself && lookup_bool(&loaded_key) {
1785    // Already loaded; the source path is not retained across loads, and the
1786    // announce site short-circuits on `already_handled` before reaching here,
1787    // so reporting an unknown (`None`) source is correct.
1788    return Ok(Some(None));
1789  }
1790
1791  // Re-entrance guard for binding loads: track which bindings are
1792  // currently mid-load on this thread, so that if a binding body
1793  // transitively calls require_package(SAME_NAME) (e.g. via
1794  // \citet → OmniBus closure → require_package(natbib) firing
1795  // during natbib's own ProcessOptions chain), we short-circuit
1796  // instead of re-entering the dispatcher and looping. Task #260.
1797  thread_local! {
1798    static IN_PROGRESS: std::cell::RefCell<rustc_hash::FxHashSet<String>> =
1799      std::cell::RefCell::new(rustc_hash::FxHashSet::default());
1800  }
1801  let request_key = request.to_string();
1802  let already_loading = IN_PROGRESS.with(|s| s.borrow().contains(&request_key));
1803  if already_loading {
1804    // A package or class that requires a package which requires it back (thmtools.sty:47-49
1805    // `\RequirePackage{thm-restate}`, thm-restate.sty:26 `\RequirePackage{thmtools}`) ends the cycle
1806    // silently in LaTeX: `\ProvidesPackage` defines `\ver@<file>` before the body runs, so the inner
1807    // `\RequirePackage` finds it loaded. Perl does the same by marking `<request>_loaded` before `do
1808    // $pathname` (Package.pm:2332). So a re-entrant .sty/.cls request is an Info; any other re-entrance (a
1809    // pool, task #260's natbib loop) keeps the Warning.
1810    let message = s!(
1811      "Binding-load re-entrance for '{}' (transitive require_package \
1812       during its own LoadDefinitions). Short-circuiting to break the \
1813       loop; binding's pending side-effects (DefMacro, Let, etc.) \
1814       will still complete in the outer frame.",
1815      request_key
1816    );
1817    if request_key.ends_with(".sty") || request_key.ends_with(".cls") {
1818      Info!("recursion", &request_key, message);
1819    } else {
1820      Warn!("recursion", &request_key, message);
1821    }
1822    return Ok(Some(None));
1823  }
1824
1825  // Normalize both dispatcher slots to one resolving closure so the shared
1826  // unlock / in-progress guards wrap a single call. The main slot already
1827  // reports a `BindingSource`; the extra (compiled) slot never has one, so its
1828  // success maps to `None`.
1829  type Resolver = Box<dyn Fn(&str) -> Option<Result<BindingSource>>>;
1830  let taken_dispatcher: Option<Resolver> = if internal {
1831    get_bindings_dispatch().map(|d| Box::new(move |r: &str| d(r)) as Resolver)
1832  } else {
1833    get_extra_bindings_dispatch()
1834      .map(|d| Box::new(move |r: &str| d(r).map(|res| res.map(|()| None))) as Resolver)
1835  };
1836  match taken_dispatcher {
1837    Some(ref dispatcher) => {
1838      // Perl `Package.pm:loadLTXML L2318` wraps the binding-load body in
1839      // `local $UNLOCKED = 1`, allowing bindings to override prior
1840      // (locked) definitions. The guard auto-pops on drop.
1841      let _unlock_guard = local_state_unlocked_guard(true);
1842      // Mark in-progress for the duration of this dispatcher call.
1843      IN_PROGRESS.with(|s| {
1844        s.borrow_mut().insert(request_key.clone());
1845      });
1846      struct InProgressGuard(String);
1847      impl Drop for InProgressGuard {
1848        fn drop(&mut self) {
1849          let key = self.0.clone();
1850          IN_PROGRESS.with(|s| {
1851            s.borrow_mut().remove(&key);
1852          });
1853        }
1854      }
1855      let _in_progress_guard = InProgressGuard(request_key);
1856      let _request_guard = BindingRequestGuard::enter(request);
1857      // Perl loadLTXML's `(Loading <path>...` opens before the binding runs (Core/Mouth/Binding.pm:31), so what it
1858      // loads nests inside; the dispatcher both finds and runs the binding, so the note waits to know (#945).
1859      let note = DeferredNote::begin(&s!("Loading {}", binding_note_name(request, None)));
1860      let result_opt = dispatcher(request);
1861      if let Some(Ok(Some(source))) = &result_opt {
1862        rename_deferred_note(&s!("Loading {}", binding_note_name(request, Some(source))));
1863      }
1864      note.end(result_opt.is_some());
1865      match result_opt {
1866        Some(result) => {
1867          // Here and only here we are certain we have binding support.
1868          // Preemptively mark as loaded to avoid recursion.
1869
1870          // Mark binding as loaded (raw `<request>_raw_loaded` is tracked
1871          // separately by load_tex_definitions). Per OXIDIZED_DESIGN #23.
1872          assign_value(&loaded_key, true, Some(Scope::Global));
1873          // `result` is `Result<BindingSource>`; wrap the success in `Some` to
1874          // signal "a binding loaded" (carrying its source path, if any).
1875          result.map(Some)
1876        },
1877        None => Ok(None),
1878      }
1879    },
1880    None => Ok(None),
1881  }
1882}
1883
1884thread_local! {
1885  /// The requests the bindings now loading answer, innermost last (`epsf.sty`, `epsf.tex`): [`binding_request`].
1886  static BINDING_REQUESTS: std::cell::RefCell<Vec<String>> =
1887    const { std::cell::RefCell::new(Vec::new()) };
1888}
1889
1890/// [`BINDING_REQUESTS`]' entry for one binding load, popped when the load ends however it ends.
1891struct BindingRequestGuard;
1892impl BindingRequestGuard {
1893  fn enter(request: &str) -> Self {
1894    BINDING_REQUESTS.with(|requests| requests.borrow_mut().push(request.to_string()));
1895    FILE_READS.with(|reads| reads.borrow_mut().push(FileRead::Binding));
1896    BindingRequestGuard
1897  }
1898}
1899impl Drop for BindingRequestGuard {
1900  fn drop(&mut self) {
1901    let _ = BINDING_REQUESTS.try_with(|requests| requests.borrow_mut().pop());
1902    let _ = FILE_READS.try_with(|reads| reads.borrow_mut().pop());
1903  }
1904}
1905
1906/// What is being read ([`FILE_READS`]), for [`provides_request`].
1907#[derive(Clone)]
1908enum FileRead {
1909  /// A binding's code.
1910  Binding,
1911  /// A file read raw under the request of the load around it (`\@currname`): a `\usepackage`'s, an `\input`'s.
1912  Current,
1913  /// A file the loader reads raw as a request of its own (`load_tex_definitions`'s `own_request`), by that request.
1914  Own(String),
1915}
1916
1917thread_local! {
1918  /// What is being read now, innermost last ([`FileRead`]).
1919  static FILE_READS: std::cell::RefCell<Vec<FileRead>> =
1920    const { std::cell::RefCell::new(Vec::new()) };
1921}
1922
1923/// [`FILE_READS`]' entry for one raw read, popped when the read ends however it ends.
1924struct RawReadGuard;
1925impl RawReadGuard {
1926  fn enter(own_request: Option<&str>) -> Self {
1927    let read = own_request.map_or(FileRead::Current, |request| {
1928      FileRead::Own(request.to_string())
1929    });
1930    FILE_READS.with(|reads| reads.borrow_mut().push(read));
1931    RawReadGuard
1932  }
1933}
1934impl Drop for RawReadGuard {
1935  fn drop(&mut self) { let _ = FILE_READS.try_with(|reads| reads.borrow_mut().pop()); }
1936}
1937
1938/// The file request the innermost binding now loading answers, with its extension (`epsf.sty` for `\usepackage{epsf}`
1939/// and for `\input epsf.sty`, `epsf.tex` for `\input epsf`): the file TeX would read, which a binding serving several
1940/// spellings of one file may need to tell apart where `\@currname`/`\@currext` cannot, an `\input` leaving them unset
1941/// (epsf_sty.rs `epsf_resets_globally`; 0906.1361, astro-ph0006390, astro-ph0109126, astro-ph0410051,
1942/// astro-ph9701125). `None` outside a binding's load.
1943pub fn binding_request() -> Option<String> {
1944  BINDING_REQUESTS.with(|requests| requests.borrow().last().cloned())
1945}
1946
1947// Factor out handling and passing loading options from input_content,
1948// to simplify main routine
1949fn before_input_handle_options(
1950  options: &mut InputDefinitionOptions,
1951  prevname: &str,
1952  prevext: &str,
1953  name: &str,
1954  as_type: &str,
1955) -> Result<bool> {
1956  // Perl-faithful translation of Package.pm:2578-2591:
1957  //
1958  //   my $pushpop = LookupDefinition(T_CS('\@pushfilename'))
1959  //              && LookupDefinition(T_CS('\@popfilename'));
1960  //   if ($pushpop) {
1961  //     Digest(Tokens(T_CS('\@pushfilename'),
1962  //         T_BEGIN, T_END, T_BEGIN, T_END, T_BEGIN, Explode($name), T_END));
1963  //   } else {
1964  //     Digest(T_CS('\lx@pushfilename'));
1965  //   }
1966  //
1967  // The 3 trailing brace-arg pairs `{}{}{name}` feed
1968  // `\@expl@push@filename@aux@@` (which the dump's `\@pushfilename`
1969  // body chains into) — that aux takes 3 args. Without them it reads
1970  // 3 garbage tokens from the input stream, corrupting the
1971  // `\g__hook_name_stack_seq` push. Subsequent `\@popfilename`
1972  // then sees an empty/corrupt seq, fires `\msg_error:nn{hooks}{extra-pop-label}`,
1973  // whose `\use:e` (=`\edef`) chain expands `\q_no_value` and triggers
1974  // recursion-detect. See docs/sandbox_failures_SYNC_STATUS.md
1975  // "\q_no_value cascade" for the full investigation.
1976  let push_defined = lookup_definition(&T_CS!("\\@pushfilename"))?.is_some();
1977  let pop_defined = lookup_definition(&T_CS!("\\@popfilename"))?.is_some();
1978  let pushpop = push_defined && pop_defined;
1979  if pushpop {
1980    let mut pushtoks = vec![
1981      T_CS!("\\@pushfilename"),
1982      T_BEGIN!(),
1983      T_END!(),
1984      T_BEGIN!(),
1985      T_END!(),
1986      T_BEGIN!(),
1987    ];
1988    pushtoks.extend(Explode!(name));
1989    pushtoks.push(T_END!());
1990    digest(Tokens::new(pushtoks))?;
1991  } else {
1992    digest(T_CS!("\\lx@pushfilename"))?;
1993  }
1994
1995  // For \RequirePackageWithOptions, pass the options from the outer class/style to the inner one.
1996  if let Some(with_options_to_pass) = options.withoptions.take()
1997    && !prevname.is_empty()
1998    && has_value(&s!("opt@{}.{}", prevname, prevext))
1999  {
2000    // Only pass those class options that are declared by the package!
2001    let mut topass = Vec::new();
2002    with_vecdeque("@declaredoptions", |vdq_opt| {
2003      if let Some(declared_options) = vdq_opt {
2004        for op in with_options_to_pass.into_iter() {
2005          if declared_options.iter().any(|x| {
2006            if let Stored::String(val) = x {
2007              arena::with(*val, |str| str == op)
2008            } else {
2009              false
2010            }
2011          }) {
2012            topass.push(op)
2013          }
2014        }
2015      }
2016    });
2017    if !topass.is_empty() {
2018      pass_options(name, as_type, topass)?;
2019    }
2020  }
2021  // Use letter-catcode (`ExplodeText`) for `\@currext` / `\@currname` so
2022  // they match `\@pkgextension`-style build-time-tokenized macros under
2023  // `\ifx`. Without this the catcodes diverge — `\@pkgextension` from a
2024  // compile-time `DefMacro!("\\@pkgextension", "sty")` tokenizes "sty"
2025  // as letters (default LaTeX catcode 11), but the previous `Explode!`
2026  // used here produces OTHER catcode tokens, so kvoptions's
2027  // `\ifx\@currext\@pkgextension` always returned false — vendor
2028  // `\PackageError{kvoptions}{\ProcessLocalKeyvalOptions is intended
2029  // for packages only}` then fired on every package that uses kvoptions
2030  // (rerunfilecheck reaches this via the hyperref backend `.def` chain).
2031  // Witnesses: arXiv:cond-mat/9611206, math/9904040, math/9904041.
2032  def_macro(
2033    T_CS!("\\@currname"),
2034    None,
2035    Tokens!(ExplodeText!(name)),
2036    None,
2037  )?;
2038  def_macro(
2039    T_CS!("\\@currext"),
2040    None,
2041    Tokens!(ExplodeText!(as_type)),
2042    None,
2043  )?;
2044  // reset options (Note reset & pass were in opposite order in LoadClass ????)
2045  reset_options()?;
2046  pass_options(name, as_type, options.options.clone())?;
2047
2048  // Note which packages are pretending to be classes.
2049  if options.as_class {
2050    push_value("@masquerading@as@class", arena::pin(name))?;
2051  }
2052  let current_opt_val = with_vecdeque(&s!("opt@{}.{}", name, as_type), |vdq_opt| match vdq_opt {
2053    Some(vdq) => {
2054      // Both item shapes the option list carries: `String` (one option) and
2055      // `Strings` (a `--preload='[a,b]pkg'` / batched pass). The latter used to
2056      // be skipped, leaving `\opt@<pkg>` EMPTY for preload options — harmless
2057      // while `process_options` read the list, fatal once it reads the macro
2058      // (latex.ltx `\@ptionlist`): `rawstyles` silently off.
2059      let mut pieces: Vec<String> = Vec::new();
2060      for x in vdq.iter() {
2061        match x {
2062          Stored::String(val) => pieces.push(arena::with(*val, |str| str.to_string())),
2063          Stored::Strings(vals) => {
2064            for val in vals.iter() {
2065              pieces.push(arena::with(*val, |str| str.to_string()));
2066            }
2067          },
2068          _ => {},
2069        }
2070      }
2071      pieces.join(",")
2072    },
2073    None => String::new(),
2074  });
2075  // Standard-catcode tokenization for the stored option list (as the
2076  // `\@raw@opt@` sibling above): real LaTeX stores the `\usepackage[...]`
2077  // ARGUMENT tokens, so alphabetic chars are LETTER (catcode 11) and `{`/`}`
2078  // group. kvoptions/keyval `\setkeys` then binds a `\DeclareString-Option`
2079  // value (e.g. `\axp@bibliography`) from these tokens, and packages
2080  // validate it with the catcode-SENSITIVE `ifthen` `\equal` (or `\ifx`):
2081  // `Explode!` (all OTHER) made `\equal{\axp@bibliography}{common}`
2082  // spuriously fail and apxproof raised `unsupported option
2083  // bibliography=common` (witness docs/known_crashes — gdsm.tex, apxproof +
2084  // biblatex). `ExplodeText!` fixed the letters but left `{`/`}` as OTHER,
2085  // so a braced value with commas fell apart in every brace-aware consumer:
2086  // l3clist split `thesis={type=dr,dr=rernat}` at its inner comma
2087  // (URspecialopts `\clist_set:cx {…}{\@ptionlist{…}}`; witness
2088  // DEMO-TUDaPhD, `\department`/`\affidavit` undefined because
2089  // tudathesis.cfg was never input) and xkeyval's `\ProcessOptionsX` read
2090  // `stylemods={mcols,bookindex}` as the style `glossary-{mcols.sty`
2091  // (glossaries-extra.sty:811 `\@for`; witness glossaries-user). Guard:
2092  // `perfect_kernel_batch53::opt_macro_keeps_braced_option_values`.
2093  def_macro(
2094    T_CS!(s!("\\opt@{}.{}", name, as_type)),
2095    None,
2096    zapped_options(current_opt_val)?,
2097    None,
2098  )?;
2099  Ok(pushpop)
2100}
2101
2102/// The option list stored in `\opt@<file>`: latex.ltx:18514-18517 `\protected@xdef` of `\zap@space#2 \@empty`. Under
2103/// the kernel's `\zap@space` (sect01.rs keeps a copy, `\lx@kernel@zap@space`) that is [`zap_space`]; a package that lets
2104/// its own `\zap@space` around a load is honored by expanding the list as latex.ltx does: tikz-timing.sty:2331-2341
2105/// `\let\zap@space\tikztiming@zap@space` (`#1 \@empty{#1}`, the list as given) around `\RequirePackage[…]{tikz-timing-…}`,
2106/// so `\usetikztiminglibrary[rising arrows]{clockarrows}` stores `rising arrows`, the key the library declares (witness
2107/// 2409.18120; the zapped `risingarrows` was an unknown key). Guard
2108/// `perfect_kernel_batch79x::a_package_zap_space_keeps_the_option_spaces`.
2109fn zapped_options(options: String) -> Result<Tokens> {
2110  if options.is_empty() || x_equals(&T_CS!("\\zap@space"), &T_CS!("\\lx@kernel@zap@space")) {
2111    return Ok(crate::mouth::tokenize_internal(TeXString::assembled(
2112      zap_space(&options),
2113    )));
2114  }
2115  let mut list = vec![T_CS!("\\zap@space")];
2116  list.extend(crate::mouth::tokenize_internal(TeXString::assembled(options)).unlist());
2117  list.extend([T_SPACE!(), T_CS!("\\@empty")]);
2118  do_expand(Tokens::new(list))
2119}
2120
2121/// latex.ltx:18695-18698 `\zap@space`, as latex.ltx:18517/18757 apply it to the option list stored in `\opt@<file>`
2122/// (`\zap@space#2 \@empty`): every space outside braces goes — the delimiter `#1 ` does not see a space inside a
2123/// group — so `share counter=true` is stored `sharecounter=true`, the name l3keys2e looks up for a key an expl3 package
2124/// declared as `share counter` (spaces are ignored under `\ExplSyntaxOn`; witness 2607.15530, its pomegranate.sty).
2125/// `\@raw@opt@<file>` keeps the list as given. A control space (`\ `) is a control sequence, not a space, and stays, as
2126/// does the space ending a control word (no token: it keeps the word apart when the list is tokenized again).
2127/// Guard `perfect_kernel_batch70b::opt_macro_drops_spaces_as_zap_space`.
2128fn zap_space(options: &str) -> String {
2129  let mut zapped = String::with_capacity(options.len());
2130  let mut depth = 0usize;
2131  let mut escaped = false;
2132  let mut control_word = false;
2133  for c in options.chars() {
2134    if escaped {
2135      escaped = false;
2136      control_word = c.is_ascii_alphabetic();
2137      zapped.push(c);
2138      continue;
2139    }
2140    if control_word && c.is_ascii_alphabetic() {
2141      zapped.push(c);
2142      continue;
2143    }
2144    let ends_word = std::mem::take(&mut control_word);
2145    match c {
2146      '\\' => escaped = true,
2147      '{' => depth += 1,
2148      '}' => depth = depth.saturating_sub(1),
2149      ' ' | '\t' | '\n' | '\r' if depth == 0 && !ends_word => continue,
2150      _ => {},
2151    }
2152    zapped.push(c);
2153  }
2154  zapped
2155}
2156
2157/// configuration for input of a TeX source (content files mostly)
2158#[derive(Debug, Default, Clone)]
2159pub struct InputOptions {
2160  pub noerror:    bool,
2161  pub reloadable: bool,
2162  pub file_type:  Option<String>,
2163  /// LaTeX's `\input{…}` (`\@iinput`, `\InputIfFileExists`): a content file runs the file hooks around it
2164  /// (`input_content_with_file_hooks`); TeX's `\@@input` runs none.
2165  pub file_hooks: bool,
2166}
2167
2168/// Input for cases when the file (or data)
2169/// is plain TeX material that is expected to contribute content
2170/// to the document (as opposed to pure definitions).
2171///
2172/// A Mouth is opened onto the file, and subsequent reading
2173/// and/or digestion will pull Tokens from that Mouth until it is
2174/// exhausted, or closed.
2175///
2176/// In some circumstances it may be useful to provide a string containing
2177/// the TeX material explicitly, rather than referencing a file.
2178/// In this case, the `literal` pseudo-protocal may be used.
2179pub fn input_content(request: &str, options: InputOptions) -> Result<()> {
2180  let filepath = find_file(request, None);
2181  match filepath {
2182    // TODO: type => $options{type}, noltxml => 1
2183    Some(path) => load_tex_content(&path, options),
2184    None => {
2185      // Perl Package.pm L2227-2233: `if (FindFile(...)) { loadTeXContent(...); }
2186      // elsif (!$options{noerror}) { Error('missing_file', $request, ..., ...); }`
2187      // Recoverable Error, NOT Fatal. Pre-fix, the Rust port emitted a
2188      // `fatal!(Package, MissingFile)` that terminated the conversion on any
2189      // missing-but-non-critical input — over-fatal-izing relative to Perl.
2190      if !options.noerror {
2191        Error!(
2192          "missing_file",
2193          request,
2194          format!("Can't find TeX file {request}")
2195        );
2196      }
2197      Ok(())
2198    },
2199  }
2200}
2201
2202/// LaTeX file substitution (latex.ltx:19677-19716 `\declare@file@substitution`,
2203/// applied by `\set@curr@file` → `\__filehook_file_subst_begin:nnn`,
2204/// latex.ltx:19785-19810): `\input`, `\InputIfFileExists` and friends read
2205/// the REPLACEMENT when a `\@file-subst@<name><ext>` macro exists. The key
2206/// is the request's basename (the directory is dropped on both sides,
2207/// `\use_ii_iii:nnn`) with `.tex` supplied for a missing extension
2208/// (`\__filehook_subst_empty_name_chk:NN`); the value is the composed
2209/// replacement name. Chains are followed with the same bound as the
2210/// kernel's tortoise/hare loop. Perl has no such step (its `\input` binding
2211/// bypasses `\set@curr@file`, Package.pm:2248-2270), so it re-reads the
2212/// ORIGINAL file: tikzlings-doc.tex:73-75 substitutes each animal `.sty` by
2213/// the `\jobname.cif` its comment harvester just wrote and `\input`s it —
2214/// without the substitution the raw `.sty` re-executes in the document body
2215/// (`\RequirePackage` "only in the preamble", `@threeD` text leaks) and the
2216/// per-animal documentation is lost. Guard:
2217/// `perfect_kernel_batch52::input_honors_file_substitution`.
2218pub fn substitute_file_request(request: &str) -> Option<String> {
2219  let mut current = request.to_string();
2220  let mut result = None;
2221  for _ in 0..8 {
2222    let base = current
2223      .rsplit(['/', '\\'])
2224      .next()
2225      .unwrap_or(&current)
2226      .to_string();
2227    let key = if base.contains('.') {
2228      base
2229    } else {
2230      s!("{base}.tex")
2231    };
2232    let cs = T_CS!(s!("\\@file-subst@{key}"));
2233    if lookup_definition(&cs).ok().flatten().is_none() {
2234      break;
2235    }
2236    let Ok(next) = do_expand(cs) else { break };
2237    let next = next.to_string().trim().to_string();
2238    if next.is_empty() || next == current {
2239      break;
2240    }
2241    current = next.clone();
2242    result = Some(next);
2243  }
2244  result
2245}
2246
2247/// This is essentially the `\input` equivalent
2248///
2249/// we are most likely expecting to get actual content,
2250/// (possibly with definitions included, as well)
2251/// but might actually be getting pure definitions,
2252/// (like a proper style file)
2253/// in which case we may really want to load a binding.
2254/// Note that generic style files (non-latex) often have a .tex extension.
2255pub fn input(request: &str, options: InputOptions) -> Result<()> {
2256  // A `"` quotes and is no part of a name, and then a name's surrounding blanks are no part of it either: l3file's
2257  // `\__kernel_file_name_sanitize:n` strips the quotes, then trims (expl3-code.tex:12431-12438), so pdflatex reads
2258  // `x;y.tex` for `\input{" x;y"}`, `\input{ x.tex}` and `\input{dir/x }` (tex.web §526 skips leading blanks too).
2259  // Perl's `Input` strips only a wrapping run of quotes and keeps the blanks (2109.01356 `\input{ data_table.tex}`,
2260  // 2509.24347 `\input{paper/encoding }`; KNOWN_PERL_ERRORS #1151, #425).
2261  let unquoted = request.replace('"', "");
2262  let clean_req: Cow<str> = Cow::Borrowed(unquoted.trim());
2263  let clean_req: Cow<str> = match substitute_file_request(&clean_req) {
2264    Some(subst) => Cow::Owned(subst),
2265    None => clean_req,
2266  };
2267  // HEURISTIC! First check if equivalent style file, but only under very specific circumstances
2268  // if pathname_is_literaldata(request) {
2269  //   let (dir, name, ftype) = pathname_split(request);
2270  //   let file = name;
2271  //   if !ftype.is_empty() {
2272  //     file += format!(".{}",ftype);
2273  //   }
2274  //   let path;
2275  //   // Firstly, check if we are going to OVERRIDE the requested raw .tex file
2276  //   // with a latexml binding to a style file.
2277  //   if ((dir.is_empty() && (ftype.is_empty() || (ftype == "tex"))  // No SPECIFIC directory, but
2278  // a raw tex file.       // AND, in preamble; SHOULD be style file, OR also if we can't find the
2279  // raw file.     && (LookupValue!("inPreamble") || !FindFile(file))
2280  //     && (path = FindFile(name, type => 'sty', notex => 1))) { // AND there IS such a style file
2281  //     Info!("ignore", request, stomach.get_gullet(),
2282  //       s!("Ignoring input of tex {}, using package {} instead", request, name));
2283  //     RequirePackage!(name); // Then override, assuming we'll find name as a package file!
2284  //     return;
2285  //   }
2286  // }
2287  // // Next special case: If we were currently reading a "known" style or binding file,
2288  // // then this file, even if .tex, must also be definitions rather than content.!!(?)
2289  // Check for *.latexml source-level bindings first — these are always handled
2290  // as definitions regardless of INTERPRETING_DEFINITIONS state.
2291  // Mirrors Perl's automatic .latexml file loading mechanism.
2292  if clean_req.ends_with(".latexml") {
2293    return input_definitions(&clean_req, InputDefinitionOptions::default());
2294  }
2295  if lookup_bool_sym(crate::pin!("INTERPRETING_DEFINITIONS")) {
2296    // A reader that set `\everyeof` takes the file as a token list (eTeX §362; expl3's `\file_get:nnN`), not a
2297    // definitions load: OXIDIZED_DESIGN_DIVERGENCES #1029 (the TL 2026 format build's glyphtounicode.tex).
2298    if everyeof_is_set()
2299      && let Some(path) = find_file(&clean_req, None)
2300    {
2301      return read_as_token_list(&path);
2302    }
2303    // TeX's `\input` reads the file on every call; only `\usepackage` /
2304    // `\RequirePackage` load once (latex.ltx `\@ifl@aded`). Perl routes an
2305    // `\input` met while reading definitions to InputDefinitions
2306    // (Package.pm:2287-2288), whose loadTeXDefinitions skips a file already
2307    // read (:2363 `return if LookupValue($request.'_loaded') && !reloadable`).
2308    // tuenc-greek.def:126 re-inputs greek-fontenc.def with `\LastDeclaredEncoding`
2309    // = TU after lgrenc.def read it for LGR (`\usepackage[LGR,TU]{fontenc}`);
2310    // the skipped read left `\TU\greekscript` and `\TU\LGR@hiatus` undeclared,
2311    // so babel-greek's `\greekscript` fell back to textalpha's switch to LGR
2312    // (`\MakeUppercase{\'u}` → ϒ) and the uppercase hiatus lost its dialytika
2313    // (ΑΥΛΟΣ; greek-fontenc test-tuenc-greek, lualatex ΑΫΛΟΣ). A file read RAW
2314    // before is therefore read again; a binding stands for the whole package
2315    // and stays once-only (the re-read never reaches the binding
2316    // dispatch, `reread` not `noltxml`: no `\@currname` directory
2317    // resolution). Guard: `greek_text::input_rereads_a_raw_definitions_file`.
2318    let reread_raw = |filename: &str| {
2319      lookup_bool(&s!("{filename}_raw_loaded")) && !lookup_bool(&s!("{filename}_loaded"))
2320    };
2321    // Split a binding extension off the request so input_definitions sees
2322    // (name, extension) — matches Perl Package.pm `FindFile` / `Input`
2323    // semantics. Without the split, `find_file_fallback` runs with
2324    // `ext_type=""` and reconstructs `"<base>."` (no extension), which
2325    // never matches a registered binding. Witness: hep-ph9911514 — the
2326    // raw-loaded `elsartwb.sty` issues `\input elsart12\@ptsize.sty` →
2327    // `\input{elsart12.sty}`; the version-strip fallback (elsart12 →
2328    // elsart) needs `ext_type="sty"` to reconstruct `"elsart.sty"` for
2329    // the binding lookup. Perl recovers `\ack` cleanly via this path; the
2330    // earlier Rust port dropped the extension and the fallback never
2331    // resolved.
2332    let has_dir = clean_req.contains('/') || clean_req.contains('\\');
2333    if !has_dir
2334      && let Some((stem, ext)) = clean_req.rsplit_once('.')
2335      && is_binding_extension(ext)
2336    {
2337      let reread = reread_raw(&clean_req);
2338      return input_definitions(stem, InputDefinitionOptions {
2339        extension: Some(Cow::Owned(ext.to_string())),
2340        // A content `.tex` re-reads every time (see below).
2341        reloadable: ext == "tex" || reread,
2342        reread,
2343        ..InputDefinitionOptions::default()
2344      });
2345    }
2346    // A plain content `.tex` (no binding extension) is `\input` material
2347    // even while a `.sty`/`.cls` is being read: TeX re-reads it every time
2348    // (Perl `Input`/`loadTeXContent` likewise), so the once-only PACKAGE
2349    // guard (`already_handled`) must not apply. babel.sty:4210-4227 inputs
2350    // `babel-<lang>.tex` once per language occurrence; with french as BOTH a
2351    // class option and `main=french` the second read was skipped, its
2352    // `\BabelBeforeIni` descriptor never recorded, and french.ldf (→ `\og`,
2353    // `\ieme`) never loaded (paresse-fra; `\documentclass[french]{…}` +
2354    // `main=french`). Guard: `perfect_kernel_batch54::content_tex_reinput_during_definitions_rereads`.
2355    // It is read under the current catcodes, as TeX's `\input` reads. Only a request with a directory or with no binding
2356    // extension (`.clo`, `.txt`, none) comes here: the `is_binding_extension` branch above still forces `@` to letter. The
2357    // definitions mouth's forced `@`-letter broke CoverPage.sty:58-70, which makes `@` the escape character and
2358    // inputs `\jobname.BibTeX.txt` so that `@article{…}` runs `\article` — the cover page printed "title
2359    // undefined" (coverpage SimpleSample; Perl Package.pm:2287-2288 + Mouth.pm:98-100 alike). Inside a package `@`
2360    // is already a letter, so only a package that changed it sees the difference.
2361    // Guard: `perfect_kernel_batch61::input_from_a_package_keeps_the_catcodes`.
2362    let is_plain_tex = clean_req.ends_with(".tex") || !clean_req.contains('.');
2363    let reread = reread_raw(&clean_req);
2364    return input_definitions(&clean_req, InputDefinitionOptions {
2365      reloadable: is_plain_tex || reread,
2366      reread,
2367      at_letter: false,
2368      ..InputDefinitionOptions::default()
2369    });
2370  }
2371  // Perl Package.pm L2109-2113: FindFile_aux checks for `"$file.ltxml"` in
2372  // $ltxml_paths BEFORE consulting raw TeX paths. In Rust the bindings are
2373  // compile-time dispatch tables rather than on-disk .ltxml files, so the
2374  // equivalent check is: if a binding dispatcher responds to `<name>.tex`,
2375  // load it (matching `\input harvmac` → `harvmac.tex.ltxml` preference
2376  // over a local `harvmac.tex`). Skip when the request carries a directory
2377  // (explicit local path).
2378  // Under `\everyeof` the file itself is read, never a binding (#1029; `\file_get:nnN{ltluatex}`, revWIN1).
2379  let binding_loaded = !everyeof_is_set() && {
2380    let has_dir = clean_req.contains('/') || clean_req.contains('\\');
2381    // Perl Package.pm:2109-2113 + 2255-2270: when `\input{name}` or
2382    // `\input{name.<ext>}` resolves to a known binding extension AND a
2383    // binding for `(name, ext)` is reachable, route to the binding
2384    // instead of the on-disk raw file. Without this, papers using
2385    // literal `\input{psfig.sty}` (common 1996-2005 idiom) fail because
2386    // TL2025 dropped the on-disk file even though Rust has the binding.
2387    //
2388    // Extensions handled dynamically via `is_binding_extension`: any
2389    // extension registered by `latexml_package` or `latexml_contrib`
2390    // (cls / sty / def / fontmap / ldf / ltx / lua / pool / tex /
2391    // code.tex / ...) is admitted, gating out `\input{foo.eps}`-style
2392    // content paths.
2393    //
2394    // For .tex / no-extension paths we still use `load_binding` (exact
2395    // dispatch lookup on `<name>.tex`) — a `<name>.tex` request is
2396    // semantically "include this content", so suffix-stripping fallback
2397    // (e.g. `mysetup.tex` → `setup.tex.ltxml`) would surprise more than
2398    // it helps.
2399    //
2400    // For .sty / .cls / .def / etc — the binding-extension cases — we
2401    // route through `input_definitions`, which gives us the full Step
2402    // 1 → Step 3 → Step 4 ladder including `find_file_fallback`'s
2403    // version-suffix strip. This is what makes `\input{psfig.sty}`
2404    // pick up `psfig_sty.rs` AND a versioned `\input{<pkg>2.sty}` fall back to
2405    // `<pkg>_sty.rs` exactly as Perl Package.pm:2266 does via
2406    // `RequirePackage($name)`.
2407    if !has_dir {
2408      let ext = clean_req.rsplit('.').next().unwrap_or("");
2409      let no_ext = ext == clean_req.as_ref();
2410      if no_ext || ext == "tex" {
2411        let tex_name = if ext == "tex" {
2412          clean_req.to_string()
2413        } else {
2414          s!("{}.tex", clean_req)
2415        };
2416        let stand_in = crate::binding::author_files::stands_in_for_an_author_file(&tex_name);
2417        let stem = tex_name.strip_suffix(".tex").unwrap_or(&tex_name);
2418        let loaded = {
2419          let _stand_in = stand_in.then(crate::definition::origin::StandInLoadGuard::new);
2420          // (its name, for the packages its load loads first, as a package or class stand-in's: mssymb.tex's
2421          // amsfonts and amssymb, `<file>:loaded_by_stand_in`; guard
2422          // `perfect_kernel_batch77w::tex_stand_in_names_its_package_loads`)
2423          let _stand_in_name = stand_in.then(|| StandInBindingName::enter(file_stem(stem)));
2424          load_binding(&tex_name)?.is_some() || load_external_binding(&tex_name)?.is_some()
2425        };
2426        if loaded && stand_in {
2427          read_stand_in_copy(stem, stem, "tex", false)?;
2428        }
2429        loaded
2430      } else if is_binding_extension(ext)
2431        && !(lookup_catcode('%') != Some(Catcode::COMMENT) && find_file(&clean_req, None).is_some())
2432      {
2433        // Not while `%` is ignored or other: doc.sty:895-897 `\DocInput{#1}` is
2434        // `\MakePercentIgnore\input{#1}\MakePercentComment`, reading the raw
2435        // file as its documentation, which a binding (standing in for the
2436        // package's definitions) does not carry. frankenstein/newclude.tex:65
2437        // `\DocInput{newclude.sty}` came out empty (recall 1.1 %) because the
2438        // Rust-only newclude_sty.rs answered, where its binding-less siblings
2439        // typeset (attrib 93 %, compsci 98 %, sweep 120). `\usepackage` does not
2440        // come here, so the binding still serves the package.
2441        // Route through input_definitions for fallback-aware dispatch.
2442        // The `name` arg expects no extension, so split it off.
2443        let name = clean_req
2444          .strip_suffix(&format!(".{}", ext))
2445          .unwrap_or(&clean_req)
2446          .to_string();
2447        // `notex: true` — only BINDING dispatch here (compiled, external,
2448        // version-strip fallback). A raw on-disk file must instead fall
2449        // through to the content path below, which reads it under the
2450        // CURRENT catcodes like real TeX's `\input`. The definitions
2451        // mouth forces `@`=letter (mouth.rs at_letter), which corrupted
2452        // doc.sty's `\CharacterTable` self-check on every
2453        // `\DocInput{<name>.sty}` re-read: the stored table (built after
2454        // doc.sty L834 \makeatother) has `\@` as control SYMBOL + space,
2455        // the @-letter re-read tokenizes `\@` as a control WORD that
2456        // swallows the spaces, and the L827 \ifx fails — "Character
2457        // table corrupted" ×11 docs (frankenstein bundle, pkgloader,
2458        // whose own log had the A/B: definitions-path load corrupted,
2459        // content-path load of the SAME file correct). Perl passes only
2460        // by skipping the re-read entirely (Package.pm L2265
2461        // reloadable=false) and thereby drops the documentation body.
2462        let result = input_definitions(&name, InputDefinitionOptions {
2463          extension: Some(Cow::Owned(ext.to_string())),
2464          noerror: true,
2465          reloadable: true,
2466          notex: true,
2467          ..InputDefinitionOptions::default()
2468        });
2469        // input_definitions returns Err on not-found with noerror=true;
2470        // treat that as "binding not loaded, fall through to raw".
2471        result.is_ok()
2472      } else {
2473        false
2474      }
2475    } else {
2476      false
2477    }
2478  };
2479  if binding_loaded {
2480    Ok(())
2481  } else if let Some(path) = find_file(&clean_req, None) {
2482    // Found something plausible. Perl Package.pm:2289-2302 routes a
2483    // `pathname_is_raw` non-`.tex` file (sty/cls/def/…) to
2484    // `loadTeXDefinitions` — `@`=letter, text suppressed and, because
2485    // `\input` passes no `reloadable`, a SECOND `\input`/`\DocInput` of the
2486    // same file is a no-op (its `_loaded` gate). Real TeX's `\input` always
2487    // reads the file as CONTENT under the current catcodes, and that is what
2488    // we do (batches 7/52): tikzlings-doc.tex:60-72 harvests each animal
2489    // `.sty` line-by-line through `\tex_input:D` under `\c_other_cctab`, and
2490    // doc.sty's `\DocInput{X.sty}` typesets X's documentation body — both
2491    // are content in pdflatex and nothing in Perl. The frankenstein manuals'
2492    // doc bodies (`\cs\attrib` examples, attrib.tex:43/63) do run here and
2493    // still error (PLANS P66) where Perl skips the whole body. Guards:
2494    // `input_routing_and_bbx::document_body_sty_input_is_content_catcodes`,
2495    // `perfect_kernel_batch52::input_rereads_loaded_sty`.
2496    input_content_with_file_hooks(&clean_req, &path, options)
2497  } else {
2498    // Perl heuristic: if the file has no directory, and is a .tex or no extension,
2499    // try loading it as definitions (which checks for binding dispatchers).
2500    // This handles cases like \input tcilatex where tcilatex.tex.ltxml exists.
2501    let has_dir = clean_req.contains('/') || clean_req.contains('\\');
2502    let ext = clean_req.rsplit('.').next().unwrap_or("");
2503    let is_tex_like = ext == clean_req.as_ref() || ext == "tex"; // no extension or .tex
2504    if !has_dir && is_tex_like {
2505      // Try loading as a .tex binding (e.g. tcilatex → tcilatex.tex)
2506      let tex_name = if ext == "tex" {
2507        clean_req.to_string()
2508      } else {
2509        s!("{}.tex", clean_req)
2510      };
2511      if load_binding(&tex_name)?.is_some() {
2512        return Ok(());
2513      }
2514    }
2515    // Couldn't find anything?
2516    note_status(LogStatus::Missing, Some(request));
2517    Error!(
2518      "missing_file",
2519      request,
2520      s!("Can't find TeX file {}", request)
2521    );
2522    Ok(())
2523  }
2524}
2525
2526/// The assignment of a file's names (`\CurrentFile`, `\CurrentFilePath` and their `Used` twins) for `request`, and its
2527/// name: `\__filehook_file_parse_full_name:nN`, the directory without its last `/`, the name with `.tex` when the
2528/// request has no extension, each a string as `\file_parse_full_name:nN` makes it (`outer_text.tex`'s `_` no
2529/// subscript).
2530pub fn file_hook_names(request: &str) -> (Vec<Token>, String) {
2531  let (dir, base) = match request.rsplit_once('/') {
2532    Some((dir, base)) => (dir, base),
2533    None => ("", request),
2534  };
2535  let name = if base.contains('.') {
2536    base.to_string()
2537  } else {
2538    s!("{base}.tex")
2539  };
2540  let mut set = vec![T_CS!("\\@expl@@@filehook@file@pop@assign@@nnnn")];
2541  for part in [dir, &name, dir, &name] {
2542    set.push(T_BEGIN!());
2543    set.extend(Explode!(part));
2544    set.push(T_END!());
2545  }
2546  (set, name)
2547}
2548
2549/// `code` read with the internal catcodes, `\@`-letter (as the code above is written).
2550fn internal_tokens(code: String) -> Vec<Token> {
2551  crate::mouth::tokenize_internal(TeXString::assembled(code)).unlist()
2552}
2553
2554/// latex.ltx:19646-19673 `\InputIfFileExists`, around a content file LaTeX's `\input{…}` reads (`\@iinput`; TeX's
2555/// `\@@input` runs no hooks): the file's names are pushed on ltfilehook's stack and set (`\CurrentFile`,
2556/// `\CurrentFilePath` and their `Used` twins), `file/before` and `file/<name>/before` run, the file is read, its names
2557/// are set again for `file/<name>/after` and `file/after`, and the stack pops back to the enclosing file's. The before
2558/// part runs ahead of the file's tokens in its own input level, the after part where the file ends
2559/// ([`input_file_ended`]). Package and class loads run the same hooks (`use_load_hooks`). Perl fires none (Package.pm
2560/// `Input`), so filehook's `file/before` code never ran and currfile's `\currfiledir` stayed the main file's inside an
2561/// `\input` file: 2110.08325's `\edef\path{\currfiledir}` + `\input{\path/settings}` read `/settings` (missing; its
2562/// TikZ figures undefined).
2563fn input_content_with_file_hooks(request: &str, path: &str, options: InputOptions) -> Result<()> {
2564  let assign = T_CS!("\\@expl@@@filehook@file@pop@assign@@nnnn");
2565  if !options.file_hooks || !load_hooks_active(request)? || lookup_definition(&assign)?.is_none() {
2566    return load_tex_content(path, options);
2567  }
2568  let (set, name) = file_hook_names(request);
2569  let pop = lookup_definition(&T_CS!("\\@expl@@@filehook@file@pop@@"))?.is_some();
2570  let push = lookup_definition(&T_CS!("\\@expl@@@filehook@file@push@@"))?.is_some() && pop;
2571  load_tex_content(path, options)?;
2572  gullet::mark_file_hooks_mouth(gullet::FileHooksEnd {
2573    request: request.to_string(),
2574    pop:     push,
2575  });
2576  let mut before = Vec::new();
2577  if push {
2578    before.push(T_CS!("\\@expl@@@filehook@file@push@@"));
2579  }
2580  before.extend(set);
2581  before.extend(internal_tokens(s!(
2582    "{}{}",
2583    use_hook("file/before", false),
2584    use_hook(&s!("file/{name}/before"), false)
2585  )));
2586  gullet::unread_expansion(Tokens::new(before));
2587  Ok(())
2588}
2589
2590/// `\InputIfFileExists`' code after `\@@input` (latex.ltx:19670-19673, :19655), where a content file read with the
2591/// hooks ends ([`gullet::close_mouth`]): its names set again, `file/<name>/after`, `file/after`, the stack's pop. With
2592/// both hooks empty and the file at a real end, the names are popped here and no token is left
2593/// (OXIDIZED_DESIGN_DIVERGENCES #1196, DG D-48): as LaTeX before 2020-10 read `\InputIfFileExists`, nothing follows
2594/// the file, so a file ending a row (`a & b \\`) leaves the next `\hline`, `\toprule` or `\cline` at the row's start
2595/// (0908.0798, 1106.3602, 1710.05930); TL 2025's non-expandable pop opens a row there ("Misplaced \noalign"). Code in
2596/// a hook keeps TL 2025's reading.
2597pub fn input_file_ended(end: &gullet::FileHooksEnd, forced: bool) -> Result<()> {
2598  let (mut code, name) = file_hook_names(&end.request);
2599  let named = s!("file/{name}/after");
2600  let hooks_empty = [named.as_str(), "file/after"]
2601    .iter()
2602    .all(|hook| crate::binding::def::dialect::hook_use_tokens(hook, false).is_empty());
2603  let digest_now =
2604    hooks_empty && !forced && gullet::scanner_status() == gullet::ScannerStatus::Normal;
2605  if !digest_now {
2606    code.extend(internal_tokens(s!(
2607      "{}{}",
2608      use_hook(&named, false),
2609      use_hook("file/after", false)
2610    )));
2611  }
2612  if end.pop {
2613    code.push(T_CS!("\\@expl@@@filehook@file@pop@@"));
2614  }
2615  if digest_now {
2616    digest(Tokens::new(code))?;
2617  } else {
2618    gullet::unread_expansion(Tokens::new(code));
2619  }
2620  Ok(())
2621}
2622
2623thread_local! {
2624  /// The files read raw as definitions in this conversion ([`load_tex_definitions`]), by canonical path: kept out of
2625  /// the state's tables, which the format dumps record (a host path there would tie a dump to its tree).
2626  static RAW_READ_PATHS: std::cell::RefCell<HashSet<String>> =
2627    std::cell::RefCell::new(HashSet::default());
2628}
2629
2630/// The canonical form of `pathname` for [`RAW_READ_PATHS`].
2631fn canonical_path(pathname: &str) -> String {
2632  std::fs::canonicalize(pathname)
2633    .map(|path| path.to_string_lossy().into_owned())
2634    .unwrap_or_else(|_| pathname.to_string())
2635}
2636
2637/// Has the file at `pathname` been read raw as definitions in this conversion ([`load_tex_definitions`])?
2638fn read_raw_already(pathname: &str) -> bool {
2639  let path = canonical_path(pathname);
2640  RAW_READ_PATHS.with(|paths| paths.borrow().contains(&path))
2641}
2642
2643/// The files read raw as definitions in this conversion (`RAW_READ_PATHS`), canonical: the title-page check reads
2644/// those of the document's own directory for the words the author wrote (latexml_engine
2645/// `base_utilities::frontmatter::title_page_check`). Rust-only.
2646pub fn raw_read_paths() -> Vec<String> {
2647  RAW_READ_PATHS.with(|paths| paths.borrow().iter().cloned().collect())
2648}
2649
2650/// Is `pathname`, read raw as definitions, a class or a file of the document's own directory (a `filecontents` one too)?
2651fn is_own_raw_file(pathname: &str) -> bool {
2652  if pathname::is_literaldata(pathname) {
2653    return false;
2654  }
2655  if pathname.ends_with(".cls") || super::virtual_files::vfs_exists(pathname) {
2656    return true;
2657  }
2658  let directory = lookup_string("SOURCEDIRECTORY");
2659  !directory.is_empty()
2660    && std::fs::canonicalize(&directory).is_ok_and(|directory| {
2661      std::fs::canonicalize(pathname).is_ok_and(|path| path.starts_with(directory))
2662    })
2663}
2664
2665/// [`crate::definition::origin::note_reading_own_file`] for a raw load, put back when it ends.
2666struct OwnFileGuard(bool);
2667impl OwnFileGuard {
2668  fn new(own: bool) -> Self { Self(crate::definition::origin::note_reading_own_file(own)) }
2669}
2670impl Drop for OwnFileGuard {
2671  fn drop(&mut self) { crate::definition::origin::note_reading_own_file(self.0); }
2672}
2673
2674/// Forget the files read raw: a new conversion starts with none (`reset_thread_engine`).
2675pub fn reset_raw_read_paths() { RAW_READ_PATHS.with(|paths| paths.borrow_mut().clear()); }
2676
2677/// The file a stand-in binding loaded as `name` answers, as the paper asked for it: the request a fallback answers
2678/// with this binding (`fallback_request` while `fallback_target` names it: `icml2026` → icml2025.sty, `mysvjour3` →
2679/// svjour3.cls, a path-prefixed class), else `name` (with the directory a basename-keyed binding's request had).
2680fn stand_in_copy_request(name: &str) -> String {
2681  let fallback_request = lookup_string("fallback_request");
2682  let fallback_target = lookup_string("fallback_target");
2683  let stem = |file: &str| file.rsplit(['/', '\\']).next().unwrap_or(file).to_string();
2684  if !fallback_request.is_empty() && stem(&fallback_target).eq_ignore_ascii_case(&stem(name)) {
2685    fallback_request
2686  } else {
2687    name.to_string()
2688  }
2689}
2690
2691/// "A stand-in's copy provides" (OXIDIZED_DESIGN_DIVERGENCES #731; user ruling 2026-10-17): after a binding that
2692/// stands in for an author's file ([`crate::binding::author_files`]), or one a shipped file's declaration routed its
2693/// request to ([`provided_binding`]; user ruling 2026-10-20), has loaded, the copy of that file the paper ships
2694/// is read too, raw, at the same `\documentclass`/`\usepackage`/`\RequirePackage`/`\input` point, origin `File`. Its
2695/// definitions of names the binding owns hold only inside its own code ([`crate::state::note_copy_provides_assignment`]),
2696/// so for the document they act as `\providecommand`; the rest stand as TeX makes them — the copy's extras: 1309.5950's
2697/// aas_macros.sty `\kms`, `\lya`; 1805.06442 `\prx`; 2001.05519 `\cac`; 1406.5372's `\plotone`. Its
2698/// `\AtEndOfClass`/`\AtEndOfPackage` code runs at this load's end under the same rule
2699/// ([`crate::state::copy_provides_wrap`]), its document-time hooks are not registered
2700/// ([`crate::state::copy_provides_defers`]), a package or class it loads is a real load, the mode suspended for it
2701/// ([`input_definitions`]: bmvc2k.cls:139 `tabularx`, ws-rv9x6.cls's `ws-crop9x6`), a file it `\input`s is part of it
2702/// (svjour.cls's `.clo`, OXIDIZED_DESIGN_DIVERGENCES #744), its expl3 syntax ends with its load, and an Error in its own code stays
2703/// an Error (user ruling 2026-10-17). The copy is the file `request`.`ext` in the paper's source (the
2704/// document's directory, or a `{filecontents}` virtual file), never one of TeX Live's; one read raw already (by its
2705/// binding: arxiv.sty, cvpr.sty, pasj00.cls, … `InputDefinitions!`) is not read again. Perl never reads it: `FindFile`
2706/// prefers the `.ltxml` (Package.pm:2113-2133).
2707fn read_stand_in_copy(request: &str, binding: &str, ext: &str, in_expl3: bool) -> Result<()> {
2708  if request.is_empty() || ext.is_empty() {
2709    return Ok(());
2710  }
2711  let file = if request.ends_with(&s!(".{ext}")) {
2712    request.to_string()
2713  } else {
2714    s!("{request}.{ext}")
2715  };
2716  let found = if crate::binding::author_files::is_a_paper_copy_read(&file) {
2717    papers_own_copy(&file)
2718  } else {
2719    find_file(
2720      &file,
2721      Some(FindFileOptions {
2722        forbid_ltxml: true,
2723        ..Default::default()
2724      }),
2725    )
2726  };
2727  let Some(path) = found else {
2728    return Ok(());
2729  };
2730  if !shipped_with_paper(&path) || read_raw_already(&path) || lookup_bool(&s!("{file}_raw_loaded"))
2731  {
2732    return Ok(());
2733  }
2734  // (a copy whose declaration routed its request here is the file by that declaration: [`provided_binding`]; the
2735  // text names its binding declares are its own, as the real class's: `state::routed_copy_text_name_yields`,
2736  // OXIDIZED_DESIGN_DIVERGENCES #731 rule 14, 1402.7103)
2737  let routed = loading_for_a_provides_route(binding);
2738  if !routed && !copy_is_the_stood_in_file(&file, binding, &path) {
2739    return Ok(());
2740  }
2741  if routed && ext == "cls" && is_latex_base_class(binding) {
2742    return read_standard_class_derivative(&file, &path, in_expl3);
2743  }
2744  if routed {
2745    Info!(
2746      "provide",
2747      &file,
2748      s!("The paper's {file} is read after the {binding}.{ext} binding, as its stand-in's copy")
2749    );
2750  }
2751  let id = new_copy_provides_record(
2752    file.rsplit(['/', '\\']).next().unwrap_or(&file),
2753    file_stem(binding),
2754    routed,
2755  );
2756  use crate::definition::origin::{CopyProvidesGuard, DefinitionOrigin, OriginGuard};
2757  // (not a raw class read for K11, `\lx@class@loaded@raw`: the binding owns the title page)
2758  let _origin = OriginGuard::new(DefinitionOrigin::File);
2759  let _provides = CopyProvidesGuard::new(id);
2760  // (a class or package copy ends as a real class or package load ends: latex.ltx's `\@popfilename` restores the
2761  // syntax a `\ProvidesExplClass` turned on — fcs.cls:70, whose expl3 catcodes stayed on for the document and ate its
2762  // spaces, `\theta_` undefined: 2606.16349, 2308.11432; an `\input` copy restores nothing, as TeX's `\input`)
2763  load_tex_definitions(
2764    &file,
2765    &path,
2766    false,
2767    ext != "tex",
2768    in_expl3,
2769    ext != "tex",
2770    true,
2771  )
2772}
2773
2774/// Is `class` one of LaTeX's own document classes — its file in the format's base distribution (TeX Live's
2775/// `tex/latex/base/`: article, report, book, letter, proc, slides, minimal), whose binding is LaTeXML's model of that
2776/// class: its text names and its structural markup?
2777///
2778/// Looked up in the TeX tree by its directory there (kpathsea's `latex/base/<class>.cls`), not by `find_file`, which
2779/// searches the paper's directory first: a paper that ships a self-named `article.cls` beside its derivative still
2780/// declares a LaTeX class (guard `perfect_kernel_batch77w::standard_class_derivative_beside_a_self_named_article`).
2781fn is_latex_base_class(class: &str) -> bool {
2782  let file = s!("latex/base/{}.cls", file_stem(class));
2783  pathname::kpsewhich(&[file.as_str()]).is_some_and(|path| {
2784    !shipped_with_paper(&path) && path.replace('\\', "/").contains("/tex/latex/base/")
2785  })
2786}
2787
2788/// "A standard-class derivative is read as a raw class over its binding" (OXIDIZED_DESIGN_DIVERGENCES #731 rule 13;
2789/// user rulings 2026-10-20: the route stays, the bindings lose nothing). A class the paper ships that declares itself
2790/// one of LaTeX's own classes ([`is_latex_base_class`]: aip-cp.cls:24 `\ProvidesClass{article}`, 1506.04050,
2791/// 1604.08112; mf.cls, 0709.4467; antonio.cls, 1808.10740; HERON.cls, 1903.06504; mbook.cls, nucl-th0703058) is not
2792/// that class but a derivative of it: what it redefines patches the kernel's class. So after the binding has loaded
2793/// (its defaults: counters and their ids, the class options, `ltx-article.css`), the copy is read as a raw class is,
2794/// not in provides mode: an unlocked name it redefines stands as TeX makes it (its size file's `\normalsize`, so the
2795/// nominal font size; its `\thesection`; its contact setters); its `\newcommand` of a name the binding defined takes
2796/// over only a text name (`\refname`; `state::standard_class_binding_name`), never the binding's structural commands
2797/// (`\appendix`, book's `\frontmatter`: hep-ex0405054, math0301023), and its `\newcounter` of a counter the binding
2798/// declared keeps the binding's ids (`S1.F1`; `counter::dialect::new_counter`); a locked name is refused with the
2799/// records a raw class's takeover leaves — `\lx@dropped@<name>` and `<name>:redefined` — so the kernel's `\author`
2800/// appends each call (OXIDIZED_DESIGN #253) and replays the class's own setter (#482), its `\maketitle` deposits what
2801/// the frontmatter does not carry (#265), and the title-page stores reach the frontmatter (K11,
2802/// `\lx@class@loaded@raw` at the binding load's end). Under provides mode aip-cp's accumulating `\author[aff1]{…}`
2803/// kept only the last author (5 → 1) and its `\affil` list was lost, silently.
2804fn read_standard_class_derivative(file: &str, path: &str, in_expl3: bool) -> Result<()> {
2805  use crate::definition::origin::{CopyProvidesGuard, DefinitionOrigin, OriginGuard};
2806  Info!(
2807    "provide",
2808    file,
2809    s!("The paper's {file} derives from a LaTeX class: read as a raw class over its binding")
2810  );
2811  let _origin = OriginGuard::new(DefinitionOrigin::File);
2812  let _not_a_copy = CopyProvidesGuard::new(0);
2813  let setters_before = crate::binding::store_setters::snapshot()?;
2814  // (the binding loaded last is the standard class's, whose load just ended: its own names are the class's)
2815  let class_names = stand_in_last_load_names();
2816  let derivative = StandardClassDerivativeRead::enter(class_names);
2817  let class_read = crate::binding::store_setters::RawClassRead::begin();
2818  let read = load_tex_definitions(file, path, false, true, in_expl3, true, true);
2819  drop(class_read);
2820  drop(derivative);
2821  read?;
2822  crate::binding::store_setters::mark_raw(&setters_before)?;
2823  UNCLAIMED_RAW_CLASS_READS.set(UNCLAIMED_RAW_CLASS_READS.get() + 1);
2824  Ok(())
2825}
2826
2827/// A standard-class derivative's read (`STANDARD_CLASS_DERIVATIVE`), popped however it ends: a panic a worker catches
2828/// would leave its class's names for the next paper's reads.
2829struct StandardClassDerivativeRead;
2830
2831impl StandardClassDerivativeRead {
2832  fn enter(class_names: HashSet<SymStr>) -> Self {
2833    STANDARD_CLASS_DERIVATIVE.with(|reads| reads.borrow_mut().push(class_names));
2834    StandardClassDerivativeRead
2835  }
2836}
2837
2838impl Drop for StandardClassDerivativeRead {
2839  fn drop(&mut self) {
2840    let _ = STANDARD_CLASS_DERIVATIVE.try_with(|reads| reads.borrow_mut().pop());
2841  }
2842}
2843
2844/// A stand-in binding's name while its load runs (`STAND_IN_BINDINGS`): a package its load loads first records it
2845/// (`<file>:loaded_by_stand_in`), so that only the copy read after this binding takes that load as its own (a renamed
2846/// elsarticle.cls copy's `\RequirePackage[square]{natbib}`, 1811.10063).
2847struct StandInBindingName;
2848
2849impl StandInBindingName {
2850  fn enter(name: &str) -> Self {
2851    STAND_IN_BINDINGS.with(|names| names.borrow_mut().push(name.to_string()));
2852    StandInBindingName
2853  }
2854}
2855
2856impl Drop for StandInBindingName {
2857  fn drop(&mut self) { let _ = STAND_IN_BINDINGS.try_with(|names| names.borrow_mut().pop()); }
2858}
2859
2860/// Is a standard-class derivative (`read_standard_class_derivative`) being read now, its own code (a file the paper
2861/// ships, `reading_author_file`) rather than a TeX Live file it loads? Its `\newcommand` of a name the standard class's
2862/// binding assigned defines it (`state::standard_class_binding_name`).
2863pub fn reading_standard_class_derivative() -> bool {
2864  STANDARD_CLASS_DERIVATIVE.with(|reads| !reads.borrow().is_empty()) && reading_author_file()
2865}
2866
2867/// Is a standard-class derivative being read now ([`reading_standard_class_derivative`]), and did its standard class's
2868/// binding assign the name `key` in its own load (`state::stand_in_last_load_names` when the derivative's read began)?
2869/// Not a name a stand-in the derivative loads assigned, which LaTeX finds defined (guard
2870/// `perfect_kernel_batch77w::standard_class_derivative_defines_only_its_class_names`).
2871pub fn standard_class_binding_assigned(key: SymStr) -> bool {
2872  reading_standard_class_derivative()
2873    && STANDARD_CLASS_DERIVATIVE.with(|reads| {
2874      reads
2875        .borrow()
2876        .last()
2877        .is_some_and(|names| names.contains(&key))
2878    })
2879}
2880
2881/// A compiled binding's load of `file` that the real file it stands for makes too (elsarticle.cls:1243, acmart.cls:300,
2882/// jmlr.cls:150, jheppub.sty:37): the file's own, so a document's later repeat with other options is LaTeX's "Option
2883/// clash" (`apply_repeat_options`). The binding records it only where the paper ships no copy of that file or one
2884/// that makes the same load (`shipped_class::shipped_copy_makes_load`): a copy loading it otherwise or not at all
2885/// leaves the binding's early load, and the document's options apply (elsarticle.cls copies: 2105.06643
2886/// `[authoryear]`, 2206.02837 none, 2402.13480 `[numbers,sort&compress]`; 2209.10785's cidr.cls, an acmart.cls copy
2887/// without natbib).
2888pub fn record_load_as_the_files_own(file: &str) {
2889  assign_value(
2890    &s!("{file}:requested_by_binding"),
2891    false,
2892    Some(Scope::Global),
2893  );
2894}
2895
2896/// The copy of `file` the paper ships, met before TeX Live's own: a `{filecontents}` file or one in the document's
2897/// directory; never one kpathsea finds (a `TEXMFHOME` beside the paper) nor one only `\input@path` reaches, which LaTeX
2898/// tries last (expl3-code.tex:12589-12603).
2899pub(crate) fn papers_own_copy(file: &str) -> Option<String> {
2900  if crate::binding::virtual_files::vfs_exists(file) {
2901    return Some(file.to_string());
2902  }
2903  pathname::find(file, PathnameFindOptions {
2904    paths: Some(get_search_paths()),
2905    ..PathnameFindOptions::default()
2906  })
2907  .filter(|path| shipped_with_paper(path))
2908}
2909
2910/// Is the file at `path` one the paper ships: a `{filecontents}` virtual file, or one under the document's own source
2911/// directory (`SOURCEDIRECTORY`), not TeX Live's?
2912fn shipped_with_paper(path: &str) -> bool {
2913  crate::binding::virtual_files::vfs_read(path).is_some() || {
2914    let dir = lookup_string("SOURCEDIRECTORY");
2915    let canonical =
2916      |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| Path::new(p).to_path_buf());
2917    !dir.is_empty() && canonical(path).starts_with(canonical(&dir))
2918  }
2919}
2920
2921/// Does the LaTeX format hold `module` — is its marker a definition of the format's own layer (the dump, or a raw
2922/// format file read for it), not one a file or the document made? Recorded once held, so a later read of another
2923/// file of the module still sees it after the tree's file redefines the marker (babel.sty:481 `\bbl@version`).
2924fn format_holds(module: &FormatModule) -> bool {
2925  use crate::definition::origin::DefinitionOrigin;
2926  let key = s!("format_module:{}", module.marker);
2927  if lookup_bool(&key) {
2928    return true;
2929  }
2930  let held = lookup_definition(&T_CS!(module.marker))
2931    .ok()
2932    .flatten()
2933    .is_some_and(|defn| {
2934      matches!(
2935        defn.get_origin(),
2936        DefinitionOrigin::LatexDump | DefinitionOrigin::Format | DefinitionOrigin::Plain
2937      )
2938    });
2939  if held {
2940    assign_value(&key, true, Some(Scope::Global));
2941  }
2942  held
2943}
2944
2945/// The file the raw read of `request` takes when it reads `file`, a module the format holds, and found `path`
2946/// (OXIDIZED_DESIGN_DIVERGENCES #1142; DG ruling 2026-11-23): `path` when it is the TeX tree's, or a copy byte-identical
2947/// to the tree's; else the tree's, the copy — `\usepackage{dir/babel}`'s, or a renamed one a declaration routed here
2948/// ([`routed_copy_request`]) — skipped with a Warning. An older babel or expl3 a paper ships fights the one in the
2949/// format: babel 3.9l's `\ifx\bbl@version\bbl@tempa\else\input switch.def` meets TL's switch.def, now `\input
2950/// babel.def`, which finds the copy again (1408.3933, 1410.2241, 1511.02101, 1511.05750, 1602.08358, 1601.02763); expl3
2951/// 2012's l3bootstrap.sty:201-241 re-wraps the file stack expl3.ltx:180-186 wraps (1207.4642, 1211.3724, 1211.6751,
2952/// 1304.5586). A tree without the file leaves the copy.
2953fn format_module_path(request: &str, file: &str, path: String, module: &FormatModule) -> String {
2954  if !shipped_with_paper(&path) {
2955    return path;
2956  }
2957  // (by the module's directory: kpathsea's `.`, first in TEXINPUTS, would find a copy in the current directory)
2958  let Some(tree) = pathname::kpsewhich(&[&s!("{}/{file}", module.tree_dir)])
2959    .filter(|tree| !shipped_with_paper(tree))
2960  else {
2961    return path;
2962  };
2963  let copy = crate::binding::virtual_files::vfs_read(&path)
2964    .map(String::into_bytes)
2965    .or_else(|| std::fs::read(&path).ok());
2966  if copy.is_some_and(|copy| std::fs::read(&tree).is_ok_and(|text| text == copy)) {
2967    return path;
2968  }
2969  Warn!(
2970    "shipped_copy",
2971    request,
2972    s!(
2973      "The paper's copy of {file}, a module the LaTeX format holds, is not read; the format's own is"
2974    )
2975  );
2976  tree
2977}
2978
2979/// "A shipped file that `\Provides` a bound name loads that binding" (OXIDIZED_DESIGN_DIVERGENCES #731, the
2980/// declaration route; user ruling 2026-10-20): the binding that answers a request with no binding of its own (`name`,
2981/// a `.sty` or `.cls`) because the file the paper ships under that name declares itself another file a binding stands
2982/// for — `\ProvidesPackage{natbib}` in natbib_vw.sty (0802.4100, 1003.3017, astro-ph0512042), modnatbib.sty,
2983/// natbib_jrm.sty; `\ProvidesClass{revtex4}` in qm2008_abs.cls and snp.cls (0805.2253, 0806.0481, 0805.4759);
2984/// `\ProvidesPackage{aistats2023}` in a renamed aistats style; `\ProvidesPackage{everyshi}` in cvpr_eso.sty. The
2985/// declaration is [`file_declaration`]'s (the declared-macro form included); its kind is the request's (a `.sty`'s
2986/// `\ProvidesPackage` or `\ProvidesFile{X.sty}`, a `.cls`'s `\ProvidesClass` or `\ProvidesFile{X.cls}`: a `.sty`
2987/// that `\ProvidesClass{X}` is not routed); the name is another (a copy declaring its own name, in any case, is that
2988/// file); and the name has a binding of that kind — the registry's, matched as a request is without regard to case,
2989/// or the one its versioned fallback reaches (`aistats2023` → aistats, [`find_file_fallback`]). Only the paper's own
2990/// files are read ([`shipped_with_paper`]): a TeX Live file is its own name's. Returns the binding's name and the
2991/// declared one. In TeX the copy is read whole, redefining everything the package defines; the binding's markup for it
2992/// is the ruled answer, the copy read after it as the stand-in's copy (`read_stand_in_copy`), its own commands added —
2993/// or, where the binding reads its own file raw, read there instead ([`routed_copy_request`]), and read even when the
2994/// binding is loaded already (OXIDIZED_DESIGN_DIVERGENCES #1118). One rule for what were per-name stand-ins (72a's
2995/// renamed natbib copies, 77o's renamed aistats styles, 68v's revtex4 copies).
2996///
2997/// A file that loads the file it declares, with a load of its own kind ([`loads_itself`]), is its extension, read raw
2998/// as itself (#731 rule 12): aalongtable.sty (1406.2868, 1412.3469); imsart-altered.cls stays a copy (2405.11676).
2999fn provided_binding(name: &str, ext: &str) -> Option<DeclaredFile> {
3000  if !matches!(ext, "sty" | "cls") {
3001    return None;
3002  }
3003  // (the search paths only, no kpsewhich: a file the paper ships is in its source directory or a `{filecontents}` one)
3004  let path = find_file(
3005    name,
3006    Some(FindFileOptions {
3007      ext_type: Some(Cow::Owned(ext.to_string())),
3008      forbid_ltxml: true,
3009      search_paths_only: true,
3010      ..FindFileOptions::default()
3011    }),
3012  )?;
3013  if !shipped_with_paper(&path) {
3014    return None;
3015  }
3016  let text = source_text(&path)?;
3017  let declarations = file_declarations(&text);
3018  // (a file that declares three files or more is a bundle of them, not a copy of the first: cauchy.sty carries
3019  // theorem, exscale, epsfig and apacite, and routed to the theorem binding the rest was lost after theorem.sty's load
3020  // guard, 1312.3078; two may be a class and a package it embeds, qm2008_abs.cls's textcase)
3021  let mut distinct: Vec<String> = Vec::new();
3022  for (_, name) in &declarations {
3023    let stem = file_stem(name).to_ascii_lowercase();
3024    if !distinct.contains(&stem) {
3025      distinct.push(stem);
3026    }
3027  }
3028  if distinct.len() >= 3 {
3029    return None;
3030  }
3031  let (kind, declared) = declarations.into_iter().next()?;
3032  let declared = declared.rsplit(['/', '\\']).next().unwrap_or(&declared);
3033  let dotted = s!(".{ext}");
3034  let declared = match (kind, ext) {
3035    ("Class", "cls") | ("Package", "sty") => declared.strip_suffix(&dotted).unwrap_or(declared),
3036    ("File", _) => declared.strip_suffix(&dotted)?,
3037    _ => return None,
3038  };
3039  let request = name.rsplit(['/', '\\']).next().unwrap_or(name);
3040  if declared.is_empty() || declared.starts_with('\\') || declared.eq_ignore_ascii_case(request) {
3041    return None;
3042  }
3043  let registered = get_binding_names().iter().find_map(|names| {
3044    names
3045      .iter()
3046      .find(|(n, e)| n.eq_ignore_ascii_case(declared) && *e == ext)
3047      .map(|(n, _)| (*n).to_string())
3048  });
3049  let binding = match registered {
3050    Some(binding) => binding,
3051    None => {
3052      let (fallback, _) = find_file_fallback(declared, ext)?;
3053      fallback
3054        .strip_suffix(&dotted)
3055        .unwrap_or(&fallback)
3056        .to_string()
3057    },
3058  };
3059  // (never the request itself: a declared name whose versioned fallback is the request's name)
3060  if binding.eq_ignore_ascii_case(request) {
3061    return None;
3062  }
3063  if loads_itself(&text, declared, ext) || loads_itself(&text, &binding, ext) {
3064    Info!(
3065      "provide",
3066      name,
3067      s!(
3068        "The paper's {request}.{ext} declares itself {declared} and loads it: an extension of {declared}, \
3069         read as itself"
3070      )
3071    );
3072    return Some(DeclaredFile::Extension);
3073  }
3074  Some(DeclaredFile::Copy(binding, declared.to_string()))
3075}
3076
3077/// What a shipped file's declaration of a bound file makes of its request ([`provided_binding`]).
3078enum DeclaredFile {
3079  /// The binding that answers the request, and the declared name: the file is read after it as its stand-in's copy.
3080  Copy(String, String),
3081  /// The file loads the file it declares: an extension of it, read raw as the requested file.
3082  Extension,
3083}
3084
3085/// Is the binding `name` loading now the one a shipped copy's declaration routed its request to
3086/// ([`provided_binding`]; `fallback_provides` names it while the route's load runs)?
3087fn loading_for_a_provides_route(name: &str) -> bool {
3088  let target = lookup_string("fallback_provides");
3089  !target.is_empty() && file_stem(&target).eq_ignore_ascii_case(file_stem(name))
3090}
3091
3092/// The paper's copy a binding's own raw read of `file` (of type `ext`) reads instead, while a shipped copy's declaration
3093/// routed its request to that binding ([`provided_binding`]): the request, when `file` is the binding's own name and
3094/// type (`fallback_provides`, `<binding>.<ext>`) and the paper ships the request's file. As in TeX, the copy is read
3095/// once, where the real file would be: fsmfart.cls `\ProvidesClass{smfart}` (1401.0915; smfartVS.cls 1110.1467,
3096/// 1404.0804) under smfart_cls.rs, tikzcd.sty `\ProvidesPackage{tikz-cd}` (1201.4414, 1512.05388) under tikz_cd_sty.rs,
3097/// pdfplots.sty (2105.12769) under pgfplots_sty.rs. Read after TeX Live's file, the copy's first-load code ran over
3098/// state TeX never builds (fsmfart.cls:365-370's `\fi` unmatched; "Arrow tip 'cm to' was already defined"). While the
3099/// copy is read, its own request for the file reads the real file ([`SubstitutedRead`]); a self-named copy is the file
3100/// the raw read finds already (OXIDIZED_DESIGN_DIVERGENCES #1110, #1118).
3101fn routed_copy_request(file: &str, ext: Option<&str>) -> Option<String> {
3102  let target = lookup_string("fallback_provides");
3103  let (binding, route_ext) = target.rsplit_once('.')?;
3104  let ext = ext?;
3105  if !file_stem(file).eq_ignore_ascii_case(binding) {
3106    return None;
3107  }
3108  let request = lookup_string("fallback_request");
3109  let shipped = |ext: &str| {
3110    find_file(
3111      &request,
3112      Some(FindFileOptions {
3113        ext_type: Some(Cow::Owned(ext.to_string())),
3114        forbid_ltxml: true,
3115        search_paths_only: true,
3116        ..FindFileOptions::default()
3117      }),
3118    )
3119    .filter(|path| shipped_with_paper(path))
3120  };
3121  let copy = shipped(route_ext)?;
3122  let text = source_text(&copy)?;
3123  if ext == route_ext {
3124    // (not a wrapper, which loads the file it declares itself — an extension, read as itself before any route
3125    // ([`loads_itself`]); a load of another kind stays out here: a `\ProvidesPackage{tikz-cd}\RequirePackage{tikz-cd}`
3126    // read here hit the binding still loading, TeX Live's file never read; nor an author's own file that defines none
3127    // of the file's names, whose request for it TeX still reads. A request the text tests miss, made while the copy is
3128    // read, reads TeX Live's file: [`SubstitutedRead`])
3129    let file = s!("{}.{ext}", file_stem(file));
3130    if loads_file(&text, binding) || !reads_as_the_file(&text, &file) {
3131      return None;
3132    }
3133    Info!(
3134      "provide",
3135      &request,
3136      s!("The paper's {request}.{ext} is read as {file}, the file the {target} binding reads")
3137    );
3138    return Some(request);
3139  }
3140  // (a file of the binding's other type is the copy's own of that name, where the copy loads one: imsart.cls:149
3141  // `\RequirePackage{imsart}`, imsart_cls.rs's imsart.sty, is 2405.11676's imsart-altered.cls:149
3142  // `\RequirePackage{imsart-altered}`)
3143  shipped(ext)?;
3144  loads_file(&text, file_stem(&request)).then_some(request)
3145}
3146
3147/// Does the TeX source `text` load the package or class `name` — a `\RequirePackage`, `\usepackage` or `\LoadClass` of
3148/// it, outside a comment, the name in any case?
3149fn loads_file(text: &str, name: &str) -> bool {
3150  let Ok(load) = Regex::new(&s!(
3151    r"\\(?:RequirePackage|usepackage|LoadClass)\s*(?:\[[^\]]*\])?\s*\{{(?:[^}}]*,)?\s*(?i:{})\s*[,}}]",
3152    regex::escape(name)
3153  )) else {
3154    return false;
3155  };
3156  source_code_lines(text).any(|code| load.is_match(code))
3157}
3158
3159/// Does the TeX source `text` load `name` as a file of its own kind `ext` — a `.sty`'s `\RequirePackage`,
3160/// `\RequirePackageWithOptions` or `\usepackage`, a `.cls`'s `\LoadClass` or `\LoadClassWithOptions` — in the code TeX
3161/// reads ([`read_code_lines`]), the name in any case? A `.cls`'s `\RequirePackage{name}` loads the package of that
3162/// name, not the class (imsart.cls:149). A load's options and name may run over lines. A load after `\protect`,
3163/// `\string`, `\token_to_str:N` or `\cs_to_str:N` is text, a message's, not code: natbib.sty:171 and :283's
3164/// `\PackageError`s, which renamed natbib copies carry; `\noexpand` defers a load an `\edef` still makes.
3165fn loads_itself(text: &str, name: &str, ext: &str) -> bool {
3166  let commands = match ext {
3167    "sty" => "RequirePackageWithOptions|RequirePackage|usepackage",
3168    "cls" => "LoadClassWithOptions|LoadClass",
3169    _ => return false,
3170  };
3171  let Ok(load) = Regex::new(&s!(
3172    concat!(
3173      r"(\\(?:protect|string|token_to_str:N|cs_to_str:N)\s*)?",
3174      r"\\(?:{})\s*(?:\[[^\]]*\])?\s*\{{(?:[^}}]*,)?\s*(?i:{})\s*[,}}]"
3175    ),
3176    commands,
3177    regex::escape(name)
3178  )) else {
3179    return false;
3180  };
3181  let code = read_code_lines(text).join("\n");
3182  load.captures_iter(&code).any(|load| load.get(1).is_none())
3183}
3184
3185/// Does a paper's copy (its source `text`) read as `file`, the file its binding reads raw (the paper's own, else TeX
3186/// Live's)? Only the names each defines count ([`names_read_as`]), never what it loads: an author's file that loads
3187/// tikz as tikz-cd.sty does but defines `\mytcd` is no copy. They share a quarter of the smaller set: a cut-down copy
3188/// (smfcopy's first-load test, 1 of 2; tikzcd.sty 1201.4414, 1512.05388: 14 of 18; pdfplots.sty 2105.12769: 2 of 2;
3189/// smfartVS.cls 1110.1467: 237 of 237) passes, a misdeclared author's file (0) does not. With no such file, the copy
3190/// is the only one there is.
3191fn reads_as_the_file(text: &str, file: &str) -> bool {
3192  let Some(original) = find_file(
3193    file,
3194    Some(FindFileOptions {
3195      forbid_ltxml: true,
3196      ..FindFileOptions::default()
3197    }),
3198  )
3199  .and_then(|path| source_text(&path)) else {
3200    return true;
3201  };
3202  let (copy, original) = (names_read_as(text), names_read_as(&original));
3203  let shared = copy.intersection(&original).count();
3204  shared > 0 && shared * 4 >= copy.len().min(original.len())
3205}
3206
3207/// The names the TeX source `text` defines ([`defined_names`]); for a file that defines none itself, those of the
3208/// files it reads with `\input` or `\usetikzlibrary`, one level: tikz-cd.sty's are tikzlibrarycd.code.tex's (`\tikzcd`,
3209/// `\arrow`, …). A `\usetikzlibrary{X}` reads tikzlibraryX.code.tex, else pgflibraryX.code.tex (tikz.code.tex
3210/// `\use@@tikzlibrary`).
3211fn names_read_as(text: &str) -> HashSet<String> {
3212  static READ: LazyLock<Regex> = LazyLock::new(|| {
3213    Regex::new(r"\\(usetikzlibrary|input)(?:\s*\{([^}]*)\}|\s+([^\s{}\\]+))").unwrap()
3214  });
3215  let mut names = defined_names(text);
3216  if !names.is_empty() {
3217    return names;
3218  }
3219  for code in source_code_lines(text) {
3220    for cap in READ.captures_iter(code) {
3221      let items = cap.get(2).or_else(|| cap.get(3)).map_or("", |m| m.as_str());
3222      for item in items
3223        .split(',')
3224        .map(str::trim)
3225        .filter(|item| !item.is_empty())
3226      {
3227        let candidates = if &cap[1] == "input" {
3228          vec![item.to_string()]
3229        } else {
3230          vec![
3231            s!("tikzlibrary{item}.code.tex"),
3232            s!("pgflibrary{item}.code.tex"),
3233          ]
3234        };
3235        let read = candidates.iter().find_map(|name| {
3236          find_file(
3237            name,
3238            Some(FindFileOptions {
3239              forbid_ltxml: true,
3240              ext_type: Some(Cow::Borrowed("tex")),
3241              ..FindFileOptions::default()
3242            }),
3243          )
3244        });
3245        if let Some(read) = read.and_then(|path| source_text(&path)) {
3246          names.extend(defined_names(&read));
3247        }
3248      }
3249    }
3250  }
3251  names
3252}
3253
3254thread_local! {
3255  /// The files a shipped copy is read in place of now ([`SubstitutedRead`]), innermost last.
3256  static SUBSTITUTED_READS: std::cell::RefCell<Vec<String>> =
3257    const { std::cell::RefCell::new(Vec::new()) };
3258}
3259
3260/// A shipped copy's read in place of `file` ([`routed_copy_request`]). While it is open, a request for `file` the text
3261/// test ([`loads_file`]) does not see — the copy's `\RequirePackageWithOptions{csquotes}`, `\LoadClassWithOptions{smfart}`
3262/// — reads the real file raw, the binding not entered again ([`substituting_for`]): TeX reads the wrapper, then the file.
3263struct SubstitutedRead;
3264
3265impl SubstitutedRead {
3266  fn enter(file: String) -> Self {
3267    SUBSTITUTED_READS.with(|reads| reads.borrow_mut().push(file));
3268    SubstitutedRead
3269  }
3270}
3271
3272impl Drop for SubstitutedRead {
3273  fn drop(&mut self) { let _ = SUBSTITUTED_READS.try_with(|reads| reads.borrow_mut().pop()); }
3274}
3275
3276/// Is a shipped copy being read in place of `file` (`<name>.<ext>`, [`SubstitutedRead`])?
3277fn substituting_for(file: &str) -> bool {
3278  SUBSTITUTED_READS.with(|reads| {
3279    reads
3280      .borrow()
3281      .iter()
3282      .any(|read| read.eq_ignore_ascii_case(file))
3283  })
3284}
3285
3286/// One class slot (OXIDIZED_DESIGN_DIVERGENCES #736): does the base class a stand-in class binding loaded stand for the
3287/// class `name` its copy's own `\LoadClass` names? A document has one class: latex.ltx:18800 lets a class file
3288/// `\LoadClass` once (a second is `\@twoloadclasserror`, :18938-18942), and the binding has already loaded the base
3289/// class it models the copy on. A binding loads the class its real file loads (r9: ceurart_cls.rs scrartcl,
3290/// atlasdoc_cls.rs its KOMA class, jgcc_cls.rs amsart), so the copy's `\LoadClass` is a repeat; this is the net for a
3291/// binding still out of step (svmult's book where svmult.cls loads article; daj's tocbase emulation). When the bindings
3292/// loaded OmniBus → article, loading the copy's class too put a second class on top of the first: ceurart.cls:62 `\LoadClass{scrartcl}` raw-read scrartcl, scrkbase and typearea over article,
3293/// whose `\@ptsize` of 0 sends typearea.sty:1400-1413 off its path ("DIV for 0.0pt", then "Conditional limit of
3294/// 48000000 exceeded": 2509.11496, 2608.23214, 2310.02658, 2505.16276); atlasdoc.cls `\LoadClass{\ADOC@mainclass}`
3295/// (scrartcl) redefined `\@startsection` and `\@sect` under the binding (2509.01219, "Bad type area settings"). So
3296/// when the copy's own code (provides-mode on: a file it loads is a real load, [`input_definitions`]) loads a class
3297/// that is not loaded yet (`\ver@<name>.cls` undefined; the binding's own base class is a repeat load, cimart.cls
3298/// `\LoadClass{article}`), the binding's load loaded a class, and the paper does not ship the class (a class the author
3299/// ships is read: the reviewer's nc_chain `\LoadClass{mybase}`), the class is not loaded: the binding's classes are the
3300/// copy's base classes (`state::note_copy_base_classes`; a copy's `\newcommand` of a name they define errs, as over
3301/// the real class), with an Info. Perl never reads the copy (Package.pm:2113-2133 prefers the `.ltxml`).
3302fn binding_base_class_stands_for(name: &str) -> Result<bool> {
3303  // (the copy read now, or the copy whose own `\LoadClass` is open: a class a shipped intermediate class loads, copy →
3304  // mybase.cls → `\LoadClass{scrartcl}`, is the copy's too — 72a review r7 NIT 8)
3305  let id = match crate::definition::origin::copy_provides() {
3306    0 => open_copy_class_load().unwrap_or(0),
3307    id => id,
3308  };
3309  if id == 0 || name.is_empty() {
3310    return Ok(false);
3311  }
3312  let file = class_file_name(name);
3313  if file_loaded(&file) {
3314    return Ok(false);
3315  }
3316  let classes = open_class_load_classes();
3317  if classes.is_empty() {
3318    return Ok(false);
3319  }
3320  if find_file(
3321    name,
3322    Some(FindFileOptions {
3323      ext_type: Some(Cow::Borrowed("cls")),
3324      forbid_ltxml: true,
3325      ..FindFileOptions::default()
3326    }),
3327  )
3328  .is_some_and(|path| shipped_with_paper(&path))
3329  {
3330    return Ok(false);
3331  }
3332  note_copy_base_classes(id, &classes);
3333  Info!(
3334    "provide",
3335    &file,
3336    s!(
3337      "the binding's base class ({}) stands for the copy's \\LoadClass{{{}}}: not loaded",
3338      classes.join(", "),
3339      name
3340    )
3341  );
3342  Ok(true)
3343}
3344
3345/// The text of the file at `path`: a `{filecontents}` virtual file, else the file on disk, each byte a character.
3346fn source_text(path: &str) -> Option<String> {
3347  crate::binding::virtual_files::vfs_read(path).or_else(|| {
3348    std::fs::read(path)
3349      .ok()
3350      .map(|bytes| bytes.iter().map(|&b| b as char).collect::<String>())
3351  })
3352}
3353
3354/// The code of each line of `text`, its `%` comment dropped; a line ends at CR or LF, as in TeX (2402.17342's
3355/// sn-jnl.cls has CR-only ends).
3356fn source_code_lines(text: &str) -> impl Iterator<Item = &str> {
3357  text
3358    .split(['\n', '\r'])
3359    .map(|line| line.split('%').next().unwrap_or(""))
3360}
3361
3362/// The request a `\ProvidesPackage`/`\ProvidesClass` answers, as `(\@currpath\@currname, \@currext)`
3363/// (latex.ltx:18471-18486). Where our loader reads a `.sty`/`.cls` without making it the request — a binding's raw read
3364/// of a file, a copy read in a binding's place (`routed_copy_request`, `read_stand_in_copy`) — the request is the file
3365/// read, as TeX's `\RequirePackage` of it would make it. `None` in a binding's code, which declares its own name
3366/// (xcolor_sty.rs `\ProvidesPackage{xcolor}`), and with no request (an `\input` of a `.sty` in the document's preamble,
3367/// where TeX's `\@currname` is empty: the declared name is kept).
3368pub fn provides_request() -> Option<(String, String)> {
3369  let read = FILE_READS.with(|reads| reads.borrow().last().cloned());
3370  let name = expand_if_defined(T_CS!("\\@currname")).unwrap_or_default();
3371  let ext = expand_if_defined(T_CS!("\\@currext")).unwrap_or_default();
3372  match read {
3373    Some(FileRead::Binding) => None,
3374    Some(FileRead::Own(read)) => read
3375      .rsplit_once('.')
3376      .filter(|(_, ext)| matches!(*ext, "sty" | "cls"))
3377      .map(|(stem, ext)| (stem.to_string(), ext.to_string())),
3378    Some(FileRead::Current) | None => (!name.is_empty()).then_some((name, ext)),
3379  }
3380}
3381
3382/// `name` without its directory and its `.cls`/`.sty`/`.tex`/`.clo`/`.def` extension.
3383fn file_stem(name: &str) -> &str {
3384  let base = name.rsplit(['/', '\\']).next().unwrap_or(name);
3385  base
3386    .rsplit_once('.')
3387    .filter(|(_, ext)| matches!(*ext, "cls" | "sty" | "tex" | "clo" | "def"))
3388    .map_or(base, |(stem, _)| stem)
3389}
3390
3391/// What a file declares itself, read as text: its first `\ProvidesClass`/`\ProvidesPackage`/`\ProvidesFile` (or the
3392/// `\ProvidesExpl…` form) outside a comment, as the kind (`Class`, `Package`, `File`) and the name. A declaration naming
3393/// a macro reads its expansion, as `\ProvidesClass` does: cimart.cls:13-14
3394/// `\def\ClassName@CiM{cimart}\ProvidesClass{\ClassName@CiM}`, 2412.00032. The file's first parameterless `\def` or
3395/// `\newcommand` of the name is taken, wherever it stands, not the one in force at the declaration; a name defined
3396/// with parameters or in another file is not found, and the macro's own name is returned. Later declarations do not
3397/// count: a class may carry the packages it is built on (qm2008_abs.cls, a REVTeX 4 copy, embeds textcase.sty's
3398/// `\ProvidesPackage{textcase}`, :3680).
3399fn file_declaration(text: &str) -> Option<(&'static str, String)> {
3400  file_declarations(text).into_iter().next()
3401}
3402
3403/// Every declaration of [`file_declaration`]'s kind in `text`, in order, up to the file's first top-level `\endinput`
3404/// — a code line of it alone, outside any brace group — where TeX stops reading the file: a declaration in the
3405/// documentation after it (a `.dtx`-style trailer) is not the file's (77w review 8).
3406fn file_declarations(text: &str) -> Vec<(&'static str, String)> {
3407  static PROVIDES: LazyLock<Regex> = LazyLock::new(|| {
3408    Regex::new(r"\\Provides(?:Expl)?(Class|Package|File)\s*\{\s*([^}\s]+)\s*\}").unwrap()
3409  });
3410  let expansion = |name: &str| {
3411    let def = Regex::new(&s!(
3412      r"\\[egx]?def\s*{}\s*\{{\s*([^{{}}\s]+)\s*\}}|\\(?:re)?newcommand\*?\s*\{{?\s*{}\s*\}}?\s*\{{\s*([^{{}}\s]+)\s*\}}",
3413      regex::escape(name),
3414      regex::escape(name)
3415    ))
3416    .ok()?;
3417    source_code_lines(text).find_map(|code| {
3418      def
3419        .captures(code)
3420        .and_then(|cap| cap.get(1).or_else(|| cap.get(2)))
3421        .map(|value| value.as_str().to_string())
3422    })
3423  };
3424  let mut declarations = Vec::new();
3425  for code in read_code_lines(text) {
3426    for cap in PROVIDES.captures_iter(code) {
3427      let kind = match &cap[1] {
3428        "Class" => "Class",
3429        "Package" => "Package",
3430        _ => "File",
3431      };
3432      let name = &cap[2];
3433      let name = if name.starts_with('\\') {
3434        expansion(name).unwrap_or_else(|| name.to_string())
3435      } else {
3436        name.to_string()
3437      };
3438      declarations.push((kind, name));
3439    }
3440  }
3441  declarations
3442}
3443
3444/// The code lines of `text` ([`source_code_lines`]) TeX reads: up to its first top-level `\endinput`, a code line of it
3445/// alone outside any brace group and any conditional, after which a `.dtx`-style trailer documents the file. An
3446/// `\endinput` between an `\if…` and its `\fi` may not run, and the code after it is read: a file's load guard,
3447/// `\ifx\x\undefined\else` `\endinput` `\fi` (tex.web §378, §362: `\endinput` ends the file at its line's end).
3448fn read_code_lines(text: &str) -> Vec<&str> {
3449  let lines: Vec<&str> = source_code_lines(text).collect();
3450  let (mut braces, mut conditionals) = (0_i64, 0_i64);
3451  for (index, code) in lines.iter().enumerate() {
3452    if braces == 0 && code.trim() == "\\endinput" {
3453      // (a conditional open before it that a `\fi` after it closes)
3454      let mut open = 0_i64;
3455      let closed = lines[index + 1..]
3456        .iter()
3457        .flat_map(|code| conditional_steps(code))
3458        .any(|step| {
3459          open += step;
3460          open < 0
3461        });
3462      if conditionals == 0 || !closed {
3463        return lines[..index].to_vec();
3464      }
3465    }
3466    // (the braces of the line's code, an escaped one not counted)
3467    let mut escaped = false;
3468    for c in code.chars() {
3469      match c {
3470        '{' if !escaped => braces += 1,
3471        '}' if !escaped => braces -= 1,
3472        _ => {},
3473      }
3474      escaped = c == '\\' && !escaped;
3475    }
3476    conditionals = conditional_steps(code).fold(conditionals, |open, step| (open + step).max(0));
3477  }
3478  lines
3479}
3480
3481/// The conditionals the code line `code` opens and closes, in order: `1` for an `\if…`, not one a `\newif`, `\let` or
3482/// `\def` names, and `-1` for a `\fi`.
3483fn conditional_steps(code: &str) -> impl Iterator<Item = i64> + '_ {
3484  static CONTROL_WORD: LazyLock<Regex> =
3485    LazyLock::new(|| Regex::new(r"(\\(?:newif|let|[egx]?def)\s*)?\\([A-Za-z@]+)").unwrap());
3486  CONTROL_WORD
3487    .captures_iter(code)
3488    .filter_map(|word| match &word[2] {
3489      _ if word.get(1).is_some() => None,
3490      "fi" => Some(-1),
3491      name if name.starts_with("if") => Some(1),
3492      _ => None,
3493    })
3494}
3495
3496/// The names the TeX source `text` defines, read as text: a `\def`, `\let`, `\newcommand`, `\newif`, register or
3497/// environment, theorem or counter declaration of a name of letters ([`copy_is_the_stood_in_file`]).
3498fn defined_names(text: &str) -> HashSet<String> {
3499  static DEFINED: LazyLock<Regex> = LazyLock::new(|| {
3500    Regex::new(
3501      r"\\(?:[egx]?def|let|(?:re|provide)?newcommand\*?|DeclareRobustCommand\*?|(?:New|Renew|Provide|Declare)DocumentCommand|newif|chardef|mathchardef|newlength|newcount|newdimen|newskip|newtoks|newbox)\s*\{?\s*(\\[A-Za-z]+)(?:[^A-Za-z@]|$)|\\(?:(?:re)?newenvironment\*?|(?:New|Renew|Provide|Declare)DocumentEnvironment)\s*\{([A-Za-z]+)\}|\\newtheorem\*?\s*\{([A-Za-z]+)\}|\\newcounter\s*\{([A-Za-z]+)\}",
3502    )
3503    .unwrap()
3504  });
3505  let mut defined: HashSet<String> = HashSet::default();
3506  for code in source_code_lines(text) {
3507    for cap in DEFINED.captures_iter(code) {
3508      // (the names a declaration makes: `\newif\ifX` also `\Xtrue`/`\Xfalse`, an environment `\X` and `\endX`, a
3509      // counter `\theX`)
3510      if let Some(name) = cap.get(1) {
3511        let name = name.as_str();
3512        // (`\expandafter\def\csname…`, `\noexpand\def\noexpand\x`: an expansion primitive after `\def` names no
3513        // definee, so it is no evidence a file shares names with another)
3514        if matches!(name, "\\csname" | "\\expandafter" | "\\noexpand") {
3515          continue;
3516        }
3517        if let Some(flag) = name.strip_prefix("\\if")
3518          && code[cap.get(0).map_or(0, |m| m.start())..].starts_with("\\newif")
3519        {
3520          defined.insert(s!("\\{flag}true"));
3521          defined.insert(s!("\\{flag}false"));
3522        }
3523        defined.insert(name.to_string());
3524      } else if let Some(env) = cap.get(2).or_else(|| cap.get(3)) {
3525        defined.insert(s!("\\{}", env.as_str()));
3526        defined.insert(s!("\\end{}", env.as_str()));
3527      } else if let Some(counter) = cap.get(4) {
3528        defined.insert(s!("\\the{}", counter.as_str()));
3529      }
3530    }
3531  }
3532  defined
3533}
3534
3535/// Is the paper's file at `path`, of the name a stand-in binding answers (`file`), the file the binding `binding`
3536/// stands in for (OXIDIZED_DESIGN_DIVERGENCES #731 rule 0)? Two tests, in order:
3537/// 1. **Its declaration.** A `\ProvidesClass`/`\ProvidesPackage`/`\ProvidesFile` (or the `\ProvidesExpl…` form) naming
3538///    the binding that answered (the file's own name only when the binding is of that name: a fallback answers a renamed
3539///    file too, 1705.03989's aaart.cls under `aa`), or a file the binding is built on (its own `LoadClass!`/`RequirePackage!`,
3540///    or a binding whose definitions it makes as code: `state::stand_in_built_on`) is that file, whatever its version:
3541///    1609.03892's fcs.cls of 2016, older than the `\fcssetup` the binding models; 2308.11432's fcs.cls
3542///    `\ProvidesExplClass{fcs}`; apjfonts.sty (1202.3442, 1009.4702); 2011.13564's IEEEtai.cls, IEEE's own file, which
3543///    declares itself `IEEEtran`, the class the binding loads; hep-ph0608235's svjour2.cls, Springer's svjour code
3544///    renamed, declaring `svjour`. The test is of the copy of the file the paper requested: a file the binding is built
3545///    on without loading it is never requested, so the paper's copy of it is not read (the older svjour.cls beside
3546///    svjour3.cls: 2101.09497, 2110.05134, 2408.12532).
3547/// 2. **Its command set**, for a copy that declares another file or none (2.09-era files declare nothing): the copy
3548///    defines at least a quarter of the public names (letters only) the binding's own code assigned, a stand-in it loads
3549///    included (`state::stand_in_public_names`; the diagrams binding's diagrams.tex). Over the reviewer's simulation of
3550///    the census's 4,346 distinct copies (`rev72a/ident_sim2.json`), the undeclared copies' shares are bimodal — 124
3551///    under a tenth, 28 between a tenth and four tenths, 1,028 above — and a quarter admits the 1,047 that read as the
3552///    file (aas_macros.sty's journal names, an icml or neurips style's `\icmltitle`, `\AND`); the earlier absolute (20
3553///    names) and copy-side (a quarter of the copy's names) clauses admitted no copy the quarter did not.
3554///
3555/// A binding with no public name of its own and a copy with no matching declaration: not read (the copy cannot be told
3556/// from an author's own file of that name: aipcheck.tex, mssymb.tex, citesort.sty, revtex.sty). An author's own file
3557/// that only shares the name is not read either: hep-ph9609379's diagrams.sty (fifteen `\special` PostScript macros,
3558/// one of them `\diagram`), 2411.02780's equations.sty (`\ProvidesPackage{annotate-equations}`). Logged at Info.
3559fn copy_is_the_stood_in_file(file: &str, binding: &str, path: &str) -> bool {
3560  let Some(text) = source_text(path) else {
3561    return false;
3562  };
3563  let stem = |name: &str| file_stem(name).to_ascii_lowercase();
3564  let declared = file_declaration(&text).map(|(_, name)| stem(&name));
3565  let built_on = stand_in_built_on();
3566  // (the binding that answered, not the name asked for: a fallback answers a renamed file too — 1705.03989's aaart.cls,
3567  // amsart renamed and declaring itself `aaart`, which the `aa` binding answers — so a copy declaring the requested
3568  // name is that binding's file only when the binding is of that name; else the command set below decides)
3569  if let Some(declared) = &declared
3570    && (*declared == stem(binding) || built_on.iter().any(|base| stem(base) == *declared))
3571  {
3572    Info!(
3573      "provide",
3574      file,
3575      s!(
3576        "The paper's {file} declares itself {declared}: read as the file its binding stands in for"
3577      )
3578    );
3579    return true;
3580  }
3581  let public = stand_in_public_names();
3582  let defined = defined_names(&text);
3583  let shared = public.iter().filter(|name| defined.contains(*name)).count();
3584  let the_file = !public.is_empty() && shared * 4 >= public.len();
3585  Info!(
3586    "provide",
3587    file,
3588    s!(
3589      "The paper's {file} defines {shared} of the {} public names its binding defines ({} names of its own{}): {}",
3590      public.len(),
3591      defined.len(),
3592      declared.map_or(String::new(), |name| s!(", declared {name}")),
3593      if the_file {
3594        "read as the file its binding stands in for"
3595      } else {
3596        "not the file its binding stands in for, not read"
3597      }
3598    )
3599  );
3600  the_file
3601}
3602
3603/// Read the file at `pathname`, requested as `request`, raw as definitions. `own_request`: the loader reads it as a
3604/// request of its own, not under the `\@currname` of the load around it ([`provides_request`]).
3605fn load_tex_definitions(
3606  request: &str,
3607  pathname: &str,
3608  reloadable: bool,
3609  at_letter: bool,
3610  grandparent_in_expl3: bool,
3611  handleoptions: bool,
3612  own_request: bool,
3613) -> Result<()> {
3614  // Perl Package.pm L2334: $STATE->getStomach->leaveHorizontal_internal;
3615  // Defensive cleanup before reading definitions — if we're somehow in
3616  // horizontal mode while bound to vertical (e.g. after \par-less inline
3617  // text), repack and flip MODE in-place. No-op in the common case but
3618  // matches Perl's pre-load state hygiene.
3619  leave_horizontal_internal();
3620
3621  // Snapshot expl3-state at load entry. The cleanup hook below should
3622  // only restore catcodes if THIS load activated expl3; if the calling
3623  // context was already in expl3 mode (e.g. tasks.sty has run
3624  // `\ExplSyntaxOn` and is now `\file_input:n` ing a child file like
3625  // tasks.cfg), we must preserve the active state for the caller.
3626  // Without this guard, the nested cleanup would reset `_` and `:` to
3627  // OTHER/SUB inside the parent's processing, breaking everything past
3628  // the nested load (e.g. tasks.sty line 817's `\file_input_stop:`).
3629  // Witness for this exact failure: arXiv:2602.21210, 2604.21347,
3630  // 2604.22630, 2604.23234, 2604.22528 (tasks.sty + expl3 cluster,
3631  // Task #20).
3632
3633  if !pathname::is_literaldata(pathname) {
3634    // We can't analyze literal data's pathnames!
3635    // let (dir, name, extension) = pathname::split(pathname);
3636
3637    // Don't load if we've already loaded it before.
3638    // Note that we'll still load it if we've already loaded only the ltxml version
3639    // since someone's presumably asking _explicitly_ for the raw TeX version.
3640    // It's probably even the ltxml version is asking for it!!
3641    // Of course, now it will be marked and wont get reloaded!
3642    // Per OXIDIZED_DESIGN #23: raw .sty/.cls/.def load tracks
3643    // `<request>_raw_loaded`, separate from the binding `<request>_loaded`.
3644    // This lets a binding .rs load the raw file of the same name without
3645    // the flags clobbering each other.
3646    if lookup_bool(&s!("{request}_raw_loaded")) && !reloadable && !pathname::is_reloadable(pathname)
3647    {
3648      return Ok(());
3649    }
3650    assign_value(&s!("{request}_raw_loaded"), true, Some(Scope::Global));
3651    // (the file itself, by its path: a stand-in binding that reads the paper's copy raw has read it,
3652    // `read_stand_in_copy`. A speculative run's read is undone with it, `<request>_raw_loaded` too: the document's own read of
3653    // that copy is still to come, `\author{First\input{aas_macros.sty}}\author{Ann}\maketitle \input{aas_macros.sty}\kms`)
3654    if !gullet::in_speculative_digestion() {
3655      let path = canonical_path(pathname);
3656      RAW_READ_PATHS.with(|paths| paths.borrow_mut().insert(path));
3657    }
3658  }
3659  // (what it defines is a raw class's or an own-directory file's: the title-page check's third source, whose setters
3660  // these are, `Expandable::watched_call`; a raw TeX Live package is neither)
3661  let _own_file = OwnFileGuard::new(is_own_raw_file(pathname));
3662  let ver_cs = T_CS!(s!("\\ver@{request}"));
3663  let loading_mark = handleoptions.then(|| mark_loading(request)).flatten();
3664  let ver_before = lookup_meaning(&ver_cs);
3665
3666  // Note that we are reading definitions (and recursive input is assumed also definitions)
3667  // (both saved as they are and put back unchanged, unset included, as Perl Package.pm:2369-2392 does:
3668  // `localrawstyles`' "searchpaths" survives the load, and the format build's raw load dumps no `0` for either,
3669  // OD #449)
3670  let was_interpreting = lookup_value("INTERPRETING_DEFINITIONS").unwrap_or_default();
3671  // And that if we're interpreting this TeX file of definitions,
3672  // we probably should interpret any TeX files IT loads.
3673  let was_including_styles = lookup_value("INCLUDE_STYLES").unwrap_or_default();
3674  assign_value_sym(crate::pin!("INTERPRETING_DEFINITIONS"), true, None);
3675  // If we're reading in these definitions, probaly will accept included ones?
3676  // (but not forbid ltxml ?)
3677  assign_value("INCLUDE_STYLES", true, None);
3678  // When set, this variable allows redefinitions of locked defns.
3679  // It is set in before/after methods to allow local rebinding of commands
3680  // but loading of sources & bindings is typically done in before/after methods of constructors!
3681  // This re-locks defns during reading of TeX packages.
3682  local_state_unlocked(false);
3683  // An EMPTY virtual file still exists (`\tcbwritetemp` over an empty
3684  // `posterboxenv` body, tcbposter.code.tex:168-171) — `Some("")` keeps the
3685  // mouth off the disk; only `None` falls through to a real file.
3686  let content = crate::binding::virtual_files::vfs_read(pathname);
3687  let pathname_mouth = Mouth::create(pathname, MouthOptions {
3688    fordefinitions: true,
3689    at_letter,
3690    notes: true,
3691    content,
3692    ..MouthOptions::default()
3693  })?;
3694
3695  let read = RawReadGuard::enter(own_request.then_some(request));
3696  gullet::reading_from_mouth(pathname_mouth, move || -> Result<()> {
3697    while let Some(token) = gullet::read_x_token(Some(false), false, None)? {
3698      if token != T_SPACE!() {
3699        invoke_token(&token)?;
3700      }
3701    }
3702    Ok(())
3703  })?;
3704  drop(read);
3705
3706  // Expl3 scope-exit cleanup: if a raw .sty load activated expl3 catcodes
3707  // via `\ProvidesExplPackage` or explicit `\ExplSyntaxOn` and forgot to
3708  // pair it with `\ExplSyntaxOff` (e.g. lipsum.sty, which relies on an
3709  // `\AtEndOfPackage`-style hook the autoload chain doesn't register),
3710  // digest `\ExplSyntaxOff` now so the pending `\group_begin:` frame pops
3711  // and catcodes restore before the next package loads.
3712  //
3713  // Perl's `TeX.pool.ltxml` L44-47 acknowledges this as a known edge-
3714  // case of the `\ProvidesExplPackage` autoload pattern.
3715  //
3716  // Skip expl3 / xparse / l3keys2e / expl3-code — those legitimately
3717  // leave expl3 active for their callers.
3718  {
3719    let (_, base, _ext) = pathname::split(pathname);
3720    let is_expl3_core = matches!(
3721      base.as_str(),
3722      "expl3" | "xparse" | "l3keys2e" | "expl3-code"
3723    );
3724    // Use grandparent_in_expl3 (snapshotted before `\@pushfilename`)
3725    // rather than entered_expl3 (snapshotted after the push flipped `_`
3726    // to SUB). Without this, sub-loads inside an active expl3 frame
3727    // saw entered_expl3=false (because of the push's `\ExplSyntaxOff`)
3728    // and over-fired `\ExplSyntaxOff` at exit, which then leaks SUB
3729    // into the grandparent's continued reading once `\@popfilename`
3730    // pops the status stack and would otherwise restore `\ExplSyntaxOn`.
3731    // Witness: `\usepackage{xsavebox}` minimal repro (xsavebox →
3732    // sys_load_backend → l3backend-dvips.def); arXiv:2509.05997/.07893/
3733    // .02344, 2510.13206/.13942/.17317.
3734    // One-directional cleanup (grandparent-guarded, as before — the real
3735    // `\@pushfilename` expl3 hook runs BEFORE our entry snapshot, so a
3736    // bidirectional entry/exit restore mis-reads a grandparent-ON chain as
3737    // OFF and re-breaks the xsavebox witness):
3738    if std::env::var("LATEXML_EXPL_TRACE").is_ok() {
3739      eprintln!(
3740        "EXPL-EXIT request={request:?} is_core={is_expl3_core} grandparent={grandparent_in_expl3} handleopts={handleoptions} us_letter={} expl_on={} off_defined={}",
3741        lookup_catcode('_') == Some(Catcode::LETTER),
3742        expl_syntax_on(),
3743        lookup_definition(&T_CS!("\\ExplSyntaxOff"))?.is_some()
3744      );
3745    }
3746    // Fire ONLY for handleoptions frames (\usepackage/\documentclass —
3747    // where the real kernel's \@popfilename restores the expl status).
3748    // A PLAIN \input (handleoptions=false: ctex's `\file_input:n` of
3749    // ctex-engine-pdftex.def, .cfg, .spa sub-files) restores NOTHING in
3750    // real TeX — the loading code manages its own state (ctexhook's
3751    // \ctex_push_file:/\ctex_pop_file: expl-status stack). Firing here
3752    // mid-class fought that machinery and leaked FULL expl3 state past
3753    // `\documentclass{ctexart}` (space=9/`:`=11/`_`=11 at document
3754    // level), garbling pgfutil-common's space-trick and cascading 1001
3755    // errors in every ctex+tikz doc (hfutexam ×4, beautybook, gckanbun).
3756    // Only when the file left expl3 syntax ON, by expl3's own flag (`\l__kernel_expl_bool`, which `\ExplSyntaxOn`
3757    // sets and the `\ExplSyntaxOff` it arms clears, expl3-code.tex:242-272), not by `_`'s catcode: etextools.sty:35-56
3758    // makes `_` a letter for its own code and restores it in its own `\AtEndOfPackage` (:55); firing here left `/`
3759    // catcode 8 after the load and broke siunitx's `\AtBeginDocument` code (2606.06323).
3760    if !is_expl3_core
3761      && handleoptions
3762      && !grandparent_in_expl3
3763      && expl_syntax_on()
3764      && lookup_definition(&T_CS!("\\ExplSyntaxOff"))?.is_some()
3765    {
3766      let _ = invoke_token(&T_CS!("\\ExplSyntaxOff"));
3767    }
3768    // PARTIAL-leak normalization: space=catcode 9 (ignored) while `_` is
3769    // NOT a letter is an invalid half-ExplSyntax state no legitimate flow
3770    // produces (`\ExplSyntaxOn` sets both, `Off` clears both). l3backend-
3771    // *.def loaded nested under a raw class (jlreq/ctex → expl3.sty →
3772    // l3backend) left exactly this state, and every later raw file then
3773    // lost its space tokens: pgfkeys' space-delimited `\def\: {…}` idiom
3774    // broke and its .code/.style handler bodies EXECUTED, leaking `#1`
3775    // to the stomach (misdefined:# — gckanbun/ctex/jlreq tail; Perl
3776    // clean; ctex+tikz min-repro 1001→101 errors with this fix).
3777    if lookup_catcode(' ') == Some(Catcode::IGNORE) && lookup_catcode('_') != Some(Catcode::LETTER)
3778    {
3779      assign_catcode(' ', Catcode::SPACE, None);
3780    }
3781  }
3782
3783  assign_value_sym(
3784    crate::pin!("INTERPRETING_DEFINITIONS"),
3785    was_interpreting,
3786    None,
3787  );
3788  assign_value("INCLUDE_STYLES", was_including_styles, None);
3789  expire_state_unlocked();
3790
3791  // Perl Package.pm L2376/L2393 Lets \ver@<file> to \fmtversion
3792  // UNCONDITIONALLY — clobbering the version string the file's own
3793  // \ProvidesPackage just recorded, so every date guard downstream
3794  // (\GetFileInfo, \@ifpackagelater, toptesi.cls L44-73's version
3795  // comparison) reads the format date instead of the package's. Real LaTeX
3796  // keeps the declared string. OXIDIZED_DESIGN #169 (surpass-Perl,
3797  // user-approved 2026-08-31): apply \fmtversion only as a FALLBACK when
3798  // the file declared nothing — the same guarded idiom the LTXML-binding
3799  // loader above already uses. Witnesses: the 12-doc toptesi cluster
3800  // ("the sty file you are using has a date of <empty>" abort). Guard:
3801  // cluster_package_guards::raw_provides_version_survives.
3802  // (not when the file set the macro itself, fontenc.sty:123's `\relax`: only a query's `\relax` from before the read)
3803  if still_loading_mark(request, &loading_mark)
3804    || (!file_loaded(request) && lookup_meaning(&ver_cs) == ver_before)
3805  {
3806    let_i(&ver_cs, &T_CS!("\\fmtversion"), Some(Scope::Global));
3807  }
3808
3809  Ok(())
3810}
3811
3812/// The state mapping of the files read as the document's content ([`load_tex_content`]: the main file, each
3813/// `\input`/`\include` of content, a `literal:` source as its text) to their reading order: the document's own text,
3814/// which the title-page check reads for the words the document wrote (latexml_engine
3815/// `base_utilities::frontmatter::title_page_check`). Rust-only. A mapping, so a book of thousands of files interns each
3816/// path once (issue 1011: a list re-interned whole per file filled the arena).
3817pub const CONTENT_FILES: &str = "lx_content_files";
3818
3819/// The document's content files ([`CONTENT_FILES`]), in the order they were first read.
3820pub fn content_files() -> Vec<String> {
3821  let mut files: Vec<(i64, SymStr)> = with_value(CONTENT_FILES, |files| match files {
3822    Some(Stored::HashStored(files)) => files
3823      .0
3824      .iter()
3825      .filter_map(|(path, order)| match order {
3826        Stored::Int(order) => Some((*order, *path)),
3827        _ => None,
3828      })
3829      .collect(),
3830    _ => Vec::new(),
3831  });
3832  files.sort_unstable();
3833  files
3834    .into_iter()
3835    .map(|(_, path)| arena::to_string(path))
3836    .collect()
3837}
3838
3839/// Note `path` as one of the document's content files ([`CONTENT_FILES`]), once.
3840fn note_content_file(path: &str) {
3841  if lookup_mapping(CONTENT_FILES, path).is_some() {
3842    return;
3843  }
3844  let order = with_value(CONTENT_FILES, |files| match files {
3845    Some(Stored::HashStored(files)) => files.len(),
3846    _ => 0,
3847  });
3848  assign_mapping(
3849    CONTENT_FILES,
3850    path,
3851    Some(Stored::Int(i64::try_from(order).unwrap_or(i64::MAX))),
3852  );
3853}
3854
3855/// Whether `\everyeof` holds tokens: an `\input` under it feeds a reader of the file's tokens, so no binding answers
3856/// it (see [`input`]).
3857fn everyeof_is_set() -> bool {
3858  matches!(
3859    lookup_register("\\everyeof", Vec::new()),
3860    Ok(Some(crate::definition::register::RegisterValue::Tokens(tokens))) if !tokens.is_empty()
3861  )
3862}
3863
3864/// TeX's `\input` of `path` while definitions are read and `\everyeof` is set: the file's text joins the input
3865/// stream under the current catcodes and ends with the `\everyeof` tokens, for the reader that set them. Neither
3866/// content of the document (no [`CONTENT_FILES`] entry, no binding) nor a definitions file (no loaded mark).
3867fn read_as_token_list(path: &str) -> Result<()> {
3868  let content = crate::binding::virtual_files::vfs_read(path);
3869  gullet::open_mouth(
3870    Mouth::create(path, MouthOptions {
3871      notes: true,
3872      content,
3873      ..MouthOptions::default()
3874    })?,
3875    true,
3876  );
3877  gullet::mark_everyeof_mouth()
3878}
3879
3880pub fn load_tex_content(path: &str, _options: InputOptions) -> Result<()> {
3881  // If there is a file-specific declaration file (name_tex.rs), load it first!
3882  // TODO: is this `.latexml` variation still relevant in the Rust port?
3883  let _has_binding = if !pathname::is_literaldata(path) {
3884    let (_dir, base, _ext) = pathname::split(path);
3885    load_external_binding(&base)?.is_some() || load_binding(&base)?.is_some()
3886  } else {
3887    false
3888  };
3889
3890  note_content_file(path);
3891  // Open a mouth for that TeX content
3892  // Empty virtual files exist too (see load_definitions above).
3893  let cached_opt = crate::binding::virtual_files::vfs_read(path);
3894  gullet::open_mouth(
3895    Mouth::create(path, MouthOptions {
3896      notes: true,
3897      content: cached_opt,
3898      ..MouthOptions::default()
3899    })?,
3900    true,
3901  );
3902  // eTeX inserts the CURRENT `\everyeof` token list at the end of EVERY
3903  // `\input` file, not only a `\scantokens` pseudo-file (etex.web §362: the
3904  // list is begun before `end_file_reading`, so a delimited scan may consume
3905  // it and no more). Line-reader idioms depend on that terminator: tikzlings'
3906  // `\CommentInput` (tikzmarmots-doc.tex:44-105, `\tex_everyeof:D{\q_nil^^M}`
3907  // + `\tex_input:D`, one `\__tikzlings_process_line:w #1^^M` per line),
3908  // stex.sty:2633 smsmode, expl3 `\file_get:nnN` (expl3-code.tex:12530-12551,
3909  // `\__file_get_do:Nw #1#2 \c__file_marker_tl` scanning across the file).
3910  // Without the mark the reader ran into the enclosing document and looped at
3911  // its true end (tikzmarmots-doc 0→501 errors + Fatal, tikzlings-doc 35→536,
3912  // sweep 28). Guard: `perfect_kernel_batch51::input_file_end_inserts_everyeof`.
3913  gullet::mark_everyeof_mouth()
3914}
3915
3916/// Pass the sequence of @options to the package $name (if $ext is 'sty'),
3917/// or class $name (if $ext is 'cls').
3918/// Perl Package.pm: PassOptions($name, $ext, @options)
3919/// Stores options to be processed when the package/class is loaded.
3920///
3921/// The raw record is the options re-read with standard catcodes
3922/// ([`option_argument_tokens`]): these lists come from the loader's explicit
3923/// `[…]` or from a binding, already expanded. `\PassOptionsToPackage` /
3924/// `\PassOptionsToClass` keep their argument tokens instead, through
3925/// [`pass_options_with_raw`].
3926pub fn pass_options(name: &str, ext: &str, options: Vec<String>) -> Result<()> {
3927  let raw = option_argument_tokens(&options.join(","));
3928  pass_options_with_raw(name, ext, options, raw)
3929}
3930
3931/// latex.ltx:18509-18526 `\@pass@ptions`, the single writer of both option
3932/// records. `\opt@<name>.<ext>` is the `\protected@xdef`ed list the loader
3933/// and `\ProcessOptions` read (here a State list of strings). `\@raw@opt@<name>.<ext>`
3934/// holds the unprocessed argument tokens, accumulated comma-separated
3935/// (:18521-18525): `\gdef` on the first pass, `\g@addto@macro{,#2}` after.
3936/// ltkeys' `\ProcessKeyOptions` reads only this record (:19398, :19457-19470).
3937///
3938/// OXIDIZED_DESIGN #164. LaTeXML's binding-level loader bypasses the kernel's,
3939/// so the record was never made and every `\ProcessKeyOptions` package dropped
3940/// its options (codedescribe `[strict,infograb]`, 10 TL-doc bundles). It is
3941/// written from `\PassOptionsTo*` too, so tudapub.cls:194's `\exp_args:Nx
3942/// \PassOptionsToPackage{paper=…}{tudarules}` reaches tudarules
3943/// (DEMO-TUDaPhD). It is written at pass time, so it exists before the load and
3944/// holds the tokens themselves: fduthesis.cls:193-202 and hustthesis.cls:197
3945/// pass `linespread = \c__fdu_line_spread_fp` to ctexbook, whose
3946/// x-expanded, re-tokenized spelling fell apart into `\s`, `__fp`… at
3947/// ctexbook.cls:336 `\ProcessKeyOptions` (TeX Live class census 2026-09-24).
3948/// It is defined for every load, an option-less one included (the empty
3949/// explicit list): scrhack.sty:284-293 forwards `\use:c{@raw@opt@setspace.sty}`
3950/// as an option of setspaceenhanced (ijsra, sweep 72; batch 56bq). Guards:
3951/// `perfect_kernel_batch53::process_key_options_sees_passed_options`,
3952/// `class_census::passed_options_keep_their_tokens`.
3953pub fn pass_options_with_raw(
3954  name: &str,
3955  ext: &str,
3956  options: Vec<String>,
3957  raw: Tokens,
3958) -> Result<()> {
3959  let key = s!("opt@{}.{}", name, ext);
3960  // (`\opt@<file>` is the list itself, latex.ltx:18514-18517: a pass after the load extends it, which a repeat load's
3961  // classic clash test, `\@if@ptions`, reads — a neurips_2022.sty copy's `\PassOptionsToPackage{numbers}{natbib}` after
3962  // the binding's natbib load, then the document's `\usepackage[numbers]{natbib}`: no clash, 2403.07005. Kept apart
3963  // from our `\opt@<file>`, which bindings read after the load as the load's own options: babel's main language.)
3964  if !options.is_empty() && file_loaded(&s!("{name}.{ext}")) {
3965    let passed_key = s!("{name}.{ext}_passed_after_load");
3966    let mut passed = lookup_string(&passed_key);
3967    for opt in &options {
3968      if !passed.is_empty() {
3969        passed.push(',');
3970      }
3971      passed.push_str(opt);
3972    }
3973    assign_value(&passed_key, passed, Some(Scope::Global));
3974  }
3975  for opt in options {
3976    push_value(&key, arena::pin(&opt))?;
3977  }
3978  let raw_opt_cs = T_CS!(s!("\\@raw@opt@{}.{}", name, ext));
3979  // `\@ifundefined`: a macro is a record, anything else (`\relax`) is not.
3980  let previous = match lookup_meaning(&raw_opt_cs) {
3981    Some(Stored::Expandable(defn)) => match defn.get_expansion() {
3982      Some(ExpansionBody::Tokens(tokens)) => Some(tokens.clone().unlist()),
3983      None => Some(Vec::new()),
3984      Some(_) => None,
3985    },
3986    _ => None,
3987  };
3988  let body = match previous {
3989    Some(mut tokens) => {
3990      tokens.push(T_OTHER!(","));
3991      tokens.extend(raw.unlist());
3992      Tokens::new(tokens)
3993    },
3994    None => raw,
3995  };
3996  def_macro(
3997    raw_opt_cs,
3998    None,
3999    body,
4000    Some(ExpandableOptions {
4001      scope: Some(Scope::Global),
4002      ..ExpandableOptions::default()
4003    }),
4004  )?;
4005  Ok(())
4006}
4007
4008/// latex.ltx:18854-18867, after a package's end hook: options its `\ProcessOptions` marked processed (or the legacy
4009/// `\@unprocessedoptions` flag, `\relax` after kvoptions' `\ProcessKeyvalOptions`, kvoptions.sty:739) are done with;
4010/// otherwise `\@@unprocessedoptions` (:18923-18928) leaves the package's own options in `\@curroptions` — so a package
4011/// required with none sees what the last one left (epstopdf-base.sty:151). Its unknown-option errors are not raised here.
4012fn unprocessed_options(name: &str, ext: &str) -> Result<()> {
4013  let processed = remove_value(&s!("lx@options@processed@{name}.{ext}")).is_some();
4014  let legacy_relax = lookup_meaning(&T_CS!("\\@unprocessedoptions"))
4015    .is_some_and(|meaning| lookup_meaning(&T_RELAX!()).is_some_and(|relax| meaning == relax));
4016  if legacy_relax {
4017    let_i(
4018      &T_CS!("\\@unprocessedoptions"),
4019      &T_CS!("\\@undefined"),
4020      None,
4021    );
4022  }
4023  if processed || legacy_relax || ext != "sty" {
4024    return Ok(());
4025  }
4026  let opt_cs = T_CS!(s!("\\opt@{name}.{ext}"));
4027  let options = if lookup_definition(&opt_cs)?.is_some() {
4028    do_expand(opt_cs)?
4029  } else {
4030    Tokens::default()
4031  };
4032  def_macro(T_CS!("\\@curroptions"), None, options, None)
4033}
4034
4035/// The control sequence a binding's `DeclareOption` defines, its name recorded as declared: Perl Package.pm:2421-2423,
4036/// `\ds@<option>` whole, and an empty name (Perl's false `$option`, as undef) is the default handler `\default@ds`.
4037pub fn declare_option_cs(option: &str) -> Result<Token> {
4038  if option.is_empty() {
4039    return Ok(T_CS!("\\default@ds"));
4040  }
4041  push_value("@declaredoptions", arena::pin(option))?;
4042  Ok(T_CS!(s!("\\ds@{option}")))
4043}
4044
4045/// Perl Package.pm L2430-2465: ProcessOptions / ProcessOptions*
4046/// `inorder=false` (\ProcessOptions) — execute in declared order, default handler for undeclared
4047/// `inorder=true` (\ProcessOptions*) — execute in order passed, class options silently skipped
4048pub fn process_options(inorder: bool, keysets: &[&str]) -> Result<()> {
4049  process_options_by(inorder, keysets, true)
4050}
4051
4052/// The options run as [`process_options`] runs them, for a package whose own options a key=value processor reads:
4053/// the kernel's `\ProcessKeyOptions` (latex.ltx:19379), kvoptions (kvoptions.sty:739), xkeyval (xkeyval.sty:132),
4054/// pgfopts (pgfopts.sty:32), l3keys2e (l3keys2e.sty:67), caption3 (caption3.sty:399). Each marks the options processed
4055/// at the package's end and leaves `\@curroptions` as it was.
4056pub fn process_key_options(inorder: bool, keysets: &[&str]) -> Result<()> {
4057  process_options_by(inorder, keysets, false)
4058}
4059
4060/// A key=value processor's mark without running options here ([`process_key_options`]): the current package's
4061/// options are processed, and `\@curroptions` stays as it was at its end.
4062pub fn key_options_processed() -> Result<()> {
4063  let name = expand_if_defined(T_CS!("\\@currname"))?;
4064  let ext = expand_if_defined(T_CS!("\\@currext"))?;
4065  assign_value(
4066    &s!("lx@options@processed@{name}.{ext}"),
4067    true,
4068    Some(Scope::Global),
4069  );
4070  Ok(())
4071}
4072
4073fn expand_if_defined(token: Token) -> Result<String> {
4074  Ok(if lookup_definition(&token)?.is_some() {
4075    do_expand(token)?.to_string()
4076  } else {
4077    String::new()
4078  })
4079}
4080
4081fn process_options_by(inorder: bool, keysets: &[&str], sets_curroptions: bool) -> Result<()> {
4082  let currname_token = T_CS!("\\@currname");
4083  let currext_token = T_CS!("\\@currext");
4084  let name = if lookup_definition(&currname_token)?.is_some() {
4085    do_expand(currname_token)?.to_string()
4086  } else {
4087    String::new()
4088  };
4089  let ext = if lookup_definition(&currext_token)?.is_some() {
4090    do_expand(currext_token)?.to_string()
4091  } else {
4092    String::new()
4093  };
4094  let declared_options: VecDeque<Stored> = lookup_vecdeque("@declaredoptions").unwrap_or_default();
4095  let opt_key = s!("opt@{}.{}", name, ext);
4096  // latex.ltx:18557 `\ProcessOptions` reads `\@curroptions` from `\@ptionlist
4097  // {\@currname.\@currext}` (:18393) — the MACRO `\opt@<name>.<ext>`, which a
4098  // package may rewrite before processing: babel.sty:316-347 strips the
4099  // `language.modifier` syntax (`greek.polutoniko` → `greek`, the modifier
4100  // kept in `\bbl@mod@greek`) by redefining `\opt@babel.sty`. Perl
4101  // (Package.pm:2430-2465) and the former Rust read the State list the loader
4102  // stored, so babel still saw `greek.polutoniko` and raised "Unknown option"
4103  // (alphabeta-doc, hyperref-with-greek; SHARED). The macro is the source of
4104  // truth when it exists (the loader defines it from the same list, so they
4105  // agree unless a package rewrote it); the list is the fallback. Guard:
4106  // `perfect_kernel_batch54::processoptions_reads_the_rewritten_opt_macro`.
4107  // The read is :18557's `\protected@edef\@curroptions{…}`: a robust or protected command in an option value stands
4108  // (`\usepackage[figurename=\textsc{Fig}]{caption}` names the figures "Fig", not `\textsc`'s expansion; a full
4109  // expansion gave two undefined-command errors). Guard: `perfect_kernel_batch68h::caption_option_values_unexpanded`.
4110  let opt_cs = T_CS!(s!("\\{opt_key}"));
4111  let current_options: VecDeque<Stored> = if lookup_definition(&opt_cs)?.is_some() {
4112    let mut items: VecDeque<Stored> = VecDeque::new();
4113    let mut cur: Vec<Token> = Vec::new();
4114    let mut depth: i32 = 0;
4115    let push_item = |cur: &mut Vec<Token>, items: &mut VecDeque<Stored>| {
4116      let text = Tokens::new(std::mem::take(cur)).to_string();
4117      let text = text.trim();
4118      if !text.is_empty() {
4119        items.push_back(Stored::String(arena::pin(text)));
4120      }
4121    };
4122    let protect_regime = T_CS!("\\@unexpandable@protect");
4123    let read = || gullet::do_expand_partially(opt_cs);
4124    let expanded = if lookup_meaning(&protect_regime).is_some() {
4125      with_let(&T_CS!("\\protect"), &protect_regime, read)?
4126    } else {
4127      read()?
4128    };
4129    for t in expanded.unlist() {
4130      match t.get_catcode() {
4131        Catcode::BEGIN => depth += 1,
4132        Catcode::END => depth -= 1,
4133        _ => {},
4134      }
4135      if depth == 0 && t.get_catcode() == Catcode::OTHER && t.with_str(|s| s == ",") {
4136        push_item(&mut cur, &mut items);
4137      } else {
4138        cur.push(t);
4139      }
4140    }
4141    push_item(&mut cur, &mut items);
4142    items
4143  } else {
4144    lookup_vecdeque(&opt_key).unwrap_or_default()
4145  };
4146  let class_options = lookup_vecdeque("class_options").unwrap_or_default();
4147
4148  let collect_syms = |vdq: &VecDeque<Stored>| -> Vec<SymStr> {
4149    let mut list = Vec::new();
4150    for item in vdq.iter() {
4151      match item {
4152        Stored::String(s) => {
4153          list.push(*s);
4154        },
4155        Stored::Strings(ss) => {
4156          for s in ss.iter() {
4157            list.push(*s);
4158          }
4159        },
4160        _ => {},
4161      }
4162    }
4163    list
4164  };
4165  let cur_options_list = collect_syms(&current_options);
4166  let cls_options_list = collect_syms(&class_options);
4167  // latex.ltx:18555-18558: `\ProcessOptions` leaves the options it reads in `\@curroptions` (a key=value processor
4168  // does not), and at the package's end (:18597-18599) marks them processed, so the loader's `\@@unprocessedoptions`
4169  // does not reset it (`unprocessed_options`). epstopdf-base.sty:151 reads it.
4170  let cur_options_text = cur_options_list
4171    .iter()
4172    .map(|option| arena::with(*option, |o| o.to_string()))
4173    .collect::<Vec<_>>()
4174    .join(",");
4175  if sets_curroptions {
4176    def_macro(
4177      T_CS!("\\@curroptions"),
4178      None,
4179      Tokens!(ExplodeText!(cur_options_text)),
4180      None,
4181    )?;
4182  }
4183  assign_value(
4184    &s!("lx@options@processed@{name}.{ext}"),
4185    true,
4186    Some(Scope::Global),
4187  );
4188
4189  if inorder {
4190    // Perl L2447-2453: ProcessOptions* — execute in the order passed
4191    // Class options: try executeOption_internal only (no default fallback)
4192    for option in &cls_options_list {
4193      let _ = execute_option_internal(*option, keysets)?;
4194    }
4195    // Current options: try executeOption, then default handler
4196    for option in &cur_options_list {
4197      if !execute_option_internal(*option, keysets)? {
4198        execute_default_option_internal(*option)?;
4199      }
4200    }
4201  } else {
4202    // Perl L2454-2461: ProcessOptions — execute in declared order
4203    let mut cur_set: HashSet<SymStr> = cur_options_list.iter().copied().collect();
4204    let mut cls_set: HashSet<SymStr> = cls_options_list.iter().copied().collect();
4205
4206    for option in declared_options.iter() {
4207      match option {
4208        Stored::String(content) if cur_set.remove(content) || cls_set.remove(content) => {
4209          execute_option_internal(*content, keysets)?;
4210        },
4211        Stored::Strings(contents) => {
4212          for content in contents.iter() {
4213            if cur_set.remove(content) || cls_set.remove(content) {
4214              execute_option_internal(*content, keysets)?;
4215            }
4216          }
4217        },
4218        _ => {},
4219      }
4220    }
4221    // Only undeclared CURRENT options go to default handler (not class options).
4222    // Perl L2460-2461: "foreach my $option (@curroptions)" — class options excluded.
4223    // Iterate cur_options_list (Vec, ordered) instead of cur_set (HashSet,
4224    // unordered) so unknown options enter `@unusedoptionlist` in source
4225    // order. Otherwise `\documentstyle[a,b,c]` produces an arbitrary
4226    // dispatch order, which breaks paper-local option chains that depend
4227    // on left-to-right evaluation (e.g. `[aaspp4,tighten]` requires
4228    // aaspp4's bindings — \tightenlines — to be defined before tighten.sty
4229    // body fires; driver: astro-ph9707180).
4230    // latex.ltx:18587-18592 `\@process@pti@ns`: such an option still runs its `\ds@<option>` when one is defined
4231    // (`\@ifundefined`: not `\relax`) — a 2.09-style class `\def`s its handlers without `\DeclareOption` (gji.cls:61-70,
4232    // 2605.19951; biom.cls:48 `\def\ds@usenatbib`, 2606.12015) — and `\default@ds` only otherwise. Perl
4233    // (Package.pm:2476-2478) sends every one to the default handler (KNOWN_PERL_ERRORS #657). Only for the kernel's
4234    // `\ProcessOptions` (`sets_curroptions`): the key=value processors (`ProcessKeyOptions!`: kvoptions, xkeyval,
4235    // l3keys) do not look an undeclared option up as `\ds@<option>`.
4236    for option in &cur_options_list {
4237      if cur_set.contains(option) && !(sets_curroptions && execute_option_internal(*option, &[])?) {
4238        execute_default_option_internal(*option)?;
4239      }
4240    }
4241  }
4242  // Now, undefine the handlers
4243  for option in declared_options.iter() {
4244    let_i(&T_CS!(s!("\\ds@{}", option)), &T_RELAX!(), None);
4245  }
4246  Ok(())
4247}
4248
4249/// Whether expl3 syntax is on, by expl3's own flag: expl3-code.tex:242 `\chardef\l__kernel_expl_bool`, set to 1 by
4250/// `\ExplSyntaxOn` and back to 0 by the `\ExplSyntaxOff` it arms (:243-272). False before expl3 is loaded.
4251fn expl_syntax_on() -> bool {
4252  lookup_definition(&T_CS!("\\l__kernel_expl_bool"))
4253    .ok()
4254    .flatten()
4255    .filter(|defn| defn.is_register())
4256    .and_then(|defn| defn.value_of(Vec::new()))
4257    .is_some_and(|value| crate::common::numeric_ops::NumericOps::value_of(value) == 1)
4258}
4259
4260fn execute_option_internal(option: SymStr, keysets: &[&str]) -> Result<bool> {
4261  if let Some((qname, value)) = keyval_option_qname(option, keysets) {
4262    // Perl Package.pm handles `key=value` package options before normal
4263    // `\ds@...` lookup when ProcessOptions was given keysets. It digests
4264    // `\KV@<keyset>@<key>{<value>}`. Rust DefKeyVal entries without code
4265    // are ordinary macros, so also store the value under the qname for
4266    // package bindings that apply keyvals after ProcessOptions.
4267    assign_value(
4268      &qname,
4269      Stored::String(arena::pin(value.trim())),
4270      Some(Scope::Global),
4271    );
4272    // The value is the option's ARGUMENT tokens (latex.ltx:18514 stores them
4273    // by `\protected@xdef`): standard catcodes, braces group, and keyval
4274    // strips one brace level (`\KV@@sp@def`) — `vmargin={0mm,0mm}` hands
4275    // `0mm,0mm` to the key, not `{0mm,0mm}` with OTHER braces (geometry
4276    // package options gave "Missing number" ×4; elzcards root-causer).
4277    let bare = value
4278      .strip_prefix('{')
4279      .and_then(|v| v.strip_suffix('}'))
4280      .unwrap_or(&value);
4281    let mut call = vec![T_CS!(s!("\\{qname}")), T_BEGIN!()];
4282    call.extend(option_argument_tokens(bare).unlist());
4283    call.push(T_END!());
4284    digest(Tokens::new(call))?;
4285    return Ok(true);
4286  }
4287
4288  let cs = T_CS!(arena::with(option, |opt| s!("\\ds@{opt}")));
4289  // latex.ltx `\@use@ption`: `\@ifundefined{ds@<option>}` — a handler
4290  // `\let` to `\relax` (the class's `landscape`/`a4paper` after its own
4291  // `\ProcessOptions`, cleared below) counts as UNDEFINED, so the package's
4292  // `\DeclareOption*` default runs for it (geometry's `landscape,a4paper`
4293  // were silently swallowed as "declared"; Perl Package.pm:2481-2486 retains
4294  // the swallow — Rust matches `\@ifundefined`, OXIDIZED_DESIGN_DIVERGENCES
4295  // #223).
4296  if lookup_definition(&cs)?.is_some() && !x_equals(&cs, &T_RELAX!()) {
4297    // Perl Package.pm L2482: `DefMacroI('\CurrentOption', undef, $option)` —
4298    // tokenizes `$option` via Tokens(Explode($option)) so letters get
4299    // catcode LETTER and others OTHER. Babel's `\ifx\CurrentOption\bbl@tempa`
4300    // (where `\bbl@tempa{frenchb}` produces LETTER tokens) only matches when
4301    // our `\CurrentOption` body has the same catcodes. Real LaTeX's
4302    // `\CurrentOption` is the ARGUMENT tokens (latex.ltx:18514), so braces
4303    // GROUP: geometry's `\DeclareOption*{…\CurrentOption}` → `\setkeys*{Gm}
4304    // {vmargin={0mm,0mm}}` needs them (OTHER braces split the pair at its
4305    // comma: "Missing number" ×4). Standard-catcode tokenization keeps
4306    // babel's LETTER match and the braces.
4307    def_macro(
4308      T_CS!("\\CurrentOption"),
4309      None,
4310      option_argument_tokens(&arena::to_string(option)),
4311      None,
4312    )?;
4313
4314    let unused = match remove_vecdeque("@unusedoptionlist") {
4315      Some(list) => list
4316        .into_iter()
4317        .filter(|item| {
4318          if let Stored::String(content) = item {
4319            *content != option
4320          } else {
4321            false
4322          }
4323        })
4324        .collect(),
4325      None => VecDeque::new(),
4326    };
4327    assign_value("@unusedoptionlist", Stored::VecDequeStored(unused), None);
4328    digest(cs)?;
4329    Ok(true)
4330  } else {
4331    Ok(false)
4332  }
4333}
4334
4335/// An option's ARGUMENT tokens (latex.ltx:18514 `\@pass@ptions` stores them by
4336/// `\protected@xdef`): letters LETTER (babel's `\ifx\CurrentOption\bbl@tempa`
4337/// match), braces GROUP (`vmargin={0mm,0mm}` is one pair for `\setkeys`), and
4338/// `@` a LETTER too — the list crossed a string, and a control word in it
4339/// came from package/class code where `@` is a letter (xebaposter.cls passes
4340/// `paperwidth=\xebaposter@finalpaperwidth`, a register token, to geometry;
4341/// re-read with `@` OTHER it split into the undefined `\xebaposter`; the
4342/// `\@raw@opt@` writer makes the same choice) — without the tokenizer's
4343/// end-of-line space, which is not part of the argument (`landscape␣` matched
4344/// no key).
4345pub fn option_argument_tokens(text: &str) -> Tokens {
4346  let mut toks = crate::mouth::tokenize_internal(TeXString::assembled(text.to_string())).unlist();
4347  while toks
4348    .last()
4349    .is_some_and(|t| t.get_catcode() == Catcode::SPACE)
4350  {
4351    toks.pop();
4352  }
4353  Tokens::new(toks)
4354}
4355
4356fn keyval_option_qname(option: SymStr, keysets: &[&str]) -> Option<(String, String)> {
4357  if keysets.is_empty() {
4358    return None;
4359  }
4360  let (key, value) = arena::with(option, |opt| {
4361    opt
4362      .split_once('=')
4363      .map(|(key, value)| (key.trim().to_string(), value.trim().to_string()))
4364  })?;
4365  if key.is_empty() {
4366    return None;
4367  }
4368  for keyset in keysets {
4369    let qname = crate::keyval::keyval_qname("KV", keyset, &key);
4370    if crate::keyval::keyval_get(&qname, "type").is_some() {
4371      return Some((qname, value));
4372    }
4373  }
4374  None
4375}
4376
4377fn execute_default_option_internal(option: SymStr) -> Result<bool> {
4378  // Perl Package.pm L2494: `DefMacroI('\CurrentOption', undef, $option)`.
4379  // Same argument-token spelling as execute_option_internal.
4380  def_macro(
4381    T_CS!("\\CurrentOption"),
4382    None,
4383    option_argument_tokens(&arena::to_string(option)),
4384    None,
4385  )?;
4386  digest(T_CS!("\\default@ds"))?;
4387  Ok(true)
4388}
4389
4390fn reset_options() -> Result<()> {
4391  assign_value(
4392    "@declaredoptions",
4393    Stored::VecDequeStored(VecDeque::new()),
4394    None,
4395  );
4396  let opt_unused_cs = if do_expand(T_CS!("\\@currext"))?.eq_text("cls") {
4397    "\\OptionNotUsed"
4398  } else {
4399    "\\@unknownoptionerror"
4400  };
4401  let_i(&T_CS!("\\default@ds"), &T_CS!(opt_unused_cs), None);
4402  Ok(())
4403}
4404
4405/// Execute a list of options (Perl: ExecuteOptions).
4406/// Tries each option's \ds@{option} definition; logs unexpected ones.
4407pub fn execute_options(options: &[&str]) -> Result<()> {
4408  let mut unhandled = Vec::new();
4409  for option in options {
4410    let sym = arena::pin(*option);
4411    if !execute_option_internal(sym, &[])? {
4412      unhandled.push(*option);
4413    }
4414  }
4415  for option in &unhandled {
4416    Info!(
4417      "unexpected",
4418      *option,
4419      s!("Unexpected options passed to ExecuteOptions '{option}'")
4420    );
4421  }
4422  Ok(())
4423}
4424
4425pub struct RequireOptions {
4426  pub options:          Vec<String>,
4427  pub withoptions:      Option<Vec<String>>,
4428  pub extension:        Option<Cow<'static, str>>,
4429  pub searchpaths_only: bool,
4430  pub as_class:         bool,
4431  pub noltxml:          Option<bool>,
4432  pub notex:            Option<bool>,
4433  pub after:            Tokens,
4434}
4435impl Default for RequireOptions {
4436  fn default() -> Self {
4437    RequireOptions {
4438      options:          Vec::new(),
4439      withoptions:      None,
4440      extension:        None,
4441      notex:            None,
4442      noltxml:          None,
4443      as_class:         false,
4444      searchpaths_only: false,
4445      after:            Tokens!(),
4446    }
4447  }
4448}
4449
4450/// An opinionated binding for \RequirePackage.
4451///
4452/// This (and `FindFile`) needs to evolve a bit to support reading raw .sty (.def, etc) files from
4453/// the standard texmf directories.  Maybe even use kpsewhich itself (INSTEAD of `pathname_find`
4454/// ???) Another potentially useful option might be that if we are reading a raw file,
4455/// perhaps it should just get digested immediately, since it shouldn't contribute any boxes.
4456/// OXIDIZED_DESIGN #177: a package requested by a source-tree relative path
4457/// (`\usepackage{../tex/tikzpingus}` — the CTAN layout where `doc/` and
4458/// `tex/` are siblings; 61 TL doc manuals) falls back to its basename when
4459/// the literal path resolves nowhere but the basename does. pdflatex and
4460/// Perl both fail in the installed tree (kpathsea misses `../tex/`), and the
4461/// whole manual's error mass follows from the package never loading. Only a
4462/// MISS is rerouted: a path that resolves (a paper's own `./mypkg`,
4463/// arXiv 0906.3507) still loads the local file. Guard:
4464/// `perfect_kernel_batch54::relative_package_path_falls_back_to_basename`.
4465/// A path that resolves to the very file its basename does (`\usepackage{graphics/graphicx}`, kpathsea's
4466/// `tex/latex/graphics/graphicx.sty`) is that package, and loads through the basename's binding when it has one:
4467/// the raw graphicx.sty over our graphics binding exhausted memory at the first `\rotatebox` (2309.12794).
4468fn source_tree_basename<'a>(name: &'a str, ext: &str) -> Cow<'a, str> {
4469  if !name.contains('/') {
4470    return Cow::Borrowed(name);
4471  }
4472  let base = name.rsplit('/').next().unwrap_or(name);
4473  if let Some(path) = find_file(&s!("{name}.{ext}"), None) {
4474    if !base.is_empty()
4475      && binding_exists(base, ext)
4476      && find_file(&s!("{base}.{ext}"), None).as_deref() == Some(path.as_str())
4477    {
4478      Info!(
4479        "loading",
4480        name,
4481        s!("'{name}.{ext}' is the installed '{base}.{ext}'; loading it as '{base}'")
4482      );
4483      return Cow::Owned(base.to_string());
4484    }
4485    return Cow::Borrowed(name);
4486  }
4487  if base.is_empty() || find_file(&s!("{base}.{ext}"), None).is_none() {
4488    return Cow::Borrowed(name);
4489  }
4490  Info!(
4491    "loading",
4492    name,
4493    s!("'{name}.{ext}' is not on disk; loading the installed '{base}.{ext}' instead")
4494  );
4495  Cow::Owned(base.to_string())
4496}
4497
4498pub fn require_package(name: &str, mut options: RequireOptions) -> Result<()> {
4499  let ext = options.extension.as_deref().unwrap_or("sty").to_string();
4500  // A `"` quotes spaces in a file name and is not part of it (tex.ch `more_name`, as `tex_file_name` reads `\input`):
4501  // `\usepackage{"mydefs"}` opens `mydefs.sty` (2407.00688: not found, its `\r`/`\b`/`\g` kept their accent meanings).
4502  let unquoted: Cow<str> = if name.contains('"') {
4503    Cow::Owned(name.replace('"', ""))
4504  } else {
4505    Cow::Borrowed(name)
4506  };
4507  let name = source_tree_basename(&unquoted, &ext);
4508  let name = name.as_ref();
4509  // A stand-in's copy read after its binding (`read_stand_in_copy`) runs the very `\usepackage`/`\RequirePackage`
4510  // lines the binding's dependency scan stands in for, so they take the scan's test (`marked_loaded_unrecorded`,
4511  // latex.ltx:18750 `\@ifl@aded`): a package the document marked loaded is skipped (sn-jnl.cls:311
4512  // `\usepackage{program}` under sn-jnl-setup.sty's `\AddToHook{class/sn-jnl/before}`, 2201.11056).
4513  if crate::definition::origin::copy_provides() != 0 && marked_loaded_unrecorded(name, &ext) {
4514    return Ok(());
4515  }
4516  // Perl Package.pm L2671-2672: notex defaults to true unless the user
4517  // explicitly set it, or INCLUDE_STYLES is true, or noltxml was passed
4518  // (a raw-only load explicitly requests raw TeX).
4519  // A source registered in `INTERPRETABLE_SOURCES` is one a binding (or the
4520  // kernel) has vouched for as safe to interpret — that is the point of the
4521  // registration — so it is raw-loaded even without `--includestyles`
4522  // (physics2.sty and its `phy-*` modules, fontawesome7.sty:
4523  // latex_constructs_rust_only.rs §10; the alternative was the wrong
4524  // glued-suffix fallback binding). Perl gates it on `notex` too, and so
4525  // misloads physics2 under its default configuration.
4526  if options.notex.is_none()
4527    && !lookup_bool("INCLUDE_STYLES")
4528    && !matches!(options.noltxml, Some(true))
4529    && lookup_mapping("INTERPRETABLE_SOURCES", &s!("{name}.{ext}")).is_none()
4530  {
4531    options.notex = Some(true);
4532  }
4533  // Perl Package.pm L2674: top-level \RequirePackage can be limited to
4534  // local sources via searchpaths_only. Triggered by the `localrawstyles`
4535  // option to latexml.sty (sets `INCLUDE_STYLES => 'searchpaths'`).
4536  // Only applies when raw TeX is allowed (notex==false); otherwise the
4537  // gate is moot since find_file won't search on-disk anyway.
4538  if !options.searchpaths_only
4539    && !matches!(options.notex, Some(true))
4540    && lookup_string("INCLUDE_STYLES") == "searchpaths"
4541  {
4542    options.searchpaths_only = true;
4543  }
4544  if options.extension.is_none() {
4545    options.extension = Some("sty".into());
4546  }
4547  // OXIDIZED_DESIGN #65 (#311): a package loaded inside a bracket LaTeXML ITSELF
4548  // opened must still end up defined at the outermost level, so hoist the load's
4549  // meaning-delta past it. Real LaTeX has no such bracket — `\@fileswithoptions`
4550  // (latex.ltx L18700) refuses to load at `\currentgrouplevel > 0` — but we
4551  // execute a subfile preamble the real `standalone.sty` gobbles (divergence
4552  // #63), which splits the package in half: frame-local definitions, global
4553  // hooks. Witness: `pgfcoreexternal.code.tex` L152
4554  // `\newif\ifpgf@external@grabshipout` popped with the child while its L171-179
4555  // `\AtEndDocument` reaches the parent's `\end{document}`. `tex.rs::def_autoload`
4556  // already used this snapshot/hoist pair for the mirror-image autoload failure
4557  // (witness 1711.11576).
4558  //
4559  // `subfile:<depth>`, not a bare depth test: a group the AUTHOR wrote must keep real
4560  // LaTeX's verdict — `{\usepackage{amsthm}}` leaves `\theoremstyle` undefined in
4561  // pdflatex and Perl alike, and rescuing it would emit fewer errors than Perl on
4562  // an authoring mistake (guards
4563  // `06_cluster_regressions::author_written_group_around_usepackage_still_loses_the_package`,
4564  // and `100_stale_autoload_no_runaway` from a fresh process). The
4565  // two cases are indistinguishable by anything cheaper: both are a group opened
4566  // inside the current file, while `inPreamble` is true, at `\currentgrouplevel`
4567  // 1. Refuted alternatives in #65 — dropping the brackets, and `\globaldefs=1`.
4568  let pre_keys = if is_scope_active(subfile_scope_here()) {
4569    Some(snapshot_top_frame_meaning_keys())
4570  } else {
4571    None
4572  };
4573  let subfile_load = SubfilePackageLoad::enter(pre_keys.is_some());
4574  let result = input_definitions(name, InputDefinitionOptions {
4575    extension: options.extension,
4576    handleoptions: true,
4577    // Pass classes options if we have NONE!
4578    withoptions: if options.options.is_empty() {
4579      Some(Vec::new())
4580    } else {
4581      None
4582    }, // fake boolean use, multi-type in latexml... refactor?
4583    options: options.options,
4584    as_class: options.as_class,
4585    noltxml: options.noltxml.unwrap_or(false),
4586    notex: options.notex.unwrap_or(false),
4587    searchpaths_only: options.searchpaths_only,
4588    after: options.after,
4589    ..InputDefinitionOptions::default()
4590  });
4591  drop(subfile_load);
4592  if let Some(pre_keys) = pre_keys {
4593    hoist_top_frame_conditional_delta(&pre_keys);
4594  }
4595  // Perl Package.pm L2679 maybeRequireDependencies is invoked from
4596  // input_definitions's miss-handler. But that handler only runs when
4597  // the file was NOT found at all. For paper-bundled .sty files that
4598  // raw-load successfully without a .sty.ltxml binding, we still need
4599  // to scan transitive \RequirePackage so that bound deps fire too.
4600  // Mirrors the same fix for load_class (search "cls.ltxml_loaded").
4601  // Witness 2208.07400 (paper-bundled emnlp2022.sty has
4602  // \RequirePackage{caption} + others; without scan, \captionsetup
4603  // and similar are undefined).
4604  if !lookup_bool(&s!("{name}.sty.ltxml_loaded")) {
4605    maybe_require_dependencies(name, "sty");
4606  }
4607  result
4608}
4609
4610/// Load the binding of package `name` for another binding to build on, without the package counting as loaded — a
4611/// binding's way of borrowing a package the real one does not load (theorem.sty's and ntheorem.sty's bindings
4612/// borrow amsthm's theorem machinery; neither real package loads amsthm). Unless the document had loaded `name`
4613/// already, it is then marked unloaded ([`crate::state::mark_unloaded`]), and so is every file first loaded during the
4614/// borrow (amsthm's amsgen, [`crate::state::end_borrow`]): `\@ifpackageloaded{name}` is false, as in LaTeX, and the
4615/// document's own later `\usepackage{name}` loads the binding again, whose definitions then take over (amsthm.sty:77's
4616/// `\newtheorem`, amsthm_sty.rs `\lx@amsthm@newtheorem`); `"{name}.sty:borrowed"` tells that load it follows a
4617/// borrow. What the borrow defines carries `DefinitionOrigin::Borrowed`: in LaTeX those names do not exist, so they
4618/// yield to any later definition — the document's, or any raw file's, TeX Live's or the author's (`\newcommand`,
4619/// `\newenvironment`, `\providecommand`; latex_constructs `is_definable_latex`) — and the binding sets no lock while
4620/// `"{name}.sty:borrowing"` is set (amsthm's proof lock), except that natbib's locks (`\citet`, `\citep`, its
4621/// `\bibitem` internals) stay, and the ijcai binding lifts those on `\citet`/`\citep` (unless natbib was loaded
4622/// first), over its own IJCAI `\cite` and `\shortcite` (2107.13646). The names the borrowing package's real file
4623/// defines too the binding claims as its own ([`crate::state::claim_borrowed_meanings`]: ntheorem's `[amsthm]` proof,
4624/// theorem.sty's skips), and they do not yield. Not covered: a conditional (`\@ifundefined{proof}`) still
4625/// sees a borrowed name defined, and a local assignment of a borrowed name clears its mark for good
4626/// (`fallback_meanings`). Witnesses 2211.14033, 2512.06733 (ifacconf), 1507.02955 (cc.cls's ccproof.sty:56). Guards
4627/// `perfect_kernel_batch67p::{theorem_then_amsthm_takes_over, amsthm_before_theorem_stays_loaded}`,
4628/// `perfect_kernel_batch67ps::*`.
4629pub fn require_package_borrowed(name: &str) -> Result<()> {
4630  use crate::definition::origin::{DefinitionOrigin, OriginGuard};
4631  let file = s!("{name}.sty");
4632  let was_loaded = lookup_bool(&s!("{file}_loaded"));
4633  if was_loaded {
4634    return require_package(name, RequireOptions::default());
4635  }
4636  /// Clears `"{file}:borrowing"` and ends the borrow's file tracking on every path out of the load.
4637  struct Borrowing(String, Option<Vec<String>>);
4638  impl Drop for Borrowing {
4639    fn drop(&mut self) {
4640      assign_value(&s!("{}:borrowing", self.0), false, Some(Scope::Global));
4641      if let Some(outer) = self.1.take() {
4642        end_borrow(outer);
4643      }
4644    }
4645  }
4646  assign_value(&s!("{file}:borrowing"), true, Some(Scope::Global));
4647  let borrowing = Borrowing(file.clone(), Some(begin_borrow()));
4648  let result = {
4649    let _origin = OriginGuard::new(DefinitionOrigin::Borrowed);
4650    require_package(name, RequireOptions::default())
4651  };
4652  drop(borrowing);
4653  // (the borrowed package itself, also when it was tracked under another name)
4654  mark_unloaded(&file);
4655  assign_value(&s!("{file}:borrowed"), true, Some(Scope::Global));
4656  result
4657}
4658
4659thread_local! {
4660  /// How many package loads in a standalone subfile bracket ([`require_package`]) are running.
4661  static SUBFILE_PACKAGE_LOAD: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4662}
4663
4664/// One package load's place in [`SUBFILE_PACKAGE_LOAD`]: entering counts the load when it runs in a
4665/// standalone subfile bracket, and dropping restores the outer count — also when the load unwinds (a
4666/// panic caught per paper by a reused worker thread), so a later conversion's `AddToMacro` is not
4667/// left local.
4668struct SubfilePackageLoad {
4669  outer: usize,
4670}
4671
4672impl SubfilePackageLoad {
4673  fn enter(in_bracket: bool) -> Self {
4674    let outer = SUBFILE_PACKAGE_LOAD.with(|depth| {
4675      let outer = depth.get();
4676      if in_bracket {
4677        depth.set(outer + 1);
4678      }
4679      outer
4680    });
4681    SubfilePackageLoad { outer }
4682  }
4683}
4684
4685impl Drop for SubfilePackageLoad {
4686  fn drop(&mut self) { let _ = SUBFILE_PACKAGE_LOAD.try_with(|depth| depth.set(self.outer)); }
4687}
4688
4689/// Clears the count of package loads in a standalone subfile bracket, for a thread that starts over
4690/// ([`crate::reset_thread_engine`]).
4691pub fn reset_subfile_package_load() { SUBFILE_PACKAGE_LOAD.with(|depth| depth.set(0)); }
4692
4693/// The scope of a binding's `AddToMacro`: global (Perl Package.pm:2545-2547), except in a package
4694/// loaded inside a standalone subfile bracket (OXIDIZED_DESIGN #63/#65), where the package's own
4695/// definitions are local to the bracket: a global addition outlived them, and every later table of
4696/// the main document called xcolor's undefined `\@xcolor@tabular@before` (2512.09430; Perl the
4697/// same, KNOWN_PERL_ERRORS #614). The addition then lives as long as the package does — and as in
4698/// pdflatex, where standalone.sty skips the sub-file's preamble, the main document's tables carry
4699/// no hook of a package only a sub-file loaded. OXIDIZED_DESIGN #543.
4700pub fn add_to_macro_scope() -> Scope {
4701  if SUBFILE_PACKAGE_LOAD.with(std::cell::Cell::get) > 0 {
4702    Scope::Local
4703  } else {
4704    Scope::Global
4705  }
4706}
4707
4708/// Perl `AddToMacro($cs, @tokens)` (Package.pm:2534): append to a macro's expansion, unlocked, in
4709/// [`add_to_macro_scope`]; an undefined `cs` is an Error and is defined with the tokens, as latex.ltx's `\g@addto@macro`
4710/// does (OD #1036). One implementation for the `AddToMacro!` macro and Rhai's `AddToMacro`.
4711pub fn add_to_macro(cs: Token, tokens: Tokens) -> Result<()> {
4712  // Package.pm:2547 `locked => $$defn{locked}`: the addition keeps the macro's lock.
4713  let locked = lookup_bool(&format!("{cs}:locked"));
4714  let options = || {
4715    Some(ExpandableOptions {
4716      scope: Some(add_to_macro_scope()),
4717      nopack_parameters: true,
4718      locked,
4719      ..ExpandableOptions::default()
4720    })
4721  };
4722  match lookup_definition(&cs)? {
4723    // TeX's `\g@addto@macro` and Perl both err on an undefined cs (OD #1036); latex.ltx still defines it with the addition.
4724    None => {
4725      let message = s!("{cs} is not defined");
4726      Error!("undefined", cs, message, "Defining it with the addition");
4727      def_macro(cs, None, ExpansionBody::Tokens(tokens), options())
4728    },
4729    Some(defn) if !defn.is_expandable() => {
4730      let message = s!("{cs} is not an expandable control sequence");
4731      Warn!("unexpected", cs, message, "Ignoring addition");
4732      Ok(())
4733    },
4734    Some(defn) => {
4735      let mut expansion = match defn.get_expansion() {
4736        Some(ExpansionBody::Tokens(old)) => old.clone().unlist(),
4737        Some(ExpansionBody::Closure(_)) => {
4738          let message = s!(
4739            "{cs} has a closure body, AddToMacro will *override* with an ExpandableBody[Tokens] ! \
4740             This is usually in error!"
4741          );
4742          Warn!("unexpected", "ExpandableBody[Closure]", message);
4743          Vec::new()
4744        },
4745        None => Vec::new(),
4746      };
4747      expansion.extend(tokens.unlist());
4748      // Package.pm:2545 `local $UNLOCKED = 1`: an addition may extend a `:locked` macro.
4749      let _unlock_guard = local_state_unlocked_guard(true);
4750      def_macro(
4751        cs,
4752        None,
4753        ExpansionBody::Tokens(Tokens::new(expansion)),
4754        options(),
4755      )
4756    },
4757  }
4758}
4759
4760/// The calling file's option list — latex.ltx:18637 `\@loadwithoptions`
4761/// `\let`s `\opt@<callee>` to `\opt@\@currname.\@currext`, the shared half
4762/// of `\RequirePackageWithOptions` and `\LoadClassWithOptions` (Perl
4763/// `withoptions => 1`, Package.pm:2610 `opt@prevname.prevext`). Empty when no
4764/// file is being loaded.
4765pub fn calling_file_options() -> Result<Vec<String>> {
4766  let currname = if lookup_definition(&T_CS!("\\@currname"))?.is_some() {
4767    do_expand(T_CS!("\\@currname"))?.to_string()
4768  } else {
4769    String::new()
4770  };
4771  let currext = if lookup_definition(&T_CS!("\\@currext"))?.is_some() {
4772    do_expand(T_CS!("\\@currext"))?.to_string()
4773  } else {
4774    String::new()
4775  };
4776  Ok(if !currname.is_empty() {
4777    let key = s!("opt@{}.{}", currname, currext);
4778    lookup_vecdeque(&key)
4779      .unwrap_or_default()
4780      .iter()
4781      .filter_map(|item| match item {
4782        Stored::String(s) => Some(arena::to_string(*s)),
4783        _ => None,
4784      })
4785      .collect()
4786  } else {
4787    Vec::new()
4788  })
4789}
4790
4791/// Perl: `RequirePackage($name, withoptions => 1)` — forward the calling
4792/// package/class's options ([`calling_file_options`]) to the required child
4793/// package as its explicit options list. Mirrors `load_class_with_options`
4794/// for the package path.
4795pub fn require_package_with_options(name: &str) -> Result<()> {
4796  let options = calling_file_options()?;
4797  require_package(name, RequireOptions {
4798    options,
4799    ..RequireOptions::default()
4800  })
4801}
4802
4803/// Perl Package.pm L2759-2796: maybeRequireDependencies
4804/// When a package/class file has no binding AND raw TeX loading is disabled,
4805/// scan the raw file for \RequirePackage/\usepackage/\LoadClass declarations
4806/// and load any dependencies that DO have bindings. This is a "best effort"
4807/// fallback that gives us the dependency chain without interpreting raw TeX.
4808// Strict translation of Perl `Package.pm:maybeRequireDependencies`
4809// (L2759-L2796). Scan a raw .sty/.cls file for transitive
4810// `\RequirePackage`, `\usepackage`, and (for classes) `\LoadClass`
4811// declarations and route them through `require_package` / `load_class`
4812// so the corresponding bindings get pulled in even when the original
4813// file has no .ltxml binding.
4814/// The `\addbibresource` names declared in a raw `.sty`/`.cls` body.
4815///
4816/// Split out of [`maybe_require_dependencies`] so the extraction is testable
4817/// without state: it is the whole of the BEYOND-PERL behaviour described there.
4818/// A comma-separated argument declares several resources at once, as biblatex
4819/// allows.
4820fn scan_bib_resources(code: &str) -> Vec<String> {
4821  use regex::Regex;
4822  static BIBRES_RE: LazyLock<Regex> =
4823    LazyLock::new(|| Regex::new(r"\\addbibresource\s*(?:\[[^\]]*\])?\s*\{([^\}]*)\}").unwrap());
4824  let mut out = Vec::new();
4825  for cap in BIBRES_RE.captures_iter(code) {
4826    for part in cap[1].split(',') {
4827      let name = part.trim();
4828      // A name holding a control sequence (`\jobname.bib`, incgraph-doc.sty:58;
4829      // `\gitLog@bibfile`, gitlog.sty:111; cleanthesis `\cthesis@bibfile`) is
4830      // resolvable only at runtime, where the native `\addbibresource[]
4831      // Expanded` (biblatex_sty.rs) already pushes its expansion; the literal
4832      // can never name a file, and `\biblatex@printbibliography`'s exact-string
4833      // dedup kept both, so MakeBibliography reported the literal as a
4834      // missing bibliography (`Error:missing_file:\jobname.bib`; batch 56ga).
4835      if !name.is_empty() && !name.contains('\\') && !out.iter().any(|o: &String| o == name) {
4836        out.push(name.to_string());
4837      }
4838    }
4839  }
4840  out
4841}
4842
4843#[cfg(test)]
4844mod bib_resource_scan_tests {
4845  use super::scan_bib_resources;
4846
4847  /// A resource named through a control sequence is left to the runtime path.
4848  #[test]
4849  fn unexpanded_macro_names_are_skipped() {
4850    assert_eq!(
4851      scan_bib_resources(
4852        "\\addbibresource{\\jobname.bib}\n\\addbibresource{\\gitLog@bibfile}\n\\addbibresource{refs.bib}"
4853      ),
4854      vec!["refs.bib".to_string()]
4855    );
4856  }
4857
4858  /// A journal class shipped with the paper declares the bibliography itself —
4859  /// `journaleducation.cls` (witness 2605.23724, 0 -> 35 entries),
4860  /// `cai26.cls` (2605.00270, 0 -> 25), `tau.cls` (2605.02720, 0 -> 31) — and
4861  /// the document then only writes `\printbibliography`. We never interpret
4862  /// that class, so this scan is the only place the declaration is visible.
4863  #[test]
4864  fn harvests_addbibresource_from_a_shipped_class() {
4865    assert_eq!(
4866      scan_bib_resources(r"\addbibresource{references.bib}"),
4867      vec!["references.bib"]
4868    );
4869    // A path, as journaleducation.cls writes it.
4870    assert_eq!(
4871      scan_bib_resources(r"\addbibresource{letters/refs.bib}"),
4872      vec!["letters/refs.bib"]
4873    );
4874    // biblatex's optional argument is skipped, not treated as the resource.
4875    assert_eq!(
4876      scan_bib_resources(r"\addbibresource[location=local]{tau.bib}"),
4877      vec!["tau.bib"]
4878    );
4879    // Several resources, and repeats collapse — naming a `.bib` twice would
4880    // make `\lx@bibliography` read it twice and double every entry.
4881    assert_eq!(
4882      scan_bib_resources("\\addbibresource{a.bib, b.bib}\n\\addbibresource{a.bib}"),
4883      vec!["a.bib", "b.bib"]
4884    );
4885    // Nothing to harvest is the common case and must stay empty.
4886    assert!(scan_bib_resources(r"\RequirePackage{biblatex}").is_empty());
4887  }
4888}
4889
4890fn maybe_require_dependencies(file: &str, ext_type: &str) {
4891  require_dependencies_except(file, ext_type, &[]);
4892}
4893
4894/// Perl's `maybeRequireDependencies` (Package.pm:2776-2813) for `file` — load
4895/// the classes and packages its source names that have a binding — except the
4896/// classes and packages in `except`, for a binding that stands in for an
4897/// unbound class and chooses or has already loaded those itself.
4898pub fn require_dependencies_except(file: &str, ext_type: &str, except: &[&str]) {
4899  require_dependencies_filtered(file, ext_type, &|name| !except.contains(&name));
4900}
4901
4902/// The same scan kept to the classes and packages in `only`: a binding that stands in for a file it does not
4903/// interpret, and loads its own choice of that file's packages, leaves to the paper's copy of the file the ones
4904/// whose choice differs between copies (the algorithm packages: icml2017.sty:72-73, which a paper edits to drop
4905/// `algorithmic` for `algpseudocode`; bmvc2k.cls, `algorithmic` or `algpseudocode` by year). The copy's
4906/// `\addbibresource` files are registered as by every scan (the bibliography deduplicates them). `false` when the
4907/// source has no such file (or it cannot be read), or when another scan is running (the re-entrancy guard), so the
4908/// binding takes its own default.
4909pub fn require_dependencies_only(file: &str, ext_type: &str, only: &[&str]) -> bool {
4910  require_dependencies_filtered(file, ext_type, &|name| only.contains(&name))
4911}
4912
4913/// [`require_dependencies_except`] / [`require_dependencies_only`]: scan `file` and load the classes and packages
4914/// it names for which `keep` holds; `false` when there is no file to scan.
4915fn require_dependencies_filtered(file: &str, ext_type: &str, keep: &dyn Fn(&str) -> bool) -> bool {
4916  use regex::Regex;
4917
4918  // Rust-only re-entrancy guard. Perl avoids this case by other means
4919  // (the call-site of `maybeRequireDependencies` is the only entry).
4920  thread_local! { static SCANNING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; }
4921  if SCANNING.with(|s| s.get()) {
4922    return false;
4923  }
4924  SCANNING.with(|s| s.set(true));
4925  struct ResetGuard;
4926  impl Drop for ResetGuard {
4927    fn drop(&mut self) { SCANNING.with(|s| s.set(false)); }
4928  }
4929  let _guard = ResetGuard;
4930
4931  // EXECUTED-SET GATE (Rust-only, more-robust-than-Perl). When this file was
4932  // actually RAW-LOADED, its `\usepackage`/`\RequirePackage` constructors ran
4933  // for every require the load REACHED — recording `<pkg>.usepackage_executed`.
4934  // A candidate the regex finds in the text but that is NOT in that set is one
4935  // whose `\usepackage` never executed — i.e. it sits inside a FALSE `\if…\fi`
4936  // the raw-load already skipped (e.g. `\ifpdf … \usepackage{hyperref} … \fi`
4937  // with `\ifpdf` false). Perl never dep-scans a raw-loaded file, so it never
4938  // anticipates such a package; mirror that by skipping it. The gate applies
4939  // ONLY when the file raw-loaded (key `<file>.<ext>_raw_loaded`): in the
4940  // miss-handler / `INCLUDE_STYLES=false` path no constructor ran, so the set
4941  // is empty and we must NOT filter (keep the anticipation). The flag is
4942  // cumulative+global, so a candidate that DID execute anywhere is kept — only
4943  // never-executed ones are dropped, which can never be a false skip.
4944  // Witnesses 1910.05586 (hyperref in false `\ifpdf` → cleveref "must be loaded
4945  // after hyperref"), 1804.09301 (xcolor in false `\ifacl@hyperref`).
4946  let raw_loaded = lookup_bool(&s!("{file}.{ext_type}_raw_loaded"));
4947
4948  // Perl L2776: `s/%[^\n]*\n//gs` — drop comment AND its trailing newline,
4949  // replacement is the empty string.
4950  // A comment on a last line without its newline is one too (Perl's pattern keeps it): a `{filecontents}` copy is
4951  // stored without that newline, so an edited-out `%\RequirePackage{algorithmic}` ending one was loaded (batch 67l,
4952  // repro icml_style_copy_without_algorithmic.tex).
4953  static COMMENT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"%[^\n]*(?:\n|$)").unwrap());
4954  // `comment`-package block: `\begin{comment}…\end{comment}` is a verbatim-SKIP
4955  // environment, so a `\usepackage`/`\RequirePackage` inside it is NEVER loaded
4956  // by LaTeX. The dep-scan must not anticipate it. Same "more-robust than Perl"
4957  // rationale as the macro-def-body skip below. Witness 1901.05713: thesis.sty
4958  // has a commented-out `\usepackage{hyperref}` inside `\begin{comment}`, which
4959  // the scan otherwise loaded — tripping cleveref's "must be loaded after
4960  // hyperref" `\AtBeginDocument` order-check (hyperref appears loaded though the
4961  // author commented it out). `comment` doesn't nest, so a non-greedy match to
4962  // the first `\end{comment}` is correct.
4963  static COMMENT_ENV_RE: LazyLock<Regex> =
4964    LazyLock::new(|| Regex::new(r"(?s)\\begin\s*\{comment\}.*?\\end\s*\{comment\}").unwrap());
4965  // Perl L2777-2779 runs two separate substitutions, in this order:
4966  // first `\RequirePackage`, then `\usepackage`. Use two regexes so that
4967  // collected order matches Perl's call order to `$collect`.
4968  static REQ_RE: LazyLock<Regex> =
4969    LazyLock::new(|| Regex::new(r"\\RequirePackage\s*(?:\[([^\]]*)\])?\s*\{([^\}]*)\}").unwrap());
4970  static USE_RE: LazyLock<Regex> =
4971    LazyLock::new(|| Regex::new(r"\\usepackage\s*(?:\[([^\]]*)\])?\s*\{([^\}]*)\}").unwrap());
4972  static CLS_RE: LazyLock<Regex> =
4973    LazyLock::new(|| Regex::new(r"\\LoadClass\s*(?:\[([^\]]*)\])?\s*\{([^\}]*)\}").unwrap());
4974  // Matches a `\newcommand`/`\def`-family DEFINITION HEADER ending exactly at a
4975  // `{` — i.e. the brace that follows opens the macro BODY. Used to detect a
4976  // `\usepackage` that lives in a deferred macro body (loads only when the
4977  // macro is later expanded) vs one inside a load-time conditional.
4978  static DEF_BODY_HEADER_RE: LazyLock<Regex> = LazyLock::new(|| {
4979    Regex::new(
4980      r"(?s)(?:\\(?:re|provide)?newcommand|\\DeclareRobustCommand)\*?\s*(?:\{\s*\\[A-Za-z@]+\s*\}|\\[A-Za-z@]+)\s*(?:\[[^\]]*\]\s*)*$|\\[egx]?def\s*\\[A-Za-z@]+[^{}]*$",
4981    )
4982    .unwrap()
4983  });
4984  // The `\def`-family sub-case of DEF_BODY_HEADER_RE, capturing the defined
4985  // macro NAME (without backslash). A `\def\<m>{… \RequirePackage{P} …}` body
4986  // is only truly deferred if `\<m>` is never invoked; the AMS-class idiom
4987  // `\def\@tempa{\RequirePackage{amsmath}}…\@tempa` invokes it immediately and
4988  // so DOES load P (witness ijnam.cls → amsmath → `{aligned}`, 1911.03415).
4989  static DEF_NAME_RE: LazyLock<Regex> =
4990    LazyLock::new(|| Regex::new(r"(?s)\\[egx]?def\s*\\([A-Za-z@]+)[^{}]*$").unwrap());
4991  // A require inside a `\DeclareOption{<opt>}{…}` (or `\DeclareOption*{…}`)
4992  // code-arm is CONDITIONAL on the option being selected (resolved later by
4993  // `\ProcessOptions`), so the dep-scan must not eagerly load it. Matches when a
4994  // group's preceding window ends at `…\DeclareOption{<opt>}` / `…\DeclareOption*`
4995  // — i.e. the `{` it precedes opens the option's code arm. (Does NOT match
4996  // `\DeclareOptionX`/`\ExecuteOptions`/`\ProcessOptions`.)
4997  static DECLARE_OPTION_RE: LazyLock<Regex> =
4998    LazyLock::new(|| Regex::new(r"(?s)\\DeclareOption\*?\s*(?:\{[^{}]*\})?\s*$").unwrap());
4999
5000  // Perl L2761: `FindFile($file, type => $type, noltxml => 1)`. `$file`
5001  // is BARE — `FindFile` glues on `.$type` itself per L2073-2076.
5002  let raw_path = find_file(
5003    file,
5004    Some(FindFileOptions {
5005      ext_type: Some(Cow::Owned(ext_type.to_string())),
5006      forbid_ltxml: true, // Perl `noltxml => 1`
5007      ..FindFileOptions::default()
5008    }),
5009  );
5010  let Some(path) = raw_path else { return false };
5011
5012  // Perl L2762-2766: slurp file. Check filecontents-cache first for the
5013  // inline-cls/sty case (e.g. `\begin{filecontents}{alggeom.cls}`), then
5014  // fall through to disk. Without the cache check, papers that bundle
5015  // their .cls inline via filecontents miss the dep-scan and downstream
5016  // CSes that the (now-cached) cls would have hand-loaded stay
5017  // undefined. Witness: arXiv:2604.09738.
5018  let code = if let Some(cached) = crate::binding::virtual_files::vfs_read(&path) {
5019    cached
5020  } else {
5021    // Use read (bytes) + UTF-8 conversion so non-UTF-8 cls/sty files
5022    // (ISO-8859 with vendor copyright headers, e.g. cpc-hepnp.cls with
5023    // Chinese comments) still get scanned. read_to_string strict UTF-8
5024    // validation would error out, leaving \RequirePackage{fancyhdr} and
5025    // friends silently undiscovered. Witness 2203.16500.
5026    //
5027    // Fast path for valid UTF-8 (the overwhelming majority): `str::from_utf8`
5028    // SIMD-validates the whole slice in one pass, where `from_utf8_lossy`
5029    // walks it through the grapheme-aware `Utf8Chunks` iterator hunting for
5030    // invalid bytes — measurable on a 197 KB class file like ieeeconf.cls.
5031    // Byte-identical to the lossy path for valid UTF-8; fall back to lossy
5032    // only on invalid bytes. Same pattern as the per-line reader in `mouth.rs`.
5033    match std::fs::read(&path) {
5034      Ok(bytes) => match str::from_utf8(&bytes) {
5035        Ok(s) => s.to_string(),
5036        Err(_) => String::from_utf8_lossy(&bytes).into_owned(),
5037      },
5038      Err(_) => {
5039        Warn!(
5040          "I/O",
5041          "read",
5042          s!("Couldn't open {} to scan dependencies, $!", path)
5043        );
5044        return false;
5045      },
5046    }
5047  };
5048
5049  // BEYOND PERL (DIVERGENCES #333): a class written with CR-only line ends
5050  // (2402.17342's sn-jnl.cls) is one line to the comment pattern below, which
5051  // needs `\n` — Perl's identical regex then strips no comment and loads every
5052  // commented-out `\usepackage`. TeX ends a line at either (web2c), so read it
5053  // as `\n`-ended first.
5054  let code = if code.contains('\r') {
5055    code.replace("\r\n", "\n").replace('\r', "\n")
5056  } else {
5057    code
5058  };
5059  // Perl L2776: strip comments (replacement empty).
5060  let code = COMMENT_RE.replace_all(&code, "");
5061  // Strip `\begin{comment}…\end{comment}` blocks (see COMMENT_ENV_RE above).
5062  let code = COMMENT_ENV_RE.replace_all(&code, "");
5063
5064  // DIVERGENCE FROM PERL (deliberate, more-robust): do NOT dep-load a
5065  // `\usepackage` / `\RequirePackage` that sits in a DEFERRED macro-definition
5066  // body (a `\newcommand` / `\def`-family body) — it loads only if that macro
5067  // is later expanded, which the dep-scan must not eagerly force. Requires
5068  // inside LOAD-TIME conditionals (`\IfFileExists{X.sty}{\usepackage{X}}`,
5069  // `\@ifundefined{..}{..}`, `\if…\usepackage…\fi`) DO execute during raw-load
5070  // and MUST still be picked up. (Perl never force-loads the deferred ones: for
5071  // a normally raw-loaded file it doesn't dep-scan at all, and the bundled deps
5072  // it wants in the binding-bypass case run at load.) Witnesses:
5073  //   - 1506.06200 — categorytheory.sty `\newcommand{\usediagrams}{\usepackage {diagrams}}` (never
5074  //     invoked) must be SKIPPED (else the `diagrams` stub's `locked` `\begin{diagram}` shadows the
5075  //     paper's tikz `{diagram}`).
5076  //   - 1703.03673 — iau.cls `\IfFileExists{amssymb.sty}{…\usepackage{amssymb}…}` must be KEPT
5077  //     (else `\bigstar` is undefined). An earlier brace-DEPTH filter wrongly skipped this
5078  //     conditional; the def-body check is precise.
5079  // A `\usepackage` is deferred iff ANY enclosing `{…}` group is opened directly
5080  // by a `\newcommand`/`\def` definition header.
5081  // Is `\<name>` INVOKED (not merely defined) somewhere in the file? A bare
5082  // control-sequence occurrence not directly preceded by a `\…def`/`\let`
5083  // introducer counts as an invocation. Used to tell an executed deferred-load
5084  // idiom (`\def\@tempa{…\RequirePackage{P}…}\@tempa`) from a never-called one.
5085  let is_invoked = |name: &str| -> bool {
5086    let pat = s!("\\{name}");
5087    let mut from = 0usize;
5088    while let Some(rel) = code[from..].find(&pat) {
5089      let at = from + rel;
5090      from = at + pat.len();
5091      // Full control sequence: next char must not extend the name.
5092      let after_ok = code[at + pat.len()..]
5093        .chars()
5094        .next()
5095        .is_none_or(|c| !c.is_ascii_alphabetic() && c != '@');
5096      if !after_ok {
5097        continue;
5098      }
5099      // Not a (re)definition: the chars just before `\name` aren't `…def`/`…let`.
5100      // Back up to a char boundary: a multi-byte char within 8 bytes of
5101      // `\name` would split a byte slice.
5102      let mut start = at.saturating_sub(8);
5103      while !code.is_char_boundary(start) {
5104        start -= 1;
5105      }
5106      let before = code[start..at].trim_end();
5107      if before.ends_with("def") || before.ends_with("let") {
5108        continue;
5109      }
5110      return true;
5111    }
5112    false
5113  };
5114  let in_macro_def_body = |start: usize| -> bool {
5115    let bytes = code.as_bytes();
5116    let mut stack: Vec<usize> = Vec::new();
5117    let mut i = 0usize;
5118    while i < start {
5119      match bytes[i] {
5120        b'\\' => {
5121          i += 2;
5122          continue;
5123        },
5124        b'{' => stack.push(i),
5125        b'}' => {
5126          stack.pop();
5127        },
5128        _ => {},
5129      }
5130      i += 1;
5131    }
5132    stack.iter().any(|&ob| {
5133      let lo = ob.saturating_sub(400);
5134      let window = code.get(lo..ob).unwrap_or(&code[..ob]);
5135      // A require inside a `\DeclareOption` code-arm is conditional (only the
5136      // option-selected arm runs, via `\ProcessOptions`) → defer it, even when
5137      // the arm `\def`s an INVOKED macro: aa/myaa.cls have
5138      //   \DeclareOption{ascii}{\def\aa@inputenc{\RequirePackage[ascii]{inputenc}}}
5139      //   …\DeclareOption{utf8}{…[utf8]…}  …  \aa@inputenc
5140      // where the single `\aa@inputenc` call would otherwise un-defer the FIRST
5141      // (ascii) arm via the `is_invoked` rule below and wrongly force
5142      // inputenc[ascii] (→ UTF-8 `ç` rejected). Perl defers all such (loads no
5143      // inputenc; the actual `utf8` default is the right answer and `ç` passes
5144      // through either way). Witness 1504.05963 (Perl 0 / Rust 1, now parity).
5145      if DECLARE_OPTION_RE.is_match(window) {
5146        return true;
5147      }
5148      // A `\def\<m>{…}` body only defers if `\<m>` is never invoked; an invoked
5149      // scratch macro (`\@tempa`) runs its body at load, so its require loads.
5150      if let Some(caps) = DEF_NAME_RE.captures(window) {
5151        return !is_invoked(&caps[1]);
5152      }
5153      // `\newcommand`/`\DeclareRobustCommand` user-command bodies stay deferred
5154      // (witness 1506.06200 `\newcommand{\usediagrams}{\usepackage{diagrams}}`).
5155      DEF_BODY_HEADER_RE.is_match(window)
5156    })
5157  };
5158  let top_level = |cap: &regex::Captures| -> bool {
5159    cap
5160      .get(0)
5161      .map(|m| !in_macro_def_body(m.start()))
5162      .unwrap_or(true)
5163  };
5164
5165  // NOTE — a former Rust-only "conflicting option sets" heuristic was REMOVED
5166  // here (was: drop a package `\RequirePackage`'d / `\usepackage`'d with two or
5167  // more DIFFERENT option sets, as the signature of a deferred require inside a
5168  // `\def`/`\DeclareOption` body, e.g. aa.cls's
5169  // `\DeclareOption{ascii}{\def\aa@inputenc{\RequirePackage[ascii]{inputenc}}}`
5170  // …`{utf8}{…[utf8]…}`). It over-fired on a package required in BOTH arms of a
5171  // load-time `\if…\else…\fi` with different options — mutually exclusive, so
5172  // exactly one branch loads and the package MUST be kept. Witness: rist.cls's
5173  // `\ifpdf \RequirePackage[pdftex,…]{hyperref} \else \RequirePackage[dvipdfm,…]
5174  // {hyperref} \fi` (1912.00781: hyperref dropped → `\url` undefined). The
5175  // heuristic was also provably REDUNDANT: it only ever saw TOP-LEVEL requires
5176  // (the captures feeding it were `top_level`-filtered), but aa.cls's inputenc
5177  // lives in a `\def`/`\DeclareOption` BODY — already dropped by the def-body
5178  // `top_level` skip below, so it never entered the conflicting set at all. Perl
5179  // has no such gate (L2767-2774 is a plain dedup); the def-body `top_level` skip
5180  // plus the executed-set gate cover the legitimate cases faithfully.
5181  static OPT_SPLIT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s*,\s*").unwrap());
5182  // Perl Package.pm:2806/2810 `options => [split(/\s*,\s*/, $options)]`. An option naming a
5183  // macro undefined at the scan (easychair.cls:365 `\LoadClass[\@PaperFormat,…]{article}`)
5184  // names the scanned file's own definitions, which never run (the file is not executed,
5185  // OmniBus stands in): Perl keeps it an inert string, where the loaded class's option
5186  // processing here expands it, "undefined" for each. An option whose macros are defined
5187  // (`headheight=\baselineskip`) passes. Witnesses 2011.11995, 2211.09353, 2607.12736.
5188  static OPTION_CS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\\([A-Za-z@]+|.)").unwrap());
5189  let scanned_options = |raw_opts: &Option<String>| -> Vec<String> {
5190    raw_opts
5191      .as_deref()
5192      .map(|s| {
5193        OPT_SPLIT
5194          .split(s)
5195          .filter(|option| {
5196            OPTION_CS
5197              .captures_iter(option)
5198              .all(|cs| has_meaning(&crate::T_CS!(format!("\\{}", &cs[1]))))
5199          })
5200          .map(|x| x.to_string())
5201          .collect()
5202      })
5203      .unwrap_or_default()
5204  };
5205
5206  // Perl L2767-2774: shared `%dups` map, $collect closure splits on
5207  // `\s*,\s*` and only enrolls a package once, AND only if its
5208  // `.sty.ltxml_loaded` flag is unset.
5209  let mut packages: Vec<(String, Option<String>)> = Vec::new();
5210  let mut dups: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();
5211  let mut collect = |pkg_csv: &str, raw_options: Option<&str>| {
5212    for p in OPT_SPLIT.split(pkg_csv) {
5213      if p.is_empty() || !keep(p) {
5214        continue;
5215      }
5216      // Executed-set gate (see top of fn): when this file raw-loaded, drop a
5217      // candidate whose `\usepackage` never executed anywhere — it was inside a
5218      // false conditional the raw-load skipped.
5219      if raw_loaded && !lookup_bool(&s!("{p}.usepackage_executed")) {
5220        continue;
5221      }
5222      // Perl L2773: `!$dups{$p} && !LookupValue($p . '.sty.ltxml_loaded')`
5223      if !dups.contains(p) && !lookup_bool(&s!("{p}.sty.ltxml_loaded")) {
5224        packages.push((p.to_string(), raw_options.map(|s| s.to_string())));
5225        dups.insert(p.to_string());
5226      }
5227    }
5228  };
5229
5230  // Perl L2777: `\RequirePackage` first.
5231  for cap in REQ_RE.captures_iter(&code) {
5232    if !top_level(&cap) {
5233      continue;
5234    }
5235    collect(&cap[2], cap.get(1).map(|m| m.as_str()));
5236  }
5237  // Perl L2778-2779: `\usepackage` second.
5238  for cap in USE_RE.captures_iter(&code) {
5239    if !top_level(&cap) {
5240      continue;
5241    }
5242    collect(&cap[2], cap.get(1).map(|m| m.as_str()));
5243  }
5244
5245  // Perl L2767/L2781-2782: `@classes` is class-only, NO dup-check.
5246  let mut classes: Vec<(String, Option<String>)> = Vec::new();
5247  if ext_type == "cls" {
5248    for cap in CLS_RE.captures_iter(&code) {
5249      if !top_level(&cap) {
5250        continue;
5251      }
5252      let class = cap[2].to_string();
5253      if !class.is_empty() && keep(&class) {
5254        classes.push((class, cap.get(1).map(|m| m.as_str().to_string())));
5255      }
5256    }
5257  }
5258
5259  // BEYOND PERL: harvest `\addbibresource` too.
5260  //
5261  // A journal class shipped with the paper routinely declares the bibliography
5262  // itself — `journaleducation.cls` has `\addbibresource{letters/refs.bib}`,
5263  // `cai26.cls` has `references.bib`, `tau.cls` has `tau.bib` — and the
5264  // document then only writes `\printbibliography`. We do not interpret that
5265  // class (no binding, OmniBus fallback), so the resource was never registered
5266  // and `\printbibliography` had nothing to print: no `MakeBibliography` line
5267  // at all and an empty References section, even though the `.bib` ships with
5268  // the paper. This scanner is already reading the file for its dependencies,
5269  // so it is the one place that can see the declaration.
5270  //
5271  // Registering the name is enough — `\biblatex@printbibliography` pops the
5272  // list and routes it through `\lx@bibliography`, which resolves the file (and
5273  // deduplicates, so a document that ALSO declares the same resource does not
5274  // get a doubled bibliography). Papers that never load biblatex simply leave
5275  // the value unread. Audit family F4(c); witnesses 2605.23724, 2605.00270,
5276  // 2605.02720.
5277  for res in scan_bib_resources(&code) {
5278    let _ = push_value("biblatex_resources", Stored::String(arena::pin(res)));
5279  }
5280
5281  // Perl L2784-2785: Info iff EITHER list is non-empty; message lists
5282  // class names then package names, separated by ',' (no space).
5283  if !classes.is_empty() || !packages.is_empty() {
5284    let names: Vec<&str> = classes
5285      .iter()
5286      .map(|(n, _)| n.as_str())
5287      .chain(packages.iter().map(|(n, _)| n.as_str()))
5288      .collect();
5289    Info!(
5290      "dependencies",
5291      "dependencies",
5292      s!("Loading dependencies for {}: {}", path, names.join(","))
5293    );
5294  }
5295
5296  // Perl L2786-2789: foreach class — gate by `FindFile($class, type=>'cls',
5297  // notex=>1)`, then `LoadClass(..., options=>[split ...])`.
5298  for (class, raw_opts) in classes {
5299    if marked_loaded_unrecorded(&class, "cls") {
5300      continue;
5301    }
5302    if find_file(
5303      &class,
5304      Some(FindFileOptions {
5305        ext_type: Some(Cow::Borrowed("cls")),
5306        notex: true, // Perl `notex => 1`
5307        ..FindFileOptions::default()
5308      }),
5309    )
5310    .is_some()
5311    {
5312      let _ = load_class(&class, scanned_options(&raw_opts), Tokens::default());
5313    }
5314  }
5315
5316  // Perl L2790-2793: foreach package — gate by `FindFile($pkg, type=>'sty',
5317  // notex=>1)`, then `RequirePackage(..., options=>[split ...])`.
5318  for (pkg, raw_opts) in packages {
5319    if marked_loaded_unrecorded(&pkg, "sty") {
5320      continue;
5321    }
5322    if find_file(
5323      &pkg,
5324      Some(FindFileOptions {
5325        ext_type: Some(Cow::Borrowed("sty")),
5326        notex: true, // Perl `notex => 1`
5327        ..FindFileOptions::default()
5328      }),
5329    )
5330    .is_some()
5331    {
5332      let _ = require_package(&pkg, RequireOptions {
5333        options: scanned_options(&raw_opts),
5334        ..RequireOptions::default()
5335      });
5336    }
5337  }
5338  true
5339}
5340
5341/// Is a dependency-scan candidate marked loaded while our records say it is not? The scan stands in for the scanned
5342/// file's own `\usepackage`/`\RequirePackage`/`\LoadClass` lines, and LaTeX skips such a line when `\ver@<name>.<ext>`
5343/// is defined and not `\relax` (latex.ltx:18750 `\@onefilewithoptions` → `\@ifl@aded`, latex.ltx:18397-18402): a
5344/// document that sets the marker before the class runs (`\AddToHook{class/sn-jnl/before}{…\gdef\csname
5345/// ver@program.sty\endcsname{9999/12/31}}`, sn-jnl-setup.sty of 2201.11056 — program.sty's active `|` breaks pgf)
5346/// suppresses the class's load. The marker can also come from a class or package read raw (memoir's
5347/// `\EmulatedPackage`, imakeidx.sty:61 `ver@makeidx.sty`, xcolor.sty:315 `ver@color.sty`) or from a binding
5348/// (biblatex's); LaTeX skips the line for each of them alike. Our own records (`_loaded`/`_raw_loaded`) say it is not
5349/// loaded, so without this the scan loads it (Perl Package.pm:2328-2330 consults only those records; KNOWN_PERL_ERRORS
5350/// #780, DIVERGENCES #605). Scan-only, by ruling (2026-10-16): `\usepackage`/`\RequirePackage` themselves keep the
5351/// records-only test (ruling 2026-10-14, no general loader `\ver@` rule). Guard:
5352/// `perfect_kernel_batch68f::scan_skips_a_package_the_document_marked_loaded`.
5353fn marked_loaded_unrecorded(name: &str, ext: &str) -> bool {
5354  let file = s!("{name}.{ext}");
5355  if lookup_bool(&s!("{file}_loaded")) || lookup_bool(&s!("{file}_raw_loaded")) {
5356    return false;
5357  }
5358  if !crate::binding::def::dialect::is_defined_token(&crate::T_CS!(s!("\\ver@{file}"))) {
5359    return false;
5360  }
5361  Info!(
5362    "dependencies",
5363    file.as_str(),
5364    s!("Skipping dependency {file}: it is marked loaded (\\ver@{file} is defined)")
5365  );
5366  true
5367}
5368
5369/// Attach a resource (CSS, JavaScript, …) to the document being built.
5370///
5371/// Port of Perl `Package.pm:RequireResource` L3139-3158. A resource needs
5372/// either a pathname or inline content, and a mime-type: an absent type is
5373/// inferred from the pathname's extension (case-sensitively, as Perl's
5374/// `$resource_types{$ext}` lookup is), and a resource still lacking one after
5375/// that is skipped with a warning rather than emitted untyped.
5376///
5377/// The resource is queued as *pending* and folded into the document later,
5378/// covering Perl's `$LaTeXML::DOCUMENT ? addResource : PushValue(PENDING_RESOURCES)`
5379/// split — bindings routinely call this from a preamble, before any document
5380/// exists.
5381pub fn require_resource(mut resource: Resource) {
5382  if resource.name.is_empty() && resource.content.is_empty() {
5383    Warn!(
5384      "expected",
5385      "resource",
5386      "Resource must have a resource pathname or content; skipping"
5387    );
5388    return;
5389  }
5390  if resource.mimetype.is_empty() && !resource.name.is_empty() {
5391    // Perl Package.pm L3129: `my $ext = pathname_type($resource);` — no
5392    // case-folding; `$resource_types{$ext}` is a case-sensitive lookup.
5393    let ext = pathname::extension(&resource.name);
5394    resource.mimetype = resource_type(&ext);
5395  }
5396  if resource.mimetype.is_empty() {
5397    Warn!(
5398      "expected",
5399      "mime-type",
5400      "Resource must have a mime-type; skipping"
5401    );
5402    return;
5403  }
5404
5405  // If we've got a document, go ahead & put the resource in.
5406  // if (document.is_some()) {
5407  //   document.as_mut().unwrap().add_resource(resource, resource);
5408  // } else {
5409  push_pending_resource(resource);
5410  // }
5411}
5412
5413/// The options [`require_resource_with`] takes, Perl Package.pm:3134 `$resource_options`.
5414pub const RESOURCE_OPTIONS: [&str; 3] = ["type", "media", "content"];
5415
5416/// Perl `RequireResource($resource, %options)` (Package.pm:3139-3158): `name` (empty for Perl's `undef`) with the
5417/// options `type`, `media` and `content`. Any other option is the Error Perl's `CheckOptions` raises
5418/// (Package.pm:1062-1067), and the resource is still required. An absolute URL (`https://…`) is kept as the link's
5419/// target: post-processing neither reads nor copies it (Perl Post/XSLT.pm:93). `origin` is who asks (OD #1249).
5420pub fn require_resource_with<K: AsRef<str>, V: Into<String>>(
5421  name: &str,
5422  options: impl IntoIterator<Item = (K, V)>,
5423  origin: ResourceOrigin,
5424) -> Result<()> {
5425  let mut resource = Resource {
5426    name: name.to_string(),
5427    origin,
5428    ..Resource::default()
5429  };
5430  let mut bad: Vec<String> = Vec::new();
5431  for (key, value) in options {
5432    match key.as_ref() {
5433      "type" => resource.mimetype = value.into(),
5434      "media" => resource.media = value.into(),
5435      "content" => resource.content = value.into(),
5436      other => bad.push(other.to_string()),
5437    }
5438  }
5439  if !bad.is_empty() {
5440    bad.sort();
5441    Error!(
5442      "misdefined",
5443      "RequireResource",
5444      s!("RequireResource does not accept options:{}", bad.join(", "))
5445    );
5446  }
5447  require_resource(resource);
5448  Ok(())
5449}
5450
5451/// Does the class `name` resolve to a file of the TeX distribution, neither beside the document (its own directory or
5452/// below it, a `filecontents` one) nor beside `binding`'s own class?
5453fn is_unrelated_distribution_class(name: &str, binding: &str) -> bool {
5454  let Some(path) = find_file(
5455    name,
5456    Some(FindFileOptions {
5457      ext_type: Some(Cow::Borrowed("cls")),
5458      forbid_ltxml: true,
5459      ..FindFileOptions::default()
5460    }),
5461  ) else {
5462    return false;
5463  };
5464  if pathname::is_literaldata(&path) || super::virtual_files::vfs_exists(&path) {
5465    return false;
5466  }
5467  let Ok(path) = std::fs::canonicalize(&path) else {
5468    return false;
5469  };
5470  if path.with_file_name(format!("{binding}.cls")).exists() {
5471    return false;
5472  }
5473  let directory = lookup_string("SOURCEDIRECTORY");
5474  directory.is_empty()
5475    || std::fs::canonicalize(&directory).is_ok_and(|directory| !path.starts_with(directory))
5476}
5477
5478/// Perl: `LoadClass($name, withoptions => 1)` — load a class passing the
5479/// caller's class options through to the child. Reads `class_options` from
5480/// state (populated by the outer `\documentclass` invocation) and forwards
5481/// those as the child's options list, matching Perl Package.pm LoadClass's
5482/// `withoptions` branch.
5483/// `\LoadClassWithOptions` — the calling class's options go to the loaded
5484/// class (latex.ltx:18637 `\@loadwithoptions`, [`calling_file_options`]);
5485/// with no file on the load stack (a class binding delegating directly, e.g.
5486/// amsart → ams_core) the document class's recorded options stand in. The
5487/// `\LoadClassWithOptions` constructor once passed an EMPTY list, so a raw
5488/// class delegating its options (oblivoir.cls → oblivoir-utf.cls:77
5489/// `\if@AMSmath\RequirePackage{amsmath}`) never saw `[amsmath]` (istgame-doc).
5490pub fn load_class_with_options(name: &str, after: Tokens) -> Result<()> {
5491  let mut options = calling_file_options()?;
5492  if options.is_empty() {
5493    let class_opts = lookup_vecdeque("class_options").unwrap_or_default();
5494    options = class_opts
5495      .iter()
5496      .filter_map(|item| match item {
5497        Stored::String(s) => Some(arena::to_string(*s)),
5498        _ => None,
5499      })
5500      .collect();
5501  }
5502  load_class(name, options, after)
5503}
5504/// The format the class file `name` (the one a raw read would take: [`find_file`], no binding) declares, when it is
5505/// not LaTeX2e: its first `\NeedsTeXFormat{…}` outside a comment names another (`pLaTeX2e`: jarticle.cls:16 and the
5506/// other 18 pLaTeX/upLaTeX classes of TeX Live 2025). Read as text, the class is not run: each line up to its first
5507/// `%` not escaped by a backslash, the braced argument of the first `\NeedsTeXFormat` given one, its spaces trimmed. LaTeX
5508/// compares it with `\fmtname` and, when they differ, raises an error and stops reading the file
5509/// (latex.ltx:18663-18674 `\NeedsTeXFormat`: "The current input file will not be processed further, because it was
5510/// written for some other flavor of TeX"). A file without the declaration, or without a readable one, is LaTeX's (`None`).
5511fn declared_other_format(name: &str) -> Option<String> {
5512  let path = find_file(
5513    name,
5514    Some(FindFileOptions {
5515      ext_type: Some(Cow::Borrowed("cls")),
5516      forbid_ltxml: true,
5517      ..FindFileOptions::default()
5518    }),
5519  )?;
5520  let text = match crate::binding::virtual_files::vfs_read(&path) {
5521    Some(cached) => cached,
5522    None => match std::fs::read(&path) {
5523      Ok(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
5524      Err(_) => return None,
5525    },
5526  };
5527  for line in text.split(['\n', '\r']) {
5528    let mut code_end = line.len();
5529    let mut escaped = false;
5530    for (at, c) in line.char_indices() {
5531      match c {
5532        '\\' => escaped = !escaped,
5533        '%' if !escaped => {
5534          code_end = at;
5535          break;
5536        },
5537        _ => escaped = false,
5538      }
5539    }
5540    // (a use without an argument is not the declaration: `\ifx\NeedsTeXFormat\undefined`, a LaTeX 2.09 test)
5541    for (at, _) in line[..code_end].match_indices("\\NeedsTeXFormat") {
5542      let rest = line[at + "\\NeedsTeXFormat".len()..code_end].trim_start();
5543      if let Some((arg, _)) = rest.strip_prefix('{').and_then(|r| r.split_once('}')) {
5544        let format = arg.trim();
5545        return (format != "LaTeX2e").then(|| format.to_string());
5546      }
5547    }
5548  }
5549  None
5550}
5551
5552/// The binding a class without one of its own is read with: Perl's step (Package.pm:2711-2716), the longest binding
5553/// name the class starts with (`mysvjour3` → `svjour3`, `mn2ebis` → `mn2e`, `IEEEtranTCOM` → `IEEEtran`), then a
5554/// Rust-only step: one equal to it but for case (2406.08163); `None` → OmniBus. A path-prefixed class whose basename
5555/// names a binding (`misc/ieeetran` → `IEEEtran`, 2105.02087) never gets here: [`class_binding_for_path`] loads that
5556/// binding first.
5557fn class_binding_alternate(name: &str) -> Option<&'static str> {
5558  let mut sorted: Vec<&'static str> = get_class_binding_names()
5559    .into_iter()
5560    .filter(|n| *n != "OmniBus" && *n != name)
5561    .collect();
5562  sorted.sort_by_key(|n| std::cmp::Reverse(n.len()));
5563  // Strict-case prefix first (Perl-faithful: `$class =~ /^\Q$_\E/`), then
5564  // a case-insensitive fallback for binding entries that differ from the
5565  // class name ONLY in capitalization (e.g. `WileyNJDv5` class vs a
5566  // `wileyNJDv5` binding entry, witness 2406.08163). The ci fallback uses
5567  // FULL equality, NOT prefix: a ci-PREFIX match wrongly fired
5568  // `AAAI-Std` → `aa` (the 2-char A&A astronomy binding) because
5569  // `"aaai-std".starts_with("aa")` — but Perl's case-SENSITIVE `/^aa/`
5570  // against `AAAI-Std` finds nothing, so Perl falls back to OmniBus
5571  // (which defines `\address`). Full ci-equality keeps the
5572  // capitalization-only Wiley case while matching Perl's no-match →
5573  // OmniBus for AAAI-Std. Witness 2008.08548.
5574  sorted
5575    .iter()
5576    .copied()
5577    .find(|candidate| name.starts_with(candidate))
5578    .or_else(|| {
5579      sorted
5580        .iter()
5581        .copied()
5582        .find(|candidate| name.eq_ignore_ascii_case(candidate))
5583    })
5584}
5585
5586/// The class binding a path-prefixed class names by its basename (`lib-acm/acmart` → `acmart`, `misc/ieeetran` →
5587/// `IEEEtran`, `JINST-Sample-files/JINST` → `JINST`): exact case first, then a case-insensitive full match, as
5588/// `pathname_find` matches (Util/Pathname.pm:383-389). Perl finds that binding directly, as the request's own file:
5589/// `FindFile_aux` looks `<class>.cls.ltxml` up in the installation's `Package` directory, which `candidate_pathnames`
5590/// adds WITHOUT the request's directory (Package.pm:2125-2128, Util/Pathname.pm:340-341) — so it loads it silently, with
5591/// no missing status, no warning and no dependency scan of the shipped class (`LoadClass`'s alternate branch,
5592/// Package.pm:2715-2733, is never reached). A full match only, never a prefix (`AAAI-Std` is not `aa`). Witnesses
5593/// 2605.00109, 2605.25901, 2606.20651 (`lib-acm/acmart`, 43 such tasks in 2605+2606), 1504.01965 (JINST),
5594/// 2105.02087 (misc/ieeetran).
5595fn class_binding_for_path(name: &str) -> Option<&'static str> {
5596  let basename = name.rsplit(['/', '\\']).next().unwrap_or(name);
5597  if basename == name || basename.is_empty() {
5598    return None;
5599  }
5600  let names = get_class_binding_names();
5601  names
5602    .iter()
5603    .copied()
5604    .find(|candidate| *candidate == basename)
5605    .or_else(|| {
5606      names
5607        .iter()
5608        .copied()
5609        .find(|candidate| basename.eq_ignore_ascii_case(candidate))
5610    })
5611}
5612
5613/// Is a class loading now ([`load_class`] entered and not yet returned)? A class's own tests are answered by what it
5614/// has defined so far (`state::class_defines_chapter`).
5615pub fn class_loading() -> bool { CLASS_LOAD_DEPTH.with(|d| d.get()) > 0 }
5616
5617/// Load a document class — the `\documentclass` / `\LoadClass` implementation,
5618/// port of Perl `Package.pm:LoadClass` L2702-2730.
5619///
5620/// Resolution runs [`input_definitions`] for `<name>.cls`, then Perl's
5621/// three-step fallback when that yields no binding: the longest known
5622/// `.cls.ltxml` binding whose name PREFIXES the requested class (so an
5623/// author-renamed `IEEEtranTCOM.cls` still gets the `IEEEtran` binding), and
5624/// failing that `OmniBus`, the generic class supplying frontmatter, counter and
5625/// theorem definitions. Whether the raw `.cls` may be read at all is the
5626/// `INCLUDE_CLASSES` value's call (`searchpaths` restricts it to local
5627/// sources); by default it may not, because a raw load that "succeeds" would
5628/// suppress the OmniBus fallback while providing none of its bindings.
5629///
5630/// See [`load_class_with_options`] for Perl's `withoptions => 1` variant. The
5631/// per-branch reasoning, and the arXiv witnesses behind it, are in the body
5632/// comments.
5633pub fn load_class(name: &str, options: Vec<String>, after: Tokens) -> Result<()> {
5634  // (a stand-in class's copy has one class slot, which its binding's base class fills: OXIDIZED_DESIGN_DIVERGENCES
5635  // #736)
5636  if binding_base_class_stands_for(name)? {
5637    return Ok(());
5638  }
5639  // A class loaded while another class loads — `\LoadClass`, a binding's
5640  // base class, the dependency scan's harvest — is nested: its options are
5641  // its own, never global options (`InputDefinitionOptions::nested_class`,
5642  // KPE #304). Only the outermost load is the document class.
5643  let nested_class = CLASS_LOAD_DEPTH.with(|d| d.get()) > 0;
5644  CLASS_LOAD_DEPTH.with(|d| d.set(d.get() + 1));
5645  struct ClassLoadDepthGuard;
5646  impl Drop for ClassLoadDepthGuard {
5647    fn drop(&mut self) { CLASS_LOAD_DEPTH.with(|d| d.set(d.get() - 1)); }
5648  }
5649  let _guard = ClassLoadDepthGuard;
5650
5651  // Perl Package.pm LoadClass: $options{notex}=1 unless LookupValue('INCLUDE_CLASSES').
5652  // Defaults to NOT loading raw .cls. Only .cls.ltxml bindings are considered;
5653  // if the binding is missing, fall through to OmniBus (below). Allowing raw
5654  // .cls to "succeed" the load prevents the OmniBus fallback that provides
5655  // generic frontmatter / counter / theorem bindings.
5656  //
5657  // PERL-FAITHFUL (2026-05-30): a directory prefix does NOT force a raw .cls
5658  // load. Perl resolves a path-prefixed class to its basename BINDING when one
5659  // exists, else OmniBus — it loads `IEEEtran.cls.ltxml` for
5660  // `\documentclass{misc/ieeetran}` and falls to OmniBus for
5661  // `\documentclass{JINST-Sample-files/JINST}`. The basename→binding match is
5662  // handled in the `alternate` search below (it strips the path). Forcing a raw
5663  // load for any path-prefixed name (the old `&& !has_path_prefix` exception)
5664  // broke bundled classes whose raw load is semantically incomplete — JINST's
5665  // begin-document `\author`/`\abstract` checks fire and `\abstract@cs` is left
5666  // undefined, where Perl (OmniBus) is clean. Witness 1504.01965; the
5667  // misc/ieeetran case (2105.02087) now matches Perl via the basename binding.
5668  // That holds under `notex` (INCLUDE_CLASSES off). The arXiv profile's raw classes (`localrawclasses` since 62k,
5669  // `rawclasses` since 67v; DIVERGENCES #444) interpret a class with no binding route raw, path-prefixed or not. JINST's begin-document checks,
5670  // which then fired (1504.01965, 1011.5969, 1310.6454), are met by its binding since 64k (OXIDIZED_DESIGN #482).
5671  // A path-prefixed class whose basename names a binding is that binding, loaded as the request's own file
5672  // ([`class_binding_for_path`]; Perl Package.pm:2125-2128): ahead of any raw read of the shipped copy, as Perl's
5673  // `FindFile_aux` prefers the `.ltxml`. It is loaded under its own name, as LaTeX names a path-prefixed class by its
5674  // basename (`\@currname` = `acmart`; latex.ltx:18740-18748 `\@onefilewithoptions`, whose `\@currpath` =
5675  // `lib-acm/` is not set here), so `\@ifclassloaded{acmart}` holds (OXIDIZED_DESIGN #444); `fallback_request` keeps the path for a family binding that reads the shipped
5676  // copy (`shipped_class::requested_shipped_class`: JINST, 1504.01965).
5677  if let Some(binding) = class_binding_for_path(name) {
5678    let outer_request = lookup_string("fallback_request");
5679    let outer_target = lookup_string("fallback_target");
5680    assign_value("fallback_request", name.to_string(), Some(Scope::Global));
5681    assign_value("fallback_target", binding.to_string(), Some(Scope::Global));
5682    let loaded = input_definitions(binding, InputDefinitionOptions {
5683      extension: Some(Cow::Borrowed("cls")),
5684      options,
5685      after,
5686      notex: true,
5687      handleoptions: true,
5688      noerror: true,
5689      nested_class,
5690      ..InputDefinitionOptions::default()
5691    });
5692    assign_value("fallback_request", outer_request, Some(Scope::Global));
5693    assign_value("fallback_target", outer_target, Some(Scope::Global));
5694    return loaded;
5695  }
5696  let notex_default = !lookup_bool("INCLUDE_CLASSES");
5697  // Perl Package.pm:2705-2707: LoadClass can be limited to local SEARCHPATHS when
5698  // `localrawclasses` option sets `INCLUDE_CLASSES => 'searchpaths'`.
5699  let searchpaths_only = !notex_default && lookup_string("INCLUDE_CLASSES") == "searchpaths";
5700  // With raw classes on — `rawclasses` (the arXiv profile since 67v) or `localrawclasses` (62k) — a raw class stands
5701  // in for OmniBus only: every binding route comes first — the basename binding of a path-prefixed class above, the
5702  // exact and versioned ones inside `input_definitions`, the prefix/case alternate here — so a shipped
5703  // `IEEEtranTCOM.cls`, `IEEEtran4PSCC.cls` or `misc/ieeetran.cls` keeps the IEEEtran binding (2105.02087) instead of
5704  // loading raw (OXIDIZED_DESIGN_DIVERGENCES #444).
5705  // Nor is a class written for another format read raw (`\NeedsTeXFormat{pLaTeX2e}`, jarticle.cls:16; TeX Live's 19
5706  // pLaTeX and upLaTeX classes, [`declared_other_format`]): LaTeX reads the declaration and processes the file no
5707  // further (latex.ltx:18663-18674), and a raw read of the rest met the other format's primitives (jarticle.cls:26-28
5708  // `\hour`, `\minute` registers; a Fatal, 1203.0762) where OmniBus kept the paper's text. The declaration itself is
5709  // read, so the format's input profile is the document's (K12: `\NeedsTeXFormat{pLaTeX2e}` letters kanji in
5710  // control-word names, sect05.rs), and the class falls to OmniBus.
5711  // A name's prefix marks an author's renamed copy beside the document, or a sibling shipped with the binding's class
5712  // (`jmlrbook` beside `jmlr.cls`, `acmart-tagged` beside `acmart.cls`), not any other published class of the TeX
5713  // distribution, which is a class of its own, read raw as LaTeX reads it: `bookest` ("Extension for the book class"),
5714  // `bookcover`, `beamerswitch`, `bookshelf`, `postcards`, `aalok`, `anima` took `book`, `beamer`, `pos`, `aa`, `an` and
5715  // lost their commands (sweep #150; docs/perfect_kernel/MANUAL_REGRESSIONS.md cluster A). Perl reads the file first,
5716  // too (Package.pm:2700-2716: the prefix scan is the no-file branch).
5717  let alternate =
5718    class_binding_alternate(name).filter(|binding| !is_unrelated_distribution_class(name, binding));
5719  let other_format = (!notex_default && alternate.is_none())
5720    .then(|| declared_other_format(name))
5721    .flatten();
5722  if let Some(format) = &other_format {
5723    digest(crate::mouth::tokenize_internal(TeXString::assembled(s!(
5724      "\\NeedsTeXFormat{{{format}}}"
5725    ))))?;
5726  }
5727  let raw_excluded = !notex_default && (alternate.is_some() || other_format.is_some());
5728  let notex_first = notex_default || raw_excluded;
5729
5730  let result = input_definitions(name, InputDefinitionOptions {
5731    extension: Some(Cow::Borrowed("cls")),
5732    options: options.clone(),
5733    after: after.clone(),
5734    notex: notex_first,
5735    searchpaths_only: searchpaths_only && !raw_excluded,
5736    handleoptions: true,
5737    noerror: true,
5738    nested_class,
5739    ..InputDefinitionOptions::default()
5740  });
5741  // A Fatal raised while the class loaded (an unbalanced expansion, a bail)
5742  // is not a missing class: it aborts the conversion (Perl dies), and the top
5743  // level logs it once. Falling to OmniBus hid the Fatal line (jarticle.cls:94
5744  // `\ds@tate`; `unbalanced_expansion_is_fatal`).
5745  if result.is_err() && get_status(LogStatus::Fatal) > 0 {
5746    return result;
5747  }
5748  // Perl Package.pm L2700-2716: if no direct binding, try a prefix-match fallback.
5749  // Scan all known cls bindings (longest-first), pick the first whose name is a
5750  // prefix of the requested class. This catches author-renamed classes like
5751  //   mysvjour3.cls → ProvidesClass{svjour3} → binding: svjour3
5752  //   mn2ebis.cls   → starts with "mn2e"   → binding: mn2e
5753  //   IEEEtranTCOM.cls → starts with "IEEEtran" → binding: IEEEtran
5754  // Fall through to OmniBus only when nothing matches.
5755  let will_fallback = (result.is_err()
5756    || (!lookup_bool(&format!("{name}.cls_loaded"))
5757      && !lookup_bool(&format!("{name}.cls_raw_loaded"))))
5758    && name != "OmniBus"
5759    && name != "article"
5760    && !lookup_bool("OmniBus.cls_loaded")
5761    && !lookup_bool("OmniBus.cls_raw_loaded");
5762
5763  // Perl Package.pm L2679 (LoadClass branch): scan the raw .cls for
5764  // \usepackage/\RequirePackage/\LoadClass dependencies when no .cls.ltxml
5765  // binding was found. This matters for unknown classes that nonetheless
5766  // pull in well-known packages (e.g. ijms-preprint.cls loads amsmath);
5767  // without it, downstream code like `\eqref{foo_bar}` sees `\eqref` as
5768  // undefined and the `_` characters then reach the stomach as subscript
5769  // catcodes, triggering runaway error recovery (arxiv 1003.0934 OOM).
5770  // Skip deps-scan only when a real `.cls.ltxml` binding has been
5771  // loaded — that binding is responsible for its own
5772  // `\RequirePackage` calls. The `cls_loaded` flag is set even for
5773  // a successful raw .cls load (no binding), so we MUST check the
5774  // binding-specific `cls.ltxml_loaded` flag instead. Without
5775  // this, paper-bundled .cls files (e.g. myclass.cls bundling
5776  // caption + many others, witness 2202.11535) raw-load
5777  // successfully but their `\RequirePackage` calls do NOT trigger
5778  // our binding loaders, leaving \captionsetup / \href / \affil
5779  // undefined.
5780  //
5781  // PERL-FAITHFUL ORDER: when we will fall through to an alternate
5782  // class binding (OmniBus or a prefix-match), DEFER the deps-scan
5783  // until AFTER the alternate is loaded. Otherwise the deps-scan
5784  // pulls natbib (et al.) ahead of OmniBus, and OmniBus's later
5785  // `Let('\lx@OmniBus@saved@bibitem', '\bibitem')` +
5786  // `DefMacro('\bibitem', ...)` clobbers natbib's `\lx@nat@bibitem`
5787  // binding — infinite-loop chain on
5788  // `\bibitem[\protect\citeauthoryear{...}{...}{...}]{key}`.
5789  // Witness: 1001.1919, 1001.5004, 0809.4358 (statsoc.cls),
5790  // 0904.3132, 0912.1617 (ectj.cls), 0904.3938 (compositio.cls),
5791  // 0908.3882 (third-input timeout), 0911.1590 (\tag\textsc cascade).
5792  // Perl's load order in this branch: warn missing-binding → load
5793  // alternate (OmniBus) → deps-scan pulls natbib LAST → natbib's Let
5794  // overrides OmniBus correctly.
5795  // ALSO skip the deps-scan after a SUCCESSFUL raw .cls load: Perl only ever
5796  // scans in the missing-binding branch, after loading the ALTERNATE
5797  // (Package.pm L2731-2733; a successful InputDefinitions returns at L2713-14
5798  // with no scan). An executed raw `\RequirePackage` triggers our binding
5799  // loaders directly (verified: bundled myclass.cls → caption_sty.rs loads,
5800  // \captionsetup/\eqref clean), so the scan only ADDS the harvest of
5801  // `\LoadClass`/`\RequirePackage` lines from UNEXECUTED branches — the
5802  // beamerswitch witness: its article branch ran, but the scan saw the three
5803  // `\LoadClass{beamer}` in never-taken branches and loaded beamer_cls.rs
5804  // AFTER raw beamerarticle, clobbering the correct raw `\mode`/`\only`
5805  // (perfect-kernel; Perl converts the same doc with 0 errors).
5806  if !lookup_bool(&s!("{name}.cls.ltxml_loaded"))
5807    && !lookup_bool(&s!("{name}.cls_raw_loaded"))
5808    && !will_fallback
5809  {
5810    maybe_require_dependencies(name, "cls");
5811  }
5812  if will_fallback {
5813    note_status(LogStatus::Missing, Some(&format!("{name}.cls")));
5814
5815    // Perl: @classes = sort { -(length($a) <=> length($b)) } available_cls_names
5816    //       my ($alternate) = grep { $class =~ /^\Q$_\E/ } @classes;
5817    // Flatten across ALL registered binding crates (latexml_package +
5818    // latexml_contrib + any future extensions) so contrib classes like
5819    // `memoir`, `siamltex`, `scrbook` are eligible alternates too.
5820    let alternate = class_binding_alternate(name);
5821
5822    let target = alternate.unwrap_or("OmniBus");
5823    Warn!(
5824      "missing_file",
5825      name,
5826      format!("Can't find binding for class {name} (using {target})"),
5827      "Anticipate undefined macros or environments"
5828    );
5829    // The request the alternate answers, as for a versioned fallback (`fallback_request` in
5830    // `input_definitions`): a binding serving a family of classes reads which one was asked for
5831    // (informs_cls.rs: `informs3noheader` prints no blind-review notice, 2609.04127).
5832    let outer_request = lookup_string("fallback_request");
5833    let outer_target = lookup_string("fallback_target");
5834    assign_value("fallback_request", name.to_string(), Some(Scope::Global));
5835    assign_value("fallback_target", target.to_string(), Some(Scope::Global));
5836    let loaded = input_definitions(target, InputDefinitionOptions {
5837      extension: Some(Cow::Borrowed("cls")),
5838      options,
5839      after,
5840      notex: true,
5841      handleoptions: true,
5842      noerror: true,
5843      nested_class,
5844      ..InputDefinitionOptions::default()
5845    });
5846    assign_value("fallback_request", outer_request, Some(Scope::Global));
5847    assign_value("fallback_target", outer_target, Some(Scope::Global));
5848    // Perl Package.pm L2715: after loading the alternate class binding, scan
5849    // the raw class file for \usepackage/\RequirePackage/\LoadClass — the
5850    // alternate rarely covers all dependencies the renamed class adds.
5851    // Run for BOTH a real prefix-match alternate AND the pure-OmniBus
5852    // fallback (the deps were deferred above so their require_package
5853    // calls fire AFTER OmniBus is in place).
5854    maybe_require_dependencies(name, "cls");
5855    return loaded;
5856  }
5857  result
5858}
5859
5860/// configuration for searching for a file in the local filesystem
5861#[derive(Default)]
5862pub struct FindFileOptions {
5863  // TODO: this is no longer used in find_file, rather a level earlier
5864  pub forbid_ltxml:      bool,
5865  pub notex:             bool,
5866  pub ext_type:          Option<Cow<'static, str>>,
5867  pub search_paths_only: bool,
5868}
5869
5870/// search for a file as prescribed by a `FindFileOptions` configuration
5871pub fn find_file(file: &str, options: Option<FindFileOptions>) -> Option<String> {
5872  // (a lookup of a type looks for the name with that extension, the file a refusal names: `\usepackage{x}` and
5873  // `\bibliography{x}` ask for `x.sty` and `x.bib` more than once)
5874  let requested = match options.as_ref().and_then(|o| o.ext_type.as_deref()) {
5875    Some(ext) if pathname::is_confined() && !ext.is_empty() && !file.ends_with(&s!(".{}", ext)) => {
5876      Cow::Owned(s!("{}.{}", file, ext))
5877    },
5878    _ => Cow::Borrowed(file),
5879  };
5880  pathname::requested_as(&requested, || find_file_requested(file, options))
5881}
5882
5883fn find_file_requested(file: &str, options: Option<FindFileOptions>) -> Option<String> {
5884  let file = pathname::dot_relative(file);
5885  let options = options.unwrap_or_default();
5886  if pathname::is_literaldata(file) {
5887    // If literal protocol return immediately (unless notex!)
5888    if options.notex {
5889      None
5890    } else {
5891      // TODO: Consider returning a Cow<str> instead to optimize
5892      Some(file.to_string())
5893    }
5894  } else if pathname::is_literaldata(file) || pathname::is_url(file) {
5895    // If a known special protocol return immediately
5896    Some(file.to_string())
5897  } else if let Some(ref ext) = options.ext_type {
5898    // Otherwise, it's some kind of "real" file, and we might have to search for it
5899    // Specific type requested? Search for it.
5900    // Add the extension, if it isn't already there. Perl tests with the DOT
5901    // (`/\.\Q$type\E$/`): a bare `\bibliography{mybib}` must retry
5902    // `mybib.bib` — the dotless ends_with("bib") matched the basename itself
5903    // and searched the literal `mybib`, silently disabling the .bib fallback
5904    // (PR_READINESS must-fix 6).
5905    let dotted = s!(".{}", ext);
5906    let aux_file = if file.ends_with(&dotted) {
5907      file.to_string()
5908    } else {
5909      s!("{}.{}", file, ext)
5910    };
5911    find_file_aux(&aux_file, &options)
5912  } else if file.ends_with(".tex") {
5913    // If no type given, we MAY expect .tex, or maybe NOT!!
5914    // No requested type, then .tex; Of course, it may already have it!
5915    find_file_aux(file, &options)
5916  } else {
5917    match find_file_aux(&s!("{}.tex", file), &options) {
5918      None => find_file_aux(file, &options),
5919      Some(f) => Some(f),
5920    }
5921  }
5922}
5923
5924/// Does a compiled binding answer an existence test (`\IfFileExists`, `\InputIfFileExists`) for `file`, as the file
5925/// itself? Perl's `\IfFileExists` asks `FindFile` (latex_constructs.pool.ltxml:5692-5697), which takes a `.ltxml`
5926/// binding for the file (Package.pm:2125-2128): pgf's `\IfFileExists{pgfsys-latexml.def}` (LaTeXML's own driver) and
5927/// babel's `\InputIfFileExists{italian.ldf}` on a tree without it find their bindings. A binding standing in for an
5928/// author's file is not that file ([`crate::binding::author_files`]): TeX finds `arxiv.sty` only where the paper ships
5929/// it, and so do we, by the disk search the caller makes first (2606.27281; Perl answers true for its own such
5930/// bindings, `neurips.sty`, KNOWN_PERL_ERRORS #770).
5931pub fn binding_counts_as_file(file: &str) -> bool {
5932  !crate::binding::author_files::stands_in_for_an_author_file(file)
5933    && find_file(
5934      file,
5935      Some(FindFileOptions {
5936        notex: true,
5937        ..Default::default()
5938      }),
5939    )
5940    .is_some()
5941}
5942
5943/// Suffixes with separator (Perl @find_fallback_suffixes).
5944static FALLBACK_SUFFIX: LazyLock<Regex> = LazyLock::new(|| {
5945  Regex::new(r"(?i)[._-](arx|arxiv|conference|workshop|tmp|alternate|preprint|fixed|[vV]?[-_.\d]+|old|new|final|clean|mine|priv|rev|mod|modified|edited|custom|altered|rtx)$").unwrap()
5946});
5947/// Glued suffixes without separator.
5948static FALLBACK_GLUED: LazyLock<Regex> =
5949  LazyLock::new(|| Regex::new(r"(?i)([vV]?[-_.\d]+|arxiv)$").unwrap());
5950/// Prefixes. Perl Package.pm L2182: `^((?:rw|my|preprint)[-_.]?)` — separator is OPTIONAL, so `mysvjour3` strips to
5951/// `svjour3` (not just `mysvjour`). Caught on arxiv 1206.0536 (\documentclass{mysvjour3}).
5952static FALLBACK_PREFIX: LazyLock<Regex> =
5953  LazyLock::new(|| Regex::new(r"(?i)^((?:rw|my|preprint)[-_.]?)").unwrap());
5954
5955/// Perl Package.pm L2141-2210: FindFile_fallback
5956/// Pure-check variant of [`find_file_fallback`]: strips the same
5957/// suffix/prefix patterns and reports whether the fallback name has a
5958/// registered binding, but DOES NOT eagerly invoke the binding's
5959/// `load_definitions`. Use this from pre-flight existence checks (e.g.
5960/// `class_cls_via_fallback` in tex_job.rs) where firing the binding's
5961/// body has side effects (\LoadClass, \RequirePackage) that contaminate
5962/// the subsequent real load. Witness: astro-ph0002213 — the `\psfig`
5963/// cluster fix (mn1 → mn fallback was eagerly running mn.cls's
5964/// `\LoadClass{article}` before the `\documentstyle[epsfig]{mn1}`
5965/// option-pass-through machinery had a chance to enqueue `epsfig` into
5966/// `opt@article.cls`).
5967pub fn find_file_fallback_exists(name: &str, ext_type: &str) -> bool {
5968  version_stripped_name(name).is_some_and(|base| binding_exists(&base, ext_type))
5969}
5970
5971/// The generic name Perl's `FindFile_fallback` asks for (Package.pm:2191-2226): `name`'s basename with its version
5972/// suffixes, glued suffixes and `rw`/`my`/`preprint` prefixes stripped, or `None` when nothing was stripped
5973/// (`aastex631` → `aastex`, `neurips_2026` → `neurips`, `mysvjour3` → `svjour3`).
5974pub fn version_stripped_name(name: &str) -> Option<String> {
5975  let (suffix_rx, glued_rx, prefix_rx) = (&*FALLBACK_SUFFIX, &*FALLBACK_GLUED, &*FALLBACK_PREFIX);
5976  // Strip a leading directory path (Perl Package.pm L2167-2170: FindFile_fallback
5977  // calls `pathname_name($name)` first, so e.g. `\documentclass{./sty/IEEEtran}`
5978  // routes the basename `IEEEtran` through the binding-name registry. Without
5979  // this, `IEEEtran.cls.ltxml` is missed because `./sty/IEEEtran.cls.ltxml`
5980  // never matches the @ltxml_paths registry. Driver paper: arXiv:1308.6663.
5981  let basename = pathname::file_name(name);
5982  let mut base = if basename.is_empty() {
5983    name.to_string()
5984  } else {
5985    basename
5986  };
5987  let dir_stripped = base != name;
5988  let mut suffix_stripped = false;
5989  // Iteratively strip suffixes, then glued, then prefixes.
5990  //
5991  // Perl's FindFile_fallback (Package.pm:2174) version-strips the FULL `$file`
5992  // *with its directory prefix intact*, so the prefix regex `^(rw|my|preprint)`
5993  // — anchored at the very START of the string — never matches a name that
5994  // begins with a directory (e.g. `sty/myunits` starts with `sty/`, not `my`).
5995  // We strip the directory FIRST (to allow a basename-exact binding match like
5996  // `misc/ieeetran` → IEEEtran), so we must NOT then apply the `^`-anchored
5997  // prefix strip to the basename, or `sty/myunits` wrongly becomes `units` and
5998  // loads the stock units.sty instead of the paper-local myunits.sty (which
5999  // defines `\T`/`\fC`/`\Cm` via its `\defUnit` mechanism). Witness 1702.05093.
6000  // The suffix/glued strips ARE `$`-anchored, so they still match the tail of a
6001  // dir-prefixed name in Perl (`./aaspp4` → `./aaspp`); keep applying them.
6002  loop {
6003    if let Some(m) = suffix_rx.find(&base) {
6004      base = base[..m.start()].to_string();
6005      suffix_stripped = true;
6006      continue;
6007    }
6008    if let Some(m) = glued_rx.find(&base) {
6009      base = base[..m.start()].to_string();
6010      suffix_stripped = true;
6011      continue;
6012    }
6013    if !dir_stripped && let Some(m) = prefix_rx.find(&base) {
6014      base = base[m.end()..].to_string();
6015      suffix_stripped = true;
6016      continue;
6017    }
6018    break;
6019  }
6020
6021  // A directory strip ALONE no longer triggers a fallback: `subdir/<name>` is a PATH, not a
6022  // version, so it must not name-match `<name>`'s binding (that shadowed paper-local subdir
6023  // packages, e.g. `utils/mathenv` -> the unrelated CTAN mathenv binding, leaving the local
6024  // file — and its cleveref/theorem defs — unloaded). Only a real VERSION suffix/prefix strip
6025  // (neurips_2026->neurips, mysvjour3->svjour3) qualifies, matching Perl's FindFile_fallback
6026  // (which never strips a directory). The retired `BasenameOnly` convenience (2105.02087
6027  // misc/ieeetran, 2405.18387 assets/equations) now falls to raw-load/OmniBus like Perl.
6028  if !suffix_stripped || base.is_empty() || base == name {
6029    return None;
6030  }
6031  Some(base)
6032}
6033
6034/// Kind of fallback that matched, returned by [`find_file_fallback`].
6035///
6036/// `Versioned` — suffix/prefix stripping changed the basename (Perl
6037/// FindFile_fallback's core function). Drivers: 1206.0536 (mysvjour3
6038/// → svjour3), astro-ph0005021 (./aaspp4 → ./aaspp).
6039///
6040/// `BasenameOnly` — the *only* change was directory-prefix removal,
6041/// matching the binding registry by leaf name. This is a Rust-specific
6042/// extension on top of Perl's FindFile_fallback that exists because
6043/// our contrib-binding registry is keyed by basename. Drivers:
6044/// 2105.02087 (misc/ieeetran → IEEEtran binding); 2405.18387
6045/// (assets/equations → equations binding).
6046///
6047/// Both kinds win unconditionally over local raw `.sty`/`.cls` files
6048/// at the call site (see `input_definitions` Step 3): the `.rs`
6049/// bindings are hand-tuned for the conversion, so a binding match
6050/// always supersedes a co-located vendored copy. The variant is
6051/// preserved for diagnostics and potential future policy tweaks.
6052#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6053pub enum FallbackKind {
6054  Versioned,
6055  BasenameOnly,
6056}
6057
6058/// Strip version/arxiv suffixes from package names to find existing bindings.
6059/// Returns the fallback filename (with extension) and which kind of fallback fired.
6060pub fn find_file_fallback(name: &str, ext_type: &str) -> Option<(String, FallbackKind)> {
6061  let base = version_stripped_name(name)?;
6062  let kind = FallbackKind::Versioned;
6063
6064  let fallback_filename = format!("{base}.{ext_type}");
6065  // Whether a binding answers to the stripped name, asked of the registry without running it, as Perl's
6066  // `FindFile_fallback` asks `pathname_find("$fallback_query.ltxml")` (Package.pm:2221-2226) — case-insensitively, as
6067  // the dispatchers match (`jhep…` → `JHEP.cls`). Running it here as the probe ran it twice with the caller's load: a
6068  // binding that saves a command before redefining it saved its own redefinition the second time —
6069  // `\usepackage{hyperref.2.0}` made `\H@refstepcounter` expand to itself, and every `\section` looped (Fatal;
6070  // 2606.14467). A binding the registry cannot name (a runtime binding) is probed by loading it; the caller's load of
6071  // the same name is then skipped (`reloadable: false`), so it still runs once.
6072  let registered = get_binding_names().iter().any(|names| {
6073    names
6074      .iter()
6075      .any(|(n, e)| n.eq_ignore_ascii_case(&base) && e.eq_ignore_ascii_case(ext_type))
6076  });
6077  if registered
6078    || matches!(load_binding(&fallback_filename), Ok(Some(_)))
6079    || matches!(load_external_binding(&fallback_filename), Ok(Some(_)))
6080  {
6081    Some((fallback_filename, kind))
6082  } else {
6083    None
6084  }
6085}
6086
6087fn find_file_aux(file: &str, options: &FindFileOptions) -> Option<String> {
6088  // If cached, return simple path (it's a key into the cache). An empty
6089  // virtual file is still a file: tcolorbox's `\tcbwritetemp` over an empty
6090  // `posterboxenv` body stores "" and `\tcbusetemp` then `\input`s it —
6091  // falling through to disk raised `missing_file:<job>.tcbtemp` ×7 on
6092  // tcolorbox/tcolorbox-tutorial-poster (+ the bfh-ci/tuda-ci poster demos).
6093  // expl3's `\file_full_name:n` (and `\input{./x}`) hand a `./`-prefixed
6094  // name to `\openin`; the cache key is the name `filecontents` was given.
6095  let vkey = file.strip_prefix("./").unwrap_or(file);
6096  // A NUL makes the system open another file (pdflatex reads `n^^@x` as `n.tex`); a CR or LF is refused with it, so
6097  // the finder and the confinement's `allows` apply one rule (OXIDIZED_DESIGN_DIVERGENCES #1193). Every other character
6098  // is looked for as pdflatex and Perl's FindFile_aux look for it (`\input{a>b/part}`; `|cmd.tex` a file's name).
6099  if file.contains(['\0', '\r', '\n']) {
6100    return None;
6101  }
6102  if crate::binding::virtual_files::vfs_exists(vkey) {
6103    return Some(vkey.to_string());
6104  }
6105  if pathname::is_absolute(file) {
6106    // Perl Package.pm L2089-2093:
6107    //   if pathname_is_absolute($file) {
6108    //     if (!$options{noltxml}) {
6109    //       return $file . '.ltxml' if -f ($file . '.ltxml'); }
6110    //     return $file if -f $file;
6111    //     return; }
6112    // No `<file>.ltxml` lookup (Perl checked one here): a `.ltxml` is a Perl
6113    // LaTeXML binding latexml-oxide can never read. Binding availability is
6114    // decided by the DISPATCHER (compiled + Rhai) in the relative-path branch's
6115    // `notex` fast-path, not by a file on disk.
6116    if pathname::read_allowed(file) {
6117      pathname::is_readable_file(file).then(|| file.to_string())
6118    } else {
6119      if pathname::refused_exists(file) {
6120        pathname::refuse(file);
6121      }
6122      None
6123    }
6124  } else {
6125    // Note that the strategy is complicated by the fact that
6126    // (1) we prefer .ltxml bindings, if present
6127    // (2) those MAY be present in kpsewhich's DB (although our searchpaths take precedence!)
6128    // (3) BUT we want to avoid kpsewhich if we can, since it's slower
6129    // (4) depending on switches we may EXCLUDE .ltxml OR raw tex OR allow both.
6130    let paths: Vec<String> = get_search_paths();
6131    // let _urlbase = state!().lookup_value("URLBASE");
6132    // let _nopaths = lookup_bool("REMOTE_REQUEST");
6133    // let _ltxml_paths: Vec<String> = if nopaths { vec![] } else { paths.clone() };
6134
6135    // Rust equivalent of Perl's ".ltxml" check: if the binding dispatcher
6136    // has an entry for this file, consider it "found". This is how Perl's
6137    // FindFile discovers pgfsys-latexml.def.ltxml etc.
6138    //
6139    // Two registry kinds are consulted (in order of cost):
6140    //  1. The per-call `{file}_binding_available` runtime flag, which packages can set to
6141    //     pre-announce their availability (used by pgf_sty for `pgfsys-latexml.def`).
6142    //  2. The compile-time class registry (latexml_package's `BINDINGS`) surfaced via
6143    //     `state::get_class_binding_names()`. Without this, `find_file("revtex4-1.cls",
6144    //     notex=true)` returned None for compiled-in bindings — so AIAA.cls's
6145    //     `\LoadClass{revtex4-1}` was silently skipped, breaking the eager natbib transitive load
6146    //     (1709.05096 / AIAA → 60s wall-clock SIGABRT in the autoload- trapped-by-abstract loop).
6147    // Binding-marker fast paths. ONLY fire when caller has requested
6148    // `notex=true` (i.e. caller wants binding-only search, not a real
6149    // disk path). Without this gate, raw `\openin` /`\IfFileExists`
6150    // calls (notex=false) get a literal binding name back as if it were
6151    // a path — `Mouth::open_file` then fails / produces an empty mouth
6152    // and `\ifeof` returns true, masking the file as missing. Mirrors
6153    // Perl `pathname_find`: only `noltxml=>0,notex=>1` returns binding
6154    // names; the disk-search variant only resolves real files.
6155    // Triggered by 2026-04-26 t1enc.def-cascade investigation: raw
6156    // fonttext.ltx's `\input  {t1enc.def}` opens via raw `\openin` /
6157    // `\IfFileExists`; without this gate find_file returned literal
6158    // "t1enc.def" → empty mouth → kernel's `\@missingfileerror` → 1M
6159    // TooManyErrors during latex.ltx dump-build.
6160    if !options.forbid_ltxml && options.notex {
6161      if lookup_bool(&s!("{file}_binding_available")) {
6162        return Some(file.to_string());
6163      }
6164      // Check the compile-time binding registries from latexml_package and
6165      // latexml_contrib for ANY (name, ext) pair that matches `file`.
6166      // Matches both multi-dot extensions (e.g. pgfmath.code.tex -> ("pgfmath", "code.tex"))
6167      // and multi-dot package names (e.g. phy-ab.braket.sty -> ("phy-ab.braket", "sty")).
6168      if file.contains('.') {
6169        // Perl pathname_find L383-389: strict-case first, then case-insensitive
6170        // fallback (mirrors the dispatcher's lookup). Without this, requests
6171        // like `find_file("jhep.cls", notex=true)` would miss `("JHEP","cls")`
6172        // entries that derive from Perl's `JHEP.cls.ltxml` filename.
6173        let exact = get_binding_names().iter().any(|slice| {
6174          slice.iter().any(|(n, e)| {
6175            file.len() == n.len() + 1 + e.len()
6176              && file.starts_with(n)
6177              && file.as_bytes()[n.len()] == b'.'
6178              && file.ends_with(e)
6179          })
6180        });
6181        let nocase = exact
6182          || get_binding_names().iter().any(|slice| {
6183            slice.iter().any(|(n, e)| {
6184              file.len() == n.len() + 1 + e.len()
6185                && file[..n.len()].eq_ignore_ascii_case(n)
6186                && file.as_bytes()[n.len()] == b'.'
6187                && file[n.len() + 1..].eq_ignore_ascii_case(e)
6188            })
6189          });
6190        if nocase {
6191          return Some(file.to_string());
6192        }
6193      }
6194    } else if !options.forbid_ltxml {
6195      // Narrow notex=false (disk-search) fallback: ONLY honor explicit
6196      // `<file>_binding_available` runtime flags, NOT the broad compile-time
6197      // registry. Mirrors Perl `\openin` calling default-args FindFile —
6198      // see `TeX_FileIO.pool.ltxml:50-64` "we SHOULD find an .ltxml version!"
6199      //
6200      // Use case: pgf.sty's pgfsys.code.tex `\pgfutil@InputIfFileExists{\pgfsysdriver}`
6201      // → `\pgfutil@IfFileExists{pgfsys-latexml.def}` → `\openin` with notex=false.
6202      // The openin impl in tex_file_io.rs creates an empty Mouth on
6203      // Mouth::create failure, so \ifeof=false → pgf inputs the driver.
6204      // pgf_sty.rs sets `pgfsys-latexml.def_binding_available=true` to
6205      // enable this; without the flag we don't fake-find arbitrary binding
6206      // names (which would re-introduce the t1enc.def `\@missingfileerror`
6207      // cascade documented above the notex=true branch).
6208      if lookup_bool(&s!("{file}_binding_available")) {
6209        return Some(file.to_string());
6210      }
6211    }
6212    // Perl L2123-2125: `elsif !notex && !interpreting && pathname_find($file,
6213    // paths=>$paths)` — search local paths for raw TeX.
6214    // (Rust does not yet honour `INTERPRETING_DEFINITIONS` — minor TODO,
6215    //  acknowledged in the audit.)
6216    if !options.notex
6217      && let Some(path) = pathname::find(file, PathnameFindOptions {
6218        paths: Some(paths),
6219        ..PathnameFindOptions::default()
6220      })
6221    {
6222      return Some(path);
6223    }
6224    // Perl L2131-2136: build kpsewhich candidate list:
6225    //   @candidates = ( "$file.ltxml" if !noltxml && !nopaths,
6226    //                   $file        if !notex );
6227    //   if (!searchpaths_only) && pathname_kpsewhich(@candidates) → -f $result
6228    // Perl gates the kpsewhich call only on `!searchpaths_only`; `notex`
6229    // and `noltxml` instead control which candidate names are tried.
6230    if options.search_paths_only {
6231      return (!options.notex).then(|| find_on_input_path(file)).flatten();
6232    }
6233    // NB: we do NOT add a `<file>.ltxml` candidate. That was Perl's logic —
6234    // a `.ltxml` is a Perl LaTeXML binding, and latexml-oxide can never read
6235    // one (as TeX or otherwise). The Rust equivalent of "is there a binding for
6236    // this name?" is the BINDING DISPATCHER (the `get_binding_names()` /
6237    // `{file}_binding_available` fast-path above, gated on `notex`), not a
6238    // `.ltxml` on disk. Otherwise kpsewhich returns e.g. `stex.sty.ltxml` (it
6239    // ships in TeX Live) ahead of the raw `stex.sty`, and the raw-loader
6240    // tokenizes the Perl source as TeX (`$out =~ s/^\s+//;` → "Script ^…",
6241    // `\DefMacroI` undefined, …). A missing binding falls through to the raw
6242    // `.sty`, matching pdflatex.
6243    let mut candidates: Vec<String> = Vec::new();
6244    if !options.notex {
6245      candidates.push(file.to_string());
6246    }
6247    if candidates.is_empty() {
6248      return None;
6249    }
6250    let refs: Vec<&str> = candidates.iter().map(|s| s.as_str()).collect();
6251    match pathname::kpsewhich(&refs) {
6252      // Perl L2136: `(-f $result ? $result : undef)` — re-confirm existence.
6253      Some(p) if Path::new(&p).exists() => Some(p),
6254      _ => find_on_input_path(file),
6255    }
6256  }
6257}
6258
6259/// l3file's `\file_full_name:n` (expl3-code.tex:12585-12612), which `\IfFileExists` asks (latex.ltx:9667-9696): a
6260/// file kpathsea does not find is looked for under each entry of `\input@path`, in order, a `/` added to an entry
6261/// lacking one (`\__file_full_name_slash:n`). Perl's FindFile has no such step, so a paper keeping its style files in a
6262/// subdirectory (`\def\input@path{{styles/}}`, 71 papers in 2609; 2609.02998's class style, whose natbib every
6263/// `\citep` needed) loaded none of them.
6264fn find_on_input_path(file: &str) -> Option<String> {
6265  let entries = input_path_entries();
6266  if entries.is_empty() {
6267    return None;
6268  }
6269  let paths = get_search_paths();
6270  entries.into_iter().find_map(|dir| {
6271    if !input_path_entry_allowed(&dir, &paths) {
6272      return None;
6273    }
6274    // (l3file makes an empty entry `/`, the filesystem root; the local paths, searched already, stand in for it)
6275    let candidate = if dir.is_empty() || dir.ends_with('/') {
6276      s!("{dir}{file}")
6277    } else {
6278      s!("{dir}/{file}")
6279    };
6280    if crate::binding::virtual_files::vfs_exists(&candidate) {
6281      return Some(candidate);
6282    }
6283    pathname::find(&candidate, PathnameFindOptions {
6284      paths: Some(paths.clone()),
6285      ..PathnameFindOptions::default()
6286    })
6287  })
6288}
6289
6290/// Whether a confined conversion searches the `\input@path` entry `dir` (absolute, or under one of `paths`); one
6291/// Warning per entry outside every root, which is then dropped.
6292pub fn input_path_entry_allowed(dir: &str, paths: &[String]) -> bool {
6293  if dir.is_empty() || !pathname::is_confined() {
6294    return true;
6295  }
6296  if pathname::is_absolute(dir) {
6297    return pathname::search_dir_allowed(dir, dir);
6298  }
6299  paths
6300    .iter()
6301    .any(|path| pathname::read_allowed(&pathname::concat(path, dir)))
6302    || pathname::search_dir_allowed(dir, &pathname::absolute(dir))
6303}
6304
6305/// The entries of `\input@path` (each brace group one directory, as `\tl_map_tokens:Nn` takes them; latex.ltx's
6306/// `\@iffileonpath` and l3file's `\file_full_name:n` look a file up under each in turn); none where it is undefined.
6307pub fn input_path_entries() -> Vec<String> {
6308  let Some(Stored::Expandable(defn)) = lookup_meaning(&T_CS!("\\input@path")) else {
6309    return Vec::new();
6310  };
6311  let Some(ExpansionBody::Tokens(body)) = defn.get_expansion() else {
6312    return Vec::new();
6313  };
6314  // `\tl_map_tokens:Nn` takes each brace group as one entry (a bare token would be an entry of its own, never a
6315  // directory).
6316  let mut entries: Vec<String> = Vec::new();
6317  let mut depth = 0usize;
6318  let mut entry = String::new();
6319  for token in body.unlist_ref() {
6320    match token.get_catcode() {
6321      Catcode::BEGIN => {
6322        if depth > 0 {
6323          entry.push_str(&token.to_string());
6324        }
6325        depth += 1;
6326      },
6327      Catcode::END if depth > 0 => {
6328        depth -= 1;
6329        if depth == 0 {
6330          entries.push(std::mem::take(&mut entry));
6331        } else {
6332          entry.push_str(&token.to_string());
6333        }
6334      },
6335      _ if depth > 0 => entry.push_str(&token.to_string()),
6336      _ => {},
6337    }
6338  }
6339  entries
6340}
6341
6342//======================================================================
6343// Declaring and Adjusting the Document Model.
6344//======================================================================
6345
6346/// Declare document-model properties for one element tag — Perl's `Tag`
6347/// (`Package.pm` L2015-2030).
6348///
6349/// Merges `properties` into the tag's existing entry rather than replacing it,
6350/// which is what lets a class, a package and the engine each contribute to the
6351/// same tag. How a property merges depends on the property: `auto_open` /
6352/// `auto_close` overwrite when given, while the accumulating properties
6353/// (`afterOpen`, `afterClose`, …) prepend or append per
6354/// [`TagOptionName::is_prepend`]/[`TagOptionName::is_append`] — Perl's
6355/// `$tag_prepend_options` / `$tag_append_options` tables, whose order decides
6356/// whether a late binding's hook runs before or after the engine's.
6357pub fn install_tag(tag: &str, mut properties: TagOptions) {
6358  let tag_ticket = arena::pin(tag);
6359  with_tag_property_mut(tag_ticket, |options| {
6360    if properties.auto_open.is_some() {
6361      options.auto_open = properties.auto_open;
6362    }
6363    if properties.auto_close.is_some() {
6364      options.auto_close = properties.auto_close;
6365    }
6366    for name in &TagOptionName::all() {
6367      if name.is_prepend() {
6368        options.prepend(name, properties.remove(name));
6369      } else if name.is_append() {
6370        options.append(name, properties.remove(name));
6371      } else {
6372        // we'll handle the regular ones out of the loop
6373      }
6374    }
6375  });
6376}
6377
6378/// Selects the RelaxNG schema defining the XML output language
6379pub fn select_relaxng_schema(schema: &str, namespaces: Option<HashMap<String, String>>) {
6380  // What verb here? Set, Choose,...
6381  model::set_relaxng_schema(schema);
6382  if let Some(namespaces) = namespaces {
6383    for (prefix, value) in namespaces {
6384      model::register_document_namespace(&prefix, Some(&value));
6385    }
6386  }
6387}
6388
6389/// Merge font attributes into the current font, **locally** — the change
6390/// reverts with the enclosing TeX group.
6391///
6392/// Port of Perl `Package.pm:MergeFont` L441-444
6393/// (`AssignValue(font => LookupValue('font')->merge(@kv), 'local')`). Only the
6394/// attributes `font` actually specifies are taken; the rest are inherited from
6395/// the font in force. See [`merge_font_ref`] to merge without moving the font.
6396///
6397/// In text, NFSS's font state follows the merge (`sync_nfss_font_state`).
6398pub fn merge_font(font: Font) { merge_font_ref(&font); }
6399
6400/// Like `merge_font` but borrows the font. Saves a clone when the caller
6401/// has a shared reference (e.g. via Rc) to the font being merged.
6402pub fn merge_font_ref(font: &Font) {
6403  let current = lookup_font().unwrap();
6404  let mut new_font = current.merge_ref(font);
6405  if font.name.is_some() {
6406    // A `\font` identifier changes `cur_font` only (tex.web §1217): NFSS's codes stay, and
6407    // the font they name is kept for the next selection to return to (`Font::nfss_font`).
6408    new_font.nfss_font = current
6409      .nfss_font
6410      .clone()
6411      .or_else(|| Some(std::sync::Arc::new((*current).clone())));
6412  } else {
6413    sync_nfss_font_state(&current, font, &new_font);
6414  }
6415  assign_font(Rc::new(new_font), Some(Scope::Local));
6416}
6417
6418/// Merge the font `\selectfont` chose from the NFSS codes (sect13.rs): those
6419/// codes are the state already, so nothing is written back — a family whose
6420/// table entry also carries a shape (`cmsltt`) must not overwrite the
6421/// `\f@shape` the next step selects.
6422pub fn merge_selected_font(font: &Font) {
6423  let new_font = lookup_font().unwrap().merge_ref(font);
6424  assign_font(Rc::new(new_font), Some(Scope::Local));
6425}
6426
6427/// Name `font` in `\f@family`, `\f@series`, `\f@shape` and `\f@size`, every
6428/// component as if selected: the NFSS half of a font reset that assigns the
6429/// font directly (base_utilities.rs `neutralize_font`), as `\reset@font` —
6430/// `\normalfont`, latex.ltx:14122 — does in `\@footnotetext`
6431/// (latex.ltx:17658-17659 `\reset@font\footnotesize`).
6432pub fn sync_nfss_font_codes(font: &Font) { sync_nfss_font_state(font, font, font); }
6433
6434/// Keep LaTeX's text-font state — `\f@family`, `\f@series`, `\f@shape`,
6435/// `\f@size` — naming the font a merge puts in force.
6436///
6437/// In LaTeX every text font change goes through those macros: `\bfseries` is
6438/// `\fontseries\bfdefault\selectfont`, `\tt` is `\normalfont\ttfamily`
6439/// (article.cls:490-493), `\small` is `\@setfontsize`, whose `\fontsize`
6440/// records `\f@size` (latex.ltx:12587, 14103-14107). The class and package
6441/// bindings switch the font directly, so a later `\selectfont` — a raw class's
6442/// `\small`, a size switch (dialect.rs) — re-selected stale codes: under
6443/// scrartcl `{\tt\small \foo}` came out roman (repro
6444/// `fonts-nfss/old_font_switch_then_size.tex`).
6445///
6446/// A component the merge specifies, or changes, is written back as an NFSS
6447/// code unless the code in force already denotes it, so `pcr` or `zi4`
6448/// survives a `\ttfamily`. A family with no NFSS code (`nullfont`, `graphic`,
6449/// `math`, and binding-only ones such as `oldstyle`) leaves `\f@family`
6450/// alone, as a raw TeX font switch leaves LaTeX's. A `\font`-defined
6451/// identifier writes no code (`merge_font_ref`), as in TeX, so
6452/// `\font\x=cmtt10 \x\small` is roman again. Math fonts are not
6453/// NFSS's text font (`\mathbf` leaves `\f@series`), so in math only an
6454/// explicit size is recorded, as `\@setfontsize`'s `\fontsize` does there
6455/// (latex.ltx:14103-14107). The writes are local, like the font assignment.
6456fn sync_nfss_font_state(current: &Font, merged: &Font, new_font: &Font) {
6457  if lookup_bool_sym(pin!("IN_MATH")) {
6458    if let Some(points) = merged.size {
6459      sync_nfss_size(points);
6460    }
6461    return;
6462  }
6463  let touched = |specified: bool, old: Option<&str>, new: Option<&str>| specified || old != new;
6464  if touched(
6465    merged.family.is_some(),
6466    current.family.as_deref(),
6467    new_font.family.as_deref(),
6468  ) && let Some(family) = new_font.family.as_deref()
6469  {
6470    sync_nfss_code(
6471      T_CS!("\\f@family"),
6472      family,
6473      |code| font::lookup_font_family(code).and_then(|f| f.family.as_deref()),
6474      font::nfss_family_code,
6475    );
6476  }
6477  if touched(
6478    merged.series.is_some() || merged.forcebold == Some(true),
6479    current.series.as_deref(),
6480    new_font.series.as_deref(),
6481  ) && let Some(series) = new_font.series.as_deref()
6482  {
6483    sync_nfss_code(
6484      T_CS!("\\f@series"),
6485      series,
6486      |code| font::lookup_font_series(code).and_then(|f| f.series.as_deref()),
6487      font::nfss_series_code,
6488    );
6489  }
6490  if touched(
6491    merged.shape.is_some() || merged.emph == Some(true),
6492    current.shape.as_deref(),
6493    new_font.shape.as_deref(),
6494  ) && let Some(shape) = new_font.shape.as_deref()
6495  {
6496    sync_nfss_code(
6497      T_CS!("\\f@shape"),
6498      shape,
6499      |code| font::lookup_font_shape(code).and_then(|f| f.shape.as_deref()),
6500      font::nfss_shape_code,
6501    );
6502  }
6503  let size_touched =
6504    merged.size.is_some() || merged.scale.is_some() || current.size != new_font.size;
6505  if size_touched && let Some(points) = new_font.size {
6506    sync_nfss_size(points);
6507  }
6508}
6509
6510/// Write `points` into `\f@size` unless it already holds that size.
6511fn sync_nfss_size(points: f64) {
6512  if points > 0.0
6513    && let Some(in_force) = nfss_code_text(T_CS!("\\f@size"))
6514    && !in_force
6515      .trim()
6516      .parse::<f64>()
6517      .is_ok_and(|p| (p - points).abs() < 0.005)
6518  {
6519    define_nfss_code(T_CS!("\\f@size"), &font::format_points(points));
6520  }
6521}
6522
6523/// Write `value`'s NFSS code into `cs` unless the code there already denotes
6524/// `value` (`denotes`) or `value` has none (`code_of`).
6525fn sync_nfss_code(
6526  cs: Token,
6527  value: &str,
6528  denotes: impl Fn(&str) -> Option<&'static str>,
6529  code_of: fn(&str) -> Option<&'static str>,
6530) {
6531  // A value with no code leaves the macro alone; plain TeX has no NFSS state.
6532  let Some(code) = code_of(value) else {
6533    return;
6534  };
6535  let Some(in_force) = nfss_code_text(cs) else {
6536    return;
6537  };
6538  if denotes(&in_force) != Some(value) {
6539    define_nfss_code(cs, code);
6540  }
6541}
6542
6543/// `\edef`-like local definition of an NFSS state macro to `code`.
6544fn define_nfss_code(cs: Token, code: &str) {
6545  let body = ExpansionBody::Tokens(crate::mouth::tokenize_internal(TeXString::assembled(
6546    code.to_string(),
6547  )));
6548  let options = ExpandableOptions {
6549    scope: Some(Scope::Local),
6550    ..ExpandableOptions::default()
6551  };
6552  // Only an unbalanced body can fail to define; a code is characters.
6553  let _ = def_macro(cs, None, Some(body), Some(options));
6554}
6555
6556/// The text an NFSS state macro (`\f@family`, …) holds, `None` while it is
6557/// undefined (plain TeX). An `\edef` leaves a parameterless list of
6558/// characters, read directly; anything else is expanded, as `\selectfont`
6559/// reads it.
6560pub fn nfss_code_text(cs: Token) -> Option<String> {
6561  let direct = with_meaning(&cs, |meaning| match meaning {
6562    None => Some(None),
6563    Some(Stored::Expandable(e)) if e.paramlist.is_none() => match &e.expansion {
6564      None => Some(Some(String::new())),
6565      Some(ExpansionBody::Tokens(body))
6566        if body
6567          .unlist_ref()
6568          .iter()
6569          .all(|t| matches!(t.get_catcode(), Catcode::LETTER | Catcode::OTHER)) =>
6570      {
6571        Some(Some(body.to_string()))
6572      },
6573      _ => None,
6574    },
6575    _ => None,
6576  });
6577  match direct {
6578    Some(text) => text,
6579    None => Some(do_expand(Tokens::from(cs)).map_or_else(|_| String::new(), |t| t.to_string())),
6580  }
6581}
6582
6583/// Define a named color (Perl: DefColor).
6584/// Stores as color_{name} and also defines \\color@{name} macro.
6585pub fn def_color(
6586  name: &str,
6587  color: &crate::common::color::Color,
6588  scope: Option<Scope>,
6589) -> Result<()> {
6590  use crate::common::color;
6591  // Check ifglobalcolors — Perl: $scope='global' if lookupDefinition(\ifglobalcolors) &&
6592  // IfCondition(\ifglobalcolors) Guard with lookup first: xcolor may not be loaded (e.g.
6593  // colordvi-only documents).
6594  //
6595  // ALSO force global when `color_force_global` is set: color_sty.rs's lazy
6596  // dvipsnam.def loader (recovering a dropped `\usepackage[dvipsnames]{color}`
6597  // option, e.g. when hyperref preloaded `color` first) fires from WITHIN a
6598  // grouped digestion (`\textcolor{Blue}{…}` / a listings keywordstyle), so the
6599  // 68 dvips colors would otherwise be defined in that local group and revert
6600  // before the next `\color{…}` — making only the FIRST color resolve. Perl
6601  // loads dvipsnam at the preamble (top level), so its colors persist; the flag
6602  // reproduces that global effect. Witness 1705.06183.
6603  let effective_scope = if (lookup_definition(&T_CS!("\\ifglobalcolors"))?.is_some()
6604    && if_condition(&T_CS!("\\ifglobalcolors"))? == Some(true))
6605    || lookup_bool("color_force_global")
6606  {
6607    Some(Scope::Global)
6608  } else {
6609    scope
6610  };
6611  // Store in state as "model c1 c2 ..."
6612  let stored = color.to_stored();
6613  // The lookup side (`color_sty::color_key`) trims; store under the same key.
6614  let name = name.trim();
6615  assign_value(
6616    &s!("color_{name}"),
6617    Stored::String(arena::pin(stored)),
6618    effective_scope,
6619  );
6620  // Define \\color@{name} macro for reversion
6621  // Perl: DefMacroI('\\color@'.$name, undef,
6622  //   '\relax\relax{model spec}{model}{spec_commas}')
6623  let model = color.model();
6624  let comps = color.components();
6625  let spec_parts: Vec<String> = comps.iter().map(|c| color::format_component(*c)).collect();
6626  let spec_space = spec_parts.join(" ");
6627  let spec_comma = spec_parts.join(",");
6628  let drv_spec = match model {
6629    "cmyk" => s!("{spec_space} k {spec_space} K"),
6630    "rgb" => s!("{spec_space} rg {spec_space} RG"),
6631    "gray" => s!("{spec_space} g {spec_space} G"),
6632    _ => s!("{model} {spec_space}"),
6633  };
6634  let model_spec = if lookup_definition(&T_CS!("\\xcolor@"))?.is_some() {
6635    s!("\\xcolor@{{}}{{{drv_spec}}}{{{model}}}{{{spec_comma}}}")
6636  } else {
6637    s!("\\relax\\relax{{{model} {spec_space}}}{{{model}}}{{{spec_comma}}}")
6638  };
6639  def_macro(
6640    T_CS!(s!("\\\\color@{name}")),
6641    None,
6642    crate::mouth::tokenize_internal(TeXString::assembled(model_spec)),
6643    Some(ExpandableOptions {
6644      scope: effective_scope,
6645      ..Default::default()
6646    }),
6647  )?;
6648  Ok(())
6649}
6650
6651/// Define a derived color model (Perl: DefColorModel).
6652/// Stores conversion functions for a derived color model.
6653pub fn def_color_model(model: &str, coremodel: &str) {
6654  assign_value(
6655    &s!("derived_color_model_{model}"),
6656    Stored::String(arena::pin(coremodel)),
6657    Some(Scope::Global),
6658  );
6659}
6660
6661/// Perl `Digest` (Package.pm:393-402): digest with side effects and mode changes, then leave a horizontal mode the
6662/// digestion entered (`leaveHorizontal_internal`), as [`crate::parameter::Parameter::digest`] does for an argument.
6663pub fn binding_digest<T: Into<Tokens>>(tokens: T) -> Result<Digested> {
6664  let mode = lookup_mode();
6665  let value = digest(tokens)?;
6666  let nmode = lookup_mode();
6667  if mode != nmode && nmode == crate::pin!("horizontal") {
6668    leave_horizontal_internal();
6669  }
6670  Ok(value)
6671}
6672
6673/// Digest tokens in text mode, whatever mode the caller is in.
6674///
6675/// Port of Perl `Package.pm:DigestText` L405-411: brackets the digestion in
6676/// `beginMode`/`endMode` so that material which must come out as text — a
6677/// title, a caption, an alt string — does so even when it is being read from
6678/// inside math. Compare [`digest_literal`], which additionally forces an ASCII
6679/// encoding and leaves the mode's other side-effects out.
6680pub fn digest_text(stuff: Tokens) -> Result<Digested> {
6681  begin_mode("text")?;
6682  let value = digest(stuff);
6683  end_mode("text")?;
6684  value
6685}
6686
6687pub fn digest_literal<T: Into<Tokens>>(stuff: T) -> Result<Digested> {
6688  let stuff: Tokens = stuff.into();
6689  // Perhaps should do StartSemiverbatim, but is it safe to push a frame? (we might cover over
6690  // valid changes of state!)
6691  begin_mode("text")?;
6692
6693  // Fall back to the global text default if no font is currently assigned —
6694  // avoids a panic at this hot path (called from e.g. RefStepID / label
6695  // digestion) when the state's "font" slot hasn't been initialised. Matches
6696  // the same fallback `assign_value("font", Font::text_default(), …)` that
6697  // stomach::init uses at startup.
6698  let font = lookup_font().unwrap_or_else(|| Rc::new(Font::text_default()));
6699  assign_font(
6700    Rc::new(font.merge(fontmap!(encoding => "ASCII"))),
6701    Some(Scope::Local),
6702  ); // try to stay as ASCII as possible
6703
6704  let value = digest(stuff);
6705  assign_font(font, None);
6706  end_mode("text")?;
6707  value
6708}
6709
6710pub fn digest_if(token: Token) -> Result<Option<Digested>> {
6711  if lookup_definition(&token)?.is_some() {
6712    match digest(Tokens!(token)) {
6713      Ok(t) => Ok(Some(t)),
6714      Err(e) => Err(e),
6715    }
6716  } else {
6717    Ok(None)
6718  }
6719}
6720
6721/// A name macro a heading is set from (`\contentsname`, `\refname`, `\indexname`, `\acknowledgmentsname`, …)
6722/// digested in a group of its own, `{\name}`, as a class's `\section*{\name}` sets it: a font switch it makes
6723/// unbraced stays in the heading (RecipeBook.cls:207-209 `\renewcommand{\contentsname}{\hypertarget{contents}{\bfseries
6724/// \fontsize{…}{…}\selectfont Recipes}}` leaked into every later heading and paragraph; recipebook/LongSample), and a
6725/// `\centering` in it, applied at the group's end, still centres the heading (tidyres-doc.tex:9). Perl digests the
6726/// list names as text (`DigestText`, latex_constructs.pool.ltxml:734; Package.pm:405-411, a restricted-horizontal
6727/// mode frame that scopes the font but drops the `\centering`; the port's bare digest leaked, Rust-only) and
6728/// `\refname`/`\bibname`/`\indexname` bare (`DigestIf`, :3885, :4523), which leaks the font in Perl too.
6729/// OXIDIZED_DESIGN #528, KNOWN_PERL_ERRORS #606.
6730pub fn digest_in_group(token: Token) -> Result<Digested> {
6731  digest(Tokens::new(vec![T_BEGIN!(), token, T_END!()]))
6732}
6733
6734/// [`digest_in_group`] for a name that may be undefined (Perl's `DigestIf`).
6735pub fn digest_in_group_if(token: Token) -> Result<Option<Digested>> {
6736  if lookup_definition(&token)?.is_some() {
6737    digest_in_group(token).map(Some)
6738  } else {
6739    Ok(None)
6740  }
6741}
6742
6743/// Test a conditional `\ifXXX` and return its boolean result (Perl: IfCondition).
6744pub fn if_condition(if_token: &Token) -> Result<Option<bool>> {
6745  if_condition_args(if_token, Vec::new())
6746}
6747
6748/// Perl's `IfCondition($if, @args)` (Package.pm:1238): the test runs on the caller's arguments, never reading the
6749/// input; an argument not given is Perl's undef.
6750pub fn if_condition_args(if_token: &Token, args: Vec<ArgWrap>) -> Result<Option<bool>> {
6751  use crate::definition::conditional::ConditionalType;
6752  if let Some(defn) = lookup_definition(if_token)?
6753    && defn.get_conditional_type() == Some(ConditionalType::If)
6754    && let Some(test) = defn.get_test()
6755  {
6756    return Ok(Some(test(args)?));
6757  }
6758  if x_equals(if_token, &T_CS!("\\iftrue")) {
6759    return Ok(Some(true));
6760  }
6761  if x_equals(if_token, &T_CS!("\\iffalse")) {
6762    return Ok(Some(false));
6763  }
6764  Error!(
6765    "expected",
6766    "conditional",
6767    s!("Expected a conditional, got '{}'", if_token) // Perl's ToString($if), Package.pm:1251
6768  );
6769  Ok(None)
6770}
6771
6772/// Set the boolean value of a `\newif`-type conditional (Perl: SetCondition, Package.pm:1256).
6773/// This is only for simple conditionals taking no arguments.
6774pub fn set_condition(if_token: &Token, value: bool, scope: Option<Scope>) {
6775  use crate::definition::conditional::ConditionalType;
6776  if let Ok(Some(defn)) = lookup_definition(if_token)
6777    && defn.get_conditional_type() == Some(ConditionalType::If)
6778    && defn.get_parameters().is_none()
6779  {
6780    let target = if value {
6781      T_CS!("\\iftrue")
6782    } else {
6783      T_CS!("\\iffalse")
6784    };
6785    let_i(if_token, &target, scope);
6786    return;
6787  }
6788  emit_error(
6789    "expected",
6790    "conditional",
6791    &format!("Expected a conditional defined by \\newif, got '{if_token}'"),
6792  );
6793}
6794
6795/// Creates a single `Tokens` representing a TeX invocation of the lead `token` over a list of
6796/// arguments.
6797///
6798/// Note: currently this is near the `Mouth` representation of data, and deals purely with tokens.
6799/// A more generic version of this method may be able to support `ArgWrap` for the argument list.
6800/// Indeed, the return type may also be lifted to a new generic ArgWrap::Invocation, if there was
6801/// benefit.
6802pub fn build_invocation<T: Into<Token>>(token: T, args: Vec<Option<Tokens>>) -> Result<Tokens> {
6803  let token: Token = token.into();
6804  build_invocation_token(token, args)
6805}
6806
6807/// String entry point for `Invocation` (Perl: `Invocation($token,@args)` with a string
6808/// first argument). The string is tokenized via `TokenizeInternal`; if it yields a single
6809/// token, this reduces to `build_invocation` on that token. Otherwise the tokens are
6810/// treated as an "anonymous macro" containing parameter markers like `#1`, and the
6811/// arguments are substituted in.
6812pub fn build_invocation_str(
6813  spec: impl Into<TeXString>,
6814  args: Vec<Option<Tokens>>,
6815) -> Result<Tokens> {
6816  let spec = spec.into();
6817  let tokens = crate::mouth::tokenize_internal(spec.clone());
6818  let mut list = tokens.unlist();
6819  if list.len() > 1 {
6820    // Treat as anonymous macro
6821    let cow_args: Vec<Option<Cow<Tokens>>> = args.into_iter().map(|a| a.map(Cow::Owned)).collect();
6822    return Ok(
6823      Tokens::new(list)
6824        .pack_parameters()?
6825        .substitute_parameters(&cow_args),
6826    );
6827  }
6828  match list.pop() {
6829    Some(cs) => build_invocation_token(cs, args), // reduce to single token.
6830    None => {
6831      Error!(
6832        "unexpected",
6833        "invocation",
6834        s!("Can't invoke empty token spec '{}'", spec)
6835      );
6836      Ok(Tokens::default())
6837    },
6838  }
6839}
6840
6841fn build_invocation_token(token: Token, args: Vec<Option<Tokens>>) -> Result<Tokens> {
6842  // Note: token may have been \let to another defn!
6843  match lookup_definition(&token)? {
6844    Some(defn) => {
6845      let mut invoked_tokens = vec![token];
6846      if let Some(params) = defn.get_parameters() {
6847        invoked_tokens.extend(params.revert_arguments(args)?);
6848      }
6849      Ok(Tokens::new(invoked_tokens))
6850    },
6851    _ => {
6852      let message = s!("Can't invoke {:?}; it is undefined", token.stringify());
6853      token.with_cs_name(|csname| {
6854        Error!("undefined", csname, message);
6855        Ok(())
6856      })?;
6857      let mut invoked_tokens = vec![token];
6858      // DefConstructor!(token, convert_latex_args(args.len(), 0),
6859      // sub { LaTeXML::Core::Stomach::makeError($_[0], 'undefined', token); });
6860      let wrapped_args: Vec<Token> = args
6861        .into_iter()
6862        .flat_map(|arg_opt| {
6863          let mut wrapped = vec![T_BEGIN!()];
6864          if let Some(arg) = arg_opt {
6865            wrapped.extend(arg.unlist());
6866          }
6867          wrapped.push(T_END!());
6868          wrapped
6869        })
6870        .collect();
6871      invoked_tokens.extend(wrapped_args);
6872      Ok(Tokens::new(invoked_tokens))
6873    },
6874  }
6875}
6876
6877/// latex.ltx:18840 `\@onefilewithoptions`: `\global\let\ver@<file>\@empty` before the read, so the file and what it loads
6878/// hear `\@ifpackageloaded` true while it loads (1411.7188's l3names.sty asks for expl3; Perl marks `<file>_loaded`
6879/// before the read, Package.pm:2328, :2363). Returns the mark and what it replaced, unless `filename` is loaded already.
6880fn mark_loading(filename: &str) -> Option<(Stored, Option<Stored>)> {
6881  if file_loaded(filename) {
6882    return None;
6883  }
6884  let ver_cs = T_CS!(s!("\\ver@{filename}"));
6885  let was = lookup_meaning(&ver_cs);
6886  let_i(&ver_cs, &T_CS!("\\@empty"), Some(Scope::Global));
6887  lookup_meaning(&ver_cs).map(|mark| (mark, was))
6888}
6889
6890/// Is `\ver@<filename>` still the very `\@empty` [`mark_loading`] set (the read declared no version)?
6891fn still_loading_mark(filename: &str, mark: &Option<(Stored, Option<Stored>)>) -> bool {
6892  match (mark, lookup_meaning(&T_CS!(s!("\\ver@{filename}")))) {
6893    (Some((Stored::Expandable(mark), _)), Some(Stored::Expandable(ver))) => Rc::ptr_eq(mark, &ver),
6894    _ => false,
6895  }
6896}
6897
6898/// Mark `filename` loaded as its load does (Perl Package.pm:2326 `\fmtversion`): `\ver@<filename>` is the version its
6899/// installed file declares ([`provides_version_of`]), so a date test reads the package's date, else `\fmtversion`.
6900fn mark_version(filename: &str) -> Result<()> {
6901  let ver_cs = T_CS!(s!("\\ver@{filename}"));
6902  match provides_version_of(filename) {
6903    Some(version) => def_macro(
6904      ver_cs,
6905      None,
6906      crate::mouth::tokenize(TeXString::assembled(version)),
6907      Some(ExpandableOptions {
6908        scope: Some(Scope::Global),
6909        ..ExpandableOptions::default()
6910      }),
6911    ),
6912    None => {
6913      let_i(&ver_cs, &T_CS!("\\fmtversion"), Some(Scope::Global));
6914      Ok(())
6915    },
6916  }
6917}
6918
6919/// The `[<date> <version> <info>]` a package or class declares with
6920/// `\ProvidesPackage{name}[…]` / `\ProvidesClass{name}[…]` (ltclass:
6921/// `\ver@name.ext` is that text), or the `date v<version> <info>` that
6922/// `\ProvidesExplPackage{name}{date}{version}{info}` makes of its groups
6923/// (expl3.sty:35-48), read from the installed file so a binding exposes the
6924/// same string as the raw file would. latex.ltx `\xdef`s the text, so the
6925/// kernel's `\space` and `\ ` read as spaces; `None` when no file is on disk,
6926/// it declares nothing, or the text holds any other control sequence — the
6927/// file's own macros (listings.sty:19-23 `\filedate\space\fileversion`, set by
6928/// a prologue a binding never runs), whose expansion a static read cannot know.
6929pub fn provides_version_of(filename: &str) -> Option<String> {
6930  let path = find_file(filename, None)?;
6931  let text = std::fs::read(&path).ok()?;
6932  provided_text(&String::from_utf8_lossy(&text), filename)
6933    .and_then(|declared| expand_declared(&declared))
6934}
6935
6936/// The text the file declares with `\Provides…{name}`, its source lines joined
6937/// with `%` comments dropped, as TeX reads them.
6938fn provided_text(text: &str, filename: &str) -> Option<String> {
6939  let name = filename.rsplit_once('.').map_or(filename, |(n, _)| n);
6940  let mut rest: &str = text;
6941  while let Some(idx) = rest.find("\\Provides") {
6942    rest = &rest[idx + 9..];
6943    let Some(kw) = ["ExplPackage", "ExplClass", "Package", "Class", "File"]
6944      .into_iter()
6945      .find(|k| rest.starts_with(k))
6946    else {
6947      continue;
6948    };
6949    let Some((arg, tail)) = leading_brace_group(&rest[kw.len()..]) else {
6950      continue;
6951    };
6952    if arg.trim() != name {
6953      continue;
6954    }
6955    // expl3.sty:35-48 `\ProvidesExpl…{name}{date}{version}{description}` stores
6956    // `date v<version> description` (the `v` kept once, left out with no version).
6957    if kw.starts_with("Expl") {
6958      let mut groups = Vec::with_capacity(3);
6959      let mut rest_groups = tail;
6960      for _ in 0..3 {
6961        let Some((group, after)) = leading_brace_group(rest_groups) else {
6962          break;
6963        };
6964        groups.push(group.split_whitespace().collect::<Vec<_>>().join(" "));
6965        rest_groups = after;
6966      }
6967      if groups.len() < 3 {
6968        continue;
6969      }
6970      let (date, version, description) = (&groups[0], &groups[1], &groups[2]);
6971      let version = if version.is_empty() {
6972        String::new()
6973      } else if version.starts_with('v') {
6974        s!("{version} ")
6975      } else {
6976        s!("v{version} ")
6977      };
6978      return Some(s!("{date} {version}{description}"));
6979    }
6980    // A `%` comment may stand between the name and the bracket (multirow.sty:25-27, fourier.sty:5-6).
6981    let Some(bracket) = skip_space_and_comments(tail).strip_prefix('[') else {
6982      continue;
6983    };
6984    let Some(end) = bracket.find(']') else {
6985      continue;
6986    };
6987    return Some(
6988      bracket[..end]
6989        .lines()
6990        .map(|l| l.split('%').next().unwrap_or("").trim())
6991        .filter(|l| !l.is_empty())
6992        .collect::<Vec<_>>()
6993        .join(" "),
6994    );
6995  }
6996  None
6997}
6998
6999/// `declared` as `\xdef` leaves it when its only control sequences are the
7000/// kernel's `\space` and `\ ` (a space after a control word is skipped);
7001/// `None` for an empty text or any other control sequence.
7002fn expand_declared(declared: &str) -> Option<String> {
7003  let mut out = String::with_capacity(declared.len());
7004  let mut chars = declared.chars().peekable();
7005  while let Some(c) = chars.next() {
7006    if c != '\\' {
7007      out.push(c);
7008      continue;
7009    }
7010    let mut word = String::new();
7011    while let Some(&l) = chars.peek()
7012      && l.is_ascii_alphabetic()
7013    {
7014      word.push(l);
7015      chars.next();
7016    }
7017    match word.as_str() {
7018      // tex.web §354: the spaces after a control space are skipped too.
7019      "" if chars.next() == Some(' ') => {
7020        while chars.next_if_eq(&' ').is_some() {}
7021        out.push(' ');
7022      },
7023      "space" => {
7024        while chars.next_if_eq(&' ').is_some() {}
7025        out.push(' ');
7026      },
7027      _ => return None,
7028    }
7029  }
7030  let out = out.trim();
7031  (!out.is_empty()).then(|| out.to_string())
7032}
7033
7034/// `text` past leading whitespace and whole `%` comment lines.
7035fn skip_space_and_comments(text: &str) -> &str {
7036  let mut text = text.trim_start();
7037  while let Some(comment) = text.strip_prefix('%') {
7038    text = comment
7039      .split_once('\n')
7040      .map_or("", |(_, next)| next)
7041      .trim_start();
7042  }
7043  text
7044}
7045
7046/// The leading `{…}` group of `text` (after optional whitespace and `%`
7047/// comments; nested braces balanced) and the text after it.
7048fn leading_brace_group(text: &str) -> Option<(&str, &str)> {
7049  // Whitespace and `%` comments may separate the groups (fontspec.sty:
7050  // `\ProvidesExplPackage{fontspec}%` then the date group on the next line).
7051  let body = skip_space_and_comments(text).strip_prefix('{')?;
7052  let mut depth = 0usize;
7053  for (i, c) in body.char_indices() {
7054    match c {
7055      '{' => depth += 1,
7056      '}' if depth == 0 => return Some((&body[..i], &body[i + 1..])),
7057      '}' => depth -= 1,
7058      _ => {},
7059    }
7060  }
7061  None
7062}
7063
7064/// One `\def`-body reading of a token list's parameter characters: `##`
7065/// (two PARAM tokens) becomes one PARAM token; a lone PARAM before a digit is
7066/// TeX's "Illegal parameter number" (kept as is here, no error).
7067fn halve_param_tokens(tks: &Tokens) -> Tokens {
7068  let toks = tks.clone().unlist();
7069  let mut out: Vec<Token> = Vec::with_capacity(toks.len());
7070  let mut i = 0;
7071  while i < toks.len() {
7072    let t = toks[i];
7073    if t.code == Catcode::PARAM && i + 1 < toks.len() && toks[i + 1].code == Catcode::PARAM {
7074      out.push(t);
7075      i += 2;
7076      continue;
7077    }
7078    out.push(t);
7079    i += 1;
7080  }
7081  Tokens::new(out)
7082}
7083
7084/// LaTeX's argument count `[n]`, 0 to 9: latex.ltx:1276-1283 `\@yargd@f` writes `#1`…`#9` and then the count, so a
7085/// count outside is tex.web §476's "You already have nine parameters". An Error, then the count clamped into range.
7086pub fn latex_arg_count(nargs: i64) -> Result<usize> {
7087  let count = nargs.clamp(0, 9);
7088  if count != nargs {
7089    Error!(
7090      "misdefined",
7091      s!("[{nargs}]"),
7092      "You already have nine parameters",
7093      s!("a LaTeX command takes 0 to 9 arguments; [{nargs}] is read as [{count}]")
7094    );
7095  }
7096  Ok(count as usize)
7097}
7098
7099/// Convert a LaTeX-style argument spec to our Package form.
7100/// Ie. given $nargs and $optional, being the two optional arguments to
7101/// something like \newcommand, convert it to the form we use
7102pub fn convert_latex_args(nargs: i64, optional: Option<Tokens>) -> Result<Option<Parameters>> {
7103  let mut nargs = latex_arg_count(nargs)?;
7104  let mut params = Vec::new();
7105  if let Some(tks) = optional {
7106    // The kernel stores an optional default through TWO `\def` bodies —
7107    // `\@xargdef`'s `\def\foo{\@protected@testopt\foo\\foo{<default>}}`
7108    // (latex.ltx:1249, `\@xargdef` 1245-1258) and `\kernel@ifnextchar`'s `\def\reserved@b{#3}`
7109    // (:14131) — each of which reads `##` as one parameter character, so
7110    // `\newcommand{\x}[4][########1]` hands `\\x` a default of `##1`
7111    // (pdflatex-probed `\detokenize{#1}` = `####1`). etoolbox's
7112    // `\patchcmd` idiom relies on exactly that (biditools.sty:769
7113    // `\newcommand{\bidi@@patchcmd}[4][########1]` — the raw `#`s reached
7114    // the stomach and every biditools-loading manual errored `misdefined:#`,
7115    // 7 docs). Perl's convertLaTeXArgs stores the default raw (KNOWN_PERL_ERRORS
7116    // #134). Guard: `perfect_kernel_batch54::newcommand_default_halves_param_tokens_twice`.
7117    let tks = halve_param_tokens(&halve_param_tokens(&tks));
7118    params.push(
7119      Parameter {
7120        name: pin!("Optional"),
7121        spec: arena::pin(s!("[Default:{}]", tks.clone().untex())),
7122        extra: vec![tks],
7123        // `\@protected@testopt`'s peek: a number scan ends at the macro
7124        // (tex.web §445; `\cc=1\foo` assigns 1, pdflatex).
7125        testopt: true,
7126        ..Parameter::default()
7127      }
7128      .init()?,
7129    );
7130    // Perl `convertLaTeXArgs` does `$nargs-- if $optional`; with `$nargs==0`
7131    // that just yields an empty `1..$nargs` range. Saturate so the malformed
7132    // `\newcommand\foo[0][d]{}` (0 args yet an optional default — outside
7133    // LaTeX's 0..9 domain) can't underflow `usize` to ~2^64 and spin the loop
7134    // below. Mirrors the sibling `convert_twoopt_args`.
7135    nargs = nargs.saturating_sub(1);
7136  }
7137
7138  for _ in 1..=nargs {
7139    params.push(
7140      Parameter {
7141        name: pin!("Plain"),
7142        spec: pin!("{}"),
7143        ..Parameter::default()
7144      }
7145      .init()?,
7146    );
7147  }
7148  if params.is_empty() {
7149    Ok(None)
7150  } else {
7151    Ok(Some(Parameters::new(params)))
7152  }
7153}
7154
7155/// Two-optional variant of `convert_latex_args` — mirrors Perl's
7156/// `convert2optArgs` helper in twoopt.sty.ltxml. `\newcommandtwoopt{\cs}[n][d1][d2]{…}`
7157/// builds a signature of `[Default d1][Default d2]{…}…` where the remaining
7158/// `n - 2` args are plain required.
7159pub fn convert_twoopt_args(
7160  nargs: i64,
7161  opt1: Option<Tokens>,
7162  opt2: Option<Tokens>,
7163) -> Result<Option<Parameters>> {
7164  let mut nargs = latex_arg_count(nargs)?;
7165  let mut params = Vec::new();
7166  if let Some(tks) = opt1 {
7167    params.push(
7168      Parameter {
7169        name: pin!("Optional"),
7170        spec: arena::pin(s!("[Default:{}]", tks.clone().untex())),
7171        extra: vec![tks],
7172        // twoopt.sty:49-53 defines the command with `\newcommand#2#3[1][{#5}]`.
7173        testopt: true,
7174        ..Parameter::default()
7175      }
7176      .init()?,
7177    );
7178    nargs = nargs.saturating_sub(1);
7179  }
7180  if let Some(tks) = opt2 {
7181    params.push(
7182      Parameter {
7183        name: pin!("Optional"),
7184        spec: arena::pin(s!("[Default:{}]", tks.clone().untex())),
7185        extra: vec![tks],
7186        ..Parameter::default()
7187      }
7188      .init()?,
7189    );
7190    nargs = nargs.saturating_sub(1);
7191  }
7192  for _ in 1..=nargs {
7193    params.push(
7194      Parameter {
7195        name: pin!("Plain"),
7196        spec: pin!("{}"),
7197        ..Parameter::default()
7198      }
7199      .init()?,
7200    );
7201  }
7202  if params.is_empty() {
7203    Ok(None)
7204  } else {
7205    Ok(Some(Parameters::new(params)))
7206  }
7207}
7208
7209/// Decode a codepoint using the fontmap for a given font and/or encoding (Perl: FontDecode).
7210/// Returns the decoded glyph (if any) and the possibly-adjusted font.
7211pub fn font_decode(
7212  code: i32,
7213  encoding_opt: Option<&str>,
7214  font_opt: Option<Rc<Font>>,
7215) -> (Option<char>, Option<Rc<Font>>) {
7216  if code < 0 {
7217    return (None, font_opt);
7218  }
7219  let font = font_opt.unwrap_or_else(|| lookup_font().unwrap());
7220  let encoding = match encoding_opt {
7221    Some(enc) => enc.to_string(),
7222    None => font
7223      .get_encoding()
7224      .map_or_else(|| "OT1".to_string(), |c| c.to_string()),
7225  };
7226  let map = load_font_map(&encoding);
7227  // Check for family-specific map. Use with_value to avoid cloning the
7228  // Stored envelope when the From<&Stored>→Option<Fontmap> impl only
7229  // needs the enum variant discriminant + an Rc bump.
7230  let (effective_map, _effective_enc) = if let Some(family) = font.get_family() {
7231    let fam_key = s!("{}_{}_fontmap", encoding, family);
7232    let fam_map: Option<Fontmap> = with_value(&fam_key, |v| v.and_then(|s| s.into()));
7233    if let Some(fm) = fam_map {
7234      (Some(fm), s!("{}_{}", encoding, family))
7235    } else {
7236      (map, encoding)
7237    }
7238  } else {
7239    (map, encoding)
7240  };
7241  let glyph = effective_map
7242    .as_ref()
7243    .and_then(|m| m.get(code as usize).copied().flatten());
7244  // In-math alphanumeric mathstyle handling is done in decodeMathChar instead
7245  (glyph, Some(font))
7246}
7247
7248/// Decode a string using the fontmap for a given encoding (Perl: FontDecodeString).
7249/// If `implicit` is true, codepoints missing from the map decode to themselves.
7250pub fn font_decode_string(string: &str, encoding_opt: Option<&str>, implicit: bool) -> String {
7251  let font = lookup_font().unwrap();
7252  let encoding = match encoding_opt {
7253    Some(enc) => enc.to_string(),
7254    None => font
7255      .get_encoding()
7256      .map_or_else(|| "OT1".to_string(), |c| c.to_string()),
7257  };
7258  let map = load_font_map(&encoding);
7259  // Check for family-specific map — same with_value motivation as above.
7260  let effective_map = if let Some(family) = font.get_family() {
7261    let fam_key = s!("{}_{}_fontmap", encoding, family);
7262    let fam_map: Option<Fontmap> = with_value(&fam_key, |v| v.and_then(|s| s.into()));
7263    fam_map.or(map)
7264  } else {
7265    map
7266  };
7267  let input_enc = lookup_string("INPUT_ENCODING");
7268  let map_max: usize = if input_enc == "utf8" { 128 } else { 256 };
7269  // Also limit for short font maps
7270  let map_max = if let Some(ref m) = effective_map {
7271    if m.len() < map_max { m.len() } else { map_max }
7272  } else {
7273    map_max
7274  };
7275
7276  let mut result = String::new();
7277  for ch in string.chars() {
7278    let code = ch as usize;
7279    if implicit {
7280      if let Some(ref m) = effective_map {
7281        if code < map_max {
7282          if let Some(Some(glyph)) = m.get(code) {
7283            result.push(*glyph);
7284          }
7285        } else {
7286          result.push(ch);
7287        }
7288      } else {
7289        result.push(ch);
7290      }
7291    } else if let Some(ref m) = effective_map
7292      && let Some(Some(glyph)) = m.get(code)
7293    {
7294      result.push(*glyph);
7295    }
7296  }
7297  result
7298}
7299
7300// Memoized key symbols for the per-encoding fontmap Value-table entries.
7301// `decode_string` runs per digested character run and used to rebuild (format!
7302// + arena probe) the `"{encoding}_fontmap"`-family keys on every call — ~1M
7303// allocations on a 1.3 s paper (2026-08-23 audit R6, dhat). Encodings are few
7304// (OT1/T1/OML/…), so the (encoding → key syms) maps stay tiny. Value lookups
7305// still go through the state tables — only the key STRINGS are memoized.
7306// Keyed by arena SymStr, so MUST be cleared with `arena::reset()`
7307// (`reset_fontmap_key_memo`, called from `reset_thread_engine`).
7308thread_local! {
7309  static FONTMAP_KEY_MEMO: std::cell::RefCell<HashMap<String, FontmapKeySyms>> =
7310    std::cell::RefCell::new(HashMap::default());
7311  static FONTMAP_FAMILY_KEY_MEMO: std::cell::RefCell<HashMap<(String, String), (SymStr, SymStr)>> =
7312    std::cell::RefCell::new(HashMap::default());
7313  /// The last answers of the two memos: text decodes glyph after glyph in one font, a few probes per glyph
7314  /// (2103.04797, 1704.02085), and a string compare is cheaper than a hash probe (the family one built two keys).
7315  static FONTMAP_KEY_LAST: std::cell::RefCell<Option<(String, FontmapKeySyms)>> =
7316    const { std::cell::RefCell::new(None) };
7317  static FONTMAP_FAMILY_KEY_LAST: std::cell::RefCell<Option<(String, String, FamilyKeySyms)>> =
7318    const { std::cell::RefCell::new(None) };
7319}
7320
7321/// `fontmap_family_key_syms`' answer: the family map's key and its multichar table's.
7322type FamilyKeySyms = (SymStr, SymStr);
7323
7324#[derive(Clone, Copy)]
7325pub struct FontmapKeySyms {
7326  /// `"{encoding}_fontmap"`
7327  pub map:       SymStr,
7328  /// `"{encoding}_fontmap_failed_to_load"`
7329  pub fail:      SymStr,
7330  /// `"{encoding}_fontmap_multichar"`
7331  pub multichar: SymStr,
7332}
7333
7334/// The memoized key symbols for `encoding`'s fontmap Value-table entries.
7335pub fn fontmap_key_syms(encoding: &str) -> FontmapKeySyms {
7336  if let Some(keys) = FONTMAP_KEY_LAST.with_borrow(|last| {
7337    last
7338      .as_ref()
7339      .filter(|(e, _)| e == encoding)
7340      .map(|(_, keys)| *keys)
7341  }) {
7342    return keys;
7343  }
7344  let keys = FONTMAP_KEY_MEMO.with(|m| {
7345    if let Some(keys) = m.borrow().get(encoding) {
7346      return *keys;
7347    }
7348    let keys = FontmapKeySyms {
7349      map:       arena::pin(s!("{encoding}_fontmap")),
7350      fail:      arena::pin(s!("{encoding}_fontmap_failed_to_load")),
7351      multichar: arena::pin(s!("{encoding}_fontmap_multichar")),
7352    };
7353    m.borrow_mut().insert(encoding.to_string(), keys);
7354    keys
7355  });
7356  FONTMAP_KEY_LAST.with_borrow_mut(|last| match last {
7357    // Reuse the buffer: text and math glyphs alternate encodings (OT1, OML).
7358    Some((e, k)) => {
7359      e.clear();
7360      e.push_str(encoding);
7361      *k = keys;
7362    },
7363    None => *last = Some((encoding.to_string(), keys)),
7364  });
7365  keys
7366}
7367
7368/// The memoized `"{encoding}_{family}_fontmap"` and `"{encoding}_{family}_fontmap_multichar"` key symbols.
7369pub fn fontmap_family_key_syms(encoding: &str, family: &str) -> (SymStr, SymStr) {
7370  if let Some(syms) = FONTMAP_FAMILY_KEY_LAST.with_borrow(|last| {
7371    last
7372      .as_ref()
7373      .filter(|(e, f, _)| e == encoding && f == family)
7374      .map(|(_, _, syms)| *syms)
7375  }) {
7376    return syms;
7377  }
7378  let syms = FONTMAP_FAMILY_KEY_MEMO.with(|m| {
7379    if let Some(syms) = m.borrow().get(&(encoding.to_string(), family.to_string())) {
7380      return *syms;
7381    }
7382    let syms = (
7383      arena::pin(s!("{encoding}_{family}_fontmap")),
7384      arena::pin(s!("{encoding}_{family}_fontmap_multichar")),
7385    );
7386    m.borrow_mut()
7387      .insert((encoding.to_string(), family.to_string()), syms);
7388    syms
7389  });
7390  FONTMAP_FAMILY_KEY_LAST.with_borrow_mut(|last| match last {
7391    Some((e, f, k)) => {
7392      e.clear();
7393      e.push_str(encoding);
7394      f.clear();
7395      f.push_str(family);
7396      *k = syms;
7397    },
7398    None => *last = Some((encoding.to_string(), family.to_string(), syms)),
7399  });
7400  syms
7401}
7402
7403/// Clear the fontmap key-symbol memos. Companion to `arena::reset()` — the
7404/// cached `SymStr`s dangle after a reset renumbers the arena.
7405pub fn reset_fontmap_key_memo() {
7406  FONTMAP_KEY_MEMO.with(|m| m.borrow_mut().clear());
7407  FONTMAP_FAMILY_KEY_MEMO.with(|m| m.borrow_mut().clear());
7408  FONTMAP_KEY_LAST.set(None);
7409  FONTMAP_FAMILY_KEY_LAST.set(None);
7410}
7411
7412pub fn load_font_map(encoding: &str) -> Option<Fontmap> {
7413  let keys = fontmap_key_syms(encoding);
7414  let _ = preload_font_map_keyed(encoding, keys); // infallible in practice; swallow Result
7415  // with_value avoids the Stored::clone; the Fontmap extraction is a cheap
7416  // Rc bump on the inner slice regardless.
7417  with_value_sym(keys.map, |v| v.and_then(|s| s.into()))
7418}
7419pub fn preload_font_map(encoding: &str) -> Result<()> {
7420  preload_font_map_keyed(encoding, fontmap_key_syms(encoding))
7421}
7422fn preload_font_map_keyed(encoding: &str, keys: FontmapKeySyms) -> Result<()> {
7423  // This check is done as a "preload" step for mutability reasons.
7424  if has_value_sym(keys.map) {
7425    return Ok(());
7426  }
7427  let failed_flag = lookup_bool_sym(keys.fail);
7428  if !failed_flag {
7429    assign_value_sym(keys.fail, true, None); // Stop recursion?
7430    let _ = input_definitions(&encoding.to_lowercase(), InputDefinitionOptions {
7431      extension: Some(Cow::Borrowed("fontmap")),
7432      noerror: true,
7433      ..InputDefinitionOptions::default()
7434    });
7435    if has_value_sym(keys.map) {
7436      // Got map?
7437      assign_value_sym(keys.fail, false, None);
7438    } else {
7439      assign_value_sym(keys.fail, true, Some(Scope::Global));
7440    }
7441  }
7442  Ok(())
7443}
7444
7445#[cfg(test)]
7446mod content_files_tests {
7447  use super::*;
7448
7449  /// A content file costs the string arena its path once, however many came before (issue 1011: the list, re-interned
7450  /// whole at every `\input`, grew with the square of the files, 61 MB at 1,000), and is noted once, in reading order.
7451  #[test]
7452  fn each_content_file_costs_the_arena_its_path_once() {
7453    set_state(State::new(StateOptions::default()));
7454    let path = |i: usize| s!("/book/chapters/chapter_{i:05}/sections/section_body.tex");
7455    let before = arena::buffer_len();
7456    for i in 0..200 {
7457      note_content_file(&path(i));
7458    }
7459    note_content_file(&path(7));
7460    let grown = arena::buffer_len() - before;
7461    let each = path(0).len() + 1;
7462    assert!(
7463      grown <= 2 * 200 * each,
7464      "{grown} bytes for 200 paths of {each}"
7465    );
7466    // The whole reading order, every path once.
7467    assert_eq!(content_files(), (0..200).map(path).collect::<Vec<_>>());
7468  }
7469}
7470
7471#[cfg(test)]
7472mod declared_info_tests {
7473  use super::*;
7474
7475  /// A standard-class derivative's read a panic unwinds out of leaves no entry: the next read is no derivative's.
7476  #[test]
7477  fn a_derivative_read_a_panic_ends_is_popped() {
7478    let unwound = std::panic::catch_unwind(|| {
7479      let _read = StandardClassDerivativeRead::enter(HashSet::default());
7480      panic!("a binding's bug");
7481    });
7482    assert!(unwound.is_err());
7483    assert!(STANDARD_CLASS_DERIVATIVE.with(|reads| reads.borrow().is_empty()));
7484  }
7485
7486  /// `\Provides…` text as latex.ltx's `\xdef` leaves it: the kernel's `\space` and `\ ` read as spaces
7487  /// (cite.sty `[2015/02/27 \space v 5.5]`); a file's own macros (listings.sty:22-23 `\filedate\space\fileversion`,
7488  /// vmargin's `\Vmargin`) give nothing.
7489  #[test]
7490  fn declared_text_expands_like_xdef() {
7491    assert_eq!(
7492      expand_declared("2015/02/27 \\space v 5.5").as_deref(),
7493      Some("2015/02/27  v 5.5")
7494    );
7495    assert_eq!(
7496      expand_declared("2015/02/27\\ v5.5").as_deref(),
7497      Some("2015/02/27 v5.5")
7498    );
7499    assert_eq!(
7500      expand_declared("2015/02/27\\  v5.5").as_deref(),
7501      Some("2015/02/27 v5.5")
7502    );
7503    assert_eq!(
7504      expand_declared("2024/11/12 v2.9 Span multiple rows").as_deref(),
7505      Some("2024/11/12 v2.9 Span multiple rows")
7506    );
7507    assert_eq!(
7508      expand_declared("\\filedate\\space\\fileversion\\space(Carsten Heinz)"),
7509      None
7510    );
7511    assert_eq!(expand_declared("\\Vmargin"), None);
7512    assert_eq!(expand_declared(""), None);
7513  }
7514
7515  /// A `%` comment between the name and the bracket (multirow.sty:25-27); a match without a bracket goes on to the
7516  /// next `\Provides`.
7517  #[test]
7518  fn provided_text_skips_comments_before_the_bracket() {
7519    let multirow =
7520      "\\ProvidesPackage{multirow}%\n  % note\n  [2024/11/12 v2.9 Span multiple rows of a table]\n";
7521    assert_eq!(
7522      provided_text(multirow, "multirow.sty").as_deref(),
7523      Some("2024/11/12 v2.9 Span multiple rows of a table")
7524    );
7525    let twice = "\\ProvidesPackage{x}\n\\ProvidesPackage{x}[2020/01/01 v1]";
7526    assert_eq!(
7527      provided_text(twice, "x.sty").as_deref(),
7528      Some("2020/01/01 v1")
7529    );
7530  }
7531}