Skip to main content

latexml/
ini_tex.rs

1//! Format dump mode — Rust equivalent of Perl's iniTeX + DumpFile.
2//!
3//! Usage: `latexml_oxide --init=latex.ltx --dest=latex_dump.oxide`
4//!
5//! Follows Perl's make formats scaffold (Makefile.PL + Core.pm::iniTeX):
6//! 1. Initialize the engine (load pools)
7//! 2. Take a snapshot of the state
8//! 3. Process the init file (e.g., latex.ltx) as raw TeX
9//! 4. Compute the diff (what changed)
10//! 5. Write the dump file with changed entries
11//!
12//! The resulting dump can be loaded at runtime to skip re-processing
13//! the LaTeX kernel on every test run.
14
15use std::{path::Path, sync::LazyLock};
16
17// Process-once cached env var (see WISDOM #56 — getenv hot-path race).
18static INIT_DEBUG: LazyLock<bool> =
19  LazyLock::new(|| std::env::var_os("LATEXML_INIT_DEBUG").is_some());
20
21use latexml_core::{
22  binding::content::{InputDefinitionOptions, input_definitions},
23  state,
24};
25
26use crate::converter::Converter;
27
28/// A progress line on stderr; `--quiet` hides it, as it does every Info note (OXIDIZED_DESIGN_DIVERGENCES #1158).
29macro_rules! progress {
30  ($($arg:tt)*) => {
31    if latexml_core::util::logger::stderr_shows_info() {
32      eprintln!($($arg)*);
33    }
34  };
35}
36
37/// Process an init file and write a format dump.
38/// Perl equivalent: Core.pm::iniTeX → TeX_Job.pool.ltxml::DumpFile
39pub fn dump_format(
40  _converter: &mut Converter,
41  init_file: &str,
42  destination: Option<&str>,
43) -> Result<usize, String> {
44  progress!("[ini_tex] Dumping format from {}", init_file);
45
46  // Strict Perl `iniTeX` + `DumpFile` order:
47  //
48  //   Core.pm L168-212 (iniTeX, default mode='Base'):
49  //     initializeState('Base.pool');     # ← Step 1 below
50  //     installDefinition('\jobname', ...);
51  //     installDefinition('\dump', Tokens());  # no-op
52  //     DumpFile($file, $dest);           # ← Step 2 below
53  //
54  //   TeX_Job.pool.ltxml L120-220 (DumpFile):
55  //     LoadPool($name . '_bootstrap');   # ← Step 3 below
56  //     $snap = ...                       # ← Step 4 below
57  //     loadTeXDefinitions($name, ...)    # ← Step 5 below
58  //     diff                              # ← Step 6 below
59  //     write                             # ← Step 7 below
60  //
61  // CRITICAL: Perl iniTeX defaults to `mode='Base'`, so `Base.pool` is
62  // loaded BEFORE any bootstrap. Without it, raw plain.tex / latex.ltx
63  // can't expand any TeX primitive — every `\def`, `\catcode`,
64  // `\let`, `\edef` etc. is undefined and we get an error cascade.
65  // After Base.pool, only `<name>_bootstrap` is loaded — NEVER
66  // `<name>_base`, `<name>_dump`, or `<name>_constructs`. Those
67  // pollute the diff with `:locked` flags, base/constructs
68  // definitions, etc. that the dump should NOT carry.
69
70  // Step 1: Load Base.pool equivalent (Perl `initializeState('Base.pool')`).
71  progress!("[ini_tex] Loading Base.pool (Perl `initializeState('Base.pool')`)");
72  if let Err(e) = latexml_package::engine::base::load_definitions() {
73    eprintln!("[ini_tex] base warning: {}", e);
74  }
75
76  // Mark this as init/dump mode so machinery elsewhere (notably
77  // `tex_file_io::\\input`'s LaTeX-style brace-arg auto-load of
78  // `LaTeX.pool`) skips behaviors that would corrupt the dump-build
79  // — see `tex_file_io.rs` for the gate.
80  state::assign_value("INI_TEX_MODE", true, Some(state::Scope::Global));
81
82  // Clear LaTeX/expl3/AmSTeX autoload triggers and `\documentstyle`
83  // installed by `tex.rs` during `prepare_session`. These triggers
84  // pre-define `\makeatletter`, `\documentclass`, etc. — which then
85  // poison the snapshot, causing raw `latex.ltx` at L1798
86  // (`\DeclareRobustCommand\makeatletter`) to hit the "redefining"
87  // branch in `\declare@robustcommand` (L1388), which calls
88  // `\@latex@info{Redefining ...}` — but `\@latex@info` isn't
89  // defined until L1799, triggering an undefined-CS cascade.
90  //
91  // Perl `Core.pm::iniTeX` defaults to `mode='Base'` for dump-build,
92  // so `Base.pool` is loaded but `TeX.pool`'s autoload triggers are
93  // NOT. Mirror that here by clearing them right before the snapshot.
94  for trigger in &[
95    // LaTeX autoload triggers (tex.rs L149-167)
96    "\\documentclass",
97    "\\newcommand",
98    "\\renewcommand",
99    "\\newenvironment",
100    "\\renewenvironment",
101    "\\NeedsTeXFormat",
102    "\\ProvidesPackage",
103    "\\RequirePackage",
104    "\\ProvidesFile",
105    "\\makeatletter",
106    "\\makeatother",
107    "\\begin",
108    "\\listfiles",
109    "\\nofiles",
110    "\\typeout",
111    "\\PassOptionsToPackage",
112    // `\@load@latex@pool` itself
113    "\\@load@latex@pool",
114    // expl3 autoload triggers
115    "\\ExplSyntaxOn",
116    "\\ProvidesExplClass",
117    "\\ProvidesExplPackage",
118    // AmSTeX/amsmath autoload triggers
119    "\\mathfrak",
120    "\\mathbb",
121    "\\Bbb",
122    "\\theoremstyle",
123    "\\numberwithin",
124    "\\align",
125    "\\subequations",
126    "\\multline",
127    "\\curraddr",
128    "\\subjclass",
129    // `\documentstyle` was also defined in tex.rs as a runtime macro
130    "\\documentstyle",
131  ] {
132    state::assign_meaning(
133      &latexml_core::T_CS!(*trigger),
134      latexml_core::common::store::Stored::None,
135      Some(state::Scope::Global),
136    );
137  }
138
139  // Step 2 + 3: install \jobname / \dump (no-op), then load bootstrap.
140  // (Perl Core.pm L204-207 + TeX_Job.pool.ltxml L127-129)
141  let init_lower = init_file.to_ascii_lowercase();
142  let is_plain_init = init_lower.contains("plain");
143
144  if is_plain_init {
145    progress!("[ini_tex] Loading plain_bootstrap (mirrors Perl `LoadPool('plain_bootstrap')`)");
146    if let Err(e) = latexml_package::engine::plain_bootstrap::load_definitions() {
147      eprintln!("[ini_tex] plain_bootstrap warning: {}", e);
148    }
149  } else {
150    progress!("[ini_tex] Loading latex_bootstrap (mirrors Perl `LoadPool('latex_bootstrap')`)");
151    // latex_bootstrap.rs L11 does `InnerPool!(plain_bootstrap)` itself
152    // (mirrors Perl `LoadPool('plain_bootstrap')` at the top of
153    // latex_bootstrap.pool.ltxml), so plain_bootstrap state is included.
154    if let Err(e) = latexml_package::engine::latex_bootstrap::load_definitions() {
155      eprintln!("[ini_tex] latex_bootstrap warning: {}", e);
156    }
157  }
158
159  // Perl `DumpFile` L132-138: snapshot all tables AFTER the bootstrap pool.
160  let snap = state::take_snapshot();
161  // Re-stage as "bootstrap" so `dump_writer` finds it for let-alias
162  // classification (early/late sections).
163  state::stage_snapshot_value("bootstrap", snap.clone());
164  let snap_size = snap.len();
165  progress!(
166    "[ini_tex] Snapshot taken at bootstrap ({} entries)",
167    snap_size
168  );
169
170  // Step 2: Process the init file as raw TeX definitions.
171  // Perl: loadTeXDefinitions($name, $path, type => $type)
172  // This digests the file through the engine, creating definitions.
173  let (_, name, ext) = split_path(init_file);
174  progress!("[ini_tex] Loading {} (ext: {})", name, ext);
175  // Use the full filename with extension for proper file resolution
176  let load_name = if ext.is_empty() {
177    name.clone()
178  } else {
179    format!("{}.{}", name, ext)
180  };
181  // Perl `DumpFile` (TeX_Job.pool.ltxml:141-144): no file, no dump —
182  // `Fatal('expected', $file, "Couldn't find definitions file $file")`. The load
183  // below only warns `missing_file`, and the dump would carry the braces at 12.
184  if latexml_core::binding::content::find_file(&load_name, None).is_none() {
185    return Err(format!("Couldn't find definitions file {init_file}"));
186  }
187
188  // Lift the token limit for format dumps — expl3-code.tex alone uses ~5M tokens.
189  let saved_limit = latexml_core::gullet::set_token_limit(None);
190
191  // In init mode, suppress error/warning output during format loading.
192  // Raw latex.ltx redefines commands already in the compiled engine ("already defined"),
193  // and expl3-code.tex has forward references that produce transient errors.
194  // All these errors are benign — the dump captures the final correct state.
195  // Set LATEXML_INIT_DEBUG=1 to keep errors visible (for debugging the
196  // expl3 cascade — Perl parity target is zero errors during expl3 load).
197  let init_debug = *INIT_DEBUG;
198  let prev_suppress = latexml_core::common::error::set_suppress_log_output(!init_debug);
199
200  // Suppress known expl3 loading errors at the state level too — except in a build for this
201  // tree at run time (`latexml::format_dumps`), which counts every error as
202  // `tools/make_formats.sh` does under LATEXML_INIT_DEBUG=1, and keeps no dump that had one.
203  let count_all = init_debug || latexml_engine::dump_paths::building_format();
204  state::assign_value("SUPPRESS_UNDEFINED_ERRORS", !count_all, None);
205  state::assign_value("SUPPRESS_UNEXPECTED_ERRORS", !count_all, None);
206
207  // Lift the MAX_ERRORS cap during dump-build. Raw latex.ltx contains
208  // many CSes our engine reports as errors (forward references in
209  // expl3-code.tex, `\@onlypreamble` checks, autoload triggers, etc.).
210  // The default 10000-error cap aborts dump-build before plain.tex's
211  // `\outer\def\newread`, `\loop`, etc. land in the diff. Mirrors Perl
212  // `DumpFile`'s behavior — Perl runs latex.ltx through to `\dump`
213  // regardless of error count.
214  state::assign_value("MAX_ERRORS", 1_000_000_i64, None);
215
216  // Read the format file with the braces as initex has them: initex starts with
217  // every character but `\`, `%`, space, the letters, `^^M`, `^^@` and `^^?` at
218  // catcode 12 (tex.web §232), and latex.ltx:98-101 (ltdirchk.dtx) refuses a
219  // preloaded format by `\ifnum\catcode`\{=1 \errmessage{LaTeX must be made
220  // using an initex with no format preloaded}\fi`, then sets `{`/`}` to 1/2
221  // itself (latex.ltx:102-103; plain.tex:11-12 likewise). The State starts from
222  // the standard table (state.rs `State::new`, as Perl State.pm:105-112), which
223  // Base.pool and the bootstrap need — so the two braces go to 12 only here,
224  // after the snapshot (Perl `DumpFile`, TeX_Job.pool.ltxml:132-138) and before
225  // the file is read (:141-144). The file restores both before the snapshot
226  // diff, so the dump is unchanged. Perl reads the file with `{` at 1 and logs
227  // the `\errmessage` as a Note (TeX_Debugging.pool.ltxml:71-74). Guard:
228  // `dump_gate_init::latex_ltx_init_has_zero_errors`.
229  state::assign_catcode('{', latexml_core::token::Catcode::OTHER, None);
230  state::assign_catcode('}', latexml_core::token::Catcode::OTHER, None);
231
232  let result = input_definitions(&load_name, InputDefinitionOptions {
233    noltxml: true,
234    ..InputDefinitionOptions::default()
235  });
236  if let Err(e) = result {
237    eprintln!("[ini_tex] Warning during loading: {}", e);
238  }
239
240  // Restore limits and suppression
241  latexml_core::gullet::restore_token_limit(saved_limit);
242  latexml_core::common::error::set_suppress_log_output(prev_suppress);
243  state::assign_value("SUPPRESS_UNDEFINED_ERRORS", false, None);
244  state::assign_value("SUPPRESS_UNEXPECTED_ERRORS", false, None);
245
246  // Step 3: Compute the diff — only entries that changed.
247  let diff = state::diff_snapshot(&snap);
248  progress!(
249    "[ini_tex] Post-load diff: {} changed entries (from {} pre-dump)",
250    diff.len(),
251    snap_size
252  );
253
254  // Step 4: Write the dump.
255  // Default: write text dump to resources/dumps/<kind>.<YYYY>.dump.txt for
256  // build.rs embedding. With --dest: write to the specified path.
257  let kind = if name.contains("latex") {
258    "latex"
259  } else {
260    "plain"
261  };
262  let ambient_year = latexml_engine::dump_paths::detect_ambient_texlive_year();
263  let (dest, is_text_dump) = match destination {
264    Some(d) if d.ends_with(".rs") => (d.to_string(), false),
265    Some(d) => (d.to_string(), true),
266    None => {
267      let year = ambient_year.ok_or_else(|| {
268        "Could not detect ambient TeXLive year (no kpsewhich/pdflatex). \
269         Pass --dest=<path> to override the dump filename."
270          .to_string()
271      })?;
272      let dump_name = latexml_engine::dump_paths::dump_filename(kind, year);
273      let dump_dir = "resources/dumps";
274      std::fs::create_dir_all(dump_dir)
275        .map_err(|e| format!("Failed to create {}: {}", dump_dir, e))?;
276      (format!("{}/{}", dump_dir, dump_name), true)
277    },
278  };
279
280  // The format files this dump was built from, as the TeX tree that built it resolves them: a loader
281  // uses the dump only with a tree that has the same files (`dump_paths::dump_matches_tree`).
282  let sources: Vec<String> = latexml_engine::dump_paths::runtime_source_stamps(kind)
283    .unwrap_or_default()
284    .iter()
285    .map(latexml_engine::dump_paths::SourceStamp::header_line)
286    .collect();
287  if is_text_dump {
288    // Write text format (loaded at runtime via dump_reader::load_from_str)
289    let write_count = latexml_core::dump_writer::write_dump(Path::new(&dest), &diff, &sources)?;
290    // Save versioned TeX Live stamp for staleness detection, beside the dumps a release builds.
291    if destination.is_none()
292      && let Some(year) = ambient_year
293    {
294      save_texlive_version(year);
295    }
296    progress!("[ini_tex] Wrote {} text entries to {}", write_count, dest);
297    progress!("Format dump complete: {} entries written", write_count);
298    Ok(write_count)
299  } else {
300    // Write compiled Rust source (legacy format)
301    let tmp = format!("{}.tmp", dest);
302    let _write_count = latexml_core::dump_writer::write_dump(Path::new(&tmp), &diff, &sources)?;
303    let rs_count = latexml_core::dump_codegen::generate_rs(Path::new(&tmp), Path::new(&dest))?;
304    let _ = std::fs::remove_file(&tmp);
305    progress!(
306      "[ini_tex] Generated {} Rust definitions to {}",
307      rs_count,
308      dest
309    );
310    progress!("Format dump complete: {} entries written", rs_count);
311    Ok(rs_count)
312  }
313}
314
315/// Generate a compiled Rust module from a dump file.
316/// Reads the text dump and produces a .rs file with direct state assignment calls.
317pub fn codegen_from_dump(dump_path: &str, output_path: &str) -> Result<usize, String> {
318  progress!("[ini_tex] Generating Rust module from {}", dump_path);
319  let count =
320    latexml_core::dump_codegen::generate_rs(Path::new(dump_path), Path::new(output_path))?;
321  progress!("[ini_tex] Generated {} entries to {}", count, output_path);
322  Ok(count)
323}
324
325fn save_texlive_version(year: u32) {
326  let version = latexml_core::util::pathname::tex_tool_command("kpsewhich")
327    .arg("--version")
328    .output()
329    .ok()
330    .and_then(|o| {
331      if o.status.success() {
332        String::from_utf8(o.stdout).ok()
333      } else {
334        None
335      }
336    });
337  if let Some(v) = version {
338    let stamp = latexml_engine::dump_paths::version_filename(year);
339    let _ = std::fs::write(format!("resources/dumps/{}", stamp), v.trim());
340  }
341}
342
343fn split_path(path: &str) -> (String, String, String) {
344  let p = Path::new(path);
345  let dir = p
346    .parent()
347    .map(|d| d.to_string_lossy().to_string())
348    .unwrap_or_default();
349  let stem = p
350    .file_stem()
351    .map(|s| s.to_string_lossy().to_string())
352    .unwrap_or_default();
353  let ext = p
354    .extension()
355    .map(|e| e.to_string_lossy().to_string())
356    .unwrap_or_default();
357  (dir, stem, ext)
358}