Skip to main content

latexml_core/
dump_writer.rs

1//! Writer for Rust-native kernel dump files.
2//!
3//! Serializes the State diff (from snapshot/diff_from_snapshot) into a
4//! compact text format that can be loaded back efficiently.
5//!
6//! This is the "DumpFile" equivalent from Perl's TeX_Job.pool.ltxml.
7//! The workflow follows Perl's Makefile.PL "make formats" scaffold:
8//!   1. take_snapshot() — before processing latex.ltx
9//!   2. Process latex.ltx through the engine
10//!   3. diff_snapshot() — find what changed
11//!   4. write_dump() — serialize the diff
12//!   5. At runtime: load_dump() restores the state
13
14use std::{io::Write, path::Path};
15
16use crate::definition::Definition; // trait for get_expansion(), get_cs(), etc.
17use crate::{
18  common::{arena, numeric_ops::NumericOps, store::Stored},
19  state::TableName,
20};
21
22/// Write a state diff to a dump file.
23/// Returns the number of entries successfully written.
24///
25/// Writes in three ordered sections, matching Perl's
26/// `TeX_Job.pool.ltxml::DumpFile` which separates
27/// `@cmds_early` / `@cmds` / `@cmds_late`:
28///
29///   1. **cmds_early** — M:PA / M:MPA let-aliases that are still the **bootstrap snapshot's**
30///      definition of their target (e.g. `\tex_let:D → \let`, `\tex_def:D → \def`,
31///      `\tex_jobname:D → \jobname`). Applied first because their targets are always available
32///      (they're in the bootstrap pool we loaded unconditionally before this dump).
33///   2. **cmds** (regular) — V / M:E / M:T / R / C / LC / UC / SC / MC / DC entries: data,
34///      expandable definitions, registers, codes — including a `\let` copy of a token-bodied
35///      macro whose target was redefined since, written by value.
36///   3. **cmds_late** — M:PA / M:MPA let-aliases that are the target's **current** definition,
37///      defined by this dump (e.g. `\bool_if_exist:NTF → \cs_if_exist:NTF`). Applied last so the
38///      target is installed before the alias fires.
39///
40/// The early/late split requires the caller (ini_tex) to have staged a
41/// snapshot via `state::stage_snapshot("bootstrap")`. If no snapshot is
42/// available, all aliases are emitted as `late` (safe — they just wait
43/// until after regular entries).
44///
45/// `sources` are header lines naming the format files the dump was built from
46/// (`latexml_engine::dump_paths::SourceStamp::header_line`), which a loader checks against the TeX tree
47/// it reads packages from.
48pub fn write_dump(
49  path: &Path,
50  entries: &[(TableName, arena::SymStr, Stored)],
51  sources: &[String],
52) -> Result<usize, String> {
53  let mut file =
54    std::fs::File::create(path).map_err(|e| format!("Failed to create dump file: {}", e))?;
55
56  writeln!(file, "# latexml-oxide kernel dump v3").ok();
57  writeln!(
58    file,
59    "# Generated by dump_writer, {} entries",
60    entries.len()
61  )
62  .ok();
63  for source in sources {
64    writeln!(file, "{source}").ok();
65  }
66  writeln!(file, "# Format: <table>\\t<key>\\t<data>").ok();
67  writeln!(file, "#   <table> = M | V | C | LC | UC | SC | MC | DC").ok();
68  writeln!(file, "#   <data> depends on <table>:").ok();
69  writeln!(
70    file,
71    "#     M/E:   E\\t<cs>\\t<nargs>\\t<flags>\\t<body>\\t<proto>\\t<v3_params>"
72  )
73  .ok();
74  writeln!(
75    file,
76    "#            v3_params encodes each Parameter structurally so Until:/Match:"
77  )
78  .ok();
79  writeln!(
80    file,
81    "#            delimiter tokens round-trip (see docs/archive/DUMP_FORMAT_PERL_ANALYSIS_2026-04-30.md)."
82  )
83  .ok();
84  writeln!(
85    file,
86    "#     M/PA:  PA\\t<target_cs>   (MPA for math primitives)"
87  )
88  .ok();
89  writeln!(file, "#     M/T:   T\\t<meaning_token>").ok();
90  writeln!(
91    file,
92    "#     M/R:   R\\t<cs>\\t<rtype>\\t<value>[\\t<mathglyph>]"
93  )
94  .ok();
95  writeln!(
96    file,
97    "#     M/N:   N                     (None-meaning sentinel)"
98  )
99  .ok();
100  writeln!(
101    file,
102    "#     V:     <type>\\t<value>       (B,I,S,CH,T,TK,N,F,G,MG,D,MD,VD)"
103  )
104  .ok();
105  writeln!(file, "#     C:                  CC\\t<u8>   (catcode)").ok();
106  writeln!(
107    file,
108    "#     DC/LC/UC/SC/MC:     CH\\t<u32>  (char-indexed table entries)"
109  )
110  .ok();
111  writeln!(
112    file,
113    "#   <flags> = subset of {{L, P, T}} (long, protected, checks \\par: tex.web §392)"
114  )
115  .ok();
116  writeln!(
117    file,
118    "#   All keys and proto are url-encoded (%09 for tab etc.); token body"
119  )
120  .ok();
121  writeln!(
122    file,
123    "#   tokens use the form <catcode_int>:<url_encoded_text> joined by commas."
124  )
125  .ok();
126
127  // Read the bootstrap snapshot so we can classify each alias's target
128  // as pre-existing (→ early) or defined-during-load (→ late).
129  let bootstrap_snap = crate::state::get_staged_snapshot("bootstrap");
130
131  // Pre-serialize + partition. Skipped keys (ver@..., unserializable
132  // values) fall out naturally.
133  let mut early_aliases: Vec<(String, String, String)> = Vec::new();
134  let mut regular: Vec<(String, String, String)> = Vec::new();
135  let mut late_aliases: Vec<(String, String, String)> = Vec::new();
136  let mut skipped = 0usize;
137
138  // Perl TeX_Job.pool.ltxml:150,153 walks `sort @tables` and, in each, `sort keys %$table`, so
139  // every section of its dump is in (table name, key) order. The diff arrives in hash-table order,
140  // which differs from one binary to the next (det354: one key set in 55 orders across 173 dumps),
141  // and the dump is applied in file order, so the order also fixes the symbol ids of every
142  // conversion. Sorting here makes the dump a function of its content alone. A table's `Display`
143  // name is Perl's capitalized (`Catcode` .. `Value`), so it sorts as Perl's `@tables` do.
144  let mut ordered: Vec<(String, String, &(TableName, arena::SymStr, Stored))> = entries
145    .iter()
146    .map(|entry| (entry.0.to_string(), arena::to_string(entry.1), entry))
147    .collect();
148  ordered.sort_unstable_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));
149
150  for (_, key_str, (table, _, value)) in ordered {
151    let table_code = table_to_code(*table);
152
153    // Skip \ver@ package version markers (runtime metadata, not definitions)
154    if key_str.starts_with("\\ver@") {
155      skipped += 1;
156      continue;
157    }
158
159    // Skip MAX_ERRORS — `ini_tex.rs:189` raises it to 1_000_000 during
160    // dump-build (so raw latex.ltx + expl3-code.tex can run through
161    // transient errors). It must NOT leak into runtime conversions:
162    // a 1M cap lets runaway error cascades (e.g. AmS-TeX `\cases` mis-
163    // parse → 1M `\hbox`/`&` per paper, math0205073) bypass the
164    // 10000 default. dump_reader has a parallel filter for the
165    // already-shipped dumps; this filter keeps future regenerations
166    // clean.
167    if matches!(*table, TableName::Value) && key_str == "MAX_ERRORS" {
168      skipped += 1;
169      continue;
170    }
171    // Skip the files a run read as content (`binding::content::CONTENT_FILES`): the format's own sources are no
172    // document's text, and a dumped list would stand in a conversion's for the files it reads.
173    if matches!(*table, TableName::Value) && key_str == crate::binding::content::CONTENT_FILES {
174      skipped += 1;
175      continue;
176    }
177
178    // Skip the file-IO bookkeeping family (`is_file_io_bookkeeping`). The
179    // dump is applied WHILE the document's preload is being read (the
180    // LaTeX pool+dump load runs inside `latexml.sty`), so any per-load
181    // state it carries clobbers the live values: a dumped
182    // `\@currnamestack` = empty made `latexml.sty`'s `\@popfilename` pop
183    // nothing, `\catcode`\@` then read an empty number ("Missing number")
184    // and every later `@`-name broke — a4wide 3 → 35 errors, every
185    // siunitx tabular (2026-09-17, cortex dump regeneration).
186    if matches!(*table, TableName::Meaning) && is_file_io_bookkeeping(&key_str) {
187      skipped += 1;
188      continue;
189    }
190
191    // Skip token-list register VALUES whose body contains a self-`\the`
192    // reference. latex.ltx L10564-10580 sets `\frozen@everymath` =
193    // `{... \the\everymath}` then allocates a NEW `\everymath` via
194    // `\newtoks`. Our `\newtoks` doesn't fully detach the new register's
195    // slot from the frozen alias's, so the body lands on `\everymath`'s
196    // value slot — `\the\everymath` then expands recursively at math
197    // entry, blowing the token limit. Until the `\newtoks`/`\let`
198    // slot-aliasing is fixed at the dialect level, the safest cure is
199    // to drop the corrupted self-referential capture; runtime
200    // re-evaluation of latex.ltx's hook chain (or LaTeXML's own
201    // `\everymath`/`\everydisplay` setup) repopulates correctly.
202    if matches!(*table, TableName::Value)
203      && matches!(
204        key_str.as_str(),
205        "\\everymath"
206          | "\\everydisplay"
207          | "\\everyhbox"
208          | "\\everyvbox"
209          | "\\everycr"
210          | "\\everyjob"
211          | "\\everypar"
212          | "\\everyeof"
213      )
214    {
215      // Confirm the loop pattern before dropping (don't suppress
216      // valid hook contributions on engines with sound aliasing).
217      if let Stored::Tokens(tks) = value {
218        let body = tks.unlist_ref();
219        let needle_cs = key_str.clone();
220        let has_self_the = body.iter().any(|t| t.with_str(|s| s == "\\the"))
221          && body.iter().any(|t| t.with_str(|s| s == needle_cs));
222        if has_self_the {
223          skipped += 1;
224          continue;
225        }
226      }
227    }
228
229    // Perl #2771 (2026-03-13) + upstream IGNORED_SYMBOLS: these are
230    // runtime-only Value entries — control-flow counters, and large
231    // registered-rule tables that can't meaningfully round-trip through
232    // the dump (they hold closures, cross-refs, or re-populate during
233    // engine init anyway). Match Perl's TeX_Job.pool.ltxml list.
234    if matches!(*table, TableName::Value)
235      && matches!(
236        key_str.as_str(),
237        "if_stack"
238          | "DOCUMENT_REWRITE_RULES"
239          | "PARAMETER_TYPES"
240          | "TAG_PROPERTIES"
241          | "MATH_LIGATURES"
242          | "TEXT_LIGATURES"
243      )
244    {
245      skipped += 1;
246      continue;
247    }
248
249    // Perl IGNORED_SYMBOLS: meaning:\lnot, meaning:\to are skipped because
250    // pre-2017 TeXlive let-aliased \lnot → \neg and \to → \rightarrow,
251    // which would gratuitously diverge tests across TL versions.
252    // Mirror Perl `TeX_Job.pool.ltxml` IGNORED_SYMBOLS L104-107.
253    if matches!(*table, TableName::Meaning) && matches!(key_str.as_str(), "\\lnot" | "\\to") {
254      skipped += 1;
255      continue;
256    }
257
258    // A font's parameter array (expl3 keeps its intarrays there, ~89k slots
259    // for an initialized expl3 + LaTeX kernel): one `IA` row, its values
260    // run-length encoded. See `docs/parity/DUMP_DESIGN.md` (IA records) and
261    // `docs/parity/WISDOM.md` #53.
262    if let Stored::FontDimens(_) = value
263      && let Some(body) = serialize_stored(value)
264    {
265      regular.push(("IA".to_string(), url_encode(&key_str), body));
266      continue;
267    }
268
269    // Perl TeX_Job.pool.ltxml:185-197: a `\let` copy — a meaning whose own cs is not its key —
270    // that is still the very definition of that cs, before the load (the bootstrap snapshot) or
271    // now, is written `Lt(<key>, <cs>)` and re-`\let` when the dump loads, so it takes the cs's
272    // definition in the run it is loaded into; any other copy is written by value. Closure bodies
273    // and primitives always take this alias form (`PA`, `serialize_stored`); a token body was
274    // written by value, which froze `\tex_jobname:D` (l3names `\cs_new_eq:NN \tex_jobname:D
275    // \jobname`) to the dump run's empty `\jobname` placeholder, so `\c_sys_jobname_str` was
276    // empty in every conversion. Repro expl3/tex_jobname_is_the_jobname.
277    if matches!(*table, TableName::Meaning)
278      && let Stored::Expandable(exp) = value
279      && !matches!(
280        exp.get_expansion(),
281        Some(crate::definition::ExpansionBody::Closure(_))
282      )
283    {
284      let cs = exp.get_cs().into_owned();
285      let cs_name = cs.with_str(ToString::to_string);
286      if cs_name != key_str {
287        let same = |other: Option<&Stored>| match other {
288          Some(Stored::Expandable(o)) => std::rc::Rc::ptr_eq(o, exp),
289          _ => false,
290        };
291        let early = bootstrap_snap
292          .as_ref()
293          .is_some_and(|snap| same(snap.get(&(TableName::Meaning, arena::pin(&cs_name)))));
294        let late = !early && crate::state::with_meaning(&cs, same);
295        if early || late {
296          let row = (
297            table_code.to_string(),
298            url_encode(&key_str),
299            format!("PA\t{}", url_encode(&cs_name)),
300          );
301          if early {
302            early_aliases.push(row);
303          } else {
304            late_aliases.push(row);
305          }
306          continue;
307        }
308      }
309    }
310
311    let Some(serialized) = serialize_stored(value) else {
312      skipped += 1;
313      continue;
314    };
315
316    // A let-alias entry is an M row whose serialized form starts with
317    // `PA\t` or `MPA\t`. Nothing else produces those prefixes.
318    let is_alias = matches!(*table, TableName::Meaning)
319      && (serialized.starts_with("PA\t") || serialized.starts_with("MPA\t"));
320
321    let row = (table_code.to_string(), url_encode(&key_str), serialized);
322    if is_alias {
323      // Extract the target CS from "PA\t<target>" / "MPA\t<target>"
324      // (we already filtered self-aliases in serialize_stored, so the
325      //  target is always a different CS than the key).
326      let target_raw = row.2.split('\t').nth(1).unwrap_or("");
327      let target = crate::dump_reader::url_decode(target_raw);
328      let target_sym = arena::pin(&target);
329      // Target pre-existed iff it was in the bootstrap meaning table.
330      let pre_existed = bootstrap_snap
331        .as_ref()
332        .is_some_and(|snap| snap.contains_key(&(TableName::Meaning, target_sym)));
333      if pre_existed {
334        early_aliases.push(row);
335      } else {
336        late_aliases.push(row);
337      }
338    } else {
339      regular.push(row);
340    }
341  }
342
343  writeln!(
344    file,
345    "# Section 0: early let-aliases ({}) — target in bootstrap",
346    early_aliases.len()
347  )
348  .ok();
349  for (t, k, v) in &early_aliases {
350    writeln!(file, "{}\t{}\t{}", t, k, v).map_err(|e| format!("Write error: {}", e))?;
351  }
352  writeln!(file, "# Section 1: regular entries ({})", regular.len()).ok();
353  for (t, k, v) in &regular {
354    writeln!(file, "{}\t{}\t{}", t, k, v).map_err(|e| format!("Write error: {}", e))?;
355  }
356  writeln!(
357    file,
358    "# Section 2: late let-aliases ({}) — target in Section 1",
359    late_aliases.len()
360  )
361  .ok();
362  for (t, k, v) in &late_aliases {
363    writeln!(file, "{}\t{}\t{}", t, k, v).map_err(|e| format!("Write error: {}", e))?;
364  }
365
366  let count = early_aliases.len() + regular.len() + late_aliases.len();
367  writeln!(file, "# Written: {}, Skipped: {}", count, skipped).ok();
368  // `--quiet` hides this progress line, as it does every Info note (OXIDIZED_DESIGN_DIVERGENCES #1158).
369  if crate::util::logger::stderr_shows_info() {
370    eprintln!(
371      "[dump_writer] Wrote {} entries to {} ({} skipped; {} early + {} regular + {} late)",
372      count,
373      path.display(),
374      skipped,
375      early_aliases.len(),
376      regular.len(),
377      late_aliases.len(),
378    );
379  }
380
381  Ok(count)
382}
383
384fn table_to_code(t: TableName) -> &'static str {
385  match t {
386    TableName::Meaning => "M",
387    TableName::Value => "V",
388    TableName::Catcode => "C",
389    TableName::Mathcode => "MC",
390    TableName::Sfcode => "SC",
391    TableName::Lccode => "LC",
392    TableName::Uccode => "UC",
393    TableName::Delcode => "DC",
394    TableName::Stash => "ST",
395    TableName::StashActive => "SA",
396  }
397}
398
399/// Serialize a Stored value to a type-tag + data string.
400/// Returns None if the value can't be serialized.
401pub(crate) fn serialize_stored(stored: &Stored) -> Option<String> {
402  match stored {
403    Stored::None => Some("N".to_string()),
404    Stored::Bool(b) => Some(format!("B\t{}", if *b { "1" } else { "0" })),
405    Stored::Int(i) => Some(format!("I\t{}", i)),
406    Stored::String(s) => Some(format!(
407      "S\t{}",
408      url_encode(&arena::with(*s, |s| s.to_string()))
409    )),
410    Stored::Charcode(c) => Some(format!("CH\t{}", c)),
411    Stored::Catcode(cc) => Some(format!("CC\t{}", u8::from(*cc))),
412    Stored::Token(t) => Some(format!("T\t{}", serialize_token(t))),
413    Stored::Tokens(tks) => {
414      let tok_strs: Vec<String> = tks.unlist_ref().iter().map(serialize_token).collect();
415      Some(format!("TK\t{}", tok_strs.join(",")))
416    },
417    Stored::Expandable(exp) => {
418      use crate::common::object::Object;
419      let cs_name = exp.get_cs().with_str(url_encode);
420      let nargs = exp.get_num_args();
421      let mut flags = String::new();
422      if exp.is_long {
423        flags.push('L');
424      }
425      if exp.is_protected() {
426        flags.push('P');
427      }
428      // Rust-only: the macro checks its arguments for `\par` (tex.web §392; `Expandable::checks_par`), which a
429      // restored definition cannot recompute (its origin is the dump's). Perl's Dumper stores none (Dumper.pm:353).
430      if exp.checks_par {
431        flags.push('T');
432      }
433      // Two parallel parameter encodings:
434      //
435      //   - `proto` (v2, 5th field) — `Parameters::stringify()`, a flat space-separated prototype
436      //     string. Round-trips simple specs but not `Until:\end{verbatim}` or other
437      //     brace-in-delimiter forms.
438      //   - `v3_params` (v3, 6th field) — per-Parameter structured record carrying (name, spec,
439      //     flags, extras). Modeled on Perl's `P(type, spec, extra=>[T(...)])`; see
440      //     `docs/archive/DUMP_FORMAT_PERL_ANALYSIS_2026-04-30.md`. Bypasses `parse_parameters` at load
441      //     time so delimited params round-trip intact.
442      //
443      // We emit both so older readers still work, and newer readers can
444      // prefer v3 transparently.
445      let proto = exp
446        .get_parameters()
447        .map(|p| p.stringify())
448        .unwrap_or_default();
449      let proto_encoded = url_encode(&proto);
450      let v3_params = exp
451        .get_parameters()
452        .map(serialize_parameters_v3)
453        .unwrap_or_default();
454      match exp.get_expansion() {
455        Some(crate::definition::ExpansionBody::Tokens(tks)) => {
456          let tok_strs: Vec<String> = tks.unlist_ref().iter().map(serialize_token).collect();
457          Some(format!(
458            "E\t{}\t{}\t{}\t{}\t{}\t{}",
459            cs_name,
460            nargs,
461            flags,
462            tok_strs.join(","),
463            proto_encoded,
464            v3_params
465          ))
466        },
467        // No body at all (e.g. `DefMacro!("\\@gobble{}", None)`): serializes
468        // as an E-entry with empty token body. The reader reconstructs an
469        // Expandable with empty Tokens + the original paramlist, which at
470        // expansion time reads and discards its arguments — semantically
471        // identical to the no-body form's runtime behavior (expandable.rs
472        // `invoke` matches `None` → reads args, returns NO_TOKENS).
473        None => Some(format!(
474          "E\t{}\t{}\t{}\t\t{}\t{}",
475          cs_name, nargs, flags, proto_encoded, v3_params
476        )),
477        // Closure-based body — can't serialize the closure itself, BUT
478        // if the dump entry is a `\let`-alias to a closure-Expandable
479        // primitive (e.g. `\let \tex_expandafter:D \expandafter`), we
480        // CAN capture it via PA. Mirrors the `Stored::Primitive` /
481        // `Stored::Conditional` arms below. Without this, every
482        // `\let \X \expandafter`-style alias is silently dropped from
483        // the dump — the cause of `\tex_expandafter:D`,
484        // `\tex_unexpanded:D`, `\tex_the:D` being missing in
485        // `latex.dump.txt` even though expl3-code.tex L357+ aliases them.
486        //
487        // The dump_reader skips a self-alias (key == cs: the canonical CS
488        // lives in the compiled engine) and replays a real let-alias
489        // (key != cs) as Perl's `Lt()`.
490        Some(crate::definition::ExpansionBody::Closure(_)) => Some(format!("PA\t{}", cs_name)),
491      }
492    },
493    // Closure-based primitives can't be serialized directly — but if the entry's
494    // CS differs from the primitive's own CS, it's a `\let`-alias, and we CAN
495    // capture the alias so the dump reader can replay `\let <key> <target>` at
496    // load time. This is how `\tex_let:D`, `\tex_def:D`, and hundreds of other
497    // expl3-renamed primitives stay reachable across dump boundaries (the
498    // defining assignment `\let \tex_let:D \let` in expl3-code.tex needs to
499    // survive the dump for `\usepackage{expl3}`'s guard `\ifx\csname
500    // tex_let:D\endcsname\relax` to short-circuit).
501    //
502    // NOTE: the KEY we're saving IS the dump entry's first column; the VALUE
503    // we write is the primitive's OWN CS name. Dump reader compares these:
504    // if equal, it's the "primary" primitive (already in bindings) and skipped;
505    // if different, it's an alias — replay `\let` at load time.
506    Stored::Primitive(p) => {
507      // Perl `Core/Dumper.pm::dump_primitive` (L383-389): if a primitive has
508      // a `font` directive AND no replacement closure (i.e. defined by `\font`),
509      // emit `FD(<cs>, <fontID>)` instead of generic Primitive serialization.
510      // `font_id` is set on `\font`-defined primitives by `engine/tex_fonts.rs`'s
511      // post-define hook (the Rust path) — it carries the value-table key under
512      // which the Stored::Font lives. The reader installs a synthesized
513      // Primitive whose before_digest looks up that font and merges, mirroring
514      // `LaTeXML::Core::Definition::FontDef::invoke` (FontDef.pm L38-45).
515      if let Some(fid) = p.font_id {
516        let fid_str = arena::with(fid, |s| s.to_string());
517        return Some(format!("FD\t{}", url_encode(&fid_str)));
518      }
519      let target_cs = p.cs.with_str(url_encode);
520      Some(format!("PA\t{}", target_cs))
521    },
522    // A font's parameter array, the body of its `IA` row: `<len>\t<rle>`.
523    Stored::FontDimens(params) => {
524      let params = params.borrow();
525      Some(format!("{}\t{}", params.len(), rle_encode_i64(&params)))
526    },
527    Stored::Font(f) => {
528      // Perl `dump_font` (Core/Dumper.pm L281-284) emits `F(... components ...)`.
529      // Rust's `Font` is a flat options struct, so we serialize the non-None
530      // fields as `key=value` pairs separated by `\x1f` (unit-separator), with
531      // values url-encoded for tab/newline-safety. Reader inverts in dump_reader.rs.
532      let mut parts = Vec::with_capacity(8);
533      if let Some(ref name) = f.name {
534        parts.push(format!("name={}", url_encode(name)));
535      }
536      if let Some(size) = f.size {
537        parts.push(format!("size={}", size));
538      }
539      if let Some(ref family) = f.family {
540        parts.push(format!("family={}", url_encode(family)));
541      }
542      if let Some(ref series) = f.series {
543        parts.push(format!("series={}", url_encode(series)));
544      }
545      if let Some(ref shape) = f.shape {
546        parts.push(format!("shape={}", url_encode(shape)));
547      }
548      if let Some(ref encoding) = f.encoding {
549        parts.push(format!("encoding={}", url_encode(encoding)));
550      }
551      if let Some(ref language) = f.language {
552        parts.push(format!("language={}", url_encode(language)));
553      }
554      if let Some(ref mathstyle) = f.mathstyle {
555        parts.push(format!("mathstyle={}", url_encode(mathstyle)));
556      }
557      if let Some(ref opacity) = f.opacity {
558        parts.push(format!("opacity={}", url_encode(opacity)));
559      }
560      if let Some(scale) = f.scale {
561        parts.push(format!("scale={}", scale));
562      }
563      if let Some(b) = f.emph {
564        parts.push(format!("emph={}", if b { 1 } else { 0 }));
565      }
566      if let Some(b) = f.scripted {
567        parts.push(format!("scripted={}", if b { 1 } else { 0 }));
568      }
569      if let Some(step) = f.mathstylestep {
570        parts.push(format!("mathstylestep={}", step));
571      }
572      if let Some(flags) = f.flags {
573        parts.push(format!("flags={}", flags));
574      }
575      Some(format!("F\t{}", parts.join("\x1f")))
576    },
577    Stored::MathPrimitive(p) => {
578      let target_cs = p.cs.with_str(url_encode);
579      Some(format!("MPA\t{}", target_cs))
580    },
581    // Conditionals — same logic as Primitives. \ifx, \ifnum, \if etc. are
582    // stored as Stored::Conditional with their canonical CS field. When
583    // expl3-code.tex does `\let \if_meaning:w \ifx`, the new entry shares
584    // the same Conditional Rc, with cs = \ifx. Capturing this as a PA
585    // alias lets the dump reader replay `\let \if_meaning:w \ifx` at load
586    // time. Without this, every expl3 conditional alias is silently lost
587    // from the dump and `\if_meaning:w`-style invocations fail at runtime.
588    Stored::Conditional(c) => {
589      let target_cs = c.cs.with_str(url_encode);
590      Some(format!("PA\t{}", target_cs))
591    },
592    // Constructors — `\cr`, `\noalign`, `\mathchoice`, etc. defined via
593    // `DefConstructor!` carry replacement / before_digest / after_digest
594    // closures that the dump format can't serialize. But the canonical
595    // CS lives in the compiled engine, so a `\let \tex_cr:D \cr`-style
596    // alias can round-trip as `PA\t<cs>` and replay via `state::let_i`.
597    // Self-aliases are no-ops at load (key already defined).
598    Stored::Constructor(c) => {
599      let target_cs = c.cs.with_str(url_encode);
600      Some(format!("PA\t{}", target_cs))
601    },
602    Stored::Register(reg) => {
603      // Register: serialize as R\tCS\tTYPE\tVALUE[\tMATHGLYPH]
604      //
605      // Closure-backed registers can't be serialized directly — but if the
606      // dump entry is a `\let`-alias to a closure-Register primitive
607      // (e.g. `\let \tex_dimexpr:D \dimexpr`), we CAN capture it via PA.
608      // Mirrors the `Stored::Primitive` / closure-`Expandable` arms above.
609      // Without this every `\let \tex_dimexpr:D \dimexpr`-style alias is
610      // silently dropped from the dump — the cause of `\tex_dimexpr:D`,
611      // `\tex_cr:D`, `\tex_dp:D`, `\tex_ht:D`, `\tex_wd:D` (and ~430
612      // engine-specific others) being missing in `latex.dump.txt` even
613      // though expl3-code.tex L280-700 aliases them. The dump_reader
614      // skips a self-alias (key == cs: the canonical CS lives in the
615      // compiled engine) and replays a real let-alias (key != cs) as
616      // Perl's `Lt()`, so the engine-only register's behavior follows.
617      if reg.getter.is_some() || reg.setter.is_some() {
618        let target_cs = reg.cs.with_str(url_encode);
619        return Some(format!("PA\t{}", target_cs));
620      }
621      let cs_name = reg.cs.with_str(url_encode);
622      let rtype = match reg.register_type {
623        crate::definition::register::RegisterType::Number => "N",
624        crate::definition::register::RegisterType::Dimension => "D",
625        crate::definition::register::RegisterType::Glue => "G",
626        crate::definition::register::RegisterType::MuGlue => "MG",
627        crate::definition::register::RegisterType::Tokens => "TK",
628        crate::definition::register::RegisterType::CharDef => "CD",
629        _ => return None,
630      };
631      let value_str = match &reg.value {
632        Some(crate::definition::register::RegisterValue::Number(n)) => n.value_of().to_string(),
633        Some(crate::definition::register::RegisterValue::Dimension(d)) => d.value_of().to_string(),
634        Some(crate::definition::register::RegisterValue::Glue(g)) => {
635          let mut s = g.skip.to_string();
636          if let Some(p) = g.plus {
637            s.push_str(&format!(",p{}", p));
638          }
639          if let Some(ref pf) = g.pfill {
640            s.push_str(&format!(",pf{}", fillcode_index(pf)));
641          }
642          if let Some(m) = g.minus {
643            s.push_str(&format!(",m{}", m));
644          }
645          if let Some(ref mf) = g.mfill {
646            s.push_str(&format!(",mf{}", fillcode_index(mf)));
647          }
648          s
649        },
650        Some(crate::definition::register::RegisterValue::Tokens(tks)) => {
651          let tok_strs: Vec<String> = tks.unlist_ref().iter().map(serialize_token).collect();
652          tok_strs.join(",")
653        },
654        _ => "0".to_string(),
655      };
656      // Serialize address if different from cs name. Allocated registers
657      // (`\newcount\m@ne`/`\newdimen\p@`/etc.) point at low-level `\count<n>`/
658      // `\dimen<n>` slots whose runtime values live there, NOT at the alias
659      // CS name. Without the address, dump_reader would `assign_internal` at
660      // the CS name's slot (default value), and `\the\m@ne` would yield 0
661      // instead of -1. Mirror Perl's `R(C(...),undef,...,address=>'\\count22')`
662      // serialization (LaTeXML/Core/Dumper.pm). Format extension:
663      // `R\t<cs>\t<rtype>\t<value>\t<mathglyph_or_empty>\t<address>`.
664      // If address == cs_name we still serialize an empty 6th field for
665      // forward-compat parsers; the reader accepts both 4/5/6-field forms.
666      let mut s = format!("R\t{}\t{}\t{}", cs_name, rtype, value_str);
667      let mathglyph_str = match reg.mathglyph {
668        Some(glyph) => format!("{}", glyph as u32),
669        None => String::new(),
670      };
671      let cs_decoded = arena::with(reg.cs.get_sym(), |s| s.to_string());
672      let address_field = if reg.address.is_empty() || reg.address == cs_decoded {
673        String::new()
674      } else {
675        url_encode(&reg.address)
676      };
677      // Only emit extended fields when needed (keep current format size for
678      // the common case)
679      if !mathglyph_str.is_empty() || !address_field.is_empty() {
680        s.push_str(&format!("\t{}", mathglyph_str));
681      }
682      if !address_field.is_empty() {
683        s.push_str(&format!("\t{}", address_field));
684      }
685      Some(s)
686    },
687    // "Nm" (Number) — distinct from "I" (raw Int) so the reader knows
688    // to install Stored::Number, matching the type expected by register
689    // slots. Round-tripping Number through "I" silently downgraded
690    // values to Stored::Int and broke `\count` register reads.
691    Stored::Number(n) => Some(format!("Nm\t{}", n.value_of())),
692    Stored::Float(f) => Some(format!("F\t{}", f.0)),
693    Stored::Dimension(d) => Some(format!("D\t{}", d.0)),
694    Stored::Glue(g) => {
695      let mut s = format!("G\t{}", g.skip);
696      if let Some(p) = g.plus {
697        s.push_str(&format!(",p{}", p));
698      }
699      if let Some(ref pf) = g.pfill {
700        s.push_str(&format!(",pf{}", fillcode_index(pf)));
701      }
702      if let Some(m) = g.minus {
703        s.push_str(&format!(",m{}", m));
704      }
705      if let Some(ref mf) = g.mfill {
706        s.push_str(&format!(",mf{}", fillcode_index(mf)));
707      }
708      Some(s)
709    },
710    Stored::MuDimension(d) => Some(format!("MD\t{}", d.0)),
711    Stored::MuGlue(g) => {
712      let mut s = format!("MG\t{}", g.skip);
713      if let Some(p) = g.plus {
714        s.push_str(&format!(",p{}", p));
715      }
716      if let Some(ref pf) = g.pfill {
717        s.push_str(&format!(",pf{}", fillcode_index(pf)));
718      }
719      if let Some(m) = g.minus {
720        s.push_str(&format!(",m{}", m));
721      }
722      if let Some(ref mf) = g.mfill {
723        s.push_str(&format!(",mf{}", fillcode_index(mf)));
724      }
725      Some(s)
726    },
727    Stored::VecDequeStored(vd) if vd.is_empty() => Some("VD\t".to_string()),
728    _ => None,
729  }
730}
731
732fn fillcode_index(fc: &crate::common::glue::FillCode) -> usize {
733  use crate::common::glue::FillCode::*;
734  match fc {
735    Fil => 1,
736    Fill => 2,
737    Filll => 3,
738  }
739}
740
741fn serialize_token(t: &crate::token::Token) -> String {
742  let cc: u8 = t.get_catcode().into();
743  let text = t.with_str(url_encode);
744  format!("{}:{}", cc, text)
745}
746
747/// Serialize a `Parameters` list in the v3 structured format.
748///
749/// Layout (ASCII control-byte delimited so nothing collides with
750/// url-encoded printable content):
751/// - `\x1e` between Parameters (RS, Record Separator)
752/// - `\x1f` between fields of a single Parameter (US, Unit Separator)
753/// - `\x1d` between Tokens lists inside `extras` (GS, Group Separator)
754///
755/// Per-parameter fields: `<name>\x1f<spec>\x1f<flags>\x1f<extras>`
756///   - `<name>` — `Parameter.name` (Perl's `type`), url-encoded.
757///   - `<spec>` — `Parameter.spec`, url-encoded.
758///   - `<flags>` — semicolon-separated `n=1` (novalue) / `o=1` (optional).
759///   - `<extras>` — `<Tokens1>\x1d<Tokens2>…` where each `<TokensN>` is the same comma-joined
760///     `<catcode>:<text>` encoding used for E-entry bodies. Empty extras → empty field.
761///
762/// The reader (`dump_reader::parse_parameters_v3`) hands the decoded
763/// `(name, spec, Some(extras))` triple directly to `Parameter::new`,
764/// bypassing `parse_parameters` entirely — so `Until:\end{verbatim}`
765/// and `Match:…` round-trip with their catcoded delimiter tokens intact.
766pub(crate) fn serialize_parameters_v3(params: &crate::parameter::Parameters) -> String {
767  let mut out = String::new();
768  for (i, p) in params.get_parameters().iter().enumerate() {
769    if i > 0 {
770      out.push('\x1e');
771    }
772    let name = arena::with(p.name, url_encode);
773    let spec = arena::with(p.spec, url_encode);
774    let mut flags = String::new();
775    if p.novalue {
776      flags.push_str("n=1");
777    }
778    if p.optional {
779      if !flags.is_empty() {
780        flags.push(';');
781      }
782      flags.push_str("o=1");
783    }
784    let extras = p
785      .extra
786      .iter()
787      .map(|tks| {
788        tks
789          .clone()
790          .unlist()
791          .iter()
792          .map(serialize_token)
793          .collect::<Vec<_>>()
794          .join(",")
795      })
796      .collect::<Vec<_>>()
797      .join("\x1d");
798    out.push_str(&name);
799    out.push('\x1f');
800    out.push_str(&spec);
801    out.push('\x1f');
802    out.push_str(&flags);
803    out.push('\x1f');
804    out.push_str(&extras);
805  }
806  out
807}
808
809fn url_encode(s: &str) -> String {
810  let mut result = String::with_capacity(s.len());
811  for ch in s.chars() {
812    match ch {
813      '\t' => result.push_str("%09"),
814      '\n' => result.push_str("%0A"),
815      '\r' => result.push_str("%0D"),
816      '%' => result.push_str("%25"),
817      ',' => result.push_str("%2C"),
818      _ if ch.is_ascii_control() => {
819        result.push_str(&format!("%{:02X}", ch as u8));
820      },
821      _ => result.push(ch),
822    }
823  }
824  result
825}
826
827/// Run-length encode a slice of i64 values as a comma-separated list:
828/// each run is either `<v>` (single) or `<v>x<n>` (count ≥ 2). Decoder
829/// in `dump_reader::rle_decode_i64` is the inverse.
830fn rle_encode_i64(values: &[i64]) -> String {
831  let mut out = String::new();
832  let mut i = 0;
833  while i < values.len() {
834    let v = values[i];
835    let mut count = 1usize;
836    while i + count < values.len() && values[i + count] == v {
837      count += 1;
838    }
839    if !out.is_empty() {
840      out.push(',');
841    }
842    if count == 1 {
843      out.push_str(&v.to_string());
844    } else {
845      out.push_str(&format!("{}x{}", v, count));
846    }
847    i += count;
848  }
849  out
850}
851
852/// Per-load file-IO state that must never be dumped. `\@currname` /
853/// `\@currext` are assigned per `\input` by `read_input_file_recursive`
854/// (`binding/content.rs`), so at snapshot time they hold the LAST opened
855/// file ("latex.ltx") — Perl's `\input` leaves them at the `\@empty`
856/// baseline its latex_dump records (latex_dump.pool.ltxml:24122-24123).
857/// `\@currnamestack` is the `\@pushfilename`/`\@popfilename` stack
858/// (tex_file_io.rs:20-31) and carries `\the\catcode`\@`; Perl never dumps it
859/// because its serialized form equals the bootstrap's (`diff_from_snapshot`
860/// now makes the same comparison — this list is the belt to that brace).
861/// All describe the file being read at dump time, not the format.
862/// ltfilehook's `\CurrentFile*` token lists are NOT in the family: latex.ltx
863/// (:19582-19585) creates them, so the dump carries them EMPTY, as Perl's
864/// blib latex_dump.pool.ltxml:2716-2719 does.
865pub(crate) fn is_file_io_bookkeeping(key: &str) -> bool {
866  matches!(key, "\\@currname" | "\\@currext" | "\\@currnamestack")
867}
868
869#[cfg(test)]
870mod tests {
871  #[test]
872  fn file_io_bookkeeping_family_is_skipped() {
873    for k in ["\\@currname", "\\@currext", "\\@currnamestack"] {
874      assert!(is_file_io_bookkeeping(k), "{k}");
875    }
876    // The static popper macro is part of the format and stays; so do
877    // latex.ltx's `\CurrentFile*` token lists (its `\tl_new:N`, dumped empty).
878    for k in [
879      "\\@p@pfilename",
880      "\\@array",
881      "\\CurrentFile",
882      "\\CurrentFilePath",
883      "\\CurrentFileUsed",
884      "\\CurrentFilePathUsed",
885    ] {
886      assert!(!is_file_io_bookkeeping(k), "{k}");
887    }
888  }
889
890  use super::*;
891  use crate::{
892    parameter::{Parameter, Parameters},
893    token::{Catcode, Token},
894    tokens::Tokens,
895  };
896
897  /// Construct a Parameter without calling `init()` — `init()` needs live
898  /// state (PARAMETER_TYPES table), which we don't set up in unit tests.
899  /// The full test suite exercises the `init()` path via dump load.
900  fn raw_param(name: &str, spec: &str, extra: Vec<Tokens>) -> Parameter {
901    Parameter {
902      name: arena::pin(name),
903      spec: arena::pin(spec),
904      extra,
905      ..Parameter::default()
906    }
907  }
908
909  /// A Parameters list with two `Plain {}` args encodes as two records
910  /// separated by RS, each `Plain<US>{}<US><US>`. Verifies baseline layout.
911  #[test]
912  fn v3_encoding_plain() {
913    let ps = Parameters::new(vec![
914      raw_param("Plain", "{}", vec![]),
915      raw_param("Plain", "{}", vec![]),
916    ]);
917    let s = serialize_parameters_v3(&ps);
918    assert_eq!(s, "Plain\x1f{}\x1f\x1f\x1ePlain\x1f{}\x1f\x1f");
919  }
920
921  /// `Until:<delim>` with a brace-containing delimiter. The test covers
922  /// the case that livelocked 00_tokenize under v2: the delimiter tokens
923  /// must serialize as catcoded tokens (not as the raw spec string), so
924  /// `{`/`}` survive as CC_BEGIN / CC_END rather than being re-parsed as
925  /// spec-level braces.
926  #[test]
927  fn v3_encoding_until_with_braces() {
928    let delim = Tokens::new(vec![
929      T_CS!("\\end"),
930      T_BEGIN!(),
931      T_LETTER!("verbatim"),
932      T_END!(),
933    ]);
934    let ps = Parameters::new(vec![raw_param("Until", "Until:\\end{verbatim}", vec![
935      delim,
936    ])]);
937    let s = serialize_parameters_v3(&ps);
938    // Expected: Until<US>Until:\end{verbatim}<US><US>16:\end,1:{,11:verbatim,2:}
939    assert!(s.starts_with("Until\x1fUntil:\\end{verbatim}\x1f\x1f"));
940    assert!(s.contains("16:\\end,1:{,11:verbatim,2:}"));
941  }
942
943  /// `novalue` flag encodes as `n=1` in the flags field.
944  #[test]
945  fn v3_encoding_novalue_flag() {
946    let mut p = raw_param("Match", "Match:abc", vec![]);
947    p.novalue = true;
948    let ps = Parameters::new(vec![p]);
949    let s = serialize_parameters_v3(&ps);
950    assert_eq!(s, "Match\x1fMatch:abc\x1fn=1\x1f");
951  }
952
953  /// `optional` flag encodes as `o=1`; both flags together as `n=1;o=1`.
954  #[test]
955  fn v3_encoding_both_flags() {
956    let mut p = raw_param("OptionalMatch", "OptionalMatch:x", vec![]);
957    p.novalue = true;
958    p.optional = true;
959    let ps = Parameters::new(vec![p]);
960    let s = serialize_parameters_v3(&ps);
961    assert_eq!(s, "OptionalMatch\x1fOptionalMatch:x\x1fn=1;o=1\x1f");
962  }
963
964  /// Empty Parameters serializes to empty string.
965  #[test]
966  fn v3_encoding_empty() {
967    let ps = Parameters::new(vec![]);
968    assert_eq!(serialize_parameters_v3(&ps), "");
969  }
970
971  /// Multiple Tokens inside `extras` (as in `Match` with multiple choices)
972  /// are separated by GS. Verifies the three-level delimiter scheme.
973  #[test]
974  fn v3_encoding_multiple_extra_tokens() {
975    let t1 = Tokens::new(vec![T_LETTER!("a")]);
976    let t2 = Tokens::new(vec![T_LETTER!("b")]);
977    let ps = Parameters::new(vec![raw_param("Match", "Match:ab", vec![t1, t2])]);
978    let s = serialize_parameters_v3(&ps);
979    // Expected extras field: "11:a<GS>11:b"
980    assert_eq!(s, "Match\x1fMatch:ab\x1f\x1f11:a\x1d11:b");
981  }
982
983  // --- RLE encoder tests (intarray consolidation) ---
984
985  #[test]
986  fn rle_empty_slice() {
987    assert_eq!(rle_encode_i64(&[]), "");
988  }
989
990  #[test]
991  fn rle_single_value() {
992    assert_eq!(rle_encode_i64(&[5]), "5");
993  }
994
995  #[test]
996  fn rle_two_distinct() {
997    assert_eq!(rle_encode_i64(&[1, 2]), "1,2");
998  }
999
1000  #[test]
1001  fn rle_run_of_two() {
1002    assert_eq!(rle_encode_i64(&[5, 5]), "5x2");
1003  }
1004
1005  #[test]
1006  fn rle_long_run() {
1007    assert_eq!(rle_encode_i64(&[218; 10000]), "218x10000");
1008  }
1009
1010  #[test]
1011  fn rle_mixed_runs() {
1012    assert_eq!(rle_encode_i64(&[1, 2, 2, 3, 3, 3, 1]), "1,2x2,3x3,1");
1013  }
1014
1015  #[test]
1016  fn rle_negative() {
1017    assert_eq!(rle_encode_i64(&[-5]), "-5");
1018    assert_eq!(rle_encode_i64(&[-5, -5, -5]), "-5x3");
1019  }
1020
1021  #[test]
1022  fn font_parameter_array_round_trips_as_its_ia_row() {
1023    use std::{cell::RefCell, rc::Rc};
1024    let params = Stored::FontDimens(Rc::new(RefCell::new(vec![10, 20, 20])));
1025    let body = serialize_stored(&params);
1026    assert_eq!(body.as_deref(), Some("3\t10,20x2"));
1027    let key = "fontdimen_fontinfo_writer_test at 1sp";
1028    crate::dump_reader::load_from_str(&format!("IA\t{}\t{}\n", url_encode(key), body.unwrap()))
1029      .unwrap();
1030    assert_eq!(crate::state::lookup_value(key), Some(params));
1031  }
1032
1033  #[test]
1034  fn an_array_written_after_the_snapshot_is_in_the_diff() {
1035    use crate::state;
1036    let key = "fontdimen_fontinfo_snapshot_test at 1sp";
1037    assert!(state::set_font_parameter(key, 1, 5));
1038    let snapshot = state::take_snapshot();
1039    // In place: the live array changes, the snapshot's copy does not.
1040    assert!(state::set_font_parameter(key, 1, 7));
1041    let diff = state::diff_snapshot(&snapshot);
1042    let (_, _, value) = diff
1043      .iter()
1044      .find(|(_, k, _)| arena::with(*k, |k| k == key))
1045      .expect("the rewritten array is in the diff");
1046    assert_eq!(
1047      serialize_stored(value).unwrap().split(['\t', ',']).nth(1),
1048      Some("7")
1049    );
1050  }
1051
1052  /// Perl TeX_Job.pool.ltxml:185-197: a `\let` copy still sharing the bootstrap's definition of
1053  /// its cs is an early `PA` row (Perl's `@cmds_early` `Lt`), one sharing the cs's current
1054  /// definition a late one (`@cmds_late`), and one whose cs was redefined since is written by value.
1055  #[test]
1056  fn let_copies_are_written_as_lt_aliases() {
1057    use std::rc::Rc;
1058
1059    use crate::{definition::expandable::Expandable, state};
1060    let macro_of = |cs: &str, body: &str| {
1061      Stored::Expandable(Rc::new(Expandable {
1062        cs: T_CS!(cs),
1063        paramlist: None,
1064        expansion: Tokens::new(Explode!(body)).into(),
1065        ..Expandable::default()
1066      }))
1067    };
1068    state::reset_thread_state();
1069    state::install_definition(macro_of("\\wdboot", "b"), None);
1070    state::stage_snapshot("bootstrap");
1071    state::let_i(&T_CS!("\\wdearly"), &T_CS!("\\wdboot"), None);
1072    state::install_definition(macro_of("\\wdlate", "l"), None);
1073    state::let_i(&T_CS!("\\wdlatecopy"), &T_CS!("\\wdlate"), None);
1074    state::install_definition(macro_of("\\wdgone", "g"), None);
1075    state::let_i(&T_CS!("\\wdstale"), &T_CS!("\\wdgone"), None);
1076    state::install_definition(macro_of("\\wdgone", "h"), None);
1077    let entries: Vec<_> = ["\\wdearly", "\\wdlatecopy", "\\wdstale"]
1078      .iter()
1079      .map(|k| {
1080        (
1081          TableName::Meaning,
1082          arena::pin(k),
1083          state::lookup_meaning(&T_CS!(k)).unwrap(),
1084        )
1085      })
1086      .collect();
1087    let path = std::env::temp_dir().join(format!("lt_aliases_{}.dump.txt", std::process::id()));
1088    write_dump(&path, &entries, &[]).unwrap();
1089    let text = std::fs::read_to_string(&path).unwrap();
1090    let _ = std::fs::remove_file(&path);
1091    let lines: Vec<&str> = text.lines().collect();
1092    let at = |prefix: &str| lines.iter().position(|l| l.starts_with(prefix)).unwrap();
1093    let (regular, late) = (at("# Section 1"), at("# Section 2"));
1094    let early = at("M\t\\wdearly\t");
1095    assert_eq!(lines[early], "M\t\\wdearly\tPA\t\\wdboot");
1096    assert!(early < regular);
1097    let late_copy = at("M\t\\wdlatecopy\t");
1098    assert_eq!(lines[late_copy], "M\t\\wdlatecopy\tPA\t\\wdlate");
1099    assert!(late_copy > late);
1100    let stale = at("M\t\\wdstale\t");
1101    assert!(
1102      lines[stale].starts_with("M\t\\wdstale\tE\t\\wdgone\t"),
1103      "{}",
1104      lines[stale]
1105    );
1106    assert!(regular < stale && stale < late);
1107  }
1108
1109  /// Perl TeX_Job.pool.ltxml:150,153 (`sort @tables`, `sort keys`): the dump is in (table, key)
1110  /// order whatever order the diff came in, so a shuffled entry list writes the same bytes (det354
1111  /// B1: one key set in 55 record orders across 173 dumps).
1112  #[test]
1113  fn a_shuffled_diff_writes_the_same_dump() {
1114    use std::rc::Rc;
1115
1116    use crate::definition::expandable::Expandable;
1117    let macro_of = |cs: &str, body: &str| {
1118      Stored::Expandable(Rc::new(Expandable {
1119        cs: T_CS!(cs),
1120        paramlist: None,
1121        expansion: Tokens::new(Explode!(body)).into(),
1122        ..Expandable::default()
1123      }))
1124    };
1125    let entries = vec![
1126      (TableName::Value, arena::pin("zeta@count"), Stored::Int(3)),
1127      (
1128        TableName::Meaning,
1129        arena::pin("\\sdbeta"),
1130        macro_of("\\sdbeta", "b"),
1131      ),
1132      (
1133        TableName::Catcode,
1134        arena::pin("@"),
1135        Stored::Catcode(Catcode::LETTER),
1136      ),
1137      (
1138        TableName::Value,
1139        arena::pin("alpha@flag"),
1140        Stored::Bool(true),
1141      ),
1142      (
1143        TableName::Meaning,
1144        arena::pin("\\sdalpha"),
1145        macro_of("\\sdalpha", "a"),
1146      ),
1147      (TableName::Lccode, arena::pin("A"), Stored::Int(97)),
1148      (
1149        TableName::Value,
1150        arena::pin("mid@name"),
1151        Stored::String(arena::pin("m")),
1152      ),
1153    ];
1154    let write = |entries: &[(TableName, arena::SymStr, Stored)], tag: &str| {
1155      let path = std::env::temp_dir().join(format!("sorted_{tag}_{}.dump.txt", std::process::id()));
1156      write_dump(&path, entries, &[]).unwrap();
1157      let text = std::fs::read_to_string(&path).unwrap();
1158      let _ = std::fs::remove_file(&path);
1159      text
1160    };
1161    let written = write(&entries, "a");
1162    let mut reversed = entries.clone();
1163    reversed.reverse();
1164    let mut rotated = entries.clone();
1165    rotated.rotate_left(3);
1166    assert_eq!(write(&reversed, "b"), written);
1167    assert_eq!(write(&rotated, "c"), written);
1168    let rows: Vec<String> = written
1169      .lines()
1170      .filter(|l| !l.starts_with('#'))
1171      .map(|l| l.splitn(3, '\t').take(2).collect::<Vec<_>>().join(" "))
1172      .collect();
1173    assert_eq!(rows, [
1174      "C @",
1175      "LC A",
1176      "M \\sdalpha",
1177      "M \\sdbeta",
1178      "V alpha@flag",
1179      "V mid@name",
1180      "V zeta@count"
1181    ]);
1182  }
1183
1184  #[test]
1185  fn rle_extreme_values() {
1186    assert_eq!(rle_encode_i64(&[i64::MIN]), i64::MIN.to_string());
1187    assert_eq!(rle_encode_i64(&[i64::MAX]), i64::MAX.to_string());
1188    assert_eq!(rle_encode_i64(&[0; 3]), "0x3");
1189  }
1190}