Skip to main content

latexml_core/binding/
kernel_autoload.rs

1//! Autoload the LaTeX format when an *undefined* control sequence turns out to
2//! be one the LaTeX kernel defines.
3//!
4//! # Why this exists
5//!
6//! In real LaTeX there is no such thing as "before the kernel": `latex.ltx`
7//! **is** the format, so every kernel command is live from token one. LaTeXML
8//! (Perl and Rust alike) instead loads `LaTeX.pool` lazily, on first sight of a
9//! *trigger* control sequence — the list ported from Perl `TeX.pool.ltxml`
10//! L33-56 (`\documentclass`, `\newcommand`, `\begin`, …), installed in
11//! `latexml_engine::tex`.
12//!
13//! A curated trigger list is incomplete by construction. Any kernel command
14//! that is *not* on it — and a document may legitimately use one before
15//! `\documentclass` — is simply undefined, gets an `<ltx:ERROR/>` stub, and the
16//! document derails. The canonical case is the "use this class if installed"
17//! idiom
18//!
19//! ```tex
20//! \IfFileExists{proc-l.cls}{\documentclass{proc-l}}{\documentclass{amsproc}}
21//! ```
22//!
23//! where the collapsed conditional means *no class is ever selected* and the
24//! run cascades into `Fatal:TooManyErrors`. Same-host Perl LaTeXML fails
25//! identically (see `docs/parity/KNOWN_PERL_ERRORS.md` — shared defect, upstream
26//! candidate), so this is a "at parity, still a bug" fix rather than a
27//! divergence repair.
28//!
29//! # What this module is
30//!
31//! The single funnel through which the undefined-CS paths ask "should the LaTeX
32//! kernel be loaded for this token instead of erroring?". It holds no policy of
33//! its own: the answer comes from a hook the engine registers at `TeX.pool`
34//! load time ([`set_hook`]), because deciding it needs the kernel dump and the
35//! pool loader, neither of which `latexml_core` owns.
36//!
37//! The eager Perl trigger list is *kept* — it fires on a legitimate use before
38//! any error is raised, which this hook cannot do. This is the safety net
39//! beneath it, not a replacement.
40//!
41//! # Call sites: two, deliberately not three
42//!
43//! `read_x_token`'s `Outcome::Undefined` arm and `invoke_token_undefined` are
44//! the paths a CS reaches when it is actually being *used*. `read_balanced`'s
45//! "cs SHOULD have defn by now; report early!" branch — the third
46//! `generate_error_stub` caller, inside token-list scanning — is left alone on
47//! purpose: it fires while collecting an `\edef`-style body rather than
48//! executing it, and loading a format mid-scan buys a rare case
49//! (`\edef\x{\IfFileExists…}` before `\documentclass`) at the price of running
50//! the whole pool from inside a partially-read token list. Wire it up only with
51//! a reproducer that needs it. A provider named for first use ([`provide_on_first_use`]) is asked there too: it
52//! defines a few commands, not a format, so the scan reads the name again.
53
54use std::sync::OnceLock;
55
56use crate::token::Token;
57
58/// Engine-supplied decision procedure for "is `token` a LaTeX kernel control
59/// sequence, and if so load the kernel and report whether it is now defined".
60///
61/// Returning `true` means the caller must **retry** `token` (it now has a real
62/// meaning); returning `false` means "carry on and report it undefined exactly
63/// as before". Implementations own the once-only guard — see
64/// `latexml_engine::latex_kernel::autoload_latex_kernel`.
65pub type KernelAutoloadHook = fn(&Token) -> bool;
66
67/// Process-global because the hook is a plain `fn` pointer with no state: the
68/// per-session bookkeeping (already-loaded, already-attempted) lives in the
69/// State, so re-registering across sessions is a no-op.
70static HOOK: OnceLock<KernelAutoloadHook> = OnceLock::new();
71
72/// Register the engine's kernel-autoload decision procedure. Called from
73/// `TeX.pool`'s definition load, which precedes every conversion. Repeat calls
74/// are ignored (the first registration wins).
75pub fn set_hook(hook: KernelAutoloadHook) { let _ = HOOK.set(hook); }
76
77/// Ask the registered hook whether `token` should pull the LaTeX kernel in.
78///
79/// `true` ⇒ the kernel was loaded *and* `token` now has a meaning, so the
80/// caller must push it back and re-resolve. `false` ⇒ nothing happened; take
81/// the ordinary bounded `Error:undefined` path.
82///
83/// Cold path only — every caller is a site that was already about to raise an
84/// undefined-CS error. With no hook registered (a bare `latexml_core` embedding)
85/// this is an atomic load and a `false`.
86pub fn try_autoload(token: &Token) -> bool {
87  match HOOK.get() {
88    Some(hook) => hook(token),
89    None => false,
90  }
91}
92
93/// Engine-supplied procedure for "does an open environment whose class definition the kernel's lock refused define
94/// `token` for its body, and if so define it as the class would have and report it defined" — a class's `\figure`
95/// that makes `\csentence` for its captions (bmcart.cls:716), its `\abstract` that makes `\parttitle` (:1508). The
96/// same contract as [`KernelAutoloadHook`]: `true` ⇒ retry `token`.
97pub type RefusedEnvironmentHook = fn(&Token) -> bool;
98
99static ENV_HOOK: OnceLock<RefusedEnvironmentHook> = OnceLock::new();
100
101/// Register the engine's [`RefusedEnvironmentHook`] (first registration wins).
102pub fn set_refused_environment_hook(hook: RefusedEnvironmentHook) { let _ = ENV_HOOK.set(hook); }
103
104/// Ask the registered [`RefusedEnvironmentHook`] about an undefined `token`, at the same two call sites as
105/// [`try_autoload`] (after it): `true` ⇒ `token` now has a meaning, retry it.
106pub fn try_refused_environment_definition(token: &Token) -> bool {
107  match ENV_HOOK.get() {
108    Some(hook) => hook(token),
109    None => false,
110  }
111}
112
113thread_local! {
114  /// Has a stand-in been named on this thread ([`name_undefined_fallback`])? Until one is, [`undefined_fallback`]
115  /// answers at once, without spelling a key for every undefined control sequence (expl3-code.tex's load meets
116  /// thousands).
117  static FALLBACK_NAMED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
118}
119
120/// Name `stand_in` as what a use of the undefined `token` reads (`"{cs}:undefined@fallback"`, global), for
121/// [`undefined_fallback`].
122pub fn name_undefined_fallback(token: &Token, stand_in: Token) {
123  FALLBACK_NAMED.with(|named| named.set(true));
124  let key = token.with_cs_name(|cs| format!("{cs}:undefined@fallback"));
125  crate::state::assign_value(
126    &key,
127    crate::state::Stored::Token(stand_in),
128    Some(crate::state::Scope::Global),
129  );
130}
131
132/// Forget that a stand-in was named (`reset_thread_engine`).
133pub fn reset_undefined_fallback() { FALLBACK_NAMED.with(|named| named.set(false)); }
134
135/// The stand-in LaTeXML reads for an undefined `token`, if one is named ([`name_undefined_fallback`]): the name stays
136/// undefined — `\ifdefined`, `\@ifundefined` and `\meaning` see what TeX sees — and a use of it reads the stand-in,
137/// which is responsible for saying that TeX errs there. The class-less `\chapter` is the one named (OXIDIZED_DESIGN
138/// #734, latexml_engine `supply_chapter_fallback`). Asked at the two undefined-CS sites, after [`try_autoload`] and
139/// [`try_refused_environment_definition`]: `Some` ⇒ read the stand-in in place of `token`.
140pub fn undefined_fallback(token: &Token) -> Option<Token> {
141  if !FALLBACK_NAMED.with(std::cell::Cell::get) {
142    return None;
143  }
144  let key = token.with_cs_name(|cs| format!("{cs}:undefined@fallback"));
145  // probe-only: a name never given a stand-in has no interned key
146  crate::common::arena::get(&key)?;
147  match crate::state::lookup_value(&key) {
148    Some(crate::state::Stored::Token(stand_in)) => Some(stand_in),
149    _ => None,
150  }
151}
152
153thread_local! {
154  /// Has a first-use provider been named on this thread ([`name_first_use_provider`])? As `FALLBACK_NAMED`.
155  static PROVIDER_NAMED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
156}
157
158/// Name `provider`, an expandable command that defines a family of commands where still undefined, as what an
159/// undefined `token` of that family runs on its first use (`"{cs}:first@use@provider"`, global). Nothing is defined
160/// until then, so `\ifdefined`, `\@ifundefined` and a document's own `\newcommand` see what TeX sees. Beyond Perl, which
161/// has no such seam: the ar5iv preload names hyperref's and atbegshi's user commands (OXIDIZED_DESIGN #588).
162pub fn name_first_use_provider(token: &Token, provider: Token) {
163  PROVIDER_NAMED.with(|named| named.set(true));
164  let key = token.with_cs_name(|cs| format!("{cs}:first@use@provider"));
165  crate::state::assign_value(
166    &key,
167    crate::state::Stored::Token(provider),
168    Some(crate::state::Scope::Global),
169  );
170}
171
172/// Forget that a provider was named (`reset_thread_engine`).
173pub fn reset_first_use_providers() { PROVIDER_NAMED.with(|named| named.set(false)); }
174
175/// Run the provider named for the undefined `token` ([`name_first_use_provider`]), until it has provided once; `true`
176/// ⇒ `token` now has a meaning, retry it. Asked at every undefined-CS site, after [`try_autoload`] and
177/// [`try_refused_environment_definition`].
178pub fn provide_on_first_use(token: &Token) -> crate::common::error::Result<bool> {
179  if !PROVIDER_NAMED.with(std::cell::Cell::get) {
180    return Ok(false);
181  }
182  let key = token.with_cs_name(|cs| format!("{cs}:first@use@provider"));
183  // probe-only: a name never given a provider has no interned key
184  if crate::common::arena::get(&key).is_none() {
185    return Ok(false);
186  }
187  let Some(crate::state::Stored::Token(provider)) = crate::state::lookup_value(&key) else {
188    return Ok(false);
189  };
190  let done = provider.with_cs_name(|cs| format!("{cs}:first@use@done"));
191  if crate::state::lookup_bool(&done) {
192    return Ok(false);
193  }
194  if let Some(defn) = crate::state::lookup_expandable(&provider, None)? {
195    defn.invoke(false)?;
196  }
197  // a provider may decline (a plain TeX document): it is asked again at the next use
198  let provided = crate::state::lookup_definition(token)?.is_some();
199  if provided {
200    crate::state::assign_value(
201      &done,
202      crate::state::Stored::Bool(true),
203      Some(crate::state::Scope::Global),
204    );
205  }
206  Ok(provided)
207}