Skip to main content

latexml_core/
state.rs

1use std::{
2  borrow::Cow,
3  cell::RefCell,
4  collections::VecDeque,
5  fmt::{self, Display},
6  rc::Rc,
7  sync::LazyLock,
8};
9
10use regex::Regex;
11use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
12
13// expose Perl-style local assignments from state
14pub use crate::common::local_assignments::*;
15pub use crate::common::store::Stored; // reexport for convenience
16use crate::{
17  Digested, DigestedData,
18  alignment::Alignment,
19  common::{
20    BindingDispatcher, LabelMappingHook, LocalBindingFinder, ResolvingBindingDispatcher,
21    arena::{self, SymHashMap, SymStr},
22    dimension::Dimension,
23    error::{emit_warn, *},
24    float::Float,
25    font::{self, Font},
26    glue::Glue,
27    model::{self, IndirectModel, Model, compute_indirect_model_aux},
28    muglue::MuGlue,
29    number::Number,
30    numeric_ops::{NumericOps, UNITY},
31  },
32  definition::{
33    Definition, ExpansionBody,
34    argument::ArgWrap,
35    conditional::ConditionalType,
36    constructor::Constructor,
37    expandable::{self, Expandable},
38    register::{Register, RegisterValue},
39  },
40  document::{
41    resource::Resource,
42    tag::{AutoOpen, TagOptions},
43  },
44  gullet, mouth, pin,
45  token::{Catcode, Token},
46  tokens::{TeXString, Tokens},
47  util::pathname,
48};
49
50static CODE_TEX_EXT: &str = ".code.tex";
51
52/// regex for *.tex and *.bib
53static TEX_OR_BIB_EXT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\.(tex|bib)$").unwrap());
54/// Used in conversion to scaled points.
55///
56/// These are the float `sp`-per-unit ratios, kept for *display / scaling*
57/// consumers (pgf/graphics/hyperref divide by them). For dimension
58/// **construction** use [`convert_unit_ratio`] + `numeric_ops::fixpoint_unit`
59/// instead — exact integer arithmetic, bit-faithful to TeX (issue #127). Each
60/// value here equals `65536·num/den` of the matching `convert_unit_ratio` entry.
61pub static UNITS: LazyLock<HashMap<String, f64>> = LazyLock::new(|| {
62  map!(
63    "pt" => 65536.0,
64    "pc" => 12.0 * 65536.0,
65    "in" => 72.27 * 65536.0,
66    "bp" => 72.27 * 65536.0 / 72.0,
67    "px" => 72.27 * 65536.0 / 72.0,   // Assume px=bp ?
68    "cm" => 72.27 * 65536.0 / 2.54,
69    "mm" => 72.27 * 65536.0 / 2.54 / 10.0,
70    "dd" => 1238.0 * 65536.0 / 1157.0,
71    "cc" => 12.0 * 1238.0 * 65536.0 / 1157.0,
72    "sp" => 1.0
73  )
74});
75
76/// installation scope in the state_tables
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum Scope {
79  /// globally visible, does not expire
80  Global,
81  /// globally visible, but expires at the end of the current group
82  Local,
83  /// a named scope - visible only when explicitly activated
84  Named(SymStr),
85  /// in-place: replace the value in the frame it was last bound in, WITHOUT
86  /// recording a new undo entry (or globally, at the locked base frame, if it
87  /// was never bound). Perl `State.pm:175` `$scope eq 'inplace'` ("Special case
88  /// for `\box` & friends"). This is Knuth's "same level" reassignment / what
89  /// @xworld21 tentatively called `scope => 'definition'`: the binding keeps its
90  /// save-stack level, so a mutation rides exactly as long as the current
91  /// binding — persisting past the current group if the binding was made above
92  /// it, reverting with the group if it was made locally. Distinct from Global
93  /// (which promotes + wipes lower-frame undo) and Local (which pushes an outer
94  /// binding down a level). The Value-table fast path is `assign_value_inplace`.
95  InPlace,
96}
97
98/// the kinds of tables bookkept in the State
99#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
100pub enum TableName {
101  /// token meaning
102  Meaning,
103  /// all stateful values
104  Value,
105  /// catcode bindings
106  Catcode,
107  /// mathcode bindings
108  Mathcode,
109  /// sf code bindings
110  Sfcode,
111  /// lc code bindings
112  Lccode,
113  /// uc code bindings
114  Uccode,
115  /// del code bindings
116  Delcode,
117  /// stash of inactive named values
118  Stash,
119  /// active stash of named values
120  StashActive,
121}
122impl Display for TableName {
123  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124    write!(f, "{}", match self {
125      TableName::Meaning => "Meaning",
126      TableName::Value => "Value",
127      TableName::Catcode => "Catcode",
128      TableName::Mathcode => "Mathcode",
129      TableName::Sfcode => "Sfcode",
130      TableName::Lccode => "Lccode",
131      TableName::Uccode => "Uccode",
132      TableName::Delcode => "Delcode",
133      TableName::Stash => "Stash",
134      TableName::StashActive => "StashActive",
135    })
136  }
137}
138impl TableName {
139  /// provides all TableName variants. useful for iterating over all tables
140  pub fn variants() -> &'static [TableName] {
141    use self::TableName::*;
142    &[
143      Meaning,
144      Value,
145      Catcode,
146      Mathcode,
147      Sfcode,
148      Lccode,
149      Uccode,
150      Delcode,
151      Stash,
152      StashActive,
153    ]
154  }
155}
156
157/// High-level catcode profiles
158#[derive(Clone, Debug, PartialEq, Eq)]
159pub enum Catcodes {
160  /// the usual mainmatter catcodes (e.g. @ is other)
161  Standard,
162  /// the usual style catcodes (e.g. @ is letter)
163  Style,
164  /// left unspecified
165  None,
166}
167
168/// Ledger for stacked assignments: how many bindings of each key a frame made (Perl's `$$frame{$table}{$key}`).
169#[derive(Debug, Clone, Default)]
170pub struct AssignmentCount {
171  counts: HashMap<SymStr, usize>,
172  /// A bit per key ever counted here, never cleared: a clear bit proves the key absent, so a `\global` assignment's
173  /// walk over the frames skips the probe (2205.15714, circuitikzmanual).
174  seen:   [u64; 4],
175}
176
177// (the map's own methods; every insertion sets the key's bit)
178impl AssignmentCount {
179  #[inline]
180  fn bit(key: SymStr) -> (usize, u64) {
181    use string_interner::Symbol;
182    let index = key.to_usize();
183    ((index >> 6) & 3, 1 << (index & 63))
184  }
185  #[inline]
186  fn note(&mut self, key: SymStr) {
187    let (word, bit) = Self::bit(key);
188    self.seen[word] |= bit;
189  }
190  /// `false` when `key` was certainly never counted here.
191  #[inline]
192  pub fn may_hold(&self, key: SymStr) -> bool {
193    let (word, bit) = Self::bit(key);
194    self.seen[word] & bit != 0
195  }
196  pub fn get(&self, key: &SymStr) -> Option<&usize> { self.counts.get(key) }
197  pub fn contains_key(&self, key: &SymStr) -> bool { self.counts.contains_key(key) }
198  pub fn insert(&mut self, key: SymStr, count: usize) -> Option<usize> {
199    self.note(key);
200    self.counts.insert(key, count)
201  }
202  pub fn remove(&mut self, key: &SymStr) -> Option<usize> { self.counts.remove(key) }
203  pub fn entry(&mut self, key: SymStr) -> std::collections::hash_map::Entry<'_, SymStr, usize> {
204    self.note(key);
205    self.counts.entry(key)
206  }
207  pub fn iter(&self) -> std::collections::hash_map::Iter<'_, SymStr, usize> { self.counts.iter() }
208  pub fn keys(&self) -> std::collections::hash_map::Keys<'_, SymStr, usize> { self.counts.keys() }
209  pub fn is_empty(&self) -> bool { self.counts.is_empty() }
210}
211/// The `(table_name, key, value)` contents of a stored table of assignments
212pub type StashTable = Vec<(TableName, SymStr, Stored)>;
213#[derive(Debug, Clone)]
214/// For each of several tables (being "value", "meaning", "catcode" or other space of names),
215/// each table maintains the bound values, and "undo" defines the stack frames
216pub struct UndoFrame {
217  /// The frame's identity, unique to it (an assignment journal tells the frames it began with from later ones at the
218  /// same depth: `AssignmentJournalGuard::rollback`).
219  id:           u64,
220  locked:       bool,
221  meaning:      AssignmentCount,
222  value:        AssignmentCount,
223  catcode:      AssignmentCount,
224  mathcode:     AssignmentCount,
225  sfcode:       AssignmentCount,
226  lccode:       AssignmentCount,
227  uccode:       AssignmentCount,
228  delcode:      AssignmentCount,
229  stash:        AssignmentCount,
230  stash_active: AssignmentCount,
231}
232
233/// The next `UndoFrame::id`.
234static NEXT_FRAME_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
235
236impl Default for UndoFrame {
237  fn default() -> Self {
238    UndoFrame {
239      id:           NEXT_FRAME_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
240      locked:       false,
241      meaning:      AssignmentCount::default(),
242      value:        AssignmentCount::default(),
243      catcode:      AssignmentCount::default(),
244      mathcode:     AssignmentCount::default(),
245      sfcode:       AssignmentCount::default(),
246      lccode:       AssignmentCount::default(),
247      uccode:       AssignmentCount::default(),
248      delcode:      AssignmentCount::default(),
249      stash:        AssignmentCount::default(),
250      stash_active: AssignmentCount::default(),
251    }
252  }
253}
254
255impl UndoFrame {
256  /// borrow the undo assignment counts for a given table name
257  pub fn table(&self, name: TableName) -> &AssignmentCount {
258    use self::TableName::*;
259    match name {
260      Meaning => &self.meaning,
261      Value => &self.value,
262      Catcode => &self.catcode,
263      Mathcode => &self.mathcode,
264      Sfcode => &self.sfcode,
265      Lccode => &self.lccode,
266      Uccode => &self.uccode,
267      Delcode => &self.delcode,
268      Stash => &self.stash,
269      StashActive => &self.stash_active,
270    }
271  }
272  /// mutably borrow the undo assignment counts for a given table name
273  pub fn table_mut(&mut self, name: TableName) -> &mut AssignmentCount {
274    use self::TableName::*;
275    match name {
276      Meaning => &mut self.meaning,
277      Value => &mut self.value,
278      Catcode => &mut self.catcode,
279      Mathcode => &mut self.mathcode,
280      Sfcode => &mut self.sfcode,
281      Lccode => &mut self.lccode,
282      Uccode => &mut self.uccode,
283      Delcode => &mut self.delcode,
284      Stash => &mut self.stash,
285      StashActive => &mut self.stash_active,
286    }
287  }
288}
289
290/// The type of values that are storable by the different namespaced "tables" in State.
291///
292/// There are tables for:
293///
294///  catcode: keys are char;
295///     Also, `math:char` =1 when `char` is active in math.
296///  mathcode, sfcode, lccode, uccode, delcode : are similar to catcode but store
297///    additional kinds codes per char (see TeX)
298///  value: keys are anything (typically a string, though) and value is the value associated with it
299///  meaning: The definition assocated with `key`, usually a control-sequence.
300///  stash & stash_active: support named scopes
301///      (see also activateScope & deactivateScope)
302pub type Table = HashMap<SymStr, VecDeque<Stored>>;
303
304/// The bindings of every key assigned since an assignment journal began ([`begin_assignment_journal`]), as they were
305/// then: taken at the key's first assignment after, the key's values in its table and its assignment counts in each
306/// frame then open (by the frame's id), so that [`AssignmentJournalGuard::rollback`] can put them back. A key's first
307/// assignment is the first time anything touches it, so the frames opened since hold none of it.
308#[derive(Debug, Default)]
309pub struct AssignmentJournal {
310  /// The meanings assigned since the log was last read, in order, each with whether globally ([`begin_meaning_log`]);
311  /// `None` while no one reads it.
312  meaning_log:    Option<Vec<MeaningAssigned>>,
313  /// the ids of the frames open when it began, from the bottom of the stack
314  frames:         Vec<u64>,
315  saved:          rustc_hash::FxHashMap<(TableName, SymStr), JournalEntry>,
316  /// each meaning's standing as a fallback guess, a kernel stub or a borrowed package's then (`fallback_meanings`),
317  /// which an assignment changes beside the meaning and no group end puts back: the meaning a rehearsal `\let`s and
318  /// rolls back keeps it (an OmniBus `\AND`, which algorithmic's `\newcommand{\AND}` may replace — siamart220329,
319  /// 2409.10200; FM S2a.2 r9)
320  fallback: rustc_hash::FxHashMap<SymStr, Option<crate::definition::origin::DefinitionOrigin>>,
321  /// each box whose `\\wd`, `\\ht` or `\\dp` was set, the property's value then, oldest first: a property of the box itself, which
322  /// a register's binding shares ([`journal_box_dimension`])
323  box_dimensions: Vec<(Digested, &'static str, Option<Stored>)>,
324  /// the watch held when it began ([`watch_state`]), which a rollback puts back
325  watch:          u64,
326}
327/// A key's values in its table (`None`: unbound) and its assignment counts by frame id.
328type JournalEntry = (Option<VecDeque<Stored>>, Vec<(u64, usize)>);
329
330/// The state efficiently bookkeeps the bindings in a TeX-like fashion.
331///
332/// Bindings associate data with keys (eg definitions with macro names)
333/// and respect TeX grouping; that is, an assignment is only in effect
334/// until the current group (opened by \bgroup) is closed (by \egroup).
335pub struct State {
336  // Tables
337  /// bookkeeps arbitrary Stored values
338  value:                       Table,
339  /// The definition assocated with a key, usually a control-sequence.
340  meaning:                     Table,
341  stash:                       Table,
342  stash_active:                Table,
343  catcode:                     Table,
344  mathcode:                    Table,
345  sfcode:                      Table,
346  lccode:                      Table,
347  uccode:                      Table,
348  delcode:                     Table,
349  // Table bookkeeping
350  undo:                        VecDeque<UndoFrame>,
351  // stateful runtime - data structures
352  /// the schema-derived model used for the current document
353  prefixes:                    HashMap<SymStr, bool>, // ?
354  pub tag_properties:          HashMap<SymStr, TagOptions>,
355  /// an optional indirect model for long-distance relationships
356  pub indirect_model:          Option<IndirectModel>,
357  /// Document-related resources declared during core conversion, pending until XML is finalized
358  pub pending_resources:       Vec<Resource>,
359  // stateful runtime - simple fields
360  // TODO: Maybe group these in a "SessionFlags" struct?
361  //       we can then reset that if we reimplement a daemon app
362  pub verbosity:               i32,
363  pub input_encoding:          Option<String>,
364  // strict: bool,
365  // include_comments: bool,
366  /// Seed only for the group-scoped `SEARCHPATHS` value-table list (read once at
367  /// construction to seed it); live lookups go through [`get_search_paths`].
368  pub search_paths:            VecDeque<String>,
369  /// Seed only for the group-scoped `GRAPHICSPATHS` value-table list (read once at
370  /// construction to seed it); live lookups go through [`get_graphics_paths`].
371  pub graphics_paths:          VecDeque<String>,
372  // include_styles: bool,
373  /// flag to disable math parsing
374  pub nomathparse:             bool,
375  /// Perl `Conditional.pm:61-62`: the `if_count` Value entry, assigned
376  /// `'global'` on every `\if…` so the per-conditional id survives group
377  /// exit. A value only ever assigned globally collapses to one base-frame
378  /// binding, so a plain monotonic field is the same counter without the
379  /// per-conditional `assign_internal(Global)` undo-frame walk (measured
380  /// 4.4 % of instructions on `\ifnum`-dense pgf input). Runtime-only, so
381  /// it never enters a dump. Micro-divergence: `\globaldefs<0` demoted
382  /// Perl's assignment to local (ids could repeat after a group); the id is
383  /// the `IfFrame`'s diagnostic tag, never a matching key, so it is unaffected.
384  pub if_count:                i64,
385  /// Perl `Conditional.pm:63` `unshiftValue('if_stack', $ifframe)`: the active conditionals,
386  /// innermost last. Perl edits the Value in place (`unshiftValue`/`shiftValue`, never grouped
387  /// or undone), so a typed field is the same stack without the per-`\if`/`\else`/`\fi`
388  /// value-table lookups. Runtime-only, so it never enters a dump.
389  pub if_stack:                Vec<Rc<RefCell<crate::definition::conditional::IfFrame>>>,
390  /// Perl `$LaTeXML::IF_LIMIT` (`latexml.sty.ltxml:101`): a plain global,
391  /// never a State value. `0` = unlimited.
392  pub if_limit:                i64,
393  /// Perl `Object.pm:165` / `Box.pm:145`: the `absorb_count` Value, assigned
394  /// `'global'` per absorbed box — the same mechanism as [`Self::if_count`]
395  /// (a Perl global-only Value becomes a typed State scalar).
396  pub absorb_count:            i64,
397  /// Perl `$LaTeXML::ABSORB_LIMIT` (`latexml.sty.ltxml:104`), `0` = unlimited.
398  pub absorb_limit:            i64,
399  /// flag enabling source-locator (`--source-map`) tracking + emission.
400  /// Off by default; gates BOTH the per-token start capture and the
401  /// per-element `data-sourcepos` stamping so a normal conversion pays
402  /// nothing. See `docs/performance/SOURCE_PROVENANCE.md`.
403  pub source_map:              bool,
404  /// Document-level `sources` table for the source-map feature: ordered
405  /// list of source files seen, index = the integer `tag` emitted in
406  /// `data-sourcepos` (Source-Map-v3 `sources` style — never an inlined
407  /// path). Populated lazily via `source_tag()` only when `source_map` is
408  /// on. See `docs/performance/SOURCE_PROVENANCE.md` §0.1.
409  pub source_table:            Vec<SymStr>,
410  /// Read-log of every *named* source opened through `Mouth::create`
411  /// (file paths and cached-content names; literal/anonymous mouths are
412  /// not named, so not recorded). Distinct from `source_table`, which
413  /// is populated lazily at *document-construction* time and filters to
414  /// user sources — this log is complete and available right after a
415  /// digest, which the LSP server's warm-cache dependency snapshot
416  /// relies on (`lsp_server/overlay.rs::warmup_dep_snapshot`).
417  pub opened_sources:          HashSet<SymStr>,
418  // TODO: We can make this a Vec<BindingDispatcher> if we want to accumulate more definitions
419  /// The installed binding-resolution chain — reports the source path it loaded
420  /// from (for a `.rhai` file binding), or `None` for a compiled-in binding.
421  pub bindings_dispatch:       Option<ResolvingBindingDispatcher>,
422  /// Auxiliary convenience -- extra dispatch
423  pub extra_bindings_dispatch: Option<BindingDispatcher>,
424  /// The chain's first tier, a user's binding file in the local search paths ([`local_binding_file`]).
425  pub local_binding_finder:    Option<LocalBindingFinder>,
426  /// All `(name, ext)` pairs for compile-time bindings the dispatchers can
427  /// load, stacked one slice per registered dispatcher. Populated at
428  /// startup by each binding crate via `add_binding_names`, so both
429  /// `latexml_package` and `latexml_contrib` contribute their classes/
430  /// styles/defs/pools to the fallback pool. Consumed by:
431  /// - `find_file(notex=true)` to resolve compile-time bindings without touching the filesystem.
432  /// - `load_class`'s Perl-parity prefix-match fallback (Package.pm L2702-2706) via the
433  ///   `get_class_binding_names()` filtered view.
434  pub binding_names:           Vec<&'static [(&'static str, &'static str)]>,
435  /// Perl: LABEL_MAPPING_HOOK — closure mapping (label, counter, norefnum) -> (refnum, id)
436  pub label_mapping_hook:      Option<LabelMappingHook>,
437  /// The names whose current meaning a fallback class installed (`DefinitionOrigin::Fallback`, OmniBus), a kernel stub
438  /// or a borrow, with that origin, until something else assigns them: a document's `\newcommand` may define them
439  /// (`is_fallback_meaning`, `fallback_meaning_origin`).
440  pub fallback_meanings: rustc_hash::FxHashMap<SymStr, crate::definition::origin::DefinitionOrigin>,
441  /// The names assigned while a provide-only load lives ([`ProvideOnlyGuard`](crate::definition::origin::ProvideOnlyGuard)):
442  /// the load's own definitions, which it may define again (`provide_only_declines`).
443  pub provide_only_assigned:   rustc_hash::FxHashSet<SymStr>,
444  /// The files first marked loaded while a provide-only load lives: loaded partly (their definitions of names defined
445  /// before were declined), so the guard unmarks them when it ends and a later request loads them whole
446  /// (`end_provide_only`).
447  pub provide_only_loaded:     Vec<String>,
448  /// The files first marked loaded while a binding borrows a package (`DefinitionOrigin::Borrowed`,
449  /// `binding::content::require_package_borrowed`): the borrowed package and what it loads (amsthm's amsgen), which the
450  /// borrow unmarks again, as LaTeX never loaded them.
451  pub borrowed_loaded:         Vec<String>,
452  /// The paper's copies of author files read after their stand-in bindings, by number less one
453  /// ([`crate::definition::origin::copy_provides`]; [`note_copy_provides_assignment`]).
454  pub copy_provides_copies:    Vec<CopyProvidesRecord>,
455  /// The frames of the stand-in copies' provides-mode in force, innermost last
456  /// ([`enter_copy_provides_frame`]).
457  pub copy_provides_frames:    Vec<CopyProvidesFrame>,
458  /// The names assigned while a stand-in binding loaded ([`crate::definition::origin::StandInLoadGuard`]): its own, which
459  /// the paper's copy read after it only provides ([`note_copy_provides_assignment`]).
460  pub stand_in_meanings:       rustc_hash::FxHashSet<SymStr>,
461  /// The names whose meaning a class the stand-in binding loads assigned last
462  /// ([`crate::definition::origin::stand_in_base_class`]): its base class's, whose text defaults are not the binding's
463  /// (`unowned_text_default`).
464  pub stand_in_base_defaults:  rustc_hash::FxHashSet<SymStr>,
465  /// The names each stand-in binding loading now has assigned in its own code, innermost last ([`begin_stand_in_load`]).
466  pub stand_in_loads:          Vec<Vec<SymStr>>,
467  /// The names the stand-in binding loaded last assigned in its own code ([`end_stand_in_load`]): the public ones are
468  /// the command set the paper's copy must define to be that binding's file (`binding::content` `read_stand_in_copy`).
469  pub stand_in_last_load:      Vec<SymStr>,
470  /// The files each stand-in binding loading now loads from its own code (its `LoadClass!`/`RequirePackage!`), or
471  /// whose binding's definitions it makes as code, innermost last ([`note_stand_in_file`]).
472  pub stand_in_load_files:     Vec<Vec<String>>,
473  /// The files the stand-in binding loaded last loaded from its own code ([`end_stand_in_load`]): the files it is
474  /// built on, which the paper's copy may declare itself (`binding::content` `copy_is_the_stood_in_file`).
475  pub stand_in_last_files:     Vec<String>,
476  /// The names LaTeXML's own code (`Unknown`, `Pool`, `Binding` origins) `\let`, recorded as it makes them
477  /// ([`let_i`]): a `\let` copies another name's definition, so the name a binding gave it is no longer on the object
478  /// (`owned_by_the_semantic_layer`; aas_support_sty.rs's `\let\subjectheadings\keywords`).
479  pub binding_lets:            rustc_hash::FxHashSet<SymStr>,
480  /// The names a lock's refusal record was written for ([`note_redefined`], `carry_refusal_records`): a
481  /// document's `\let` reads the records only of these.
482  pub refused_names:           rustc_hash::FxHashSet<SymStr>,
483  /// The frontmatter setters whose calls are observed ([`crate::definition::origin::watch_setter_calls`]).
484  pub watched_setters:         rustc_hash::FxHashSet<SymStr>,
485  /// Which names [`watch_meanings`] watches; `None` once one has changed, or with no watch.
486  meaning_watch:               Option<MeaningWatch>,
487  /// The first of [`Self::meaning_watch`]'s names to change.
488  watched_meaning_changed:     Option<SymStr>,
489  /// Each class loaded, with the names its load frame assigned and the classes loaded inside it: what that class
490  /// defines, as its real file does ([`ClassLoadFrame`], `copy_base_class_defines`, `class_layer_definition`).
491  pub class_loads:             Vec<ClassLoadRecord>,
492  /// The class loads open now, as indices into [`State::class_loads`], innermost last ([`ClassLoadFrame`]).
493  pub class_load_frames:       Vec<usize>,
494  /// The stand-in copies whose own `\LoadClass` is open now, innermost last, each with the classes the class load
495  /// open when it began had loaded: a class loaded inside it is a base class of that copy too ([`ClassLoadFrame`]; the
496  /// reviewer's probe nc_chain, `\LoadClass{mybase}` over article), and a copy's first entry holds the classes its
497  /// binding's load loaded ([`open_class_load_classes`]).
498  pub copy_class_loads:        Vec<(u32, Vec<String>)>,
499  /// The open assignment journal, if any ([`begin_assignment_journal`]).
500  journal:                     Option<AssignmentJournal>,
501  /// The open meaning recorders, innermost last ([`begin_meaning_recorder`]): each the meanings assigned since it
502  /// began, with the value each had then.
503  meaning_recorders:           Vec<rustc_hash::FxHashMap<SymStr, Option<Stored>>>,
504}
505
506/// One class loaded ([`ClassLoadFrame`]): its file name (`article.cls`), the names its load frame assigned a macro (the
507/// macro itself, to tell it is still the meaning: compared by [`Rc::ptr_eq`]) or had a definition refused by a lock
508/// (`None`), and the classes loaded while its frame was open, innermost included (a binding's `LoadClass!` of its base
509/// class: ceurart_cls.rs → OmniBus → article).
510#[derive(Debug, Default)]
511pub struct ClassLoadRecord {
512  pub file:    String,
513  pub names:   rustc_hash::FxHashMap<SymStr, Option<Rc<Expandable>>>,
514  pub classes: Vec<String>,
515}
516
517/// What [`note_copy_provides_assignment`] keeps for one stand-in's copy: the copy's file, its own definitions of names
518/// the binding owns (in force only inside its code), and the names and deferring seams logged.
519#[derive(Debug, Default)]
520pub struct CopyProvidesRecord {
521  pub file:          String,
522  /// The stand-in binding the copy is read after (`binding::content::read_stand_in_copy`): a package that binding's
523  /// load loaded first is the copy's own load (`<file>:loaded_by_stand_in`).
524  pub binding:       String,
525  pub overlay:       rustc_hash::FxHashMap<SymStr, Stored>,
526  pub declined:      rustc_hash::FxHashSet<SymStr>,
527  /// The meaning each declined name took back when the copy's frame ended ([`leave_copy_provides_frame`]): the one its
528  /// overlay stands beside, while still in force ([`copy_kept_meaning`]).
529  pub restored:      rustc_hash::FxHashMap<SymStr, Stored>,
530  pub deferred:      rustc_hash::FxHashSet<SymStr>,
531  /// The copy's own `\maketitle`/`\@maketitle` bodies, refused or overlaid as they may be
532  /// ([`copy_provides_title_pages`]).
533  pub title_page:    Vec<Tokens>,
534  /// The copy's own last `\maketitle` body, one of [`Self::title_page`] ([`copy_provides_maketitle`]).
535  pub maketitle:     Option<Tokens>,
536  /// The classes the copy's own code loaded (`\LoadClass`, and the classes loaded inside it: [`ClassLoadFrame`]): the
537  /// real class has the names they define ([`copy_provides_text_default_clashes`]).
538  pub loads_classes: Vec<String>,
539  /// Whether the copy's `\Provides` line routed its request to the binding (OXIDIZED_DESIGN_DIVERGENCES #731 rule 12):
540  /// the declared text names it defines stand (rule 14, [`routed_copy_text_name_yields`]).
541  pub routed:        bool,
542}
543
544/// One frame of a stand-in copy's provides-mode ([`enter_copy_provides_frame`]): the copy (`0`: a suspension), whether
545/// it repeats the frame in force (a hook chunk wrapped twice), and the names whose meanings its code replaced, with
546/// the meanings kept aside.
547#[derive(Debug, Default)]
548pub struct CopyProvidesFrame {
549  pub id:        u32,
550  pub repeat:    bool,
551  pub kept:      Vec<(SymStr, Stored)>,
552  pub kept_keys: rustc_hash::FxHashSet<SymStr>,
553  /// The other names the copy's code assigned in this frame, which may be `\let` to its own version of a kept name
554  /// ([`leave_copy_provides_frame`]).
555  pub assigned:  rustc_hash::FxHashSet<SymStr>,
556  /// The environment's opener the copy's code defined (`\longtable`, [`declare_copy_environment`]), with the binding's
557  /// meaning of it and the file's own meanings the binding declared: where the copy's equals one, the binding's stays.
558  pub opener:    Option<(SymStr, Stored, Vec<Stored>)>,
559}
560impl Default for State {
561  fn default() -> Self { State::with_table_capacity(8_192, 131_072, 512) }
562}
563
564impl State {
565  /// An empty State whose `value`, `meaning` and character-keyed tables are pre-sized as given ([`Default`]'s sizes
566  /// absorb the dump load; [`shrink_thread_state`] gives zero).
567  fn with_table_capacity(value: usize, meaning: usize, chars: usize) -> Self {
568    let top_frame = UndoFrame {
569      locked: true,
570      ..UndoFrame::default()
571    };
572    // Room for the top frame alone: a shrunk State (`shrink_thread_state`) holds no more; a converting one grows.
573    let mut undo_vdq = VecDeque::with_capacity(1);
574    undo_vdq.push_front(top_frame);
575
576    State {
577      // Tables — pre-size the two largest to absorb dump load. The
578      // `meaning` table receives 109,863 entries from latex.dump
579      // alone, so without pre-sizing it doubles 5+ times during
580      // dump load (each rehash is O(N)). `value` receives several
581      // thousand register/state-key entries through the lifecycle.
582      // Effective capacity (FxHashMap, 0.875 load factor): 131072 → ~115k.
583      value:                   HashMap::with_capacity_and_hasher(value, Default::default()),
584      meaning:                 HashMap::with_capacity_and_hasher(meaning, Default::default()),
585      stash:                   HashMap::default(),
586      stash_active:            HashMap::default(),
587      // Char-keyed tables: ASCII alphabet + a smattering of high-codepoint
588      // entries get installed (textcomp + ts1enc.dfu populate ~200-300
589      // entries each). Pre-size to 512 to skip the 8→16→…→256→512
590      // doubling chain on startup.
591      catcode:                 HashMap::with_capacity_and_hasher(chars, Default::default()),
592      mathcode:                HashMap::with_capacity_and_hasher(chars, Default::default()),
593      sfcode:                  HashMap::with_capacity_and_hasher(chars, Default::default()),
594      lccode:                  HashMap::with_capacity_and_hasher(chars, Default::default()),
595      uccode:                  HashMap::with_capacity_and_hasher(chars, Default::default()),
596      delcode:                 HashMap::with_capacity_and_hasher(chars, Default::default()),
597      // Table bookkeeping
598      undo:                    undo_vdq,
599      // stateful runtime - data structures
600      prefixes:                HashMap::default(),
601      tag_properties:          HashMap::default(),
602      indirect_model:          None,
603      pending_resources:       Vec::new(),
604      // stateful runtime - simple fields
605      verbosity:               0,
606      input_encoding:          None,
607      // strict: false,
608      // include_comments: true,
609      search_paths:            VecDeque::new(),
610      graphics_paths:          VecDeque::new(),
611      // include_styles: false,
612      nomathparse:             false,
613      if_count:                0,
614      if_stack:                Vec::new(),
615      if_limit:                0,
616      absorb_count:            0,
617      absorb_limit:            0,
618      source_map:              false,
619      source_table:            Vec::new(),
620      opened_sources:          HashSet::default(),
621      bindings_dispatch:       None,
622      extra_bindings_dispatch: None,
623      local_binding_finder:    None,
624      binding_names:           Vec::new(),
625      label_mapping_hook:      None,
626      fallback_meanings:       rustc_hash::FxHashMap::default(),
627      provide_only_assigned:   rustc_hash::FxHashSet::default(),
628      provide_only_loaded:     Vec::new(),
629      borrowed_loaded:         Vec::new(),
630      copy_provides_copies:    Vec::new(),
631      copy_provides_frames:    Vec::new(),
632      stand_in_meanings:       rustc_hash::FxHashSet::default(),
633      stand_in_base_defaults:  rustc_hash::FxHashSet::default(),
634      stand_in_loads:          Vec::new(),
635      stand_in_last_load:      Vec::new(),
636      stand_in_load_files:     Vec::new(),
637      stand_in_last_files:     Vec::new(),
638      binding_lets:            rustc_hash::FxHashSet::default(),
639      refused_names:           rustc_hash::FxHashSet::default(),
640      watched_setters:         rustc_hash::FxHashSet::default(),
641      meaning_watch:           None,
642      watched_meaning_changed: None,
643      class_loads:             Vec::new(),
644      class_load_frames:       Vec::new(),
645      copy_class_loads:        Vec::new(),
646      journal:                 None,
647      meaning_recorders:       Vec::new(),
648    }
649  }
650}
651
652thread_root! {
653fn std_state_root() -> RefCell<State> = RefCell::new(State::new(StateOptions {
654  catcodes: Some(Catcodes::Standard),
655  ..StateOptions::default()
656}));
657}
658thread_root! {
659fn sty_state_root() -> RefCell<State> = RefCell::new(State::new(StateOptions {
660  catcodes: Some(Catcodes::Style),
661  ..StateOptions::default()
662}));
663}
664thread_root! {
665fn state_root() -> RefCell<State> = RefCell::new(State::new(StateOptions {
666  catcodes: Some(Catcodes::Standard),
667  ..StateOptions::default()
668}));
669}
670
671/// Eagerly initialize this thread's `STD_STATE`/`STY_STATE` catcode-regime
672/// templates. They are accessed mid-conversion on catcode switches
673/// (`\makeatletter`, verbatim, …); each one's initializer runs
674/// `State::new`, which interns via the arena. Forcing them at conversion
675/// entry — AFTER [`arena::force_init`](crate::common::arena::force_init) —
676/// keeps them from initializing re-entrantly mid-expansion, the macOS
677/// thread-local hazard behind issue #217. (The active `STATE` is
678/// already forced by `set_state` in `Core::new`.) No behavioral change on
679/// Linux.
680pub(crate) fn force_init() {
681  std_state_root();
682  sty_state_root();
683}
684
685macro_rules! state {
686  () => {
687    state_root().borrow()
688  };
689}
690macro_rules! state_mut {
691  () => {
692    state_root().borrow_mut()
693  };
694}
695macro_rules! sty_state_mut {
696  () => {
697    sty_state_root().borrow_mut()
698  };
699}
700macro_rules! std_state_mut {
701  () => {
702    std_state_root().borrow_mut()
703  };
704}
705
706/// state fields allowed for customization during construction
707#[derive(Default)]
708pub struct StateOptions {
709  pub model:            Option<Model>,
710  pub verbosity:        Option<i32>,
711  pub strict:           Option<bool>,
712  pub include_comments: Option<bool>,
713  pub include_styles:   Option<bool>,
714  pub nomathparse:      Option<bool>,
715  pub source_map:       Option<bool>,
716  pub documentid:       Option<String>,
717  pub search_paths:     Option<Vec<String>>,
718  pub graphics_paths:   Option<Vec<String>>,
719  pub catcodes:         Option<Catcodes>,
720  pub input_encoding:   Option<String>,
721}
722
723// Public interface: package-access methods, for an implied thread-local singleton STATE
724
725// Private interface: struct-access methods, for a concrete piece of State data
726
727impl State {
728  pub fn new(options: StateOptions) -> Self {
729    use crate::token::Catcode::*;
730
731    // Setup default catcodes.
732    let catcode_profile = match options.catcodes {
733      None => Catcodes::Standard,
734      Some(cp) => cp,
735    };
736
737    let mut catcodes: HashMap<char, Catcode> = HashMap::default();
738    match catcode_profile {
739      Catcodes::Standard | Catcodes::Style => {
740        catcodes.insert('\\', ESCAPE);
741        catcodes.insert('{', BEGIN);
742        catcodes.insert('}', END);
743        catcodes.insert('$', MATH);
744        catcodes.insert('&', ALIGN);
745        catcodes.insert('\r', EOL);
746        catcodes.insert('#', PARAM);
747        catcodes.insert('^', SUPER);
748        catcodes.insert('_', SUB);
749        catcodes.insert(' ', SPACE);
750        catcodes.insert('\t', SPACE);
751        catcodes.insert('%', COMMENT);
752        catcodes.insert('~', ACTIVE);
753        // NUL (`\^^@`, U+0000): Perl LaTeXML's default is catcode 12 (OTHER),
754        // NOT the TeXbook's 9 (IGNORE). We follow Perl (ground truth) so that
755        // `\^^@`/`` `^^@ `` reads code 0 (TeXbook 9 would *drop* the NUL token,
756        // making `` `^^@ `` skip to the next token — `\relax` etc. — and return
757        // a bogus code; xint's `\romannumeral`&&@` expansion idiom needs 0).
758        // Real-world bbl files (e.g. astro-ph0004127's spie4012-01a.bbl) carry
759        // stray NULs from BibTeX `\"u`-mangling; as OTHER they become harmless
760        // literal chars (stripped at XML serialization), matching Perl —
761        // crucially NOT ESCAPE, so no bogus `\uninger`-style CS forms. An
762        // explicit `\catcode`^^Q=9` (user/package) is still honored; only the
763        // *default* changes.
764        catcodes.insert('\0', OTHER);
765        catcodes.insert('\u{000c}', ACTIVE);
766        for c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".chars() {
767          catcodes.insert(c, LETTER);
768        }
769      },
770      Catcodes::None => {},
771    }
772    if catcode_profile == Catcodes::Style {
773      catcodes.insert('@', LETTER);
774    }
775
776    let mut value_table = HashMap::default();
777    let mut specials_vdq = VecDeque::new();
778    specials_vdq.push_front(Stored::Chars(Box::new([
779      '^', '_', '~', '&', '$', '#', '\'',
780    ])));
781    value_table.insert(arena::pin_static("SPECIALS"), specials_vdq);
782
783    let mut catcodes_typed: Table = HashMap::default();
784    for (k, v) in catcodes {
785      let mut vdq = VecDeque::new();
786      vdq.push_front(Stored::Catcode(v));
787      catcodes_typed.insert(arena::pin_char(k), vdq);
788    }
789
790    // Basic defaults
791    if let Some(model) = options.model {
792      model::set_model(model);
793    };
794    let verbosity = options.verbosity.unwrap_or(0);
795    // let strict = options.strict.unwrap_or(false);
796    // INCLUDE_COMMENTS: Perl defaults to true (Core.pm L143).
797    // T_COMMENT tokens are now properly converted to XML comment nodes
798    // via Document::insert_comment using raw libxml2 FFI.
799    // Note: Only set when explicitly specified, because STY_STATE/STD_STATE
800    // use default options and state rotation (swap) would overwrite the
801    // main state's INCLUDE_COMMENTS value.
802    let include_comments = options.include_comments;
803    // let include_styles = options.include_styles.unwrap_or(false);
804    let nomathparse = options.nomathparse.unwrap_or(false);
805    let source_map = options.source_map.unwrap_or(false);
806
807    // Perl Core.pm L50-52: `SEARCHPATHS => [map { pathname_absolute(...) } '.',
808    // @searchpaths]` — the current working directory is ALWAYS searched, and
809    // FIRST (it takes precedence over the `--path` dirs). A `--path` entry
810    // ending in `//` is the kpsewhich recursive-search marker; preserve it
811    // across canonicalization (strip it, canonicalize the base, re-append) so
812    // `candidate_pathnames` can expand the marker to the whole subtree.
813    // `.` is the working directory by its physical name, as `SOURCEDIRECTORY` is (`pathname::canonicalize`): Unix's
814    // `getcwd` already is, while Windows' may be an 8.3 alias (`C:\Users\RUNNER~1\…`, GitHub's runners) of the long
815    // name, under which one file was found twice — an image listed again as `../../RUNNER~1/…`. The `--path`
816    // directories stay as written: resolving their symlinks would change what Linux prints.
817    let cwd = pathname::canonicalize(".")
818      .map(|cwd| cwd.to_string_lossy().into_owned())
819      .unwrap_or_else(|_| String::from("."));
820    // A confined conversion never searches the working directory unless it is one of its roots.
821    let cwd = pathname::cwd_allowed().then_some(cwd);
822    let search_paths: VecDeque<String> = cwd
823      .into_iter()
824      .chain(options.search_paths.into_iter().flatten())
825      .map(|p| match p.strip_suffix("//") {
826        Some(base) => format!("{}//", pathname::absolute(&pathname::canonical(base))),
827        None => pathname::absolute(&pathname::canonical(&p)),
828      })
829      .collect();
830    let graphics_paths = match options.graphics_paths {
831      None => VecDeque::new(),
832      Some(paths) => paths
833        .iter()
834        .map(|p| pathname::absolute(&pathname::canonical(p)))
835        .collect(),
836    };
837
838    let mut state = State {
839      value: value_table,
840      catcode: catcodes_typed,
841      verbosity,
842      // strict,
843      // include_comments,
844      search_paths,
845      graphics_paths,
846      // include_styles,
847      input_encoding: options.input_encoding,
848      nomathparse,
849      source_map,
850      ..State::default()
851    };
852    // INITEX-equivalent defaults — mirror Perl `State.pm:128-137`.
853    // Sets letter/digit mathcodes (class 7, family 1 for letters / 0 for digits),
854    // upper/lowercase mappings, and sfcode=999 for uppercase letters. Without
855    // these, dump-load path leaves letter mathcodes unset (plain.dump.txt only
856    // captures the 57 plain.tex OVERRIDES), so `\cal abc` math falls through
857    // the text path and loses meaning/role attributes. NODUMP path used to set
858    // these via plain_base.rs L17-41 only — not Perl-faithful since INITEX
859    // owns these (TeXbook ch.17 p309). Setting them here makes both paths
860    // consistent and matches Perl's State::new behaviour.
861    for c in b'0'..=b'9' {
862      state.assign_internal(
863        TableName::Mathcode,
864        arena::pin_char(c as char),
865        Stored::Charcode(0x7000 + c as u16),
866        None,
867      );
868    }
869    for c in b'a'..=b'z' {
870      let big = c - 32;
871      state.assign_internal(
872        TableName::Mathcode,
873        arena::pin_char(c as char),
874        Stored::Charcode(0x7100 + c as u16),
875        None,
876      );
877      state.assign_internal(
878        TableName::Mathcode,
879        arena::pin_char(big as char),
880        Stored::Charcode(0x7100 + big as u16),
881        None,
882      );
883      state.assign_internal(
884        TableName::Uccode,
885        arena::pin_char(c as char),
886        Stored::Charcode(big as u16),
887        None,
888      );
889      state.assign_internal(
890        TableName::Lccode,
891        arena::pin_char(big as char),
892        Stored::Charcode(c as u16),
893        None,
894      );
895      state.assign_internal(
896        TableName::Sfcode,
897        arena::pin_char(big as char),
898        Stored::Charcode(999),
899        None,
900      );
901    }
902    // TODO: should these be *fields* in state or really as in Perl - globally assigned values?
903    state.assign_value(
904      "DOCUMENTID",
905      options.documentid.unwrap_or_default(),
906      Some(Scope::Global),
907    );
908    // Perl Core.pm L143: assignValue(INCLUDE_COMMENTS => ..., 'global')
909    // Only set when explicitly specified (not for STY_STATE/STD_STATE defaults)
910    if let Some(ic) = include_comments {
911      state.assign_value("INCLUDE_COMMENTS", ic, Some(Scope::Global));
912    }
913    // Perl Core.pm L47: INCLUDE_PATH_PIS (default true) — emit searchpath PIs
914    state.assign_value("INCLUDE_PATH_PIS", true, Some(Scope::Global));
915    // Perl Core.pm L43: STRICT (default false)
916    if let Some(strict) = options.strict {
917      state.assign_value("STRICT", strict, Some(Scope::Global));
918    }
919    // Perl Core.pm L55-57: `--includestyles` fans out to BOTH INCLUDE_STYLES
920    // and INCLUDE_CLASSES (both default 0), so it raw-loads .sty packages AND
921    // .cls classes from the search path. Faithful to Perl — its own
922    // `# … accept both classes and styles?` hedge notwithstanding, the code
923    // sets both, and INCLUDE_CLASSES is what unlocks raw .cls in LoadClass. Assigned unset too (`|| 0`), before any
924    // load: a format build's raw load then puts back what it found, and its dump holds neither key.
925    let include_styles = options.include_styles.unwrap_or(false);
926    state.assign_value("INCLUDE_STYLES", include_styles, Some(Scope::Global));
927    state.assign_value("INCLUDE_CLASSES", include_styles, Some(Scope::Global));
928    // Perl Core.pm L62: NOMATHPARSE
929    state.assign_value("NOMATHPARSE", nomathparse, Some(Scope::Global));
930    // Perl Core.pm L61: PERL_INPUT_ENCODING (default utf-8)
931    let enc = state.input_encoding.as_deref().unwrap_or("utf-8");
932    state.assign_value(
933      "PERL_INPUT_ENCODING",
934      Stored::String(arena::pin(enc)),
935      Some(Scope::Global),
936    );
937
938    // Perl Core.pm L53: $state->assignValue(GRAPHICSPATHS => [map {…} @{$opts{graphicspaths}}])
939    // Mirror with a VecDequeStored of String entries; subsequent push/unshift
940    // operations in `\graphicspath`, `\svgpath`, and Core.pm-equivalent source
941    // directory prepends will append/prepend to this same list.
942    if !state.graphics_paths.is_empty() {
943      let vdq: VecDeque<Stored> = state
944        .graphics_paths
945        .iter()
946        .map(|p| Stored::String(arena::pin(p)))
947        .collect();
948      state.assign_internal(
949        TableName::Value,
950        arena::pin("GRAPHICSPATHS"),
951        Stored::VecDequeStored(vdq),
952        Some(Scope::Global),
953      );
954    }
955
956    // SEARCHPATHS mirrors GRAPHICSPATHS: a group-scoped value list (Perl
957    // `AssignValue(SEARCHPATHS…)`, local-by-default) rather than a plain field,
958    // so an `\import`/`\subimport` group reverts its change at `}` while a
959    // package's global add persists (#561). Seeded Global from the `search_paths`
960    // field (`.` + the `--path` dirs); `get_search_paths` reads the value table.
961    {
962      let vdq: VecDeque<Stored> = state
963        .search_paths
964        .iter()
965        .map(|p| Stored::String(arena::pin(p)))
966        .collect();
967      state.assign_internal(
968        TableName::Value,
969        arena::pin("SEARCHPATHS"),
970        Stored::VecDequeStored(vdq),
971        Some(Scope::Global),
972      );
973    }
974
975    state
976  }
977
978  /// borrow/get the named table
979  pub fn table(&self, name: TableName) -> &Table {
980    use self::TableName::*;
981    match name {
982      Meaning => &self.meaning,
983      Value => &self.value,
984      Catcode => &self.catcode,
985      Mathcode => &self.mathcode,
986      Sfcode => &self.sfcode,
987      Lccode => &self.lccode,
988      Uccode => &self.uccode,
989      Delcode => &self.delcode,
990      Stash => &self.stash,
991      StashActive => &self.stash_active,
992    }
993  }
994  /// mutably borrow/get the named table
995  pub fn table_mut(&mut self, name: TableName) -> &mut Table {
996    use self::TableName::*;
997    match name {
998      Meaning => &mut self.meaning,
999      Value => &mut self.value,
1000      Catcode => &mut self.catcode,
1001      Mathcode => &mut self.mathcode,
1002      Sfcode => &mut self.sfcode,
1003      Lccode => &mut self.lccode,
1004      Uccode => &mut self.uccode,
1005      Delcode => &mut self.delcode,
1006      Stash => &mut self.stash,
1007      StashActive => &mut self.stash_active,
1008    }
1009  }
1010
1011  /// Perl DumpFile equivalent: Take a snapshot of the current state.
1012  /// Returns a HashMap mapping (table_name, key) → Stored value.
1013  /// Only captures the front (current) value of each key.
1014  /// Used before processing latex.ltx to diff what changed.
1015  pub fn snapshot(&self) -> rustc_hash::FxHashMap<(TableName, SymStr), Stored> {
1016    let tables = [
1017      TableName::Value,
1018      TableName::Meaning,
1019      TableName::Catcode,
1020      TableName::Mathcode,
1021      TableName::Sfcode,
1022      TableName::Lccode,
1023      TableName::Uccode,
1024      TableName::Delcode,
1025    ];
1026    let mut snap = rustc_hash::FxHashMap::default();
1027    for &tname in &tables {
1028      let table = self.table(tname);
1029      for (key, values) in table {
1030        if let Some(front) = values.front() {
1031          let value = match front {
1032            // A font's parameter array is written in place: the snapshot
1033            // keeps a copy of its own, or no later change would show.
1034            Stored::FontDimens(params) => {
1035              Stored::FontDimens(Rc::new(RefCell::new(params.borrow().clone())))
1036            },
1037            value => value.clone(),
1038          };
1039          snap.insert((tname, *key), value);
1040        }
1041      }
1042    }
1043    snap
1044  }
1045
1046  /// Perl DumpFile equivalent: Compute the diff between current state and a snapshot.
1047  /// Returns only entries that CHANGED since the snapshot was taken.
1048  /// Skips entries that contain closures (Primitive, Constructor, Conditional)
1049  /// since those can't be serialized — they come from Rust engine code.
1050  pub fn diff_from_snapshot(
1051    &self,
1052    snap: &rustc_hash::FxHashMap<(TableName, SymStr), Stored>,
1053  ) -> Vec<(TableName, SymStr, Stored)> {
1054    let tables = [
1055      TableName::Value,
1056      TableName::Meaning,
1057      TableName::Catcode,
1058      TableName::Mathcode,
1059      TableName::Sfcode,
1060      TableName::Lccode,
1061      TableName::Uccode,
1062      TableName::Delcode,
1063    ];
1064    let mut diff = Vec::new();
1065    for &tname in &tables {
1066      let table = self.table(tname);
1067      for (key, values) in table {
1068        if let Some(current) = values.front() {
1069          let key_pair = (tname, *key);
1070          let changed = match snap.get(&key_pair) {
1071            None => true, // new entry
1072            Some(prev) => {
1073              // Perl diffs the SERIALIZED dump form against the bootstrap
1074              // snapshot (TeX_Job.pool.ltxml:126-200: a key whose `Dump`
1075              // string equals the `<fmt>_bootstrap` baseline is omitted), so
1076              // a raw redefinition to an identical body — latex.ltx:18386
1077              // `\gdef\@currnamestack{}` over the bootstrap's empty macro —
1078              // is NOT dumped. A `Debug` comparison also sees definition
1079              // metadata (the `:redefined@nargs` lock records of batch 56z)
1080              // and reported such entries as changed; the dumped empty
1081              // `\@currnamestack` then clobbered the live file stack of the
1082              // preload being read (a4wide 3 → 35 errors, cortex 2026-09-17).
1083              match (
1084                crate::dump_writer::serialize_stored(current),
1085                crate::dump_writer::serialize_stored(prev),
1086              ) {
1087                (Some(a), Some(b)) => a != b,
1088                _ => format!("{:?}", current) != format!("{:?}", prev),
1089              }
1090            },
1091          };
1092          if changed && is_serializable(current) {
1093            diff.push((tname, *key, current.clone()));
1094          }
1095        }
1096      }
1097    }
1098    diff
1099  }
1100
1101  // needed for assign_internal, so keeping it as a object method
1102  /// gets the current value of a named prefix
1103  pub fn get_prefix(&self, prefix: &str) -> bool { self.get_prefix_sym(arena::pin(prefix)) }
1104
1105  /// `get_prefix` variant with a pre-pinned SymStr (see `crate::pin!`) —
1106  /// `assign_internal` probes the `global` prefix on every unscoped
1107  /// assignment, so the per-call `arena::pin` there was pure overhead.
1108  pub fn get_prefix_sym(&self, prefix: SymStr) -> bool {
1109    match self.prefixes.get(&prefix) {
1110      Some(b) => *b,
1111      _ => false,
1112    }
1113  }
1114
1115  /// Record `key`'s bindings in the open assignment journal before its first assignment since the journal began, and
1116  /// end the watch held ([`watch_state`]).
1117  #[inline]
1118  fn journal_touch(&mut self, table_name: TableName, key: SymStr) {
1119    if table_name == TableName::Meaning && !self.meaning_recorders.is_empty() {
1120      self.record_meaning(key);
1121    }
1122    if WRITES_WATCHED.get() {
1123      self.journal_save(table_name, key);
1124    }
1125  }
1126
1127  /// [`Self::journal_touch`], for an assignment whose scope is known: `global`, whether it is global, goes to the meaning
1128  /// log ([`begin_meaning_log`]), when a field's token is being invoked. The log lives on the journal, a rehearsal's, so an
1129  /// assignment outside one pays nothing for it: the test sits past the guard's.
1130  #[inline]
1131  fn journal_touch_assignment(&mut self, table_name: TableName, key: SymStr, global: bool) {
1132    if table_name == TableName::Meaning && !self.meaning_recorders.is_empty() {
1133      self.record_meaning(key);
1134    }
1135    if WRITES_WATCHED.get() {
1136      if table_name == TableName::Meaning
1137        && JOURNAL_GUARD_LIVE.get()
1138        && let Some(log) = self
1139          .journal
1140          .as_mut()
1141          .and_then(|journal| journal.meaning_log.as_mut())
1142        && let Some(by) = get_current_token().filter(|t| t.prov != 0)
1143      {
1144        log.push(MeaningAssigned { key, global, by });
1145      }
1146      self.journal_save(table_name, key);
1147    }
1148  }
1149
1150  /// Save `key`'s bindings in the live journal, unless they are already, and end the watch held ([`watch_state`]): out
1151  /// of line, a journal being open only for a rehearsal or a replay, a watch held only for a title-page reading.
1152  #[cold]
1153  #[inline(never)]
1154  fn journal_save(&mut self, table_name: TableName, key: SymStr) {
1155    note_state_change(table_name, key);
1156    // (a journal whose guard is gone is stale: nothing records into it until the next begin discards it)
1157    if !JOURNAL_GUARD_LIVE.get() {
1158      return;
1159    }
1160    let Some(journal) = self.journal.as_ref() else {
1161      return;
1162    };
1163    if journal.saved.contains_key(&(table_name, key)) {
1164      return;
1165    }
1166    let mut values = self.table(table_name).get(&key).cloned();
1167    // (a font's parameter array is written in place, `set_font_parameter`: saved as a copy of its own)
1168    if let Some(values) = values.as_mut().filter(|_| table_name == TableName::Value) {
1169      for value in values {
1170        if let Stored::FontDimens(params) = value {
1171          let copy = params.borrow().clone();
1172          *value = Stored::FontDimens(Rc::new(RefCell::new(copy)));
1173        }
1174      }
1175    }
1176    let counts: Vec<(u64, usize)> = self
1177      .undo
1178      .iter()
1179      .filter(|frame| journal.frames.contains(&frame.id))
1180      .filter_map(|frame| frame.table(table_name).get(&key).map(|n| (frame.id, *n)))
1181      .collect();
1182    let standing =
1183      (table_name == TableName::Meaning).then(|| self.fallback_meanings.get(&key).copied());
1184    if let Some(journal) = self.journal.as_mut() {
1185      journal.saved.insert((table_name, key), (values, counts));
1186      if let Some(standing) = standing {
1187        journal.fallback.insert(key, standing);
1188      }
1189    }
1190  }
1191
1192  /// Record `key`'s meaning in each open meaning recorder before its first assignment since that recorder began
1193  /// ([`begin_meaning_recorder`]).
1194  #[cold]
1195  fn record_meaning(&mut self, key: SymStr) {
1196    let then = self
1197      .meaning
1198      .get(&key)
1199      .and_then(|values| values.front().cloned());
1200    for recorder in &mut self.meaning_recorders {
1201      recorder.entry(key).or_insert_with(|| then.clone());
1202    }
1203  }
1204
1205  /// The `Scope::Local` binding itself: record one undo entry in the top
1206  /// frame (unless the key is already bound there — then replace) and push the
1207  /// value. Reached by every local assignment, and DIRECTLY by the save-frame
1208  /// bookkeeping ([`assign_frame_value_sym`]): tex.web §1214 lets
1209  /// `\globaldefs` (and the `\global` prefix, §1211) globalize an
1210  /// ASSIGNMENT made by `prefixed_command`, never the save stack (§274
1211  /// `new_save_level` / §282 `unsave`), so a group's own records must stay
1212  /// local whatever `\globaldefs` says. Perl (State.pm:144-151) routes its
1213  /// frame bookkeeping through the same override, and under `\globaldefs=1`
1214  /// (msc.sty:2616 `\msc@global@set`, tikzexternalshared, latex.ltx's
1215  /// `\math@fonts` block) a closed `{` group kept reporting itself as the
1216  /// current frame — the D12 "close non-boxing group" cascades.
1217  pub(crate) fn assign_local_unconditional(
1218    &mut self,
1219    table_name: TableName,
1220    key: SymStr,
1221    value: Stored,
1222  ) {
1223    self.journal_touch(table_name, key);
1224    // Again, split the logic as 1) bookkeeping in undo, then 2) operations in state_tables
1225    let mut is_replace = false;
1226    // 1. Undo mutable logic
1227    if let Some(current_frame) = self.undo.front_mut() {
1228      let current_frame_table = current_frame.table_mut(table_name);
1229
1230      is_replace = current_frame_table.get(&key).unwrap_or(&0) > &0;
1231      if is_replace { // If the value was previously assigned in this frame
1232        // we do this in 2.1, then proceed to 2.2
1233      } else {
1234        // Otherwise, push new value & set 1 to be undone
1235        current_frame_table.insert(key, 1);
1236        //  And push new binding in 2.2
1237      }
1238    }
1239    // 2. state_table mutable logic
1240    let state_table = self.table_mut(table_name);
1241    let defs = state_table.entry(key).or_default();
1242    if is_replace {
1243      // 2.1. Replace the value, i.e. remove existing one
1244      defs.pop_front();
1245    }
1246    // 2.2 Add new value
1247    defs.push_front(value);
1248  }
1249
1250  /// [`watch_meanings`]' look at an assignment of `key`'s meaning. A scope move or a copy onto itself is no change
1251  /// (`hoist_top_frame_delta`, under the lazy LaTeX.pool load); nor is a first definition: the name undefined, or, for a
1252  /// name [`WatchedName::RelaxIsUnset`], the `\relax` a `\csname` made it (`\exp_args:NNc`).
1253  #[inline]
1254  fn watch_meaning(&mut self, watched: fn(&str) -> WatchedName, key: SymStr, value: &Stored) {
1255    let kind = arena::with(key, watched);
1256    if kind != WatchedName::No
1257      && let Some(standing) = self.meaning.get(&key).and_then(|stack| stack.front())
1258      && !same_meaning(standing, value)
1259      && !(kind == WatchedName::RelaxIsUnset
1260        && self
1261          .meaning
1262          .get(&pin!("\\relax"))
1263          .and_then(|stack| stack.front())
1264          .is_some_and(|relax| same_meaning(standing, relax)))
1265    {
1266      self.meaning_watch = None;
1267      self.watched_meaning_changed = Some(key);
1268    }
1269  }
1270
1271  pub(crate) fn assign_internal(
1272    &mut self,
1273    table_name: TableName,
1274    key: SymStr,
1275    value: Stored,
1276    mut scope_opt: Option<Scope>,
1277  ) {
1278    // (a meaning a fallback class, a kernel stub or a borrowed package installs, until anything else assigns the name:
1279    // `fallback_meanings`; an open journal records the standing first)
1280    if table_name == TableName::Meaning {
1281      self.journal_touch(table_name, key);
1282      let origin = crate::definition::origin::current_origin();
1283      // (not LaTeXML's own code, which every conversion's preload runs and which assigns no such name)
1284      if let Some(watched) = self.meaning_watch
1285        && matches!(
1286          origin,
1287          crate::definition::origin::DefinitionOrigin::File
1288            | crate::definition::origin::DefinitionOrigin::Document
1289            | crate::definition::origin::DefinitionOrigin::Format
1290        )
1291        && arena::first_bytes(key).is_some_and(|[_, second, third]| watched.may_take(second, third))
1292      {
1293        self.watch_meaning(watched.select, key, &value);
1294      }
1295      if matches!(
1296        origin,
1297        crate::definition::origin::DefinitionOrigin::Fallback
1298          | crate::definition::origin::DefinitionOrigin::Stub
1299          | crate::definition::origin::DefinitionOrigin::Borrowed
1300      ) {
1301        self.fallback_meanings.insert(key, origin);
1302      } else if !self.fallback_meanings.is_empty() {
1303        self.fallback_meanings.remove(&key);
1304      }
1305      if crate::definition::origin::provide_only() {
1306        self.provide_only_assigned.insert(key);
1307      }
1308      // (a macro a class's load frame defines — its binding's, its raw file's, a package's it loads — not LaTeXML's
1309      // kernel layers: `ClassLoadFrame`)
1310      if let Some(&class) = self.class_load_frames.last()
1311        && matches!(value, Stored::Expandable(_))
1312        && !matches!(
1313          origin,
1314          crate::definition::origin::DefinitionOrigin::Unknown
1315            | crate::definition::origin::DefinitionOrigin::Plain
1316            | crate::definition::origin::DefinitionOrigin::LatexDump
1317            | crate::definition::origin::DefinitionOrigin::Pool
1318            | crate::definition::origin::DefinitionOrigin::Format
1319            | crate::definition::origin::DefinitionOrigin::Document
1320        )
1321        && let Stored::Expandable(defn) = &value
1322        && let Some(record) = self.class_loads.get_mut(class)
1323      {
1324        record.names.insert(key, Some(Rc::clone(defn)));
1325      }
1326      if crate::definition::origin::stand_in_loading() {
1327        self.stand_in_meanings.insert(key);
1328        if crate::definition::origin::stand_in_base_class() {
1329          self.stand_in_base_defaults.insert(key);
1330        } else if !self.stand_in_base_defaults.is_empty() {
1331          self.stand_in_base_defaults.remove(&key);
1332        }
1333        if crate::definition::origin::stand_in_own_code()
1334          && let Some(load) = self.stand_in_loads.last_mut()
1335        {
1336          load.push(key);
1337        }
1338      }
1339    } else if table_name == TableName::Value && matches!(value, Stored::Bool(true)) {
1340      // (`<file>_loaded`, `load_ltxml`: a file loaded under the provide-only guard, or by a borrow)
1341      let provide_only = crate::definition::origin::provide_only();
1342      let borrowed = crate::definition::origin::current_origin()
1343        == crate::definition::origin::DefinitionOrigin::Borrowed;
1344      if provide_only || borrowed {
1345        arena::with(key, |name| {
1346          if let Some(file) = name.strip_suffix("_loaded")
1347            && !file.ends_with(".ltxml")
1348            && !file.ends_with("_raw")
1349          {
1350            for (on, list) in [
1351              (provide_only, &mut self.provide_only_loaded),
1352              (borrowed, &mut self.borrowed_loaded),
1353            ] {
1354              if on && !list.iter().any(|f| f == file) {
1355                list.push(file.to_string());
1356              }
1357            }
1358          }
1359        });
1360      }
1361    }
1362    // hotcode lookupDefinition for \globaldefs,
1363    // since this is called extremely often and should be highly standardized.
1364    // TeX semantics: positive → all assignments global, negative → \global
1365    // ignored, zero → no override. `\globaldefs` is a Number register, so the
1366    // stored variant is `Stored::Number`, NOT `Stored::Int` — Perl's `==`
1367    // coerces both, Rust must unwrap explicitly. Perl `State.pm:144-151` uses
1368    // strict `==1`/`==-1`; we slightly broaden to TeX's sign-based rule
1369    // (matches behavior for the canonical `\globaldefs=1`/`\globaldefs=-1`
1370    // uses while also handling rare `\globaldefs=2` etc).
1371    // `Scope::Named(_)` and `Scope::InPlace` are preserved per Perl's "ONLY
1372    // override global/local/undef" rule (State.pm:146 — `$scope ne 'global' &&
1373    // $scope ne 'local'` short-circuits the override): an in-place mutation of
1374    // the existing binding is NOT re-scoped by `\globaldefs`.
1375    // Without this: pgfplots' `\pgfplots@pop@next@legend`
1376    // (`\def\foo{{\globaldefs=1 \let\x=\relax}}`) silently drops the `\let`
1377    // on group exit, leaving `\pgfplots@curlegend`/`@curplotlist` undefined
1378    // and looping `\pgfplots@createlegend` at the digest wall-clock cap.
1379    let preserve = matches!(scope_opt, Some(Scope::Named(_) | Scope::InPlace));
1380    if !preserve
1381      && let Some(globaldefs) = self.value.get(&pin!("\\globaldefs"))
1382      && let Some(global_value) = globaldefs.front()
1383    {
1384      let int_value: i64 = match *global_value {
1385        Stored::Int(v) => v,
1386        Stored::Number(n) => n.0,
1387        _ => 0,
1388      };
1389      if int_value > 0 {
1390        scope_opt = Some(Scope::Global);
1391      } else if int_value < 0 {
1392        scope_opt = Some(Scope::Local);
1393      }
1394    }
1395    // TRACE: watch for cleanup:w
1396    // regular check, local scope is default, unless a global prefix is set
1397    let mut scope = match scope_opt {
1398      Some(s) => s,
1399      None => {
1400        if self.get_prefix_sym(pin!("global")) {
1401          Scope::Global
1402        } else {
1403          Scope::Local
1404        }
1405      },
1406    };
1407    // A build-time local binding at the build's BASE level is global in
1408    // effect: eager builds after digestion, when no group can pop it. The
1409    // streaming driver interleaves the build with digestion, so the same
1410    // binding would land in a digestion frame and vanish at that group's end
1411    // (`with_build_floor`).
1412    if matches!(scope, Scope::Local) && BUILD_FLOOR.get() == Some(self.undo.len()) {
1413      scope = Scope::Global;
1414    }
1415    self.journal_touch_assignment(table_name, key, matches!(scope, Scope::Global));
1416    match scope {
1417      Scope::Global => {
1418        // Remove bindings made in all frames down-to & including the next lower locked frame (State.pm:156-168);
1419        // the last frame's count is read and set to 1 in one probe, and a frame that never counted the key is not probed.
1420        let mut undo_count = 0;
1421        let depth = self.undo.len();
1422        for (index, frame) in self.undo.iter_mut().enumerate() {
1423          let is_last = frame.locked || index + 1 == depth;
1424          let frame_table = frame.table_mut(table_name);
1425          if is_last {
1426            // whatever is left -- if anything -- should be bindings below the locked frame.
1427            undo_count += frame_table.insert(key, 1).unwrap_or(0);
1428            break;
1429          } else if frame_table.may_hold(key)
1430            && let Some(n) = frame_table.remove(&key)
1431          {
1432            undo_count += n;
1433          }
1434        }
1435        // Undo the bindings `key` had in those frames, then push the new one: one probe of the state table.
1436        let defs = self.table_mut(table_name).entry(key).or_default();
1437        for _ in 0..undo_count {
1438          defs.pop_front();
1439        }
1440        defs.push_front(value);
1441      },
1442      Scope::Local => self.assign_local_unconditional(table_name, key, value),
1443      Scope::InPlace => {
1444        // Perl `State.pm:175`: replace the front value in the frame it was last
1445        // bound in, adding NO undo entry, so the mutation keeps the binding's
1446        // save-stack level (the `\box` / same-level semantics). If the key was
1447        // never bound, seed it at the locked base frame (Perl's "push globally"
1448        // fallback). Mirrors the Value-table `assign_value_inplace` fast path.
1449        let state_table = self.table_mut(table_name);
1450        if let Some(defs) = state_table.get_mut(&key)
1451          && let Some(front) = defs.front_mut()
1452        {
1453          *front = value;
1454        } else {
1455          state_table.entry(key).or_default().push_front(value);
1456          for frame in &mut self.undo {
1457            if frame.locked {
1458              frame.table_mut(table_name).insert(key, 1);
1459              break;
1460            }
1461          }
1462        }
1463      },
1464      Scope::Named(scope_name) => {
1465        // initialize stash if empty
1466        let needs_init = match self.stash.get(&scope_name) {
1467          None => true,
1468          Some(v) => v.is_empty(),
1469        };
1470        if needs_init {
1471          self.assign_internal(
1472            TableName::Stash,
1473            scope_name,
1474            Stored::Stash(Vec::new()),
1475            Some(Scope::Global),
1476          );
1477        }
1478        self.journal_touch(TableName::Stash, scope_name);
1479        if let Some(Stored::Stash(stash)) =
1480          self.stash.get_mut(&scope_name).as_mut().unwrap().get_mut(0)
1481        {
1482          stash.push((table_name, key, value.clone()));
1483        }
1484        let has_active = match self.stash_active.get(&scope_name) {
1485          None => false,
1486          Some(v) => !v.is_empty(),
1487        };
1488        if has_active {
1489          self.assign_internal(table_name, key, value, Some(Scope::Local));
1490        }
1491      },
1492    }
1493  }
1494
1495  /// assigns a `Stored` value at the given key and scope
1496  pub fn assign_value<T: Into<Stored>, S: Into<Option<Scope>>>(
1497    &mut self,
1498    key: &str,
1499    value: T,
1500    scope: S,
1501  ) {
1502    let value = value.into();
1503    let scope = scope.into();
1504    let key_sym = arena::pin(key);
1505    self.assign_internal(TableName::Value, key_sym, value, scope);
1506  }
1507  //======================================================================
1508  /// fetches a Stored value at the given key, from the Value table
1509  pub fn lookup_value(&self, key: &str) -> Option<&Stored> {
1510    self.lookup_value_sym(arena::pin(key))
1511  }
1512  pub fn lookup_value_sym(&self, key: SymStr) -> Option<&Stored> {
1513    match self.value.get(&key) {
1514      None => None,
1515      Some(vvec) => match vvec.front() {
1516        None | Some(Stored::None) => None,
1517        Some(other) => Some(other),
1518      },
1519    }
1520  }
1521
1522  /// mutably borrows a Stored value at the given key, from the Value table
1523  pub fn lookup_value_mut(&mut self, key: &str) -> Option<&mut Stored> {
1524    let key = arena::pin(key);
1525    self.journal_touch(TableName::Value, key);
1526    match self.value.get_mut(&key) {
1527      None => None,
1528      Some(vvec) => match vvec.front_mut() {
1529        None | Some(Stored::None) => None,
1530        Some(other) => Some(other),
1531      },
1532    }
1533  }
1534  /// like `lookup_value` but only recognizes `Stored::VecDequeStored`
1535  pub fn lookup_vecdeque(&self, key: &str) -> Option<&VecDeque<Stored>> {
1536    match self.lookup_value(key) {
1537      None | Some(Stored::None) => None,
1538      Some(v) => v.into(),
1539    }
1540  }
1541  pub fn lookup_font_info(&self, key: &Token) -> Result<Option<&Stored>> {
1542    let key_str = match lookup_definition(key)? {
1543      Some(defn) => {
1544        s!("fontinfo_{}", defn.get_cs_name())
1545      },
1546      _ => {
1547        s!("fontinfo_{key}")
1548      },
1549    };
1550    Ok(self.lookup_value(&key_str))
1551  }
1552  /// manage a (global) hash of values
1553  pub fn lookup_mapping(&self, map: &str, key: &str) -> Option<&Stored> {
1554    self.lookup_mapping_sym(arena::pin(map), key)
1555  }
1556  pub fn lookup_mapping_sym(&self, map_sym: SymStr, key: &str) -> Option<&Stored> {
1557    match self.value.get(&map_sym) {
1558      None => None,
1559      Some(map_vec) => match map_vec.front() {
1560        Some(Stored::HashStored(h)) => h.get(key),
1561        _ => None,
1562      },
1563    }
1564  }
1565
1566  pub fn lookup_mapping_keys(&self, map: &str) -> Vec<SymStr> {
1567    let map_sym = arena::pin(map);
1568    match self.value.get(&map_sym) {
1569      None => Vec::new(),
1570      Some(map_vec) => match map_vec.front() {
1571        Some(Stored::HashStored(h)) => h.keys().copied().collect(),
1572        _ => Vec::new(),
1573      },
1574    }
1575  }
1576
1577  pub fn lookup_stacked_values(&self, key: &str) -> Vec<&Stored> {
1578    let key_sym = arena::pin(key);
1579    self.lookup_stacked_values_sym(key_sym)
1580  }
1581
1582  pub fn lookup_stacked_values_sym(&self, key: SymStr) -> Vec<&Stored> {
1583    if let Some(vdq) = self.value.get(&key) {
1584      vdq.iter().collect::<Vec<&Stored>>()
1585    } else {
1586      Vec::new()
1587    }
1588  }
1589
1590  fn lookup_definition_internal(&self, key: &Token) -> Option<&VecDeque<Stored>> {
1591    let cc = key.get_catcode();
1592    let name = key.get_sym();
1593    let lookupname: Option<SymStr> = if (cc == Catcode::ACTIVE) || (cc == Catcode::CS) {
1594      // `\special_relax`-family tokens all resolve under the bare `\special_relax`
1595      // name (shared `\relax` meaning; identity lives in `noexpand_shadowed`).
1596      if name == pin!("") {
1597        None
1598      } else {
1599        Some(meaning_key(key))
1600      }
1601    } else {
1602      key.get_executable_primitive_name().map(arena::pin)
1603    };
1604
1605    if let Some(lname) = lookupname {
1606      self.meaning.get(&lname)
1607    } else {
1608      None
1609    }
1610  }
1611  pub fn ensure_tag_property(&mut self, tag: SymStr) -> &mut TagOptions {
1612    self.tag_properties.entry(tag).or_default()
1613  }
1614}
1615
1616#[derive(Debug, Copy, Clone, PartialEq)]
1617enum RotateState {
1618  Main,
1619  Std,
1620  Sty,
1621}
1622// Perf/safety: `Cell<RotateState>` instead of `static mut` — RotateState is
1623// Copy, so Cell gives us Get/Set with no unsafe, preserving the thread_local
1624// single-threaded access guarantee without requiring unsafe at each call site.
1625thread_local! {
1626  static STATE_IN_USE: std::cell::Cell<RotateState> =
1627    const { std::cell::Cell::new(RotateState::Main) };
1628}
1629
1630pub fn use_sty_state() {
1631  if STATE_IN_USE.get() != RotateState::Sty {
1632    let mut sty_state = sty_state_mut!();
1633    let mut main_state = state_mut!();
1634    std::mem::swap(&mut *sty_state, &mut *main_state);
1635    STATE_IN_USE.set(RotateState::Sty);
1636  }
1637}
1638pub fn use_std_state() {
1639  if STATE_IN_USE.get() != RotateState::Std {
1640    let mut std_state = std_state_mut!();
1641    let mut main_state = state_mut!();
1642    std::mem::swap(&mut *std_state, &mut *main_state);
1643    STATE_IN_USE.set(RotateState::Std);
1644  }
1645}
1646pub fn use_main_state() {
1647  match STATE_IN_USE.get() {
1648    RotateState::Sty => {
1649      let mut sty_state = sty_state_mut!();
1650      let mut main_state = state_mut!();
1651      std::mem::swap(&mut *sty_state, &mut *main_state);
1652      STATE_IN_USE.set(RotateState::Main);
1653    },
1654    RotateState::Std => {
1655      let mut std_state = std_state_mut!();
1656      let mut main_state = state_mut!();
1657      std::mem::swap(&mut *std_state, &mut *main_state);
1658      STATE_IN_USE.set(RotateState::Main);
1659    },
1660    RotateState::Main => {},
1661  };
1662}
1663
1664/// Free every definition/register/box this thread accumulated, returning
1665/// all three `State` singletons (`STATE`, `STD_STATE`, `STY_STATE`) to a
1666/// fresh, empty baseline and the rotation to `Main`.
1667///
1668/// **Danger:** this invalidates all live definitions/`SymStr`-keyed data
1669/// on the thread. Sound only between fully independent conversions in a
1670/// reused process — the test harness (each test serializes to owned
1671/// `String`s, then resets before its thread exits) or a future daemon
1672/// that re-initializes afterward. The single-conversion binary never
1673/// calls this; it exits instead. Pairs with [`crate::common::arena::reset`]
1674/// — see [`crate::reset_thread_engine`] for the combined entry point and
1675/// the leaked-root no-drop rationale.
1676pub fn reset_thread_state() {
1677  // Make sure STATE holds the main state (not swapped out with std/sty)
1678  // before we replace it, so all three slots are freed for real.
1679  use_main_state();
1680  *state_root().borrow_mut() = State::new(StateOptions {
1681    catcodes: Some(Catcodes::Standard),
1682    ..StateOptions::default()
1683  });
1684  *std_state_root().borrow_mut() = State::new(StateOptions {
1685    catcodes: Some(Catcodes::Standard),
1686    ..StateOptions::default()
1687  });
1688  *sty_state_root().borrow_mut() = State::new(StateOptions {
1689    catcodes: Some(Catcodes::Style),
1690    ..StateOptions::default()
1691  });
1692  STATE_IN_USE.set(RotateState::Main);
1693  STAGED_SNAPSHOTS.with(|m| m.borrow_mut().clear());
1694}
1695
1696/// Empty this thread's three States to zero-capacity tables, for a thread about to exit
1697/// (`latexml_core::shrink_thread_engine`): they are leaked roots, so what they hold outlives the thread.
1698pub fn shrink_thread_state() {
1699  use_main_state();
1700  for root in [state_root(), std_state_root(), sty_state_root()] {
1701    *root.borrow_mut() = State::with_table_capacity(0, 0, 0);
1702  }
1703  STATE_IN_USE.set(RotateState::Main);
1704  STAGED_SNAPSHOTS.with(|m| *m.borrow_mut() = Default::default());
1705}
1706
1707/// A refused redefinition of a locked `\<name>` that EXTENDS the meaning it read — the locked binding's replacement
1708/// text with tokens appended or prepended, as etoolbox's `\appto`/`\preto` (`\edef#1{\expandonce#1…}`) and
1709/// latex.ltx's `\g@addto@macro` (`\toks@\expandafter{#1#2}\xdef#1{\the\toks@}`) make it — extends what the
1710/// class itself defined: in TeX the class's own definition is the meaning it extends, so the record of the class's
1711/// definition (`\lx@dropped@<name>`, `dropped_key`) becomes that definition with the same tokens appended or
1712/// prepended. wiley-article.cls:420-466 `\renewcommand{\maketitle}{…\@papertype…\@paperfield…}` then :576
1713/// `\appto{\maketitle}{…}`: the record held the kernel's body and the append, and the class's title page, which
1714/// the `\maketitle` deposit replays, was gone (1911.06213). `None` (the refused definition is recorded as it is)
1715/// unless the class's record and the binding are parameterless token bodies and the refused one is the binding's body
1716/// with tokens added at one end.
1717fn extended_refused_definition(
1718  token: &Token,
1719  definition: &Stored,
1720  dropped_key: SymStr,
1721) -> Option<Stored> {
1722  let parameterless = |d: &Expandable| {
1723    d.get_parameters()
1724      .is_none_or(|p| p.get_parameters().is_empty())
1725  };
1726  let Stored::Expandable(new) = definition else {
1727    return None;
1728  };
1729  let Some(Stored::Expandable(binding)) = lookup_meaning(token) else {
1730    return None;
1731  };
1732  let Some(Stored::Expandable(prior)) =
1733    lookup_meaning(&T_CS!(arena::with(dropped_key, ToString::to_string)))
1734  else {
1735    return None;
1736  };
1737  if !parameterless(new) || !parameterless(&binding) || !parameterless(&prior) {
1738    return None;
1739  }
1740  let (
1741    Some(ExpansionBody::Tokens(new_body)),
1742    Some(ExpansionBody::Tokens(kernel)),
1743    Some(ExpansionBody::Tokens(own)),
1744  ) = (
1745    new.get_expansion(),
1746    binding.get_expansion(),
1747    prior.get_expansion(),
1748  )
1749  else {
1750    return None;
1751  };
1752  let (new_body, kernel, own) = (new_body.unlist_ref(), kernel.unlist_ref(), own.unlist_ref());
1753  if kernel.is_empty() || new_body.len() <= kernel.len() {
1754    return None;
1755  }
1756  let extended: Vec<Token> = if new_body.starts_with(kernel) {
1757    own
1758      .iter()
1759      .chain(&new_body[kernel.len()..])
1760      .copied()
1761      .collect()
1762  } else if new_body.ends_with(kernel) {
1763    new_body[..new_body.len() - kernel.len()]
1764      .iter()
1765      .chain(own)
1766      .copied()
1767      .collect()
1768  } else {
1769    return None;
1770  };
1771  let mut kept = (*prior).clone();
1772  kept.expansion = Some(ExpansionBody::Tokens(Tokens::new(extended)));
1773  Some(Stored::Expandable(Rc::new(kept)))
1774}
1775
1776/// A shorthand for installing definitions
1777pub fn install_definition<T: Into<Stored>>(definition: T, scope: Option<Scope>) {
1778  let definition = definition.into();
1779
1780  // Locked definitions!!! (or should this test be in assignMeaning?)
1781  // Ignore attempts to (re)define $cs from tex sources
1782  let token = match definition {
1783    Stored::Expandable(ref defn) => defn.get_cs(),
1784    Stored::Conditional(ref defn) => defn.get_cs(),
1785    Stored::Constructor(ref defn) => defn.get_cs(),
1786    Stored::Primitive(ref defn) => defn.get_cs(),
1787    Stored::MathPrimitive(ref defn) => defn.get_cs(),
1788    Stored::Register(ref defn) => defn.get_cs(),
1789    Stored::Token(ref token) => Cow::Borrowed(token),
1790    _ => panic!("_wrong_argument_for_install_definition"),
1791  };
1792  let cs_sym = token.get_cs_name();
1793  // A real definition retires the error-stub provenance (`is_error_stub`):
1794  // a name stubbed as `<ltx:ERROR/>` and later `\def`ed is a defined cs
1795  // again, so `\csname…\endcsname` takes tex.web's §373 path for it, not the
1796  // §370 discard. Probe-only, like the `:locked` check below.
1797  if let Some(stub_sym) = token.with_cs_name(|cs| arena::get_suffixed(cs, ":error@stub"))
1798    && lookup_bool_sym(stub_sym)
1799  {
1800    assign_value_sym(stub_sym, false, Some(Scope::Global));
1801  }
1802  // (read against this redefinition's own interface: a lock that holds only against copies, `files_lock_holds`; an
1803  // unlocked state reads no lock and allocates nothing here)
1804  let locked = !state_is_unlocked()
1805    && token.with_cs_name(|cs| redefinition_locked(cs, &definition))
1806    && !document_redefines_guess(&token)
1807    // (before the class declaration the lock yields, except to a value the binding keeps owning the calls of below,
1808    // OXIDIZED_DESIGN #500: `\def\title{On Widgets}`, 1704.01336's `\def\date{4.4.2017}`)
1809    && !keep_binding_aside_before_class(&token, Some(&definition), scope.as_ref());
1810  // (a stand-in's copy's own write to LaTeX's document hooks is document-time code, which it does not register, as it
1811  // does not its `\AtBeginDocument` code: `copy_provides_defers`. ltxgrid's `\prepdef\@begindocumenthook{\open@column@one
1812  // \@ne\set@colht…}` in qm2008_abs.cls and snp.cls, REVTeX 4 copies routed to the revtex4 binding, ran its page
1813  // grid over the binding's names at `\begin{document}`: 7 "Missing number" Warnings, 0805.2253, 0806.0481, 0805.4759)
1814  if !state_is_unlocked() && copy_provides_defers_hook_write(&token) {
1815    return;
1816  }
1817  // (a stand-in's copy's own title page, whatever becomes of it: what it prints decides its setters' defaults,
1818  // `copy_title_page_prints`)
1819  if let Stored::Expandable(ref defn) = definition
1820    && let Some(ExpansionBody::Tokens(body)) = defn.get_expansion()
1821  {
1822    note_copy_provides_title_page(&token, body);
1823  }
1824  if locked && copy_provides_refuses_locked(&token) {
1825    restore_cleared_binding(&token);
1826  } else if locked {
1827    restore_cleared_binding(&token);
1828    // A LOCKED BINDING OWNS ITS CALLS. The lock keeps the semantic markup of a call (Perl acb3b27e: commands "that
1829    // lose semantics when redefined"), and a use without an argument cannot produce that markup: the binding would
1830    // read the next token as its argument (a pgffor `\foreach \i/\text` loop variable: 15 errors; `\@for\text:=`:
1831    // Fatal; `\def\title{On Widgets}` then `\section*{\title}`). So a VALUE the document defines — a definition
1832    // without parameters — of a binding that takes a braced argument ([`owns_calls`]; a robust binding by its inner
1833    // `\cs␣`, the kernel `\cite`: eplain's btxmac scratch, SYNC_STATUS 67n) becomes the meaning: what
1834    // `\ifx`, `\meaning` and every use without an argument see, as in pdflatex; the binding stays the handler of
1835    // its calls, as `\lx@locked@<cs>` ([`crate::definition::expandable::SpecialCall::YieldsCalls`]). A definition
1836    // with parameters defines a command, not a value, so every use of it stays the binding's (`\renewcommand\mathbf
1837    // [1]{\boldsymbol{#1}}` with `\mathbf a`; 2006.08408's `\renewcommand{\sqrt}[2][\mkern8mu]{…}` with
1838    // `\sqrt k`). Raw class and package code stays refused, as in Perl (State.pm:502-517), and so does a binding
1839    // without a braced interface (sectioning, `\footnote`, `\url`, `\maketitle`). The records below are written
1840    // either way, so calls behave as before. Accepted residual: a parameterless forwarder used without braces
1841    // (`\def\mathcal{\mathscr}` with `\mathcal C`; the `\mathpalette` `\sqrt` hack with `\sqrt n`, 1806.09639,
1842    // 1904.10871) runs the document's definition, as pdflatex does: author code is not analysed.
1843    // OXIDIZED_DESIGN #500; repros macro-state/m5_*; witnesses 2405.18512, 1406.2544, 1511.05179.
1844    let call_owner = match definition {
1845      Stored::Expandable(ref defn)
1846        if crate::definition::origin::current_origin()
1847          == crate::definition::origin::DefinitionOrigin::Document
1848          && defines_value(&token, defn) =>
1849      {
1850        lookup_meaning(&token)
1851          .filter(|binding| owns_calls(&token, binding))
1852          .map(|binding| (Rc::clone(defn), binding))
1853      },
1854      _ => None,
1855    };
1856    // THE DROPPED SETTER'S INTERNALS EXIST, EMPTY. A raw class that
1857    // redefines a locked frontmatter command as a plain setter —
1858    // afthesis.cls:520 `\def\author#1{\def\auth@r{#1}}` — expects the
1859    // internal it would define to exist for its own readers (`\flyleaf`,
1860    // `\titlepage` :637/:688 read `\auth@r`); afthesis itself initializes its
1861    // other internals empty at load (:494-495 `\def\ti@tle{}`). Perl
1862    // (`State.pm:502-517`) drops the redefinition and nothing else, so
1863    // `\auth@r` stays undefined (usethesis). The locked binding remains the
1864    // sole semantic source (running the setter's body with the real
1865    // arguments would duplicate the author through the class layout), and
1866    // every `\def`/`\gdef`/`\edef`/`\xdef <cs>` in the dropped body whose
1867    // `<cs>` is still undefined gets an EMPTY definition — the class's own
1868    // default convention, with no name enumerated. Guard:
1869    // `perfect_kernel_batch54::refused_setter_internals_take_the_replayed_value`.
1870    if let Stored::Expandable(ref defn) = definition
1871      && let Some(ExpansionBody::Tokens(body)) = defn.get_expansion()
1872    {
1873      let body = body.unlist_ref();
1874      let def_names = ["\\def", "\\gdef", "\\edef", "\\xdef"];
1875      for (i, t) in body.iter().enumerate() {
1876        if t.get_catcode() == Catcode::CS
1877          && t.with_cs_name(|n| def_names.contains(&n))
1878          && let Some(target) = body.get(i + 1)
1879          && target.get_catcode() == Catcode::CS
1880          && lookup_meaning(target).is_none()
1881          && let Ok(empty) = Expandable::new(
1882            *target,
1883            None,
1884            Some(ExpansionBody::Tokens(Tokens::new(Vec::new()))),
1885            None,
1886          )
1887        {
1888          state_mut!().assign_internal(
1889            TableName::Meaning,
1890            target.get_cs_name(),
1891            Stored::Expandable(Rc::new(empty)),
1892            Some(Scope::Global),
1893          );
1894        }
1895      }
1896    }
1897    // Keep the dropped definition itself, as `\lx@dropped@<name>`: a locked
1898    // binding may run what the class wrote where its own semantics leave a gap —
1899    // `\lx@deposit@maketitle` (sect05.rs) runs a class's title-page body for the
1900    // fields the frontmatter does not carry (ryethesis.cls:282 degree/program/
1901    // university). Nothing runs it unless a binding asks. OXIDIZED_DESIGN #265.
1902    // Macros only: a later `\let<cs>\relax` (article-style classes end their
1903    // `\maketitle` with one) must not overwrite the body it follows.
1904    if matches!(definition, Stored::Expandable(_)) {
1905      let dropped_key =
1906        arena::pin(token.with_cs_name(|cs| s!("\\lx@dropped@{}", cs.trim_start_matches('\\'))));
1907      let kept = extended_refused_definition(&token, &definition, dropped_key)
1908        .unwrap_or_else(|| definition.clone());
1909      state_mut!().assign_internal(TableName::Meaning, dropped_key, kept, Some(Scope::Global));
1910    }
1911    // Record that a redefinition was dropped: a locked binding may consult
1912    // `<cs>:redefined` to yield the parts of its behaviour the class took
1913    // over (see `\lx@maketitle@cleanup`).
1914    // (a class whose load defines the name the lock kept defines it all the same, as its real file does:
1915    // `ClassLoadFrame`, `copy_base_class_defines`)
1916    note_class_load_name(meaning_key(&token));
1917    note_redefined(&token);
1918    // …and the dropped setter's SIGNATURE: an argument-taking `\def\abstract#1`
1919    // (apa7.cls:785, uwthesis.cls:805) means the class reads `{…}` as one
1920    // pre-tokenized argument stored for later, which the locked binding can
1921    // honour (`\abstract`, sect05.rs). `\newcommand` records it at its own
1922    // locked bail (sect08.rs).
1923    if let Stored::Expandable(ref defn) = definition {
1924      let nargs = defn
1925        .get_parameters()
1926        .map_or(0, |p| p.get_parameters().len());
1927      let nargs_key = arena::pin(token.with_cs_name(|cs| s!("{cs}:redefined@nargs")));
1928      state_mut!().assign_internal(
1929        TableName::Value,
1930        nargs_key,
1931        Stored::Number(Number::new(nargs as i64)),
1932        Some(Scope::Global),
1933      );
1934    }
1935    // …and, against a lock that holds only against copies, the default of the optional argument the copy takes first
1936    // (`[1][\thu@proof@name]`; a robust copy's by its inner `\cs␣`), which the binding titles its own use with
1937    // (amsthm's proof, amsthm_sty.rs).
1938    if let Some(default) = copy_default(&definition) {
1939      record_redefined_default(&token, default);
1940    }
1941    if let Some((defn, binding)) = call_owner {
1942      // The binding, kept on the first override (a later one, a loop's next iteration, overrides an override).
1943      if !matches!(binding, Stored::Expandable(ref b) if b.yields_calls()) {
1944        let owner = locked_binding_token(&token);
1945        state_mut!().assign_internal(
1946          TableName::Meaning,
1947          owner.get_cs_name(),
1948          binding,
1949          Some(Scope::Global),
1950        );
1951      }
1952      let mut overriding = (*defn).clone();
1953      overriding.special_call = expandable::SpecialCall::YieldsCalls;
1954      state_mut!().assign_internal(
1955        TableName::Meaning,
1956        cs_sym,
1957        Stored::Expandable(Rc::new(overriding)),
1958        scope,
1959      );
1960      // One report per control sequence and document (a loop overrides it on every iteration).
1961      let reported_key = arena::pin(token.with_cs_name(|cs| s!("{cs}:lock@reported")));
1962      if !lookup_bool_sym(reported_key) {
1963        assign_value_sym(reported_key, true, Some(Scope::Global));
1964        let cs_name = token.with_cs_name(ToString::to_string);
1965        Info!(
1966          "lock",
1967          cs_name,
1968          s!(
1969            "{cs_name} is locked: its calls keep the binding; its other uses take the document's definition"
1970          )
1971        );
1972      }
1973      return;
1974    }
1975    if let Some(Stored::String(s)) = state!().lookup_value("SOURCEFILE") {
1976      // report if the redefinition seems to come from document source
1977      if arena::with(*s, |txt| {
1978        txt == "Anonymous String" || TEX_OR_BIB_EXT_RE.is_match(txt) && !txt.ends_with(CODE_TEX_EXT)
1979      }) {
1980        // Perl `State.pm` L514 reports the CS itself — `Ignoring redefinition
1981        // of \cite` — not the lookup key. Reporting `lock_key` here named a
1982        // control sequence that does not exist (`\cite:locked`), so the one
1983        // diagnostic for a refused redefinition did not grep for the command
1984        // it was about.
1985        let cs_name = token.with_cs_name(ToString::to_string);
1986        Info!("ignore", cs_name, s!("Ignoring redefinition of {cs_name}"));
1987      }
1988    }
1989  } else {
1990    note_copy_provides_assignment(&token);
1991    state_mut!().assign_internal(TableName::Meaning, cs_sym, definition, scope);
1992  }
1993}
1994
1995/// Generate a stub definition for an undefined control-sequence,
1996/// along with appropriate error messge.
1997pub fn generate_error_stub(token: &Token) -> Result<Token> {
1998  let cs = token.with_cs_name(ToString::to_string);
1999  // Perl `generateErrorStub` (State.pm L532-553) has no counter branch: an undefined `\c@<ctr>` read as a
2000  // control sequence is the error TeX raises too (`! Undefined control sequence.`). The leniency Perl has is in
2001  // its counter readers, `CounterValue` (Package.pm L712; ours `counter::dialect::counter_value`): `\arabic`,
2002  // `\stepcounter`, `\addtocounter`. Witness 1910.02851 (`\ContinuedFloat` in an `algorithm` float reading
2003  // `\c@subalgorithm@save`; Perl's subfig binding reads it through `CounterValue`) is served by subfig.sty:587's own
2004  // guard in the subfig binding, which touches no sub-counter a float type lacks.
2005  // Guard `perfect_kernel_batchga1::an_undefined_counter_register_is_the_error_tex_raises`.
2006  // Gate the undefined-CS summary tally by SUPPRESS_UNDEFINED_ERRORS so it
2007  // matches the `Error!` gate at L1021 below — during expl3-code.tex raw
2008  // load with thousands of forward-references we install the ERROR stub
2009  // without polluting the user-facing summary count. See
2010  // project_kernel_dump_parity.md "iow_wrap residual" for full diagnosis.
2011  if !lookup_bool("SUPPRESS_UNDEFINED_ERRORS") {
2012    note_status(LogStatus::Undefined, Some(&cs));
2013  }
2014  // To minimize chatter, go ahead and define it...
2015  if cs.starts_with("\\if") {
2016    // Apparently an \ifsomething ???
2017    let name = cs.replace("\\if", "");
2018    // Perl `generateErrorStub` (State.pm L539-540) passes the recovery note
2019    // as a SEPARATE Error detail, so `generateMessage` renders it on its own
2020    // indented line — not merged into the primary message. Match that (and
2021    // the already-correct stomach.rs path) so the cortex `details`/log first
2022    // line is just "...is not defined." like Perl.
2023    Error!(
2024      "undefined",
2025      token,
2026      s!("The token {} is not defined.", token.stringify()),
2027      "Defining it now as with \\newif"
2028    );
2029    let setters = [
2030      Expandable::new(
2031        T_CS!(s!("\\{}true", name)),
2032        None,
2033        Some(s!("\\let{}\\iftrue", cs).into()),
2034        None,
2035      )?,
2036      Expandable::new(
2037        T_CS!(s!("\\{}false", name)),
2038        None,
2039        Some(s!("\\let{}\\iffalse", cs).into()),
2040        None,
2041      )?,
2042    ];
2043    let scope = stub_scope(&cs);
2044    past_the_lock(|| {
2045      for setter in setters {
2046        install_definition(setter, Some(Scope::Global));
2047      }
2048      let_i(token, &T_CS!("\\iffalse"), Some(scope));
2049    });
2050    crate::util::logger::note_held_stub(*token);
2051  } else {
2052    // Allow suppression of undefined errors during bulk loading (e.g., expl3-code.tex)
2053    // where forward references are later resolved by post-load fixups.
2054    if !lookup_bool("SUPPRESS_UNDEFINED_ERRORS") {
2055      Error!(
2056        "undefined",
2057        token,
2058        s!("The token {} is not defined.", token.stringify()),
2059        "Defining it now as <ltx:ERROR/>"
2060      );
2061    }
2062    let scope = stub_scope(&cs);
2063    let stub = Constructor {
2064      cs: *token,
2065      replacement: Some(Rc::new(move |document, _args, _props| {
2066        document.make_error("undefined", &cs)
2067      })),
2068      ..Constructor::default()
2069    };
2070    //TODO: sizer => "X"),
2071    past_the_lock(|| install_definition(stub, Some(scope)));
2072    // The stub's provenance travels with the NAME (tex.web §370 discards an
2073    // undefined cs inside `\csname…\endcsname`; a defined non-expandable one
2074    // takes the §373 `back_error` path): `<cs>:error@stub`, read by
2075    // `gullet::read_cs_name_inner` — not a global "last stubbed token", which
2076    // went stale across interleaved stubs.
2077    // (at the stub's own scope: a locked name's stub that ends with its group leaves the binding, which is no stub)
2078    assign_value_sym(
2079      arena::pin(token.with_cs_name(|c| s!("{c}:error@stub"))),
2080      true,
2081      Some(scope),
2082    );
2083    crate::util::logger::note_held_stub(*token);
2084  }
2085  Ok(*token)
2086}
2087
2088/// The scope [`generate_error_stub`] installs a stub at: global, as Perl's `generateErrorStub` (State.pm:553
2089/// `installDefinition(…, 'global')`), except for a name that carries a lock ([`name_carries_lock`]). Such a name is
2090/// undefined only because a `\let` cleared its binding, and that `\let` may be local: the stub is the recovery for
2091/// this clearing, so it is local too and ends where the clearing ends — `{\let\cite\undefined X\cite{a}} Y\cite{b}`
2092/// typesets the second citation, as pdflatex does, and `\begingroup\let\section\nonexist\section{A}\endgroup
2093/// \section{B}` keeps the section B. A clearing at the top level leaves the stub for the rest of the document, one
2094/// Error per name as before. Guards `perfect_kernel_batch68u::a_locked_name_cleared_in_a_group_is_back_after_it`.
2095fn stub_scope(cs: &str) -> Scope {
2096  if name_carries_lock(cs) {
2097    Scope::Local
2098  } else {
2099    Scope::Global
2100  }
2101}
2102
2103/// Run [`generate_error_stub`]'s installs with the state unlocked. The stub is the engine's recovery from an undefined
2104/// control sequence, not a source redefinition, so a lock does not refuse it: a document's `\let` of a locked binding to
2105/// an undefined name (`\let\cite\parencite` with `\parencite` undefined, 2006.07968's apa6 paper; pittetd.cls:313
2106/// `\let\maketitle\HyOrg@maketitle`, 1509.06375) clears the binding, and a refused stub left the name undefined for the
2107/// Stomach's retry (stomach.rs, Perl Stomach.pm:236-237 `invokeToken_undefined`), which raised the same Error until
2108/// TooManyErrors. Installed, the name gives one Error and its `<ltx:ERROR/>`, as pdflatex gives one "Undefined control
2109/// sequence" per use. Perl refuses its own locked names' stubs the same way (State.pm:509; `\let\section\nonexist`:
2110/// 101 Errors and Fatal, KNOWN_PERL_ERRORS #841). OXIDIZED_DESIGN_DIVERGENCES #641; repro
2111/// macro-state/locked_name_let_to_undefined_stub_loop; guard
2112/// `perfect_kernel_batch68u::a_locked_name_let_to_an_undefined_one_errs_once`.
2113fn past_the_lock(install: impl FnOnce()) {
2114  let _unlocked = local_state_unlocked_guard(true);
2115  install();
2116}
2117
2118/// Undo [`generate_error_stub`]: `token` (and a stubbed `\ifX`'s `\Xtrue`/`\Xfalse`) is undefined
2119/// again. A discarded [`crate::util::logger::DiagnosticsHold`] takes back its scope's errors and the
2120/// stubs standing in for them, so the document's own later use of the command reports it.
2121pub fn remove_error_stub(token: &Token) {
2122  let cs = token.with_cs_name(ToString::to_string);
2123  // A locked name's stub was local ([`stub_scope`]): undone only while it still stands — not after the group it was
2124  // made in has ended, which gave the binding back — and undone there, so the binding of the enclosing groups stands.
2125  let scope = stub_scope(&cs);
2126  let local = matches!(scope, Scope::Local);
2127  if let Some(name) = cs.strip_prefix("\\if") {
2128    for setter in [T_CS!(s!("\\{name}true")), T_CS!(s!("\\{name}false"))] {
2129      assign_meaning(&setter, Stored::None, Some(Scope::Global));
2130    }
2131    if local && !x_equals(token, &T_CS!("\\iffalse")) {
2132      return;
2133    }
2134  } else {
2135    if local && !is_error_stub(token) {
2136      return;
2137    }
2138    assign_value_sym(arena::pin(s!("{cs}:error@stub")), false, Some(scope));
2139  }
2140  assign_meaning(token, Stored::None, Some(scope));
2141}
2142
2143/// Was `token` stubbed as `<ltx:ERROR/>` by [`generate_error_stub`]? Probe
2144/// only: the flag key is interned when the stub is made, so an unknown name
2145/// costs no arena entry (the `:locked` probe's discipline).
2146pub fn is_error_stub(token: &Token) -> bool {
2147  // Spelled without a new string: the font identifier reader asks it of every font token (l3intarray's `\fontdimen`).
2148  token
2149    .with_cs_name(|c| arena::get_suffixed(c, ":error@stub"))
2150    .is_some_and(lookup_bool_sym)
2151}
2152
2153/// Install a `Constructor` for `token` whose sole effect at digestion time is to
2154/// emit `<ltx:ERROR class='undefined'>content</ltx:ERROR>` (the Rust equivalent
2155/// of Perl `Document::makeError`). It logs NOTHING — the caller is responsible
2156/// for the `Error!`/`note_status`. Mirrors the make_error constructor that
2157/// `generate_error_stub` installs for undefined *commands*, so undefined
2158/// *environments* (`\begin{undefinedenv}`) leave the same visible
2159/// `<ltx:ERROR>` marker as Perl instead of silently vanishing from the output.
2160/// Like that stub, it installs past a lock (`past_the_lock`, below).
2161pub fn install_undefined_error_constructor(token: Token, content: &str) {
2162  let content = content.to_string();
2163  let stub = Constructor {
2164    cs: token,
2165    replacement: Some(Rc::new(move |document, _args, _props| {
2166      document.make_error("undefined", &content)
2167    })),
2168    ..Constructor::default()
2169  };
2170  let scope = token.with_cs_name(stub_scope);
2171  past_the_lock(|| install_definition(stub, Some(scope)));
2172}
2173
2174/// Does a provide-only load ([`ProvideOnlyGuard`](crate::definition::origin::ProvideOnlyGuard)) decline this definition
2175/// of `token`? While the guard lives, a binding's definition (`DefinitionOrigin::Binding`, `Fallback` or `Borrowed`:
2176/// OmniBus and every binding it requires, inst_support's `\author[]{}` and epsf's `\epsfbox` among them) is declined
2177/// when the name was defined before the guard: defined now in the `\providecommand` sense (latex.ltx `\@ifundefined`: a
2178/// meaning other than `\relax`, `binding::def::dialect::is_defined_token`), not a fallback guess
2179/// (`is_fallback_meaning`), and not assigned since the guard began (`provide_only_assigned`: the load's own names,
2180/// which it may define again — OmniBus's `\keywords{}` before its `\keywords` that also opens `{keywords}`). An
2181/// environment `\begin{X}`/`\end{X}` counts as defined when `\X` is (latex.ltx `\begin` runs `\X`), and `\end{X}` also
2182/// when `\endX` is. The binding definers (`def_macro`, `def_primitive`, `def_constructor`, `def_register`,
2183/// `def_conditional`, `def_environment`, `def_math`) and `Let!` consult it before they assign anything; TeX's own
2184/// `\def`/`\let` do not, so TeX code run during the load keeps its usual effect (a hook appended to, a scratch macro),
2185/// nor does the loader's bookkeeping, made at its caller's origin. A macro marked `extends` (it wraps and delegates to
2186/// the name's current meaning) is not declined.
2187pub fn provide_only_declines(token: &Token) -> bool {
2188  use crate::{
2189    binding::def::dialect::is_defined_token,
2190    definition::origin::{DefinitionOrigin, current_origin, provide_only},
2191  };
2192  if !provide_only()
2193    || !matches!(
2194      current_origin(),
2195      DefinitionOrigin::Binding | DefinitionOrigin::Fallback | DefinitionOrigin::Borrowed
2196    )
2197  {
2198    return false;
2199  }
2200  let defined = |token: &Token| {
2201    is_defined_token(token)
2202      && !is_fallback_meaning(token)
2203      && !state!().provide_only_assigned.contains(&meaning_key(token))
2204  };
2205  if defined(token) {
2206    return true;
2207  }
2208  token.with_cs_name(|name| {
2209    let env = |prefix: &str| {
2210      name
2211        .strip_prefix(prefix)
2212        .and_then(|rest| rest.strip_suffix('}'))
2213    };
2214    if let Some(env) = env("\\begin{") {
2215      defined(&T_CS!(s!("\\{env}")))
2216    } else if let Some(env) = env("\\end{") {
2217      defined(&T_CS!(s!("\\{env}"))) || defined(&T_CS!(s!("\\end{env}")))
2218    } else {
2219      false
2220    }
2221  })
2222}
2223
2224/// "A stand-in's copy provides" (OXIDIZED_DESIGN_DIVERGENCES #731): note this assignment of `token`'s meaning, made
2225/// while the paper's copy of an author file is read after the binding that stands in for it
2226/// (`binding::content::read_stand_in_copy`), or while the `\AtEndOfClass`/`\AtEndOfPackage` code it registered runs
2227/// at the end of that load ([`copy_provides_wrap`]). Every assignment of a meaning goes through here — TeX's `\def`
2228/// family, `\let`, `\futurelet`, `\chardef` and the `\countdef` family, and the LaTeX declarators (`\newcommand`,
2229/// `\renewcommand`, `\DeclareRobustCommand`, `\newenvironment`, `\newcounter`, `\newif`, `\newtheorem`, `\newlength`…),
2230/// at [`install_definition`] and [`assign_meaning`]. One of a name LaTeXML's semantic layer owns
2231/// (`owned_by_the_semantic_layer`; an environment `{X}` is owned when `\begin{X}`, `\X` or `\endX` is) holds only
2232/// inside the copy's own code: the binding's meaning is kept aside and put back when the copy's read ends
2233/// ([`leave_copy_provides_frame`]), so for the document the definition acted as `\providecommand` does, while the
2234/// copy's load-time logic sees what it defined, as in TeX: aipproc.cls:559 `\ifnum\pageref>0` after its option's
2235/// `\chardef\pageref` (astro-ph0105128); epl2.cls:1317-1318's `\let\epl@org@bibitem\bibitem` before its `\def\bibitem`,
2236/// which the epl binding makes too (a kept `\let` would take the binding's wrapper for the original, and `\bibitem`
2237/// would call itself: 0906.2627, 1102.2776, 1203.4765). Every other assignment stands as TeX makes it: an undefined
2238/// name (the copy's extras), a raw kernel name, an earlier raw file's or the document's, a stub or borrow. Not while
2239/// the state is unlocked (a binding's `before`/`after` code, an `AddToMacro!` append), nor for a locked name, which
2240/// `install_definition` refuses first ([`copy_provides_refuses_locked`]). Each name kept for the binding is logged
2241/// once per copy, at Info.
2242pub fn note_copy_provides_assignment(token: &Token) {
2243  let id = crate::definition::origin::copy_provides();
2244  if id == 0 || state_is_unlocked() || !matches!(token.get_catcode(), Catcode::CS | Catcode::ACTIVE)
2245  {
2246    return;
2247  }
2248  let key = meaning_key(token);
2249  let Some(at) = state!()
2250    .copy_provides_frames
2251    .iter()
2252    .rposition(|frame| frame.id == id && !frame.repeat)
2253  else {
2254    return;
2255  };
2256  if state!().copy_provides_frames[at].kept_keys.contains(&key) {
2257    return;
2258  }
2259  // (a name whose earlier assignment in the copy's code stood is the copy's: `\let\refname\relax` then
2260  // `\newcommand\refname{…}`, as LaTeX's `\newcommand` finds a `\relax` name definable)
2261  if state!().copy_provides_frames[at].assigned.contains(&key) {
2262    return;
2263  }
2264  // (a counter's representation and reset list are owned only when the stand-in binding's own load assigned them:
2265  // `counter_part`)
2266  // (an environment's names are provided or declined together: once the copy's code redefined one the binding owns —
2267  // its `\begin{X}`, kept aside — the others it defines next are kept too, though the name it redefined now carries
2268  // the copy's meaning; cimart.cls:295-315's `\newtheorem{theorem}[definition]` under OmniBus's `{theorem}` left the
2269  // binding's `\begin{theorem}` with the copy's `\end{theorem}`, a group open at the document's end: 2412.00032,
2270  // 2408.07575's `{example}`)
2271  let pair_kept = token.with_cs_name(|name| {
2272    environment_names(name).iter().any(|other| {
2273      state!().copy_provides_frames[at]
2274        .kept_keys
2275        .contains(&meaning_key(&T_CS!(other.as_str())))
2276    })
2277  });
2278  let owned = if copy_keeps_environment_name(token, at) {
2279    note_copy_environment_opener(token, at);
2280    false
2281  } else if token.with_cs_name(counter_part).is_some() {
2282    state!().stand_in_meanings.contains(&key)
2283  } else if unowned_text_default(token) || base_class_name_made_relax(token) {
2284    false
2285  } else {
2286    // (not by its macro partner alone: plain's `\endgroup` does not make a copy's `\group` LaTeXML's)
2287    let environment = |name: &str| name.starts_with("\\begin{") || name.starts_with("\\end{");
2288    pair_kept
2289      || owned_by_the_semantic_layer(token)
2290      || token.with_cs_name(|name| {
2291        environment_names(name)
2292          .iter()
2293          .filter(|other| environment(name) || environment(other))
2294          .any(|other| owned_by_the_semantic_layer(&T_CS!(other.as_str())))
2295      })
2296  };
2297  if !owned {
2298    state_mut!().copy_provides_frames[at].assigned.insert(key);
2299    return;
2300  }
2301  let binding = lookup_meaning(token).unwrap_or(Stored::None);
2302  let mut state = state_mut!();
2303  let frame = &mut state.copy_provides_frames[at];
2304  frame.kept.push((key, binding));
2305  frame.kept_keys.insert(key);
2306}
2307
2308/// Is `token` a name the stand-in binding's base class assigned (`State::stand_in_base_defaults`) that a file since
2309/// made `\relax` — a raw base class the copy loads: `\let\figurename\relax` before the copy's
2310/// `\newcommand\figurename{Fig}`? LaTeX finds a `\relax` name undefined (`\newcommand`, `\@ifundefined`), so the copy's
2311/// definition stands, as in TeX.
2312fn base_class_name_made_relax(token: &Token) -> bool {
2313  state!()
2314    .stand_in_base_defaults
2315    .contains(&meaning_key(token))
2316    && lookup_meaning(token)
2317      .is_some_and(|meaning| Some(meaning) == lookup_meaning(&crate::token::TOKEN_RELAX))
2318}
2319
2320/// Does a stand-in's copy, read or running its hook now ([`note_copy_provides_assignment`]), redefine the locked
2321/// `token`? Then the lock refuses it as for any file, but keeps no record of it — no `\lx@dropped@<name>` body for
2322/// the binding to run in a gap, no `<cs>:redefined` for it to yield to, no default or signature (the records of a raw
2323/// class taking over a locked command, OXIDIZED_DESIGN #265, #500): the binding stands in for this very file, so the
2324/// copy takes nothing over. Logged once per copy, at Info, as a redefinition of an owned name is.
2325pub fn copy_provides_refuses_locked(token: &Token) -> bool {
2326  let id = crate::definition::origin::copy_provides();
2327  if id == 0 {
2328    return false;
2329  }
2330  let key = meaning_key(token);
2331  let mut state = state_mut!();
2332  if let Some(copy) = state.copy_provides_copies.get_mut(id as usize - 1)
2333    && copy.declined.insert(key)
2334  {
2335    let file = copy.file.clone();
2336    drop(state);
2337    let name = token.with_cs_name(ToString::to_string);
2338    Info!(
2339      "provide",
2340      name,
2341      s!("{name} keeps LaTeXML's locked definition: the paper's {file} redefines it")
2342    );
2343  }
2344  true
2345}
2346
2347/// Does a stand-in's copy, read now ([`note_copy_provides_assignment`]), save `source` again into `token` — `\let
2348/// \token\source` — where `token` already holds an earlier meaning of `source` (its definition is a `\let` copy made
2349/// under `source`'s name, `definition_cs`) that the stand-in binding's load assigned, and `source` has been redefined
2350/// since — by the binding, the copy's read not having assigned `source` itself — to a meaning that reaches `token`
2351/// (`meaning_reaches`), so that the `\let` would make it call itself? Then the
2352/// `\let` is declined, in the copy's code too: `token` keeps the meaning TeX gives it, `source` before the redefinition. The binding (or a file it read) made the very save-and-wrap the copy makes — `\let\org\X`, then
2353/// `\X` redefined to call `\org` —, and saving the wrapper into `\org` makes `\X` call itself: myjmlr.cls and
2354/// jmlr_mod.cls (renamed jmlr.cls copies routed to the jmlr binding, whose jmlrutils.sty made the same wrap) run
2355/// `\let\jmlr@org@newtheorem\newtheorem` (jmlr.cls:753-754) before their own `\newtheorem{example}`, which looped to
2356/// the timeout (1506.02582, 2304.14217; OXIDIZED_DESIGN_DIVERGENCES #731 rule 2, the epl2.cls `\let\epl@org@bibitem`
2357/// case met in the copy's own code). Logged once per copy, at Info.
2358pub fn copy_provides_keeps_saved_meaning(token: &Token, source: &Token, meaning: &Stored) -> bool {
2359  let id = crate::definition::origin::copy_provides();
2360  if id == 0
2361    || state_is_unlocked()
2362    || !matches!(token.get_catcode(), Catcode::CS | Catcode::ACTIVE)
2363    || token == source
2364  {
2365    return false;
2366  }
2367  let key = meaning_key(token);
2368  if !state!().stand_in_meanings.contains(&key) {
2369    return false;
2370  }
2371  let Some(saved) = lookup_meaning(token) else {
2372    return false;
2373  };
2374  if definition_cs(&saved) != Some(*source) || same_meaning(&saved, meaning) {
2375    return false;
2376  }
2377  // (only while `source` still holds the binding's meaning — the copy's read has not assigned it — and only a `\let`
2378  // that would make that wrapper call itself, `source`'s meaning reaching `token`: pgf's scratch
2379  // `\let\pgfutil@reserved@c\pgfutil@reserved@b`, which `\usetikzlibrary` runs while the copy is read right after its
2380  // own `\def\pgfutil@reserved@b`, is no save-and-wrap — declining it lost 2207.07492's sn-jnl.cls:303
2381  // `\usetikzlibrary{snakes}`, and where `@b`'s loop body names `@c` it left pgf's recursion spinning to the timeout,
2382  // 2101.08181's lmcs.cls copy)
2383  let reassigned_by_the_copy = state!()
2384    .copy_provides_frames
2385    .iter()
2386    .rev()
2387    .find(|frame| frame.id == id && !frame.repeat)
2388    .is_some_and(|frame| frame.assigned.contains(&meaning_key(source)));
2389  if reassigned_by_the_copy || !meaning_reaches(meaning, key) {
2390    return false;
2391  }
2392  let mut state = state_mut!();
2393  if let Some(copy) = state.copy_provides_copies.get_mut(id as usize - 1)
2394    && copy.declined.insert(key)
2395  {
2396    let file = copy.file.clone();
2397    drop(state);
2398    let name = token.with_cs_name(ToString::to_string);
2399    let source_name = source.with_cs_name(ToString::to_string);
2400    Info!(
2401      "provide",
2402      name,
2403      s!(
2404        "{name} keeps its saved {source_name}: the paper's {file} saves {source_name} again after its binding \
2405         redefined it"
2406      )
2407    );
2408  }
2409  true
2410}
2411
2412/// Does the macro `meaning` reach the name `key` — `key` in its body, or in the body of a macro its body names, and so
2413/// on — so that `\let\<key>` to it would make it call itself? A breadth-first walk over macro bodies, each name visited
2414/// once, up to [`MEANING_REACH_LIMIT`] names (beyond it, no: the wrapper the walk looks for calls its saved command
2415/// within a step or two — jmlrutils.sty:466-494's `\newtheorem` → `\jmlr@newtheorem` → `\jmlr@org@newtheorem`,
2416/// epl2.cls's `\bibitem` → `\epl@org@bibitem`).
2417fn meaning_reaches(meaning: &Stored, key: SymStr) -> bool {
2418  let mut seen: HashSet<SymStr> = HashSet::default();
2419  let mut pending: VecDeque<Stored> = VecDeque::from([meaning.clone()]);
2420  while let Some(current) = pending.pop_front() {
2421    let Stored::Expandable(defn) = current else {
2422      continue;
2423    };
2424    let Some(ExpansionBody::Tokens(body)) = defn.get_expansion() else {
2425      continue;
2426    };
2427    for t in body.unlist_ref().iter() {
2428      if !matches!(t.get_catcode(), Catcode::CS | Catcode::ACTIVE) {
2429        continue;
2430      }
2431      let name = meaning_key(t);
2432      if name == key {
2433        return true;
2434      }
2435      if seen.len() >= MEANING_REACH_LIMIT {
2436        return false;
2437      }
2438      if seen.insert(name)
2439        && let Some(next) = lookup_meaning(t)
2440      {
2441        pending.push_back(next);
2442      }
2443    }
2444  }
2445  false
2446}
2447
2448/// How many names [`meaning_reaches`] visits at most.
2449const MEANING_REACH_LIMIT: usize = 256;
2450
2451/// Does a stand-in's copy, read now ([`note_copy_provides_assignment`]), (re)declare or renumber the counter `ctr` the
2452/// stand-in binding's own load declared or numbered (its `\c@<ctr>` assigned while the binding loaded,
2453/// `State::stand_in_meanings`, or the `\the<ctr>` of a counter that exists: `\newcounter`, `\numberwithin`,
2454/// `\@addtoreset`, `\counterwithin`)? Then the counter keeps the binding's numbering: its reset list is the binding's, as
2455/// its `\the<ctr>` is. Any other counter is the copy's, declared for real (`new_counter` suspends the copy's
2456/// provides-mode for it): the kernel's `equation` with the pool's article `\theequation` — as article.cls's defaults
2457/// yield to the real class's own: jheppub.sty:313-314
2458/// `\renewcommand\theequation{\thesection.\arabic{equation}}` and `\numberwithin{equation}{section}` number (2.1) as its
2459/// PDF does (2112.14648, 2607.20603) — and a counter the binding only has a `\the<ctr>` for, OmniBus's `\thechapter`
2460/// autoload stub: WileyNJDv5.cls:5728 and MRM.cls:2160 `\newcounter{chapter}[part]`, ws-rv9x6.cls:399
2461/// `\newcounter{chapter}` (2301.03442: declined, `\c@chapter` was "not a register"). Logged once per copy, at Info.
2462pub fn copy_provides_keeps_counter(ctr: &str) -> bool {
2463  let id = crate::definition::origin::copy_provides();
2464  if id == 0 || state_is_unlocked() {
2465    return false;
2466  }
2467  let counter = T_CS!(s!("\\c@{ctr}"));
2468  let numbered = |token: &Token| state!().stand_in_meanings.contains(&meaning_key(token));
2469  // (a `\the<ctr>` numbers a counter that exists — the kernel's `equation` — not one it only stands for: OmniBus's
2470  // `\thechapter` autoload stub with no `\c@chapter`)
2471  let exists = lookup_meaning(&counter).is_some_and(|meaning| !matches!(meaning, Stored::None));
2472  if !numbered(&counter) && !(exists && numbered(&T_CS!(s!("\\the{ctr}")))) {
2473    return false;
2474  }
2475  let key = meaning_key(&counter);
2476  let mut state = state_mut!();
2477  if let Some(copy) = state.copy_provides_copies.get_mut(id as usize - 1)
2478    && copy.declined.insert(key)
2479  {
2480    let file = copy.file.clone();
2481    drop(state);
2482    Info!(
2483      "provide",
2484      ctr,
2485      s!("Counter {ctr} keeps LaTeXML's numbering: the paper's {file} redeclares or renumbers it")
2486    );
2487  }
2488  true
2489}
2490
2491/// The counter whose representation or reset list `name` is — `\the<ctr>`, `\p@<ctr>`, `\cl@<ctr>` of a counter
2492/// `\c@<ctr>` — for [`note_copy_provides_assignment`] and [`copy_provides_keeps_counter`].
2493fn counter_part(name: &str) -> Option<String> {
2494  let ctr = name
2495    .strip_prefix("\\the")
2496    .or_else(|| name.strip_prefix("\\p@"))
2497    .or_else(|| name.strip_prefix("\\cl@"))?;
2498  if ctr.is_empty() {
2499    return None;
2500  }
2501  matches!(
2502    lookup_meaning(&T_CS!(s!("\\c@{ctr}"))),
2503    Some(Stored::Register(_))
2504  )
2505  .then(|| ctr.to_string())
2506}
2507
2508/// Keep a stand-in copy's own title page (`\maketitle`, `\@maketitle`), defined while it is read
2509/// ([`install_definition`], `\newcommand`'s refusal), whether the binding's lock refuses it or the overlay holds it:
2510/// what it prints decides which of the copy's setter defaults the document shows (`frontmatter_stores::copy_title_page_prints`,
2511/// latexml_engine).
2512pub fn note_copy_provides_title_page(token: &Token, body: &Tokens) {
2513  let id = crate::definition::origin::copy_provides();
2514  if id == 0 || !matches!(token.get_catcode(), Catcode::CS) {
2515    return;
2516  }
2517  if !token.with_cs_name(|name| matches!(name, "\\maketitle" | "\\@maketitle")) {
2518    return;
2519  }
2520  if let Some(copy) = state_mut!().copy_provides_copies.get_mut(id as usize - 1) {
2521    copy.title_page.push(body.clone());
2522    if token.with_cs_name(|name| name == "\\maketitle") {
2523      copy.maketitle = Some(body.clone());
2524    }
2525  }
2526}
2527
2528/// The latest stand-in copy's own `\maketitle` body ([`note_copy_provides_title_page`]), with the copy's number
2529/// ([`new_copy_provides_record`]) and file: the `\maketitle` pdflatex runs where the binding keeps LaTeXML's (spconf.sty's,
2530/// 2110.09738; latexml_engine `latex_constructs::class_maketitle_in_force`).
2531pub fn copy_provides_maketitle() -> Option<(u32, String, Tokens)> {
2532  state!()
2533    .copy_provides_copies
2534    .iter()
2535    .enumerate()
2536    .rev()
2537    .find_map(|(index, copy)| {
2538      (copy.maketitle.clone()).map(|body| (index as u32 + 1, copy.file.clone(), body))
2539    })
2540}
2541
2542/// The number the next stand-in copy gets ([`new_copy_provides_record`]).
2543pub fn next_copy_provides_id() -> u32 { state!().copy_provides_copies.len() as u32 + 1 }
2544
2545/// The `\maketitle` body ([`note_copy_provides_title_page`]) of the first stand-in copy of `file` numbered `from` or
2546/// later, with its number.
2547pub fn copy_provides_maketitle_of(file: &str, from: u32) -> Option<(u32, Tokens)> {
2548  state!()
2549    .copy_provides_copies
2550    .iter()
2551    .enumerate()
2552    .skip(from.saturating_sub(1) as usize)
2553    .find(|(_, copy)| copy.file == file)
2554    .and_then(|(index, copy)| copy.maketitle.clone().map(|body| (index as u32 + 1, body)))
2555}
2556
2557/// What [`watch_meanings`]' selection says of a name.
2558#[derive(Clone, Copy, PartialEq, Eq)]
2559pub enum WatchedName {
2560  No,
2561  Yes,
2562  /// Watched, its `\relax` being what a `\csname` leaves on a name not yet defined rather than a meaning of its own.
2563  RelaxIsUnset,
2564}
2565
2566/// A selection of names for [`watch_meanings`]. Asked of every assignment a document or a raw file makes, so the bytes after a
2567/// name's backslash that `select` can take are the only cost of any other name: 1 of 3 at the second, one at the third.
2568#[derive(Clone, Copy)]
2569pub struct MeaningWatch {
2570  pub second_byte: [u8; 3],
2571  pub third_byte:  u8,
2572  pub select:      fn(&str) -> WatchedName,
2573}
2574
2575impl MeaningWatch {
2576  #[inline]
2577  fn may_take(&self, second: u8, third: u8) -> bool {
2578    third == self.third_byte && self.second_byte.contains(&second)
2579  }
2580}
2581
2582/// Watch the meanings of the control sequences whose names `select` takes, from now on: any later assignment by a document,
2583/// a raw file or a format file that changes the standing meaning of one, however local, is seen by
2584/// [`watched_meaning_changed`] for the rest of the conversion; a new name has none to change. A native path that stands for a family of macros answers only while they are what it ports, at
2585/// the cost of a test by two bytes per such assignment and none per use (latexml_engine `l3fp_native`).
2586pub fn watch_meanings(select: MeaningWatch) {
2587  let mut state = state_mut!();
2588  state.meaning_watch = Some(select);
2589  state.watched_meaning_changed = None;
2590}
2591
2592/// Has a meaning [`watch_meanings`] watches changed? The first that did.
2593pub fn watched_meaning_changed() -> Option<SymStr> { state!().watched_meaning_changed }
2594
2595/// Would [`note_setter_call`] observe a call of `cs`? Without the observation, for a native reader that declines such a
2596/// call to whoever then makes it.
2597pub fn setter_call_is_observed(cs: &Token) -> bool {
2598  crate::definition::origin::copy_default_watch()
2599    && crate::definition::origin::copy_provides() == 0
2600    && state!().watched_setters.contains(&meaning_key(cs))
2601}
2602
2603/// Observe the calls of the setters `names` ([`State::watched_setters`]).
2604pub fn watch_setters(names: &[&str]) {
2605  let keys: Vec<SymStr> = names.iter().map(|name| meaning_key(&T_CS!(name))).collect();
2606  state_mut!().watched_setters.extend(keys);
2607}
2608
2609/// A macro `cs` is called (`Expandable::invoke`, while [`crate::definition::origin::setter_watch`]): a watched setter
2610/// called outside a stand-in copy's read is the document's (or its binding's) call, `<cs>:called`, whatever its
2611/// arguments — `\author{}` as much as `\author{Jane Doe}`, which a binding's accumulating `\author` (inst_support's)
2612/// does not queue nor clear.
2613pub fn note_setter_call(cs: &Token) {
2614  if setter_call_is_observed(cs) {
2615    assign_value(
2616      &cs.with_cs_name(|name| s!("{name}:called")),
2617      true,
2618      Some(Scope::Global),
2619    );
2620  }
2621}
2622
2623/// A call of one of LaTeXML's own macros (a binding's or the kernel's) that read its arguments from the document's own
2624/// text ([`note_document_call`]): the title-page check's second source.
2625#[derive(Debug, Clone)]
2626pub struct DocumentCall {
2627  /// the macro called
2628  pub cs:   Token,
2629  /// its arguments as read, kept once: every entry made inside the call shares them ([`claim_open_document_calls`])
2630  pub args: CallArguments,
2631  /// the input after its arguments: its expansion is read before it (open while [`gullet::input_unread_since`])
2632  mark:     gullet::InputMark,
2633  /// the entry queued inside it first, by the title-page check's count ([`claim_open_document_calls`])
2634  claimed:  Option<usize>,
2635}
2636
2637/// The arguments a [`DocumentCall`] read, shared by the entries made inside it.
2638pub type CallArguments = Rc<[DocumentArgument]>;
2639
2640/// An argument a [`DocumentCall`] read.
2641#[derive(Debug, Clone)]
2642pub struct DocumentArgument {
2643  /// its parameter's number (`#n`)
2644  pub number:   usize,
2645  /// its parameter is optional
2646  pub optional: bool,
2647  /// the call's body names it (`#n`), or its use is unknown (a closure's): it is handed on; or the macro is the kernel's,
2648  /// whose drop is TeX's own, or the binding declares it dropped by design (`Expandable::dropped_by_design`): no loss
2649  pub used:     bool,
2650  /// the tokens read
2651  pub tokens:   Tokens,
2652}
2653
2654thread_local! {
2655  /// The document calls whose expansions are still being read ([`note_document_call`]), innermost last.
2656  static DOCUMENT_CALLS: RefCell<Vec<DocumentCall>> = const { RefCell::new(Vec::new()) };
2657}
2658
2659/// A macro of LaTeXML's own read its arguments `args` from the document's text (`Expandable::invoke`, while
2660/// [`crate::definition::origin::document_call_watch`]): kept while its expansion is read, the calls whose expansions
2661/// ended dropped. An argument-less call is not kept.
2662pub fn note_document_call(cs: Token, args: Vec<DocumentArgument>) {
2663  DOCUMENT_CALLS.with(|calls| {
2664    let mut calls = calls.borrow_mut();
2665    calls.retain(|call| gullet::input_unread_since(&call.mark));
2666    if args.iter().any(|arg| !arg.tokens.is_empty()) {
2667      calls.push(DocumentCall {
2668        cs,
2669        args: args.into(),
2670        mark: gullet::input_mark(),
2671        claimed: None,
2672      });
2673    }
2674  });
2675}
2676
2677/// The document calls whose expansions are being read now ([`note_document_call`]), for an entry `claimer` the
2678/// frontmatter API queues inside them (latexml_engine `title_page_check::note_frontmatter_entry`): `None` when there are
2679/// none, else the claimer of the outermost (the entry an earlier one inside the same call made, or `claimer`), those no
2680/// entry claimed before, outermost first, now `claimer`'s, and the arguments of them all — shared, not copied: an
2681/// `\author` of 3,000 names joined by `\and` makes 3,000 entries inside one call.
2682pub fn claim_open_document_calls(
2683  claimer: usize,
2684) -> Option<(usize, Vec<DocumentCall>, Vec<CallArguments>)> {
2685  DOCUMENT_CALLS.with(|calls| {
2686    let mut calls = calls.borrow_mut();
2687    calls.retain(|call| gullet::input_unread_since(&call.mark));
2688    let outermost = calls.first()?.claimed.unwrap_or(claimer);
2689    let arguments = calls.iter().map(|call| Rc::clone(&call.args)).collect();
2690    let mut claimed = Vec::new();
2691    for call in calls.iter_mut().filter(|call| call.claimed.is_none()) {
2692      call.claimed = Some(claimer);
2693      claimed.push(call.clone());
2694    }
2695    Some((outermost, claimed, arguments))
2696  })
2697}
2698
2699/// A call of a setter a raw class or a raw file of the document's own directory made ([`note_store_call`]).
2700#[derive(Debug, Clone)]
2701pub struct StoreCall {
2702  /// the setter
2703  pub cs:     Token,
2704  /// a later call of it replaces this one, the stores it writes
2705  /// ([`crate::definition::expandable::StoredParameters`])
2706  pub stored: expandable::StoredParameters,
2707  /// the arguments it writes into a store
2708  pub args:   Vec<Tokens>,
2709  /// those of them optional or in brackets: a store's key or label far more often than its text
2710  pub keys:   Vec<Tokens>,
2711}
2712
2713/// What [`take_store_calls`] gives: the setter calls kept, and what the bound left out.
2714#[derive(Debug, Default)]
2715pub struct StoreCalls {
2716  /// the calls, in order
2717  pub calls:           Vec<StoreCall>,
2718  /// how many calls [`STORE_CALLS_KEPT`] left out
2719  pub dropped:         usize,
2720  /// the setters of those, the first few, each once
2721  pub dropped_setters: Vec<Token>,
2722}
2723
2724/// The most setter calls kept ([`note_store_call`]): a document whose own style's setter is called thousands of times
2725/// before its title page keeps the first ones; what the check digests stays bounded.
2726pub const STORE_CALLS_KEPT: usize = 512;
2727
2728/// How many setters of the calls left out [`StoreCalls::dropped_setters`] names.
2729const DROPPED_SETTERS_NAMED: usize = 8;
2730
2731thread_local! {
2732  /// The setter calls the document's text made before its title page ([`note_store_call`]).
2733  static STORE_CALLS: RefCell<StoreCalls> = RefCell::new(StoreCalls::default());
2734}
2735
2736/// A setter a raw class or a raw file of the document's own directory made was called while the document's text is read
2737/// (`Expandable::invoke`, while [`crate::definition::origin::store_call_watch`]): its stored arguments `args`, and those
2738/// `keys` optional or in brackets, kept for the title-page check's third source (latexml_engine
2739/// `title_page_check::digest_raw_setter_calls`); a replacing setter's earlier call is superseded by this one, as its store is.
2740pub fn note_store_call(
2741  cs: Token,
2742  stored: &expandable::StoredParameters,
2743  args: Vec<Tokens>,
2744  keys: Vec<Tokens>,
2745) {
2746  STORE_CALLS.with(|calls| {
2747    let mut calls = calls.borrow_mut();
2748    if stored.replaces {
2749      calls.calls.retain(|call| call.cs != cs);
2750    }
2751    if args.is_empty() && keys.is_empty() {
2752      return;
2753    }
2754    if calls.calls.len() < STORE_CALLS_KEPT {
2755      calls.calls.push(StoreCall {
2756        cs,
2757        stored: stored.clone(),
2758        args,
2759        keys,
2760      });
2761    } else {
2762      calls.dropped += 1;
2763      if calls.dropped_setters.len() < DROPPED_SETTERS_NAMED && !calls.dropped_setters.contains(&cs)
2764      {
2765        calls.dropped_setters.push(cs);
2766      }
2767    }
2768  });
2769}
2770
2771/// The setter calls kept ([`note_store_call`]), taken: none are left, a new conversion's or after a title page's.
2772pub fn take_store_calls() -> StoreCalls {
2773  STORE_CALLS.with(|calls| std::mem::take(&mut *calls.borrow_mut()))
2774}
2775
2776/// Does the control sequence `cs` mean a token register (`\newtoks`, `\toks@`)?
2777pub fn is_token_register(cs: &Token) -> bool {
2778  use crate::definition::register::RegisterType;
2779  with_meaning(cs, |meaning| match meaning {
2780    Some(Stored::Register(register)) => matches!(register.register_type, RegisterType::Tokens),
2781    _ => false,
2782  })
2783}
2784
2785thread_local! {
2786  /// The arguments binding macros dropped while the watch was on ([`note_dropped_argument`]).
2787  static DROPPED_ARGUMENTS: RefCell<Vec<DroppedArgument>> = const { RefCell::new(Vec::new()) };
2788}
2789
2790/// An argument a macro dropped, which the title-page check digests itself ([`note_dropped_argument`]; latexml_engine
2791/// `title_page_check::never_digested`).
2792#[derive(Debug, Clone)]
2793pub struct DroppedArgument {
2794  /// the macro that dropped it
2795  pub cs:     Token,
2796  /// its parameter's number (`#n`)
2797  pub number: usize,
2798  /// the tokens read
2799  pub tokens: Tokens,
2800}
2801
2802/// A binding's macro `cs` dropped its required argument `argument` — its token body never names it, nor does the
2803/// binding declare it dropped by design (`Expandable::dropped_by_design`) — while a frontmatter entry the document gave
2804/// is digested (`Expandable::invoke`, while [`crate::definition::origin::dropped_argument_watch`]): kept for the
2805/// title-page check (latexml_engine `title_page_check`, jmlr's `\titletag`). A blank argument is not kept.
2806pub fn note_dropped_argument(cs: Token, argument: &DocumentArgument) {
2807  if argument.tokens.unlist_ref().iter().any(|token| {
2808    !matches!(
2809      token.get_catcode(),
2810      Catcode::SPACE | Catcode::BEGIN | Catcode::END
2811    )
2812  }) {
2813    DROPPED_ARGUMENTS.with(|dropped| {
2814      dropped.borrow_mut().push(DroppedArgument {
2815        cs,
2816        number: argument.number,
2817        tokens: argument.tokens.clone(),
2818      })
2819    });
2820  }
2821}
2822
2823/// The arguments binding macros dropped ([`note_dropped_argument`]) since the count `from`, taken; with `from` the
2824/// count before them, for a nested watch.
2825pub fn take_dropped_arguments(from: usize) -> Vec<DroppedArgument> {
2826  DROPPED_ARGUMENTS.with(|dropped| {
2827    let mut dropped = dropped.borrow_mut();
2828    let from = from.min(dropped.len());
2829    dropped.split_off(from)
2830  })
2831}
2832
2833/// How many arguments binding macros dropped so far ([`note_dropped_argument`]): a watch's start.
2834pub fn dropped_argument_count() -> usize {
2835  DROPPED_ARGUMENTS.with(|dropped| dropped.borrow().len())
2836}
2837
2838/// Forget the document calls ([`note_document_call`]): a conversion's start.
2839pub fn reset_document_calls() {
2840  DOCUMENT_CALLS.with(|calls| calls.borrow_mut().clear());
2841  DROPPED_ARGUMENTS.with(|dropped| dropped.borrow_mut().clear());
2842}
2843
2844/// Was the watched setter `cs` called outside a stand-in copy's read ([`note_setter_call`])?
2845pub fn setter_called(cs: &Token) -> bool {
2846  lookup_bool(&cs.with_cs_name(|name| s!("{name}:called")))
2847}
2848
2849/// The title pages stand-in copies defined ([`note_copy_provides_title_page`]), each with its copy's number, for
2850/// `frontmatter_stores::copy_title_page_prints` (latexml_engine).
2851pub fn copy_provides_title_pages() -> Vec<(u32, Tokens)> {
2852  state!()
2853    .copy_provides_copies
2854    .iter()
2855    .enumerate()
2856    .flat_map(|(index, copy)| {
2857      copy
2858        .title_page
2859        .iter()
2860        .map(move |body| (index as u32 + 1, body.clone()))
2861    })
2862    .collect()
2863}
2864
2865/// Copy `id`'s own version of the name `token` the binding owns, kept in its overlay while the binding's meaning is in
2866/// force ([`note_copy_provides_assignment`]).
2867pub fn copy_provides_overlaid_meaning(id: u32, token: &Token) -> Option<Stored> {
2868  state!()
2869    .copy_provides_copies
2870    .get((id as usize).checked_sub(1)?)
2871    .and_then(|copy| copy.overlay.get(&meaning_key(token)).cloned())
2872}
2873
2874/// Begin a frame of copy `id`'s provides-mode ([`crate::definition::origin::enter_copy_provides`]; `0` suspends the mode for
2875/// a file the copy loads, a repeat of the mode in force adds nothing): the copy's own definitions of names the binding
2876/// owns, kept from its earlier read or hooks, are in force again for its code, the meanings they replace kept aside.
2877pub fn enter_copy_provides_frame(id: u32, previous: u32) {
2878  let mut kept = Vec::new();
2879  let mut kept_keys = rustc_hash::FxHashSet::default();
2880  if id != 0 && id != previous {
2881    let overlay: Vec<(SymStr, Stored)> = state!()
2882      .copy_provides_copies
2883      .get(id as usize - 1)
2884      .map(|copy| copy.overlay.iter().map(|(k, v)| (*k, v.clone())).collect())
2885      .unwrap_or_default();
2886    for (key, meaning) in overlay {
2887      let current = meaning_by_key(key);
2888      kept.push((key, current));
2889      kept_keys.insert(key);
2890      state_mut!().assign_internal(TableName::Meaning, key, meaning, Some(Scope::Global));
2891    }
2892  }
2893  state_mut!().copy_provides_frames.push(CopyProvidesFrame {
2894    id,
2895    repeat: id == previous,
2896    kept,
2897    kept_keys,
2898    assigned: rustc_hash::FxHashSet::default(),
2899    opener: None,
2900  });
2901}
2902
2903/// End the frame [`enter_copy_provides_frame`] began: each name the copy's code redefined, and the binding owns, takes
2904/// back the meaning kept aside, and the copy's own is kept for its next frame (a hook it registered).
2905pub fn leave_copy_provides_frame() {
2906  let Some(frame) = state_mut!().copy_provides_frames.pop() else {
2907    return;
2908  };
2909  if frame.id == 0 || frame.repeat {
2910    return;
2911  }
2912  let mut frame = frame;
2913  copy_text_names_stand(&mut frame);
2914  // (a copy whose `\<env>` is the file's own, as the binding declared it, leaves the binding's: TeX Live's
2915  // longtable.sty shipped beside the paper; one that changed it keeps its own)
2916  if let Some((key, binding, stock)) = frame.opener.take()
2917    && stock.contains(&meaning_by_key(key))
2918  {
2919    frame.assigned.remove(&key);
2920    frame.kept_keys.insert(key);
2921    frame.kept.push((key, binding));
2922  }
2923  // A name the copy `\let` to its own version of a name the binding owns takes the binding's back with it:
2924  // emulateapj5.sty:386 defines `\keywords`, :394 `\let\subjectheadings=\keywords`, and the document's
2925  // `\subjectheadings` made the class's "Subject headings:" paragraph where the binding makes `<keywords>`
2926  // (astro-ph0011001). Kept in the copy's overlay with the rest, for its hooks. Only a definition the copy made under
2927  // the kept name itself: a kept flag the copy `\let` to `\iftrue` shares that object with every other true flag
2928  // (elife.cls:336-337's `\ifstre@msuppinfoopen`, newfile.sty:91: 2303.08822).
2929  let replaced: Vec<(Stored, Stored)> = frame
2930    .kept
2931    .iter()
2932    .map(|(key, kept)| (*key, meaning_by_key(*key), kept.clone()))
2933    .filter(|(key, copys, kept)| {
2934      !same_meaning(copys, kept) && definition_cs(copys).is_some_and(|cs| meaning_key(&cs) == *key)
2935    })
2936    .map(|(_, copys, kept)| (copys, kept))
2937    .collect();
2938  if !replaced.is_empty() {
2939    for key in &frame.assigned {
2940      let current = meaning_by_key(*key);
2941      if let Some((_, kept)) = replaced
2942        .iter()
2943        .find(|(copys, _)| same_meaning(copys, &current))
2944      {
2945        let mut state = state_mut!();
2946        if let Some(copy) = state.copy_provides_copies.get_mut(frame.id as usize - 1) {
2947          copy.overlay.insert(*key, current);
2948        }
2949        state.assign_internal(TableName::Meaning, *key, kept.clone(), Some(Scope::Global));
2950      }
2951    }
2952  }
2953  for (key, kept) in frame.kept.into_iter().rev() {
2954    let copys = meaning_by_key(key);
2955    // (a name the copy's code left as it found it — the kernel's `\protected@edef` lets `\protect` aside and back —
2956    // was not redefined: nothing to log)
2957    let redefined = !same_meaning(&copys, &kept);
2958    let mut state = state_mut!();
2959    let mut logged = None;
2960    if let Some(copy) = state.copy_provides_copies.get_mut(frame.id as usize - 1) {
2961      if redefined && copy.declined.insert(key) {
2962        logged = Some(copy.file.clone());
2963      }
2964      if redefined {
2965        copy.restored.insert(key, kept.clone());
2966      }
2967      copy.overlay.insert(key, copys);
2968    }
2969    state.assign_internal(TableName::Meaning, key, kept, Some(Scope::Global));
2970    drop(state);
2971    if let Some(file) = logged {
2972      let name = arena::to_string(key);
2973      Info!(
2974        "provide",
2975        name,
2976        s!(
2977          "{name} keeps LaTeXML's definition: the paper's {file} redefines it for its own code only"
2978        )
2979      );
2980    }
2981  }
2982}
2983
2984/// Are `a` and `b` the same meaning: the same definition object (a `\let` copies the object), or equal otherwise?
2985fn same_meaning(a: &Stored, b: &Stored) -> bool {
2986  match (a, b) {
2987    (Stored::Expandable(x), Stored::Expandable(y)) => Rc::ptr_eq(x, y),
2988    (Stored::Constructor(x), Stored::Constructor(y)) => Rc::ptr_eq(x, y),
2989    (Stored::Primitive(x), Stored::Primitive(y)) => Rc::ptr_eq(x, y),
2990    (Stored::MathPrimitive(x), Stored::MathPrimitive(y)) => Rc::ptr_eq(x, y),
2991    (Stored::Conditional(x), Stored::Conditional(y)) => Rc::ptr_eq(x, y),
2992    (Stored::Register(x), Stored::Register(y)) => Rc::ptr_eq(x, y),
2993    (Stored::Token(x), Stored::Token(y)) => x == y,
2994    (Stored::None, Stored::None) => true,
2995    _ => false,
2996  }
2997}
2998
2999/// The meaning bound to `key` (a [`meaning_key`]), `Stored::None` when there is none.
3000fn meaning_by_key(key: SymStr) -> Stored {
3001  state!()
3002    .meaning
3003    .get(&key)
3004    .and_then(|entry| entry.front().cloned())
3005    .unwrap_or(Stored::None)
3006}
3007
3008/// A routed copy's definitions of the declared text names (OXIDIZED_DESIGN_DIVERGENCES #731 rule 14,
3009/// [`copy_text_name_declared`]) that read as text ([`copy_text_refusal`]) stand for the document when its read ends,
3010/// as the real class's: they leave `frame`'s kept names, which the binding's meanings replace. Decided on the copy's
3011/// own meanings, before any is put back, so `\let\refname\relax` then `\newcommand\refname{…}` is the copy's last.
3012/// Logged once per name, at Info.
3013fn copy_text_names_stand(frame: &mut CopyProvidesFrame) {
3014  let file = {
3015    let state = state!();
3016    match state.copy_provides_copies.get(frame.id as usize - 1) {
3017      Some(copy) if copy.routed => copy.file.clone(),
3018      _ => return,
3019    }
3020  };
3021  let mut standing = Vec::new();
3022  for (key, kept) in &frame.kept {
3023    let name = arena::to_string(*key);
3024    let copys = meaning_by_key(*key);
3025    if same_meaning(&copys, kept) || !copy_text_name_declared_as(&name) {
3026      continue;
3027    }
3028    match copy_text_refusal(&copys) {
3029      None => {
3030        standing.push(*key);
3031        Info!(
3032          "provide",
3033          name,
3034          s!("{name} takes the paper's {file} definition: a text name its binding declares")
3035        );
3036      },
3037      Some(refused) => {
3038        // (one Info per name, when it is first declined — the check runs again at each frame the copy's read leaves
3039        // — and not the general one of `leave_copy_provides_frame`)
3040        let first = state_mut!()
3041          .copy_provides_copies
3042          .get_mut(frame.id as usize - 1)
3043          .is_some_and(|copy| copy.declined.insert(*key));
3044        if first {
3045          Info!(
3046            "provide",
3047            name,
3048            s!(
3049              "{name} keeps LaTeXML's definition: the paper's {file} defines this text name as more than text \
3050               ({refused})"
3051            )
3052          );
3053        }
3054      },
3055    }
3056  }
3057  frame.kept.retain(|(key, _)| !standing.contains(key));
3058  for key in standing {
3059    frame.kept_keys.remove(&key);
3060  }
3061}
3062
3063/// Number a new stand-in copy of `file` for [`note_copy_provides_assignment`] (1-based,
3064/// [`crate::definition::origin::copy_provides`]); `routed`: its `\Provides` line routed it to `binding`
3065/// (OXIDIZED_DESIGN_DIVERGENCES #731 rule 12).
3066pub fn new_copy_provides_record(file: &str, binding: &str, routed: bool) -> u32 {
3067  let mut state = state_mut!();
3068  state.copy_provides_copies.push(CopyProvidesRecord {
3069    file: file.to_string(),
3070    binding: binding.to_string(),
3071    routed,
3072    ..CopyProvidesRecord::default()
3073  });
3074  state.copy_provides_copies.len() as u32
3075}
3076
3077/// The other names of the environment a name `\X`, `\endX`, `\begin{X}` or `\end{X}` belongs to (latex.ltx `\begin{X}`
3078/// runs `\X`, `\end{X}` runs `\endX`): for `\X` the binding's `\begin{X}`, `\end{X}` and the macro `\endX`, for `\endX`
3079/// `\begin{X}`, `\end{X}` and `\X`; for `\begin{X}` the macros `\X`, `\endX` and `\end{X}`, for `\end{X}` `\X`, `\endX`
3080/// and `\begin{X}`.
3081fn environment_names(name: &str) -> Vec<String> {
3082  if let Some(env) = name
3083    .strip_prefix("\\begin{")
3084    .and_then(|rest| rest.strip_suffix('}'))
3085  {
3086    return vec![s!("\\{env}"), s!("\\end{env}"), s!("\\end{{{env}}}")];
3087  }
3088  if let Some(env) = name
3089    .strip_prefix("\\end{")
3090    .and_then(|rest| rest.strip_suffix('}'))
3091  {
3092    return vec![s!("\\{env}"), s!("\\end{env}"), s!("\\begin{{{env}}}")];
3093  }
3094  match name.strip_prefix('\\') {
3095    Some(macro_name) if !macro_name.is_empty() => {
3096      match macro_name.strip_prefix("end").filter(|env| !env.is_empty()) {
3097        Some(env) => vec![s!("\\begin{{{env}}}"), s!("\\end{{{env}}}"), s!("\\{env}")],
3098        None => vec![
3099          s!("\\begin{{{macro_name}}}"),
3100          s!("\\end{{{macro_name}}}"),
3101          s!("\\end{macro_name}"),
3102        ],
3103      }
3104    },
3105    _ => Vec::new(),
3106  }
3107}
3108
3109/// Is `token`'s meaning a text default: a public name (letters only) whose meaning is a macro without parameters
3110/// expanding to text (characters, at least one letter: `\refname`'s "References")?
3111fn text_default(token: &Token) -> bool {
3112  let public = token.with_cs_name(|name| {
3113    name.strip_prefix('\\').is_some_and(|letters| {
3114      !letters.is_empty() && letters.chars().all(|c| c.is_ascii_alphabetic())
3115    })
3116  });
3117  if !public {
3118    return false;
3119  }
3120  let Some(Stored::Expandable(defn)) = lookup_meaning(token) else {
3121    return false;
3122  };
3123  if defn
3124    .paramlist
3125    .as_ref()
3126    .is_some_and(|params| !params.get_parameters().is_empty())
3127  {
3128    return false;
3129  }
3130  let Some(ExpansionBody::Tokens(body)) = &defn.expansion else {
3131    return false;
3132  };
3133  body.unlist_ref().iter().all(|t| {
3134    matches!(
3135      t.get_catcode(),
3136      Catcode::LETTER | Catcode::OTHER | Catcode::SPACE
3137    )
3138  }) && body
3139    .unlist_ref()
3140    .iter()
3141    .any(|t| t.get_catcode() == Catcode::LETTER)
3142}
3143
3144/// Is `token`'s meaning a text default ([`text_default`]) the stand-in binding does not own, for
3145/// [`note_copy_provides_assignment`]: assigned last by the base class the binding loaded
3146/// (`State::stand_in_base_defaults`: article, report or book, whose bindings assign their classes' names in their own
3147/// load, the OmniBus guess) or by LaTeXML's kernel before it? Then the copy's definition of it stands, as the real
3148/// class's does over article.cls's: MRM.cls:3191 `\def\refname{REFERENCES}` (2506.14995's PDF), ws-rv9x6.cls:91
3149/// `\newcommand\bibname{References}` (2301.03442). One the binding's own code assigned, or a binding it required
3150/// (natbib's), stays the binding's.
3151fn unowned_text_default(token: &Token) -> bool {
3152  use crate::definition::origin::DefinitionOrigin;
3153  if !text_default(token) {
3154    return false;
3155  }
3156  let key = meaning_key(token);
3157  if state!().stand_in_meanings.contains(&key) {
3158    return state!().stand_in_base_defaults.contains(&key);
3159  }
3160  let Some(Stored::Expandable(defn)) = lookup_meaning(token) else {
3161    return false;
3162  };
3163  matches!(
3164    defn.origin,
3165    DefinitionOrigin::Unknown | DefinitionOrigin::Pool
3166  ) || class_layer_definition(token)
3167}
3168
3169/// Does a stand-in's copy, read now, `\newcommand` a text default its binding does not own (`unowned_text_default`),
3170/// in a real class that lacks the name? Then the declaration defines it, as it does in TeX: LaTeXML's kernel or the
3171/// binding's base class predefined it, and no base class the copy loads defines it — a standalone class (ws-rv9x6.cls:91
3172/// `\newcommand\bibname{References}`, 2301.03442), or a name its base class lacks (article.cls has no `\bibname`). A
3173/// name the base class the copy `\LoadClass`es defines is the real class's already, so its `\newcommand` is TeX's
3174/// "already defined" ([`copy_provides_text_default_clashes`]).
3175pub fn copy_provides_text_default_yields(token: &Token) -> bool {
3176  crate::definition::origin::copy_provides() != 0
3177    && !state_is_unlocked()
3178    && unowned_text_default(token)
3179    && !copy_base_class_defines(token)
3180}
3181
3182/// Does a stand-in's copy, read now, `\newcommand` a text default its binding does not own that a base class it
3183/// `\LoadClass`ed defines (`copy_base_class_defines`: article.cls:616 `\newcommand\refname`, :618 `\figurename`, which
3184/// the article binding assigns in its own load; a raw base class's own definition)? The real class has the name, so
3185/// LaTeX stops with "Command … already defined" and keeps the first definition: an Error here as there (sect08.rs
3186/// `\newcommand`; the reviewer's probes newcmd_base and nc_chain, pdflatex 2 errors, "References"/"Figure 1";
3187/// nc_namedef 1). A name the base class made `\relax` is definable, as LaTeX's `\newcommand` finds it.
3188/// `\def`/`\renewcommand` redefine as before.
3189pub fn copy_provides_text_default_clashes(token: &Token) -> bool {
3190  crate::definition::origin::copy_provides() != 0
3191    && !state_is_unlocked()
3192    && text_default(token)
3193    && !binding_owns(token)
3194    && copy_base_class_defines(token)
3195}
3196
3197/// The stand-in binding the copy read now (`copy_provides`) was read after, or the empty string when no copy is read.
3198pub fn copy_provides_binding() -> String {
3199  let id = crate::definition::origin::copy_provides();
3200  if id == 0 {
3201    return String::new();
3202  }
3203  state!()
3204    .copy_provides_copies
3205    .get(id as usize - 1)
3206    .map(|copy| copy.binding.clone())
3207    .unwrap_or_default()
3208}
3209
3210/// The text names a stand-in's copy may supply over its binding, the kernel's default (OXIDIZED_DESIGN_DIVERGENCES
3211/// #731 rules 13 and 14; user ruling 2026-10-21: "the bindings should always win in terms of semantic markup … the
3212/// slight typographic variations in the raw .cls or .sty file … if we can preserve and reuse them that should be via
3213/// a generic mechanism that is set in the binding with a reasonable default"): the standard classes' and LaTeX's
3214/// `\…name` macros, the word a heading or a label prints — aip-cp.cls:875 `\newcommand\refname{REFERENCES}`
3215/// (1506.04050, 1604.08112), the AASTeX 6+ copies' `\def\abstractname{ABSTRACT}` (2107.03400), proto.cls:798
3216/// `\def\abstractname{~}` (1402.7103). A binding extends it with its own ([`declare_copy_text_names`]). Everything else
3217/// a binding defines is its markup of the class, and the copy's version of it is declined: caption formats
3218/// (`\fnum@<type>`, whose punctuation met the binding's caption separator, "Fig. 1.—.— " in 1106.2565), the caption
3219/// separator, `\@thmcountersep` (1803.06644's "Theorem 51"), `\the<ctr>`, `\p@<ctr>`, `\the<ctr>@ID`, list labels
3220/// (`\labelitemi`), `\today`, `\baselinestretch`, `\CurrentOption`, every `\lx@` name, structure.
3221pub const COPY_TEXT_NAMES: [&str; 13] = [
3222  "\\abstractname",
3223  "\\appendixname",
3224  "\\bibname",
3225  "\\chaptername",
3226  "\\contentsname",
3227  "\\figurename",
3228  "\\indexname",
3229  "\\listfigurename",
3230  "\\listtablename",
3231  "\\partname",
3232  "\\proofname",
3233  "\\refname",
3234  "\\tablename",
3235];
3236
3237/// Declare `names` (`\apj`) text names of the binding loading now, besides the kernel's [`COPY_TEXT_NAMES`]: a copy
3238/// routed to it or a derivative of its class may supply them (OXIDIZED_DESIGN_DIVERGENCES #731 rules 13 and 14). The
3239/// one declaration point of the mechanism, a value `"<name>:copy@text"` as a lock is `"<name>:locked"`; a binding
3240/// declares the names it defines, where it defines them (aas_macros_sty.rs: its journal abbreviations, which
3241/// 1402.7103's proto.cls :1729-1790 spells out, "Astrophys. J.").
3242pub fn declare_copy_text_names(names: &[&str]) {
3243  for name in names {
3244    assign_value(&s!("{name}:copy@text"), true, Some(Scope::Global));
3245  }
3246}
3247
3248/// Declare `{env}` the environment a paper's copy of `binding` keeps, and `table` the binding's table macro (OD #731
3249/// rule 15); `stock` names macros holding the file's own `\<env>` meanings, and a copy whose `\<env>` equals one, as our
3250/// `\ifx` compares (prefixes aside), leaves the binding's (OD #1202, [`leave_copy_provides_frame`]).
3251pub fn declare_copy_environment(binding: &str, env: &str, table: &str, stock: &[&str]) {
3252  assign_value(
3253    &s!("{binding}:copy@stock"),
3254    stock.join(" "),
3255    Some(Scope::Global),
3256  );
3257  assign_value(
3258    &s!("{binding}:copy@environment"),
3259    env.to_string(),
3260    Some(Scope::Global),
3261  );
3262  assign_value(
3263    &s!("{binding}:copy@table"),
3264    table.to_string(),
3265    Some(Scope::Global),
3266  );
3267}
3268
3269/// Does the copy read now keep `token` ([`declare_copy_environment`])? `\<env>` always; `\end<env>` only when the
3270/// copy also defined `\<env>` and it does not reach the binding's table macro (astro-ph0411798's mytable.sty keeps its
3271/// check-free `\longtable` and the binding's `\LT@array` … `\endlongtable`).
3272fn copy_keeps_environment_name(token: &Token, at: usize) -> bool {
3273  let binding = copy_provides_binding();
3274  let env = lookup_string(&s!("{binding}:copy@environment"));
3275  if env.is_empty() {
3276    return false;
3277  }
3278  let opener = T_CS!(s!("\\{env}"));
3279  token.with_cs_name(|name| {
3280    if name == s!("\\{env}") || name == s!("\\begin{{{env}}}") {
3281      return true;
3282    }
3283    if name != s!("\\end{env}") && name != s!("\\end{{{env}}}") {
3284      return false;
3285    }
3286    let table = meaning_key(&T_CS!(lookup_string(&s!("{binding}:copy@table"))));
3287    state!().copy_provides_frames[at]
3288      .assigned
3289      .contains(&meaning_key(&opener))
3290      && !lookup_meaning(&opener).is_some_and(|meaning| meaning_reaches(&meaning, table))
3291  })
3292}
3293
3294/// Note the binding's meaning of the environment's opener `token` (`\longtable`) that the copy's code first assigns in
3295/// the frame at `at`, with the file's own meanings the binding declared ([`declare_copy_environment`]), for
3296/// [`leave_copy_provides_frame`] to compare the copy's with.
3297fn note_copy_environment_opener(token: &Token, at: usize) {
3298  let binding = copy_provides_binding();
3299  let env = lookup_string(&s!("{binding}:copy@environment"));
3300  if state!().copy_provides_frames[at].opener.is_some()
3301    || !token.with_cs_name(|name| name == s!("\\{env}"))
3302  {
3303    return;
3304  }
3305  let stock: Vec<Stored> = lookup_string(&s!("{binding}:copy@stock"))
3306    .split_whitespace()
3307    .filter_map(|name| lookup_meaning(&T_CS!(name)))
3308    .collect();
3309  let kept = lookup_meaning(token).unwrap_or(Stored::None);
3310  state_mut!().copy_provides_frames[at].opener = Some((meaning_key(token), kept, stock));
3311}
3312
3313/// Does a stand-in's copy, read now, `\newenvironment` (`\newcommand`, `\providecommand`) the environment its binding
3314/// lets it keep ([`declare_copy_environment`])? Then the declaration defines it, as the first definition TeX sees: in
3315/// TeX the copy is the file, and the binding's `{longtable}` never existed.
3316pub fn copy_provides_environment_yields(name: &Token) -> bool {
3317  crate::definition::origin::copy_provides() != 0
3318    && !state_is_unlocked()
3319    && name.with_cs_name(|name| {
3320      let env = lookup_string(&s!("{}:copy@environment", copy_provides_binding()));
3321      !env.is_empty() && name == s!("\\{env}")
3322    })
3323}
3324
3325/// Is `token` a declared text name ([`COPY_TEXT_NAMES`], [`declare_copy_text_names`])? Decided by its name; a routed
3326/// copy's definition of it must read as text besides ([`copy_text_refusal`]).
3327fn copy_text_name_declared(token: &Token) -> bool { token.with_cs_name(copy_text_name_declared_as) }
3328
3329/// [`copy_text_name_declared`] for the name `name` (`\refname`).
3330fn copy_text_name_declared_as(name: &str) -> bool {
3331  COPY_TEXT_NAMES.contains(&name) || arena::get(s!("{name}:copy@text")).is_some_and(lookup_bool_sym)
3332}
3333
3334/// Is `token` a text name the standard class's binding assigned in its own load, which a derivative of that class read
3335/// now defines itself (`binding::content::standard_class_binding_assigned`, OXIDIZED_DESIGN_DIVERGENCES #731 rule 13)?
3336/// In TeX the derivative is read in the class's place, so its `\newcommand` of the name is the first: aip-cp.cls:875
3337/// `\newcommand\refname{REFERENCES}` (1506.04050, 1604.08112). Only a declared text name yields
3338/// (`copy_text_name_declared`: `\refname`, `\figurename`, `\abstractname`); every other name the binding defined
3339/// stays its markup of the class — `\appendix` (`<ltx:appendix>`, article_cls.rs, book_cls.rs), book's
3340/// `\frontmatter`/`\mainmatter`/`\backmatter` (unnumbered chapters), whose `\newcommand`s in a full class copy
3341/// (hep-ex0405054's book_modified.cls:531, math0301023's khbook.cls:285; 0705.2210, hep-ph0008011, cond-mat0402505,
3342/// quant-ph0409078) lost the appendices and numbered the preface; the caption formats (`\fnum@table`), `\@ptsize`,
3343/// `\@pnumwidth`. Names a stand-in the derivative loads assigned are not the class's (guard
3344/// `perfect_kernel_batch77w::standard_class_derivative_defines_only_its_class_names`).
3345pub fn standard_class_binding_name(token: &Token) -> bool {
3346  copy_text_name_declared(token)
3347    && crate::binding::content::standard_class_binding_assigned(meaning_key(token))
3348}
3349
3350/// Is a copy its `\Provides` line routed to its binding (OXIDIZED_DESIGN_DIVERGENCES #731 rule 12) read now, its own
3351/// code locked as a raw read's is?
3352fn reading_a_routed_copy() -> bool {
3353  let id = crate::definition::origin::copy_provides();
3354  id != 0
3355    && !state_is_unlocked()
3356    && state!()
3357      .copy_provides_copies
3358      .get(id as usize - 1)
3359      .is_some_and(|copy| copy.routed)
3360}
3361
3362/// Does a routed copy, read now, `\newcommand` (or `\providecommand`) a declared text name (`copy_text_name_declared`)
3363/// that LaTeXML's code defined (owned as rule 1 tells, `owned_by_the_semantic_layer`) and no base class the copy
3364/// `\LoadClass`es defines? Then the declaration defines it, as the real class's first definition (proto.cls:798's
3365/// `\abstractname`, :1731 `\newcommand\apj{\ref@jnl{\it Astrophys.\ J.}}` over the aas_macros binding's "ApJ",
3366/// 1402.7103; OXIDIZED_DESIGN_DIVERGENCES #731 rule 14); a name the copy's base class has is LaTeX's "already
3367/// defined", as before. Whether its definition stands for the document is decided when the copy's read ends
3368/// (`leave_copy_provides_frame`, `copy_text_refusal`).
3369pub fn routed_copy_text_name_yields(token: &Token) -> bool {
3370  copy_text_name_declared(token)
3371    && reading_a_routed_copy()
3372    && owned_by_the_semantic_layer(token)
3373    && !copy_base_class_defines(token)
3374}
3375
3376/// Why does the routed copy's meaning `meaning` of a declared text name not stand for the document, when the copy's
3377/// read ends (`leave_copy_provides_frame`; OXIDIZED_DESIGN_DIVERGENCES #731 rule 14)? `None`: it stands — a macro
3378/// without parameters whose body reads as text ([`text_body_refusal`]). The safety check reads the copy's own
3379/// definition and fails closed: `\let\refname\relax`, a macro reading arguments, one whose expansion is LaTeXML's code
3380/// or a `\refname` that sets a heading keeps the binding's; the reason names the first refused token.
3381fn copy_text_refusal(meaning: &Stored) -> Option<String> {
3382  let Stored::Expandable(defn) = meaning else {
3383    return Some(s!("not a macro"));
3384  };
3385  if defn
3386    .paramlist
3387    .as_ref()
3388    .is_some_and(|params| !params.get_parameters().is_empty())
3389  {
3390    return Some(s!("parameters"));
3391  }
3392  match &defn.expansion {
3393    Some(ExpansionBody::Tokens(body)) => {
3394      text_body_refusal(body.unlist_ref(), &mut Vec::new()).map(|refused| refused.to_string())
3395    },
3396    Some(ExpansionBody::Closure(_)) => Some(defn.cs.to_string()),
3397    None => None,
3398  }
3399}
3400
3401/// Does `meaning` read arguments — a macro or primitive with parameters?
3402fn reads_arguments(meaning: &Stored) -> bool {
3403  let params = match meaning {
3404    Stored::Expandable(defn) => defn.paramlist.as_ref(),
3405    Stored::Primitive(defn) => defn.paramlist.as_ref(),
3406    _ => None,
3407  };
3408  params.is_some_and(|params| !params.get_parameters().is_empty())
3409}
3410
3411/// The most macros a copy's text name may go through ([`text_body_refusal`]): a journal name's `\ref@jnl`, a font
3412/// switch's, a counter's representation; sectioning and title pages go through LaTeX's machinery of many more.
3413const TEXT_NAME_MACROS: usize = 32;
3414
3415/// The primitives of LaTeXML's code a text name may call besides those printing a character or selecting a font by
3416/// their definition ([`printing_primitive`]): the spaces a name prints, `\ ` (1402.7103's proto.cls:1731 `Astrophys.\
3417/// J.`), `~`'s `\lx@NBSP` (proto.cls:798 `\def\abstractname{~}`, :1737 `Appl.~Opt.`) and `\nobreakspace`'s
3418/// `\lx@nobreakspace`.
3419const TEXT_NAME_SPACES: &[&str] = &["\\ ", "\\lx@NBSP", "\\lx@nobreakspace"];
3420
3421/// LaTeX's font selection interface (NFSS, latex.ltx's `\DeclareRobustCommand\fontseries` …), which a font switch's
3422/// robust command reaches and LaTeXML defines (latex_constructs sect08.rs, sect13.rs): a text name may call them,
3423/// unfollowed — `\fontfamily` reads its argument under a lock, `\not@math@alphabet@@` reads one to warn in math. The
3424/// AASTeX 6+ and emulateapj copies' journal names reach them (`\let\jnl@style=\rm`, `\rm` → `\rmfamily` →
3425/// `\fontfamily\rmdefault\selectfont`: 2007.00749, 2107.03400, 1905.12710), the PoS copies' `\bfseries\scshape`
3426/// (1506.03731, 2504.20273).
3427const TEXT_NAME_FONT_SELECTION: &[&str] = &[
3428  "\\fontencoding",
3429  "\\fontfamily",
3430  "\\fontseries",
3431  "\\fontshape",
3432  "\\fontsize",
3433  "\\selectfont",
3434  "\\usefont",
3435  "\\not@math@alphabet",
3436  "\\not@math@alphabet@@",
3437  "\\lx@normalfont@base",
3438];
3439
3440/// Does the primitive `defn` print or select a font: a character (`\ss`), a font switch (`\it`, a `\font` selector)
3441/// or one of [`TEXT_NAME_SPACES`]?
3442fn printing_primitive(defn: &crate::definition::primitive::Primitive) -> bool {
3443  defn.font.is_some()
3444    || defn.font_id.is_some()
3445    || matches!(
3446      defn.replacement,
3447      Some(crate::definition::PrimitiveBody::String(_))
3448    )
3449    || defn
3450      .cs
3451      .with_cs_name(|name| TEXT_NAME_SPACES.contains(&name))
3452}
3453
3454/// The first token of `body`, a copy's definition of a declared text name, that does not read as text — the safety
3455/// check, which fails closed. Every macro it calls is followed, and those theirs call (at most [`TEXT_NAME_MACROS`],
3456/// `seen`); a robust command's `\protect\X` is followed through `\X` and LaTeX's inner `\X ` (`\DeclareRobustCommand`).
3457/// Characters, a `\let` or `\chardef` character (`\bgroup`, `\&`), a conditional (both branches are read), a font, a
3458/// primitive that prints or selects a font ([`printing_primitive`]), LaTeX's font selection commands
3459/// ([`TEXT_NAME_FONT_SELECTION`], not followed) and macros composing them read as text, so does an empty body (the
3460/// class prints no name). Refused: a constructor (an element), `\par` (a paragraph), `\csname`/`\endcsname` (a name
3461/// made at run time), an undefined name (an error), a macro whose expansion is LaTeXML's code (`\begin`), any other
3462/// primitive (`\noindent`, `\vskip`), a register, a locked command reading arguments (LaTeXML's markup interface:
3463/// `\@startsection`, `\@lbibitem`; a binding owns its calls, OXIDIZED_DESIGN_DIVERGENCES #500).
3464fn text_body_refusal(body: &[Token], seen: &mut Vec<SymStr>) -> Option<Token> {
3465  let protect = T_CS!("\\protect");
3466  for t in body {
3467    if !matches!(t.get_catcode(), Catcode::CS | Catcode::ACTIVE) || *t == protect {
3468      continue;
3469    }
3470    if t.with_cs_name(|name| matches!(name, "\\par" | "\\csname" | "\\endcsname")) {
3471      return Some(*t);
3472    }
3473    let key = meaning_key(t);
3474    if seen.contains(&key) {
3475      continue;
3476    }
3477    let meaning = lookup_meaning(t);
3478    if meaning.is_some() && t.with_cs_name(|name| TEXT_NAME_FONT_SELECTION.contains(&name)) {
3479      continue;
3480    }
3481    if t.with_cs_name(name_carries_lock) && meaning.as_ref().is_some_and(reads_arguments) {
3482      return Some(*t);
3483    }
3484    let reads_as_text = match meaning {
3485      Some(Stored::Expandable(defn)) => {
3486        seen.push(key);
3487        if seen.len() > TEXT_NAME_MACROS {
3488          return Some(*t);
3489        }
3490        match &defn.expansion {
3491          Some(ExpansionBody::Tokens(inner)) => {
3492            if let Some(refused) = text_body_refusal(inner.unlist_ref(), seen) {
3493              return Some(refused);
3494            }
3495            true
3496          },
3497          Some(ExpansionBody::Closure(_)) => false,
3498          None => true,
3499        }
3500      },
3501      Some(Stored::Primitive(defn)) => {
3502        printing_primitive(&defn)
3503          && defn
3504            .paramlist
3505            .as_ref()
3506            .is_none_or(|params| params.get_parameters().is_empty())
3507      },
3508      // (a `\chardef` character prints it: `\&`, latex.ltx's chardef, in the AASTeX copies' `A\&A`)
3509      Some(Stored::Register(register)) => {
3510        matches!(
3511          register.register_type,
3512          crate::definition::register::RegisterType::CharDef
3513        )
3514      },
3515      Some(
3516        Stored::Token(_) | Stored::Conditional(_) | Stored::Font(_) | Stored::FontDirective(_),
3517      ) => true,
3518      _ => false,
3519    };
3520    if !reads_as_text {
3521      return Some(*t);
3522    }
3523  }
3524  None
3525}
3526
3527/// Did the stand-in binding's own load assign `token` last (`State::stand_in_meanings`, not its base class's
3528/// `State::stand_in_base_defaults`)? Then the copy's definition only provides it ([`note_copy_provides_assignment`]).
3529fn binding_owns(token: &Token) -> bool {
3530  let key = meaning_key(token);
3531  let state = state!();
3532  state.stand_in_meanings.contains(&key) && !state.stand_in_base_defaults.contains(&key)
3533}
3534
3535/// The class file name a load request names (`article`, `dir/mybase.cls` → `article.cls`, `mybase.cls`).
3536pub fn class_file_name(file: &str) -> String {
3537  let name = file.trim();
3538  let name = name.rsplit(['/', '\\']).next().unwrap_or(name);
3539  if name.ends_with(".cls") {
3540    name.to_string()
3541  } else {
3542    s!("{name}.cls")
3543  }
3544}
3545
3546/// RAII frame of one class load (`binding::content::input_definitions`, a `.cls` with its options handled: the
3547/// `\documentclass`, a `\LoadClass`, a binding's `LoadClass!`). While it is open, the macros assigned outside LaTeXML's
3548/// kernel layers — the class binding's own (article.cls's names, article_cls.rs), the raw file's, a package's it
3549/// loads — and the names a lock kept from a definition it made are recorded as the class's (`State::class_loads`),
3550/// as its real file defines them; a repeat load records nothing new. A load a stand-in's copy requests (`copy`: its own
3551/// `\LoadClass`, or a class loaded while that one is open) also names the class among the copy's base classes
3552/// (`CopyProvidesRecord::loads_classes`), whose names its `\newcommand` finds defined
3553/// ([`copy_provides_text_default_clashes`]): chained `\LoadClass{mybase}` over article (the reviewer's probe nc_chain).
3554pub struct ClassLoadFrame {
3555  copy: bool,
3556}
3557
3558impl ClassLoadFrame {
3559  /// Open the frame of loading the class `file`, requested by the stand-in copy `copy` if any.
3560  pub fn enter(file: &str, copy: Option<u32>) -> Self {
3561    let name = class_file_name(file);
3562    let mut state = state_mut!();
3563    if let Some(id) = copy
3564      && let Some(record) = state.copy_provides_copies.get_mut(id as usize - 1)
3565      && !record.loads_classes.contains(&name)
3566    {
3567      record.loads_classes.push(name.clone());
3568    }
3569    // (a class loaded inside the frames open now is loaded inside each of them: the binding's `LoadClass!` of its
3570    // base class, ceurart_cls.rs → OmniBus → article, is a class the binding's load loaded)
3571    let state = &mut *state;
3572    // (the classes the load open now had loaded before this one: for a copy's own load, its binding's base classes)
3573    let outer_classes = copy
3574      .and_then(|_| state.class_load_frames.last())
3575      .and_then(|&open| state.class_loads.get(open))
3576      .map(|record| record.classes.clone())
3577      .unwrap_or_default();
3578    for &open in &state.class_load_frames {
3579      if let Some(outer) = state.class_loads.get_mut(open)
3580        && outer.file != name
3581        && !outer.classes.contains(&name)
3582      {
3583        outer.classes.push(name.clone());
3584      }
3585    }
3586    let index = match state
3587      .class_loads
3588      .iter()
3589      .position(|record| record.file == name)
3590    {
3591      Some(index) => index,
3592      None => {
3593        state.class_loads.push(ClassLoadRecord {
3594          file: name,
3595          ..ClassLoadRecord::default()
3596        });
3597        state.class_loads.len() - 1
3598      },
3599    };
3600    state.class_load_frames.push(index);
3601    if let Some(id) = copy {
3602      state.copy_class_loads.push((id, outer_classes));
3603    }
3604    ClassLoadFrame { copy: copy.is_some() }
3605  }
3606}
3607
3608impl Drop for ClassLoadFrame {
3609  fn drop(&mut self) {
3610    let mut state = state_mut!();
3611    state.class_load_frames.pop();
3612    if self.copy {
3613      state.copy_class_loads.pop();
3614    }
3615  }
3616}
3617
3618/// The stand-in copy whose own `\LoadClass` is open now, if any ([`ClassLoadFrame`]).
3619pub fn open_copy_class_load() -> Option<u32> { state!().copy_class_loads.last().map(|(id, _)| *id) }
3620
3621/// The classes the stand-in binding's load loaded — its base class — for the copy read now
3622/// ([`ClassLoadRecord::classes`]). While the copy's own code runs, the classes of the class load open now; inside a
3623/// class the copy's own `\LoadClass` loaded (a shipped mybase.cls between the copy and a TeX Live class), the classes
3624/// loaded when the copy's first class load began ([`State::copy_class_loads`]), so a class mybase.cls `\LoadClass`es
3625/// meets the binding's base class too, not the empty class load of mybase.cls (72a review r7 NIT 8; guard
3626/// `perfect_kernel_batchint23::a_shipped_intermediate_class_meets_the_class_slot`).
3627pub fn open_class_load_classes() -> Vec<String> {
3628  let state = state!();
3629  if crate::definition::origin::copy_provides() != 0 {
3630    return state
3631      .class_load_frames
3632      .last()
3633      .and_then(|&class| state.class_loads.get(class))
3634      .map(|record| record.classes.clone())
3635      .unwrap_or_default();
3636  }
3637  let Some((id, _)) = state.copy_class_loads.last() else {
3638    return Vec::new();
3639  };
3640  state
3641    .copy_class_loads
3642    .iter()
3643    .find(|(copy, _)| copy == id)
3644    .map(|(_, classes)| classes.clone())
3645    .unwrap_or_default()
3646}
3647
3648/// Name `classes` among the base classes of the stand-in copy `id` (`CopyProvidesRecord::loads_classes`): the classes
3649/// its binding loaded, which stand for the class the copy's own `\LoadClass` named (`binding::content`
3650/// `binding_base_class_stands_for`).
3651pub fn note_copy_base_classes(id: u32, classes: &[String]) {
3652  let mut state = state_mut!();
3653  if let Some(record) = state.copy_provides_copies.get_mut(id as usize - 1) {
3654    for class in classes {
3655      if !record.loads_classes.contains(class) {
3656        record.loads_classes.push(class.clone());
3657      }
3658    }
3659  }
3660}
3661
3662/// Record `key` as a name the class load open now defines ([`ClassLoadFrame`]).
3663fn note_class_load_name(key: SymStr) {
3664  let mut state = state_mut!();
3665  if let Some(&class) = state.class_load_frames.last()
3666    && let Some(record) = state.class_loads.get_mut(class)
3667  {
3668    record.names.entry(key).or_insert(None);
3669  }
3670}
3671
3672/// A lock dropped a definition of `token`: `<cs>:redefined`, and whose code made it, `<cs>:redefined@class` (a class
3673/// file's load, the packages it loads included: [`ClassLoadFrame`]) or `<cs>:redefined@document` (the document's, a
3674/// package's it loads). A document's by-meaning wrapper of the class's `\maketitle` (`\let\oldmt\maketitle
3675/// \renewcommand\maketitle{\oldmt}`) leaves the class's own title page in force (`latex_constructs::
3676/// title_marks_unknown`, OD #1053). A format file's drops (latex.ltx over the plain pool's `\newif`) are neither's.
3677pub fn note_redefined(token: &Token) {
3678  use crate::definition::origin::{DefinitionOrigin, current_origin};
3679  let by = if !state!().class_load_frames.is_empty() {
3680    Some("@class")
3681  } else if matches!(
3682    current_origin(),
3683    DefinitionOrigin::File | DefinitionOrigin::Document
3684  ) {
3685    Some("@document")
3686  } else {
3687    None
3688  };
3689  if by.is_some() {
3690    state_mut!().refused_names.insert(meaning_key(token));
3691  }
3692  for suffix in std::iter::once("").chain(by) {
3693    let key = arena::pin(token.with_cs_name(|cs| s!("{cs}:redefined{suffix}")));
3694    state_mut!().assign_internal(
3695      TableName::Value,
3696      key,
3697      Stored::Bool(true),
3698      Some(Scope::Global),
3699    );
3700  }
3701  // (and the file whose load made it, `\@currname.\@currext` as LaTeX keeps them: a class file's own, or an option file's
3702  // its class loads, 11lomcon.sty under `\documentstyle[11lomcon]{article}`, hep-ph0312288)
3703  if by.is_some() {
3704    let name = |cs: &str| match lookup_meaning(&T_CS!(cs)) {
3705      Some(Stored::Expandable(defn)) => match defn.get_expansion() {
3706        Some(ExpansionBody::Tokens(body)) => body.to_string(),
3707        _ => String::new(),
3708      },
3709      _ => String::new(),
3710    };
3711    let file = s!("{}.{}", name("\\@currname"), name("\\@currext"));
3712    let key = arena::pin(token.with_cs_name(|cs| s!("{cs}:redefined@in")));
3713    state_mut!().assign_internal(
3714      TableName::Value,
3715      key,
3716      Stored::String(arena::pin(&file)),
3717      Some(Scope::Global),
3718    );
3719  }
3720}
3721
3722/// A document's `\let\token1\token2` gives `token1` the meaning TeX's `\token2` has, which the lock's refusal record
3723/// says (`\lx@dropped@<cs>`, `<cs>:redefined@document`/`@class`/`@in`, [`note_redefined`]): `token2`'s records go
3724/// with it, and a `token1` refused before takes none (`\let\stdmaketitle\maketitle`, a refused `\renewcommand`, then
3725/// `\let\maketitle\stdmaketitle`: the class's again, 2509.02894). `:redefined` itself stays. OD #1053.
3726fn carry_refusal_records(token1: &Token, token2: &Token, scope: Option<Scope>) {
3727  {
3728    let state = state!();
3729    if !state.refused_names.contains(&meaning_key(token1))
3730      && !state.refused_names.contains(&meaning_key(token2))
3731    {
3732      return;
3733    }
3734  }
3735  let key = |t: &Token, suffix: &str| arena::pin(t.with_cs_name(|cs| s!("{cs}:redefined{suffix}")));
3736  let dropped =
3737    |t: &Token| arena::pin(t.with_cs_name(|cs| s!("\\lx@dropped@{}", cs.trim_start_matches('\\'))));
3738  let refused =
3739    |t: &Token| lookup_bool_sym(key(t, "@document")) || lookup_bool_sym(key(t, "@class"));
3740  let dropped_cs =
3741    |t: &Token| T_CS!(t.with_cs_name(|cs| s!("\\lx@dropped@{}", cs.trim_start_matches('\\'))));
3742  if refused(token2) {
3743    let values: Vec<Stored> = ["@document", "@class", "@in"]
3744      .iter()
3745      .map(|suffix| {
3746        state!()
3747          .lookup_value_sym(key(token2, suffix))
3748          .cloned()
3749          .unwrap_or(Stored::Bool(false))
3750      })
3751      .collect();
3752    let body = lookup_meaning(&dropped_cs(token2)).unwrap_or(Stored::None);
3753    let mut state = state_mut!();
3754    for (suffix, value) in ["@document", "@class", "@in"].into_iter().zip(values) {
3755      state.assign_internal(TableName::Value, key(token1, suffix), value, scope);
3756    }
3757    state.assign_internal(TableName::Meaning, dropped(token1), body, scope);
3758    state.refused_names.insert(meaning_key(token1));
3759  } else if refused(token1) {
3760    let mut state = state_mut!();
3761    for suffix in ["@document", "@class"] {
3762      state.assign_internal(
3763        TableName::Value,
3764        key(token1, suffix),
3765        Stored::Bool(false),
3766        scope,
3767      );
3768    }
3769    state.assign_internal(TableName::Meaning, dropped(token1), Stored::None, scope);
3770  }
3771}
3772
3773/// Does a base class of the stand-in copy read now — a class its own `\LoadClass` requested, or one loaded while that
3774/// was open ([`ClassLoadFrame`]) — define `token`: did that class's load frame assign it (article.cls:613-622's names,
3775/// which article_cls.rs assigns in its own load; a raw base class's `\expandafter\def\csname bibname\endcsname`, the
3776/// reviewer's probe nc_namedef) or a lock keep its definition? Its document-time code
3777/// (`\AtBeginDocument{\def\bibname…}`, nc_cond) has not run, so defines nothing yet, as in TeX.
3778fn copy_base_class_defines(token: &Token) -> bool {
3779  let id = crate::definition::origin::copy_provides();
3780  if id == 0 {
3781    return false;
3782  }
3783  let key = meaning_key(token);
3784  let state = state!();
3785  let Some(copy) = state.copy_provides_copies.get(id as usize - 1) else {
3786    return false;
3787  };
3788  copy.loads_classes.iter().any(|class| {
3789    state
3790      .class_loads
3791      .iter()
3792      .any(|record| record.file == *class && record.names.contains_key(&key))
3793  })
3794}
3795
3796/// Is `token`'s meaning the macro a class's load frame assigned it ([`ClassLoadFrame`]): the class layer's —
3797/// article.cls's names, which its binding assigns, a raw class's own —, not LaTeXML's semantic layer? A text default of
3798/// the class layer is the class's, as LaTeXML's kernel predefinitions of the same names are ([`unowned_text_default`]).
3799fn class_layer_definition(token: &Token) -> bool {
3800  let Some(Stored::Expandable(defn)) = lookup_meaning(token) else {
3801    return false;
3802  };
3803  let key = meaning_key(token);
3804  state!().class_loads.iter().any(
3805    |record| matches!(record.names.get(&key), Some(Some(assigned)) if Rc::ptr_eq(assigned, &defn)),
3806  )
3807}
3808
3809/// The one "has chapters" test (OXIDIZED_DESIGN #179): does the class have chapters, as the real class's
3810/// `\@ifundefined{chapter}` sees it? natbib's forks head the bibliography by it (NJDnatbib.sty:1050, ws-rv-har.sty:676),
3811/// appendix.sty:38 and titlesec.sty:1526 number by it, and the kernel's `\appendix` numbers within chapters only then
3812/// (`begin_appendices`). The answer the "has chapters" step stored after the document's class loaded
3813/// (`settle_chapter_after_class_load`, latexml_engine sect01.rs, [`CLASS_HAS_CHAPTERS`]); while a class loads, the
3814/// test made now ([`class_has_chapters_now`]), as a class's own `\@ifundefined{chapter}` is answered by what it has
3815/// defined so far. Not a `chapter` counter alone: WileyNJDv5.cls:5728 and MRM.cls:2160 `\newcounter{chapter}[part]` with
3816/// no `\chapter` (2609.08425, 2506.14995: "REFERENCES"; 2211.16474: "Appendix A"). A LaTeX 2.09 `\documentstyle`
3817/// document never settles (only a `\documentclass` retracts and settles, `\chapter:settles`); its class's end stores
3818/// the answer (`\chapter:stored`, `store_chapter_after_latex_ix_class_load`, latexml_engine sect01.rs), so
3819/// `\documentstyle[appendix]{report}` numbers its appendix chapters "Appendix A" and `\documentstyle{article}` with the
3820/// document's own `\newcounter{chapter}` + `\def\chapter` letters its appendix "A", as pdflatex. Before any class load
3821/// (plain TeX), the test made now.
3822pub fn class_defines_chapter() -> bool {
3823  if crate::binding::content::class_loading()
3824    || !(lookup_bool("\\chapter:settles") || lookup_bool("\\chapter:stored"))
3825  {
3826    class_has_chapters_now()
3827  } else {
3828    lookup_bool(CLASS_HAS_CHAPTERS)
3829  }
3830}
3831
3832/// The value [`class_defines_chapter`] reads once the document's class has loaded.
3833pub const CLASS_HAS_CHAPTERS: &str = "\\chapter:class@has@chapters";
3834
3835/// The "has chapters" test made now (OXIDIZED_DESIGN #179), which `settle_chapter_after_class_load` stores after each
3836/// class load: the class has chapters when
3837/// - (a) its own code assigned `\chapter`: a meaning other than the kernel's (a raw class's `\providecommand\chapter`, a
3838///   binding's own `\chapter`: ws-rv9x6, nic-series, jmlr, kluwer's `chapter` option; a `\let\chapter\artchapter`), a
3839///   redefinition the kernel's lock refused (`\chapter:redefined`, state.rs `install_definition`, sect08.rs), or a
3840///   stand-in copy's definition its binding's owned name kept aside or declined (pasj00.cls's `\def\chapter`;
3841///   ws-rv9x6.cls:499 `\newcommand\chapter`, 2301.03442). A meaning that is undefined, `\relax`
3842///   (`\let\chapter\@undefined`; `\csname chapter\endcsname`) or the undefined-error stub of a call is no definition;
3843/// - (b) a compiled binding made the chapter counter (`\c@chapter` of LaTeXML's own origin: report, book, memoir…;
3844///   Perl's own probe, latex_constructs.pool.ltxml:690). A raw or copy `\newcounter{chapter}` alone is not;
3845/// - (c) the class is unknown and OmniBus guesses it (`OmniBus:fallback`: the class loader's fallback, and subfiles,
3846///   whose subfiles.cls:38-40 loads the main file's class), as an unknown class may well have chapters: OmniBus
3847///   autoloads book.cls on `\thechapter` (arXiv:2602.10407).
3848pub fn class_has_chapters_now() -> bool {
3849  let (assigned, kernel_kept) = class_chapter_sources();
3850  assigned || kernel_kept
3851}
3852
3853/// The two halves of [`class_has_chapters_now`]: whether the class's own code assigned `\chapter` (a), and whether the
3854/// class keeps LaTeXML's kernel `\chapter` as a binding's chapters (b) or OmniBus's guess (c).
3855pub fn class_chapter_sources() -> (bool, bool) {
3856  use crate::definition::origin::DefinitionOrigin;
3857  let chapter = T_CS!("\\chapter");
3858  let relax = lookup_meaning(&T_CS!("\\relax"));
3859  let meaningful =
3860    |meaning: &Stored| !matches!(meaning, Stored::None) && relax.as_ref() != Some(meaning);
3861  let key = meaning_key(&chapter);
3862  let by_copy = state!()
3863    .copy_provides_copies
3864    .iter()
3865    .any(|copy| copy.declined.contains(&key) || copy.overlay.get(&key).is_some_and(meaningful));
3866  let meaning = lookup_meaning(&chapter);
3867  let defined = meaning.as_ref().is_some_and(meaningful) && !lookup_bool("\\chapter:error@stub");
3868  // the kernel's own meaning (the pool's, or `\lx@kernel@chapter` / `\lx@kernel@chapter@counted` put back): a class's
3869  // same-bodied `\newcommand\chapter{\@startsection{chapter}…}` is the class's
3870  let kernels = defined
3871    && (x_equals(&chapter, &T_CS!("\\lx@kernel@chapter"))
3872      || x_equals(&chapter, &T_CS!("\\lx@kernel@chapter@counted")))
3873    && meaning
3874      .as_ref()
3875      .and_then(definition_origin)
3876      .is_some_and(|origin| matches!(origin, DefinitionOrigin::Pool | DefinitionOrigin::Unknown));
3877  let assigned = by_copy || lookup_bool("\\chapter:redefined") || (defined && !kernels);
3878  let binding_counter = matches!(
3879    lookup_meaning(&T_CS!("\\c@chapter")),
3880    Some(Stored::Register(ref register)) if register.origin.is_latexml_owned()
3881  );
3882  (assigned, binding_counter || lookup_bool("OmniBus:fallback"))
3883}
3884
3885/// The meaning the latest stand-in copy of `file` (a file name, `NJDnatbib.sty`) gave `token` in its own code: its
3886/// overlaid version of a name its binding owns, if the copy redefined it ([`note_copy_provides_assignment`]). For a
3887/// binding's code that runs after its copy (`\AtEndOfPackage`), to tell the copy's version by what it defined.
3888pub fn stand_in_copy_meaning(file: &str, token: &Token) -> Option<Stored> {
3889  let key = meaning_key(token);
3890  state!()
3891    .copy_provides_copies
3892    .iter()
3893    .rev()
3894    .find(|copy| copy.file.rsplit(['/', '\\']).next() == Some(file))
3895    .and_then(|copy| copy.overlay.get(&key).cloned())
3896}
3897
3898/// The meaning the latest stand-in copy that redefined `token` for its own code only gave it (its overlay, the copy's
3899/// `declined` name: "keeps LaTeXML's definition", [`note_copy_provides_assignment`]), while the meaning in force is still
3900/// the binding's the copy's frame gave back ([`CopyProvidesRecord::restored`]; a later file's redefinition is no stale
3901/// copy's to read, review revPB S4): what the paper's copy runs where the binding's version runs here. For the frontmatter's reading of a class's title code (latexml_engine `title_code_author_definitions`:
3902/// neurips_2022.sty's `\@maketitle`, which defines `\NewAnd`, where the neurips binding keeps its own; 2205.14141,
3903/// 2205.14539).
3904pub fn copy_kept_meaning(token: &Token) -> Option<Stored> {
3905  let key = meaning_key(token);
3906  if !owned_by_the_semantic_layer(token) {
3907    return None;
3908  }
3909  let current = meaning_by_key(key);
3910  state!()
3911    .copy_provides_copies
3912    .iter()
3913    .rev()
3914    .find(|copy| copy.declined.contains(&key))
3915    .filter(|copy| {
3916      copy
3917        .restored
3918        .get(&key)
3919        .is_some_and(|kept| same_meaning(kept, &current))
3920    })
3921    .and_then(|copy| copy.overlay.get(&key).cloned())
3922}
3923
3924/// Is `token`'s current meaning owned by LaTeXML's semantic layer, for [`note_copy_provides_assignment`]? Either the
3925/// name was assigned while a stand-in binding loaded ([`crate::definition::origin::StandInLoadGuard`]: its own definitions,
3926/// `\let`s and `RawTeX`, and the bindings it required), at an origin of LaTeXML's own, or its meaning is a definition
3927/// made under this very name (not a `\let` copy of another's, whose object carries the other name) at such an origin —
3928/// `Unknown`, `Pool` or `Binding` (definition/origin.rs): a pool's (`\section`, `\maketitle`) or another binding's
3929/// (natbib's `\citep`, xkeyval's `\usevalue`); a name the stand-in binding's load assigned is owned at `Fallback` too,
3930/// the OmniBus base a class binding loads (`\received`, `\corres`). The format's own definitions (`Plain`,
3931/// `LatexDump`, `Format`), the document's world (`File`, `Document`) and the other guesses that yield (`Fallback`,
3932/// `Stub`, `Borrowed`) are not owned, except a borrowed meaning its binding claimed ([`claim_borrowed_meanings`]: the
3933/// ijcai binding's `\citeauthor` over the paper's ijcai21.sty, 2105.02711). The test is that the name no longer stands
3934/// as a fallback, so a binding's `\let` copy of a borrowed definition counts as claimed too.
3935/// A name a package the binding loaded defined stays owned: the narrower rule (only the binding's own code, so that a
3936/// copy's redefinition of a package's macro stands as in TeX) gave the copy the class bindings' frontmatter and layout
3937/// macros (`\title`, `\author`, `\thanks`, `\@makecaption`, `\the<counter>`, the NFSS size commands; aastex7's three
3938/// Fatals again, 2504.00922, 2605.15371, 2607.03848); the case it was for, 2411.02780's equations.sty, is another file
3939/// of that name (`binding::content` `copy_is_the_stood_in_file`).
3940fn owned_by_the_semantic_layer(token: &Token) -> bool {
3941  use crate::definition::origin::DefinitionOrigin;
3942  let claimed = !is_fallback_meaning(token);
3943  let ours = |origin: DefinitionOrigin| {
3944    matches!(
3945      origin,
3946      DefinitionOrigin::Unknown | DefinitionOrigin::Pool | DefinitionOrigin::Binding
3947    ) || (claimed && origin == DefinitionOrigin::Borrowed)
3948  };
3949  lookup_meaning(token).is_some_and(|meaning| {
3950    definition_origin(&meaning).is_some_and(|origin| {
3951      let key = meaning_key(token);
3952      if state!().binding_lets.contains(&key) && ours(origin) {
3953        // (a `\let` LaTeXML's own code made: the object carries the source's name, `State::binding_lets`)
3954        true
3955      } else if state!().stand_in_meanings.contains(&key) {
3956        // (the stand-in binding's guesses too: the OmniBus base a class binding loads, `Fallback` so that the
3957        // document's own definition wins, OXIDIZED_DESIGN_DIVERGENCES #408 — the copy is not the document: WileyNJDv5's
3958        // `\received` keeps OmniBus's dated frontmatter, 2609.19994)
3959        ours(origin) || origin == DefinitionOrigin::Fallback
3960      } else {
3961        // (or a `\let` the pool made to one of the semantic layer's own internals, `\let\label\lx@label`
3962        // (sect11.rs): no file defines an `\lx@` name, so the object is LaTeXML's construct — a copy's `\def\label`
3963        // writing the `.aux` (aastex7.cls:635, aastex701.cls, siamltex.cls, emulateapj.cls) left every label of the
3964        // document unrecorded: 2508.00291, 2510.05388, 2604.27071)
3965        ours(origin)
3966          && definition_cs(&meaning)
3967            .is_some_and(|cs| cs == *token || cs.with_cs_name(|name| name.starts_with("\\lx@")))
3968      }
3969    })
3970  })
3971}
3972
3973/// The name a definition was made under (a `\let` copy keeps its source's).
3974fn definition_cs(meaning: &Stored) -> Option<Token> {
3975  match meaning {
3976    Stored::Expandable(defn) => Some(defn.cs),
3977    Stored::Constructor(defn) => Some(defn.cs),
3978    Stored::Primitive(defn) => Some(defn.cs),
3979    Stored::MathPrimitive(defn) => Some(defn.cs),
3980    Stored::Conditional(defn) => Some(defn.cs),
3981    Stored::Register(defn) => Some(defn.cs),
3982    _ => None,
3983  }
3984}
3985
3986/// Who made the definition `meaning` (`None`: not a definition — a `\let` to a character, an undefined name).
3987fn definition_origin(meaning: &Stored) -> Option<crate::definition::origin::DefinitionOrigin> {
3988  match meaning {
3989    Stored::Expandable(defn) => Some(defn.origin),
3990    Stored::Constructor(defn) => Some(defn.origin),
3991    Stored::Primitive(defn) => Some(defn.origin),
3992    Stored::MathPrimitive(defn) => Some(defn.origin),
3993    Stored::Conditional(defn) => Some(defn.origin),
3994    Stored::Register(defn) => Some(defn.origin),
3995    _ => None,
3996  }
3997}
3998
3999/// The code a stand-in's copy registers with `\AtEndOfClass`/`\AtEndOfPackage`, which runs at the end of its own
4000/// load: wrapped in the copy's scope markers `\lx@copy@provides@begin{N}` … `\lx@copy@provides@end`, so it runs under
4001/// the copy's provides-mode, with the copy's own definitions in force ([`enter_copy_provides_frame`]; aa.cls:71's
4002/// `\AtEndOfClass` redefinition of `{abstract}` keeps the binding's). `tokens` unchanged when no copy is read or it is
4003/// wrapped already.
4004pub fn copy_provides_wrap(tokens: Tokens) -> Tokens {
4005  let id = crate::definition::origin::copy_provides();
4006  let begin = T_CS!("\\lx@copy@provides@begin");
4007  if id == 0 || tokens.unlist_ref().first() == Some(&begin) {
4008    return tokens;
4009  }
4010  let mut wrapped = vec![begin, T_BEGIN!()];
4011  wrapped.extend(mouth::tokenize_internal(TeXString::assembled(id.to_string())).unlist());
4012  wrapped.push(T_END!());
4013  wrapped.extend(tokens.unlist());
4014  wrapped.push(T_CS!("\\lx@copy@provides@end"));
4015  Tokens::new(wrapped)
4016}
4017
4018/// Does a stand-in's copy, read now, defer code to the document through `seam` (`\AtBeginDocument`,
4019/// `\AtEndDocument`, etoolbox's `\AtEndPreamble`/`\AfterEndPreamble`/`\AfterEndDocument`, lthooks' `\AddToHook`)? Then
4020/// the code is not registered: it is the class's or style's document-time machinery, which the binding has taken over
4021/// — layout checks against the class's page dimensions (icml2024.sty's "The page layout violates the ICML style",
4022/// 2407.02750), validations of the class's own setters the document called as the binding's (PoS.cls "\abstract{...}
4023/// should appear before \begin{document}", 1001.3214; ieeeaccess.cls's `\EOD`, 2007.03025; aipproc.cls's
4024/// `\layoutstyle`, astro-ph0105128), patches of the kernel's `\enddocument` (aastex7.cls:459, whose
4025/// `\rvtx@enddocument@patch` reads up to `\@checkend` and ran off the file: 2504.00922, 2605.15371, 2607.03848). On the
4026/// 2026-10-17 census sample no Error was fixed by such code. Logged once per copy and seam, at Info.
4027pub fn copy_provides_defers(seam: &str) -> bool {
4028  let id = crate::definition::origin::copy_provides();
4029  if id == 0 {
4030    return false;
4031  }
4032  let key = arena::pin(seam);
4033  let mut state = state_mut!();
4034  if let Some(copy) = state.copy_provides_copies.get_mut(id as usize - 1)
4035    && copy.deferred.insert(key)
4036  {
4037    let file = copy.file.clone();
4038    drop(state);
4039    Info!(
4040      "provide",
4041      seam,
4042      s!(
4043        "The paper's {file} defers code to the document ({seam}); not registered: its binding stands in for that code"
4044      )
4045    );
4046  }
4047  true
4048}
4049
4050/// Is `token` one of LaTeX's document hooks (`\@begindocumenthook`, `\@enddocumenthook`), which a stand-in's copy read
4051/// now writes — `\g@addto@macro`, ltxgrid's `\prepdef`, a `\def` —, so that the write is document-time code, which the
4052/// copy does not register, as it does not its `\AtBeginDocument` code ([`copy_provides_defers`], Info)? ltxgrid's
4053/// `\prepdef\@begindocumenthook{\open@column@one\@ne\set@colht…}` (qm2008_abs.cls:3233, snp.cls; REVTeX 4 copies
4054/// routed to the revtex4 binding) ran its page grid over the binding's names at `\begin{document}`: 7 "Missing number"
4055/// Warnings in 0805.2253, 0806.0481, 0805.4759.
4056pub fn copy_provides_defers_hook_write(token: &Token) -> bool {
4057  crate::definition::origin::copy_provides() != 0
4058    && token.with_cs_name(|cs| matches!(cs, "\\@begindocumenthook" | "\\@enddocumenthook"))
4059    && token.with_cs_name(copy_provides_defers)
4060}
4061
4062/// Put lthooks' code registration (`\AddToHook code`, the inner macro latex.ltx's `\AddToHook` hands the hook name,
4063/// label and code: `\hook_gput_code:nnn{#1}{#2}{#3}`) under `\lx@copy@provides@AddToHook`, which registers nothing
4064/// ([`copy_provides_defers`]), while `on` — a stand-in's copy is read — and back after. The kernel's
4065/// own meaning is kept as `\lx@copy@provides@saved@AddToHook`. No-op where the format has no hooks or no seam is
4066/// defined.
4067pub fn swap_copy_provides_hook_seam(on: bool) {
4068  let seam = T_CS!("\\AddToHook code");
4069  let saved = T_CS!("\\lx@copy@provides@saved@AddToHook");
4070  let wrapper = T_CS!("\\lx@copy@provides@AddToHook");
4071  let set = |token: &Token, meaning: Stored| {
4072    let key = token.pin_cs_name();
4073    state_mut!().assign_internal(TableName::Meaning, key, meaning, Some(Scope::Global));
4074  };
4075  if on {
4076    if let (Some(kernel), Some(wrap)) = (lookup_meaning(&seam), lookup_meaning(&wrapper)) {
4077      set(&saved, kernel);
4078      set(&seam, wrap);
4079    }
4080  } else if let Some(kernel) = lookup_meaning(&saved) {
4081    set(&seam, kernel);
4082    set(&saved, Stored::None);
4083  }
4084}
4085
4086/// Begin a stand-in binding's load ([`crate::definition::origin::StandInLoadGuard`]): no name of its own assigned yet
4087/// ([`State::stand_in_loads`]); a stand-in it loads records its own apart.
4088pub fn begin_stand_in_load() {
4089  let mut state = state_mut!();
4090  state.stand_in_loads.push(Vec::new());
4091  state.stand_in_load_files.push(Vec::new());
4092}
4093
4094/// A stand-in binding's own code loads `file`, or makes `file`'s binding's definitions as code without loading it
4095/// (svjour3_cls.rs over svjour's, jhep_cls.rs `jhep_definitions`): a file it is built on
4096/// ([`State::stand_in_load_files`]), not marked loaded.
4097pub fn note_stand_in_file(file: &str) {
4098  if let Some(files) = state_mut!().stand_in_load_files.last_mut() {
4099    files.push(file.to_string());
4100  }
4101}
4102
4103/// The files the stand-in binding loaded last loaded from its own code ([`State::stand_in_last_files`]).
4104pub fn stand_in_built_on() -> Vec<String> { state!().stand_in_last_files.clone() }
4105
4106/// End the stand-in binding's load [`begin_stand_in_load`] began: its names are the last load's
4107/// ([`State::stand_in_last_load`]), and, when the stand-in binding loading it requested it in its own code
4108/// (`into_outer`, `StandInLoadGuard::loaded_by`), that binding's too.
4109pub fn end_stand_in_load(into_outer: bool) {
4110  let mut state = state_mut!();
4111  let files = state.stand_in_load_files.pop().unwrap_or_default();
4112  if let Some(load) = state.stand_in_loads.pop() {
4113    // (a stand-in its own code loads is part of its command set: the diagrams binding's `diagrams.tex`, whose names
4114    // are Paul Taylor's package's, hep-ph9609379; not one a file it loads requests — OmniBus's aas_macros under
4115    // asme2ej, 2309.12017, or nature-pre, 2102.01782, 2111.09589, swelled their sets from 22 and 3 names to 87 and 68)
4116    if into_outer && let Some(outer) = state.stand_in_loads.last_mut() {
4117      outer.extend(load.iter().copied());
4118    }
4119    state.stand_in_last_load = load;
4120    state.stand_in_last_files = files;
4121  }
4122}
4123
4124/// Every name the latest stand-in binding's own code assigned ([`State::stand_in_last_load`]).
4125pub fn stand_in_last_load_names() -> rustc_hash::FxHashSet<SymStr> {
4126  state!().stand_in_last_load.iter().copied().collect()
4127}
4128
4129/// The public names (letters only: no `@`) the latest stand-in binding's own code assigned ([`State::stand_in_last_load`]).
4130pub fn stand_in_public_names() -> rustc_hash::FxHashSet<String> {
4131  state!()
4132    .stand_in_last_load
4133    .iter()
4134    .map(|key| arena::to_string(*key))
4135    .filter(|name| {
4136      name.strip_prefix('\\').is_some_and(|letters| {
4137        !letters.is_empty() && letters.chars().all(|c| c.is_ascii_alphabetic())
4138      })
4139    })
4140    .collect()
4141}
4142
4143/// Begin a provide-only load: no name assigned in it yet.
4144pub fn reset_provide_only_assigned() {
4145  let mut state = state_mut!();
4146  state.provide_only_assigned.clear();
4147  state.provide_only_loaded.clear();
4148}
4149
4150/// End a provide-only load: the files first loaded during it (but the fallback class itself) loaded only what they
4151/// could provide, so they are marked unloaded again — `<file>_loaded`, its `.ltxml_loaded` twin, `_load_attempted` and
4152/// the kernel's `\ver@<file>` — and a later `\usepackage`/`\RequirePackage` of one loads it whole
4153/// (`\documentstyle[graphics,myjunkx]{article}\usepackage{graphicx}`: graphicx's keyval `\includegraphics`).
4154pub fn end_provide_only() {
4155  let files = std::mem::take(&mut state_mut!().provide_only_loaded);
4156  for file in files {
4157    if file == "OmniBus.cls" {
4158      continue;
4159    }
4160    mark_unloaded(&file);
4161  }
4162}
4163
4164/// Mark `file` (`amsthm.sty`) as not loaded, globally: its `<file>_loaded`, the `.ltxml_loaded` twin, the raw load's
4165/// `_raw_loaded` and `_load_attempted` are cleared and the kernel's `\ver@<file>` and `\opt@<file>` are undefined, so
4166/// `\@ifpackageloaded` is false, no option clash is checked, and a later `\usepackage`/`\RequirePackage` loads it
4167/// again — the binding and the raw file it reads. The definitions it made stay in force. Used when a load provided
4168/// only part of a file ([`end_provide_only`]) and for a binding's borrowed package and the files it loaded
4169/// (`binding::content::require_package_borrowed`).
4170pub fn mark_unloaded(file: &str) {
4171  for flag in ["_loaded", ".ltxml_loaded", "_raw_loaded", "_load_attempted"] {
4172    if lookup_bool(&s!("{file}{flag}")) {
4173      assign_value(&s!("{file}{flag}"), false, Some(Scope::Global));
4174    }
4175  }
4176  for kernel in ["ver", "opt"] {
4177    assign_meaning(
4178      &T_CS!(s!("\\{kernel}@{file}")),
4179      Stored::None,
4180      Some(Scope::Global),
4181    );
4182  }
4183}
4184
4185/// Begin a borrow (`binding::content::require_package_borrowed`): no file loaded by it yet. Returns the list of an
4186/// enclosing borrow, which [`end_borrow`] puts back.
4187pub fn begin_borrow() -> Vec<String> { std::mem::take(&mut state_mut!().borrowed_loaded) }
4188
4189/// End a borrow: the files first marked loaded during it (`borrowed_loaded`) are marked unloaded ([`mark_unloaded`]),
4190/// and the enclosing borrow's list is put back.
4191pub fn end_borrow(outer: Vec<String>) {
4192  let files = std::mem::replace(&mut state_mut!().borrowed_loaded, outer);
4193  for file in files {
4194    mark_unloaded(&file);
4195  }
4196}
4197
4198/// Has the document unloaded `file` (`amsthm.sty`), which a class binding marked loaded on its class's behalf, by
4199/// letting its `\ver@<file>` to `\relax` or `\undefined`? LaTeX's loaded test is that macro (latex.ltx `\@ifl@aded`:
4200/// `\expandafter\ifx\csname ver@#2.#1\endcsname\relax`, true for both), which a binding load defines (content.rs, Perl
4201/// Package.pm:2326). The rule is narrow, as floatrow's marks are (user ruling 2026-10-14: no general loader `\ver@`
4202/// rule; floatrow_sty.rs): only a file a binding recorded as `<file>:class_marked` — ams_support_sty.rs for amsart's
4203/// `\@namedef{ver@amsthm.sty}` (amsart.cls:41-42; amsproc, amsbook alike) — is so taken back; every other file keeps
4204/// the loader's own record. The amsart idiom is `\expandafter\let\csname ver@amsthm.sty\endcsname\relax` before
4205/// `\usepackage{amsthm}` (1510.08833, 1704.05671, 1707.00258, 1611.00843, 2106.07418, 2304.10644). Perl's loader reads
4206/// only `<file>_loaded` (Package.pm:2327-2329), KNOWN_PERL_ERRORS #720.
4207pub fn unmarked_by_document(file: &str) -> bool {
4208  if !lookup_bool(&s!("{file}:class_marked")) || !lookup_bool(&s!("{file}_loaded")) {
4209    return false;
4210  }
4211  match lookup_meaning(&T_CS!(s!("\\ver@{file}"))) {
4212    None => true,
4213    Some(ver) => lookup_meaning(&T_CS!("\\relax")).is_some_and(|relax| ver == relax),
4214  }
4215}
4216
4217/// Is `file` (`amsmath.sty`, `memoir.cls`) loaded, as LaTeX asks it (`\@ifpackageloaded`, `\@ifclassloaded`: latex.ltx
4218/// `\@ifl@aded`, `\ver@<file>` defined and not `\relax`)? One answer on every load path: a binding's load and a raw
4219/// file's define the macro (Package.pm:2343, :2393), and so do a class's or a document's own marks (floatrow.sty:34,
4220/// `\@namedef{ver@…}`) and their removals (fontenc.sty's tail, a document's `\let\ver@amsthm.sty\relax`). Perl's
4221/// `\@ifl@aded` reads the loader's records (latex_constructs.pool.ltxml:946-953), which a binding may clear so that the
4222/// next request runs it again ([`load_recorded`]; aa.cls.ltxml:57): OXIDIZED_DESIGN_DIVERGENCES #1015.
4223pub fn file_loaded(file: &str) -> bool {
4224  lookup_meaning(&T_CS!(s!("\\ver@{file}"))).is_some_and(|ver| {
4225    !matches!(ver, Stored::None)
4226      && Some(&ver) != lookup_meaning(&crate::token::TOKEN_RELAX).as_ref()
4227  })
4228}
4229
4230/// `\@ifpackageloaded{name}` ([`file_loaded`]).
4231pub fn package_loaded(name: &str) -> bool { file_loaded(&s!("{name}.sty")) }
4232
4233/// `\@ifclassloaded{name}` ([`file_loaded`]).
4234pub fn class_loaded(name: &str) -> bool { file_loaded(&s!("{name}.cls")) }
4235
4236/// Has the loader recorded a load of `file`: its binding's or a stand-in's (`<file>_loaded`) or its raw TeX's
4237/// ([`raw_loaded`])? The loader's own question (Package.pm:2328-2330, :2363; `DefAutoload`, :1096), not LaTeX's
4238/// ([`file_loaded`]): it says whether the definitions were read here, and a binding clears it to be read again.
4239pub fn load_recorded(file: &str) -> bool { lookup_bool(&s!("{file}_loaded")) || raw_loaded(file) }
4240
4241/// Did the binding of this very name load `file` (`<file>.ltxml_loaded`, Package.pm:2332), not a stand-in's?
4242pub fn binding_loaded(file: &str) -> bool { lookup_bool(&s!("{file}.ltxml_loaded")) }
4243
4244/// Was `file`'s raw TeX read (`<file>_raw_loaded`, OXIDIZED_DESIGN #23)?
4245pub fn raw_loaded(file: &str) -> bool { lookup_bool(&s!("{file}_raw_loaded")) }
4246
4247/// Record `file` loaded for a binding that stands in for it (thmtools for thm-patch.sty, aipproc for aipxfm.sty), as
4248/// the original's own load does: the loader's record, so a later request is a no-op, and `\ver@<file>` (`\fmtversion`,
4249/// Package.pm:2343) unless the file is marked already.
4250pub fn mark_loaded(file: &str) {
4251  assign_value(&s!("{file}_loaded"), true, Some(Scope::Global));
4252  if !file_loaded(file)
4253    && let Some(fmtversion) = lookup_meaning(&T_CS!("\\fmtversion"))
4254  {
4255    assign_meaning(&T_CS!(s!("\\ver@{file}")), fmtversion, Some(Scope::Global));
4256  }
4257}
4258
4259/// Take back a binding's load of `file` that its original does not make (revtex4_support's hyperref, which revtex4-2.cls
4260/// never loads): its record, so the document's own request runs the binding again, and `\ver@<file>`, so
4261/// `\@ifpackageloaded` is false until then. The definitions stay; the binding's other records too ([`mark_unloaded`]
4262/// clears them all).
4263pub fn unmark_loaded(file: &str) {
4264  assign_value(&s!("{file}_loaded"), Stored::None, Some(Scope::Global));
4265  assign_meaning(
4266    &T_CS!(s!("\\ver@{file}")),
4267    Stored::None,
4268    Some(Scope::Global),
4269  );
4270}
4271
4272/// Run `read` with `file` marked loaded in the current group, its record and `\ver@<file>`, where it is not loaded
4273/// and not recorded (a recorded load the document unmarked keeps its record): cleveref's binding reads cleveref.sty as
4274/// if amsmath were loaded (Perl cleveref.sty.ltxml:23-27).
4275pub fn with_pretended_load<R>(file: &str, read: impl FnOnce() -> R) -> R {
4276  if file_loaded(file) || load_recorded(file) {
4277    return read();
4278  }
4279  let (record, ver) = (s!("{file}_loaded"), T_CS!(s!("\\ver@{file}")));
4280  let was = lookup_meaning(&ver);
4281  assign_value(&record, true, Some(Scope::Local));
4282  if let Some(fmtversion) = lookup_meaning(&T_CS!("\\fmtversion")) {
4283    assign_meaning(&ver, fmtversion, Some(Scope::Local));
4284  }
4285  let result = read();
4286  assign_value(&record, Stored::None, Some(Scope::Local));
4287  assign_meaning(&ver, was.unwrap_or(Stored::None), Some(Scope::Local));
4288  result
4289}
4290
4291/// Run `read`, a read of `file` that must not use it up (colordvi's of dvipsnam.def), and put `file`'s load records
4292/// back as they were.
4293pub fn keeping_load_records<R>(file: &str, read: impl FnOnce() -> R) -> R {
4294  let flags = ["_raw_loaded", "_loaded", "_load_attempted"].map(|flag| s!("{file}{flag}"));
4295  let was = flags.clone().map(|flag| lookup_bool(&flag));
4296  let result = read();
4297  for (flag, was) in flags.iter().zip(was) {
4298    assign_value(flag, was, Some(Scope::Global));
4299  }
4300  result
4301}
4302
4303/// Is `token`'s current meaning a fallback class's guess (`DefinitionOrigin::Fallback`), a kernel stub
4304/// (`DefinitionOrigin::Stub`) or a borrowed package's (`DefinitionOrigin::Borrowed`), which a document's own
4305/// `\newcommand` may replace?
4306pub fn is_fallback_meaning(token: &Token) -> bool {
4307  let state = state!();
4308  !state.fallback_meanings.is_empty() && state.fallback_meanings.contains_key(&meaning_key(token))
4309}
4310
4311/// The origin of `token`'s current meaning when it is a fallback guess, a kernel stub or a borrowed package's
4312/// ([`is_fallback_meaning`]): `Fallback`, `Stub` or `Borrowed`, whatever kind of definition it is (only macros record
4313/// their own origin, `Definition::get_origin`; amsthm's proof is a constructor).
4314pub fn fallback_meaning_origin(
4315  token: &Token,
4316) -> Option<crate::definition::origin::DefinitionOrigin> {
4317  let state = state!();
4318  if state.fallback_meanings.is_empty() {
4319    return None;
4320  }
4321  state.fallback_meanings.get(&meaning_key(token)).copied()
4322}
4323
4324/// A borrowing binding's claim on the borrowed names its real package defines too: their meanings no longer carry the
4325/// borrowed mark (`DefinitionOrigin::Borrowed`, [`fallback_meaning_origin`]), so they are the binding's own, as if it
4326/// had defined them again at its own origin, and a later file's `\newcommand`/`\newenvironment` of them is refused
4327/// as LaTeX refuses it ("Command … already defined"), not honoured. ntheorem.sty's `[amsthm]` option defines
4328/// `\proofname` and `{proof}` (ntheorem.sty:668-711), which its binding takes from the borrowed amsthm; theorem.sty's
4329/// `\newskip\theorempreskipamount` (theorem.sty:122-123) likewise. A name whose meaning is not borrowed is left
4330/// alone.
4331pub fn claim_borrowed_meanings(names: &[&str]) {
4332  use crate::definition::origin::DefinitionOrigin;
4333  if state!().fallback_meanings.is_empty() {
4334    return;
4335  }
4336  let keys: Vec<SymStr> = names
4337    .iter()
4338    .map(|name| meaning_key(&crate::T_CS!(*name)))
4339    .collect();
4340  let mut state = state_mut!();
4341  for key in keys {
4342    if state.fallback_meanings.get(&key) == Some(&DefinitionOrigin::Borrowed) {
4343      state.fallback_meanings.remove(&key);
4344    }
4345  }
4346}
4347
4348// SAFETY
4349// any method which does not return a borrowed piece of data should be package-level
4350// so that the global singleton State can get locked+unlocked during the same call
4351// thus entirely AVOIDING possible runtime panics due to RefCell lock races.
4352// TODO: Should this be a prelude?
4353
4354/// assigns a `Stored` value at the given key and scope
4355/// Direct mirror of Perl's free-function form
4356/// `LaTeXML::Core::State::assign_internal($STATE, $table, $key, $value, $scope)`
4357/// (Core/State.pm L140). Bypasses every dialect / lock / let-chase / admission
4358/// layer Rust has accreted on top of the table mutation; used by the dump
4359/// loader (Core/Dumper.pm `V/Cc/Mc/Sc/Lc/Uc/Dc/Im/I/Lt`) so the dump replay
4360/// matches Perl exactly: one record == one `assign_internal` call.
4361pub fn assign_internal<T: Into<Stored>>(
4362  table_name: TableName,
4363  key: SymStr,
4364  value: T,
4365  scope: Option<Scope>,
4366) {
4367  state_mut!().assign_internal(table_name, key, value.into(), scope);
4368}
4369
4370/// Bind `key` to `value` in the value table — Perl's `AssignValue`.
4371///
4372/// [`Scope`] decides how long the binding lasts: [`Scope::Local`] expires with
4373/// the enclosing TeX group, [`Scope::Global`] does not, [`Scope::Named`] applies
4374/// only while that scope is activated, and [`Scope::InPlace`] rebinds at the
4375/// frame the value was last bound in. Passing `None` takes the state's current
4376/// default. Read back with [`lookup_value`], or one of the typed
4377/// [`lookup_string`] / [`lookup_number`] / [`lookup_bool`] accessors.
4378pub fn assign_value<T: Into<Stored>, S: Into<Option<Scope>>>(key: &str, value: T, scope: S) {
4379  state_mut!().assign_value(key, value, scope)
4380}
4381
4382/// Assigns `value` to `key` globally and past the open assignment journal's rollback (Rust-only), as TeX never takes back
4383/// what it wrote to a file: no speculative run's undoing (a frontmatter rehearsal, a label's ink run) takes it back. Only
4384/// for a record TeX writes to a file and reads back on a later run — an aux-file label, imsart.sty's `\ead` `\safelabel`
4385/// that its `\printead` reads —, never for a value a rehearsal's own reading decides: that one must roll back with it.
4386/// OXIDIZED_DESIGN_DIVERGENCES #986.
4387pub fn assign_value_past_rollback(key: &str, value: impl Into<Stored>) {
4388  let mut state = state_mut!();
4389  state.assign_value(key, value, Some(Scope::Global));
4390  let key = arena::pin(key);
4391  if let Some(journal) = state.journal.as_mut() {
4392    journal.saved.remove(&(TableName::Value, key));
4393  }
4394}
4395
4396/// assigns a `Stored` value 'inplace': replaces the front value in whatever frame
4397/// it was originally assigned in, without recording an undo entry.
4398/// This matches Perl's `assignValue(key, value, 'inplace')`.
4399/// Used for MODE changes in enter_horizontal (switches mode without creating a new binding).
4400pub fn assign_value_inplace(key: &str, value: impl Into<Stored>) {
4401  assign_value_inplace_sym(arena::pin(key), value)
4402}
4403/// Sym-keyed variant of `assign_value_inplace` — skip the per-call
4404/// `arena::pin(key)` for hot callers with a pre-pinned SymStr.
4405pub fn assign_value_inplace_sym(key_sym: SymStr, value: impl Into<Stored>) {
4406  let value = value.into();
4407  let state = &mut *state_mut!();
4408  state.journal_touch(TableName::Value, key_sym);
4409  let table = &mut state.value;
4410  if let Some(vvec) = table.get_mut(&key_sym)
4411    && let Some(front) = vvec.front_mut()
4412  {
4413    *front = value;
4414    return;
4415  }
4416  // If the value was never assigned, push globally (matching Perl behavior)
4417  let vvec = table.entry(key_sym).or_default();
4418  vvec.push_front(value);
4419  // Find the locked frame and record the undo there
4420  for frame in &mut state.undo {
4421    if frame.locked {
4422      frame.table_mut(TableName::Value).insert(key_sym, 1);
4423      break;
4424    }
4425  }
4426}
4427
4428/// A save-frame bookkeeping binding (`groupInitiator`, `BOUND_MODE`, the
4429/// frame id, an environment's group code…): always local to the current
4430/// frame, exempt from `\globaldefs` and the `\global` prefix — tex.web §1214
4431/// vs §274. See `State::assign_local_unconditional`.
4432pub fn assign_frame_value_sym<T: Into<Stored>>(key: SymStr, value: T) {
4433  state_mut!().assign_local_unconditional(TableName::Value, key, value.into());
4434}
4435
4436/// [`assign_frame_value_sym`] with a string key.
4437pub fn assign_frame_value<T: Into<Stored>>(key: &str, value: T) {
4438  assign_frame_value_sym(arena::pin(key), value);
4439}
4440
4441/// assigns a `Stored` value at the given (arena ticket!) key and scope
4442pub fn assign_value_sym<T: Into<Stored>, S: Into<Option<Scope>>>(key: SymStr, value: T, scope: S) {
4443  let value = value.into();
4444  let scope = scope.into();
4445  state_mut!().assign_internal(TableName::Value, key, value, scope);
4446}
4447
4448/// inline lookup_value after which globally assign an empty Tokens() to undo
4449pub fn remove_value(key: &str) -> Option<Stored> { remove_value_sym(arena::pin(key)) }
4450
4451/// `remove_value` variant for hot call sites with a pre-pinned SymStr (see
4452/// `crate::pin!`) — added for `after_assignment`, which fires on every
4453/// `\def`/`\let`/register assignment.
4454pub fn remove_value_sym(key_sym: SymStr) -> Option<Stored> {
4455  let mut state = state_mut!();
4456  state.journal_touch(TableName::Value, key_sym);
4457  match state.value.get_mut(&key_sym) {
4458    None => None,
4459    Some(vvec) => match vvec.front_mut() {
4460      None | Some(&mut Stored::None) => None,
4461      Some(found) => Some(std::mem::take(found)),
4462    },
4463  }
4464}
4465/// Replaces the value in question with `Stored::None` (see `checkin_value` for returning it)
4466pub fn checkout_value(key: &str) -> Option<Stored> {
4467  let key = arena::pin(key);
4468  let mut state = state_mut!();
4469  state.journal_touch(TableName::Value, key);
4470  match state.value.get_mut(&key) {
4471    None => None,
4472    Some(vvec) => vvec.front_mut().map(std::mem::take),
4473  }
4474}
4475/// Returns a value into its `Stored::None` placeholder (see `checkout_value` for taking it)
4476pub fn checkin_value(key: &str, value: Stored) {
4477  let key_sym = arena::pin(key);
4478  let mut state = state_mut!();
4479  state.journal_touch(TableName::Value, key_sym);
4480  match state.value.get_mut(&key_sym) {
4481    None => {
4482      // Key was never assigned — silently ignore the checkin
4483      emit_warn(
4484        "internal",
4485        "state",
4486        &format!("checkin_value called for unknown key '{key}'"),
4487      );
4488    },
4489    Some(vvec) => match vvec.front_mut() {
4490      None => {
4491        emit_warn(
4492          "internal",
4493          "state",
4494          &format!("checkin_value called with empty value stack for key '{key}'"),
4495        );
4496      },
4497      Some(found) => {
4498        match found {
4499          Stored::None => std::mem::replace(found, value),
4500          _ => panic!("checkin_value should only be called after checkout_value"),
4501        };
4502      },
4503    },
4504  }
4505}
4506/// manage a (global) list of values
4507pub fn push_value<T: Into<Stored>>(key: &str, value: T) -> Result<()> {
4508  let key_sym = arena::pin(key);
4509  let value = value.into();
4510  // Capture any BUG-path message, but raise the Error! *after* the state_mut!()
4511  // borrow is dropped — Error! reads MAX_ERRORS, and a live mutable borrow there
4512  // panics "RefCell already mutably borrowed" (tikz-cd 2001.08973).
4513  let bug: Option<String> = {
4514    let mut state = state_mut!();
4515    state.journal_touch(TableName::Value, key_sym);
4516    if !state.value.contains_key(&key_sym) {
4517      state.assign_internal(
4518        TableName::Value,
4519        key_sym,
4520        Stored::VecDequeStored(VecDeque::new()),
4521        Some(Scope::Global),
4522      );
4523    }
4524    match state.value.get_mut(&key_sym).unwrap().front_mut() {
4525      Some(&mut Stored::VecDequeStored(ref mut front)) => {
4526        front.push_back(value);
4527        None
4528      },
4529      // auto-vivify, if None
4530      Some(ref mut field) if matches!(field, Stored::None) => {
4531        let mut new_vdq = VecDeque::new();
4532        new_vdq.push_back(value);
4533        **field = Stored::VecDequeStored(new_vdq);
4534        None
4535      },
4536      // Convert Strings (immutable array) to VecDequeStored for push — matches Perl auto-vivification
4537      Some(ref mut field) if matches!(field, Stored::Strings(_)) => {
4538        let existing: VecDeque<Stored> = if let Stored::Strings(strings) = &**field {
4539          strings.iter().map(|s| Stored::String(*s)).collect()
4540        } else {
4541          VecDeque::new()
4542        };
4543        let mut new_vdq = existing;
4544        new_vdq.push_back(value);
4545        **field = Stored::VecDequeStored(new_vdq);
4546        None
4547      },
4548      other => Some(s!(
4549        "BUG: Tried to push_value into an unsupported Stored field! Field was: {other:?}"
4550      )),
4551    }
4552  };
4553  if let Some(message) = bug {
4554    // Lowercase category for consistency with engine convention.
4555    Error!("state", "Stored", message);
4556  }
4557  Ok(())
4558}
4559/// pops the last value in a named `Stored::VecDequeStored` queue, if any
4560pub fn pop_value(key: &str) -> Result<Option<Stored>> {
4561  let key_sym = arena::pin(key);
4562  // Compute the pop result under the borrow, then raise the BUG Error! *after*
4563  // dropping it — Error! reads MAX_ERRORS, which panics under a live mutable
4564  // borrow (mirrors push_value; tikz-cd 2001.08973).
4565  let popped: std::result::Result<Option<Stored>, ()> = {
4566    let mut state = state_mut!();
4567    state.journal_touch(TableName::Value, key_sym);
4568    if !state.value.contains_key(&key_sym) {
4569      state.assign_internal(
4570        TableName::Value,
4571        key_sym,
4572        Stored::VecDequeStored(VecDeque::new()),
4573        Some(Scope::Global),
4574      );
4575    }
4576    if let Some(&mut Stored::VecDequeStored(ref mut front)) =
4577      state.value.get_mut(&key_sym).unwrap().front_mut()
4578    {
4579      Ok(front.pop_back())
4580    } else {
4581      Err(())
4582    }
4583  };
4584  match popped {
4585    Ok(v) => Ok(v),
4586    Err(()) => {
4587      Error!(
4588        "State",
4589        "Stored",
4590        "BUG: Tried to pop_value from a non-vecdeque value key!"
4591      );
4592      Ok(None)
4593    },
4594  }
4595}
4596/// Check if the Value table contains a given key
4597pub fn has_value(key: &str) -> bool { has_value_sym(arena::pin(key)) }
4598/// Sym-keyed variant of `has_value` — avoids the per-call `arena::pin(key)`.
4599pub fn has_value_sym(key_sym: SymStr) -> bool {
4600  match state!().value.get(&key_sym) {
4601    None => false,
4602    Some(list) => match list.front() {
4603      None => false,
4604      Some(v) => !matches!(v, &Stored::None),
4605    },
4606  }
4607}
4608/// Pushes Tokens into a `Stored::Tokens` value when defined,
4609/// or assigns when new.
4610pub fn push_tokens(key: &str, value: Tokens) {
4611  let mut state = state_mut!();
4612  match state.lookup_value_mut(key) {
4613    Some(Stored::Tokens(tks)) => tks.unlist_mut().extend(value.unlist()),
4614    // Perl `pushValue` (State.pm:218-223) creates a missing list globally: a `\vadjust` inside a group
4615    // (`Alpha {\vadjust{Bravo}} Charlie.`) kept its material past the group's end, where a local list was lost
4616    // (guard `box_primitives::vadjust`).
4617    None | Some(Stored::None) => {
4618      state.assign_value(key, Stored::Tokens(value), Some(Scope::Global))
4619    },
4620    Some(other) => panic!("Can only push_tokens into a Stored::Tokens, but got {other:?}"),
4621  }
4622}
4623
4624/// Appends a digested box to the `Stored::VecDigested` list under `key`, creating the list globally when missing (as
4625/// [`push_tokens`], Perl `pushValue`, State.pm:218-223).
4626pub fn push_digested(key: &str, value: Digested) {
4627  let mut state = state_mut!();
4628  match state.lookup_value_mut(key) {
4629    Some(Stored::VecDigested(list)) => list.push(value),
4630    None | Some(Stored::None) => {
4631      state.assign_value(key, Stored::VecDigested(vec![value]), Some(Scope::Global))
4632    },
4633    Some(other) => panic!("Can only push_digested into a Stored::VecDigested, but got {other:?}"),
4634  }
4635}
4636
4637/// Take the list [`push_tokens`] or [`push_digested`] has built under `key`, leaving it empty in place; `None` when
4638/// there is none.
4639pub fn take_pushed(key: &str) -> Option<Stored> {
4640  match state_mut!().lookup_value_mut(key) {
4641    Some(Stored::Tokens(tks)) => Some(Stored::Tokens(std::mem::take(tks))),
4642    Some(Stored::VecDigested(list)) => Some(Stored::VecDigested(std::mem::take(list))),
4643    _ => None,
4644  }
4645}
4646
4647/// Make `value` the list under `key` again, in place: what [`take_pushed`] took, the list built since dropped.
4648pub fn restore_pushed(key: &str, value: Option<Stored>) {
4649  let mut state = state_mut!();
4650  match (state.lookup_value_mut(key), value) {
4651    (Some(slot @ (Stored::Tokens(_) | Stored::VecDigested(_))), Some(value)) => *slot = value,
4652    (Some(slot @ (Stored::Tokens(_) | Stored::VecDigested(_))), None) => *slot = Stored::None,
4653    (None | Some(Stored::None), Some(value)) => state.assign_value(key, value, Some(Scope::Global)),
4654    _ => {},
4655  }
4656}
4657
4658/// The value bound to `key`, or `None` when nothing is bound — Perl's
4659/// `LookupValue`.
4660///
4661/// Returns whatever [`Stored`] variant was assigned, so a caller that knows the
4662/// type usually wants [`lookup_string`] / [`lookup_number`] / [`lookup_bool`]
4663/// instead. Clones the value; [`with_value`] lends it when inspecting is enough.
4664pub fn lookup_value(key: &str) -> Option<Stored> { state!().lookup_value(key).cloned() }
4665pub fn with_value<R, FnR>(key: &str, caller: FnR) -> R
4666where FnR: FnOnce(Option<&Stored>) -> R {
4667  caller(state!().lookup_value(key))
4668}
4669/// Sym-keyed variant of `with_value` — avoids the per-call `arena::pin(key)`.
4670pub fn with_value_sym<R, FnR>(key: SymStr, caller: FnR) -> R
4671where FnR: FnOnce(Option<&Stored>) -> R {
4672  caller(state!().lookup_value_sym(key))
4673}
4674pub fn with_value_mut<R, FnR>(key: &str, caller: FnR) -> R
4675where FnR: FnOnce(Option<&mut Stored>) -> R {
4676  caller(state_mut!().lookup_value_mut(key))
4677}
4678/// `\fontdimen<p>` of the font whose parameter array is stored under `key`,
4679/// in sp (Perl's `$$fontinfo{data}`, TeX_Fonts.pool.ltxml:131-137); `None`
4680/// when the font has no array yet or `p` lies past its end.
4681pub fn font_parameter(key: &str, p: usize) -> Option<i64> {
4682  with_value(key, |value| match value {
4683    Some(Stored::FontDimens(params)) => p
4684      .checked_sub(1)
4685      .and_then(|index| params.borrow().get(index).copied()),
4686    _ => None,
4687  })
4688}
4689
4690/// Give the font whose array is stored under `key` its parameters, in sp:
4691/// Perl's `\font` filling a new font's `$$fontinfo{data}` from its metric
4692/// (TeX_Fonts.pool.ltxml:108-117). Unbound by any group, as a font is.
4693pub fn assign_font_parameters(key: &str, params: Vec<i64>) {
4694  assign_value_inplace(key, Stored::FontDimens(Rc::new(RefCell::new(params))));
4695}
4696
4697/// Set `\fontdimen<p>` of the font whose array is stored under `key`; a
4698/// parameter past its end grows it with zeros (TeX_Fonts.pool.ltxml:138-146,
4699/// tex.web §580), and a font without one gets an array of its own — as TeX's
4700/// `\nullfont` has parameters, where Perl's setter does nothing for a font
4701/// without data (:141). Written in
4702/// place and so global, as every font parameter assignment is (tex.web §1253):
4703/// the array is created unbound by any group, whatever `\globaldefs`. Returns
4704/// false, assigning nothing, for parameter 0 or one past TeX's font memory
4705/// ([`font::FONT_MEM_SIZE`]).
4706pub fn set_font_parameter(key: &str, p: usize, value: i64) -> bool {
4707  let Some(index) = p
4708    .checked_sub(1)
4709    .filter(|&index| index < font::FONT_MEM_SIZE)
4710  else {
4711    return false;
4712  };
4713  let set = |params: &mut Vec<i64>| {
4714    if params.len() <= index {
4715      params.resize(index + 1, 0);
4716    }
4717    params[index] = value;
4718  };
4719  let existing = with_value(key, |stored| match stored {
4720    Some(Stored::FontDimens(params)) => Some(Rc::clone(params)),
4721    _ => None,
4722  });
4723  match existing {
4724    Some(params) => {
4725      // (a font's parameter is written in loops: the key's pinned only for a journal or a watch)
4726      if WRITES_WATCHED.get() {
4727        state_mut!().journal_touch(TableName::Value, arena::pin(key));
4728      }
4729      set(&mut params.borrow_mut())
4730    },
4731    None => {
4732      let mut params = Vec::new();
4733      set(&mut params);
4734      assign_font_parameters(key, params);
4735    },
4736  }
4737  true
4738}
4739
4740/// A binding's document-wide state, one value of the Value table: bound globally, as the `\global` macros and registers
4741/// of the package it stands for are, so a rollback (`begin_assignment_journal`: a rehearsal, a title-page check) puts it
4742/// back, where a thread-local would keep what the discarded run did (`FRONTMATTER_SINGLE_ENGINE_PLAN.md` "What a rollback
4743/// leaves"). It changes in place, unless an open journal holds it: the first change under a journal works on a copy, so a
4744/// list a binding grows costs no more than a thread-local's outside one.
4745pub struct DocumentState<T> {
4746  key:   &'static str,
4747  state: std::marker::PhantomData<fn() -> T>,
4748}
4749
4750impl<T: Clone + Default + 'static> DocumentState<T> {
4751  pub const fn new(key: &'static str) -> Self {
4752    Self {
4753      key,
4754      state: std::marker::PhantomData,
4755    }
4756  }
4757
4758  /// Read the state; the default where nothing was changed yet.
4759  pub fn read<R>(&self, read: impl FnOnce(&T) -> R) -> R {
4760    let held = with_value(self.key, |stored| match stored {
4761      Some(Stored::Opaque(held)) => Some(Rc::clone(held)),
4762      _ => None,
4763    });
4764    match held.as_ref().and_then(|held| held.downcast_ref::<T>()) {
4765      Some(state) => read(state),
4766      None => read(&T::default()),
4767    }
4768  }
4769
4770  /// Change the state; `change` must not reach this same state again.
4771  pub fn update<R>(&self, change: impl FnOnce(&mut T) -> R) -> R {
4772    let key = arena::pin(self.key);
4773    let held = {
4774      let state = &mut *state_mut!();
4775      state.journal_touch(TableName::Value, key);
4776      state
4777        .value
4778        .get_mut(&key)
4779        .and_then(VecDeque::front_mut)
4780        .map(std::mem::take)
4781    };
4782    let bound = held.is_some();
4783    let mut own: Rc<dyn std::any::Any> = match held {
4784      Some(Stored::Opaque(held)) if held.is::<T>() => held,
4785      _ => Rc::new(T::default()),
4786    };
4787    if Rc::get_mut(&mut own).is_none() {
4788      let copy = own.downcast_ref::<T>().cloned().unwrap_or_default();
4789      own = Rc::new(copy);
4790    }
4791    let result = Rc::get_mut(&mut own)
4792      .and_then(|state| state.downcast_mut::<T>())
4793      .map(change)
4794      .expect("a state held once, of its type");
4795    if bound {
4796      assign_value_inplace_sym(key, Stored::Opaque(own));
4797    } else {
4798      assign_value_sym(key, Stored::Opaque(own), Some(Scope::Global));
4799    }
4800    result
4801  }
4802}
4803
4804/// Note for an open assignment journal that the box in the register `key` is about to have its dimension `property` set
4805/// (`\\wd`, `\\ht`, `\\dp`): a property of the box itself, which no binding's value holds. Also ends the watch held
4806/// ([`watch_state`]).
4807pub fn journal_box_dimension(key: &str, property: &'static str) {
4808  if !WRITES_WATCHED.get() {
4809    return;
4810  }
4811  set_watch(0);
4812  if !JOURNAL_GUARD_LIVE.get() {
4813    return;
4814  }
4815  let a_box = with_value(key, |stored| match stored {
4816    Some(Stored::Digested(a_box)) => Some(a_box.clone()),
4817    _ => None,
4818  });
4819  if let Some(a_box) = a_box
4820    && let Some(journal) = state_mut!().journal.as_mut()
4821  {
4822    let value = crate::BoxOps::get_property(&a_box, property)
4823      .as_deref()
4824      .cloned();
4825    journal.box_dimensions.push((a_box, property, value));
4826  }
4827}
4828
4829/// The input stream stored under `key` (`\\openin`'s), to read it or close it: a mouth changes in place, so under an open
4830/// assignment journal the first one to change it works on a copy of its own, in the stream's place, and a rollback gives the
4831/// document's back where it stood. A `\\read` in a rehearsal (a frontmatter field, a title page) took the document's next line.
4832pub fn input_stream_to_change(key: &str) -> Option<Rc<RefCell<mouth::Mouth>>> {
4833  let mouth = with_value(key, |stored| match stored {
4834    Some(Stored::Mouth(mouth)) => Some(Rc::clone(mouth)),
4835    _ => None,
4836  })?;
4837  let key_sym = arena::pin(key);
4838  let copying = {
4839    let state = state!();
4840    JOURNAL_GUARD_LIVE.get()
4841      && state
4842        .journal
4843        .as_ref()
4844        .is_some_and(|journal| !journal.saved.contains_key(&(TableName::Value, key_sym)))
4845  };
4846  if !copying {
4847    return Some(mouth);
4848  }
4849  let copy = Rc::new(RefCell::new(mouth.borrow_mut().copy_for_a_rollback()));
4850  assign_value_inplace_sym(key_sym, Stored::Mouth(Rc::clone(&copy)));
4851  Some(copy)
4852}
4853
4854/// Undo-stack depth (open TeX groups) — pass-1 streaming telemetry.
4855pub fn undo_depth() -> usize { state!().undo.len() }
4856
4857thread_local! {
4858  /// The save-stack depth at which an interleaved build step began (`None` =
4859  /// not building, or building after digestion the eager way).
4860  static BUILD_FLOOR: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
4861}
4862
4863/// Run a build step (a fragment's `Document::absorb`) that the streaming
4864/// driver interleaves with digestion. Eager Rust and Perl build AFTER
4865/// digestion, outside every group, so a constructor's local `assign_value`
4866/// (the aligning context's `ALIGNING_NODE`, a frontmatter store, a
4867/// counter) never pops; interleaved, the same binding lands in whichever
4868/// digestion group is open at the seam and is popped at that group's end —
4869/// tikz-network under tufte-book streamed with a stale root-level aligning
4870/// context re-exposed by `\end{fullwidth}`, stamping `ltx_align_left` on
4871/// chapters 4-5 and the appendices. Bindings made at the depth the step
4872/// began at are therefore global for the step; the frames the build itself
4873/// pushes above that depth (collected environment frames) keep their local
4874/// bindings and pop as in eager.
4875pub fn with_build_floor<R>(f: impl FnOnce() -> R) -> R {
4876  let previous = BUILD_FLOOR.replace(Some(undo_depth()));
4877  let result = f();
4878  BUILD_FLOOR.set(previous);
4879  result
4880}
4881
4882/// A bit of Perl "existence as truth" semantics mixed in with proper boolean lookup
4883pub fn lookup_bool(key: &str) -> bool { lookup_bool_sym(arena::pin(key)) }
4884
4885/// `lookup_bool` variant for hot call sites with a pre-pinned SymStr
4886/// (see `crate::pin!`). Skips the per-call `arena::pin(key)` hash
4887/// lookup — significant on every-expansion hot paths. `SymStr` is a
4888/// `u32` wrapper (Copy), so it passes by value — no borrow overhead.
4889pub fn lookup_bool_sym(key: SymStr) -> bool {
4890  let state = state!();
4891  match state.lookup_value_sym(key) {
4892    None => false,
4893    Some(v) => v.into(),
4894  }
4895}
4896
4897/// `lookup_string` variant using a pre-pinned SymStr key.
4898pub fn lookup_string_from_sym(key: SymStr) -> String {
4899  let state = state!();
4900  match state.lookup_value_sym(key) {
4901    None => String::new(),
4902    Some(v) => v.into(),
4903  }
4904}
4905
4906/// [`lookup_string_from_sym`]'s value as its interned symbol (`pin!("")` when unset), without the `String`.
4907pub fn lookup_string_sym_from_sym(key: SymStr) -> SymStr {
4908  let state = state!();
4909  match state.lookup_value_sym(key) {
4910    None => pin!(""),
4911    Some(Stored::String(v)) => *v,
4912    Some(other) => arena::pin(String::from(other)),
4913  }
4914}
4915
4916/// The current `MODE`, for the mode tests on every digested token: compare with `pin!("horizontal")`, or use
4917/// [`mode_ends_with`].
4918pub fn lookup_mode() -> SymStr { lookup_string_sym_from_sym(pin!("MODE")) }
4919
4920/// Whether the current `MODE` ends with `suffix` (Perl's `lookupValue('MODE') =~ /vertical$/`).
4921pub fn mode_ends_with(suffix: &str) -> bool {
4922  arena::with(lookup_mode(), |mode| mode.ends_with(suffix))
4923}
4924
4925/// like `lookup_value`, but casts the entry into a SymStr from the string interner
4926///  (`pin!("")` if None)
4927pub fn lookup_string_sym(key: &str) -> SymStr {
4928  let state = state!();
4929  match state.lookup_value(key) {
4930    None => pin!(""),
4931    Some(Stored::String(v)) => *v,
4932    Some(other) => arena::pin(other.to_string()),
4933  }
4934}
4935/// like `lookup_value`, but casts the entry into a String (empty if None)
4936pub fn lookup_string(key: &str) -> String {
4937  let state = state!();
4938  match state.lookup_value(key) {
4939    None => String::new(),
4940    // A list value has no scalar string form; return "" rather than leaking the
4941    // internal `VecDequeStored[…]`/`Strings` Debug repr (#315). Structural
4942    // access to list values is via the Rhai `LookupValue` binding, which
4943    // returns an array (mirroring Perl's `LookupValue` → arrayref).
4944    Some(v) if v.is_list() => String::new(),
4945    Some(v) => v.into(),
4946  }
4947}
4948/// like `lookup_value` but only recognizes Int, Bool and Number variants of Stored (default: 0)
4949pub fn lookup_int(key: &str) -> i64 { lookup_int_sym(arena::pin(key)) }
4950
4951/// Perl `Conditional.pm:61-62`: bump the global conditional counter and
4952/// return the new id for the `IfFrame` (see [`State::if_count`]).
4953pub fn next_if_id() -> i64 {
4954  let mut state = state_mut!();
4955  state.if_count += 1;
4956  state.if_count
4957}
4958/// Perl `unshiftValue('if_stack', …)` (Conditional.pm:63): open a conditional (see
4959/// [`State::if_stack`]).
4960pub fn push_if_frame(frame: Rc<RefCell<crate::definition::conditional::IfFrame>>) {
4961  state_mut!().if_stack.push(frame);
4962}
4963/// The innermost active conditional, Perl `LookupValue('if_stack')->[0]`.
4964pub fn top_if_frame() -> Option<Rc<RefCell<crate::definition::conditional::IfFrame>>> {
4965  state!().if_stack.last().cloned()
4966}
4967/// Perl `shiftValue('if_stack')`: close the innermost active conditional.
4968pub fn pop_if_frame() -> Option<Rc<RefCell<crate::definition::conditional::IfFrame>>> {
4969  state_mut!().if_stack.pop()
4970}
4971/// The number of active conditionals.
4972pub fn if_stack_depth() -> usize { state!().if_stack.len() }
4973/// The active conditionals, each with its state as it is now, for [`restore_if_stack`] to put back.
4974pub fn if_stack_snapshot() -> Vec<(
4975  Rc<RefCell<crate::definition::conditional::IfFrame>>,
4976  crate::definition::conditional::IfFrame,
4977)> {
4978  state!()
4979    .if_stack
4980    .iter()
4981    .map(|frame| (Rc::clone(frame), frame.borrow().clone()))
4982    .collect()
4983}
4984/// Put the active conditionals back as [`if_stack_snapshot`] took them: the frames it held, their state as it was —
4985/// those a run opened dropped, those it closed (a `\fi` of its own matching one opened before it) open again.
4986pub fn restore_if_stack(
4987  snapshot: Vec<(
4988    Rc<RefCell<crate::definition::conditional::IfFrame>>,
4989    crate::definition::conditional::IfFrame,
4990  )>,
4991) {
4992  let frames = snapshot
4993    .into_iter()
4994    .map(|(frame, saved)| {
4995      *frame.borrow_mut() = saved;
4996      frame
4997    })
4998    .collect();
4999  state_mut!().if_stack = frames;
5000}
5001/// Perl `$LaTeXML::IF_LIMIT`: the runaway ceiling on conditional ids
5002/// (`0` = unlimited), set by `latexml.sty`'s `iflimit` option.
5003pub fn if_limit() -> i64 { state!().if_limit }
5004/// Set [`if_limit`] (Perl `latexml.sty.ltxml:101`).
5005pub fn set_if_limit(limit: i64) { state_mut!().if_limit = limit; }
5006/// The conditionals counted so far ([`State::if_count`]).
5007pub fn if_count() -> i64 { state!().if_count }
5008/// Put [`if_count`] back: a discarded run the read budget ended counts against no limit (latexml_engine sect05.rs
5009/// `speculative_run_read`).
5010pub fn set_if_count(count: i64) { state_mut!().if_count = count; }
5011/// Perl `Object.pm:163-168`: bump the global absorb counter and return it
5012/// (see [`State::absorb_count`]).
5013pub fn next_absorb_id() -> i64 {
5014  let mut state = state_mut!();
5015  state.absorb_count += 1;
5016  state.absorb_count
5017}
5018/// Perl `$LaTeXML::ABSORB_LIMIT`: the runaway ceiling on absorbed boxes
5019/// (`0` = unlimited), set by `latexml.sty`'s `absorblimit` option.
5020pub fn absorb_limit() -> i64 { state!().absorb_limit }
5021/// Set [`absorb_limit`] (Perl `latexml.sty.ltxml:104`).
5022pub fn set_absorb_limit(limit: i64) { state_mut!().absorb_limit = limit; }
5023/// `lookup_int` variant for hot call sites with a pre-pinned SymStr (see
5024/// `crate::pin!`). Skips the per-call `arena::pin(key)` hash lookup — the
5025/// sibling of [`lookup_bool_sym`].
5026pub fn lookup_int_sym(key: SymStr) -> i64 {
5027  let state = state!();
5028  match state.lookup_value_sym(key) {
5029    Some(Stored::Int(i)) => *i,
5030    Some(Stored::Bool(true)) => 1, // this is Perl's boolean -> integer semantics
5031    Some(Stored::Number(n)) => n.value_of(),
5032    _ => 0,
5033  }
5034}
5035/// `lookup_int` variant that never panics on a live mutable borrow.
5036///
5037/// Returns `None` when STATE is currently mutably borrowed (contention),
5038/// `Some(0)` when the key is absent/non-integer (matching `lookup_int`'s
5039/// default), else `Some(value)`.
5040///
5041/// This exists for the `Error!`/`Warn!` reporting path: an error can legitimately
5042/// be raised from inside a `state_mut()` scope (e.g. `push_value`'s BUG branch,
5043/// or any constructor `after_digest` holding the borrow). A plain `borrow()` there
5044/// panics "RefCell already mutably borrowed", aborting the whole conversion
5045/// (FATAL_panic; crashed tikz-cd 2001.08973 via `push_value("QED@stack", …)`).
5046/// The error reporter must be re-entrancy-safe regardless of what borrows are
5047/// held — degrade to "unknown" on contention rather than crash.
5048pub fn try_lookup_int(key: &str) -> Option<i64> {
5049  let state = state_root().try_borrow().ok()?;
5050  Some(match state.lookup_value(key) {
5051    Some(Stored::Int(i)) => *i,
5052    Some(Stored::Bool(true)) => 1,
5053    Some(Stored::Number(n)) => n.value_of(),
5054    _ => 0,
5055  })
5056}
5057
5058/// [`try_lookup_int`]'s string counterpart: the string at `key`, `None` when it holds none or the state is borrowed.
5059pub fn try_lookup_string(key: &str) -> Option<String> {
5060  let state = state_root().try_borrow().ok()?;
5061  match state.lookup_value(key) {
5062    Some(Stored::String(s)) => Some(arena::with(*s, str::to_owned)),
5063    _ => None,
5064  }
5065}
5066
5067/// [`assign_value`] globally on the reporting path, where the state may be borrowed (as [`try_lookup_int`]): whether
5068/// it was assigned.
5069pub fn try_assign_value_global(key: &str, value: Stored) -> bool {
5070  let Ok(mut state) = state_root().try_borrow_mut() else {
5071    return false;
5072  };
5073  state.assign_value(key, value, Some(Scope::Global));
5074  true
5075}
5076
5077pub fn remove_vecdeque(key: &str) -> Option<VecDeque<Stored>> {
5078  match remove_value(key) {
5079    Some(Stored::VecDequeStored(v)) => Some(v),
5080    _ => None,
5081  }
5082}
5083/// convenience method to lookup the current value at the "font" key
5084pub fn lookup_font() -> Option<Rc<Font>> {
5085  // try_borrow, not state!()'s borrow(): this accessor is reachable from a
5086  // Whatsit's Display/revert path (e.g. tex_glue::revert_skip → lookup_font)
5087  // which can run *while STATE is already mutably borrowed* — e.g. formatting a
5088  // whatsit into a log/error message inside a state_mut() scope. A plain
5089  // borrow() then panics "RefCell already mutably borrowed", aborting the worker
5090  // (FATAL_101; crashed hep-th9908053, a \documentstyle[12pt]{article} 2.09
5091  // paper). Degrade to None on contention instead of crashing.
5092  //
5093  // CAUTION for future callers (PR #249 review P3-18): None-on-contention is
5094  // only correct for Display/revert/log-formatting consumers (where a
5095  // defaulted font is cosmetic). Several digestion-path callers `.unwrap()`
5096  // the result (tbox.rs, whatsit.rs, stomach.rs) — they would panic loudly on
5097  // contention, which is the desired behavior there: a DIGESTION-path
5098  // re-entrant lookup is a real bug, and silently defaulting the font would
5099  // turn it into invisible wrong-font drift in the XML. If you add a caller,
5100  // pick deliberately: `.unwrap()` on digestion paths, graceful None only
5101  // where the font is presentational.
5102  let Ok(st) = state_root().try_borrow() else {
5103    return None;
5104  };
5105  match st.lookup_value_sym(pin!("font")) {
5106    None | Some(Stored::None) => None,
5107    Some(f) => f.into(),
5108  }
5109}
5110/// convenience method to lookup the current value at the "mathfont" key
5111pub fn lookup_mathfont() -> Option<Rc<Font>> {
5112  // Route through `lookup_value_sym` with a cached SymStr (via
5113  // `pin!`) to skip the per-call `arena::pin("mathfont")` probe on
5114  // this hot path (math-env entry/exit, per-formula checks).
5115  match state!().lookup_value_sym(pin!("mathfont")) {
5116    None | Some(Stored::None) => None,
5117    Some(v) => v.into(),
5118  }
5119}
5120
5121/// a convenience method to globally asign a `Font` to the "font" key
5122pub fn assign_font(font: Rc<Font>, scope: Option<Scope>) {
5123  assign_value_sym(pin!("font"), Stored::Font(font), scope);
5124}
5125
5126/// a variant of `lookup_value` that casts the value into `Number`
5127pub fn lookup_number(key: &str) -> Option<Number> {
5128  match state!().lookup_value(key) {
5129    None | Some(Stored::None) => None,
5130    Some(v) => v.into(),
5131  }
5132}
5133/// a variant of `lookup_value` that casts the value into `Float`
5134///
5135/// The float counterpart of [`lookup_number`]. `Float` isn't a TeX register
5136/// type (see `common::float`), but binding authors need a fractional read/write
5137/// pair — e.g. `NOMINAL_FONT_SIZE` at the `11pt` class option is `10.95`, which
5138/// [`lookup_number`]/[`lookup_int`] would truncate to `10` (issue #542).
5139pub fn lookup_float(key: &str) -> Option<Float> {
5140  match state!().lookup_value(key) {
5141    None | Some(Stored::None) => None,
5142    Some(v) => v.into(),
5143  }
5144}
5145/// a variant of `lookup_value` that casts the value into `Dimension`
5146pub fn lookup_dimension(key: &str) -> Option<Dimension> {
5147  let key = register_value_key(key);
5148  match state!().lookup_value(&key) {
5149    None | Some(Stored::None) => None,
5150    Some(v) => v.into(),
5151  }
5152}
5153/// Whether `address` is a slot of a primitive register bank — `\count<n>`,
5154/// `\dimen<n>`, `\skip<n>`, `\muskip<n>`, `\toks<n>`, `\box<n>` — i.e. what
5155/// `\newdimen` & co. allocate (tex.web §1224), as opposed to a register named
5156/// after its own (or another) control sequence.
5157pub fn is_allocated_register_address(address: &str) -> bool {
5158  [
5159    "\\count", "\\dimen", "\\skip", "\\muskip", "\\toks", "\\box",
5160  ]
5161  .iter()
5162  .any(|bank| {
5163    address
5164      .strip_prefix(bank)
5165      .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
5166  })
5167}
5168
5169/// Where a register's value lives: its address, which is not its CS name once the
5170/// format allocated it (latex.ltx's `\newdimen\columnsep` is `\dimen124`; the
5171/// dump records it and `def_register` keeps it). Name-keyed readers of a kernel
5172/// length (`lookup_dimension("\\textwidth")`) go through the address.
5173fn register_value_key(key: &str) -> Cow<'_, str> {
5174  if key.starts_with('\\')
5175    && let Some(register) = lookup_register_definition(&T_CS!(key))
5176    && is_allocated_register_address(&register.address)
5177  {
5178    return Cow::Owned(register.address.clone());
5179  }
5180  Cow::Borrowed(key)
5181}
5182/// a variant of `lookup_value` that only recognizes a `Stored::Glue`
5183pub fn lookup_glue(key: &str) -> Option<Glue> {
5184  let key = register_value_key(key);
5185  match state!().lookup_value(&key) {
5186    Some(Stored::Glue(v)) => Some(*v),
5187    None | Some(Stored::None) => None,
5188    Some(other) => panic!("State lookup expected Glue, found: {other:?}"),
5189  }
5190}
5191/// a variant of `lookup_value` that only recognizes a `Stored::Glue`
5192pub fn lookup_muglue(key: &str) -> Option<MuGlue> {
5193  match state!().lookup_value(key) {
5194    Some(Stored::MuGlue(v)) => Some(*v),
5195    None | Some(Stored::None) => None,
5196    Some(other) => panic!("State lookup expected MuGlue, found: {other:?}"),
5197  }
5198}
5199/// a variant of `lookup_value` that casts the response into `Tokens`
5200pub fn lookup_tokens(key: &str) -> Option<Tokens> {
5201  let state = state!();
5202  match state.lookup_value(key) {
5203    None | Some(Stored::None) => None,
5204    Some(Stored::Tokens(v)) => Some(v.clone()),
5205    Some(Stored::Token(v)) => Some(Tokens::new(vec![*v])),
5206    Some(Stored::String(sym)) => {
5207      // Release the state borrow first, then read the interned string through
5208      // the arena. The copy is unavoidable: an arena `&str` lives only for the
5209      // lend, and `TeXString` borrows only `'static`, so the value has to be owned
5210      // to cross into the tokenizer. `Mouth::new` copies its input anyway.
5211      let sym = *sym;
5212      drop(state);
5213      arena::with(sym, |astr| {
5214        Some(mouth::tokenize_internal(TeXString::assembled(
5215          astr.to_string(),
5216        )))
5217      })
5218    },
5219    Some(Stored::VecDequeStored(v)) => {
5220      // Reverting the queue to Tokens routes each String item through
5221      // `mouth::tokenize_internal`, which takes a *mutable* STATE borrow — so
5222      // clone the queue and drop the immutable `state` borrow first (mirrors
5223      // the `Stored::String` branch above). Without this, LookupTokens on a
5224      // VecDequeStored key (e.g. "class_options") panics "RefCell already
5225      // borrowed" (#314).
5226      let vdq = v.clone();
5227      drop(state);
5228      Stored::VecDequeStored(vdq).into()
5229    },
5230    _ => None,
5231  }
5232}
5233/// a variant of `lookup_value` that only recognizes a `Stored::Token`
5234pub fn lookup_token(key: &str) -> Option<Token> {
5235  match state!().lookup_value(key) {
5236    Some(Stored::Token(t)) => Some(*t),
5237    _ => None,
5238  }
5239}
5240
5241/// a variant of `lookup_token` taking an already-pinned SymStr key —
5242/// avoids the per-call `arena::pin(key)` hash lookup.
5243pub fn lookup_token_sym(key: SymStr) -> Option<Token> {
5244  match state!().lookup_value_sym(key) {
5245    Some(Stored::Token(t)) => Some(*t),
5246    _ => None,
5247  }
5248}
5249
5250pub fn lookup_alignment() -> Option<Digested> {
5251  // Can only be a token or definition; we want defns!
5252  // is this the right logic here? don't expand unless digesting?
5253  state!().lookup_value_sym(pin!("Alignment")).and_then(|v| {
5254    if let Stored::Digested(d) = v {
5255      if matches!(d.data(), DigestedData::Alignment(_)) {
5256        // for now clone the Digested object (approx. an Rc<_> clone)
5257        // instead of returning &Digested, to simplify lifetime checks
5258        Some(d.clone())
5259      } else {
5260        None
5261      }
5262    } else {
5263      None
5264    }
5265  })
5266}
5267pub fn assign_alignment(alignment: Alignment, scope: Option<Scope>) {
5268  assign_value("Alignment", alignment, scope);
5269}
5270
5271pub fn assign_register(
5272  cs: &str,
5273  value: RegisterValue,
5274  scope: Option<Scope>,
5275  parameters: Vec<ArgWrap>,
5276) -> Result<()> {
5277  assign_register_token(&T_CS!(cs), value, scope, parameters)
5278}
5279/// `assign_register` variant taking a pre-built Token — lets hot
5280/// callers skip the `T_CS!(&str)` pin when they already have the CS
5281/// cached (e.g. via `T_CS!("\\c@…")` literal which routes through
5282/// `pin!`).
5283pub fn assign_register_token(
5284  cs: &Token,
5285  value: RegisterValue,
5286  scope: Option<Scope>,
5287  parameters: Vec<ArgWrap>,
5288) -> Result<()> {
5289  let defn_opt = lookup_definition(cs)?;
5290  if let Some(defn) = defn_opt
5291    && defn.is_register()
5292  {
5293    defn.set_value(value, scope, parameters)?;
5294    return Ok(());
5295  }
5296  warn_not_register(cs);
5297  Ok(())
5298}
5299/// Perl `LookupRegister`/`AssignRegister`'s Warning (Package.pm:1367-1369, 1404-1405) on a cs that is not a register.
5300pub fn warn_not_register(cs: impl Display) {
5301  Warn!(
5302    "expected",
5303    "register",
5304    format!("The control sequence {cs} is not a register")
5305  );
5306}
5307pub fn lookup_register(cs: &str, parameters: Vec<ArgWrap>) -> Result<Option<RegisterValue>> {
5308  lookup_register_token(&T_CS!(cs), parameters)
5309}
5310/// Token-keyed variant of `lookup_register` — saves the per-call
5311/// `T_CS!(&str)` pin for hot callers with a cached CS token.
5312pub fn lookup_register_token(
5313  cs: &Token,
5314  parameters: Vec<ArgWrap>,
5315) -> Result<Option<RegisterValue>> {
5316  // Quiet on an undefined cs, unlike Perl `LookupRegister` (Package.pm:1360-1369): kernel callers probe optional
5317  // registers with it (geometry's `\Gm@tw`); the binding macro `LookupRegister!` Warns.
5318  Ok(match lookup_definition(cs)? {
5319    Some(defn) if defn.is_register() => defn.value_of(parameters),
5320    Some(_) => {
5321      warn_not_register(cs);
5322      None
5323    },
5324    None => None,
5325  })
5326}
5327
5328/// Quiet sibling of [`lookup_register`] for call sites that mirror Perl's
5329/// explicit `lookupDefinition(cs) && $defn->isRegister ? $defn->valueOf : <default>`
5330/// guard — e.g. TeX_Tables `\lx@text@intercol`/`\lx@math@intercol`
5331/// (`TeX_Tables.pool.ltxml` L639/L646), where a document may legitimately
5332/// `\renewcommand` a length register (`\tabcolsep`/`\arraycolsep`) into a plain
5333/// macro. In that case the register-ness is genuinely gone in Perl too, and Perl
5334/// silently falls back to its default (`Dimension(0)`) with **no warning**.
5335/// Returns `None` (no warning) when the CS is undefined or is not a register,
5336/// so the caller can apply its own faithful default.
5337pub fn lookup_register_quiet(cs: &str) -> Option<RegisterValue> {
5338  let defn = lookup_definition(&T_CS!(cs)).ok().flatten()?;
5339  if defn.is_register() {
5340    defn.value_of(Vec::new())
5341  } else {
5342    None
5343  }
5344}
5345
5346/// The value the engine's own parameter holds at its fixed address, the register's name (Perl Register.pm:52-56),
5347/// whatever the name now means: pdfTeX reads `every_eof`, `show_stream`, `err_help` from `eqtb`, so after
5348/// `\def\everyeof{E}` or `\let\everyeof\toks0` too. `None` while never assigned (the caller's default).
5349pub fn internal_register_value(address: &str) -> Option<RegisterValue> {
5350  with_value(address, |value| value.and_then(Into::into))
5351}
5352
5353/// Faithful port of Perl `LookupDimension` (`Package.pm` L1371-1393, as
5354/// widened by upstream PR #2829): try to turn the argument into a Dimension,
5355/// recognizing strings, registers, ….
5356///
5357/// * a string that looks like an obvious dimension (`/^[0-9+-.]\w\w+$/`,
5358///   e.g. `"3pt"` — but NOT `"0.4pt"`, whose `.` fails `\w`) parses directly;
5359/// * otherwise the string is tokenized: a single token that resolves to a
5360///   register returns its value ("easy and proper case");
5361/// * a multi-token sequence is read as a dimension from a fresh mouth;
5362/// * anything else warns (`expected:register`) unless `noerror`, and yields
5363///   `None` (Perl returns undef).
5364///
5365/// NOTE the #2829 semantics change carried over faithfully: a single token
5366/// whose definition is a MACRO (e.g. a document that `\def`s `\jot`) no
5367/// longer reads its body as a dimension — it now falls through to the warn
5368/// branch. (Perl's digested-Box coercion branch has no Rust equivalent here:
5369/// all our callers pass strings.)
5370pub fn lookup_dimension_cs(cs: &str, noerror: bool) -> Option<Dimension> {
5371  use std::str::FromStr;
5372  // Obvious dimension string? (Perl: /^[0-9\+\-\.]\w\w+$/)
5373  let mut chars = cs.chars();
5374  let leading_sign_or_digit =
5375    matches!(chars.next(), Some(c) if c.is_ascii_digit() || matches!(c, '+' | '-' | '.'));
5376  let obvious = leading_sign_or_digit
5377    && cs.chars().count() >= 3
5378    && chars.all(|c| c.is_alphanumeric() || c == '_');
5379  if obvious && let Ok(d) = Dimension::from_str(cs) {
5380    return Some(d);
5381  }
5382  let tokens = mouth::tokenize_internal(TeXString::assembled(cs.to_string()));
5383  let toks = tokens.unlist();
5384  if toks.len() == 1 {
5385    match lookup_definition(&toks[0]) {
5386      Ok(Some(defn)) if defn.is_register() => {
5387        // Easy (and proper) case.
5388        return defn.value_of(Vec::new()).map(|rv| Dimension::from(&rv));
5389      },
5390      // Defined but not a register (a `\def`-ized length): fall through and
5391      // read its body as a dimension. NB this is a deliberate DIVERGENCE
5392      // from post-#2829 Perl, which unintentionally LOST this path in the
5393      // rewrite (a single macro token falls to the warn branch upstream) —
5394      // see KNOWN_PERL_ERRORS #41. Real arXiv papers `\def\arraycolsep{...}`
5395      // (cluster regressions cover this); pre-#2829 Perl read the body.
5396      Ok(Some(_)) => {},
5397      // Undefined single token: warn like Perl and yield nothing.
5398      _ => {
5399        if !noerror {
5400          warn_not_register(cs);
5401        }
5402        return None;
5403      },
5404    }
5405  }
5406  // Read the token sequence (a defined single CS expands here, exactly like
5407  // Perl's readingFromMouth) as a dimension from a fresh mouth; an
5408  // unreadable sequence warns Missing-number inside read_dimension and
5409  // yields Dimension(0), matching Perl.
5410  gullet::reading_from_mouth(mouth::Mouth::default(), move || {
5411    gullet::unread(Tokens::new(toks));
5412    gullet::read_dimension()
5413  })
5414  .ok()
5415}
5416
5417pub fn lookup_expandable(
5418  token: &Token,
5419  toplevel_opt: Option<bool>,
5420) -> Result<Option<Rc<dyn Definition>>> {
5421  let toplevel = toplevel_opt.unwrap_or(true); // Default, for full expansion, same as read_x_token
5422  // Can only be a token or definition; we want defns!
5423  // is this the right logic here? don't expand unless digesting?
5424  Ok(
5425    lookup_definition(token)?
5426      .filter(|defn| (*defn).is_expandable() && (toplevel || !(*defn).is_protected())),
5427  )
5428}
5429
5430/// Whether token is affected by \noexpand
5431pub fn is_dont_expandable(token: &Token) -> bool {
5432  // Basically: a CS or Active token that is either not defined, or is expandable
5433  // (but not \let to a token)
5434  if token.get_catcode().is_active_or_cs() {
5435    let lookupname = meaning_key(token);
5436    if lookupname != pin!("") {
5437      match state!().meaning.get(&lookupname) {
5438        Some(entry) => {
5439          if let Some(def) = entry.front() {
5440            // the expandable variants are allowed
5441            matches!(
5442              def,
5443              Stored::Expandable(_) | Stored::Conditional(_) | Stored::None
5444            )
5445          } else {
5446            // undefined is allowed too (this is *really* subtle -- took some debugging of
5447            // etoolbox) both an empty VDQ, a VDQ with an entry present but matching
5448            // Stored::Noney, OR a completely missing VDQ are allowed "undefined" cases, each of
5449            // which flagging as "true"
5450            true
5451          }
5452        },
5453        None => true,
5454      }
5455    } else {
5456      true
5457    }
5458  } else {
5459    false
5460  }
5461}
5462
5463pub fn lookup_conditional(token: &Token) -> Option<ConditionalType> {
5464  // `get_executable_name` previously built a fresh `String` + `arena::pin`
5465  // probe per call; `pin_cs_name` already returns a cached `SymStr`
5466  // (primitive → `Catcode::name_sym`, otherwise `self.text`). Saves a
5467  // RefCell mut-borrow on the interner + a hashmap probe per token in
5468  // the gullet's conditional dispatch.
5469  if !token.code.is_executable() {
5470    return None;
5471  }
5472  let lookup_sym = token.pin_cs_name();
5473  state!().meaning.get(&lookup_sym).and_then(|entry| {
5474    if let Some(Stored::Conditional(defn)) = entry.front() {
5475      Some(defn.conditional_type)
5476    } else {
5477      None
5478    }
5479  })
5480}
5481
5482pub fn unshift_value<T: Into<Stored>>(key: &str, values: Vec<T>) {
5483  let values_iter = values.into_iter().map(Into::into);
5484  let key_sym = arena::pin(key);
5485  let mut state = state_mut!();
5486  state.journal_touch(TableName::Value, key_sym);
5487  if !state.value.contains_key(&key_sym) {
5488    state.assign_internal(
5489      TableName::Value,
5490      key_sym,
5491      Stored::VecDequeStored(VecDeque::new()),
5492      Some(Scope::Global),
5493    )
5494  }
5495  let receiver = state.value.get_mut(&key_sym).unwrap().front_mut();
5496  if let Some(&mut Stored::VecDequeStored(ref mut front)) = receiver {
5497    for value in values_iter.rev() {
5498      // preserving order unshift, as Perl's
5499      front.push_front(value)
5500    }
5501  } else if receiver.is_none() || matches!(receiver, Some(Stored::None)) {
5502    // Key doesn't exist yet — create a new VecDequeStored via the existing borrow
5503    let mut vd = VecDeque::new();
5504    for value in values_iter {
5505      vd.push_back(value);
5506    }
5507    state.assign_internal(
5508      TableName::Value,
5509      key_sym,
5510      Stored::VecDequeStored(vd),
5511      Some(Scope::Global),
5512    );
5513  } else {
5514    // Wrong type — warn but don't panic
5515    Warn!(
5516      "unexpected",
5517      "unshift_value",
5518      s!(
5519        "unshift_value expects VecDequeStored receiver for key {:?}, got: {:?}",
5520        key,
5521        receiver.map(|r| std::mem::discriminant(r))
5522      )
5523    );
5524  }
5525}
5526
5527pub fn shift_value(key: &str) -> Result<Option<Stored>> {
5528  let key_sym = arena::pin(key);
5529  let mut state = state_mut!();
5530  state.journal_touch(TableName::Value, key_sym);
5531  if !state.value.contains_key(&key_sym) {
5532    state.assign_internal(
5533      TableName::Value,
5534      key_sym,
5535      Stored::VecDequeStored(VecDeque::new()),
5536      Some(Scope::Global),
5537    )
5538  }
5539  Ok(
5540    if let Some(&mut Stored::VecDequeStored(ref mut front)) =
5541      state.value.get_mut(&key_sym).unwrap().front_mut()
5542    {
5543      front.pop_front()
5544    } else {
5545      Error!(
5546        "State",
5547        "Stored",
5548        "BUG: Tried to shift_value from a non-vecdeque value key!"
5549      );
5550      None
5551    },
5552  )
5553}
5554
5555/// Bind `key` to `value` inside the named mapping — Perl's `AssignMapping`.
5556///
5557/// A mapping is a named hash living in the value table (`TAG_PROPERTIES`,
5558/// `counter_for_type`, …). The mapping itself is created **globally** on first
5559/// use, so that entries assigned inside a group are still found from outside
5560/// it; passing `None` for `value` removes the key. Read entries back with
5561/// [`with_mapping`].
5562pub fn assign_mapping<T: Into<Stored>>(map: &str, key: &str, value: Option<T>) {
5563  let map_sym = arena::pin(map);
5564  let mut state = state_mut!();
5565  state.journal_touch(TableName::Value, map_sym);
5566  if !state.value.contains_key(&map_sym) || state.value[&map_sym].is_empty() {
5567    state.assign_internal(
5568      TableName::Value,
5569      map_sym,
5570      Stored::HashStored(SymHashMap::default()),
5571      Some(Scope::Global),
5572    );
5573  }
5574  let map_store = state.value.get_mut(&map_sym).unwrap();
5575  // TODO: What is the right abstraction here? this is hacky
5576  let mut stub_hash = SymHashMap::default();
5577  let mapping = match *map_store.front_mut().unwrap() {
5578    Stored::HashStored(ref mut mapping) => mapping,
5579    _ => &mut stub_hash,
5580  };
5581  match value {
5582    None => mapping.remove(key),
5583    Some(v) => mapping.insert(key, v.into()),
5584  };
5585}
5586
5587pub fn lookup_mapping(map: &str, key: &str) -> Option<Stored> {
5588  state!().lookup_mapping(map, key).cloned()
5589}
5590/// Sym-keyed variant — skip the per-call `arena::pin(map)` for hot
5591/// callers with a pre-pinned map key (e.g. via `pin!("siunitx_macros")`).
5592pub fn lookup_mapping_sym(map_sym: SymStr, key: &str) -> Option<Stored> {
5593  state!().lookup_mapping_sym(map_sym, key).cloned()
5594}
5595
5596//======================================================================
5597/// Was `name` bound?  If  `frame` is given, check only whether it is bound in
5598/// that frame (0 is the topmost).
5599pub fn is_value_bound(key: &str, frame_opt: Option<usize>) -> bool {
5600  let key_sym = arena::pin(key);
5601  match frame_opt {
5602    Some(frame) => state!()
5603      .undo
5604      .get(frame)
5605      .as_ref()
5606      .unwrap()
5607      .table(TableName::Value)
5608      .contains_key(&key_sym),
5609    None => !state!()
5610      .value
5611      .get(&key_sym)
5612      .unwrap_or(&VecDeque::new())
5613      .is_empty(),
5614  }
5615}
5616
5617/// The value `key` has in stack frame `frame` (0 = innermost): Perl State.pm:280-286 `valueInFrame`, which skips
5618/// the bindings the frames above it made.
5619pub fn value_in_frame(key: &str, frame: usize) -> Option<Stored> {
5620  let key_sym = arena::pin(key);
5621  let state = state!();
5622  let p: usize = state
5623    .undo
5624    .iter()
5625    .take(frame)
5626    .map(|f| {
5627      f.table(TableName::Value)
5628        .get(&key_sym)
5629        .copied()
5630        .unwrap_or(0)
5631    })
5632    .sum();
5633  state.value.get(&key_sym).and_then(|v| v.get(p)).cloned()
5634}
5635
5636/// The position in `key`'s value stack of the binding stack frame `frame` (0 = innermost) made, and how many it made
5637/// there (0 when it made none).
5638fn frame_binding_span(state: &State, key_sym: SymStr, frame: usize) -> (usize, usize) {
5639  let count = |f: &UndoFrame| {
5640    f.table(TableName::Value)
5641      .get(&key_sym)
5642      .copied()
5643      .unwrap_or(0)
5644  };
5645  let offset = state.undo.iter().take(frame).map(count).sum();
5646  (offset, state.undo.get(frame).map_or(0, count))
5647}
5648
5649/// Undoes the bindings of `key` that stack frame `frame` (0 = innermost) made — what popping that frame would undo,
5650/// for this key alone — and leaves the frames above it as they are.
5651pub fn unbind_value_in_frame(key: &str, frame: usize) {
5652  let key_sym = arena::pin(key);
5653  let mut state = state_mut!();
5654  let (offset, count) = frame_binding_span(&state, key_sym, frame);
5655  if count == 0 {
5656    return;
5657  }
5658  state.journal_touch(TableName::Value, key_sym);
5659  if let Some(f) = state.undo.get_mut(frame) {
5660    f.table_mut(TableName::Value).remove(&key_sym);
5661  }
5662  if let Some(values) = state.value.get_mut(&key_sym) {
5663    let end = (offset + count).min(values.len());
5664    values.drain(offset.min(end)..end);
5665  }
5666}
5667
5668/// Replaces the value `key` has in stack frame `frame` (0 = innermost), which must have bound it; returns the value
5669/// it had there, `None` when the frame made no binding of `key` (and nothing is changed).
5670pub fn replace_value_in_frame(key: &str, frame: usize, value: Stored) -> Option<Stored> {
5671  let key_sym = arena::pin(key);
5672  let mut state = state_mut!();
5673  let (offset, count) = frame_binding_span(&state, key_sym, frame);
5674  if count == 0 {
5675    return None;
5676  }
5677  state.journal_touch(TableName::Value, key_sym);
5678  let slot = state.value.get_mut(&key_sym)?.get_mut(offset)?;
5679  Some(std::mem::replace(slot, value))
5680}
5681
5682/// Binds `key` to `value` in stack frame `frame` (0 = innermost), replacing the binding that frame made, if any: the
5683/// value is undone with that frame, and the bindings of the frames above it still shadow it.
5684pub fn bind_value_in_frame(key: &str, frame: usize, value: Stored) {
5685  let key_sym = arena::pin(key);
5686  let mut state = state_mut!();
5687  if frame >= state.undo.len() {
5688    return;
5689  }
5690  let (offset, count) = frame_binding_span(&state, key_sym, frame);
5691  state.journal_touch(TableName::Value, key_sym);
5692  let values = state.value.entry(key_sym).or_default();
5693  if count > 0 {
5694    if let Some(slot) = values.get_mut(offset) {
5695      *slot = value;
5696    }
5697    return;
5698  }
5699  values.insert(offset.min(values.len()), value);
5700  if let Some(f) = state.undo.get_mut(frame) {
5701    f.table_mut(TableName::Value).insert(key_sym, 1);
5702  }
5703}
5704
5705/// The stack frame (0 = innermost) that made the `n`-th newest binding of `key` (0 = the binding in force), for
5706/// [`value_in_frame`]: which group a value was set in.
5707pub fn frame_of_binding(key: &str, n: usize) -> Option<usize> {
5708  let key_sym = arena::pin(key);
5709  let state = state!();
5710  let mut seen = 0;
5711  for (frame, f) in state.undo.iter().enumerate() {
5712    let bound = f
5713      .table(TableName::Value)
5714      .get(&key_sym)
5715      .copied()
5716      .unwrap_or(0);
5717    if bound > 0 {
5718      if seen + bound > n {
5719        return Some(frame);
5720      }
5721      seen += bound;
5722    }
5723  }
5724  None
5725}
5726
5727//======================================================================
5728/// Lookup & assign a character's Catcode
5729pub fn lookup_catcode(c: char) -> Option<Catcode> {
5730  // speedup over variant with allocation
5731  // i.e. "let s = c.to_string();"
5732  let s = arena::pin_char(c);
5733  match state!().catcode.get(&s) {
5734    None => unicode_letter_catcode_default(c),
5735    Some(cvec) => match cvec.front() {
5736      Some(Stored::Catcode(cc)) => Some(*cc),
5737      Some(_) => None, // non-catcode value in catcode table — treat as undefined
5738      _ => unicode_letter_catcode_default(c),
5739    },
5740  }
5741}
5742
5743/// Whether the document's engine persona is a Unicode engine: the `luatex` or
5744/// `xetex` profile of latexml.sty. Both formats load load-unicode-data
5745/// (latex.ltx:22071-22076), take `\char` code points above 255 natively and
5746/// have no utf8.def byte model; the engine-identity probes stay per-profile.
5747pub fn unicode_engine_profile() -> bool {
5748  lookup_bool("LUATEX_PROFILE") || lookup_bool("XETEX_PROFILE")
5749}
5750
5751/// The format-time Unicode letter catcodes of the LuaTeX/XeTeX kernels, as a
5752/// lazy default for code points the catcode table does not pin.
5753///
5754/// latex.ltx:22071-22076 inputs `load-unicode-data` only under LuaTeX/XeTeX, and
5755/// load-unicode-data.tex:98-99,134-135 assigns `\catcode 11` to every code point
5756/// of General_Category L or M. pdfTeX never does (utf8.def makes the bytes
5757/// active), and Perl `State.pm:113-115` letters only ASCII, so outside the
5758/// LuaTeX profile a non-ASCII char without a table entry stays OTHER
5759/// (`Mouth::get_next_char`). The profile check runs only for non-ASCII chars,
5760/// so the ASCII tokenizer path is untouched. U+0080–U+00FF are pinned OTHER by
5761/// the format dump; the `luatex` option re-letters them eagerly
5762/// (`latexml_sty/mod.rs`). Witnesses: circledtext (102→0), jnuexam, tikz-bagua;
5763/// guards `perfect_kernel_batch56::{non_ascii_letters_stay_other_under_pdftex,
5764/// non_ascii_letters_are_letters_under_luatex}`.
5765fn unicode_letter_catcode_default(c: char) -> Option<Catcode> {
5766  if c > '\x7f'
5767    && ((unicode_engine_profile() && is_unicode_letter_or_mark(c))
5768      || (lookup_bool("PTEX_PROFILE") && is_ptex_kanji_letter(c)))
5769  {
5770    Some(Catcode::LETTER)
5771  } else {
5772    None
5773  }
5774}
5775
5776/// K12 — pTeX's control-word letters. pTeX/upTeX give every non-ASCII code
5777/// point a `kcatcode` (upTeX manual §kcatcode: 16 kanji, 17 kana, 18 other
5778/// kchar, 19 hangul, 20 modifier; ASCII is always Latin), and a control word
5779/// after `\` extends over kanji, kana (and, upTeX, hangul/modifier) characters
5780/// — `\if西暦` is one control sequence (jsarticle.cls:1927 `\newif\if西暦`,
5781/// ptex-manual `\黄マーカー`); kcatcode 18 (symbols, fullwidth punctuation)
5782/// ends it, and Latin-1/Greek/Cyrillic stay inputenc bytes (kcatcode 15), so
5783/// this is the block set of the kanji/kana/hangul kcatcodes, not the Unicode
5784/// letter class. Under `PTEX_PROFILE` (set by `\NeedsTeXFormat{pLaTeX2e}` /
5785/// `{upLaTeX2e}`) these default to LETTER, as the LuaTeX profile letters the
5786/// L/M class; under pdfTeX they stay OTHER, where both LaTeXML engines let
5787/// `\newif\if西暦`'s bare `\if` to `\iffalse` and every `\if` after it fails.
5788pub fn is_ptex_kanji_letter(c: char) -> bool {
5789  matches!(c as u32,
5790    0x3040..=0x30FF   // Hiragana, Katakana (kana, 17)
5791    | 0x31F0..=0x31FF // Katakana phonetic extensions (17)
5792    | 0x1AFF0..=0x1B16F // Kana Supplement / Extended-A/B, Small Kana (17)
5793    | 0xFF66..=0xFF6F // halfwidth katakana (17; U+FF70 ー is 18)
5794    | 0xFF71..=0xFF9D
5795    | 0xFF10..=0xFF19 // fullwidth digits and Latin letters (17)
5796    | 0xFF21..=0xFF3A
5797    | 0xFF41..=0xFF5A
5798    | 0x2E80..=0x2FDF // CJK radicals, Kangxi radicals (16)
5799    | 0x3105..=0x312F // Bopomofo (16)
5800    | 0x3190..=0x31EF // Kanbun, Bopomofo extended, CJK strokes (16)
5801    | 0x3400..=0x4DBF // CJK Unified Ideographs Extension A (16)
5802    | 0x4E00..=0x9FFF // CJK Unified Ideographs (16)
5803    | 0xF900..=0xFAFF // CJK Compatibility Ideographs (16)
5804    | 0x20000..=0x3FFFF // CJK Extensions B-J (16)
5805    | 0x1100..=0x11FF // Hangul Jamo (19)
5806    | 0x3130..=0x318F // Hangul compatibility Jamo (19)
5807    | 0xA960..=0xA97F // Hangul Jamo Extended-A (19)
5808    | 0xAC00..=0xD7FF // Hangul syllables and Jamo Extended-B (19)
5809  )
5810}
5811
5812/// load-unicode-data.tex:134-135 for U+0080–U+00FF: the LuaTeX/XeTeX format
5813/// letters every L/M code point, but the latex dump pins that range OTHER
5814/// (pdfTeX's utf8.def model), so the lazy default in `lookup_catcode` never
5815/// reaches it. Called at the format seam (`latexml_engine::latex`) and by the
5816/// `luatex`/`xetex` options of latexml.sty; 65 global assignments.
5817pub fn assign_luatex_latin1_letters() {
5818  for n in 0x80u32..=0xFF {
5819    if let Some(ch) = char::from_u32(n)
5820      && is_unicode_letter_or_mark(ch)
5821    {
5822      assign_catcode(ch, Catcode::LETTER, Some(Scope::Global));
5823    }
5824  }
5825}
5826
5827/// General_Category L ∪ M, the set load-unicode-data.tex letters. `is_alphabetic`
5828/// also admits Nl (Roman numerals), which the kernel leaves OTHER; combining marks
5829/// (M) are added explicitly.
5830pub fn is_unicode_letter_or_mark(c: char) -> bool {
5831  (c.is_alphabetic() && !c.is_numeric()) || unicode_normalization::char::is_combining_mark(c)
5832}
5833
5834/// assigns a Catcode for a given character
5835pub fn assign_catcode(key: char, value: Catcode, scope: Option<Scope>) {
5836  let s = arena::pin_char(key);
5837  state_mut!().assign_internal(TableName::Catcode, s, Stored::Catcode(value), scope);
5838}
5839/// like `lookup_catcode` but targets Mathcode and its table
5840pub fn lookup_mathcode(key: &str) -> Option<u16> {
5841  let key_sym = arena::pin(key);
5842  match state!().mathcode.get(&key_sym) {
5843    Some(c) => match c.front() {
5844      Some(Stored::Charcode(codeval)) => Some(*codeval),
5845      _ => None,
5846    },
5847    None => None,
5848  }
5849}
5850pub fn lookup_mathcode_sym(key_sym: SymStr) -> Option<u16> {
5851  match state!().mathcode.get(&key_sym) {
5852    Some(c) => match c.front() {
5853      Some(Stored::Charcode(codeval)) => Some(*codeval),
5854      _ => None,
5855    },
5856    None => None,
5857  }
5858}
5859/// like `assign_catcode` but targets Mathcode and its table
5860pub fn assign_mathcode<T: Into<u16>>(key: char, value: T, scope: Option<Scope>) {
5861  state_mut!().assign_internal(
5862    TableName::Mathcode,
5863    arena::pin_char(key),
5864    Stored::Charcode(value.into()),
5865    scope,
5866  );
5867}
5868/// like `lookup_catcode` but targets Sfcode and its table
5869pub fn lookup_sfcode(key: char) -> Option<u16> {
5870  match state!().sfcode.get(&arena::pin_char(key)) {
5871    Some(c) => match c.front() {
5872      Some(Stored::Charcode(codeval)) => Some(*codeval),
5873      _ => None,
5874    },
5875    None => None,
5876  }
5877}
5878/// like `assign_catcode` but targets Sfcode and its table
5879pub fn assign_sfcode<T: Into<u16>>(key: char, value: T, scope: Option<Scope>) {
5880  state_mut!().assign_internal(
5881    TableName::Sfcode,
5882    arena::pin_char(key),
5883    Stored::Charcode(value.into()),
5884    scope,
5885  );
5886}
5887/// like `lookup_catcode` but targets Lccode and its table
5888pub fn lookup_lccode(key: char) -> Option<u16> {
5889  match state!().lccode.get(&arena::pin_char(key)) {
5890    Some(c) => match c.front() {
5891      Some(Stored::Charcode(codeval)) => Some(*codeval),
5892      _ => None,
5893    },
5894    None => None,
5895  }
5896}
5897/// like `assign_catcode` but targets Lccode and its table
5898pub fn assign_lccode<T: Into<u16>, C: Into<char>>(key: C, value: T, scope: Option<Scope>) {
5899  let c: char = key.into();
5900  state_mut!().assign_internal(
5901    TableName::Lccode,
5902    arena::pin_char(c),
5903    Stored::Charcode(value.into()),
5904    scope,
5905  );
5906}
5907/// like `lookup_catcode` but targets Uccode and its table
5908pub fn lookup_uccode(key: char) -> Option<u16> {
5909  let mut tmp = [0u8; 4];
5910  let s = arena::pin(key.encode_utf8(&mut tmp));
5911  match state!().uccode.get(&s) {
5912    Some(c) => match c.front() {
5913      Some(Stored::Charcode(codeval)) => Some(*codeval),
5914      _ => None,
5915    },
5916    None => None,
5917  }
5918}
5919/// like `assign_catcode` but targets Uccode and its table
5920pub fn assign_uccode<T: Into<u16>, C: Into<char>>(key: C, value: T, scope: Option<Scope>) {
5921  let c: char = key.into();
5922  let mut tmp = [0u8; 4];
5923  let s = arena::pin(c.encode_utf8(&mut tmp));
5924  state_mut!().assign_internal(TableName::Uccode, s, Stored::Charcode(value.into()), scope);
5925}
5926/// like `lookup_catcode` but targets Delcode and its table
5927pub fn lookup_delcode(key: char) -> Option<u16> {
5928  let mut tmp = [0u8; 4];
5929  let s = arena::pin(key.encode_utf8(&mut tmp));
5930  match state!().delcode.get(&s) {
5931    Some(c) => match c.front() {
5932      Some(Stored::Charcode(codeval)) => Some(*codeval),
5933      _ => None,
5934    },
5935    None => None,
5936  }
5937}
5938/// like `assign_catcode` but targets Delcode and its table
5939pub fn assign_delcode<T: Into<u16>>(key: char, value: T, scope: Option<Scope>) {
5940  let mut tmp = [0u8; 4];
5941  let s = arena::pin(key.encode_utf8(&mut tmp));
5942  state_mut!().assign_internal(TableName::Delcode, s, Stored::Charcode(value.into()), scope);
5943}
5944/// The key under which a token's meaning is stored. **All** `\special_relax`-family
5945/// tokens (`\noexpand`'d forms — the bare `\special_relax` and every
5946/// `\special_relax\x01<shadowed>`) resolve under the bare `\special_relax` name:
5947/// they share its `\relax` meaning, faithful to TeX where a `\noexpand`'d token
5948/// has relax meaning regardless of which token it shadows. The shadowed identity
5949/// is recovered separately via [`Token::noexpand_shadowed`] (delimited matching
5950/// only). Use this anywhere a token's *name* keys a meaning lookup or a
5951/// "same control sequence?" comparison. Cheap on the common path: non-CS tokens
5952/// short-circuit before any string access.
5953#[inline]
5954pub fn meaning_key(token: &Token) -> SymStr {
5955  if token.is_noexpand_family() {
5956    pin!("\\special_relax")
5957  } else {
5958    token.text
5959  }
5960}
5961
5962/// Get the "Meaning" of a token.
5963///
5964/// For active control sequences this may give the definition object (if
5965/// defined) or another token (if `\let`) or `None`. Any other token is returned
5966/// as is — which is what makes a `\let`-style comparison between a control
5967/// sequence and a character token work.
5968///
5969/// Clones the stored meaning; use [`with_meaning`] when inspecting it is enough.
5970pub fn lookup_meaning(token: &Token) -> Option<Stored> {
5971  if token.get_catcode().is_active_or_cs() && token.text != pin!("") {
5972    match state!().meaning.get(&meaning_key(token)) {
5973      Some(entry) => match entry.front() {
5974        None | Some(Stored::None) => None,
5975        Some(other) => Some(other.clone()),
5976      },
5977      None => None,
5978    }
5979  } else {
5980    Some(Stored::Token(*token))
5981  }
5982}
5983
5984/// Whether the current meaning of `token` was made inside a group open now, so it is gone once that group closes —
5985/// whether or not a meaning stands outside it (a global assignment clears the counts of the open groups' frames). A
5986/// binding that queues what it reads to digest later (the frontmatter API) loses such a meaning: aistats's
5987/// `\aistatsaddress` prints in place inside `\twocolumn[…]`, where 1302.5348 defines `\newcommand{\UMDAddress}{…}`
5988/// just before it, and where a paper may renew a macro it defined globally (77o review probe `g_globlocal`: pdflatex
5989/// prints the local meaning).
5990pub fn meaning_is_group_local(token: &Token) -> bool {
5991  if !token.get_catcode().is_active_or_cs() {
5992    return false;
5993  }
5994  let key = meaning_key(token);
5995  let state = state!();
5996  let Some(values) = state.meaning.get(&key) else {
5997    return false;
5998  };
5999  if values
6000    .front()
6001    .is_none_or(|value| matches!(value, Stored::None))
6002  {
6003    return false;
6004  }
6005  // (the groups above the locked base frame, which holds the global binding: a global assignment is counted there,
6006  // and clears the counts above it, state.rs `assign_internal`)
6007  state
6008    .undo
6009    .iter()
6010    .take_while(|frame| !frame.locked)
6011    .any(|frame| frame.meaning.get(&key).is_some_and(|count| *count > 0))
6012}
6013
6014/// Closure-based variant of `lookup_meaning` — avoids the per-call
6015/// `Stored::clone()` when the caller only needs to *inspect* the
6016/// meaning (e.g. extract a CS Token from an Expandable/Primitive
6017/// definition). Stored::clone is ~1% of total instructions on
6018/// siunitx-heavy fixtures (5M+ calls per run, each cloning a full
6019/// Stored enum). This helper borrows the stored value instead.
6020///
6021/// For non-CS/ACTIVE tokens, passes `Some(Stored::Token(*token))` —
6022/// matching lookup_meaning's fallback semantics. Note this requires
6023/// a single stack allocation of Stored::Token (Copy), not a heap
6024/// clone.
6025pub fn with_meaning<R>(token: &Token, f: impl FnOnce(Option<&Stored>) -> R) -> R {
6026  let state = state!();
6027  if token.get_catcode().is_active_or_cs() && token.text != pin!("") {
6028    match state.meaning.get(&meaning_key(token)) {
6029      Some(entry) => match entry.front() {
6030        None | Some(Stored::None) => f(None),
6031        Some(other) => f(Some(other)),
6032      },
6033      None => f(None),
6034    }
6035  } else {
6036    // Non-CS/ACTIVE: the "meaning" is just the token itself. The
6037    // caller gets a borrow of a temporary here, which is safe for
6038    // the duration of the closure.
6039    let s = Stored::Token(*token);
6040    f(Some(&s))
6041  }
6042}
6043
6044/// like `lookup_value` but only recognizes `Stored::VecDequeStored`
6045pub fn lookup_vecdeque(key: &str) -> Option<VecDeque<Stored>> {
6046  match state!().lookup_value(key) {
6047    None | Some(Stored::None) => None,
6048    Some(v) => <Option<&VecDeque<Stored>>>::from(v).cloned(),
6049  }
6050}
6051
6052pub fn with_vecdeque<R, FnR>(key: &str, caller: FnR) -> R
6053where FnR: FnOnce(Option<&VecDeque<Stored>>) -> R {
6054  caller(state!().lookup_vecdeque(key))
6055}
6056
6057/// Whether `token`'s definition is locked while state is not unlocked, so `install_definition` drops a redefinition.
6058pub fn is_definition_locked(token: &Token) -> bool { token.with_cs_name(is_name_locked) }
6059
6060/// Whether `token` means nothing a lock protects: undefined, or `\relax`, what TeX's `\csname` makes of an undefined
6061/// name (tex.web §372) on the way to every `\@namedef`, `\expandafter\def\csname…` and expl3 `\cs_set:cpn`/`…:cc`
6062/// definition ([`restore_cleared_binding`]).
6063fn is_cleared_meaning(token: &Token) -> bool { is_cleared(lookup_meaning(token).as_ref()) }
6064
6065/// [`is_cleared_meaning`] of a meaning.
6066fn is_cleared(meaning: Option<&Stored>) -> bool {
6067  meaning.is_none_or(|meaning| {
6068    matches!(meaning, Stored::None)
6069      || lookup_meaning(&crate::T_CS!("\\relax")).as_ref() == Some(meaning)
6070  })
6071}
6072
6073/// Puts back the binding of a locked name that a file's `\let` cleared ([`let_i`], `"{cs}:locked@cleared"`) when
6074/// the file's new meaning for it is refused, so that the binding's other callers (a raw `\end` running `\csname
6075/// end<env>\endcsname`, alatex.sty:105-109) still meet it rather than an undefined name.
6076fn restore_cleared_binding(token: &Token) {
6077  let cleared_key = token.with_cs_name(|cs| s!("{cs}:locked@cleared"));
6078  if arena::get(&cleared_key).is_none() || !is_cleared_meaning(token) {
6079    return;
6080  }
6081  if let Some(binding) = lookup_value(&cleared_key).filter(|b| !matches!(b, Stored::None)) {
6082    state_mut!().assign_internal(
6083      TableName::Meaning,
6084      token.get_cs_name(),
6085      binding,
6086      Some(Scope::Global),
6087    );
6088    // Once: a later `\relax` the document gives the name is its own, and a later clearing `\let` keeps the binding
6089    // aside again.
6090    assign_value(&cleared_key, Stored::None, Some(Scope::Global));
6091  }
6092}
6093
6094/// Whether the control sequence named `cs` is locked while state is not unlocked: against every definition
6095/// (`"{cs}:locked"`), or against those the class and package files make (`"{cs}:locked@files"`), which leaves the
6096/// document free to define it, as LaTeX and Perl do (the kernel minipage: sect12.rs, OXIDIZED_DESIGN_DIVERGENCES #453).
6097pub fn is_name_locked(cs: &str) -> bool { !state_is_unlocked() && name_carries_lock(cs) }
6098
6099/// Whether the control sequence named `cs` carries a lock ([`is_name_locked`]'s two), read as a value whatever the
6100/// unlocked state: Perl's `\newenvironment`/`\renewenvironment` test `LookupValue('\name:locked')` directly
6101/// (latex_constructs.pool.ltxml:2787-2803), so a class's `\renewenvironment{thebibliography}` that a binding's hook runs
6102/// unlocked (as Perl runs before/after-digest code, Primitive.pm:44/:52) still leaves the locked environment alone
6103/// (wiley2sp's w2sp-pss.clo:444 in `\AtEndOfClass`: 100 of run 336's PushbackLimit papers, 0710.1676, 0809.3379;
6104/// ptptex: 0706.0316).
6105pub fn name_carries_lock(cs: &str) -> bool { lock_holds_against(cs, || true) }
6106
6107/// [`name_carries_lock`] for a known redefinition: `copies_interface` tells whether it takes an optional argument first
6108/// with a default ([`takes_optional_first`]), which a lock against the files that holds only against copies of the
6109/// binding's interface ([`files_lock_holds`]) reads.
6110pub fn lock_holds_against(cs: &str, copies_interface: impl FnOnce() -> bool) -> bool {
6111  // Probe-only: if "{cs}:locked" was never interned it cannot be bound, so
6112  // skip both the intern (which permanently grew the arena by one ":locked"
6113  // twin per defined cs) and the table lookup (2026-08-23 audit R6).
6114  let locked = |suffix: &str| arena::get_suffixed(cs, suffix).is_some_and(lookup_bool_sym);
6115  locked(":locked")
6116    || (crate::definition::origin::current_origin()
6117      != crate::definition::origin::DefinitionOrigin::Document
6118      && locked(":locked@files")
6119      && files_lock_holds(cs, copies_interface))
6120}
6121
6122/// Whether a lock against the class and package files on `cs` holds against this redefinition. Most such locks hold
6123/// against every one. One that holds only against a COPY of the binding's interface (`"{cs}:locked@copies"`: amsthm's
6124/// proof, amsthm_sty.rs) holds against a redefinition taking an optional argument with a default first
6125/// ([`takes_optional_first`]) — amsthm.sty:431's own
6126/// `{proof}[1][\proofname]`, which smfart.cls:1194, ijmart.cls:336 or thuthesis.cls:4052 re-implement over a
6127/// `\trivlist` — and lets one with a head of its own through (fascicules.sty:142 `{\textbf{D\'emonstration:} \par}`,
6128/// NotesTeX.sty:124, a paper's own `\renewenvironment{proof}{…Beweisskizze:…}{…$\blacksquare$}`), whose head text
6129/// and end mark the binding would replace. The environment's end half (`\end<name>` of a qualified `\<name>`)
6130/// follows its begin half: locked while that is still the binding's (not cleared, and LaTeXML's own,
6131/// `DefinitionOrigin::is_latexml_owned`). OXIDIZED_DESIGN_DIVERGENCES #596.
6132pub fn files_lock_holds(cs: &str, copies_interface: impl FnOnce() -> bool) -> bool {
6133  // It keeps the binding's own meaning only while that is in force (or kept aside by a file's clearing `\let`,
6134  // [`let_i`]): once the document, or a definition the lock let through, has replaced or undefined the name, the
6135  // lock has lapsed and later definitions go through as in LaTeX (amsart, the document's `\let\proof\undefined`, then
6136  // a package's copy `\newenvironment{proof}[1][Nachweis]`: `perfect_kernel_batch67ps::
6137  // proof_lock_lapses_once_the_document_undefines_it`; 0705.0545's nccthm.sty:173 `\newcommand*{\proof}[1][]{…}` after
6138  // the same `\let` goes through on the copy rule alone, its default being empty). The protected
6139  // meaning is the one the lock names (`\proof:locked@copies` = `\@proof`), not any binding's: llncs's proof that
6140  // apxproof.sty:46 puts back is not amsthm's (2311.01302).
6141  if let Some(name) = cs.strip_prefix("\\end")
6142    && !name.is_empty()
6143  {
6144    let begin = s!("\\{name}");
6145    if let Some(protected) = copies_lock(&begin) {
6146      return copies_lock_in_force(&begin, &protected) || copies_lock_kept_aside(&begin);
6147    }
6148    // The end half of a begin half locked against everyone (the kernel's `\endabstract`, sect05.rs) is a file's own
6149    // when the file pairs it with a plain `\begin<name>`: nanosymp.sty:25-31's `\beginabstract` list (cond-mat0105361),
6150    // not the end of the kernel's environment that IMjournal.sty:81/83 (1702.00108, 2304.05575) and asect.sty:297's
6151    // `\let` (2401.14559) give.
6152    if arena::get_suffixed(&begin, ":locked").is_some_and(lookup_bool_sym)
6153      && crate::binding::def::dialect::is_defined(&s!("\\begin{name}"))
6154    {
6155      return false;
6156    }
6157  }
6158  if let Some(protected) = copies_lock(cs) {
6159    if !copies_lock_in_force(cs, &protected) && !copies_lock_kept_aside(cs) {
6160      return false;
6161    }
6162    return copies_interface();
6163  }
6164  true
6165}
6166
6167/// The meaning a lock that holds only against copies protects (`"{cs}:locked@copies"`, [`files_lock_holds`]).
6168pub fn copies_lock(cs: &str) -> Option<Token> {
6169  arena::get(s!("{cs}:locked@copies"))?;
6170  match lookup_value(&s!("{cs}:locked@copies")) {
6171    Some(Stored::Token(token)) => Some(token),
6172    _ => None,
6173  }
6174}
6175
6176/// Whether `cs` still has the meaning its copies lock protects.
6177fn copies_lock_in_force(cs: &str, protected: &Token) -> bool { x_equals(&T_CS!(cs), protected) }
6178
6179/// Whether a file's clearing `\let` has put the protected meaning of `cs` aside (`"{cs}:locked@cleared"`, [`let_i`]).
6180fn copies_lock_kept_aside(cs: &str) -> bool {
6181  lookup_value(&s!("{cs}:locked@cleared")).is_some_and(|b| !matches!(b, Stored::None))
6182}
6183
6184/// Whether `definition` is a value the document defines for `binding`, a locked binding that owns its calls
6185/// ([`install_definition`]'s call owner, OXIDIZED_DESIGN #500).
6186fn defines_owned_value(token: &Token, definition: &Stored, binding: &Stored) -> bool {
6187  matches!(definition, Stored::Expandable(defn)
6188    if crate::definition::origin::current_origin() == crate::definition::origin::DefinitionOrigin::Document
6189      && defines_value(token, defn)
6190      && owns_calls(token, binding))
6191}
6192
6193/// Set at the document's class declaration (or, failing one, its `\begin{document}`): from here on the locks hold
6194/// against the document too ([`locks_take_hold`]).
6195const LOCKS_HOLD: &str = "lx@locks@hold";
6196/// The names whose binding a definition before the class declaration displaced, each kept as `"{cs}:lock@aside"`.
6197const LOCKS_ASIDE: &str = "lx@locks@aside";
6198
6199/// Whether a lock waits for the class declaration (DG D-49, OXIDIZED_DESIGN_DIVERGENCES #1195): a LaTeX-route
6200/// document's own definition made before `\documentclass`/`\documentstyle` goes through, since a class's bindings
6201/// arrive with the class (Perl's timeline: the author's meaning until the class pool loads, the binding after); a
6202/// definition after the class stays refused. The Colli/Gilardi/Sprekels header
6203/// `\def\LaTeX{\let\Begin\begin\let\End\end\let\salta\relax}\LaTeX` (1307.1572, 0902.4741, 1103.4585) runs before its
6204/// class, after the preload has loaded the format with its locked `\LaTeX`. Not in a format build (`--init`), which
6205/// reads plain.tex at the document's origin and has no class declaration.
6206pub fn lock_waits_for_class() -> bool {
6207  // (the two thread-local tests first: every `\let` asks, and most come from class and package files)
6208  crate::definition::origin::current_origin()
6209    == crate::definition::origin::DefinitionOrigin::Document
6210    && !plain_tex_document()
6211    && !lookup_bool(LOCKS_HOLD)
6212    && !lookup_bool("INI_TEX_MODE")
6213}
6214
6215/// Whether an assignment at `scope` is global, as [`State::assign_internal`] resolves it (`\globaldefs`, the `\global`
6216/// prefix; tex.web §1214).
6217fn assigns_globally(scope: Option<&Scope>) -> bool {
6218  let globaldefs = match lookup_value("\\globaldefs") {
6219    Some(Stored::Number(n)) => n.0,
6220    Some(Stored::Int(v)) => v,
6221    _ => 0,
6222  };
6223  match scope {
6224    Some(Scope::Named(_) | Scope::InPlace) => false,
6225    _ if globaldefs != 0 => globaldefs > 0,
6226    Some(scope) => matches!(scope, Scope::Global),
6227    None => get_prefix("global"),
6228  }
6229}
6230
6231/// Whether an assignment at `scope` is local to a group open now, which the group's end undoes.
6232fn local_to_a_group(scope: Option<&Scope>) -> bool {
6233  !assigns_globally(scope)
6234    && !matches!(scope, Some(Scope::Named(_) | Scope::InPlace))
6235    && get_frame_depth() > 0
6236}
6237
6238/// The meaning `token` has outside every open group: what a global assignment replaces for good.
6239fn meaning_outside_groups(token: &Token) -> Option<Stored> {
6240  let key = meaning_key(token);
6241  let state = state!();
6242  let in_groups: usize = state
6243    .undo
6244    .iter()
6245    .take_while(|frame| !frame.locked)
6246    .filter_map(|frame| frame.meaning.get(&key))
6247    .sum();
6248  state
6249    .meaning
6250    .get(&key)
6251    .and_then(|values| values.get(in_groups))
6252    .filter(|meaning| !matches!(meaning, Stored::None))
6253    .cloned()
6254}
6255
6256/// [`lock_waits_for_class`] for `definition` of `token` at `scope` (`None` for an environment's end half, which
6257/// follows its begin half), which the lock would refuse. The binding it displaces is read once, for the value test
6258/// and for the aside: the one kept aside already, else the one a clearing `\let` set aside (`"{cs}:locked@cleared"`)
6259/// when the name is cleared, else the meaning (outside every group, for a global definition). A value for a binding
6260/// that owns its calls does not wait: the binding is back in place for OXIDIZED_DESIGN #500's call owner, and the
6261/// value stands past the class (`\let\title\undefined` or `\def\title#1{…}`, then `\def\title{On Widgets}`). A
6262/// definition local to a group keeps nothing aside, since the group's end undoes it (`\begingroup\let\LaTeX\mylogo
6263/// \def\LaTeX{X}\endgroup`). Otherwise the binding is kept aside (once per name) for [`locks_take_hold`] to put back,
6264/// with one `Info:lock`.
6265pub fn keep_binding_aside_before_class(
6266  token: &Token,
6267  definition: Option<&Stored>,
6268  scope: Option<&Scope>,
6269) -> bool {
6270  if !lock_waits_for_class() {
6271    return false;
6272  }
6273  let global = assigns_globally(scope);
6274  let in_group = local_to_a_group(scope);
6275  let aside_key = token.with_cs_name(|cs| s!("{cs}:lock@aside"));
6276  let cleared_key = token.with_cs_name(|cs| s!("{cs}:locked@cleared"));
6277  let aside = lookup_value(&aside_key).filter(|b| !matches!(b, Stored::None));
6278  let shadowed = if global {
6279    meaning_outside_groups(token)
6280  } else {
6281    lookup_meaning(token)
6282  };
6283  let cleared = aside.is_none() && is_cleared(shadowed.as_ref());
6284  let displaced = if aside.is_some() {
6285    aside.clone()
6286  } else if cleared {
6287    lookup_value(&cleared_key).filter(|b| !matches!(b, Stored::None))
6288  } else {
6289    shadowed
6290  };
6291  if let (Some(definition), Some(binding)) = (definition, &displaced)
6292    && defines_owned_value(token, definition, binding)
6293  {
6294    if lookup_meaning(token).as_ref() != Some(binding) {
6295      state_mut!().assign_internal(
6296        TableName::Meaning,
6297        token.get_cs_name(),
6298        binding.clone(),
6299        Some(Scope::Global),
6300      );
6301    }
6302    if aside.is_some() {
6303      assign_value(&aside_key, Stored::None, Some(Scope::Global));
6304    } else if cleared {
6305      assign_value(&cleared_key, Stored::None, Some(Scope::Global));
6306    }
6307    return false;
6308  }
6309  if in_group || aside.is_some() {
6310    return true;
6311  }
6312  let Some(binding) = displaced else {
6313    return true;
6314  };
6315  if cleared {
6316    assign_value(&cleared_key, Stored::None, Some(Scope::Global));
6317  }
6318  // (an earlier value's override, #500, gives way to the binding it kept: the definition replaced the value too,
6319  // `\def\title{On Widgets}\def\title#1{…}`)
6320  let binding = match binding {
6321    Stored::Expandable(ref defn) if defn.yields_calls() => {
6322      lookup_meaning(&locked_binding_token(token)).unwrap_or(binding)
6323    },
6324    binding => binding,
6325  };
6326  assign_value(&aside_key, binding, Some(Scope::Global));
6327  let mut names = lookup_tokens(LOCKS_ASIDE)
6328    .map(Tokens::unlist)
6329    .unwrap_or_default();
6330  // (once per name: a `\let` or a value may have taken an earlier aside back)
6331  if names.contains(token) {
6332    return true;
6333  }
6334  names.push(*token);
6335  assign_value(LOCKS_ASIDE, Tokens::new(names), Some(Scope::Global));
6336  let cs_name = token.with_cs_name(ToString::to_string);
6337  Info!(
6338    "lock",
6339    cs_name,
6340    s!(
6341      "{cs_name} is locked from the class declaration on: the document's definition before it holds until then"
6342    )
6343  );
6344  true
6345}
6346
6347/// The class declaration (`\documentclass`, `\documentstyle`; `\begin{document}` without one): the locks hold from
6348/// here on, and every binding a definition before it displaced ([`keep_binding_aside_before_class`]) is back in place.
6349pub fn locks_take_hold() {
6350  if lookup_bool(LOCKS_HOLD) {
6351    return;
6352  }
6353  assign_value(LOCKS_HOLD, true, Some(Scope::Global));
6354  let Some(names) = lookup_tokens(LOCKS_ASIDE) else {
6355    return;
6356  };
6357  for token in names.unlist_ref() {
6358    let aside_key = token.with_cs_name(|cs| s!("{cs}:lock@aside"));
6359    if let Some(binding) = lookup_value(&aside_key).filter(|b| !matches!(b, Stored::None)) {
6360      state_mut!().assign_internal(
6361        TableName::Meaning,
6362        token.get_cs_name(),
6363        binding,
6364        Some(Scope::Global),
6365      );
6366      assign_value(&aside_key, Stored::None, Some(Scope::Global));
6367    }
6368  }
6369  assign_value(LOCKS_ASIDE, Stored::None, Some(Scope::Global));
6370}
6371
6372/// Whether the document redefines a guess of the fallback class, which wins under OmniBus (BM Q3.12, DG 2026-11-14):
6373/// OmniBus sets `GUESSES_REDEFINABLE` for a class with no binding, so its locks yield to the document's own text — not
6374/// to hook code (apacite's `\AtBeginDocument{\providecommand{\doi}…}` keeps OmniBus's `\doi`).
6375pub fn document_redefines_guess(token: &Token) -> bool {
6376  crate::definition::origin::current_origin()
6377    == crate::definition::origin::DefinitionOrigin::Document
6378    && !state_is_relocked()
6379    && fallback_meaning_origin(token) == Some(crate::definition::origin::DefinitionOrigin::Fallback)
6380    && lookup_bool("GUESSES_REDEFINABLE")
6381}
6382
6383/// [`install_definition`]'s verdict, in the locked state, on a redefinition of `cs`: [`lock_holds_against`] read
6384/// against its own interface, and a redefinition the lock lets through drops what a copies lock kept aside
6385/// ([`drop_copies_lock_aside`]) — probed only where a lock against the files is set, as every copies lock is one (so
6386/// a name without one costs the two probes the lock test always made).
6387fn redefinition_locked(cs: &str, definition: &Stored) -> bool {
6388  let probe = |suffix: &str| arena::get_suffixed(cs, suffix).is_some_and(lookup_bool_sym);
6389  if probe(":locked") {
6390    return !another_interface(cs, definition);
6391  }
6392  if !probe(":locked@files") {
6393    return false;
6394  }
6395  let holds = crate::definition::origin::current_origin()
6396    != crate::definition::origin::DefinitionOrigin::Document
6397    && files_lock_holds(cs, || takes_optional_first(definition));
6398  if !holds {
6399    drop_copies_lock_aside(cs);
6400  }
6401  holds
6402}
6403
6404/// Whether `definition` declares parameters other than the interface the lock on `cs` protects
6405/// (`"{cs}:locked@arity"`), so that it is a command of its own and no copy of the binding's: sltables.sty:193's
6406/// `\def\multicolumn##1{\omit…\stmultispan…}`, its table's one-argument command, against latex.ltx's three, which
6407/// agupp.sty:599, eqnarray.sty:45 and srdp-tables.sty:1218 copy. One declaring none may read any number and stays
6408/// refused. This looks at a definition's parameters only; a `\let` never comes here, a plain `:locked` having never
6409/// refused one (`let_i`, as Perl's `Let`): `\let\multicolumn\mymc` stands.
6410fn another_interface(cs: &str, definition: &Stored) -> bool {
6411  let Some(key) = arena::get(s!("{cs}:locked@arity")) else {
6412    return false;
6413  };
6414  let arity = lookup_int_sym(key);
6415  let count = definition_parameters(definition).map_or(0, |params| params.get_num_args()) as i64;
6416  arity > 0 && count > 0 && count != arity
6417}
6418
6419/// A definition the copies lock on `cs` let through replaces the protected meaning for good: nothing kept aside is
6420/// put back, and the end half follows (`\endproof` after a file's own `\proof`).
6421fn drop_copies_lock_aside(cs: &str) {
6422  if copies_lock(cs).is_some() && copies_lock_kept_aside(cs) {
6423    assign_value(
6424      &s!("{cs}:locked@cleared"),
6425      Stored::None,
6426      Some(Scope::Global),
6427    );
6428  }
6429}
6430
6431/// Record the default of the optional argument a refused redefinition of `token` takes first, as
6432/// `"{cs}:redefined@default"` (`[1][\proofname]`), for the locked binding to title its own use with — only under a
6433/// lock that holds only against copies ([`copies_lock`]), whose binding reads it.
6434pub fn record_redefined_default(token: &Token, default: Tokens) {
6435  if token.with_cs_name(copies_lock).is_none() {
6436    return;
6437  }
6438  let key = arena::pin(token.with_cs_name(|cs| s!("{cs}:redefined@default")));
6439  state_mut!().assign_internal(
6440    TableName::Value,
6441    key,
6442    Stored::Tokens(default),
6443    Some(Scope::Global),
6444  );
6445}
6446
6447/// Whether a definition takes an optional argument first whose default is not empty — `[1][\proofname]`
6448/// (amsthm.sty:431), `[1][\thu@proof@name]` (thuthesis.cls:4052): the shape of a copy of amsthm's proof, whose
6449/// optional argument is the head's text and whose default the name, which a lock that holds only against copies reads
6450/// ([`files_lock_holds`]). An empty default (`[1][]`) adds to a head of the file's own (thmbox.sty:214
6451/// `\proofname\ #1`) or makes a command, not a proof environment (nccthm.sty:173 `\newcommand*{\proof}[1][]`).
6452///
6453/// A robust definition is judged by what it wraps, as [`owns_calls`] judges a robust binding: its own meaning is the
6454/// parameterless `\protect \cs␣` (`robust_wrapper_body`), defined after the inner `\cs␣` that takes the arguments
6455/// (`\DeclareRobustCommand\proof[1][\proofname]{…}`).
6456pub fn takes_optional_first(definition: &Stored) -> bool {
6457  copy_default(definition).is_some_and(|default| !default.is_empty())
6458}
6459
6460/// The parameters `definition` declares.
6461fn definition_parameters(definition: &Stored) -> Option<&crate::parameter::Parameters> {
6462  match definition {
6463    Stored::Expandable(defn) => defn.get_parameters(),
6464    Stored::Constructor(defn) => defn.get_parameters(),
6465    Stored::Primitive(defn) => defn.get_parameters(),
6466    Stored::MathPrimitive(defn) => defn.get_parameters(),
6467    _ => None,
6468  }
6469}
6470
6471/// The default of the optional argument `definition` takes first, if it takes one first ([`takes_optional_first`];
6472/// a robust definition's by its inner `\cs␣`).
6473fn copy_default(definition: &Stored) -> Option<Tokens> {
6474  if let Stored::Expandable(defn) = definition
6475    && let Some(inner) = robust_wrapper_body(defn, &defn.get_cs())
6476  {
6477    return lookup_meaning(&inner).and_then(|inner| copy_default(&inner));
6478  }
6479  definition_parameters(definition)
6480    .and_then(|params| params.get_parameters().first())
6481    .filter(|param| param.optional)
6482    .and_then(|param| param.extra.first().cloned())
6483}
6484
6485/// Whether the locked `binding` of `cs` owns its calls, so that the document's own definition of `cs` takes its other
6486/// uses ([`install_definition`]): its signature reads a braced argument — its first mandatory parameter is one of
6487/// [`BRACED_ARGUMENT_TYPES`], after optional ones only (`\text{}`, `\title[]{}`, `\cite OptionalMatch:* [][]
6488/// Semiverbatim`) — or it is itself such an override (a loop redefining it on every iteration). Derived from the
6489/// binding's own parameter list; a binding that reads its argument downstream (`\section`'s `\@startsection`,
6490/// `\footnote`, `\url`) or none (`\maketitle`) stays absolutely locked. So does the machinery (user ruling
6491/// 2026-10-11: the machinery stays absolutely locked): LaTeX's internal namespace, a name with `@`, which LaTeX's
6492/// convention keeps out of a document's reach until `\makeatletter` (clsguide.tex:187, latex.ltx:1797).
6493/// Its locks keep LaTeXML's engine model against code that re-implements it (`\alloc@{}{}{}{}{}`, called
6494/// `\alloc@0\count\countdef\insc@unt`; `\@startsection`, `\@caption`, `\@lbibitem`).
6495pub fn owns_calls(cs: &Token, binding: &Stored) -> bool {
6496  if cs.with_cs_name(|name| name.contains('@')) {
6497    return false;
6498  }
6499  // A robust binding is judged by what it wraps (user ruling 2026-10-15, D1 extends to robust bindings): its own
6500  // meaning is the parameterless `\protect \cs␣` ([`robust_wrapper_body`]), its signature the inner `\cs␣`'s — the
6501  // kernel `\cite` (sect11.rs) reads `[] Semiverbatim` there. Witnesses math0308041, math0612670, 0705.2148,
6502  // 0802.3843, 1207.1752, 1401.4197 (eplain.tex:346 `\edef\cite{\the\catcode`@}`; SYNC_STATUS 67n).
6503  if let Stored::Expandable(defn) = binding
6504    && !defn.yields_calls()
6505    && let Some(inner) = robust_wrapper_body(defn, cs)
6506  {
6507    return lookup_meaning(&inner).is_some_and(|inner_binding| owns_calls(&inner, &inner_binding));
6508  }
6509  let params = match binding {
6510    Stored::Expandable(defn) if defn.yields_calls() => return true,
6511    Stored::Expandable(defn) => defn.get_parameters(),
6512    Stored::Constructor(defn) => defn.get_parameters(),
6513    Stored::Primitive(defn) => defn.get_parameters(),
6514    Stored::MathPrimitive(defn) => defn.get_parameters(),
6515    _ => None,
6516  };
6517  params
6518    .and_then(|params| params.get_parameters().iter().find(|param| !param.optional))
6519    .is_some_and(|param| arena::with(param.name, |name| BRACED_ARGUMENT_TYPES.contains(&name)))
6520}
6521
6522/// Whether the document's definition `defn` of `cs` is a VALUE — no parameters — rather than a command
6523/// ([`install_definition`]): neither it nor what it wraps reads an argument. A robust wrapper (`\protect \cs␣`,
6524/// [`robust_wrapper_body`]: `\DeclareRobustCommand\mathit[1]{…}`) is judged by its inner `\cs␣`, an ltcmd wrapper
6525/// (`\__cmd_start_optimized: \cs code`, `\__cmd_start:nNNnnn {o m}…`, `\__cmd_start_expandable:nNNNNn {…}…`:
6526/// `\RenewDocumentCommand\mathbf{m}{…}`) by its signature: written out (braced) in the general and expandable wrappers,
6527/// and for the optimized one the argument count ltcmd generates `\cs code` from right after the wrapper
6528/// (`\l__cmd_current_arg_int`, latex.ltx:1963-1983 `\__cmd_declare_cmd_optimized:Nnn`) (2306.08511, 2306.10719,
6529/// 2306.05287). A body naming `cs` itself is no value but a command that redefines itself on use (amsppt.sty's
6530/// `\def\title{\let\savedef@\title \def\title##1\endtitle{…}\title}`, whose inner command the lock refuses: a
6531/// recursion to `Fatal:oom`, math0410032) or recurses.
6532fn defines_value(cs: &Token, defn: &Expandable) -> bool {
6533  let reads_arguments = |params: Option<&crate::parameter::Parameters>| {
6534    params.is_some_and(|params| !params.get_parameters().is_empty())
6535  };
6536  let wrapped_reads_arguments = |inner: &Token| {
6537    lookup_definition(inner)
6538      .ok()
6539      .flatten()
6540      .is_some_and(|inner| reads_arguments(inner.get_parameters()))
6541  };
6542  if reads_arguments(defn.get_parameters()) {
6543    return false;
6544  }
6545  if let Some(inner) = robust_wrapper_body(defn, cs) {
6546    return !wrapped_reads_arguments(&inner);
6547  }
6548  let Some(ExpansionBody::Tokens(body)) = defn.get_expansion() else {
6549    return true;
6550  };
6551  let body = body.unlist_ref();
6552  if body.contains(cs) {
6553    return false;
6554  }
6555  if !body
6556    .first()
6557    .is_some_and(|first| first.with_str(|name| name.starts_with("\\__cmd_start")))
6558  {
6559    return true;
6560  }
6561  // `\__cmd_start:nNNnnn {<signature>}…`: a non-empty signature reads arguments.
6562  let signature_reads = body
6563    .get(1)
6564    .is_some_and(|t| t.get_catcode() == Catcode::BEGIN)
6565    && body.get(2).is_some_and(|t| t.get_catcode() != Catcode::END);
6566  let optimized_count = lookup_definition(&T_CS!("\\l__cmd_current_arg_int"))
6567    .ok()
6568    .flatten()
6569    .and_then(|count| count.value_of(Vec::new()))
6570    .is_some_and(|count| matches!(count, RegisterValue::Number(n) if n.value_of() > 0));
6571  let optimized = body
6572    .first()
6573    .is_some_and(|first| first.with_str(|name| name == "\\__cmd_start_optimized:"));
6574  // Not `\cs code`: ltcmd installs the wrapper before it rebuilds `\cs code`, which is still the previous
6575  // declaration's (`\RenewDocumentCommand\text{m}{…}` then `\RenewDocumentCommand\text{}{V}` is a value).
6576  !signature_reads && !(optimized && optimized_count)
6577}
6578
6579/// The parameter types that read one TeX argument, a braced group (`read_arg`/`read_balanced`, base_parameter_types.rs):
6580/// a binding whose first mandatory parameter is one of them takes a braced argument ([`owns_calls`]).
6581pub const BRACED_ARGUMENT_TYPES: &[&str] = &[
6582  "Plain",
6583  "Position",
6584  "Semiverbatim",
6585  "ExpandedSemiverbatim",
6586  "UnexpandedSemiverbatim",
6587  "Undigested",
6588  "Digested",
6589  "Expanded",
6590  "ExpandedPartially",
6591  "ProtectedExpanded",
6592  "Verbatim",
6593  "HyperVerbatim",
6594  "RequiredKeyVals",
6595  "RequiredKeyValsStar",
6596  "RequiredKeyValsPlus",
6597  "RequiredKeyValsStarPlus",
6598  "DisplayStyle",
6599  "TextStyle",
6600  "ScriptStyle",
6601  "ScriptscriptStyle",
6602  "InFractionStyle",
6603  "InScriptStyle",
6604];
6605
6606/// `\lx@locked@<cs>`: where a document's override of the locked `cs` keeps the binding that handles its calls
6607/// ([`install_definition`]). The binding object itself, so its reversion still names `cs`.
6608pub fn locked_binding_token(cs: &Token) -> Token {
6609  T_CS!(cs.with_cs_name(|name| s!("\\lx@locked@{}", name.trim_start_matches('\\'))))
6610}
6611
6612/// The inner `\cs␣` that the robust command `cs` wraps (its meaning the parameterless `\protect \cs␣`:
6613/// `\DeclareRobustCommand`, a binding's `robust => true`, [`let_i`]'s copy of either), whose definition takes the
6614/// arguments; `None` for any other meaning.
6615pub fn robust_inner(cs: &Token) -> Option<Token> {
6616  match lookup_meaning(cs) {
6617    Some(Stored::Expandable(ref wrapper)) => robust_wrapper_body(wrapper, &wrapper.get_cs()),
6618    _ => None,
6619  }
6620}
6621
6622/// The other tokens that open a call of `binding` (a [`locked_binding_token`]) besides an explicit `{`: the `[` of
6623/// each optional argument its signature opens with, and the token of an `OptionalMatch:*`. A robust binding's
6624/// signature is its inner `\cs␣`'s, as in [`owns_calls`]: `\cite[p.~3]{x}` opens the kernel `\cite`.
6625pub fn call_openers(binding: &Token) -> Vec<Token> {
6626  let inner = robust_inner(binding);
6627  let Ok(Some(defn)) = lookup_definition(inner.as_ref().unwrap_or(binding)) else {
6628    return Vec::new();
6629  };
6630  let mut openers = Vec::new();
6631  if let Some(params) = defn.get_parameters() {
6632    for param in params
6633      .get_parameters()
6634      .iter()
6635      .take_while(|param| param.optional)
6636    {
6637      if arena::with(param.name, |name| name == "OptionalMatch") {
6638        openers.extend(
6639          param
6640            .extra
6641            .first()
6642            .and_then(|extra| extra.unlist_ref().first().copied()),
6643        );
6644      } else if !param.novalue {
6645        openers.push(T_OTHER!("["));
6646      }
6647    }
6648  }
6649  openers
6650}
6651
6652/// Every control sequence carrying a `"{cs}:locked"` lock, sorted: for the census of which own their calls
6653/// ([`owns_calls`]).
6654pub fn locked_control_sequences() -> Vec<String> {
6655  let state = state!();
6656  let mut names: Vec<String> = state
6657    .value
6658    .iter()
6659    .filter(|(_, values)| matches!(values.front(), Some(Stored::Bool(true))))
6660    .filter_map(|(key, _)| {
6661      arena::with(*key, |key| {
6662        key.strip_suffix(":locked").map(ToString::to_string)
6663      })
6664    })
6665    .collect();
6666  names.sort();
6667  names
6668}
6669
6670/// $meaning should be a definition (for defining active control sequences)
6671/// or another token, for \let
6672pub fn assign_meaning<T: Into<Stored>>(token: &Token, meaning: T, scope: Option<Scope>) {
6673  let mut meaning = meaning.into();
6674  // short-circuit guard to avoid e.g. T_MATH let to itself
6675  if let Stored::Token(ref mt) = meaning
6676    && token == mt
6677  {
6678    return;
6679  }
6680  // For \let chains: if the target token has an expandable/primitive definition,
6681  // store that definition directly instead of the Token indirection.
6682  // This ensures `\let \foo \bar` where \bar is expandable makes \foo expandable too.
6683  // Follow at most 50 \let links to avoid cycles.
6684  if let Stored::Token(ref target) = meaning {
6685    let mut current = *target;
6686    for _ in 0..50 {
6687      match lookup_meaning(&current) {
6688        Some(Stored::Token(next)) => {
6689          current = next; // follow chain
6690        },
6691        Some(Stored::None) | None => break, // dead end — keep as Token
6692        Some(defn) => {
6693          // Found a real definition — use it directly
6694          meaning = defn;
6695          break;
6696        },
6697      }
6698    }
6699  }
6700  note_copy_provides_assignment(token);
6701  let csname_sym = token.pin_cs_name();
6702  state_mut!().assign_internal(TableName::Meaning, csname_sym, meaning, scope);
6703}
6704
6705/// Re-point every `\let` copy of `cs`'s current definition — any other meaning bound to that very
6706/// definition (the same `Rc`: taken while it was in force, and not redefined since) — to `new`.
6707/// Each binding is replaced in place, so a copy keeps its scope: a local copy stays local, and one
6708/// a group shadows is `new` again when the group ends. Returns how many bindings were re-pointed;
6709/// `cs` itself is left to the caller, which installs `new` for it. For a definition TeX treats as
6710/// fixed before any code runs but installed late here: the job's `\jobname`
6711/// (`core_interface::install_jobname`).
6712///
6713/// The walk over the meaning table is bounded by the definition's holders. Each holder besides
6714/// `cs`'s own binding and this lookup may be a copy, so a definition nobody else holds needs no
6715/// walk (no preload ran before the job), and the walk stops once as many copies as holders are
6716/// found. A holder outside the table (a snapshot) leaves the bound loose, never short.
6717pub fn rebind_let_copies(cs: &Token, new: &Stored) -> usize {
6718  let Some(Stored::Expandable(old_def)) = lookup_meaning(cs) else {
6719    return 0;
6720  };
6721  let mut unseen = Rc::strong_count(&old_def).saturating_sub(2);
6722  if unseen == 0 {
6723    return 0;
6724  }
6725  let own = meaning_key(cs);
6726  let mut rebound = 0;
6727  let mut state = state_mut!();
6728  // (the keys holding a copy, journaled — and recorded — before they are rewritten in place)
6729  if state.journal.is_some() || !state.meaning_recorders.is_empty() {
6730    let copies: Vec<SymStr> = state
6731      .meaning
6732      .iter()
6733      .filter(|(key, values)| {
6734        **key != own
6735          && values
6736            .iter()
6737            .any(|value| matches!(value, Stored::Expandable(def) if Rc::ptr_eq(def, &old_def)))
6738      })
6739      .map(|(key, _)| *key)
6740      .collect();
6741    for key in copies {
6742      state.journal_touch(TableName::Meaning, key);
6743    }
6744  }
6745  'walk: for (key, values) in state.table_mut(TableName::Meaning).iter_mut() {
6746    if *key == own {
6747      continue;
6748    }
6749    for value in values.iter_mut() {
6750      if matches!(value, Stored::Expandable(def) if Rc::ptr_eq(def, &old_def)) {
6751        *value = new.clone();
6752        rebound += 1;
6753        unseen -= 1;
6754        if unseen == 0 {
6755          break 'walk;
6756        }
6757      }
6758    }
6759  }
6760  rebound
6761}
6762
6763/// Remove a token's meaning entirely — the token becomes undefined, as if it
6764/// had never been defined, so a later use takes the normal undefined-CS error
6765/// path naming the token itself. Bypasses the group-undo journal: intended
6766/// ONLY for format-bootstrap time (no user groups open), where a format layer
6767/// retracts a definition inherited from a lower layer that the emulated
6768/// format must not expose (e.g. plain.tex's `\+` in a LaTeX session — real
6769/// LaTeX is INITEX-based and never defines it).
6770pub fn remove_meaning_global(token: &Token) {
6771  let key = meaning_key(token);
6772  let mut state = state_mut!();
6773  state.journal_touch(TableName::Meaning, key);
6774  state.meaning.remove(&key);
6775}
6776
6777/// Begin recording what assignments change, to undo them all ([`AssignmentJournalGuard::rollback`]) or keep them
6778/// ([`AssignmentJournalGuard::keep`]; also on drop, so a panic leaves no journal open): a transaction over the binding
6779/// tables, of every assignment however scoped and of the in-place edits of the tables (`push_value`,
6780/// `assign_mapping`, `lookup_value_mut`, `checkout_value`/`checkin_value`, named-scope activation,
6781/// `rebind_let_copies`, the graphics path list), of a font's parameter array (`set_font_parameter`, saved as a copy), an input
6782/// stream's mouth (`input_stream_to_change`) and a box register's dimensions (`journal_box_dimension`), each edited in place,
6783/// and of a name's standing in the fallback-guess set
6784/// (`AssignmentJournal::fallback`, FM S2a.2 r9: siamart's `\AND`, 2409.10200). Not of what lives outside the tables: the
6785/// provide-only and stand-in name sets, which change only while a package or class loads. Made for the replay of a refused
6786/// frontmatter setter (sect05.rs `replay_class_setter`), which a setter that errs half-way must not leave half-done
6787/// (jsty3-author.sty:542's expl3 author list, which its printer then looped over: 2607.24171). `None`, recording
6788/// nothing, while one is already open (journals do not nest); a journal its guard could not close (the state was
6789/// borrowed when the guard dropped) is discarded here.
6790pub fn begin_assignment_journal() -> Option<AssignmentJournalGuard> {
6791  let mut state = state_mut!();
6792  if state.journal.is_some() && JOURNAL_GUARD_LIVE.get() {
6793    return None;
6794  }
6795  let frames = state.undo.iter().rev().map(|frame| frame.id).collect();
6796  state.journal = Some(AssignmentJournal {
6797    meaning_log: None,
6798    frames,
6799    saved: rustc_hash::FxHashMap::default(),
6800    fallback: rustc_hash::FxHashMap::default(),
6801    box_dimensions: Vec::new(),
6802    watch: WATCH.get(),
6803  });
6804  JOURNAL_GUARD_LIVE.set(true);
6805  WRITES_WATCHED.set(true);
6806  Some(AssignmentJournalGuard { open: true })
6807}
6808
6809/// Begin recording which meanings are assigned, each with its value before its first assignment since
6810/// ([`end_meaning_recorder`]): what [`AssignmentJournalGuard::assigned`] reads of [`TableName::Meaning`], without the
6811/// journal — recorders nest, and a journal (a speculative run's, a replay's) may open and close inside one. Made for a
6812/// displaced setter's call (frontmatter_stores.rs `\lx@displaced@begin`), whose own code may run a speculative label
6813/// read (queue_digest.rs `speculative_label_ink`: utarticle.cls:125's `\address` prints its `\@makeadmark{\@tempb}`,
6814/// 1209.6020). Kept in the state, so a document that stops inside a call leaves none to the next. Returns its depth:
6815/// how many were open before it, which [`end_meaning_recorder_at`] closes it by.
6816pub fn begin_meaning_recorder() -> usize {
6817  let recorders = &mut state_mut!().meaning_recorders;
6818  recorders.push(rustc_hash::FxHashMap::default());
6819  recorders.len() - 1
6820}
6821
6822/// Close the innermost meaning recorder ([`begin_meaning_recorder`]): the meanings assigned since it began, each with
6823/// its value then (`None`: unbound). Empty when none is open.
6824pub fn end_meaning_recorder() -> Vec<(SymStr, Option<Stored>)> {
6825  state_mut!()
6826    .meaning_recorders
6827    .pop()
6828    .map(|recorded| recorded.into_iter().collect())
6829    .unwrap_or_default()
6830}
6831
6832/// Close the meaning recorder [`begin_meaning_recorder`] opened at `depth`, and every one opened inside it and left open
6833/// (an `Err` out of a displaced call between its begin and its end): the meanings it recorded, as
6834/// [`end_meaning_recorder`]; empty when it is no longer open.
6835pub fn end_meaning_recorder_at(depth: usize) -> Vec<(SymStr, Option<Stored>)> {
6836  let recorders = &mut state_mut!().meaning_recorders;
6837  if recorders.len() <= depth {
6838    return Vec::new();
6839  }
6840  recorders.truncate(depth + 1);
6841  recorders
6842    .pop()
6843    .map(|recorded| recorded.into_iter().collect())
6844    .unwrap_or_default()
6845}
6846
6847/// A meaning assigned in the meaning log ([`begin_meaning_log`]).
6848#[derive(Debug, Clone, Copy)]
6849pub struct MeaningAssigned {
6850  /// the meaning's key
6851  pub key:    SymStr,
6852  /// whether globally
6853  pub global: bool,
6854  /// the token being invoked
6855  pub by:     Token,
6856}
6857
6858/// Begin logging the meanings assigned on the open journal by a token with a field provenance (`Token::prov`), in order:
6859/// what a rehearsal reads a definition in its field by (the engine's `field_notes`), since a
6860/// definition leaves no box. What a token of no provenance assigns is no invocation of the field's, wherever it stands:
6861/// `\begin{minipage}`'s hooks, the `\size@update` that `\selectfont` puts back. One rehearsal at a time, journals not nesting
6862/// ([`begin_assignment_journal`]); the log goes with the journal.
6863pub fn begin_meaning_log() {
6864  if let Some(journal) = state_mut!().journal.as_mut() {
6865    journal.meaning_log = Some(Vec::new());
6866  }
6867}
6868
6869/// Whether the meaning log ([`begin_meaning_log`]) holds nothing since it was last read.
6870pub fn meaning_log_is_empty() -> bool {
6871  state!()
6872    .journal
6873    .as_ref()
6874    .and_then(|journal| journal.meaning_log.as_ref())
6875    .is_none_or(Vec::is_empty)
6876}
6877
6878/// Exchange what the meaning log ([`begin_meaning_log`]) holds since it was last read with `buffer`, an empty one: a field
6879/// token's read of the log, so it allocates nothing.
6880pub fn swap_meaning_log(buffer: &mut Vec<MeaningAssigned>) {
6881  if let Some(log) = state_mut!()
6882    .journal
6883    .as_mut()
6884    .and_then(|journal| journal.meaning_log.as_mut())
6885  {
6886    std::mem::swap(log, buffer);
6887  }
6888}
6889
6890thread_local! {
6891  /// Whether an [`AssignmentJournalGuard`] is live: one that dropped while the state was borrowed leaves its journal
6892  /// for the next [`begin_assignment_journal`] to discard.
6893  static JOURNAL_GUARD_LIVE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
6894}
6895
6896thread_local! {
6897  /// The watch held on the state ([`watch_state`]): its number, 0 when none is or the state changed since.
6898  static WATCH: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
6899}
6900
6901thread_local! {
6902  /// Whether a write is noted: a journal's guard is live or a watch is held. The one test a write pays.
6903  static WRITES_WATCHED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
6904}
6905
6906/// Set the watch held ([`WATCH`]), 0 to end it.
6907fn set_watch(watch: u64) {
6908  WATCH.set(watch);
6909  WRITES_WATCHED.set(watch != 0 || JOURNAL_GUARD_LIVE.get());
6910}
6911
6912/// The journal's guard is gone ([`JOURNAL_GUARD_LIVE`]).
6913fn end_journal_guard() {
6914  JOURNAL_GUARD_LIVE.set(false);
6915  WRITES_WATCHED.set(WATCH.get() != 0);
6916}
6917
6918thread_local! {
6919  /// The last watch begun: numbers only grow, so none is begun twice.
6920  static LAST_WATCH: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
6921}
6922
6923/// A write to `key` of `table_name`, in place or not ([`State::journal_touch`]): it ends the watch held, but a
6924/// LaTeXML-internal value's (a key `lx…` in the value table: a frontmatter flag, which no TeX code reads).
6925#[inline]
6926fn note_state_change(table_name: TableName, key: SymStr) {
6927  if WATCH.get() != 0
6928    && (table_name != TableName::Value || arena::first_bytes::<2>(key) != Some(*b"lx"))
6929  {
6930    set_watch(0);
6931  }
6932}
6933
6934/// Begin a watch on the state, ending the one held (the title-page reading's key, `latex_constructs::title_page_reading`).
6935/// Every write ends it (an assignment, a write in place, a box's `\wd`, a group's end restoring a value) but an `lx…`
6936/// value's; a rollback ([`AssignmentJournalGuard::rollback`]) puts back the watch it began with, with the state.
6937pub fn watch_state() -> u64 {
6938  let watch = LAST_WATCH.get() + 1;
6939  LAST_WATCH.set(watch);
6940  set_watch(watch);
6941  watch
6942}
6943
6944/// Is the state unchanged since `watch` began ([`watch_state`])?
6945pub fn state_unchanged_since(watch: u64) -> bool { watch != 0 && WATCH.get() == watch }
6946
6947/// The open assignment journal ([`begin_assignment_journal`]).
6948#[must_use = "an assignment journal is kept or rolled back"]
6949pub struct AssignmentJournalGuard {
6950  open: bool,
6951}
6952
6953impl AssignmentJournalGuard {
6954  /// The keys of `table` the journal saw assigned since it began, each with its value then (the front of its stack;
6955  /// `None`: unbound).
6956  pub fn assigned(&self, table: TableName) -> Vec<(SymStr, Option<Stored>)> {
6957    let state = state!();
6958    let Some(journal) = state.journal.as_ref() else {
6959      return Vec::new();
6960    };
6961    journal
6962      .saved
6963      .iter()
6964      .filter(|((t, _), _)| *t == table)
6965      .map(|((_, key), (values, _))| (*key, values.as_ref().and_then(|v| v.front().cloned())))
6966      .collect()
6967  }
6968
6969  /// Close the journal, keeping every assignment made since it began.
6970  pub fn keep(mut self) {
6971    self.open = false;
6972    end_journal_guard();
6973    state_mut!().journal = None;
6974  }
6975
6976  /// Close the journal, undoing every assignment made since it began: each key's values and its counts in the frames
6977  /// open then are put back as they were. Only when exactly those frames are open again — the same frames, by id,
6978  /// each one opened since closed and none of them closed: false, undoing nothing (the assignments stay), otherwise.
6979  pub fn rollback(mut self) -> bool {
6980    self.open = false;
6981    end_journal_guard();
6982    let mut state = state_mut!();
6983    let Some(journal) = state.journal.take() else {
6984      return false;
6985    };
6986    if !state
6987      .undo
6988      .iter()
6989      .rev()
6990      .map(|frame| frame.id)
6991      .eq(journal.frames.iter().copied())
6992    {
6993      return false;
6994    }
6995    for ((table_name, key), (values, counts)) in journal.saved {
6996      match values {
6997        Some(values) => {
6998          state.table_mut(table_name).insert(key, values);
6999        },
7000        None => {
7001          state.table_mut(table_name).remove(&key);
7002        },
7003      }
7004      for frame in state.undo.iter_mut() {
7005        let id = frame.id;
7006        let frame_table = frame.table_mut(table_name);
7007        frame_table.remove(&key);
7008        if let Some((_, n)) = counts.iter().find(|(at, _)| *at == id) {
7009          frame_table.insert(key, *n);
7010        }
7011      }
7012    }
7013    for (key, standing) in journal.fallback {
7014      match standing {
7015        Some(origin) => {
7016          state.fallback_meanings.insert(key, origin);
7017        },
7018        None => {
7019          state.fallback_meanings.remove(&key);
7020        },
7021      }
7022    }
7023    for (a_box, property, value) in journal.box_dimensions.into_iter().rev() {
7024      match value {
7025        Some(value) => {
7026          a_box.try_set_property(property, value);
7027        },
7028        None => {
7029          a_box.try_remove_property(property);
7030        },
7031      }
7032    }
7033    set_watch(journal.watch);
7034    true
7035  }
7036}
7037
7038impl Drop for AssignmentJournalGuard {
7039  fn drop(&mut self) {
7040    if self.open {
7041      end_journal_guard();
7042      if let Ok(mut state) = state_root().try_borrow_mut() {
7043        state.journal = None;
7044      }
7045    }
7046  }
7047}
7048
7049/// Every control sequence whose current meaning satisfies `keep`, with that meaning: a whole-table scan, for a
7050/// one-off survey of what a loaded file defined (K11's reader scan, `frontmatter_stores.rs`), never a hot path.
7051pub fn current_meanings_where(keep: impl Fn(&Stored) -> bool) -> Vec<(SymStr, Stored)> {
7052  state!()
7053    .meaning
7054    .iter()
7055    .filter_map(|(key, entry)| match entry.front() {
7056      Some(stored) if !matches!(stored, Stored::None) && keep(stored) => {
7057        Some((*key, stored.clone()))
7058      },
7059      _ => None,
7060    })
7061    .collect()
7062}
7063
7064/// Whether the meaning key `key` (a [`meaning_key`]) is bound now.
7065pub fn has_meaning_key(key: SymStr) -> bool { !matches!(meaning_by_key(key), Stored::None) }
7066
7067// keep this in sync with `lookup_meaning`, it is copied over for optimization purposes
7068pub fn has_meaning(token: &Token) -> bool {
7069  if token.get_catcode().is_active_or_cs() && token.text != pin!("") {
7070    match state!().meaning.get(&meaning_key(token)) {
7071      Some(entry) => match entry.front() {
7072        None | Some(Stored::None) => false,
7073        Some(_) => true,
7074      },
7075      None => false,
7076    }
7077  } else {
7078    true
7079  }
7080}
7081
7082/// used for expansion & various queries
7083/// Since we're not doing digestion here, we don't need to handle mathactive,
7084/// nor cs let to executable tokens
7085/// This returns a definition object, or undef
7086pub fn lookup_definition(key: &Token) -> Result<Option<Rc<dyn Definition>>> {
7087  Ok(
7088    if let Some(defs) = state!().lookup_definition_internal(key) {
7089      match defs.front() {
7090        Some(Stored::Conditional(entry)) => Some(entry.clone()),
7091        Some(Stored::Constructor(entry)) => Some(entry.clone()),
7092        Some(Stored::Expandable(entry)) => Some(entry.clone()),
7093        Some(Stored::MathPrimitive(entry)) => Some(entry.clone()),
7094        Some(Stored::Primitive(entry)) => Some(entry.clone()),
7095        Some(Stored::Register(entry)) => Some(entry.clone()),
7096        Some(Stored::None) | Some(Stored::Token(_)) | None => None,
7097        Some(v) => {
7098          let message = s!("in lookup_definition for {:?}. Value was: {:?}", key, v);
7099          Error!("unexpected", "value", message);
7100          None
7101        },
7102      }
7103    } else {
7104      None
7105    },
7106  )
7107}
7108
7109/// Returns a definition as `Stored` so that one can call `.read_arguments`
7110///
7111/// This can't be specialized during compile-time over a trait object?
7112/// Instead we'll dispatch via `Stored` at runtime, to allow generic calls.
7113pub fn lookup_definition_stored(key: &Token) -> Result<Option<Stored>> {
7114  Ok(match state!().lookup_definition_internal(key) {
7115    Some(defs) => match defs.front() {
7116      // Still, good time to handle the Token case and catch weird storage errors
7117      Some(Stored::Conditional(entry)) => Some(Stored::Conditional(Rc::clone(entry))),
7118      Some(Stored::Constructor(entry)) => Some(Stored::Constructor(Rc::clone(entry))),
7119      Some(Stored::Expandable(entry)) => Some(Stored::Expandable(Rc::clone(entry))),
7120      Some(Stored::MathPrimitive(entry)) => Some(Stored::MathPrimitive(Rc::clone(entry))),
7121      Some(Stored::Primitive(entry)) => Some(Stored::Primitive(Rc::clone(entry))),
7122      Some(Stored::Register(entry)) => Some(Stored::Register(Rc::clone(entry))),
7123      Some(Stored::Token(entry)) => Some(Stored::Expandable(Rc::new(Expandable {
7124        cs: key.with_str(|k| T_CS!(k)),
7125        paramlist: None,
7126        expansion: (*entry).into(),
7127        ..Expandable::default()
7128      }))),
7129      // A control sequence `\let` to an undefined one (`let_i`) has no definition, as in
7130      // `lookup_definition`.
7131      Some(Stored::None) => None,
7132      Some(v) => {
7133        let message = s!("in lookup_definition for {:?}. Value was: {:?}", key, v);
7134        Error!("unexpected", "value", message);
7135        None
7136      },
7137      None => None,
7138    },
7139    _ => None,
7140  })
7141}
7142
7143/// A specialized version of `lookup_definition` for registers, since we can't adequately perform
7144/// multi-dispatch when we have a "Self: Sized" for the Definition trait object.
7145pub fn lookup_register_definition(key: &Token) -> Option<Rc<Register>> {
7146  match state!().lookup_definition_internal(key) {
7147    Some(defs) => match defs.front() {
7148      Some(Stored::Register(entry)) => Some(Rc::clone(entry)),
7149      _ => None,
7150    },
7151    _ => None,
7152  }
7153}
7154/// Recognizes mathactive tokens in math mode and also looks for
7155/// cs that have been let to other `executable' tokens.
7156/// Returns a definition object, or a "self inserting" token.
7157/// Used for digestion.
7158pub fn lookup_digestable_definition(token: &Token) -> Option<Stored> {
7159  let cc = token.get_catcode();
7160  let t_sym = token.get_sym();
7161  let is_active_or_cs = cc.is_active_or_cs();
7162  let lookup_sym = if is_active_or_cs
7163    || ((cc == Catcode::LETTER || (cc == Catcode::OTHER))
7164      && lookup_bool_sym(crate::pin!("IN_MATH"))
7165      && (lookup_mathcode_sym(t_sym).unwrap_or(0) == 0x8000)
7166      && !crate::stomach::digesting_delimiter())
7167  {
7168    // `\special_relax`-family tokens digest under the bare `\special_relax` no-op.
7169    meaning_key(token)
7170  } else {
7171    // Use cached SymStr from `Catcode::name_sym` instead of re-interning
7172    // `cc.name()` (a &'static str) on every non-active-or-cs token —
7173    // saves a hashmap probe per token on the digest hot path.
7174    cc.name_sym()
7175  };
7176  // Debug!("Looking up digestable {:?}", lookupname);
7177  let state = state!();
7178  let entry_opt = state.meaning.get(&lookup_sym);
7179  if lookup_sym != pin!("") && entry_opt.is_some() && !entry_opt.as_ref().unwrap().is_empty() {
7180    // Debug!("Found definition for: {:?}", lookupname);
7181    if let Some(entry) = entry_opt
7182      && let Some(front) = entry.front()
7183    {
7184      if let Stored::Token(t) = front {
7185        if let Some(lookup_name) = t.get_executable_primitive_name() {
7186          let lookup_sym = arena::pin(lookup_name);
7187          if let Some(retry_entry) = state!().meaning.get(&lookup_sym) {
7188            // special case,
7189            // If a cs has been let to an executable token, lookup ITS defn.
7190            return retry_entry.front().cloned();
7191          }
7192        }
7193        // Also follow \let chains for CS tokens: if \foo is \let to \bar,
7194        // resolve \bar's definition. This handles expl3 aliases like
7195        // \tex_long:D → \long, \tex_gdef:D → \gdef.
7196        if t.get_catcode() == Catcode::CS
7197          && let Some(target_entry) = state.meaning.get(&t.text)
7198          && let Some(target_front) = target_entry.front()
7199          && !matches!(target_front, Stored::Token(_) | Stored::None)
7200        {
7201          return Some(target_front.clone());
7202        }
7203      }
7204      // Perl State.pm:474 lookupDigestableDefinition: the guard
7205      // `($defn = $$entry[0])` is FALSE when the entry's value is undef, so
7206      // execution falls through to `return $token` (self-inserting) for a
7207      // LETTER/OTHER token and to `return undef` for an active/CS one. A
7208      // math-active LETTER/OTHER character whose active meaning was `\let`
7209      // to an undefined CS hits exactly this case — e.g. braket-style
7210      // `\Pr{A|B}`: the macro body does `\mathcode`\|=32768 \let|\SetVert`
7211      // with `\SetVert` itself undefined (neither our nor Perl's braket
7212      // binding defines it), leaving `|`'s meaning an explicit
7213      // `Stored::None`. Returning `Some(Stored::None)` here routed the `|`
7214      // to generateErrorStub ("The token T_OTHER[|] is not defined"); Perl
7215      // instead self-inserts the literal char. Mirror Perl: a None-valued
7216      // entry for a non-active/CS (math-active) char self-inserts; active/CS
7217      // tokens still fall to the `None` return below. Witness 1602.01342.
7218      if matches!(front, Stored::None) && !is_active_or_cs {
7219        return Some(token.into());
7220      }
7221      // if a regular definition, just return.
7222      return Some(front.clone());
7223    }
7224  } else if is_active_or_cs {
7225    return None;
7226  }
7227  Some(token.into())
7228}
7229
7230// NOTE: Common usage patterns seem to be to lookup
7231//   expandable definitions
7232//   register values
7233//   conditionals
7234//   digestibles
7235// or just variants on testing defined-ness
7236// May be will introduce more clarity (possibly efficiency)
7237// to collect those more uniformly and implement here, or in Package
7238
7239//======================================================================
7240/// Starts a new level of grouping.
7241/// Note that this is lower level than C<\bgroup>;
7242/// Diagnostic helper: dump the keys in undo`0`'s value table.
7243/// For temporary instrumentation only — no production callers should rely on this.
7244/// The newest `n` values bound to `key` in the Value table, newest first —
7245/// one entry per frame that bound it (`LXML_TRACE_FRAMES` group-stack dump).
7246pub fn value_history(key: &str, n: usize) -> Vec<String> {
7247  let key_sym = arena::pin(key);
7248  state!()
7249    .value
7250    .get(&key_sym)
7251    .map(|d| d.iter().take(n).map(|v| v.to_string()).collect())
7252    .unwrap_or_default()
7253}
7254
7255pub fn dump_top_frame_keys() -> String {
7256  let state = state!();
7257  let f0 = state.undo.front().expect("undo is non-empty");
7258  let mut entries: Vec<String> = Vec::new();
7259  for (k, v) in f0.table(TableName::Value).iter() {
7260    let val = state
7261      .value
7262      .get(k)
7263      .and_then(|vec| vec.front())
7264      .map(|s| format!("{s:?}"))
7265      .unwrap_or_else(|| "<none>".into());
7266    let ks: String = arena::with(*k, |s| s.to_string());
7267    entries.push(format!("{ks}=[{v}, {val}]"));
7268  }
7269  entries.sort();
7270  entries.join(", ")
7271}
7272
7273pub fn push_frame() {
7274  // Easy: just push a new undo frame.
7275  if *crate::stomach::TRACE_FRAMES {
7276    eprintln!(
7277      "[state] push_frame depth {} -> {}",
7278      get_frame_depth(),
7279      get_frame_depth() + 1
7280    );
7281  }
7282  state_mut!().undo.push_front(UndoFrame::default());
7283}
7284
7285/// Snapshot of the keys currently bound at the topmost (calling) undo frame
7286/// for the Meaning table. Used by Perl-style autoload triggers that need to
7287/// promote everything a package's load just installed at this scope to
7288/// GLOBAL — without that promotion, sibling autoload triggers fired AFTER
7289/// a group pop would re-fire on a now-undefined sibling CS (the canonical
7290/// case is `\begin{subequations}` triggering amsmath autoload at depth=N,
7291/// then a later `\begin{align}` at depth=0 finding `\align` undefined
7292/// because amsmath's depth=N install was popped on `\end{subequations}`).
7293pub fn snapshot_top_frame_meaning_keys() -> Vec<SymStr> {
7294  state!()
7295    .undo
7296    .front()
7297    .map(|f| f.meaning.keys().copied().collect())
7298    .unwrap_or_default()
7299}
7300
7301/// The rest of each defined control sequence's name that begins with `prefix`: the `<type>` of latex.ltx's
7302/// `\ftype@<type>`, one per float type. In no particular order.
7303pub fn defined_names_after_prefix(prefix: &str) -> Vec<String> {
7304  state!()
7305    .meaning
7306    .iter()
7307    .filter(|(_, values)| {
7308      values
7309        .front()
7310        .is_some_and(|value| !matches!(value, Stored::None))
7311    })
7312    .filter_map(|(key, _)| arena::with(*key, |name| name.strip_prefix(prefix).map(str::to_string)))
7313    .collect()
7314}
7315
7316/// The meanings first made in the innermost group: the control sequences bound at the topmost frame and nowhere
7317/// outside it (every binding they have is the frame's), with their current binding (a key bound there to nothing is
7318/// left out).
7319pub fn top_frame_new_meanings() -> Vec<(SymStr, Stored)> {
7320  let state = state!();
7321  let Some(frame) = state.undo.front() else {
7322    return Vec::new();
7323  };
7324  frame
7325    .meaning
7326    .iter()
7327    .filter_map(|(key, count)| {
7328      let values = state.meaning.get(key)?;
7329      if values.len() > *count {
7330        return None;
7331      }
7332      values
7333        .front()
7334        .filter(|value| !matches!(value, Stored::None))
7335        .map(|value| (*key, value.clone()))
7336    })
7337    .collect()
7338}
7339
7340/// The meanings the topmost `n` frames bind — new ones and changes to what an outer frame defined — that are plain
7341/// groups (`{…}`, `\begingroup`): a frame an environment or a mode opened (it binds `current_environment` or `MODE`)
7342/// is skipped, its bindings being that construct's own machinery. Each key with the binding of the innermost such frame
7343/// that binds it (a key bound there to nothing is left out). For a replayed environment begin code (sect05.rs
7344/// `replay_class_setter`).
7345pub fn top_group_frames_meanings(n: usize) -> Vec<(SymStr, Stored)> {
7346  let state = state!();
7347  let environment = crate::pin!("current_environment");
7348  let mode = crate::pin!("MODE");
7349  // how many bindings of a key the frames above the current one hold: the current frame's is at that position
7350  let mut above: HashMap<SymStr, usize> = HashMap::default();
7351  let mut chosen: Vec<(SymStr, Stored)> = Vec::new();
7352  let mut seen: HashSet<SymStr> = HashSet::default();
7353  for frame in state.undo.iter().take(n) {
7354    let plain_group = !frame.value.contains_key(&environment) && !frame.value.contains_key(&mode);
7355    for (key, count) in frame.meaning.iter() {
7356      let offset = above.entry(*key).or_insert(0);
7357      if plain_group
7358        && *count > 0
7359        && seen.insert(*key)
7360        && let Some(value) = state
7361          .meaning
7362          .get(key)
7363          .and_then(|values| values.get(*offset))
7364        && !matches!(value, Stored::None)
7365      {
7366        chosen.push((*key, value.clone()));
7367      }
7368      *offset += *count;
7369    }
7370  }
7371  chosen
7372}
7373
7374/// The keys bound at the topmost frame for the Meaning and Value tables, taken before an autoloaded package loads,
7375/// and the meaning recorder ([`begin_meaning_recorder`]) open over the load; see [`hoist_top_frame_package_load`],
7376/// which closes it (as dropping it does: a load that fails).
7377pub struct TopFrameKeys {
7378  meaning:  Vec<SymStr>,
7379  value:    Vec<SymStr>,
7380  recorder: Option<usize>,
7381}
7382pub fn snapshot_top_frame_keys() -> TopFrameKeys {
7383  let (meaning, value, locked) = {
7384    let state = state!();
7385    let frame = state.undo.front();
7386    (
7387      frame
7388        .map(|f| f.meaning.keys().copied().collect())
7389        .unwrap_or_default(),
7390      frame
7391        .map(|f| f.value.keys().copied().collect())
7392        .unwrap_or_default(),
7393      frame.is_none_or(|f| f.locked),
7394    )
7395  };
7396  // (a locked frame is where a global assignment lands: nothing there to hoist, and the lazy LaTeX.pool load at the
7397  // base frame records no 23,000 meanings)
7398  TopFrameKeys {
7399    meaning,
7400    value,
7401    recorder: (!locked).then(begin_meaning_recorder),
7402  }
7403}
7404impl Drop for TopFrameKeys {
7405  fn drop(&mut self) {
7406    if let Some(depth) = self.recorder.take() {
7407      end_meaning_recorder_at(depth);
7408    }
7409  }
7410}
7411
7412/// Hoist what an autoloaded package installed at the topmost frame since `pre` was taken — its meanings and its
7413/// values — to GLOBAL scope. The trigger (`def_autoload`, OmniBus's `\lx@late@usepackage`, the LaTeX-pool autoload) is
7414/// cleared and the package's loaded-flag set globally, so what the package defines must live as long. Fired inside a
7415/// group, natbib's locked `\citep` was otherwise popped while its lock survived, every later `\citep` undefined (arXiv
7416/// 2605.08349, 2605.10423, 2605.14513, 2605.04028: `Fatal:TooManyErrors`), and its citation style reverted after the
7417/// group. A meaning the group had bound before the load and the load re-bound there goes too (the frame's count stays
7418/// 1, a local assignment replacing its binding: State.pm:169-174): natbib's `\let\bibitem\lx@nat@bibitem`,
7419/// loaded by OmniBus's hook in a `thebibliography` that had armed `\bibitem`, was popped at the list's end, and the
7420/// next list's `\bibitem` ran the hook forever (arXiv 2006.04387, KNOWN_PERL_ERRORS #1367). A value the group had
7421/// bound stays the group's: those are its own machinery (the mode, the font, the list's registers).
7422pub fn hoist_top_frame_package_load(mut pre: TopFrameKeys) {
7423  let recorded = pre
7424    .recorder
7425    .take()
7426    .map(end_meaning_recorder_at)
7427    .unwrap_or_default();
7428  let rebound: Vec<SymStr> = {
7429    let state = state!();
7430    let before: rustc_hash::FxHashSet<SymStr> = pre.meaning.iter().copied().collect();
7431    let frame = state.undo.front();
7432    recorded
7433      .into_iter()
7434      .filter(|(key, then)| {
7435        before.contains(key)
7436          && frame.is_some_and(|f| f.meaning.get(key).is_some_and(|count| *count > 0))
7437          && !matches!(
7438            (state.meaning.get(key).and_then(|stack| stack.front()), then),
7439            (Some(now), Some(then)) if same_meaning(now, then)
7440          )
7441      })
7442      .map(|(key, _)| key)
7443      .collect()
7444  };
7445  hoist_top_frame_delta(TableName::Meaning, &pre.meaning, &rebound, false);
7446  hoist_top_frame_delta(TableName::Value, &pre.value, &[], false);
7447}
7448
7449/// Hoist the conditionals installed at the topmost frame since `pre_snapshot`
7450/// was taken to GLOBAL scope: for a package loaded inside a LaTeXML subfile
7451/// bracket (`require_package`, OXIDIZED_DESIGN #65). Idempotent: keys already
7452/// in `pre_snapshot` are skipped, re-bound or not, so a conditional the child's
7453/// own preamble set stays the child's.
7454pub fn hoist_top_frame_conditional_delta(pre_snapshot: &[SymStr]) {
7455  hoist_top_frame_delta(TableName::Meaning, pre_snapshot, &[], true);
7456}
7457
7458/// Hoist to GLOBAL scope the keys of `table` the topmost frame bound since `pre_snapshot` (its keys then) was taken,
7459/// and the keys in `rebound`.
7460fn hoist_top_frame_delta(
7461  table: TableName,
7462  pre_snapshot: &[SymStr],
7463  rebound: &[SymStr],
7464  conditionals_only: bool,
7465) {
7466  let pre: rustc_hash::FxHashSet<SymStr> = pre_snapshot.iter().copied().collect();
7467  let new_keys: Vec<SymStr> = {
7468    let state = state!();
7469    state
7470      .undo
7471      .front()
7472      .map(|f| {
7473        f.table(table)
7474          .keys()
7475          .copied()
7476          .filter(|k| !pre.contains(k))
7477          .chain(rebound.iter().copied())
7478          .collect()
7479      })
7480      .unwrap_or_default()
7481  };
7482  for key in new_keys {
7483    let current = {
7484      let state = state!();
7485      state
7486        .table(table)
7487        .get(&key)
7488        .and_then(|stack| stack.front().cloned())
7489    };
7490    if let Some(value) = current {
7491      // CONDITIONALS ONLY, for a subfile bracket. The failure this exists for is a definition destroyed
7492      // while a GLOBAL document hook still reads it, and every witness is a
7493      // `\newif` conditional (`\ifpgf@external@grabshipout`, OXIDIZED_DESIGN
7494      // #65). Hoisting a package's ordinary macros too is what makes a second
7495      // sibling subfile render the FIRST one's content: promoting pkgA's
7496      // `\newcommand` to global makes pkgB's same-named `\newcommand` a silent
7497      // no-op, so sibling B shows A's body — silent wrong content, and worse
7498      // than Perl, which scopes both. `\newif` installs `\ifX` as a Conditional
7499      // (`\Xtrue`/`\Xfalse` are plain macros the hooks do not read), so this
7500      // filter keeps every witness working while leaving macros scoped.
7501      if conditionals_only && !matches!(value, Stored::Conditional(_)) {
7502        continue;
7503      }
7504      // Direct re-bind via assign_internal so we don't need to round-trip a
7505      // full Token. The Meaning table is keyed by SymStr (the CS name);
7506      // any future read via `assign_meaning(token, ...)` would reach the
7507      // same cell. Scope::Global removes higher-frame undo entries and
7508      // installs at the lowest non-locked frame. A scope move, not a new
7509      // definition: whatever origin is current, a meaning keeps its standing
7510      // as a fallback class's guess or not (`fallback_meanings`; the lazy
7511      // LaTeX.pool hoist had made a pool convenience ours and refused the
7512      // document's `\newcommand`). Guard:
7513      // `reentrancy_tests::package_load_hoist_keeps_fallback_standing`.
7514      let fallback = if table == TableName::Meaning {
7515        state!().fallback_meanings.get(&key).copied()
7516      } else {
7517        None
7518      };
7519      let mut state = state_mut!();
7520      state.assign_internal(table, key, value, Some(Scope::Global));
7521      if table == TableName::Meaning {
7522        if let Some(origin) = fallback {
7523          state.fallback_meanings.insert(key, origin);
7524        } else {
7525          state.fallback_meanings.remove(&key);
7526        }
7527      }
7528    }
7529  }
7530}
7531/// Ends the current level of grouping.
7532/// Note that this is lower level than `\egroup`;
7533pub fn pop_frame() -> Result<()> {
7534  if *crate::stomach::TRACE_FRAMES {
7535    eprintln!(
7536      "[state] pop_frame depth {} -> {}",
7537      get_frame_depth(),
7538      get_frame_depth().saturating_sub(1)
7539    );
7540  }
7541  let mut state = state_mut!();
7542  if state.undo.front().as_ref().unwrap().locked {
7543    fatal!(
7544      TargetUnexpected,
7545      Endgroup,
7546      "attempt to pop last locked stack frame"
7547    );
7548  // Fatal('unexpected', '<endgroup>', $self->getStomach,
7549  // "Attempt to pop last locked stack frame"); }
7550  } else {
7551    let popped_frame = state.undo.pop_front().unwrap();
7552    let watched = WATCH.get() != 0;
7553    for table_name in TableName::variants() {
7554      let undo_table = popped_frame.table(*table_name);
7555      let state_table = state.table_mut(*table_name);
7556      for (key, undo_count) in undo_table.iter() {
7557        // (a value restored is a change of the state's: [`watch_state`])
7558        if watched && *undo_count > 0 {
7559          note_state_change(*table_name, *key);
7560        }
7561        // Typically only 1 value to shift off the table, unless scopes have been activated.
7562        let named_table = state_table.get_mut(key).unwrap();
7563        for _ in 0..*undo_count {
7564          named_table.pop_front();
7565        }
7566      }
7567    }
7568  }
7569  Ok(())
7570}
7571
7572/// Determine depth of group nesting.
7573///
7574/// nesting created by {,},\bgroup,\egroup,\begingroup,\endgroup
7575/// by counting all frames which are not Daemon frames (and thus don't possess _FRAME_LOCK_).
7576/// This may give incorrect results for some special environments (e.g. minipage)
7577pub fn get_frame_depth() -> usize { state!().undo.iter().filter(|frame| !frame.locked).count() }
7578
7579/// `true` when the CURRENT (front) stack frame is the locked bottom frame —
7580/// i.e. there is no openable group/mode frame to pop. Popping it would FATAL.
7581pub fn current_frame_locked() -> bool { state!().undo.front().map(|f| f.locked).unwrap_or(true) }
7582/// begins a semiverbatim frame, neutralizing the usual + requested characters
7583pub fn begin_semiverbatim(extraspecials: Option<&[char]>) {
7584  // Is this a good/safe enough shorthand, or should we really be doing beginMode?
7585  push_frame();
7586  assign_value("MODE", "restricted_horizontal", None);
7587  assign_value("IN_MATH", false, None);
7588  let mut all_specials: Vec<char> = Vec::new();
7589  if let Some(extra) = extraspecials {
7590    for special in extra {
7591      all_specials.push(*special);
7592    }
7593  }
7594  {
7595    if let Some(Stored::Chars(specials_store)) = state!().lookup_value("SPECIALS") {
7596      for special_char in &**specials_store {
7597        all_specials.push(*special_char);
7598      }
7599    }
7600  }
7601
7602  for special_char in all_specials {
7603    assign_catcode(special_char, Catcode::OTHER, Some(Scope::Local));
7604  }
7605  // `\dospecials` carries every ACTIVE shorthand a language registered
7606  // (babel.def `\bbl@add@special`), so `\url`'s `\@makeother` loop inertizes
7607  // babel-czech's `-`, babel-german's `"` … A live active `-` in a hyperref
7608  // url reached the `href` attribute's expansion, where czech.ldf:243-322's
7609  // `\futurelet` word scanner cannot assign and spun to PushbackLimit
7610  // (csbulletin `\nolinkurl{a-b}`; pdflatex/Perl clean). Guard:
7611  // `perfect_kernel_batch54::semiverbatim_inertizes_babel_shorthands`.
7612  for code in 0x21u8..=0x7Eu8 {
7613    let ch = code as char;
7614    if lookup_catcode(ch) == Some(Catcode::ACTIVE) {
7615      assign_catcode(ch, Catcode::OTHER, Some(Scope::Local));
7616    }
7617  }
7618  assign_mathcode('\'', 0x8000u16, Some(Scope::Local));
7619  // try to stay as ASCII as possible
7620  if let Some(ref current_font) = lookup_font() {
7621    let local_font = current_font.merge(fontmap!(encoding => "ASCII"));
7622    assign_font(Rc::new(local_font), Some(Scope::Local));
7623  }
7624}
7625/// end by just calling `pop_frame`
7626pub fn end_semiverbatim() -> Result<()> { pop_frame() }
7627
7628//   #======================================================================
7629
7630// PARTIAL port of Perl `LaTeXML::Core::State::push/popDaemonFrame`
7631// (used by the Perl `latexmls` daemon to reset bindings between runs while
7632// keeping the loaded Pool). `pop_daemon_frame` is faithful (pop unlocked
7633// frames, unlock + pop the daemon frame, Fatal on the last frame).
7634// `push_daemon_frame` is NOT yet: Perl (State.pm L607-627) additionally
7635// `daemon_copy`s every mutable HASH/ARRAY value binding into the new frame —
7636// so IN-PLACE mutations under the daemon frame (Rust: `with_value_mut` on
7637// `VecDequeStored`/`HashTagData`/... values, and a font's parameter array,
7638// `Stored::FontDimens`, written through its own `Rc<RefCell>` without any
7639// state borrow) can't corrupt the pre-frame
7640// state — and records `_PRELOADED_POOL_`. Without that copy, a daemon reset
7641// only undoes frame-tracked ASSIGNMENTS, not in-place mutations. The Rust
7642// persistent server (`latexml_oxide --server`) instead isolates each
7643// conversion in a `fork()`ed child, so these are not currently wired into a
7644// caller — kept (with the round-trip test in `tests/00_unit_state.rs`) as the
7645// seed of an in-process reset primitive for a future thread-reusing daemon
7646// mode, which MUST add the deep-copy semantics before relying on it. See
7647// `lsp_server` for the chosen fork-isolation design.
7648pub fn push_daemon_frame() {
7649  let daemon_frame = UndoFrame {
7650    locked: true,
7651    ..UndoFrame::default()
7652  };
7653  state_mut!().undo.push_front(daemon_frame);
7654}
7655
7656pub fn pop_daemon_frame() -> Result<()> {
7657  let mut state = state_mut!();
7658  // `is_some_and(!locked)` rather than `unwrap()`: an (impossible-in-practice)
7659  // empty undo stack must fall through to the Fatal below, not panic.
7660  while state.undo.front().is_some_and(|f| !f.locked) {
7661    drop(state);
7662    pop_frame()?;
7663    state = state_mut!();
7664  }
7665  if state.undo.len() > 1 {
7666    state.undo.front_mut().unwrap().locked = false;
7667    drop(state);
7668    pop_frame()?;
7669  } else {
7670    fatal!(
7671      TargetUnexpected,
7672      Endgroup,
7673      "Daemon Attempt to pop last stack frame"
7674    );
7675  }
7676  Ok(())
7677}
7678
7679// ======================================================================
7680/// Set one of the definition prefixes global, etc (only global matters!)
7681pub fn set_prefix(prefix: &str) { state_mut!().prefixes.insert(arena::pin(prefix), true); }
7682/// gets the current value of a named prefix
7683pub fn get_prefix(prefix: &str) -> bool { state!().get_prefix(prefix) }
7684/// `get_prefix` with a pre-pinned SymStr key (see `crate::pin!`) — for the
7685/// per-`\def` prefix probes in `Expandable::new` and friends.
7686pub fn get_prefix_sym(prefix: SymStr) -> bool { state!().get_prefix_sym(prefix) }
7687
7688/// clears the global prefixes
7689pub fn clear_prefixes() { state_mut!().prefixes = HashMap::default(); }
7690/// Whether one of TeX's own prefixes (`\global`, `\long`, `\outer`,
7691/// `\protected`) is waiting for its command. LaTeXML's internal prefixes (the
7692/// algorithm2e binding's `didpar`) are not TeX's and keep Perl's clearing.
7693pub fn has_tex_prefixes() -> bool {
7694  // Probed for every digested primitive: pre-pinned keys, no per-call interning.
7695  let state = state!();
7696  !state.prefixes.is_empty()
7697    && [
7698      pin!("global"),
7699      pin!("long"),
7700      pin!("outer"),
7701      pin!("protected"),
7702    ]
7703    .into_iter()
7704    .any(|p| state.get_prefix_sym(p))
7705}
7706
7707// #======================================================================
7708/// Named scope bracketing a subfile LaTeXML included itself — a `standalone`
7709/// child's preamble, an `\import`ed file. Real LaTeX has no group at either spot
7710/// (standalone *gobbles* the child preamble; import restores its paths by plain
7711/// `\def` after the `\input`), so a package loaded inside one is an artifact of
7712/// LaTeXML executing what the real packages skip. Bindings that open such a
7713/// bracket activate this scope; `require_package` reads it to decide whether a
7714/// load must outlive the bracket. See OXIDIZED_DESIGN #65.
7715///
7716/// The name carries the frame depth of the bracket that opened it — Perl's own
7717/// `section:4` / `label:foo` convention (State.pm L965-975) — because activity
7718/// alone is not enough: `StashActive` is `Scope::Local` at the bracket's frame,
7719/// so a plain "is the region active?" test is ALSO true at every deeper frame,
7720/// and an author's `{\usepackage{…}}` written *inside* a subfile preamble would
7721/// be hoisted as well. That is a downgrade: pdflatex and Perl both leave such a
7722/// package lost. Matching the depth confines the region to the bracket's own
7723/// level.
7724pub fn subfile_scope_at_depth(depth: usize) -> SymStr { arena::pin(format!("subfile:{depth}")) }
7725
7726/// The subfile scope for the CURRENT frame depth — what a bracket activates on
7727/// opening, and what `require_package` tests before hoisting.
7728pub fn subfile_scope_here() -> SymStr { subfile_scope_at_depth(get_frame_depth()) }
7729
7730/// Is the named scope currently active? See `scope_active_in` for why this is a
7731/// front-value test and not a presence test, and `subfile_scope_at_depth` for the region
7732/// marker it supports.
7733pub fn is_scope_active(scope: SymStr) -> bool { scope_active_in(&state!(), scope) }
7734
7735/// Perl's scope-activity test, shared by the three call sites that need it
7736/// (`is_scope_active`, `activate_scope`, `deactivate_scope`; `get_active_scopes`
7737/// deliberately still enumerates KEYS, faithful to Perl State.pm L722-725, which
7738/// has the same latent quirk — it has no callers):
7739/// the truthiness of the FRONT `stash_active` value — `$$self{stash_active}
7740/// {$scope}[0]` in `activateScope` (State.pm L682) and `deactivateScope`
7741/// (L700).
7742///
7743/// Presence is NOT the test, and cannot be: deactivation OVERWRITES the front
7744/// value with a falsy one rather than removing the key — an ordinary global
7745/// assignment (`assign_internal(… 'stash_active', $scope, 0, 'global')`,
7746/// State.pm L701; ours passes `Stored::Bool(false)`). A global assign replaces
7747/// rather than layers: it drops the per-frame counts down to the locked frame,
7748/// pops exactly that many values, and leaves ONE. So the front value is the
7749/// whole state. (A delete is not available anyway — `stash_active` rides the
7750/// generic table + undo machinery, whose per-frame pop counts a removed key
7751/// would desynchronise.) Pinned by
7752/// `reentrancy_tests::scope_activity_tracks_value_not_presence`.
7753///
7754/// Reach: the production consumers — `counter/dialect.rs` (a reference number's
7755/// `<ctr>:<refnum>` scope, deactivated then re-activated as the counter moves,
7756/// mirroring Perl `Package.pm` L774-779) and `latex_constructs.rs`'s `label:`
7757/// scopes — activate names that nothing currently STASHES into, so an activation
7758/// installs no bindings and the re-activation fix is correct but latent. It
7759/// becomes observable the moment a binding defines with `scope => "<ctr>:<n>"`.
7760/// That is why the guards are unit-level: there is no output difference to
7761/// assert end-to-end yet. (The one `Scope::Named` stash writer, `declare.rs`'s
7762/// declaration scope — `id:<unit id>` or `label:<label>` — is consumed by `rewrite.rs`
7763/// by prefix, not by activation.)
7764///
7765/// The local/global asymmetry is deliberate (Perl's own note above
7766/// `deactivateScope`): activation is `local`, so it expires with its group
7767/// without a teardown call — which is what makes a named scope usable as a
7768/// region marker (see `subfile_scope_at_depth`) — while deactivation is `global` so it
7769/// survives group exit. A local deactivation would be undone by the very group
7770/// that contained it.
7771fn scope_active_in(state: &State, scope: SymStr) -> bool {
7772  state
7773    .stash_active
7774    .get(&scope)
7775    .and_then(|entry| entry.front())
7776    .is_some_and(|v| !matches!(v, Stored::Bool(false)))
7777}
7778
7779/// Activates all stashed definitions for the named scope. No-op if the scope is already active.
7780pub fn activate_scope(scope: SymStr) {
7781  let mut state = state_mut!();
7782  // Perl L682 `if (!$$self{stash_active}{$scope}[0])` — do not re-activate if
7783  // already active, but a scope that was DEACTIVATED must be activatable again.
7784  if scope_active_in(&state, scope) {
7785    return;
7786  }
7787
7788  state.assign_internal(
7789    TableName::StashActive,
7790    scope,
7791    Stored::Bool(true),
7792    Some(Scope::Local),
7793  );
7794  // Also, we need to take ownership of the stashed data, so that we can assign it.
7795  // TODO: Potential to optimize?
7796  // Also x2, we are using a shared "Stored" interface for all data that passes through
7797  // assign_internal, but that causes both uncertainty and overhead in the Stash table
7798  // specifically. TODO x2: Maybe a more ambitious refactor will separate out the Stash logic
7799  // and use "StashTable" directly instead of Stored::Stash(StashTable) ?
7800
7801  let mut actions = Vec::new();
7802
7803  if let Some(Some(Stored::Stash(defns))) = state.stash.get(&scope).map(|x| x.iter().next()) {
7804    for (table_name, key, value) in defns {
7805      // copy the values out from the stashed defns, so that Rust
7806      // is calm we are borrowing safely.
7807
7808      actions.push((*table_name, key.to_owned(), value.clone()));
7809    }
7810  }
7811  // Here we ALWAYS push the stashed values into the table
7812  // since they may be popped off by deactivateScope
7813  for (table_name, key, value) in actions {
7814    state.journal_touch(table_name, key);
7815    let frame = &mut state.undo[0];
7816    let frame_table = frame.table_mut(table_name);
7817    let entry = frame_table.entry(key).or_insert(0);
7818    *entry += 1; // Note that this many values must be undone
7819    let key_table = state.table_mut(table_name).entry(key).or_default();
7820    key_table.push_front(value); // And push new binding.
7821  }
7822}
7823
7824// Probably, in most cases, the assignments made by activateScope
7825// will be undone by egroup or popping frames.
7826// But they can also be undone explicitly
7827
7828/// Removes any definitions that were associated with the named `scope`.
7829/// Normally not needed, since a scopes definitions are locally bound anyway.
7830pub fn deactivate_scope(scope: SymStr) {
7831  let mut state = state_mut!();
7832  // Perl L700 `if ($$self{stash_active}{$scope}[0])` — only an ACTIVE scope is
7833  // deactivated; a second deactivation must not re-run the pop below.
7834  if !scope_active_in(&state, scope) {
7835    return;
7836  }
7837
7838  state.assign_internal(
7839    TableName::StashActive,
7840    scope,
7841    Stored::Bool(false),
7842    Some(Scope::Global),
7843  );
7844
7845  let mut collected = Vec::new();
7846  if let Some(Some(Stored::Stash(defns))) = state.stash.get(&scope).map(|x| x.iter().next()) {
7847    for (table_name, key, value) in defns {
7848      collected.push((table_name.to_owned(), key.to_owned(), value.to_owned()));
7849    }
7850  }
7851
7852  for (table_name, key, value) in collected {
7853    state.journal_touch(table_name, key);
7854    let front_is_value = if let Some(table_entry_peek) = state.table(table_name).get(&key) {
7855      if let Some(table_front) = table_entry_peek.front() {
7856        *table_front == value
7857      } else {
7858        false
7859      }
7860    } else {
7861      false
7862    };
7863    let table_entry = state.table_mut(table_name).entry(key).or_default();
7864    if front_is_value {
7865      // Here we're popping off the values pushed by activateScope
7866      // to (possibly) reveal a local assignment in the same frame, preceding activateScope.
7867      (*table_entry).pop_front();
7868
7869      if let Some(frame) = state.undo.front_mut() {
7870        let frame_table = frame.table_mut(table_name);
7871        let frame_count = frame_table.entry(key).or_default();
7872        *frame_count -= 1;
7873      }
7874    } else {
7875      let message = arena::with(key, |key_str| {
7876        s!(
7877          "Unassigning wrong value for {} from table {} in deactivateScopevalue is {:?} but stack \
7878          is {:?}",
7879          key_str,
7880          table_name,
7881          value,
7882          table_entry
7883            .iter()
7884            .map(ToString::to_string)
7885            .collect::<Vec<String>>()
7886            .join(", ")
7887        )
7888      });
7889      arena::with(key, |key_str| Warn!("internal", key_str, message));
7890    }
7891  }
7892}
7893/// return all known named scopes
7894pub fn get_known_scopes() -> Vec<SymStr> { state!().stash.keys().copied().collect::<Vec<_>>() }
7895/// return the currently activated named scopes
7896pub fn get_active_scopes() -> Vec<SymStr> {
7897  state!().stash_active.keys().copied().collect::<Vec<_>>()
7898}
7899
7900//======================================================================
7901// Units.
7902// Put here since it could concievably evolve to depend on the current font.
7903/// convert a unit name into a `f64` scaling factor over `sp`
7904pub fn convert_unit(unit_arg: &str) -> f64 {
7905  let unit = unit_arg.to_lowercase();
7906  // Font-relative units fall back to 10pt metrics when no current font is
7907  // set (e.g. pre-bootstrap unit conversion). Perl gets this via the
7908  // built-in default font; matching with a static fallback is cheaper
7909  // than forcing every caller to ensure a font frame exists.
7910  let font_metric =
7911    |getter: fn(&Font) -> i64| -> f64 { lookup_font().map(|f| getter(&f) as f64).unwrap_or(0.0) };
7912  match unit.as_str() {
7913    "em" | "zw" | "zh" => font_metric(|f| f.get_em_width()),
7914    "ex" => font_metric(|f| f.get_ex_height()),
7915    "mu" => font_metric(|f| f.get_mu_width()),
7916    u => match UNITS.get(u) {
7917      Some(sp) => *sp,
7918      None => {
7919        let message = s!("Illegal unit of measure {:?}, assuming pt.", u);
7920        Warn!("expected", "<unit>", message);
7921        *UNITS.get("pt").unwrap()
7922      },
7923    },
7924  }
7925}
7926
7927/// Convert a unit name into the exact TeX `(num, den)` fraction such that a
7928/// dimension of `value` units is `floor(round(value·65536)·num/den)` scaled
7929/// points (see `numeric_ops::fixpoint_unit`).
7930///
7931/// Physical units use TeX's `set_conversion(num)(denom)` fractions verbatim
7932/// (tex.web §458, lines 9020-9032): `in=7227/100, pc=12/1, cm=7227/254,
7933/// mm=7227/2540, bp=7227/7200, dd=1238/1157, cc=14856/1157`, plus `pt=1/1` and
7934/// `sp=1/65536`. `px` follows LaTeXML in aliasing `bp`. Font-relative units
7935/// (`em`/`ex`/`mu`) return `(metric_sp, 65536)`, matching tex.web §8983's
7936/// `nx_plus_y(_, v, xn_over_d(v, f, 65536))` for internal units. This is the
7937/// exact-integer counterpart of [`convert_unit`]; each physical entry satisfies
7938/// `convert_unit(u) == 65536·num/den`.
7939pub fn convert_unit_ratio(unit_arg: &str) -> (i64, i64) {
7940  let unit = unit_arg.to_lowercase();
7941  let font_metric =
7942    |getter: fn(&Font) -> i64| -> i64 { lookup_font().map(|f| getter(&f)).unwrap_or(0) };
7943  // UNITY == 65536 sp per pt; font-relative and `sp` units convert via the
7944  // `floor(fix·v/UNITY)` path (tex.web §8983 nx_plus_y/xn_over_d).
7945  match unit.as_str() {
7946    "em" | "zw" | "zh" => (font_metric(|f| f.get_em_width()), UNITY),
7947    "ex" => (font_metric(|f| f.get_ex_height()), UNITY),
7948    "mu" => (font_metric(|f| f.get_mu_width()), UNITY),
7949    "pt" => (1, 1),
7950    "pc" => (12, 1),
7951    "in" => (7227, 100),
7952    "bp" | "px" => (7227, 7200),
7953    "cm" => (7227, 254),
7954    "mm" => (7227, 2540),
7955    "dd" => (1238, 1157),
7956    "cc" => (14856, 1157),
7957    "sp" => (1, UNITY),
7958    u => {
7959      let message = s!("Illegal unit of measure {:?}, assuming pt.", u);
7960      Warn!("expected", "<unit>", message);
7961      (1, 1)
7962    },
7963  }
7964}
7965
7966// ======================================================================
7967
7968// sub getStatus {
7969//   my ($self, $type) = @_;
7970//   return $$self{status}{$type}; }
7971
7972// sub getStatusMessage {
7973//   my ($self) = @_;
7974//   my $status = $$self{status};
7975//   my @report = ();
7976// push(@report, colorizeString("$$status{warning} warning" . ($$status{warning} > 1 ? 's' :
7977// ''), 'warning'))     if $$status{warning};
7978// push(@report, colorizeString("$$status{error} error" . ($$status{error} > 1 ? 's' : ''),
7979// 'error'))     if $$status{error};
7980//   push(@report, "$$status{fatal} fatal error" . ($$status{fatal} > 1 ? 's' : ''))
7981
7982//     if $$status{fatal};
7983//   my @undef = ($$status{undefined} ? keys %{ $$status{undefined} } : ());
7984//   push(@report, colorizeString(scalar(@undef) . " undefined macro" . (@undef > 1 ? 's' : '')
7985//         . "[" . join(', ', @undef) . "]", 'details'))
7986//     if @undef;
7987//   my @miss = ($$status{missing} ? keys %{ $$status{missing} } : ());
7988//   push(@report, colorizeString(scalar(@miss) . " missing file" . (@miss > 1 ? 's' : '')
7989//         . "[" . join(', ', @miss) . "]", 'details'))
7990//     if @miss;
7991//   return join('; ', @report) || colorizeString('No obvious problems', 'success'); }
7992
7993// sub getStatusCode {
7994//   my ($self) = @_;
7995//   my $status = $$self{status};
7996//   my $code;
7997//   if ($$status{fatal} && $$status{fatal} > 0) {
7998//     $code = 3; }
7999//   elsif ($$status{error} && $$status{error} > 0) {
8000//     $code = 2; }
8001//   elsif ($$status{warning} && $$status{warning} > 0) {
8002//     $code = 1; }
8003//   else {
8004//     $code = 0; }
8005//   return $code; }
8006// #======================================================================
8007
8008// TODO: Continue here -- need to diagnose why the indirect model is not returning
8009// an intermediate "ltx:p" when asking for "#PCDATA" inside "ltx:_CaptureBlock_",
8010// instead getting an intermediate "ltx:para".
8011
8012/// The indirect model includes all elements allowed as direct children,
8013/// and all descendents of a node that can be inserted after autoOpen'ing intermediate elements.
8014///
8015/// This model therefor includes information from the Schema, as well as
8016/// `auto_open` information that may be introduced in binding files.
8017// [Thus it should NOT be modifying the Model object, which may cover several documents in Daemon]
8018// `imodel[tag][child] => inter` means if in `tag`, to open `child`, we must first open `inter`
8019pub fn compute_indirect_model() -> IndirectModel {
8020  let mut imodel: IndirectModel = SymHashMap::default();
8021  // Determine any indirect paths to each descendent via an `autoOpen-able' tag.
8022  // Perl Document.pm L196-199 maps the `autoOpen` property to a fractional
8023  // OPENABILITY. Most tags get 1.0; `ltx:picture` gets 0.5 (latex_constructs.pool.ltxml:4943) so it
8024  // loses path-priority against full auto-openers (para, p, text, item, …).
8025  // We scale to u32 (100 = full, 50 = half, `AutoOpen`) to keep integer
8026  // arithmetic; the `desirability * openability / 100` recursion mirrors
8027  // Perl's float math. An openability of 0 is no auto-opener (Perl's falsy
8028  // `$::OPENABILITY{$kid}`, L216).
8029  let mut openability: SymHashMap<u32> = SymHashMap::default();
8030  // Collect all known tags: from the schema model AND from state tag_properties
8031  let mut all_tags: HashSet<SymStr> = model::get_tags().into_iter().collect();
8032  for tag in state!().tag_properties.keys() {
8033    all_tags.insert(*tag);
8034  }
8035  for tag in &all_tags {
8036    if let Some(x) = state!().tag_properties.get(tag)
8037      && let Some(AutoOpen(priority)) = x.auto_open
8038      && priority > 0
8039    {
8040      openability.insert_sym(*tag, priority);
8041    }
8042  }
8043
8044  for tag in &all_tags {
8045    let tag = *tag;
8046    let mut desc: SymHashMap<SymHashMap<usize>> = SymHashMap::default();
8047    compute_indirect_model_aux(tag, None, 100, &mut openability, &mut desc);
8048    let desc_keys: Vec<SymStr> = desc.keys().copied().collect();
8049    for kid in desc_keys {
8050      // Find best path to `kid`.
8051      let mut best = 0;
8052      let mut desc_kid_keys: Vec<SymStr> =
8053        desc.entry_sym(kid).or_default().keys().copied().collect();
8054      // TODO: why sort?
8055      // Update: it appears that "ltx:p" and "ltx:para" in ltx:_CaptureBlock_ is one reason!!!
8056      desc_kid_keys.sort_by(|a, b| arena::with2(*a, *b, |astr, bstr| astr.cmp(bstr)));
8057      for start in desc_kid_keys {
8058        if tag != kid && tag != start {
8059          let start_entry = {
8060            let kid_entry = desc.entry_sym(kid).or_default();
8061            *kid_entry.entry_sym(start).or_insert(0)
8062          };
8063          if start_entry > best {
8064            imodel.entry_sym(tag).or_default().insert_sym(kid, start);
8065            {
8066              best = start_entry;
8067            }
8068          }
8069        }
8070      }
8071    }
8072  }
8073  // PATCHUP
8074  if model::is_permissive() {
8075    // !!! Alarm!!!
8076    imodel
8077      .entry("#Document")
8078      .or_default()
8079      .insert("#PCDATA", arena::pin_static("ltx:p"));
8080  }
8081
8082  imodel
8083}
8084
8085// Package helpers used in core need to be localized here -- as state methods
8086/// `Let` macro setter
8087/// Run `body` with `cs` temporarily `\let` to `target` (local scope), then
8088/// restore `cs`'s prior meaning — the `{\let\cs\target …}` idiom of latex.ltx
8089/// (`\protected@edef`'s `\let\protect\@unexpandable@protect`, :1442) without
8090/// a save-stack group, for a reader that must not open one. The prior
8091/// meaning is restored whether or not `body` fails. A `cs` with no meaning
8092/// is restored to none.
8093pub fn with_let<R>(cs: &Token, target: &Token, body: impl FnOnce() -> Result<R>) -> Result<R> {
8094  let saved = lookup_meaning(cs);
8095  let_i(cs, target, None);
8096  let result = body();
8097  match saved {
8098    Some(meaning) => assign_meaning(cs, meaning, None),
8099    None => assign_meaning(cs, Stored::None, None),
8100  }
8101  result
8102}
8103
8104/// A binding's `\let` (`Let!`): [`let_i`], unless a provide-only load declines it ([`provide_only_declines`]).
8105/// TeX's own `\let` and `\futurelet` are `let_i`.
8106pub fn let_definition(token1: &Token, token2: &Token, scope: Option<Scope>) {
8107  if !provide_only_declines(token1) {
8108    let_i(token1, token2, scope);
8109  }
8110}
8111
8112pub fn let_i(token1: &Token, token2: &Token, scope: Option<Scope>) {
8113  {
8114    use crate::definition::origin::{DefinitionOrigin, current_origin, stand_in_loading};
8115    // (only while a stand-in binding loads, whose `\let`s a copy may meet: not every `\newif` flag of the pool)
8116    if stand_in_loading()
8117      && matches!(
8118        current_origin(),
8119        DefinitionOrigin::Unknown | DefinitionOrigin::Pool | DefinitionOrigin::Binding
8120      )
8121      && matches!(token1.get_catcode(), Catcode::CS | Catcode::ACTIVE)
8122    {
8123      let key = meaning_key(token1);
8124      state_mut!().binding_lets.insert(key);
8125    }
8126  }
8127  let meaning =// if token2.get_dont_expand().is_some() {
8128  //   Stored::Token(token2.clone())
8129  // } else {
8130    lookup_meaning(token2)
8131      .unwrap_or(Stored::None);
8132  // };
8133  if copy_provides_keeps_saved_meaning(token1, token2, &meaning) {
8134    let _ = after_assignment(); // (`let_i` returns no Result; a Fatal is logged where `Fatal!` raises it)
8135    return;
8136  }
8137  // A lock against the class and package files (`"{cs}:locked@files"`, [`name_carries_lock`]) holds for their `\let`
8138  // as for their `\def` ([`install_definition`]): arabtex's asect.sty:297 `\let\endabstract\endquotation`, which its
8139  // own raw `\end` (alatex.sty:105-109) then calls, closed the kernel abstract's body as a quotation (2401.14559). A
8140  // plain `:locked` is left to a `\let` to a non-robust meaning, as Perl's `Let` checks none (Package.pm:383-390); a
8141  // `\let` to a robust command takes the body copy below, whose wrapper the lock refuses (OXIDIZED_DESIGN #568). So
8142  // are the engine's own meaning writes ([`assign_meaning`]: `\csname`'s `\relax`, restores). A `\let` to an undefined token only clears
8143  // the name, and is kept: the "undefine, then define anew" idiom (projlib-author.sty:243-246 `\cs_undefine:N
8144  // \endabstract` before `\newenvsc{abstract}`, whose scontents `\NewDocumentEnvironment` "already defined" check
8145  // would fail; the homework and jwjournal manuals). The binding is kept aside (`"{cs}:locked@cleared"`) and back in
8146  // place when the file's new meaning is refused ([`restore_cleared_binding`]), whether the name is still undefined or
8147  // `\csname` has made it `\relax` on the way. Read at the origins `install_definition` reads the lock at (every one
8148  // but the document's, [`name_carries_lock`]). OXIDIZED_DESIGN #569; guards `perfect_kernel_batch66b::file_let_*`,
8149  // `…::refused_*_restores_the_binding`.
8150  // A lock that holds only against copies of the binding's interface ([`files_lock_holds`]) judges the `\let` by the
8151  // meaning it copies: one taking an optional argument with a default first is refused as above; any other goes
8152  // through, the binding kept aside as for a clearing `\let`, so that a copy defined next and refused puts it back
8153  // (a package's `\let\proof\relax` … `\newenvironment{proof}[1][\proofname]`; guard
8154  // `perfect_kernel_batch67s::package_redefined_proof_keeps_the_binding`). Not GT.cls (2503.05183): its `\let\proof
8155  // \relax` (:1469-1470) is the class's, but its copy is defined inside `\AtBeginDocument` (:1488-1494), at the
8156  // document's origin, and honoured (OXIDIZED_DESIGN_DIVERGENCES #596).
8157  if crate::definition::origin::current_origin()
8158    != crate::definition::origin::DefinitionOrigin::Document
8159    && !state_is_unlocked()
8160    && matches!(token1.get_catcode(), Catcode::CS | Catcode::ACTIVE)
8161    && token1.with_cs_name(|cs| arena::get(s!("{cs}:locked@files")).is_some_and(lookup_bool_sym))
8162  {
8163    let cs = token1.with_cs_name(|cs| cs.to_string());
8164    let holds = files_lock_holds(&cs, || takes_optional_first(&meaning));
8165    if holds && !matches!(meaning, Stored::None) {
8166      restore_cleared_binding(token1);
8167      let _ = after_assignment();
8168      return;
8169    }
8170    let protected = copies_lock(&cs);
8171    let clearing = matches!(meaning, Stored::None) || x_equals(token2, &crate::T_CS!("\\relax"));
8172    if clearing {
8173      if !is_cleared_meaning(token1)
8174        && protected
8175          .as_ref()
8176          .is_none_or(|protected| copies_lock_in_force(&cs, protected))
8177        && let Some(binding) = lookup_meaning(token1)
8178      {
8179        let cleared_key = token1.with_cs_name(|cs| s!("{cs}:locked@cleared"));
8180        assign_value(&cleared_key, binding, Some(Scope::Global));
8181      }
8182    } else {
8183      drop_copies_lock_aside(&cs);
8184    }
8185  } else if !state_is_unlocked()
8186    && matches!(token1.get_catcode(), Catcode::CS | Catcode::ACTIVE)
8187    && (matches!(meaning, Stored::None) || x_equals(token2, &crate::T_CS!("\\relax")))
8188    && !is_cleared_meaning(token1)
8189    && token1.with_cs_name(|cs| arena::get(s!("{cs}:locked")).is_some_and(lookup_bool_sym))
8190    && let Some(binding) = lookup_meaning(token1)
8191  {
8192    // A plain `:locked` binding a file's `\let` clears is kept aside too, the `\let` itself going through as in Perl,
8193    // and back in place when the file's own new meaning is refused ([`restore_cleared_binding`]): eulerpx.sty:130-132
8194    // `\let\mathscr=\undefined` then `\DeclareMathAlphabet\mathscr{U}{zeus}{m}{n}`, which the lock on the kernel's
8195    // `\mathscr` (sect07.rs) refuses, left `\mathscr` undefined, an Error at every use (2311.14793, 2501.10505,
8196    // 2510.26876; KNOWN_PERL_ERRORS #863). OXIDIZED_DESIGN #569. The document's own `\let` too, at every origin: the
8197    // plain lock refuses the document's redefinition as it refuses a file's (`\let\mathcal\undefined
8198    // \DeclareMathAlphabet{\mathcal}{OMS}{cmsy}{m}{n}` left `\mathcal` undefined; `\let\mathscr\relax` before
8199    // `\DeclareMathAlphabet{\mathscr}{U}{rsfs}{m}{n}` lost its script font), and a stale binding a package's
8200    // group-local clear set aside is replaced by the current one. A document value-definition after the restore still
8201    // reaches the binding's call owner (OXIDIZED_DESIGN #500). The `:locked@files` branch above keeps its origin test.
8202    let cleared_key = token1.with_cs_name(|cs| s!("{cs}:locked@cleared"));
8203    assign_value(&cleared_key, binding, Some(Scope::Global));
8204  }
8205  // Deep-copy the robust-wrapper pair.
8206  //
8207  // Our `DefConstructor`/`DefMacro` with `robust => true` stores the
8208  // public CS (e.g. `\ref`) as an Expandable wrapper that expands to
8209  // `\protect \<cs><space>`. The actual body lives under a SEPARATE
8210  // `\<cs><space>` slot. A plain `\let \origref \ref` would copy
8211  // only the wrapper — leaving the `\ref<space>` body shared between
8212  // `\origref` and `\ref`. A subsequent `\DeclareRobustCommand \ref
8213  // {...}` then overwrites `\ref<space>` and `\origref` silently
8214  // tracks the new body — often causing an infinite loop when the
8215  // new body references `\origref` itself (a common LaTeX idiom for
8216  // adding starred-form support: `\let\origref\ref
8217  // \DeclareRobustCommand\ref{\@ifstar\origref\origref}`).
8218  //
8219  // So the body half is `\let` too: `\let \origref<space> \ref<space>`, and
8220  // the two CSes own independent body slots. This is NOT TeX's `\let`, which
8221  // copies the wrapper `\protect \ref<space>` itself (and loops on that idiom
8222  // for a robust `\ref`; latex.ltx's `\ref` is not robust, the binding's is):
8223  // `\meaning\origref` reads `\protect \origref  ` where TeX reads `\protect
8224  // \ref  `, and `\ifx` compares the bodies ([`same_robust_body`]).
8225  // OXIDIZED_DESIGN_DIVERGENCES #315.
8226  //
8227  // Witnesses: canvas-3 stage-23 0810.0695 (PlanarMain.tex's
8228  // `\ifpdf...\else \let\origref\ref \DeclareRobustCommand\ref{
8229  // \@ifstar\origref\origref}\fi` triggers via the else-branch
8230  // when `\ifpdf` is false; its `\pdfoutput=1` makes it true since K6).
8231  //
8232  // Not when the body calls `\<token1><space>` itself: copied there it would call itself, so `\<token1><space>` is left
8233  // alone, as TeX's `\let` leaves it, and `\<token1>` takes `\<token2>`'s wrapper. mathfixs' autobold
8234  // (mathfixs.sty:24-32) builds `\mafx@bfseries` by one-step expansion of the robust `\bfseries` — its body
8235  // `\protect\bfseries<space>\ifmmode…` — and then `\let\bfseries=\mafx@bfseries` (33 of run 336's papers ran to
8236  // PushbackLimit, 2205.10090, 2211.07279). A copy over an existing body slot is still a copy (`\DeclareCommandCopy`
8237  // onto a robust command, `\let\origref\ref` run twice).
8238  //
8239  // Not over a locked inner: the body copy writes `\<token1><space>` directly, so for a locked robust binding (the
8240  // kernel `\cite`, whose inner is locked against the files, OXIDIZED_DESIGN #568) a class's `\let\cite\mycite` would
8241  // put its body under the binding's own wrapper, whose reinstallation the lock then refuses. Such a `\let` takes
8242  // TeX's (and Perl's `Let`) plain path below instead. A locked binding whose inner is free (a constructor: the
8243  // kernel `\LaTeX`) keeps the copy, whose wrapper the lock refuses: bera.sty:12-23's `\let\LaTeX=\fveLaTeX` (a
8244  // `\DeclareRobustCommand`) would otherwise replace the logo with its typeset boxes (enumitem, colorspace and mathador
8245  // manuals); its `\let\TeX=\fveTeX` (:10-11, a `\def`) takes the plain path and replaces `\TeX`, as in Perl. Guard
8246  // `perfect_kernel_batch66b::robust_let_over_a_locked_constructor_keeps_it`.
8247  if let Stored::Expandable(ref defn) = meaning
8248    && let Some(token2_space) = robust_wrapper_body(defn, token2)
8249    && !token1.with_str(|s| body_mentions(&token2_space, &s!("{s} ")))
8250    && !token1.with_str(|s| is_name_locked(&s!("{s} ")))
8251  {
8252    let token1_space = crate::T_CS!(token1.with_str(|s| s!("{s} ")));
8253    // (1) Copy `\<token2><space>` body to `\<token1><space>`
8254    // so the two CSes have independent body slots.
8255    let body_meaning = lookup_meaning(&token2_space).unwrap_or(Stored::None);
8256    let body_csname_sym = token1_space.pin_cs_name();
8257    state_mut!().assign_internal(TableName::Meaning, body_csname_sym, body_meaning, scope);
8258    // (2) Install `\<token1>` as a NEW robust wrapper that
8259    // points to `\<token1><space>` (rather than reusing
8260    // `\<token2>`'s wrapper, which still hardcodes
8261    // `\<token2><space>` in its body and would silently
8262    // re-track any later `\DeclareRobustCommand\<token2>{...}`).
8263    let new_wrapper_body = Tokens::new(vec![crate::T_CS!("\\protect"), token1_space]);
8264    let new_wrapper = Expandable::new(
8265      *token1,
8266      None,
8267      Some(ExpansionBody::Tokens(new_wrapper_body)),
8268      Some(expandable::ExpandableOptions {
8269        robust: true,
8270        ..expandable::ExpandableOptions::default()
8271      }),
8272    );
8273    if let Ok(wrapper) = new_wrapper {
8274      carry_document_refusal_records(token1, token2, scope);
8275      install_definition(wrapper, scope);
8276      let _ = after_assignment();
8277      return;
8278    }
8279  }
8280  let meaning = restored_setter(token1, meaning, scope).unwrap_or_else(setter_as_copied);
8281  carry_document_refusal_records(token1, token2, scope);
8282  let clearing = matches!(meaning, Stored::None) || x_equals(token2, &crate::T_CS!("\\relax"));
8283  let_takes_binding_from_aside(token1, clearing, scope.as_ref());
8284  assign_meaning(token1, meaning, scope);
8285  let _ = after_assignment();
8286}
8287
8288/// A document's `\let` before the class stands, as it does with no definition before it (a plain `\let` is never
8289/// refused): the binding a yield kept aside ([`keep_binding_aside_before_class`]) is not put back at the class
8290/// (`\def\LaTeX{A}\let\LaTeX\mylogo` prints "MYLOGO", as pdflatex does), and a clearing `\let` keeps it where a clearing
8291/// `\let` keeps a binding (`"{cs}:locked@cleared"`), for the next definition to find. A `\let` local to a group leaves
8292/// it: the group's end undoes the `\let`.
8293fn let_takes_binding_from_aside(token: &Token, clearing: bool, scope: Option<&Scope>) {
8294  if !matches!(token.get_catcode(), Catcode::CS | Catcode::ACTIVE)
8295    || !lock_waits_for_class()
8296    || local_to_a_group(scope)
8297  {
8298    return;
8299  }
8300  let aside_key = token.with_cs_name(|cs| s!("{cs}:lock@aside"));
8301  let Some(binding) = lookup_value(&aside_key).filter(|b| !matches!(b, Stored::None)) else {
8302    return;
8303  };
8304  assign_value(&aside_key, Stored::None, Some(Scope::Global));
8305  if clearing {
8306    let cleared_key = token.with_cs_name(|cs| s!("{cs}:locked@cleared"));
8307    assign_value(&cleared_key, binding, Some(Scope::Global));
8308  }
8309}
8310
8311/// A `\let` copy of a frontmatter setter that replays the class's refused definition of itself
8312/// (`\lx@replay@class@setter{<name>}`, OXIDIZED_DESIGN #482), taken before any was refused (`\<name>:redefined` unset),
8313/// is the setter as it stood then, as TeX's `\let` (tex.web §1221) freezes it: its body runs inside
8314/// `\lx@setter@as@copied{<name>}{…}`, which hides a later refusal's records. tocbase.cls:647-677 `\let\orig@author
8315/// \author` before its `\renewcommand\author`, then `\orig@author{\toc@authors}` (1811.06821, 1811.11810, 1904.05269,
8316/// 2011.14174, 1905.07135, 2311.03341). OXIDIZED_DESIGN_DIVERGENCES #1078.
8317fn setter_as_copied(meaning: Stored) -> Stored {
8318  let Stored::Expandable(ref defn) = meaning else {
8319    return meaning;
8320  };
8321  let Some(ExpansionBody::Tokens(ref body)) = defn.expansion else {
8322    return meaning;
8323  };
8324  let tokens = body.unlist_ref();
8325  // (the setters' bodies open with their call wrapper or the replay itself; one name test for every other macro)
8326  let opens_setter = tokens.first().is_some_and(|t| {
8327    t.with_str(|s| {
8328      matches!(
8329        s,
8330        "\\lx@sealed@class@call" | "\\lx@titlepage@class@call" | "\\lx@replay@class@setter"
8331      )
8332    })
8333  });
8334  let Some((name, close)) = setter_call_name(tokens).filter(|_| opens_setter) else {
8335    return meaning;
8336  };
8337  if lookup_bool(&s!("\\{name}:redefined"))
8338    || !tokens
8339      .iter()
8340      .any(|t| t.with_str(|s| s == "\\lx@replay@class@setter"))
8341  {
8342    return meaning;
8343  }
8344  let mut wrapped = vec![crate::T_CS!("\\lx@setter@as@copied"), T_BEGIN!()];
8345  wrapped.extend_from_slice(&tokens[2..close]);
8346  wrapped.extend([T_END!(), T_BEGIN!()]);
8347  wrapped.extend_from_slice(tokens);
8348  wrapped.push(T_END!());
8349  let mut copy = (**defn).clone();
8350  copy.expansion = Some(ExpansionBody::Tokens(Tokens::new(wrapped)));
8351  copy.plan = std::cell::OnceCell::new();
8352  copy.stored = std::cell::OnceCell::new();
8353  Stored::Expandable(Rc::new(copy))
8354}
8355
8356/// The per-name records of a lock's refusal of `\<name>` (after `:redefined`, [`note_redefined`],
8357/// `install_definition`): what a replay or a locked binding reads of the class's definition (OXIDIZED_DESIGN #482).
8358pub const REFUSAL_RECORD_SUFFIXES: [&str; 6] =
8359  ["", "@class", "@document", "@nargs", "@in", "@default"];
8360
8361/// `\let\<name>\<copy>` of a frozen copy of `\<name>` itself ([`setter_as_copied`]) restores the setter: in TeX the
8362/// class's definition is gone, so the copy's body is installed unwrapped and the refusal's records are cleared in the
8363/// `\let`'s own scope, as TeX's `\let` (a group's restore reverts at `\endgroup`; `\lx@dropped@<name>`,
8364/// [`REFUSAL_RECORD_SUFFIXES`]); a later refused redefinition records itself again and replays.
8365/// Review SETCOPY B1 (`\let\author\orig@author` then a second `\renewcommand\author`). OXIDIZED_DESIGN_DIVERGENCES #1078.
8366fn restored_setter(
8367  token1: &Token,
8368  meaning: Stored,
8369  scope: Option<Scope>,
8370) -> std::result::Result<Stored, Stored> {
8371  let Some((name, inner)) = frozen_setter_parts(&meaning) else {
8372    return Err(meaning);
8373  };
8374  if !token1.with_cs_name(|cs| cs.strip_prefix('\\') == Some(name.as_str())) {
8375    return Err(meaning);
8376  }
8377  let Stored::Expandable(ref defn) = meaning else {
8378    return Err(meaning);
8379  };
8380  let mut restored = (**defn).clone();
8381  restored.expansion = Some(ExpansionBody::Tokens(Tokens::new(inner)));
8382  restored.plan = std::cell::OnceCell::new();
8383  restored.stored = std::cell::OnceCell::new();
8384  let mut state = state_mut!();
8385  state.assign_internal(
8386    TableName::Meaning,
8387    arena::pin(s!("\\lx@dropped@{name}")),
8388    Stored::None,
8389    scope,
8390  );
8391  for suffix in REFUSAL_RECORD_SUFFIXES {
8392    state.assign_internal(
8393      TableName::Value,
8394      arena::pin(s!("\\{name}:redefined{suffix}")),
8395      Stored::None,
8396      scope,
8397    );
8398  }
8399  Ok(Stored::Expandable(Rc::new(restored)))
8400}
8401
8402/// The `{<name>}` of a setter call opening a macro body (`\lx@sealed@class@call{author}…`, `\lx@setter@as@copied
8403/// {author}{…}`), and the index of its closing brace.
8404fn setter_call_name(tokens: &[Token]) -> Option<(String, usize)> {
8405  if tokens.get(1) != Some(&T_BEGIN!()) {
8406    return None;
8407  }
8408  let close = tokens.iter().position(|t| *t == T_END!())?;
8409  Some((
8410    tokens[2..close]
8411      .iter()
8412      .map(|t| t.with_str(str::to_string))
8413      .collect(),
8414    close,
8415  ))
8416}
8417
8418/// A frozen setter copy's name and its unwrapped body: `\lx@setter@as@copied{<name>}{<body>}` ([`setter_as_copied`]).
8419fn frozen_setter_parts(meaning: &Stored) -> Option<(String, Vec<Token>)> {
8420  let Stored::Expandable(defn) = meaning else {
8421    return None;
8422  };
8423  let Some(ExpansionBody::Tokens(body)) = &defn.expansion else {
8424    return None;
8425  };
8426  let tokens = body.unlist_ref();
8427  if tokens.first() != Some(&crate::T_CS!("\\lx@setter@as@copied")) {
8428    return None;
8429  }
8430  let (name, close) = setter_call_name(tokens)?;
8431  Some((name, tokens.get(close + 2..tokens.len() - 1)?.to_vec()))
8432}
8433
8434/// Whether one of two macros is the other's copy as a setter stood ([`setter_as_copied`]): `\ifx` reads them as one
8435/// meaning, as TeX's are.
8436fn same_copied_setter(def1: &Stored, def2: &Stored) -> bool {
8437  let (Stored::Expandable(defn1), Stored::Expandable(defn2)) = (def1, def2) else {
8438    return false;
8439  };
8440  let unwrapped =
8441    |outer: &Expandable, inner: &Expandable| match (&outer.expansion, &inner.expansion) {
8442      (Some(ExpansionBody::Tokens(outer_body)), Some(ExpansionBody::Tokens(inner_body))) => {
8443        let outer_body = outer_body.unlist_ref();
8444        let inner_body = inner_body.unlist_ref();
8445        outer_body
8446          .first()
8447          .is_some_and(|t| t.with_str(|s| s == "\\lx@setter@as@copied"))
8448          && outer_body.len() > inner_body.len()
8449          && outer_body[outer_body.len() - inner_body.len() - 1..outer_body.len() - 1]
8450            == *inner_body
8451          && outer.paramlist == inner.paramlist
8452      },
8453      _ => false,
8454    };
8455  unwrapped(defn1, defn2) || unwrapped(defn2, defn1)
8456}
8457
8458/// [`carry_refusal_records`] for the document's own `\let`s of `\maketitle`, the records' one reader
8459/// (`latex_constructs::class_maketitle_in_force`; the kernel's `\global\let\thanks\relax` keeps `\lx@dropped@thanks`). A file's
8460/// `\let` onto a refused `\maketitle` (a package's restore, review revPRESBXb BL3) leaves its marks unknown: the refused
8461/// body forgotten, the document's record kept. Not a class's replayed body, which clears its own name as it runs
8462/// (`\global\let\maketitle\relax`).
8463fn carry_document_refusal_records(token1: &Token, token2: &Token, scope: Option<Scope>) {
8464  use crate::definition::origin::{DefinitionOrigin, current_origin};
8465  let maketitle = |t: &Token| t.with_cs_name(|cs| cs == "\\maketitle");
8466  if state!().refused_names.is_empty() || !(maketitle(token1) || maketitle(token2)) {
8467    return;
8468  }
8469  match current_origin() {
8470    DefinitionOrigin::Document => carry_refusal_records(token1, token2, scope),
8471    DefinitionOrigin::File
8472      if maketitle(token1)
8473        && !lookup_bool("lx_depositing_class_maketitle")
8474        && !lookup_bool("lx_replaying_class_setter")
8475        && ["@document", "@class"]
8476          .iter()
8477          .any(|suffix| lookup_bool(&s!("\\maketitle:redefined{suffix}"))) =>
8478    {
8479      let mut state = state_mut!();
8480      state.assign_internal(
8481        TableName::Value,
8482        arena::pin("\\maketitle:redefined@document"),
8483        Stored::Bool(true),
8484        scope,
8485      );
8486      state.assign_internal(
8487        TableName::Meaning,
8488        arena::pin("\\lx@dropped@maketitle"),
8489        Stored::None,
8490        scope,
8491      );
8492    },
8493    _ => {},
8494  }
8495}
8496/// `XEquals` check for two token arguments
8497pub fn x_equals(token1: &Token, token2: &Token) -> bool {
8498  let def1_opt = lookup_meaning(token1); // # token, definition object or None
8499  let def2_opt = lookup_meaning(token2); // ditto
8500  match (def1_opt, def2_opt) {
8501    (Some(def1), Some(def2)) => {
8502      def1 == def2
8503        || same_robust_body(token1, &def1, token2, &def2)
8504        || same_copied_setter(&def1, &def2)
8505    },
8506    (None, None) => true, // true if both undefined
8507    (..) => false,        // False, if only one has 'meaning'
8508  }
8509}
8510
8511/// Whether the macro `cs`'s token body mentions the control sequence named `name` (a closure body is opaque: no). By
8512/// name, so no token is interned for a name that may never exist.
8513pub fn body_mentions(cs: &Token, name: &str) -> bool {
8514  match lookup_meaning(cs) {
8515    Some(Stored::Expandable(defn)) => match defn.expansion {
8516      Some(ExpansionBody::Tokens(ref tks)) => {
8517        tks.unlist_ref().iter().any(|t| t.with_str(|s| s == name))
8518      },
8519      _ => false,
8520    },
8521    _ => false,
8522  }
8523}
8524
8525/// The inner control sequence of a robust wrapper: `defn` is `cs`'s meaning,
8526/// a macro whose expansion is exactly `\protect \<cs><space>`
8527/// (`\DeclareRobustCommand`, a binding's `robust => true`, or [`let_i`]'s copy
8528/// of either).
8529fn robust_wrapper_body(defn: &Expandable, cs: &Token) -> Option<Token> {
8530  let Some(ExpansionBody::Tokens(ref tks)) = defn.expansion else {
8531    return None;
8532  };
8533  let body = tks.unlist_ref();
8534  if body.len() != 2 || !body[0].with_str(|s| s == "\\protect") {
8535    return None;
8536  }
8537  let inner = cs.with_str(|s| s!("{s} "));
8538  body[1]
8539    .with_str(|s| s == inner)
8540    .then(|| crate::T_CS!(inner))
8541}
8542
8543/// `\ifx` of two robust wrappers whose inner macros have the same meaning.
8544/// In TeX `\let\x\bfseries` copies the wrapper `\protect \bfseries␣` itself,
8545/// so `\ifx\x\bfseries` is true (tex.web §507 compares the token lists);
8546/// [`let_i`] instead gives `\x` its own wrapper `\protect \x␣` and a copy of
8547/// the body under `\x␣` (arXiv 0810.0695, OXIDIZED_DESIGN_DIVERGENCES #315), so
8548/// the wrappers differ by name only and the bodies decide. `\ifx\reset@font
8549/// \normalfont` relies on it, and in the preamble amsthm.sty:209-212's
8550/// `\nonslanted` (`\let\@tempa\csname\f@shape shape\endcsname \ifx\@tempa
8551/// \itshape`; in the body the shape switches are `\protected` macros, a plain
8552/// meaning comparison). The bodies must be the same definition, not only
8553/// equal: two robust commands declared apart with the same body compare
8554/// false, as in TeX. A `\LetLtxMacro` copy (letltxmacro.sty) and a
8555/// `\NewCommandCopy`/`\DeclareCommandCopy`/`\RenewCommandCopy` copy (each its
8556/// own wrapper over a `\let` of the body) compare true, where TeX says false:
8557/// their state is [`let_i`]'s.
8558fn same_robust_body(token1: &Token, def1: &Stored, token2: &Token, def2: &Stored) -> bool {
8559  let (Stored::Expandable(defn1), Stored::Expandable(defn2)) = (def1, def2) else {
8560    return false;
8561  };
8562  if defn1.paramlist != defn2.paramlist {
8563    return false;
8564  }
8565  match (
8566    robust_wrapper_body(defn1, token1),
8567    robust_wrapper_body(defn2, token2),
8568  ) {
8569    (Some(inner1), Some(inner2)) => match (lookup_meaning(&inner1), lookup_meaning(&inner2)) {
8570      // The body [`let_i`] copies is the source's own `Rc<Expandable>`, so its
8571      // `cs` still names the inner macro it was defined as (`\bfseries␣`, as
8572      // the dump keeps it): equal bodies from two separate declarations
8573      // (`\DeclareRobustCommand\ra{x}`, `\DeclareRobustCommand\rb{x}`) stay
8574      // unequal, as their wrappers are in TeX.
8575      (Some(Stored::Expandable(body1)), Some(Stored::Expandable(body2))) => {
8576        body1 == body2 && body1.cs == body2.cs
8577      },
8578      (Some(body1), Some(body2)) => body1 == body2,
8579      _ => false,
8580    },
8581    _ => false,
8582  }
8583}
8584
8585/// simple id generator for a ligature
8586pub fn generate_ligature_id() -> usize {
8587  let id = 1 + lookup_int("autogen_ligature_id");
8588  assign_value("autogen_ligature_id", Stored::Int(id), Scope::Global);
8589  id as usize
8590}
8591
8592/// run the accumulated directives from `\afterassignment` (Package.pm:716); a value that is no token (a binding's
8593/// `AssignValue("afterAssignment", "Q")`) is an Error and dropped.
8594pub fn after_assignment() -> Result<()> {
8595  match remove_value_sym(pin!("afterAssignment")) {
8596    Some(Stored::Tokens(after)) => gullet::unread(after),
8597    Some(Stored::Token(after)) => gullet::unread_one(after),
8598    None | Some(Stored::None) => {},
8599    Some(other) => {
8600      Error!(
8601        "unexpected",
8602        "afterAssignment",
8603        format!("the saved \\afterassignment is not a token: {other:?}; dropped")
8604      );
8605    },
8606  }
8607  Ok(())
8608}
8609
8610// Ported from Perl's "local" declarations
8611
8612pub fn get_tag_property(tag: SymStr) -> TagOptions { state_mut!().ensure_tag_property(tag).clone() }
8613pub fn ensure_tag_property(tag: SymStr) { state_mut!().ensure_tag_property(tag); }
8614
8615pub fn with_tag_property<R, FnR>(tag: SymStr, caller: FnR) -> R
8616where FnR: FnOnce(Option<&TagOptions>) -> R {
8617  caller(state!().tag_properties.get(&tag))
8618}
8619pub fn with_tag_property_mut<R, FnR>(tag: SymStr, caller: FnR) -> R
8620where FnR: FnOnce(&mut TagOptions) -> R {
8621  ensure_tag_property(tag);
8622  caller(state_mut!().tag_properties.get_mut(&tag).unwrap())
8623}
8624
8625pub fn has_indirect_model() -> bool { state!().indirect_model.is_some() }
8626pub fn set_indirect_model(im: IndirectModel) {
8627  let mut state = state_mut!();
8628  state.indirect_model = Some(im);
8629}
8630pub fn get_nomathparse_flag() -> bool { state!().nomathparse }
8631pub fn set_nomathparse_flag(val: bool) {
8632  let mut state = state_mut!();
8633  state.nomathparse = val;
8634}
8635
8636/// Whether source-locator (`--source-map`) tracking + emission is on.
8637/// Read by the source-provenance machinery (mouth token-start capture,
8638/// `Document::absorb` `data-sourcepos` stamping) to stay zero-cost when off.
8639/// See `docs/performance/SOURCE_PROVENANCE.md`.
8640pub fn source_map_enabled() -> bool { state!().source_map }
8641pub fn set_source_map_flag(val: bool) {
8642  let mut state = state_mut!();
8643  state.source_map = val;
8644}
8645
8646/// Find-or-append a source file in the document-level `sources` table,
8647/// returning its integer `tag` (index). The per-element `data-sourcepos`
8648/// attribute carries this compact integer rather than a path — the
8649/// Source-Map-v3 `sources` convention (compact + anonymisable). Only
8650/// called on the source-map path. See `docs/performance/SOURCE_PROVENANCE.md` §0.1.
8651pub fn source_tag(source: SymStr) -> u32 {
8652  let mut state = state_mut!();
8653  if let Some(idx) = state.source_table.iter().position(|s| *s == source) {
8654    idx as u32
8655  } else {
8656    state.source_table.push(source);
8657    (state.source_table.len() - 1) as u32
8658  }
8659}
8660
8661/// Snapshot of the `sources` table (index = tag) for emitting the
8662/// document-level tag→file header.
8663pub fn source_table_snapshot() -> Vec<SymStr> { state!().source_table.clone() }
8664
8665/// Record a *named* source in the opened-sources read-log. Called from
8666/// `Mouth::create` for file and cached-content mouths — a cold path (one
8667/// call per file open, not per token).
8668pub fn record_opened_source(source: SymStr) { state_mut!().opened_sources.insert(source); }
8669
8670/// Snapshot of the opened-sources read-log (see `record_opened_source`).
8671pub fn opened_sources_snapshot() -> Vec<SymStr> {
8672  state!().opened_sources.iter().copied().collect()
8673}
8674
8675pub fn current_verbosity() -> i32 { state!().verbosity }
8676
8677pub fn push_pending_resource(value: Resource) { state_mut!().pending_resources.push(value); }
8678pub fn take_pending_resources() -> Vec<Resource> {
8679  std::mem::take(&mut state_mut!().pending_resources)
8680}
8681pub fn reset_pending_resources() { state_mut!().pending_resources = Vec::new(); }
8682pub fn get_indirect_model_relationship(tag: SymStr, childtag: SymStr) -> Option<SymStr> {
8683  match state!().indirect_model.as_ref().unwrap().get_sym(tag) {
8684    Some(sub_m) => sub_m.get_sym(childtag).copied(),
8685    None => None,
8686  }
8687}
8688
8689pub fn get_bindings_dispatch() -> Option<ResolvingBindingDispatcher> {
8690  state!().bindings_dispatch.clone()
8691}
8692pub fn get_extra_bindings_dispatch() -> Option<BindingDispatcher> {
8693  state!().extra_bindings_dispatch.clone()
8694}
8695pub fn set_bindings_dispatch(dispatcher: ResolvingBindingDispatcher) {
8696  let mut state = state_mut!();
8697  state.bindings_dispatch = Some(dispatcher);
8698}
8699pub fn set_extra_bindings_dispatch(dispatcher: BindingDispatcher) {
8700  let mut state = state_mut!();
8701  state.extra_bindings_dispatch = Some(dispatcher);
8702}
8703pub fn set_local_binding_finder(finder: LocalBindingFinder) {
8704  let mut state = state_mut!();
8705  state.local_binding_finder = Some(finder);
8706}
8707/// The binding file a user supplied for `request` in the local search paths, which the chain loads instead of any
8708/// compiled binding of that name (#947); `None` without one, or where runtime bindings are not built in.
8709pub fn local_binding_file(request: &str) -> Option<String> {
8710  let finder = state!().local_binding_finder.clone()?;
8711  finder(request)
8712}
8713
8714std::thread_local! {
8715  static PLAIN_TEX_DOCUMENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
8716}
8717/// Records whether the document about to be converted is a plain TeX one, by arXiv AutoTeX's test (its main file, or a
8718/// file a cue-less main file inputs, names neither `\documentclass`, `\documentstyle` nor `\begin{document}` before an
8719/// `\endinput`); set per conversion before the session's preloads load (`latexml::converter::Converter::note_main_source`).
8720pub fn set_plain_tex_document(plain: bool) { PLAIN_TEX_DOCUMENT.with(|c| c.set(plain)); }
8721/// Whether the document being converted is a plain TeX one ([`set_plain_tex_document`]): latexml.sty's preload must not
8722/// load the LaTeX format for it.
8723pub fn plain_tex_document() -> bool { PLAIN_TEX_DOCUMENT.with(std::cell::Cell::get) }
8724std::thread_local! {
8725  static DVI_DRIVER_OPTION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
8726}
8727/// Records whether the main file's `\documentclass` names a DVI driver option (`dvips`, `dvipdfmx`, …) and the file sets
8728/// no `\pdfoutput=1`: the document is a latex+dvips one (the K6 ruling's DVI cue, stream F).
8729pub fn set_dvi_driver_option(dvi: bool) { DVI_DRIVER_OPTION.with(|c| c.set(dvi)); }
8730/// Whether the document is a latex+dvips one by its class options ([`set_dvi_driver_option`]).
8731pub fn dvi_driver_option() -> bool { DVI_DRIVER_OPTION.with(std::cell::Cell::get) }
8732std::thread_local! {
8733  static PDF_DRIVER_OPTION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
8734}
8735/// Records whether the main file's `\documentclass` names the `pdftex` driver option: the document is a pdflatex one,
8736/// whatever PostScript files it also ships (the K6 ruling's PDF cue, mirroring [`set_dvi_driver_option`]).
8737pub fn set_pdf_driver_option(pdf: bool) { PDF_DRIVER_OPTION.with(|c| c.set(pdf)); }
8738/// Whether the document is a pdflatex one by its class options ([`set_pdf_driver_option`]).
8739pub fn pdf_driver_option() -> bool { PDF_DRIVER_OPTION.with(std::cell::Cell::get) }
8740/// What the figures a source includes say of its output mode (the K6 ruling's figure cue,
8741/// OXIDIZED_DESIGN_DIVERGENCES #537): read from the `\includegraphics`-family targets the main file and the files it
8742/// inputs name, resolved against the source tree, and from a pstricks load.
8743#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8744pub enum FigureOutputCue {
8745  /// No included figure resolves and no pstricks is loaded: the source tree's files decide.
8746  #[default]
8747  Undecided,
8748  /// Every included figure that resolves has a PostScript form, one has no other, or pstricks is loaded: latex+dvips.
8749  Dvi,
8750  /// An included figure exists only as PDF/PNG/JPEG, which latex+dvips cannot include: pdflatex.
8751  Pdf,
8752}
8753std::thread_local! {
8754  static FIGURE_OUTPUT_CUE: std::cell::Cell<FigureOutputCue> =
8755    const { std::cell::Cell::new(FigureOutputCue::Undecided) };
8756}
8757/// Records the output-mode cue of the figures the document's source includes ([`FigureOutputCue`]); set per conversion
8758/// before the session's preloads load.
8759pub fn set_figure_output_cue(cue: FigureOutputCue) { FIGURE_OUTPUT_CUE.with(|c| c.set(cue)); }
8760/// The output-mode cue of the figures the document's source includes ([`set_figure_output_cue`]).
8761pub fn figure_output_cue() -> FigureOutputCue { FIGURE_OUTPUT_CUE.with(std::cell::Cell::get) }
8762std::thread_local! {
8763  static SOURCE_DATE_EPOCH: std::cell::Cell<Option<i64>> = const { std::cell::Cell::new(None) };
8764}
8765/// Records the date of the document's source (Unix seconds, UTC): the newest modification time among the TeX source
8766/// files of the bundle it came in (`Config::source_date_epoch`), `None` when the source carries none; set per
8767/// conversion before the session's preloads load. ar5iv's archival preload reads it as the job's clock.
8768pub fn set_source_date_epoch(epoch: Option<i64>) { SOURCE_DATE_EPOCH.with(|c| c.set(epoch)); }
8769/// The date of the document's source ([`set_source_date_epoch`]).
8770pub fn source_date_epoch() -> Option<i64> { SOURCE_DATE_EPOCH.with(std::cell::Cell::get) }
8771
8772/// Snapshot of all registered (name, ext) binding pairs across all
8773/// dispatchers. Used by `find_file(notex=true)` to detect compiled-binding
8774/// existence regardless of extension (cls/sty/def/pool/code.tex/...).
8775pub fn get_binding_names() -> Vec<&'static [(&'static str, &'static str)]> {
8776  state!().binding_names.clone()
8777}
8778/// Append one crate's `(name, ext)` slice. Companion to
8779/// `set_bindings_dispatch` / `set_extra_bindings_dispatch` — call alongside
8780/// dispatcher registration so `find_file` can resolve compile-time
8781/// bindings. Duplicates are deduplicated by pointer so repeated calls from
8782/// the same crate don't inflate the fallback pool.
8783pub fn add_binding_names(names: &'static [(&'static str, &'static str)]) {
8784  let mut state = state_mut!();
8785  let ptr = names.as_ptr();
8786  if state.binding_names.iter().any(|s| s.as_ptr() == ptr) {
8787    return;
8788  }
8789  state.binding_names.push(names);
8790}
8791
8792/// Filtered view of `get_binding_names()` returning ONLY class names
8793/// (without `.cls` suffix). Used by `load_class` for Perl's prefix-match
8794/// fallback (Package.pm L2702-2706). Returns a flat `Vec<&str>` rather
8795/// than per-crate slices — callers that need to preserve crate boundaries
8796/// should iterate `get_binding_names()` directly.
8797pub fn get_class_binding_names() -> Vec<&'static str> {
8798  state!()
8799    .binding_names
8800    .iter()
8801    .flat_map(|slice| slice.iter())
8802    .filter(|(_, ext)| *ext == "cls")
8803    .map(|(name, _)| *name)
8804    .collect()
8805}
8806
8807/// `true` when at least one registered binding declares `ext` as its
8808/// extension. Used by `\input`'s heuristic to decide whether
8809/// `\input{name.<ext>}` should consult the binding registry — e.g.
8810/// `.sty`, `.cls`, `.def`, `.pool`, `code.tex` are all valid binding
8811/// extensions, while `.eps`, `.png`, `.bib` are not. Matches by extension
8812/// only (the `name` is checked separately by `dispatch()`'s exact lookup).
8813pub fn is_binding_extension(ext: &str) -> bool {
8814  state!()
8815    .binding_names
8816    .iter()
8817    .any(|slice| slice.iter().any(|(_, e)| *e == ext))
8818}
8819
8820/// `true` when a binding is registered for the exact `(name, ext)` pair.
8821/// Convenience wrapper over the per-crate slices in `binding_names`.
8822/// Mirrors `dispatch()`'s lookup but without the side effect of loading.
8823pub fn binding_exists(name: &str, ext: &str) -> bool {
8824  state!()
8825    .binding_names
8826    .iter()
8827    .any(|slice| slice.iter().any(|(n, e)| *n == name && *e == ext))
8828}
8829
8830pub fn get_label_mapping_hook() -> Option<LabelMappingHook> { state!().label_mapping_hook.clone() }
8831pub fn set_label_mapping_hook(hook: LabelMappingHook) {
8832  let mut state = state_mut!();
8833  state.label_mapping_hook = Some(hook);
8834}
8835
8836/// Read SEARCHPATHS from the group-scoped value table (Perl
8837/// `LookupValue('SEARCHPATHS')`). Mirrors [`get_graphics_paths`]: the list is a
8838/// group-scoped value, not a plain field, so an `\import`/`\subimport` group
8839/// reverts its change at `}` and a package's global add persists.
8840pub fn get_search_paths() -> Vec<String> {
8841  lookup_value("SEARCHPATHS")
8842    .map(|v| match v {
8843      Stored::Strings(syms) => syms.iter().map(|s| arena::to_string(*s)).collect(),
8844      Stored::VecDequeStored(vdq) => vdq
8845        .iter()
8846        .filter_map(|item| match item {
8847          Stored::String(s) => Some(arena::to_string(*s)),
8848          _ => None,
8849        })
8850        .collect(),
8851      _ => Vec::new(),
8852    })
8853    .unwrap_or_default()
8854}
8855pub fn with_search_paths<R, FnR>(caller: FnR) -> R
8856where FnR: FnOnce(&[String]) -> R {
8857  caller(&get_search_paths())
8858}
8859/// Global append (Perl `PushValue(SEARCHPATHS)`) — a persistent search dir.
8860pub fn add_search_path(path: String) {
8861  let mut paths = get_search_paths();
8862  paths.push(path);
8863  set_search_paths(paths);
8864}
8865/// Global prepend (Perl `UnshiftValue(SEARCHPATHS)`) — a persistent search dir.
8866pub fn search_paths_push_front(path: String) {
8867  let mut paths = get_search_paths();
8868  paths.insert(0, path);
8869  set_search_paths(paths);
8870}
8871/// Replace SEARCHPATHS GLOBALLY (Perl `AssignValue(SEARCHPATHS => [...], 'global')`).
8872/// For the local-by-default `\import` scoping, use [`set_search_paths_local`].
8873pub fn set_search_paths(paths: Vec<String>) { assign_search_paths(paths, Scope::Global); }
8874/// Replace SEARCHPATHS in the CURRENT group only (Perl `AssignValue(SEARCHPATHS
8875/// => [...])` default-local): reverted when the enclosing `\import`/`\subimport`
8876/// group closes. This is what makes `import.sty` faithful without an explicit
8877/// save/restore stack.
8878pub fn set_search_paths_local(paths: Vec<String>) { assign_search_paths(paths, Scope::Local); }
8879fn assign_search_paths(paths: Vec<String>, scope: Scope) {
8880  let vdq: VecDeque<Stored> = paths
8881    .into_iter()
8882    .map(|p| Stored::String(arena::pin(&p)))
8883    .collect();
8884  assign_value("SEARCHPATHS", Stored::VecDequeStored(vdq), Some(scope));
8885}
8886pub fn has_search_paths() -> bool { !get_search_paths().is_empty() }
8887/// Mirror Perl's `LookupValue('GRAPHICSPATHS')` — a list value that all
8888/// `\graphicspath`, `\svgpath`, initial source-directory prepends, and
8889/// `image_candidates` consult. Always return as `Vec<String>` even if the
8890/// value was stored as `Strings` (initial assignValue) or `VecDequeStored`
8891/// (after any push/unshift).
8892pub fn get_graphics_paths() -> Vec<String> {
8893  lookup_value("GRAPHICSPATHS")
8894    .map(|v| match v {
8895      Stored::Strings(syms) => syms.iter().map(|s| arena::to_string(*s)).collect(),
8896      Stored::VecDequeStored(vdq) => vdq
8897        .iter()
8898        .filter_map(|item| match item {
8899          Stored::String(s) => Some(arena::to_string(*s)),
8900          _ => None,
8901        })
8902        .collect(),
8903      _ => Vec::new(),
8904    })
8905    .unwrap_or_default()
8906}
8907
8908/// Zero-alloc membership test for GRAPHICSPATHS. Mirrors the Perl idiom
8909/// `grep { $_ eq $dir } @{ $state->lookupValue('GRAPHICSPATHS') }` but
8910/// without allocating an owned `Vec<String>` for a single boolean — the
8911/// interned-symbol `with`/`with2` family resolves each path in place.
8912pub fn graphics_paths_contains(needle: &str) -> bool {
8913  lookup_value("GRAPHICSPATHS")
8914    .map(|v| match v {
8915      Stored::Strings(syms) => syms.iter().any(|s| arena::with(*s, |p| p == needle)),
8916      Stored::VecDequeStored(vdq) => vdq.iter().any(|item| match item {
8917        Stored::String(s) => arena::with(*s, |p| p == needle),
8918        _ => false,
8919      }),
8920      _ => false,
8921    })
8922    .unwrap_or(false)
8923}
8924
8925/// Mirror Perl's `$state->unshiftValue(GRAPHICSPATHS => $dir)`. Used by
8926/// Core.pm-style source-directory prepends.
8927pub fn graphics_paths_push_front(path: String) {
8928  let key = arena::pin("GRAPHICSPATHS");
8929  let entry = Stored::String(arena::pin(&path));
8930  let mut state = state_mut!();
8931  state.journal_touch(TableName::Value, key);
8932  if !state.value.contains_key(&key) {
8933    state.assign_internal(
8934      TableName::Value,
8935      key,
8936      Stored::VecDequeStored(VecDeque::new()),
8937      Some(Scope::Global),
8938    );
8939  }
8940  let receiver = state.value.get_mut(&key).unwrap().front_mut();
8941  match receiver {
8942    Some(Stored::VecDequeStored(vdq)) => vdq.push_front(entry),
8943    Some(Stored::Strings(syms)) => {
8944      let mut vdq: VecDeque<Stored> = syms.iter().map(|s| Stored::String(*s)).collect();
8945      vdq.push_front(entry);
8946      state.assign_internal(
8947        TableName::Value,
8948        key,
8949        Stored::VecDequeStored(vdq),
8950        Some(Scope::Global),
8951      );
8952    },
8953    _ => {
8954      let mut vdq = VecDeque::new();
8955      vdq.push_front(entry);
8956      state.assign_internal(
8957        TableName::Value,
8958        key,
8959        Stored::VecDequeStored(vdq),
8960        Some(Scope::Global),
8961      );
8962    },
8963  }
8964}
8965
8966/// manage a (global) hash of values
8967pub fn with_mapping<R, FnR>(map: &str, key: &str, caller: FnR) -> R
8968where FnR: FnOnce(Option<&Stored>) -> R {
8969  let map_sym = arena::pin(map);
8970  caller(match state!().value.get(&map_sym) {
8971    None => None,
8972    Some(map_vec) => match map_vec.front() {
8973      Some(Stored::HashStored(h)) => h.get(key),
8974      _ => None,
8975    },
8976  })
8977}
8978
8979pub fn with_mapping_sym<R, FnR>(map: SymStr, key: SymStr, caller: FnR) -> R
8980where FnR: FnOnce(Option<&Stored>) -> R {
8981  caller(match state!().value.get(&map) {
8982    None => None,
8983    Some(map_vec) => match map_vec.front() {
8984      Some(Stored::HashStored(h)) => h.get_sym(key),
8985      _ => None,
8986    },
8987  })
8988}
8989
8990pub fn with_mapping_keys<R, FnR>(map: &str, caller: FnR) -> R
8991where FnR: FnOnce(Vec<SymStr>) -> R {
8992  caller(state!().lookup_mapping_keys(map))
8993}
8994
8995pub fn with_font_info<R, FnR>(key: &Token, caller: FnR) -> R
8996where FnR: FnOnce(Result<Option<&Stored>>) -> R {
8997  caller(state!().lookup_font_info(key))
8998}
8999
9000pub fn get_input_encoding() -> Option<SymStr> { state!().input_encoding.as_ref().map(arena::pin) }
9001pub fn set_input_encoding(val: Option<String>) {
9002  let mut state = state_mut!();
9003  state.input_encoding = val;
9004}
9005
9006pub fn with_stacked_values<R, FnR>(key: &str, caller: FnR) -> R
9007where FnR: FnOnce(Vec<&Stored>) -> R {
9008  caller(state!().lookup_stacked_values(key))
9009}
9010/// Sym-keyed variant of `with_stacked_values`.
9011pub fn with_stacked_values_sym<R, FnR>(key: SymStr, caller: FnR) -> R
9012where FnR: FnOnce(Vec<&Stored>) -> R {
9013  caller(state!().lookup_stacked_values_sym(key))
9014}
9015
9016pub fn set_state(incoming_state: State) {
9017  // Reset state rotation to Main to prevent stale Sty/Std state from previous runs
9018  STATE_IN_USE.set(RotateState::Main);
9019  let mut global_state = state_mut!();
9020  *global_state = incoming_state;
9021}
9022
9023/// Check whether a Stored value can be serialized for the kernel dump.
9024/// Values containing closures (Primitive, Constructor, Conditional, etc.)
9025/// cannot be serialized — they come from Rust engine code, not the dump.
9026/// This matches Perl's DumpFile which only serializes Expandable macros.
9027pub fn is_serializable(stored: &Stored) -> bool {
9028  use Stored::*;
9029  match stored {
9030    // Data types: always serializable
9031    None | Bool(_) | String(_) | Charcode(_) | Int(_) | Catcode(_) => true,
9032    Token(_) | Tokens(_) | Number(_) | Float(_) => true,
9033    Glue(_) | MuGlue(_) | Dimension(_) | MuDimension(_) => true,
9034    Reversion(_) | KeyVal(_) => true,
9035    Chars(_) | Strings(_) => true,
9036    // Expandable: serializable when body is Tokens OR None (regular
9037    // macros). Closure-bodied Expandables (e.g. `\expandafter`,
9038    // `\unexpanded`, `\the` — defined via `DefMacro!` with a closure
9039    // body) ALSO pass — dump_writer's `serialize_stored` emits a PA
9040    // alias to the canonical CS so `\let \tex_expandafter:D
9041    // \expandafter`-style aliases survive the dump. (Bug C parity fix
9042    // — see project_kernel_dump_tdd.md.) The dump reader skips a
9043    // self-alias (the key is the canonical CS of the compiled engine),
9044    // so primary CSes don't double-bind.
9045    Expandable(_) => true,
9046    // Register: serializable (stores value + type, no closures)
9047    Register(_) => true,
9048    // Font: serializable (data only)
9049    Font(_) => true,
9050    // A font's parameter array: serializable (data only), as an `IA` record.
9051    FontDimens(_) => true,
9052    // Primitives/MathPrimitives/Conditionals: the CLOSURE can't be
9053    // serialized, but each carries its own canonical CS name. If the
9054    // entry's key differs from that canonical CS, this is a `\let`-alias
9055    // we CAN capture (as a "PA" pointer) so the dump reader replays the
9056    // `\let` at load time. dump_writer returns the PA tag; dump_reader
9057    // re-applies via state::let_i. This is how \tex_let:D, \tex_def:D,
9058    // \tex_ifx:D, \if_meaning:w, and the hundreds of other expl3-renamed
9059    // primitives + conditionals survive the dump without needing to re-run
9060    // 36k lines of expl3-code.tex.
9061    //
9062    // Returning true here only means "pass to dump_writer"; the writer's
9063    // serialize_stored emits the PA target. Self-aliases (primary CSes
9064    // not yet aliased anywhere) typically don't appear in the diff because
9065    // they're in the pre-snapshot — but if they do, the dump reader skips
9066    // them by comparing key to target.
9067    Primitive(_) | MathPrimitive(_) | Conditional(_) => true,
9068    // Constructor: same logic as Primitive/Conditional. Constructors carry a
9069    // closure body the dump can't serialize, BUT they each carry a canonical
9070    // CS field. When the entry key differs from that CS, it's a `\let`-alias
9071    // (e.g. `\let \tex_par:D \par` where `\par` is itself a `Let!` alias to
9072    // `\lx@normal@par` — a Constructor). dump_writer emits `PA\t<cs>`;
9073    // dump_reader replays via `state::let_i`. Mirrors Perl's writer:
9074    // `dump_constructor` is undefined in `Dumper.pm`, but TeX_Job.pool
9075    // `DumpFile`'s let-detection branch (L184-198) catches the (key !=
9076    // value->getCSName) case and emits `Lt(key, letkey)`. Without this,
9077    // `\tex_par:D`, `\tex_cr:D`, `\tex_noindent:D`, etc. drop from the dump
9078    // because diff_from_snapshot filters them before the writer's
9079    // Constructor arm sees them.
9080    Constructor(_) => true,
9081    // Collections: serializable if contents are
9082    VecDequeStored(_) | HashStored(_) | HashString(_) => true,
9083    // Everything else: skip for safety
9084    _ => false,
9085  }
9086}
9087
9088/// Take a snapshot of the current State (for dump diff).
9089pub fn take_snapshot() -> rustc_hash::FxHashMap<(TableName, SymStr), Stored> { state!().snapshot() }
9090
9091/// Compute diff from snapshot and return changed serializable entries.
9092pub fn diff_snapshot(
9093  snap: &rustc_hash::FxHashMap<(TableName, SymStr), Stored>,
9094) -> Vec<(TableName, SymStr, Stored)> {
9095  state!().diff_from_snapshot(snap)
9096}
9097
9098// Thread-local holder for the snapshot taken at a named init phase.
9099// Currently only "bootstrap" is used: when `latex.rs` finishes loading
9100// `latex_bootstrap`, it stashes the state snapshot here. `ini_tex::dump_format`
9101// reads it so its diff matches Perl's `DumpFile` semantics — "what did raw
9102// latex.ltx + the rest of the engine init add on top of pure bootstrap".
9103// Without this hook the snapshot is taken after `_base.rs` + `_constructs.rs`
9104// have also run, making the diff far narrower than Perl's dump. See
9105// SYNC_STATUS D0 (d.1).
9106type StateSnapshot = rustc_hash::FxHashMap<(TableName, SymStr), Stored>;
9107type StagedSnapshotMap = rustc_hash::FxHashMap<&'static str, StateSnapshot>;
9108
9109thread_local! {
9110  static STAGED_SNAPSHOTS: RefCell<StagedSnapshotMap> =
9111    RefCell::new(rustc_hash::FxHashMap::default());
9112}
9113
9114/// Take a snapshot now and store it under a named key for later retrieval.
9115/// Intended for phased engine init (e.g. `stage_snapshot("bootstrap")` called
9116/// right after `latex_bootstrap` has loaded).
9117pub fn stage_snapshot(name: &'static str) {
9118  let snap = take_snapshot();
9119  STAGED_SNAPSHOTS.with(|m| {
9120    m.borrow_mut().insert(name, snap);
9121  });
9122}
9123
9124/// Stage an already-taken snapshot under a named key. Used by callers
9125/// (like `ini_tex`) that want to snapshot at a specific point without
9126/// waiting for a pool hook.
9127pub fn stage_snapshot_value(
9128  name: &'static str,
9129  snap: rustc_hash::FxHashMap<(TableName, SymStr), Stored>,
9130) {
9131  STAGED_SNAPSHOTS.with(|m| {
9132    m.borrow_mut().insert(name, snap);
9133  });
9134}
9135
9136/// Retrieve a previously staged snapshot, if present.
9137pub fn get_staged_snapshot(
9138  name: &str,
9139) -> Option<rustc_hash::FxHashMap<(TableName, SymStr), Stored>> {
9140  STAGED_SNAPSHOTS.with(|m| m.borrow().get(name).cloned())
9141}
9142
9143#[cfg(test)]
9144mod conditional_counter_tests {
9145  use super::*;
9146
9147  /// Perl `Conditional.pm:61-62` assigns `if_count` *globally* so the
9148  /// per-conditional id keeps climbing across group exits; the typed field
9149  /// must not revert with the frame it was bumped in, and the limit is a
9150  /// plain global (`$LaTeXML::IF_LIMIT`), unlimited when `0`.
9151  #[test]
9152  fn if_ids_climb_across_group_exits() {
9153    reset_thread_state();
9154    let first = next_if_id();
9155    push_frame();
9156    let inner = next_if_id();
9157    pop_frame().expect("pop the probe frame");
9158    let after = next_if_id();
9159    assert_eq!((first, inner, after), (1, 2, 3));
9160    assert_eq!(
9161      if_limit(),
9162      0,
9163      "unlimited until latexml.sty's iflimit sets it"
9164    );
9165    set_if_limit(3_999_999);
9166    assert_eq!(if_limit(), 3_999_999);
9167    // The absorb counter is the same mechanism (Perl Object.pm:165).
9168    push_frame();
9169    assert_eq!(next_absorb_id(), 1);
9170    pop_frame().expect("pop the probe frame");
9171    assert_eq!(next_absorb_id(), 2);
9172    set_absorb_limit(7);
9173    assert_eq!(absorb_limit(), 7);
9174    reset_thread_state();
9175    assert_eq!(next_if_id(), 1, "a fresh conversion restarts the counter");
9176    assert_eq!(if_limit(), 0, "and forgets the previous limit");
9177    assert_eq!((next_absorb_id(), absorb_limit()), (1, 0));
9178  }
9179}
9180
9181#[cfg(test)]
9182mod reentrancy_tests {
9183  use super::*;
9184
9185  /// A package-load hoist moves a meaning to global scope without changing whether it is a fallback class's
9186  /// guess (`fallback_meanings`), whatever origin is current while it runs.
9187  #[test]
9188  fn package_load_hoist_keeps_fallback_standing() {
9189    use crate::definition::origin::{DefinitionOrigin, with_origin};
9190    let guess = T_CS!("\\p1a_hoisted_fallback_probe");
9191    let own = T_CS!("\\p1a_hoisted_own_probe");
9192    push_frame();
9193    let pre = snapshot_top_frame_keys();
9194    with_origin(DefinitionOrigin::Fallback, || {
9195      let_i(&guess, &T_LETTER!("x"), None)
9196    });
9197    let_i(&own, &T_LETTER!("y"), None);
9198    with_origin(DefinitionOrigin::Fallback, || {
9199      hoist_top_frame_package_load(pre)
9200    });
9201    assert!(pop_frame().is_ok());
9202    assert!(
9203      lookup_meaning(&guess).is_some() && lookup_meaning(&own).is_some(),
9204      "both hoisted to global scope"
9205    );
9206    assert!(is_fallback_meaning(&guess), "a fallback guess stays one");
9207    assert!(
9208      !is_fallback_meaning(&own),
9209      "a hoist under a fallback origin makes nothing a guess"
9210    );
9211  }
9212
9213  /// A package-load hoist takes a meaning the frame had bound before the load and the load re-bound there (natbib's
9214  /// `\let\bibitem\lx@nat@bibitem` in a `thebibliography` that had armed `\bibitem`, arXiv 2006.04387), not one the
9215  /// load re-bound to the very same definition object, nor one it left alone.
9216  #[test]
9217  fn package_load_hoist_takes_a_rebound_meaning() {
9218    let rebound = T_CS!("\\p1a_hoist_rebound_probe");
9219    let restored = T_CS!("\\p1a_hoist_restored_probe");
9220    let untouched = T_CS!("\\p1a_hoist_untouched_probe");
9221    push_frame();
9222    for cs in [&rebound, &restored, &untouched] {
9223      let_i(cs, &T_LETTER!("a"), None);
9224    }
9225    let pre = snapshot_top_frame_keys();
9226    let_i(&rebound, &T_LETTER!("b"), None);
9227    let_i(&restored, &T_LETTER!("b"), None);
9228    let_i(&restored, &T_LETTER!("a"), None);
9229    hoist_top_frame_package_load(pre);
9230    assert!(pop_frame().is_ok());
9231    assert!(
9232      matches!(lookup_meaning(&rebound), Some(Stored::Token(t)) if t == T_LETTER!("b")),
9233      "the re-bound meaning outlives the group"
9234    );
9235    assert!(lookup_meaning(&restored).is_none(), "put back: the group's");
9236    assert!(
9237      lookup_meaning(&untouched).is_none(),
9238      "untouched: the group's"
9239    );
9240    assert!(
9241      state!().meaning_recorders.is_empty(),
9242      "the hoist closes its recorder"
9243    );
9244  }
9245
9246  /// `with_let` binds for the body only and restores the prior meaning —
9247  /// including "no meaning" — even when the body fails.
9248  #[test]
9249  fn with_let_restores_the_prior_meaning() {
9250    let cs = T_CS!("\\p1a_with_let_probe");
9251    // A character token is its own meaning even in a bare State (no engine).
9252    let target = T_OTHER!("x");
9253    assert!(lookup_meaning(&cs).is_none());
9254    let seen: Result<bool> = with_let(&cs, &target, || Ok(lookup_meaning(&cs).is_some()));
9255    assert_eq!(seen.ok(), Some(true));
9256    assert!(lookup_meaning(&cs).is_none(), "restored to no meaning");
9257    let_i(&cs, &T_LETTER!("y"), None);
9258    let before = lookup_meaning(&cs);
9259    assert!(before.is_some());
9260    let failed: Result<()> = with_let(&cs, &target, || Err("boom".into()));
9261    assert!(failed.is_err());
9262    assert_eq!(lookup_meaning(&cs), before, "restored after a failing body");
9263  }
9264
9265  /// `try_lookup_int` must degrade to `None` under a live mutable borrow
9266  /// (contention) instead of panicking, while behaving like `lookup_int`
9267  /// otherwise. This is the load-bearing primitive of the `Error!`-during-
9268  /// `state_mut()` fix (tikz-cd 2001.08973).
9269  #[test]
9270  fn try_lookup_int_degrades_on_contention() {
9271    // Absent key, no contention → Some(0), matching lookup_int's default.
9272    assert_eq!(try_lookup_int("p1a_absent_key_xyz"), Some(0));
9273    // A live mutable borrow → None (cannot read), no panic.
9274    let _guard = state_root().borrow_mut();
9275    assert_eq!(try_lookup_int("MAX_ERRORS"), None);
9276  }
9277
9278  /// Reproduces tikz-cd 2001.08973: `push_value` into a non-VecDeque field
9279  /// hits the BUG-path `Error!`, which reads `MAX_ERRORS`. Before the fix,
9280  /// `push_value` held `state_mut!()` across that `Error!`, panicking
9281  /// "RefCell already mutably borrowed". It must now report the BUG and
9282  /// return Ok without panicking.
9283  #[test]
9284  fn push_value_bug_path_is_borrow_safe() {
9285    assign_value("p1a_bug_key", Stored::Int(7), Some(Scope::Global));
9286    let r = push_value("p1a_bug_key", Stored::Int(1));
9287    assert!(r.is_ok());
9288    // Same guarantee for the pop side.
9289    let r2 = pop_value("p1a_bug_key");
9290    assert!(r2.is_ok());
9291  }
9292
9293  /// `Scope::InPlace` (Perl `State.pm:175` 'inplace') is the same-level
9294  /// reassignment behind the Rhai `LookupDefinition(cs).push*` hook-splice
9295  /// (`install_definition(d, Some(Scope::InPlace))`). It must be neither Global
9296  /// nor Local across a group boundary — this is exactly the divergence
9297  /// @xworld21 flagged in PR #333 (r3623947537). Exercised on the Value table,
9298  /// which funnels through the identical `assign_internal` arm.
9299  #[test]
9300  fn inplace_scope_keeps_the_bindings_level() {
9301    // Scenario 1: a value bound ABOVE the group, mutated in-place from INSIDE
9302    // the group, PERSISTS past group exit (Local would have reverted it). This
9303    // is BookML's real case: patch an already-global def, mutation stays.
9304    assign_value("ip_above", Stored::Int(1), Some(Scope::Global));
9305    push_frame();
9306    assign_value("ip_above", Stored::Int(2), Some(Scope::InPlace));
9307    assert_eq!(
9308      lookup_int("ip_above"),
9309      2,
9310      "in-place mutation is active at once"
9311    );
9312    pop_frame().expect("pop group");
9313    assert_eq!(
9314      lookup_int("ip_above"),
9315      2,
9316      "in-place patch of an outer-bound value rode the outer binding past group \
9317       exit (Local would revert to 1)"
9318    );
9319
9320    // Scenario 2: a value LOCALLY redefined in the group, then mutated in-place,
9321    // REVERTS to the outer value at group exit (Global would have kept the
9322    // patch). The in-place edit rode the LOCAL binding, which is discarded.
9323    assign_value("ip_local", Stored::Int(1), Some(Scope::Global));
9324    push_frame();
9325    assign_value("ip_local", Stored::Int(2), Some(Scope::Local));
9326    assign_value("ip_local", Stored::Int(3), Some(Scope::InPlace));
9327    assert_eq!(
9328      lookup_int("ip_local"),
9329      3,
9330      "in-place mutated the local front"
9331    );
9332    pop_frame().expect("pop group");
9333    assert_eq!(
9334      lookup_int("ip_local"),
9335      1,
9336      "in-place patch of a locally-bound value was discarded with the group \
9337       (Global would keep 3)"
9338    );
9339  }
9340
9341  /// `is_scope_active` must track the FRONT value's truthiness, not key presence:
9342  /// `deactivate_scope` OVERWRITES the front value with `Stored::Bool(false)`
9343  /// instead of removing the entry, so a presence test reports a deactivated
9344  /// scope as still active.
9345  /// Perl writes the same test inline as `$$self{stash_active}{$scope}[0]`
9346  /// (State.pm L682). The region property `subfile_scope_at_depth` relies on
9347  /// (OXIDIZED_DESIGN #65) is the second assertion: an activation made inside a
9348  /// group is undone by that group, with no matching teardown call.
9349  #[test]
9350  fn scope_activity_tracks_value_not_presence() {
9351    let scope = arena::pin("t@scope@activity");
9352    assert!(!is_scope_active(scope), "unknown scope must be inactive");
9353
9354    activate_scope(scope);
9355    assert!(is_scope_active(scope), "activated scope must read active");
9356
9357    deactivate_scope(scope);
9358    assert!(
9359      !is_scope_active(scope),
9360      "a deactivated scope must read INACTIVE — `stash_active` still holds the \
9361       key, carrying Stored::Bool(false)"
9362    );
9363    // Deactivation is a GLOBAL assign, which replaces rather than layers: the
9364    // stack collapses to exactly that one falsy value. This is why the front
9365    // value is the whole state, and why presence cannot be the activity test.
9366    let depth = state!()
9367      .stash_active
9368      .get(&scope)
9369      .map(|entry| entry.len())
9370      .unwrap_or(0);
9371    assert_eq!(
9372      depth, 1,
9373      "global assign must overwrite, leaving one value — not stack a second"
9374    );
9375
9376    // A second deactivation must be a silent no-op. Perl gates on `[0]` being
9377    // TRUE (State.pm L700) precisely so the binding-pop below it does not run
9378    // twice; re-running it pops values `activate_scope` never pushed, which is
9379    // what Perl's "Unassigning wrong value for KEY from table T in
9380    // deactivateScope" warning reports.
9381    deactivate_scope(scope);
9382    assert!(
9383      !is_scope_active(scope),
9384      "still inactive after a second deactivate"
9385    );
9386    let depth2 = state!()
9387      .stash_active
9388      .get(&scope)
9389      .map(|entry| entry.len())
9390      .unwrap_or(0);
9391    assert_eq!(
9392      depth2, 1,
9393      "a second deactivation must not stack another value"
9394    );
9395  }
9396
9397  /// A DEACTIVATED scope must be activatable again — Perl gates `activateScope`
9398  /// on `!$$self{stash_active}{$scope}[0]` (State.pm L682), the front value's
9399  /// truthiness. Gating on key presence instead made the first deactivation
9400  /// permanent, since `deactivate_scope` leaves `Stored::Bool(false)` behind.
9401  /// Reached in Perl by the counter/label scopes, which deactivate the old
9402  /// reference number before activating the next (`Package.pm` L774-779).
9403  #[test]
9404  fn a_deactivated_scope_can_be_reactivated() {
9405    let scope = arena::pin("t@scope@reactivate");
9406    activate_scope(scope);
9407    deactivate_scope(scope);
9408    assert!(!is_scope_active(scope), "precondition: deactivated");
9409
9410    activate_scope(scope);
9411    assert!(
9412      is_scope_active(scope),
9413      "re-activation after deactivation must take effect (Perl State.pm L682)"
9414    );
9415  }
9416
9417  /// The self-terminating half: `activate_scope` marks `StashActive` with
9418  /// `Scope::Local`, so the enclosing group ends the region by construction.
9419  #[test]
9420  fn scope_activation_is_bounded_by_its_group() {
9421    let scope = arena::pin("t@scope@bounded");
9422    push_frame();
9423    activate_scope(scope);
9424    assert!(
9425      is_scope_active(scope),
9426      "active inside the group that opened it"
9427    );
9428    pop_frame().expect("pop group");
9429    assert!(
9430      !is_scope_active(scope),
9431      "the region must end with its group — no explicit deactivate_scope"
9432    );
9433  }
9434}
9435
9436#[cfg(test)]
9437mod let_copy_tests {
9438  use super::*;
9439
9440  fn macro_of(cs: &str, body: &str) -> Stored {
9441    Stored::Expandable(Rc::new(Expandable {
9442      cs: T_CS!(cs),
9443      paramlist: None,
9444      expansion: Tokens::new(Explode!(body)).into(),
9445      ..Expandable::default()
9446    }))
9447  }
9448
9449  fn holds(cs: &str, def: &Stored) -> bool {
9450    matches!((lookup_meaning(&T_CS!(cs)), def),
9451      (Some(Stored::Expandable(a)), Stored::Expandable(b)) if Rc::ptr_eq(&a, b))
9452  }
9453
9454  fn body_of(cs: &str) -> String {
9455    match lookup_meaning(&T_CS!(cs)) {
9456      Some(Stored::Expandable(def)) => match def.get_expansion() {
9457        Some(ExpansionBody::Tokens(body)) => body.to_string(),
9458        None => String::new(),
9459        Some(ExpansionBody::Closure(_)) => "<closure>".to_string(),
9460      },
9461      other => format!("{other:?}"),
9462    }
9463  }
9464
9465  /// A `\let` copy still sharing the definition follows it to the late one — a copy a group
9466  /// shadows as well, once the group ends; a copy of an older definition keeps its own; the source
9467  /// itself is left to the caller; no copies, nothing moves. No clone of the placeholder is held,
9468  /// so its holders are exactly its bindings and the walk ends on the last copy found.
9469  #[test]
9470  fn let_copies_follow_a_late_definition() {
9471    reset_thread_state();
9472    let job = T_CS!("\\lcjob");
9473    let older = macro_of("\\lcjob", "older");
9474    install_definition(older.clone(), None);
9475    let_i(&T_CS!("\\lcstale"), &job, None);
9476    install_definition(macro_of("\\lcjob", ""), None);
9477    let_i(&T_CS!("\\lccopy"), &job, None);
9478    let_i(&T_CS!("\\lcshadowed"), &job, None);
9479    push_frame();
9480    let_i(&T_CS!("\\lcshadowed"), &T_CS!("\\lcstale"), None);
9481
9482    let name = macro_of("\\lcjob", "name");
9483    assert_eq!(rebind_let_copies(&job, &name), 2);
9484    assert!(holds("\\lccopy", &name));
9485    assert!(
9486      holds("\\lcshadowed", &older),
9487      "the group's own binding is untouched"
9488    );
9489    pop_frame().expect("pop the probe frame");
9490    assert!(
9491      holds("\\lcshadowed", &name),
9492      "the shadowed copy was re-pointed in place"
9493    );
9494    assert!(
9495      holds("\\lcstale", &older),
9496      "a copy of an older definition keeps it"
9497    );
9498    assert_eq!(
9499      body_of("\\lcjob"),
9500      "",
9501      "the source is the caller's to install"
9502    );
9503
9504    install_definition(macro_of("\\lcsolo", "x"), None);
9505    assert_eq!(
9506      rebind_let_copies(&T_CS!("\\lcsolo"), &macro_of("\\lcsolo", "y")),
9507      0
9508    );
9509  }
9510}
9511
9512#[cfg(test)]
9513mod assignment_journal_tests {
9514  use super::*;
9515
9516  /// A rollback puts back a meaning's standing as a fallback guess with the meaning (`fallback_meanings`): a group-local
9517  /// `\let` of it under the journal cleared the standing, which the group's end does not put back (FM S2a.2 r9: the
9518  /// observer rehearsal's `\let\AND`, OmniBus's `\AND` under the siamart binding, 2409.10200); and a name the journal
9519  /// saw become a guess is none after it.
9520  #[test]
9521  fn rollback_restores_a_fallback_standing() {
9522    use crate::definition::origin::{DefinitionOrigin, with_origin};
9523    let guess = T_CS!("\\r9_fallback_standing_probe");
9524    let fresh = T_CS!("\\r9_fallback_fresh_probe");
9525    with_origin(DefinitionOrigin::Fallback, || {
9526      let_i(&guess, &T_LETTER!("x"), Some(Scope::Global))
9527    });
9528    assert!(is_fallback_meaning(&guess));
9529    let journal = begin_assignment_journal().expect("no journal open");
9530    push_frame();
9531    let_i(&guess, &T_LETTER!("y"), None);
9532    with_origin(DefinitionOrigin::Fallback, || {
9533      let_i(&fresh, &T_LETTER!("z"), Some(Scope::Global))
9534    });
9535    assert!(pop_frame().is_ok());
9536    assert!(
9537      !is_fallback_meaning(&guess),
9538      "the group's end leaves the standing cleared"
9539    );
9540    assert!(journal.rollback(), "the frames it began with are open");
9541    assert!(is_fallback_meaning(&guess), "the rollback puts it back");
9542    assert!(!is_fallback_meaning(&fresh) && lookup_meaning(&fresh).is_none());
9543  }
9544
9545  /// A rollback puts back a global and a local assignment made since the journal began; a kept journal keeps them.
9546  #[test]
9547  fn rollback_undoes_and_keep_keeps() {
9548    assign_value("j65e_probe", "before", Some(Scope::Global));
9549    let journal = begin_assignment_journal().expect("no journal open");
9550    push_frame();
9551    assign_value("j65e_probe", "inner", None);
9552    assign_value("j65e_probe", "global", Some(Scope::Global));
9553    assert!(pop_frame().is_ok());
9554    assert_eq!(lookup_string("j65e_probe"), "global");
9555    assert!(journal.rollback(), "the frames it began with are open");
9556    assert_eq!(lookup_string("j65e_probe"), "before");
9557    let journal = begin_assignment_journal().expect("no journal open");
9558    assign_value("j65e_probe", "kept", Some(Scope::Global));
9559    journal.keep();
9560    assert_eq!(lookup_string("j65e_probe"), "kept");
9561  }
9562
9563  /// A journal that began inside a frame closed since cannot roll back: the assignments stay.
9564  #[test]
9565  fn rollback_refused_when_its_frames_changed() {
9566    push_frame();
9567    let journal = begin_assignment_journal().expect("no journal open");
9568    assign_value("j65e_frames", "set", Some(Scope::Global));
9569    assert!(pop_frame().is_ok());
9570    assert!(!journal.rollback(), "a frame it began with is gone");
9571    assert_eq!(lookup_string("j65e_frames"), "set");
9572  }
9573
9574  /// A guard dropped while the state is borrowed leaves its journal stale: nothing records into it, and the next begin
9575  /// discards it.
9576  #[test]
9577  fn stale_journal_records_nothing_and_is_discarded() {
9578    let journal = begin_assignment_journal().expect("no journal open");
9579    {
9580      let _held = state_root().borrow_mut();
9581      drop(journal);
9582    }
9583    assert!(state!().journal.is_some(), "the guard could not close it");
9584    assign_value("j65e_stale", "x", Some(Scope::Global));
9585    assert!(
9586      state!()
9587        .journal
9588        .as_ref()
9589        .is_some_and(|j| j.saved.is_empty()),
9590      "a stale journal records nothing"
9591    );
9592    let journal = begin_assignment_journal().expect("the stale journal is discarded");
9593    journal.keep();
9594    assert!(state!().journal.is_none());
9595  }
9596}