Skip to main content

latexml_core/
dump_reader.rs

1//! Reader for Rust-native kernel dump files (produced by dump_writer.rs).
2//!
3//! Loads a dump file produced by `latexml_oxide --init=latex.ltx --dest=dump`
4//! and replays the state assignments into the engine.
5//!
6//! **Loading policy:** `M` and `V` entries replay with Perl-style global
7//! assignment semantics, matching `Core/Dumper.pm`'s `I()` / `V()` helpers.
8//! Runtime-state filters below are narrow exceptions for entries that should
9//! never be useful from a format dump.
10//!
11//! Format: tab-separated lines:
12//!   V\tKEY\tTYPE\tDATA             — value assignment
13//!   M\tKEY\tE\tCS\tNARGS\tFLAGS\tTOKENS — Expandable definition
14//!   M\tKEY\tN                       — None meaning (undefined)
15//!   M\tKEY\tT\tCC:TEXT              — Token meaning (let-assignment)
16//!   C\tCHAR\tCC\tVALUE             — catcode assignment
17//!   LC\tCHAR\tCH\tVALUE            — lccode assignment
18//!   UC\tCHAR\tCH\tVALUE            — uccode assignment
19//!   SC\tCHAR\tCH\tVALUE            — sfcode assignment
20//!   DC\tCHAR\tCH\tVALUE            — delcode assignment
21//!   MC\tCHAR\tCH\tVALUE            — mathcode assignment
22
23use std::{borrow::Cow, path::Path};
24
25use crate::{
26  common::{arena, numeric_ops::NumericOps, store::Stored},
27  definition::expandable::{Expandable, ExpandableOptions},
28  state::{self, Scope, TableName},
29  token::{Catcode, Token},
30  tokens::Tokens,
31};
32
33/// Load a Rust-native dump file into the current State.
34/// Returns the number of entries loaded.
35pub fn load_native_dump(path: &Path) -> Result<usize, String> {
36  let content = std::fs::read_to_string(path)
37    .map_err(|e| format!("Failed to read dump file {}: {}", path.display(), e))?;
38  let count = load_from_str_internal(&content, &path.display().to_string())?;
39  Ok(count)
40}
41
42/// Load dump data from a string (used by the embedded LaTeX kernel dump
43/// module — `latexml_engine/src/latex_dump.rs`).
44/// Returns the number of entries loaded.
45pub fn load_from_str(content: &str) -> Result<usize, String> {
46  // Labelled `<embedded:latex>` (mirroring `<embedded:plain>`) so the
47  // "Loaded N entries from ..." info line names which dump was loaded.
48  load_from_str_internal(content, "<embedded:latex>")
49}
50
51/// Backwards-compat alias kept until call sites are migrated. Both
52/// entry points now load unconditionally, mirroring Perl `I(...)` /
53/// `V(...)` (Core/Dumper.pm) which call `assign_internal('global')`
54/// without filters.
55pub fn load_from_str_plain(content: &str) -> Result<usize, String> {
56  load_from_str_internal(content, "<embedded:plain>")
57}
58
59/// Load a dump, naming `source` (a real path or an `<embedded TLyyyy>` label) in
60/// the single `dump_reader:loaded` Info line. The dump wrappers
61/// (`plain_dump`/`latex_dump`) use this so there is exactly ONE "loaded N
62/// entries from <source>" message per dump — they no longer emit a second,
63/// redundant `*_dump:loaded` line of their own.
64pub fn load_from_str_labeled(content: &str, source: &str) -> Result<usize, String> {
65  load_from_str_internal(content, source)
66}
67
68// Per-load context used to attach a nominal Locator to dump-installed
69// Expandables. Matches Perl #aaacdba2 (2026): dump-loaded definitions
70// should be traceable to the dump file + line, not report the arena's
71// internal location. Thread-local so concurrent loads (there are none
72// today, but the state is cooperative) don't clobber each other.
73thread_local! {
74  static CURRENT_LOAD_CTX: std::cell::Cell<Option<(arena::SymStr, u32)>> =
75    const { std::cell::Cell::new(None) };
76  /// PA/MPA aliases whose target wasn't defined at dump-load time.
77  /// Populated by `load_meaning`'s PA arm, drained by
78  /// `flush_deferred_aliases()` after `_constructs` finishes.
79  static DEFERRED_ALIASES: std::cell::RefCell<Vec<(Token, Token)>> =
80    const { std::cell::RefCell::new(Vec::new()) };
81}
82
83/// Replay any PA/MPA aliases that were deferred during dump load
84/// because their target was not yet defined. Call once after the
85/// post-dump definition pass (`_constructs`) has loaded.
86/// Returns `(applied, skipped)`.
87pub fn flush_deferred_aliases() -> (usize, usize) {
88  let pending: Vec<(Token, Token)> =
89    DEFERRED_ALIASES.with(|cell| std::mem::take(&mut *cell.borrow_mut()));
90  let mut applied = 0usize;
91  let mut skipped = 0usize;
92  for (cs_tok, target_tok) in pending {
93    // Target still undefined — the alias's target must be defined
94    // in some source we never load (e.g. expl3 intarrays that the
95    // short-circuit skips). Leave the key undefined; the engine's
96    // undefined-CS handler will cope at runtime.
97    if !state::has_meaning(&target_tok) {
98      skipped += 1;
99      continue;
100    }
101    // Perl `Lt()` parity: look up target's meaning, write it at
102    // alias key via `assign_internal('meaning', ..., 'global')`.
103    match state::lookup_meaning(&target_tok) {
104      Some(meaning) => {
105        state::assign_internal(
106          TableName::Meaning,
107          cs_tok.get_cs_name(),
108          meaning,
109          Some(Scope::Global),
110        );
111        applied += 1;
112      },
113      _ => {
114        skipped += 1;
115      },
116    }
117  }
118  (applied, skipped)
119}
120
121fn current_dump_locator() -> crate::common::locator::Locator {
122  if let Some((source, lineno)) = CURRENT_LOAD_CTX.with(|c| c.get()) {
123    crate::common::locator::Locator {
124      source,
125      from_line: lineno,
126      to_line: lineno,
127      from_column: 1,
128      to_column: 1,
129    }
130  } else {
131    crate::common::locator::Locator::default()
132  }
133}
134
135fn load_from_str_internal(content: &str, source_name: &str) -> Result<usize, String> {
136  // K1 provenance: dump-restored definitions carry the dump's origin.
137  let plain_dump = source_name == "<embedded:plain>"
138    || Path::new(source_name)
139      .file_name()
140      .and_then(|f| f.to_str())
141      .is_some_and(|f| f.starts_with("plain."));
142  let _origin = crate::definition::origin::OriginGuard::new(if plain_dump {
143    crate::definition::origin::DefinitionOrigin::Plain
144  } else {
145    crate::definition::origin::DefinitionOrigin::LatexDump
146  });
147  let mut count = 0;
148  let mut skipped = 0;
149  let mut errors = 0;
150  let source_sym = arena::pin(source_name);
151
152  for (lineno, line) in content.lines().enumerate() {
153    // Trim only CR (from CRLF line endings); `lines()` already strips LF.
154    // Do NOT use `trim()` here — it strips trailing tabs, which are part of
155    // the tab-separated format for entries with empty trailing fields (e.g.
156    // E-entries with empty body: `E\t<cs>\t<nargs>\t<flags>\t`).
157    let line = line.trim_end_matches('\r');
158    if line.is_empty() || line.starts_with('#') {
159      continue;
160    }
161
162    CURRENT_LOAD_CTX.with(|c| c.set(Some((source_sym, (lineno + 1) as u32))));
163
164    match parse_and_load(line) {
165      Ok(true) => count += 1,
166      Ok(false) => skipped += 1,
167      Err(e) => {
168        errors += 1;
169        if errors <= 10 {
170          Warn!(
171            "dump_reader",
172            "line",
173            s!(
174              "Line {}: {}: {}",
175              lineno + 1,
176              e,
177              &line[..line.len().min(80)]
178            )
179          );
180        }
181      },
182    }
183  }
184
185  if errors > 10 {
186    Warn!(
187      "dump_reader",
188      "errors",
189      s!("... and {} more errors", errors - 10)
190    );
191  }
192  Info!(
193    "dump_reader",
194    "loaded",
195    s!(
196      "Loaded {} entries from {} ({} skipped, {} errors)",
197      count,
198      source_name,
199      skipped,
200      errors
201    )
202  );
203
204  Ok(count)
205}
206
207/// Collect the control-sequence keys of every `M` (meaning) record in a dump,
208/// **without applying anything to State**.
209///
210/// This is a pure index scan over the same text [`load_from_str_labeled`]
211/// replays: one `splitn(3, '\t')` per line, keeping field 1 of the `M` rows and
212/// dropping everything else. No token bodies are parsed, no arena interning
213/// happens, and the State is not touched — so it is safe to call in a session
214/// that has deliberately *not* loaded the dump (see
215/// `latexml_engine::latex_kernel`, which uses it to answer "does the LaTeX
216/// kernel define this CS?" before committing to a pool load).
217///
218/// Keys are url-decoded exactly as `parse_and_load` decodes them, so a name
219/// found here compares equal to the CS name the loader would install.
220pub fn collect_meaning_keys(content: &str) -> rustc_hash::FxHashSet<Box<str>> {
221  let mut keys = rustc_hash::FxHashSet::default();
222  for line in content.lines() {
223    // `M` is the only table code whose keys are control-sequence names;
224    // the char-table rows (`C`/`LC`/…) and value rows (`V`/`IA`) are keyed
225    // by character or by internal parameter name.
226    let Some(rest) = line.strip_prefix("M\t") else {
227      continue;
228    };
229    let raw_key = rest.split('\t').next().unwrap_or("");
230    if raw_key.is_empty() {
231      continue;
232    }
233    if raw_key.contains('%') {
234      keys.insert(url_decode(raw_key).into_owned().into_boxed_str());
235    } else {
236      keys.insert(Box::from(raw_key));
237    }
238  }
239  keys
240}
241
242/// Parse a single dump line and load it. Returns Ok(true) if loaded,
243/// Ok(false) if filtered (e.g. corrupt MC/DC), Err on parse error.
244fn parse_and_load(line: &str) -> Result<bool, String> {
245  // Direct splitn iteration — saves the per-line Vec<&str> allocation
246  // that splitn(3).collect() was doing × 110k dump entries.
247  let mut it = line.splitn(3, '\t');
248  let table = it.next().ok_or("Too few fields")?;
249  let raw_key = match it.next() {
250    Some(k) => k,
251    None => return Err("Too few fields".into()),
252  };
253  // Key decode: Cow borrows the original &str when no `%` escape is
254  // present (the overwhelming majority). Saves a per-line allocation
255  // for the ~25k dump entries that have plain CS-name keys.
256  let key_cow = url_decode(raw_key);
257  let key = key_cow.as_ref();
258  let data = it.next().unwrap_or("");
259
260  match table {
261    // V: Value entries (registers, font metadata; a legacy per-slot
262    // `fontdimen_fontinfo_*_N` record goes into its font's array).
263    // An unconditional global write, bar `load_value`'s skip lists.
264    //
265    // Skip MAX_ERRORS: it was set to 1_000_000 in `ini_tex.rs` during
266    // dump-build (to let raw latex.ltx run through transient errors)
267    // and got captured into the dump. Loading that into a regular
268    // conversion lets runaway error cascades (e.g. AmS-TeX `\cases`
269    // mis-parse → 1M `\hbox`/`&` errors per paper) bypass the 10000
270    // default cap. Filter at read time so existing dumps are clean.
271    "V" if key == "MAX_ERRORS" => Ok(false),
272    "V" => load_value(key, data),
273    // IA: a font's parameter array (`\fontdimen`; expl3 keeps its intarrays
274    // there), one record per font. Body is `<len>\t<rle>` where rle is a
275    // comma-list of `v` or `vxn` runs; it loads as the font's whole array.
276    "IA" => load_intarray(key, data),
277    // M: Meaning entries (Expandable, Let-alias, Register, etc.).
278    //
279    // Perl-faithful: `plain_dump.pool.ltxml` and `latex_dump.pool.ltxml`
280    // emit one `I(...)` per Meaning entry, which is
281    // `assign_internal($STATE, 'meaning', $cs, $def, 'global')` —
282    // unconditional global write. No admission gate, no skip-if-defined.
283    // Match it: route every M entry to `load_meaning` directly.
284    "M" => load_meaning(key, data),
285    // LC/UC: case-mapping codes — safe, always load
286    "LC" => load_lccode(key, data),
287    "UC" => load_uccode(key, data),
288    // SC: space factor codes — safe, always load
289    "SC" => load_sfcode(key, data),
290    // C: catcodes — only for non-ASCII (>127). ASCII catcodes are set by
291    // the engine; loading from dump would conflict.
292    "C" => {
293      let ch = decode_char_key(key);
294      if ch.is_some_and(|c| c as u32 > 127) {
295        load_catcode(key, data)
296      } else {
297        Ok(false)
298      }
299    },
300    // Perl `Core/Dumper.pm:dump_mathcode/dump_delcode` write MC/DC for
301    // every state-set entry; the matching reader is unconditional apply
302    // (CLAUDE.md "Unconditional dump apply"). plain.tex / latex.ltx need
303    // letter mathcodes and `\delcode\(="0028300` etc. replayed from dump
304    // so `\cal abc` (cmsy fam 2) and delimited symbols decode correctly
305    // — without this, `decode_math_char` never fires for letters in the
306    // dump path and they get default-decoded to ASCII (no meaning/role).
307    "MC" => load_mathcode(key, data),
308    "DC" => load_delcode(key, data),
309    _ => Ok(false),
310  }
311}
312
313/// The `V` keys not applied (OXIDIZED_DESIGN_DIVERGENCES #449, OD ruling 12). Each is a run-time switch that the
314/// format build captures in a state no document has:
315/// - `INCLUDE_STYLES` and `INTERPRETING_DEFINITIONS`, for the dumps built before `State::new` assigned the first
316///   (Perl Core.pm L55-57) and the format's raw load put both back unchanged (content.rs `input_definitions`, Perl
317///   Package.pm:2369-2392): those carry `0` for each, where Perl's dump holds neither. Applied, `0` turns raw `.sty`
318///   loading off for every document, and inside a definitions file (a braced `\input` in a `.latexml` file or a raw
319///   preload) the rest of that load reads as content. A dump built now holds no `INCLUDE_STYLES` and an unapplied `N`
320///   for `INTERPRETING_DEFINITIONS`; the skips go once no stale dump is in use (a hand-set `LATEXML_DUMP_DIR`, a
321///   checkout's `resources/dumps`).
322/// - `CURRENT_INPUT_ENCODING` (no Perl counterpart), `UTF8` from the format's utf8.def (`utf8_def.rs`): applied, a code
323///   point 0x80-0xFF that `\DeclareUnicodeCharacter` (sect08.rs) declares before the document loads utf8.def stays at
324///   catcode 12, where pdflatex has 13 (`perfect_kernel_batchregfixw::latin1_char_before_utf8_inputenc_keeps_meaning`).
325const SKIP_VALUE_KEYS: &[&str] = &[
326  "INCLUDE_STYLES",
327  "INTERPRETING_DEFINITIONS",
328  "CURRENT_INPUT_ENCODING",
329];
330
331/// The load flags (`<file>_loaded`, `.ltxml_loaded`, `_raw_loaded`, OXIDIZED_DESIGN_DIVERGENCES #23), which Perl dumps
332/// and applies (latex_dump.pool.ltxml). The format is built under the pdfTeX persona: applied, they keep the `luatex`
333/// and `xetex` personas from re-reading the engine's expl3 code (`perfect_kernel_batch54::
334/// ltluatex_format_surface_under_luatex_profile`: l3backend-luatex.def's `\tex_pdfvariable:D` is undefined), and an
335/// author's old `expl3.sty` copy is read beside the format's
336/// (`perfect_kernel_batchltxown::shipped_expl3_xparse_l3keys2e_are_not_read`). OD #449.
337const SKIP_VALUE_CONTAINS: &[&str] = &["_loaded"];
338
339/// Load a value entry: `V\tKEY\tTYPE\tDATA`.
340///
341/// An unconditional global write, as Perl's `V()` (`Core/Dumper.pm` L59): the dumped value replaces whatever the
342/// key holds, bar the keys of [`SKIP_VALUE_KEYS`] and [`SKIP_VALUE_CONTAINS`] and a `N` (none) value, which are not
343/// applied.
344fn load_value(key: &str, data: &str) -> Result<bool, String> {
345  // A font parameter slot written as its own record (a dump from before the
346  // arrays, or a sparse one): into the font's array, as `IA` loads it.
347  if let Some((font_key, p)) = key
348    .rsplit_once('_')
349    .filter(|(font_key, _)| font_key.starts_with("fontdimen_fontinfo_"))
350    .and_then(|(font_key, p)| Some((font_key, p.parse::<usize>().ok()?)))
351    && let Some(sp) = data
352      .strip_prefix("D\t")
353      .and_then(|sp| sp.parse::<i64>().ok())
354  {
355    return Ok(state::set_font_parameter(font_key, p, sp));
356  }
357  if SKIP_VALUE_KEYS.contains(&key) || SKIP_VALUE_CONTAINS.iter().any(|part| key.contains(part)) {
358    return Ok(false);
359  }
360  // Perl `V()` parity (`Core/Dumper.pm` L59): every dumped Value entry
361  // maps to `assign_internal($STATE, 'value', $key, $val, 'global')` —
362  // unconditional global write. No skip-if-defined.
363
364  // Avoid the per-line Vec<&str> allocation — direct iter destructure
365  // matches the pattern used in load_meaning and parse_and_load.
366  let mut top_it = data.splitn(2, '\t');
367  let kind = top_it.next().ok_or("Missing value type")?;
368  let rest = top_it.next().unwrap_or("");
369  // Helper to default to "0" for numeric parses (the prior code used
370  // `rest_or_zero.parse()`).
371  let rest_or_zero = if rest.is_empty() { "0" } else { rest };
372
373  let value = match kind {
374    "N" => return Ok(false), // Don't load None values (would erase existing)
375    "B" => Stored::Bool(rest == "1"),
376    "I" => {
377      let n: i64 = rest_or_zero
378        .parse()
379        .map_err(|e| format!("Bad int: {}", e))?;
380      Stored::Int(n)
381    },
382    // "Nm": Stored::Number marker (distinct from "I" Stored::Int) —
383    // see dump_writer's Number serializer for rationale.
384    "Nm" => {
385      let n: i64 = rest_or_zero
386        .parse()
387        .map_err(|e| format!("Bad number: {}", e))?;
388      Stored::Number(crate::common::number::Number(n))
389    },
390    "S" => Stored::from(url_decode(rest).into_owned()),
391    "F" => {
392      // Stored::Font — written by dump_writer's Stored::Font arm.
393      // Format: F\tname=...\x1fsize=...\x1ffamily=...\x1f...
394      // Each unit-separator-delimited segment is `key=urlencoded_value`.
395      // Mirrors Perl `dump_font` (Core/Dumper.pm L281-284).
396
397      use crate::common::font::Font;
398      let mut font = Font::default();
399      for kv in rest.split('\x1f') {
400        if let Some((k, v)) = kv.split_once('=') {
401          let v_dec = url_decode(v).into_owned();
402          match k {
403            "name" => font.name = Some(Cow::Owned(v_dec)),
404            "family" => font.family = Some(Cow::Owned(v_dec)),
405            "series" => font.series = Some(Cow::Owned(v_dec)),
406            "shape" => font.shape = Some(Cow::Owned(v_dec)),
407            "encoding" => font.encoding = Some(Cow::Owned(v_dec)),
408            "language" => font.language = Some(Cow::Owned(v_dec)),
409            "mathstyle" => font.mathstyle = Some(Cow::Owned(v_dec)),
410            "opacity" => font.opacity = Some(Cow::Owned(v_dec)),
411            "size" => font.size = v_dec.parse().ok(),
412            "scale" => font.scale = v_dec.parse().ok(),
413            "emph" => font.emph = Some(v_dec == "1"),
414            "scripted" => font.scripted = Some(v_dec == "1"),
415            "mathstylestep" => font.mathstylestep = v_dec.parse().ok(),
416            "flags" => font.flags = v_dec.parse().ok(),
417            _ => {},
418          }
419        }
420      }
421      Stored::Font(std::rc::Rc::new(font))
422    },
423    "CH" => {
424      let n: u16 = rest_or_zero
425        .parse()
426        .map_err(|e| format!("Bad charcode: {}", e))?;
427      Stored::Charcode(n)
428    },
429    "CC" => {
430      let n: u8 = rest_or_zero
431        .parse()
432        .map_err(|e| format!("Bad catcode: {}", e))?;
433      Stored::Catcode(Catcode::from(n))
434    },
435    "T" => {
436      let tok = parse_token(rest)?;
437      Stored::Token(tok)
438    },
439    "TK" => {
440      let toks = parse_token_list(rest)?;
441      Stored::Tokens(Tokens::from(toks))
442    },
443    "D" => {
444      let n: i64 = rest_or_zero
445        .parse()
446        .map_err(|e| format!("Bad dimension: {}", e))?;
447      Stored::Dimension(crate::common::dimension::Dimension(n))
448    },
449    "G" => Stored::Glue(parse_glue(rest_or_zero)?),
450    "MD" => {
451      let n: i64 = rest_or_zero
452        .parse()
453        .map_err(|e| format!("Bad mudimension: {}", e))?;
454      Stored::MuDimension(crate::common::mudimension::MuDimension(n))
455    },
456    "MG" => Stored::MuGlue(parse_muglue(rest_or_zero)?),
457    "VD" => return Ok(false), // Don't load empty VecDeque (runtime state)
458    _ => return Ok(false),    // Unknown value type
459  };
460
461  // Perl `V()` (`Core/Dumper.pm` L59):
462  //   sub V { State::assign_internal($STATE,'value',$_[0],$_[1],'global'); }
463  // Direct table mutation, no dialect.
464  state::assign_internal(
465    TableName::Value,
466    arena::pin(key),
467    value,
468    Some(Scope::Global),
469  );
470  Ok(true)
471}
472
473/// Load an `IA` (intarray) record: a font's parameter array (`\fontdimen1`..,
474/// in sp; expl3 keeps its intarrays there), stored whole under its key, as
475/// Perl keeps `$$fontinfo{data}` (TeX_Fonts.pool.ltxml:131-146). Format: key =
476/// `fontdimen_<font>` (e.g. `fontdimen_fontinfo_cmr10 at 15sp`), data =
477/// `<len>\t<rle>`. RLE tokens are comma-separated; each is either `<v>` (one
478/// entry) or `<v>x<n>` (n consecutive entries of value v). Mismatched
479/// RLE-length vs declared len is an error.
480fn load_intarray(key: &str, data: &str) -> Result<bool, String> {
481  let mut it = data.splitn(2, '\t');
482  let len_s = it.next().unwrap_or("");
483  let rle = it.next().unwrap_or("");
484  let len: usize = len_s.parse().map_err(|e| format!("Bad IA length: {}", e))?;
485  let values = rle_decode_i64(rle)?;
486  if values.len() != len {
487    return Err(format!(
488      "IA length mismatch for {:?}: declared {} but RLE decoded to {}",
489      key,
490      len,
491      values.len()
492    ));
493  }
494  state::assign_internal(
495    TableName::Value,
496    arena::pin(key),
497    Stored::FontDimens(std::rc::Rc::new(std::cell::RefCell::new(values))),
498    Some(Scope::Global),
499  );
500  Ok(true)
501}
502
503/// Inverse of `dump_writer::rle_encode_i64`. Parses a comma-separated
504/// list of tokens, each `v` (single) or `vxn` (n copies of v). Empty
505/// input decodes to an empty vector.
506fn rle_decode_i64(s: &str) -> Result<Vec<i64>, String> {
507  let mut out = Vec::new();
508  if s.is_empty() {
509    return Ok(out);
510  }
511  for tok in s.split(',') {
512    if let Some(xi) = tok.find('x') {
513      let val: i64 = tok[..xi]
514        .parse()
515        .map_err(|e| format!("Bad RLE value in {:?}: {}", tok, e))?;
516      let cnt: usize = tok[xi + 1..]
517        .parse()
518        .map_err(|e| format!("Bad RLE count in {:?}: {}", tok, e))?;
519      for _ in 0..cnt {
520        out.push(val);
521      }
522    } else {
523      let val: i64 = tok
524        .parse()
525        .map_err(|e| format!("Bad RLE value {:?}: {}", tok, e))?;
526      out.push(val);
527    }
528  }
529  Ok(out)
530}
531
532/// Load a meaning entry: `M\tKEY\tTYPE\t...`.
533///
534/// An unconditional global write, as Perl's `I()`/`Im()` (`Core/Dumper.pm` L66-67): the dumped definition
535/// replaces any meaning the CS has, with no admission filter; a `N` (none) meaning is not applied.
536fn load_meaning(key: &str, data: &str) -> Result<bool, String> {
537  let cs_tok = T_CS!(key);
538
539  // Perl `I(...)` parity (`Core/Dumper.pm` L67): every dumped Meaning
540  // entry maps to `assign_internal($STATE, 'meaning', $cs, $def,
541  // 'global')` — unconditional global write. No skip-if-defined, no
542  // admission filter.
543
544  // Avoid the per-line Vec<&str> allocation — this fn runs ~80k times
545  // during latex.dump load (every M entry).
546  let mut top_it = data.splitn(2, '\t');
547  let kind = top_it.next().ok_or("Missing meaning type")?;
548  let rest = top_it.next().unwrap_or("");
549
550  match kind {
551    "N" => {
552      // None meaning — skip (don't define as undefined)
553      Ok(false)
554    },
555    "E" => {
556      // Expandable: E\tCSNAME\tNARGS\tFLAGS\tTOKENS[\tPROTO[\tV3_PARAMS]]
557      //
558      // Three historical shapes, read in fallback order:
559      //   v3 — 6th field present: structured Parameter records; bypasses
560      //        parse_parameters entirely. Only format that round-trips
561      //        Until:/Match: with catcoded delimiter tokens intact.
562      //   v2 — 5th field present: url-decoded prototype string fed to
563      //        parse_parameters. Good for {} / [] / DefToken / simple
564      //        typed params; loses brace-in-delimiter forms.
565      //   v1 — nargs only: "{}".repeat(nargs), all params flattened to
566      //        Plain. Kept as last resort so ancient dumps still load.
567      // Direct iter destructure — saves the Vec<&str>::collect()
568      // allocation × ~80k E entries.
569      let mut eit = rest.splitn(6, '\t');
570      let alias_field = eit.next().ok_or("Incomplete Expandable entry")?;
571      let nargs_field = eit.next().ok_or("Incomplete Expandable entry")?;
572      let flags_field = eit.next().ok_or("Incomplete Expandable entry")?;
573      let tok_field = eit.next().ok_or("Incomplete Expandable entry")?;
574      let proto_field = eit.next();
575      let v3_field = eit.next();
576
577      // eparts[0] is the alias-cs from the dump (Perl-side: the cs of
578      // the Definition object that this entry was let-aliased from).
579      // A `\let` copy still sharing its cs's definition is a `PA` row
580      // (`dump_writer::write_dump`, Perl's `Lt`) and never reaches here —
581      // `\exp_not:n` is `PA \unexpanded`, the very definition. An E row
582      // with a differing alias is a by-value copy: its cs was redefined
583      // after the `\let` (77 in the 2025 LaTeX dump, none of them a copy
584      // of a deferred command).
585      //
586      // We propagate the alias ONLY when the target is a known deferred
587      // command (`\unexpanded`, `\the`, `\detokenize`, `\showthe`), so
588      // such a copy still skips re-expansion inside `\edef` bodies
589      // (Perl `Gullet.pm:505`'s DEFERRED path). Any other alias would
590      // change `defn.get_cs_name()`'s return value, which feeds into
591      // many lookup paths and triggered infinite-loop regressions in
592      // `\@nil` handling. Keep blast radius tight.
593      const DEFERRED_NAMES: &[&str] = &["\\unexpanded", "\\the", "\\detokenize", "\\showthe"];
594      let alias_decoded = url_decode(alias_field);
595      let is_alias_diff = cs_tok.with_cs_name(|s| s != alias_decoded);
596      let alias_for_traits = if is_alias_diff && DEFERRED_NAMES.contains(&&*alias_decoded) {
597        Some(alias_decoded.into_owned())
598      } else {
599        None
600      };
601      let nargs: usize = nargs_field.parse().unwrap_or(0);
602      let flags = flags_field;
603      let tok_data = tok_field;
604      let proto_opt = proto_field.map(url_decode).filter(|s| !s.is_empty());
605      let v3_opt = v3_field.filter(|s| !s.is_empty());
606
607      let is_long = flags.contains('L');
608      let is_protected = flags.contains('P');
609
610      let expansion = parse_token_list(tok_data)?;
611
612      // Build parameter spec, preferring v3 structured → v2 proto →
613      // v1 nargs-repeat fallback. init_flag=true for both fallbacks:
614      // state is live at runtime so Parameter::init() can resolve
615      // readers via PARAMETER_TYPES.
616      let paramlist = if let Some(v3) = v3_opt {
617        match parse_parameters_v3(v3) {
618          Ok(pl) => pl,
619          Err(_) => proto_opt
620            .as_ref()
621            .and_then(|p| crate::common::def_parser::parse_parameters(p, &cs_tok, true).ok())
622            .flatten()
623            .or_else(|| {
624              if nargs > 0 {
625                let fallback = "{}".repeat(nargs);
626                crate::common::def_parser::parse_parameters(&fallback, &cs_tok, true)
627                  .ok()
628                  .flatten()
629              } else {
630                None
631              }
632            }),
633        }
634      } else {
635        // v2 path: no v3 field, fall back to proto-parsing (with the
636        // original silent-degrade-to-nargs behavior).
637        match proto_opt {
638          Some(proto) => match crate::common::def_parser::parse_parameters(&proto, &cs_tok, true) {
639            Ok(pl) => pl,
640            Err(_) if nargs > 0 => {
641              let fallback = "{}".repeat(nargs);
642              crate::common::def_parser::parse_parameters(&fallback, &cs_tok, true)
643                .map_err(|e| format!("Param parse fallback: {}", e))?
644            },
645            Err(_) => None,
646          },
647          None if nargs > 0 => {
648            let proto = "{}".repeat(nargs);
649            crate::common::def_parser::parse_parameters(&proto, &cs_tok, true)
650              .map_err(|e| format!("Param parse: {}", e))?
651          },
652          None => None,
653        }
654      };
655
656      let options = Some(ExpandableOptions {
657        long: is_long,
658        protected: is_protected,
659        nopack_parameters: true, // tokens already have ARG catcode
660        alias: alias_for_traits,
661        ..ExpandableOptions::default()
662      });
663
664      let expansion_body = Tokens::from(expansion).into();
665      match Expandable::new(cs_tok, paramlist, Some(expansion_body), options) {
666        Ok(mut exp) => {
667          exp.checks_par = flags.contains('T');
668          // Perl #aaacdba2: stamp dump-loaded definitions with a
669          // nominal Locator pointing at the dump file + line. Helps
670          // diagnostics attribute errors to the dump source rather
671          // than the arena's compile-site default.
672          exp.locator = current_dump_locator();
673          // Perl `I()` (`Core/Dumper.pm` L67):
674          //   sub I { State::assign_internal($STATE,'meaning',
675          //           $_[0]->getCSName, $_[0], 'global'); }
676          // Direct table mutation — no `:locked` gate, no add-only.
677          // CONFIRMED via probe (2026-04-27): Perl dump load bypasses
678          // the :locked gate. `installDefinition` (State.pm L502-517)
679          // checks :locked and refuses; `assign_internal` (State.pm
680          // L140) does not. Dumper's `I` shorthand calls `assign_internal`
681          // directly, so locked defs ARE silently overwritten by dump.
682          // Rust matches: this code calls `state::assign_internal`, not
683          // `install_definition`. Verified `\hidewidth` and `\leavevmode`
684          // get overwritten by dump entries despite earlier bootstrap defs.
685          state::assign_internal(
686            TableName::Meaning,
687            cs_tok.get_cs_name(),
688            Stored::from(exp),
689            Some(Scope::Global),
690          );
691          Ok(true)
692        },
693        Err(e) => Err(format!("Expandable creation failed: {}", e)),
694      }
695    },
696    "T" => {
697      // Token meaning. Perl `Im()` (`Core/Dumper.pm` L66):
698      //   sub Im { State::assign_internal($STATE,'meaning',
699      //            $_[0], $_[1], 'global'); }
700      // Direct write — no `\let`-chase, no chain follow.
701      let tok = parse_token(rest)?;
702      state::assign_internal(
703        TableName::Meaning,
704        cs_tok.get_cs_name(),
705        Stored::Token(tok),
706        Some(Scope::Global),
707      );
708      Ok(true)
709    },
710    "FD" => {
711      // FontDef: `FD\t<font_id>` — Perl `dump_primitive` (Core/Dumper.pm L383-389)
712      // emits this for `\font`-defined primitives. Install a Primitive whose
713      // `before_digest` mirrors `LaTeXML::Core::Definition::FontDef::invoke`
714      // (FontDef.pm L38-45):
715      //   1. lookup the fontinfo hash at <font_id>
716      //   2. assignValue(current_FontDef => $cs)
717      //   3. merge the font into $STATE->lookupValue('font')
718      // The fontinfo Stored::Font rides through the dump as a `V` entry with
719      // `F\t...` payload (see Stored::Font arm in dump_writer + the `F` arm
720      // in parse_value above).
721      use crate::definition::{BeforeDigestClosure, primitive::Primitive};
722      let font_id_raw = url_decode(rest).into_owned();
723      let font_id_pin = arena::pin(&font_id_raw);
724      let font_id_str = font_id_raw;
725      let cs_for_fontdef = cs_tok;
726      let merge_closure: BeforeDigestClosure = std::rc::Rc::new(move || {
727        state::assign_value("current_FontDef", Stored::Token(cs_for_fontdef), None);
728        if let Some(Stored::Font(f)) = state::lookup_value(&font_id_str) {
729          crate::binding::content::merge_font((*f).clone());
730        }
731        Ok(Vec::new())
732      });
733      let prim = Primitive {
734        cs: cs_tok,
735        before_digest: vec![merge_closure],
736        font_id: Some(font_id_pin),
737        ..Primitive::default()
738      };
739      state::assign_internal(
740        TableName::Meaning,
741        cs_tok.get_cs_name(),
742        Stored::Primitive(std::rc::Rc::new(prim)),
743        Some(Scope::Global),
744      );
745      Ok(true)
746    },
747    "PA" | "MPA" => {
748      // Primitive alias: PA\t<target_cs> — the entry's meaning is an
749      // Rc<Primitive> whose own cs is <target_cs>. If <target_cs> == key
750      // this is the "primary" entry (already provided by compiled bindings
751      // in _base.rs etc.); skip. Otherwise, replay `\let <key> <target>`
752      // so the Rc<Primitive> is shared just as it was when the dump was
753      // generated. This is how \tex_let:D, \tex_def:D, etc. survive the
754      // dump — without this the expl3.sty short-circuit guard
755      // `\ifx\csname tex_let:D\endcsname\relax` never fires and the 36k
756      // lines of expl3-code.tex get reprocessed on every run.
757      let target_cs_raw = url_decode(rest);
758      if target_cs_raw == key {
759        return Ok(false);
760      }
761      let target_tok = T_CS!(&target_cs_raw);
762      // Perl `Lt()` (`Core/Dumper.pm` L69-72):
763      //   sub Lt { my $d = State::lookupDefinition($STATE, T_CS($_[1]));
764      //            State::assign_internal($STATE,'meaning',$_[0],$d,'global'); }
765      // Look up the target's current Meaning entry, then writes that
766      // very Stored value at the alias key. Sharing the Rc preserves
767      // identity (e.g. \let\tex_let:D\let keeps the same Primitive Rc).
768      //
769      // If the target is not yet defined (load order has _constructs
770      // running after the dump for some let-aliases — e.g.
771      // `\let\a=\@tabacckludge`), defer until flush_deferred_aliases().
772      if !state::has_meaning(&target_tok) {
773        DEFERRED_ALIASES.with(|cell| {
774          cell.borrow_mut().push((cs_tok, target_tok));
775        });
776        return Ok(false);
777      }
778      let target_meaning = state::lookup_meaning(&target_tok);
779      if let Some(meaning) = target_meaning {
780        state::assign_internal(
781          TableName::Meaning,
782          cs_tok.get_cs_name(),
783          meaning,
784          Some(Scope::Global),
785        );
786      }
787      Ok(true)
788    },
789    "R" => {
790      // Register: R\tCS\tTYPE\tVALUE[\tMATHGLYPH][\tADDRESS]
791      // rparts[0] (internal CS name) is redundant with the outer key —
792      // same reasoning as the E arm; we skip the decode + alloc.
793      // ADDRESS field is a url-encoded address-slot key for allocated
794      // registers (Perl `\newcount\m@ne` → address='\count22'). When
795      // absent, address defaults to the CS name. Without this, dump_reader
796      // wrote `\m@ne`'s -1 to its CS-name slot, but `\m@ne`'s actual
797      // address (`\count22`) held the default 0 — `\settabs 20\columns`
798      // looped infinitely because `\m@ne == 0` never advanced `\count@`
799      // toward 0 in `\loop\ifnum\count@>\z@\@nother\repeat`.
800      // Direct iter destructure, mirroring the E-branch pattern.
801      let mut rit = rest.splitn(5, '\t');
802      let r_cs = rit.next().ok_or("Incomplete Register entry")?;
803      let r_type = rit.next().ok_or("Incomplete Register entry")?;
804      let r_value = rit.next().ok_or("Incomplete Register entry")?;
805      let r_glyph_field = rit.next();
806      let r_addr_field = rit.next();
807      let rtype = r_type;
808      let value_str = r_value;
809      let mathglyph = r_glyph_field
810        .filter(|s| !s.is_empty())
811        .and_then(|s| s.parse::<u32>().ok())
812        .and_then(char::from_u32);
813      let dump_address: Option<String> = r_addr_field
814        .filter(|s| !s.is_empty())
815        .map(|s| url_decode(s).into_owned());
816      // For register-aliases (M-line key != register's internal cs), the
817      // storage slot lives at the cs name, not the alias key. e.g.
818      //   M  \tex_endlinechar:D  R  \endlinechar  N  0
819      // means "\tex_endlinechar:D" is meaning-installed but the underlying
820      // register storage is at "\endlinechar". Without this, assignments
821      // through the alias (\tex_endlinechar:D = 32) write to a separate
822      // slot and the real \endlinechar stays unchanged — breaking
823      // \ExplSyntaxOn's `\tex_endlinechar:D = 32 \scan_stop:` line, which
824      // in turn breaks the entire dump-path expl3 whitespace handling
825      // (8 expl3 tests). Mirror Perl's address-via-internal-cs semantics.
826      let internal_cs_decoded = url_decode(r_cs);
827      let dump_address: Option<String> = dump_address.or_else(|| {
828        if internal_cs_decoded != *key && !internal_cs_decoded.is_empty() {
829          Some(internal_cs_decoded.into_owned())
830        } else {
831          None
832        }
833      });
834
835      use crate::{
836        common::number::Number,
837        definition::register::{Register, RegisterType, RegisterValue},
838      };
839
840      let (reg_type, reg_value) = match rtype {
841        "N" | "CD" => {
842          let n: i64 = value_str.parse().unwrap_or(0);
843          let rt = if rtype == "CD" {
844            RegisterType::CharDef
845          } else {
846            RegisterType::Number
847          };
848          (rt, Some(RegisterValue::Number(Number::new(n))))
849        },
850        "D" => {
851          let n: i64 = value_str.parse().unwrap_or(0);
852          (
853            RegisterType::Dimension,
854            Some(RegisterValue::Dimension(
855              crate::common::dimension::Dimension(n),
856            )),
857          )
858        },
859        "G" => (
860          RegisterType::Glue,
861          Some(RegisterValue::Glue(parse_glue(value_str)?)),
862        ),
863        "MG" => (
864          RegisterType::MuGlue,
865          Some(RegisterValue::MuGlue(parse_muglue(value_str)?)),
866        ),
867        "TK" => {
868          // Token register: value is comma-separated token list, or "0" for empty
869          let toks = if value_str == "0" || value_str.is_empty() {
870            Vec::new()
871          } else {
872            parse_token_list(value_str)?
873          };
874          (
875            RegisterType::Tokens,
876            Some(RegisterValue::Tokens(Tokens::from(toks))),
877          )
878        },
879        _ => return Ok(false),
880      };
881
882      // Perl-parity with def_register (binding/def/dialect.rs): store the
883      // initial value at the Register's `address` slot AND set `default`, so
884      // a subsequent `value_of` lookup — which reads state::with_value(address)
885      // and falls back to `default` — actually sees the dump's initial value.
886      // CharDefs read their immediate `value` field instead, so we skip the
887      // storage write for them.
888      let mut reg = Register {
889        cs: cs_tok,
890        register_type: reg_type,
891        value: reg_value.clone(),
892        default: if matches!(reg_type, RegisterType::CharDef) {
893          None
894        } else {
895          reg_value.clone()
896        },
897        mathglyph,
898        locator: current_dump_locator(),
899        ..Register::default()
900      };
901      // Set address: prefer dump-supplied address (allocated registers),
902      // fall back to CS name (direct registers like `\count1`).
903      let has_explicit_address = dump_address.is_some();
904      reg.address = dump_address.unwrap_or_else(|| key.to_string());
905      // Copy parameters from the base register at the address slot if
906      // present. The dump R-line carries no parameter spec, so without
907      // this an alias like `\tex_skip:D` (R \skip G 0) loses the
908      // `Number` index parameter that the base `\skip` register has.
909      // At digest time this caused `\tex_skip:D 0 = ... sp \scan_stop:`
910      // to skip the index reading entirely — the `0`, `=`, and rest got
911      // treated as a glue value and stranded tokens. Driver: expl3
912      // regex VM through `\__tl_analysis_a_store:`. See
913      // project_expl3_regex_vm_engine.md item #2.
914      if reg.parameters.is_none() && reg.address != key {
915        let address_tok = T_CS!(&reg.address);
916        if let Some(base_defn) = state::lookup_register_definition(&address_tok)
917          && let Some(params) = base_defn.parameters.clone()
918        {
919          reg.parameters = Some(params);
920        }
921      }
922      if !matches!(reg_type, RegisterType::CharDef)
923        && let Some(ref rv) = reg_value
924      {
925        // Perl `R(...)` register dump-restore: the address slot
926        // gets the initial value via `assign_internal('value', ...,
927        // 'global')`. Mirror Perl `def_register` behavior: when the
928        // address is allocated (different from CS) AND already has a
929        // value (from an earlier V entry), DO NOT overwrite — the V
930        // entry holds the runtime value (e.g. `\m@ne`'s `\count22 =
931        // -1`), and the Register's `value` field is just the default
932        // (typically 0). Without this guard, the M entry resets
933        // `\count22` to 0, breaking `\settabs 20\columns` (loops
934        // because `\m@ne` reads as 0 instead of -1, so
935        // `\advance\count@\m@ne` doesn't decrement).
936        let should_assign = !has_explicit_address || !state::has_value(&reg.address);
937        if should_assign {
938          state::assign_internal(
939            TableName::Value,
940            arena::pin(&reg.address),
941            rv.clone(),
942            Some(Scope::Global),
943          );
944        }
945      }
946      // Perl `I(...)` for the Register meaning entry — direct
947      // `assign_internal('meaning', ..., 'global')`, bypassing the
948      // `:locked` and add-only checks of install_definition.
949      state::assign_internal(
950        TableName::Meaning,
951        cs_tok.get_cs_name(),
952        Stored::from(reg),
953        Some(Scope::Global),
954      );
955      Ok(true)
956    },
957    _ => Ok(false),
958  }
959}
960
961/// Decode a character key from the dump. Handles:
962/// - Single characters: "A", "è"
963/// - URL-encoded control chars: "%19" (→ char 0x19), "%0A" (→ char 0x0A)
964fn decode_char_key(key: &str) -> Option<char> {
965  let decoded = url_decode(key);
966  decoded.chars().next()
967}
968
969/// Char-keyed table key: dump uses the single character as the key.
970/// `assign_internal` wants a SymStr — pin the single-char string.
971fn char_key(ch: char) -> arena::SymStr {
972  let mut buf = [0u8; 4];
973  arena::pin(ch.encode_utf8(&mut buf))
974}
975
976/// Load a catcode entry: C\tCHAR\tCC\tVALUE.
977/// Perl `Cc()` (`Core/Dumper.pm` L60): `assign_internal('catcode', ..., 'global')`.
978fn load_catcode(key: &str, data: &str) -> Result<bool, String> {
979  let ch = decode_char_key(key).ok_or_else(|| format!("Bad catcode char: {}", key))?;
980  let (tag, val_str) = data
981    .split_once('\t')
982    .ok_or_else(|| format!("Bad catcode data: {}", data))?;
983  if tag != "CC" {
984    return Err(format!("Bad catcode data: {}", data));
985  }
986  let cc: u8 = val_str
987    .parse()
988    .map_err(|e| format!("Bad catcode value: {}", e))?;
989  state::assign_internal(
990    TableName::Catcode,
991    char_key(ch),
992    Stored::Catcode(Catcode::from(cc)),
993    Some(Scope::Global),
994  );
995  Ok(true)
996}
997
998/// Load a lccode entry: LC\tCHAR\tCH\tVALUE.
999/// Perl `Lc()` (`Core/Dumper.pm` L63): `assign_internal('lccode', ..., 'global')`.
1000fn load_lccode(key: &str, data: &str) -> Result<bool, String> {
1001  let ch = decode_char_key(key).ok_or_else(|| format!("Bad lccode char: {}", key))?;
1002  let (tag, val_str) = data
1003    .split_once('\t')
1004    .ok_or_else(|| format!("Bad lccode data: {}", data))?;
1005  if tag != "CH" {
1006    return Err(format!("Bad lccode data: {}", data));
1007  }
1008  let val: u16 = val_str
1009    .parse()
1010    .map_err(|e| format!("Bad lccode value: {}", e))?;
1011  state::assign_internal(
1012    TableName::Lccode,
1013    char_key(ch),
1014    Stored::Charcode(val),
1015    Some(Scope::Global),
1016  );
1017  Ok(true)
1018}
1019
1020/// Load a uccode entry: UC\tCHAR\tCH\tVALUE.
1021/// Perl `Uc()` (`Core/Dumper.pm` L64): `assign_internal('uccode', ..., 'global')`.
1022fn load_uccode(key: &str, data: &str) -> Result<bool, String> {
1023  let ch = decode_char_key(key).ok_or_else(|| format!("Bad uccode char: {}", key))?;
1024  let (tag, val_str) = data
1025    .split_once('\t')
1026    .ok_or_else(|| format!("Bad uccode data: {}", data))?;
1027  if tag != "CH" {
1028    return Err(format!("Bad uccode data: {}", data));
1029  }
1030  let val: u16 = val_str
1031    .parse()
1032    .map_err(|e| format!("Bad uccode value: {}", e))?;
1033  state::assign_internal(
1034    TableName::Uccode,
1035    char_key(ch),
1036    Stored::Charcode(val),
1037    Some(Scope::Global),
1038  );
1039  Ok(true)
1040}
1041
1042/// Load an sfcode entry: SC\tCHAR\tCH\tVALUE.
1043/// Perl `Sc()` (`Core/Dumper.pm` L62): `assign_internal('sfcode', ..., 'global')`.
1044fn load_sfcode(key: &str, data: &str) -> Result<bool, String> {
1045  let ch = decode_char_key(key).ok_or_else(|| format!("Bad sfcode char: {}", key))?;
1046  let (tag, val_str) = data
1047    .split_once('\t')
1048    .ok_or_else(|| format!("Bad sfcode data: {}", data))?;
1049  if tag != "CH" {
1050    return Err(format!("Bad sfcode data: {}", data));
1051  }
1052  let val: u16 = val_str
1053    .parse()
1054    .map_err(|e| format!("Bad sfcode value: {}", e))?;
1055  state::assign_internal(
1056    TableName::Sfcode,
1057    char_key(ch),
1058    Stored::Charcode(val),
1059    Some(Scope::Global),
1060  );
1061  Ok(true)
1062}
1063
1064/// Load a delcode entry: DC\tCHAR\tCH\tVALUE
1065/// Mirrors Perl `Core/Dumper.pm:dump_delcode` round-trip.
1066fn load_delcode(key: &str, data: &str) -> Result<bool, String> {
1067  let ch = decode_char_key(key).ok_or_else(|| format!("Bad delcode char: {}", key))?;
1068  let (tag, val_str) = data
1069    .split_once('\t')
1070    .ok_or_else(|| format!("Bad delcode data: {}", data))?;
1071  if tag != "CH" {
1072    return Err(format!("Bad delcode data: {}", data));
1073  }
1074  let val: u16 = val_str
1075    .parse()
1076    .map_err(|e| format!("Bad delcode value: {}", e))?;
1077  state::assign_delcode(ch, val, Some(Scope::Global));
1078  Ok(true)
1079}
1080
1081/// Load a mathcode entry: MC\tCHAR\tCH\tVALUE
1082/// Mirrors Perl `Core/Dumper.pm:dump_mathcode` round-trip.
1083fn load_mathcode(key: &str, data: &str) -> Result<bool, String> {
1084  let ch = decode_char_key(key).ok_or_else(|| format!("Bad mathcode char: {}", key))?;
1085  let (tag, val_str) = data
1086    .split_once('\t')
1087    .ok_or_else(|| format!("Bad mathcode data: {}", data))?;
1088  if tag != "CH" {
1089    return Err(format!("Bad mathcode data: {}", data));
1090  }
1091  let val: u16 = val_str
1092    .parse()
1093    .map_err(|e| format!("Bad mathcode value: {}", e))?;
1094  state::assign_mathcode(ch, val, Some(Scope::Global));
1095  Ok(true)
1096}
1097
1098/// Parse a single token from "CC:TEXT" format
1099fn parse_token(s: &str) -> Result<Token, String> {
1100  let (cc_str, text) = s.split_once(':').ok_or("Missing ':' in token")?;
1101  let cc: u8 = cc_str.parse().map_err(|e| format!("Bad CC: {}", e))?;
1102  // Fast path: most token text fields have no `%` escapes, so pin the
1103  // &str directly — avoids the String allocation url_decode would make
1104  // even on its own fast path. Parsing the expl3 kernel alone produces
1105  // hundreds of thousands of token entries; every `to_owned()` avoided
1106  // here matters.
1107  let text_sym = if text.contains('%') {
1108    arena::pin(url_decode(text).as_ref())
1109  } else {
1110    arena::pin(text)
1111  };
1112  Ok(Token!(sym text_sym, Catcode::from(cc)))
1113}
1114
1115/// Parse comma-separated token list
1116fn parse_token_list(s: &str) -> Result<Vec<Token>, String> {
1117  if s.is_empty() {
1118    return Ok(Vec::new());
1119  }
1120  // Pre-size the Vec. Avg ~19.6 tokens/list across the 16k E-entries
1121  // in latex.dump; the default `.collect()` size_hint is (0, None) so
1122  // Vec resizes ~log2(19) ≈ 5 times per call. Counting commas first
1123  // (one extra pass over the str) eliminates those re-allocs.
1124  let n = s.bytes().filter(|b| *b == b',').count() + 1;
1125  let mut out = Vec::with_capacity(n);
1126  for tok in s.split(',') {
1127    out.push(parse_token(tok)?);
1128  }
1129  Ok(out)
1130}
1131
1132/// Decode the v3 structured Parameters encoding emitted by
1133/// `dump_writer::serialize_parameters_v3` (see that function's docstring
1134/// and `docs/archive/DUMP_FORMAT_PERL_ANALYSIS_2026-04-30.md` for the layout).
1135///
1136/// Returns `Ok(None)` for an empty record (no parameters); `Ok(Some(ps))`
1137/// on success; `Err` if any record is malformed. Each Parameter is
1138/// constructed via `Parameter::new(name, spec, Some(extras))`, which
1139/// calls `init()` — the reader function is resolved against the live
1140/// PARAMETER_TYPES table, mirroring the runtime path.
1141pub(crate) fn parse_parameters_v3(
1142  v3: &str,
1143) -> Result<Option<crate::parameter::Parameters>, String> {
1144  if v3.is_empty() {
1145    return Ok(None);
1146  }
1147  let mut params = Vec::new();
1148  for record in v3.split('\x1e') {
1149    // <name>\x1f<spec>\x1f<flags>\x1f<extras>
1150    let fields: Vec<&str> = record.splitn(4, '\x1f').collect();
1151    if fields.len() != 4 {
1152      return Err(format!(
1153        "v3 Parameter record has {} fields, expected 4",
1154        fields.len()
1155      ));
1156    }
1157    let name = url_decode(fields[0]);
1158    let spec = url_decode(fields[1]);
1159    let flags = fields[2];
1160    let extras_str = fields[3];
1161
1162    let extras = if extras_str.is_empty() {
1163      Vec::new()
1164    } else {
1165      extras_str
1166        .split('\x1d')
1167        .map(|tok_list| parse_token_list(tok_list).map(Tokens::new))
1168        .collect::<Result<Vec<_>, _>>()?
1169    };
1170
1171    let mut param = crate::parameter::Parameter::new(name, spec, Some(extras))
1172      .map_err(|e| format!("Parameter::new failed: {}", e))?;
1173
1174    // Apply flags after construction — Parameter::new + init() handle
1175    // the reader side, but novalue/optional are struct-level booleans
1176    // that the spec-driven init() may or may not have set (e.g. "Optional"
1177    // prefix auto-sets optional, but we want explicit round-trip).
1178    for flag in flags.split(';').filter(|s| !s.is_empty()) {
1179      match flag {
1180        "n=1" => param.novalue = true,
1181        "o=1" => param.optional = true,
1182        _ => {
1183          // Unknown flag — ignore for forward compat; future flags
1184          // added to the writer shouldn't break older readers.
1185        },
1186      }
1187    }
1188    params.push(param);
1189  }
1190  if params.is_empty() {
1191    Ok(None)
1192  } else {
1193    Ok(Some(crate::parameter::Parameters::new(params)))
1194  }
1195}
1196
1197pub(crate) fn url_decode(s: &str) -> Cow<'_, str> {
1198  // Fast path: the overwhelming majority of dump entries have no `%`
1199  // escapes in their key or proto fields, so the field itself is the
1200  // answer (~68k decodes per conversion; most callers only compare or pin).
1201  if !s.contains('%') {
1202    return Cow::Borrowed(s);
1203  }
1204  let mut result = String::with_capacity(s.len());
1205  let mut chars = s.chars();
1206  while let Some(ch) = chars.next() {
1207    if ch == '%' {
1208      let hex: String = chars.by_ref().take(2).collect();
1209      if let Ok(byte) = u8::from_str_radix(&hex, 16) {
1210        result.push(byte as char);
1211      }
1212    } else {
1213      result.push(ch);
1214    }
1215  }
1216  Cow::Owned(result)
1217}
1218
1219/// Parse a serialized Glue value: "skip,pN,pfN,mN,mfN"
1220fn parse_glue(s: &str) -> Result<crate::common::glue::Glue, String> {
1221  use crate::common::glue::{FillCode, Glue};
1222  let mut skip = 0i64;
1223  let mut plus = None;
1224  let mut pfill = None;
1225  let mut minus = None;
1226  let mut mfill = None;
1227  for (i, part) in s.split(',').enumerate() {
1228    if i == 0 {
1229      skip = part.parse().map_err(|e| format!("Bad glue skip: {}", e))?;
1230    } else if let Some(rest) = part.strip_prefix("pf") {
1231      pfill = FillCode::new(rest.parse::<usize>().unwrap_or(0));
1232    } else if let Some(rest) = part.strip_prefix('p') {
1233      plus = Some(rest.parse().map_err(|e| format!("Bad glue plus: {}", e))?);
1234    } else if let Some(rest) = part.strip_prefix("mf") {
1235      mfill = FillCode::new(rest.parse::<usize>().unwrap_or(0));
1236    } else if let Some(rest) = part.strip_prefix('m') {
1237      minus = Some(rest.parse().map_err(|e| format!("Bad glue minus: {}", e))?);
1238    }
1239  }
1240  Ok(Glue {
1241    skip,
1242    plus,
1243    pfill,
1244    minus,
1245    mfill,
1246  })
1247}
1248
1249/// Parse a serialized MuGlue value (same format as Glue)
1250fn parse_muglue(s: &str) -> Result<crate::common::muglue::MuGlue, String> {
1251  use crate::common::{glue::FillCode, muglue::MuGlue};
1252  let mut skip = 0i64;
1253  let mut plus = None;
1254  let mut pfill = None;
1255  let mut minus = None;
1256  let mut mfill = None;
1257  for (i, part) in s.split(',').enumerate() {
1258    if i == 0 {
1259      skip = part
1260        .parse()
1261        .map_err(|e| format!("Bad muglue skip: {}", e))?;
1262    } else if let Some(rest) = part.strip_prefix("pf") {
1263      pfill = FillCode::new(rest.parse::<usize>().unwrap_or(0));
1264    } else if let Some(rest) = part.strip_prefix('p') {
1265      plus = Some(
1266        rest
1267          .parse()
1268          .map_err(|e| format!("Bad muglue plus: {}", e))?,
1269      );
1270    } else if let Some(rest) = part.strip_prefix("mf") {
1271      mfill = FillCode::new(rest.parse::<usize>().unwrap_or(0));
1272    } else if let Some(rest) = part.strip_prefix('m') {
1273      minus = Some(
1274        rest
1275          .parse()
1276          .map_err(|e| format!("Bad muglue minus: {}", e))?,
1277      );
1278    }
1279  }
1280  Ok(MuGlue {
1281    skip,
1282    plus,
1283    pfill,
1284    minus,
1285    mfill,
1286  })
1287}
1288
1289#[cfg(test)]
1290mod tests {
1291  use super::*;
1292
1293  #[test]
1294  fn test_load_native_dump_inline() {
1295    // Test with inline tab-separated dump content (no external file dependency)
1296    let content = "V\tcount@\tI\t42\nM\t\\mymacro\tE\t\\mymacro\t1\t\t6:1,6:2\n";
1297    let count = load_from_str(content).unwrap();
1298    assert!(
1299      count > 0,
1300      "Expected entries loaded from inline dump, got {}",
1301      count
1302    );
1303  }
1304
1305  #[test]
1306  fn test_catcode_loading_nonascii() {
1307    // Only non-ASCII catcodes are loaded from the dump
1308    let content = "C\t\u{00e8}\tCC\t12\n"; // è → catcode 12 (OTHER)
1309    let count = load_from_str(content).unwrap();
1310    assert!(count > 0, "Expected non-ASCII catcode entry loaded");
1311  }
1312
1313  #[test]
1314  fn test_lccode_loading() {
1315    let content = "LC\t\u{00c8}\tCH\t232\n"; // È → lccode 232 (è)
1316    let count = load_from_str(content).unwrap();
1317    assert!(count > 0, "Expected lccode entry loaded");
1318  }
1319
1320  // --- RLE decoder tests (intarray consolidation) ---
1321
1322  #[test]
1323  fn rle_decode_empty() {
1324    assert_eq!(rle_decode_i64("").unwrap(), Vec::<i64>::new());
1325  }
1326
1327  #[test]
1328  fn rle_decode_single() {
1329    assert_eq!(rle_decode_i64("5").unwrap(), vec![5]);
1330  }
1331
1332  #[test]
1333  fn rle_decode_single_run() {
1334    assert_eq!(rle_decode_i64("5x3").unwrap(), vec![5, 5, 5]);
1335  }
1336
1337  #[test]
1338  fn rle_decode_mixed() {
1339    assert_eq!(rle_decode_i64("1,2x2,3x3,1").unwrap(), vec![
1340      1, 2, 2, 3, 3, 3, 1
1341    ]);
1342  }
1343
1344  #[test]
1345  fn rle_decode_negative() {
1346    assert_eq!(rle_decode_i64("-5").unwrap(), vec![-5]);
1347    assert_eq!(rle_decode_i64("-5x3").unwrap(), vec![-5, -5, -5]);
1348  }
1349
1350  #[test]
1351  fn rle_decode_long_run() {
1352    let v = rle_decode_i64("218x10000").unwrap();
1353    assert_eq!(v.len(), 10000);
1354    assert!(v.iter().all(|&x| x == 218));
1355  }
1356
1357  #[test]
1358  fn rle_decode_malformed_returns_err() {
1359    assert!(rle_decode_i64("abc").is_err());
1360    assert!(rle_decode_i64("5xabc").is_err());
1361    assert!(rle_decode_i64("5x").is_err());
1362  }
1363
1364  // --- IA load → state assignment tests ---
1365
1366  #[test]
1367  fn ia_load_stores_the_font_parameter_array() {
1368    // A key of its own, so that no other test's font parameters collide.
1369    let key = "fontdimen_fontinfo_ia_test at 1sp";
1370    load_from_str(&format!("IA\t{key}\t3\t10,20x2\n")).unwrap();
1371    let params: Vec<_> = (1..=4).map(|p| state::font_parameter(key, p)).collect();
1372    assert_eq!(params, [Some(10), Some(20), Some(20), None]);
1373  }
1374
1375  #[test]
1376  fn ia_load_length_mismatch_errors() {
1377    // Declared len 5 but RLE only decodes to 3 → error
1378    let content = "IA\tia_mismatch_prefix\t5\t10,20,30\n";
1379    // load_from_str collects per-line errors; verify the malformed IA
1380    // line did NOT successfully load anything.
1381    let count = load_from_str(content).unwrap_or(0);
1382    assert_eq!(count, 0, "Length-mismatch IA should not load");
1383  }
1384
1385  // --- Backward-compat: V-records-only dumps (pre-IA format) ---
1386
1387  #[test]
1388  fn v_record_dimension_still_loads() {
1389    // This is the pre-IA storage format: one V record per slot.
1390    // dump_reader must still accept these so older / partner-machine
1391    // dumps load correctly.
1392    let prefix = "v_backcompat_prefix";
1393    let content = format!("V\t{}_1\tD\t111\nV\t{}_2\tD\t222\n", prefix, prefix);
1394    load_from_str(&content).unwrap();
1395
1396    use crate::{
1397      common::{dimension::Dimension, store::Stored},
1398      state,
1399    };
1400
1401    assert_eq!(
1402      state::lookup_value(&format!("{}_1", prefix)),
1403      Some(Stored::Dimension(Dimension(111)))
1404    );
1405    assert_eq!(
1406      state::lookup_value(&format!("{}_2", prefix)),
1407      Some(Stored::Dimension(Dimension(222)))
1408    );
1409  }
1410
1411  #[test]
1412  fn v_record_font_parameter_slot_loads_into_the_font_array() {
1413    // A dump from before the arrays wrote a sparse font (expl3's `\intarray_new`
1414    // sets slots 1-8 and the last) one V record per slot.
1415    let key = "fontdimen_fontinfo_v_test at 1sp";
1416    let content = format!("V\t{key}_1\tD\t0\nV\t{key}_30\tD\t7\n");
1417    load_from_str(&content).unwrap();
1418    assert_eq!(state::font_parameter(key, 1), Some(0));
1419    assert_eq!(state::font_parameter(key, 30), Some(7));
1420    // A font without an array gets one; growth is zeros (tex.web §580).
1421    assert_eq!(state::font_parameter(key, 29), Some(0));
1422    assert_eq!(state::lookup_value(&format!("{key}_30")), None);
1423  }
1424
1425  #[test]
1426  fn v_record_not_a_font_parameter_slot_stays_a_value() {
1427    use crate::common::{dimension::Dimension, store::Stored};
1428    // No `fontinfo_` font, a non-numeric or an empty slot: plain values.
1429    for key in [
1430      "fontdimen_cmr10_15",
1431      "fontdimen_fontinfo_v_test2 at 1sp_abc",
1432      "fontdimen_fontinfo_v_test3 at 1sp_",
1433    ] {
1434      load_from_str(&format!("V\t{key}\tD\t9\n")).unwrap();
1435      assert_eq!(
1436        state::lookup_value(key),
1437        Some(Stored::Dimension(Dimension(9))),
1438        "{key}"
1439      );
1440    }
1441  }
1442}