Rename the crate, binary, core crate, font families, env vars, and internal commands from texcraft/tex-engine to texrra. Serve the separately versioned texrra-web frontend from TEXRRA_WEB_DIR, ../web, or ./web instead of embedding index.html. Add starred section heading support and an arXiv template conformance fixture.
31 KiB
XeTeX core port map
Target
Rewrite the XeTeX engine in Rust and use XeLaTeX as the compatibility oracle: the same LaTeX format, package inputs, fonts, and document should produce equivalent diagnostics and page layout. Then add Typst-style dependency tracking and incremental recomputation around stable TeX state boundaries. The current Rust compiler is a running subset and migration host; it is not yet that rewrite. The target is to move the live execution and layout path into project-owned Rust modules, rather than grow the existing subset indefinitely.
XeTeX and LaTeX are separate compatibility layers. XeTeX supplies TeX's execution and typesetting engine plus Unicode and modern-font support. The LaTeX format and packages define document-level commands on top of that engine. Rewriting the engine does not automatically implement the package ecosystem.
Migration contract
The target is observable XeLaTeX behavior across the engine, the selected LaTeX format, package inputs, and fonts. PDF object bytes do not need to match; page dimensions, line and page breaks, glyph selection and placement, references, and source-located errors do.
Typst's phase boundaries and incremental reuse are architectural references. TeX still executes tokens against mutable state, so cached work is reusable only when the incoming engine state and every dependency are unchanged. The Rust engine's semantic output must be built from TeX modes and native horizontal, vertical, and math lists. A command is not a completed engine port merely because it has a parser event or a PDF drawing branch.
New engine behavior belongs behind project-owned token, state, expansion,
primitive, and list interfaces. Texlang remains a temporary compatibility
adapter while those interfaces are migrated; it must not define the long-term
engine state or execution contract. The current DocumentModel renderer stays
available during the transition, but it is not the target TeX intermediate
representation.
Upstream reference
- XeTeX engine source:
texk/web2c/xetexdir/xetex.webin the TeX Live source mirror. - Base TeX engine source:
tex.web. - XeTeX source tree and build description: TeX-Live/xetex.
- XeTeX's
xetexdir/COPYINGand the header ofxetex.webcontain MIT-style permission for XeTeX portions, with notice-retention requirements. The samexetex.webheader also includes a separate e-TeX notice that restricts copying that material. TeX Live is a collection with package-specific licenses, so record the exact upstream file and applicable notice for every ported slice; do not assume the whole source tree shares one license.
Current dependency boundary
| Engine responsibility | Current implementation | Rewrite boundary |
|---|---|---|
| Semantic document IR and parsing | texrra-core::document owns document metadata, source-anchored blocks, text/math runs, tables, lists, unresolved references, and page settings. texrra-core::document_parser::parse_document consumes the source-mapped expanded stream; texrra-core::references resolves labels and citations over the resulting IR, and CompilerSession invokes both core phases directly. The application document and parser modules remain compatibility re-exports; PDF and HTML use the core types. |
Reuse semantic nodes across edits using source identity and dependency-aware invalidation; the parser and its paragraph cache are core-owned, but a source edit still traverses the document. |
| TeX input, tokens, macro expansion, primitive execution | texrra-core::mouth owns runtime scanning for the document, compatibility prelude, \input files, and .sty sources. It now emits the shared EngineTokenValue plus a source span; engine::mouth is a compatibility re-export, and conversion to VM tokens happens in the adapter. texrra-core::source owns source origins and locations independently of Texlang; texrra-core also owns EngineToken, token values, control-sequence names, category-code and math-code types, plain TeX catcode defaults, macro definitions, argument matching, replacement instantiation, scoped macro tables, assignment scope, environment stack, and native-command meanings independently of Texlang's interned IDs. The application modules engine::token, engine::macros, and engine::expansion are compatibility re-exports; Texlang re-exports the shared category-code and math-code types as a compatibility API. texrra-core::mouth::CatCodeTable stores and scopes catcodes directly. texrra-core::math_code::MathCodeTable owns ordinary math codes, while texrra-core::math_code::UnicodeMathCodeTable and texrra-core::math_code::DelimiterCodeTable hold Unicode math codes and delimiter registrations; math token lowering and the \mathcode, \Umathcode, and \delcode adapters use these engine-owned tables and their local/global save stacks. The Texlang variable adapters opt out of the VM save stack for these engine-owned values. texrra-core::environment::EnvironmentStack owns serialized LIFO environment state and rejects mismatched \end operations. texrra-core::assignment_scope::AssignmentScope owns the scoped \globaldefs value and resolves local/global assignment scope. texrra-core::macros::MacroTable owns macro names, parameter prefixes, delimiters, and replacement token values; texrra-core::expansion matches arguments through an engine-owned token-stream interface and instantiates replacements. A Texlang adapter hook consults the macro table before command-map lookup in both normal expansion and expand_once; command-map entries remain reflection markers for primitives that inspect meanings. Engine tokens carry source-trace IDs; a bridge table maps those IDs to Texlang trace keys for source diagnostics. \read streams and a few lower-level stdlib paths still use Texlang's lexer. |
Replace the remaining Texlang expansion stream, primitive dispatch, variable, grouping, and error contracts with engine-owned semantics, while keeping a per-phase comparison path against XeTeX. |
| Registers, dimensions, and glue | engine::registers::RegisterTable owns sparse \\count, \\dimen, \\skip, \\muskip, and \\toks values plus local/global group history. Their \\countdef, \\dimendef, \\skipdef, \\muskipdef, and \\toksdef aliases bind to those tables. texrra-core::integer owns signed, octal, hexadecimal, character-constant, and internal-value integer scanning; \\penalty, register indices, and expression factors use it through the adapter. engine::dimension scans explicit dimensions and glue for \\kern, \\hskip, \\vskip, \\above, and \\abovewithdelims; it evaluates e-TeX \\dimexpr and \\glueexpr arithmetic using the shared integer scanner. Other internal-value forms retain a Texlang parser fallback. engine::arithmetic owns command dispatch and arithmetic semantics for \\advance, \\multiply, and \\divide over typed integer, dimension, glue, and math-glue variables. engine::variable owns assignment parsing and writes for arithmetic variables, including small integers; Texlang still supplies variable descriptors and dynamic index resolution. Texlang typed parsers for integers, dimensions, ordinary glue, and math glue delegate to Rust scanner hooks for assignments and arithmetic operands. The Rust dimension scanner also backs \\kern, \\hskip, and \\vskip; non-arithmetic assignments and other internal-value forms retain the Texlang compatibility path. texrra-core::glue::TeXGlue owns stretch/shrink fields and infinity orders; engine::glue re-exports it at the adapter boundary. Fixed-point storage still uses common::Scaled. |
Move remaining internal-value parsing, variable access, and fixed-point representation into the engine; keep conversions at backend edges. |
| Paragraph breaking and font metric repository | boxworks, boxworks-knuthplass, rusttype |
Port TeX's list and line-breaking behavior; isolate font metric/shaping providers behind engine interfaces. |
| Math parsing and much of 2D math layout | texrra-core::expanded owns the source-mapped expanded token/event stream; texrra-core::math_mode validates math scope transitions and math-only events; texrra-core::math_lowering converts math delimiters, validates and lowers math environments, builds equation rows, and caches parsed expressions; texrra-core::math_parser consumes the stream into texrra-core::math_expr::MathExpr; texrra-core::math_style owns the eight TeX math styles and child-style transitions; texrra-core::math_list owns style-sensitive class boundaries, \\mathchoice selection, binary-operator normalization, the eight-class spacing table, and style-aware math-skip selection; texrra-core::math_alphabet selects Unicode math alphabets and rewrites ordinary atoms through nested expressions; texrra-core::math_constants parses OpenType MATH constants and selects fraction, script, operator-limit, radical, and bar parameters; texrra-core::math_layout owns math-sequence state planning and measured child placement plus fraction-box, ordinary script, display-limit, radical-box, delimiter-target, ordinary delimited-box, fenced-row, accent, alignment, display-row, multline, and equation-tag geometry; the application supplies measured glyphs and font-availability queries, converts mu to page units, and assembles delimiter glyphs |
Move glyph access and font metric queries behind core layout interfaces; compare noad construction, style transitions, math alphabets, MATH constants, and glyph selection against XeTeX. |
| Page breaking | page_builder.rs plus a restricted positioned-page path in pdf.rs; page-break badness now follows TeX's integer approximation from tex.web, and \\vskip glue enters the vertical node list |
Extend from fixed boxes/glue/penalties to engine-owned vertical lists, insertions, output routines, and page frames. |
| PDF assembly and page composition | genpdf |
Make an engine-owned positioned page tree the source for PDF and live preview; retain only a replaceable PDF serialization backend. |
| Font table access and images | ttf-parser, image |
Keep format parsers as replaceable I/O components; define shaping, metrics, and asset contracts in the engine. |
The core now selects math-atom glyph text, font preference, and atom slant, and
interprets OpenType MATH per-glyph italic corrections, top accent attachments,
and height-dependent corner-kern selection through
texrra-core::math_glyph and its engine-owned MathGlyphMetrics and
MathKernTable values. The application maps core slants to backend styles and
converts parsed OpenType records into these values; font opening,
character-to-glyph lookup, page-unit conversion, glyph bounds, outlines, and
delimiter assembly remain in the application backend.
texrra-core::math_layout::math_script_kern selects the larger of XeTeX's
two candidate horizontal kern sums for ordinary subscripts and superscripts
using those backend-provided glyph measurements. Nucleus classification for
character scripts, single-glyph operators, and operator limits now resides in
texrra-core::math_expr and is consumed by the application layout adapter.
texrra-core::math_alphabet also owns the Unicode mappings and recursive
expression rewrite for TeX math alphabets; the application provides selected-
font and default-math-font glyph-availability queries. The script-kern adapter
uses the core's first-nucleus traversal, while the backend still resolves the
font face and glyph outline.
texrra-core::math_layout::plan_math_sequence resolves each item's active
math style, spacing settings, class boundary, and nested-list context.
layout_math_sequence arranges measured child boxes around their shared
baseline and returns backend-neutral positions; PDF code now only measures
children and converts those positions to its page units.
CompilerSession reuses the active MathFontMetrics across edit compiles and
PDF/HTML renders when the selected font files have unchanged contents; cloned
metrics share extracted glyph data keyed by font-byte identity and character.
Port order
The runtime source stack and TeX file-name scanning now live in
texrra-core::input; engine::input is a compatibility re-export.
Tokenization is implemented in texrra-core::mouth and re-exported
through engine::mouth. The core owns source frames, tokenized macro
replacement frames, text, line offsets, input priority, TeX filename splitting,
and InputFileLocation::resolve_path.
CompilerState supplies the working directory, performs file reads and
records dependencies, and keeps Texlang diagnostic trace mapping at the
adapter boundary. \\input and \\endinput now dispatch
through project-owned primitives and push or end those engine frames. The Rust
scan_file_location follows XeTeX's more_name
and scan_file_name
rules. The filename scanner receives expanded tokens through its adapter;
path resolution uses the Rust-owned InputFileLocation::resolve_path, while
the adapter performs file reads and records dependencies. It passes resolved
source text when pushing
the nested input frame. File areas are reported as a source-located error
instead of reaching Texlang's panic path; area-to-directory mappings remain
unimplemented.
texrra-core::layout_primitive owns the primitive set, action selection,
operand scan order, and typed effect contract for \\par, \\newline,
\\pagebreak, \\penalty, \\kern, \\hskip, and \\vskip;
engine::layout_primitive is a compatibility re-export. The Texlang adapter
supplies the concrete token cursor and numeric scanners, then translates core
effects into source-located output events.
texrra-core::command::NativeCommandTable owns the meanings for these
layout primitives, \\advance, \\multiply, \\divide, and the \\global,
\\long, \\outer, and \\relax prefix primitives. The patched VM tag still
routes those tokens into the adapter. EngineSemanticState::command_meaning
resolves macro meanings before native meanings, and both expansion and
execution hooks use that shared lookup. \\let copies native meanings into
scoped aliases; macro definitions clear any native meaning they shadow. The
VM's main execution loop and other primitive dispatch remain to be replaced.
The engine now owns the explicit-token scan for dimensions and glue. It reads
decimal, octal, and hexadecimal numeric forms; the standard physical units;
em/ex; true magnification; fil, fill, and filll glue orders; and
parenthesized e-TeX \\dimexpr/\\glueexpr arithmetic with +, -, *, /,
and \\relax termination. The project adapters still supply expanded tokens
and diagnostics. em/ex still use Texlang's default 12 pt metrics because
Rust font metrics are not connected yet. Magnification is owned by the Rust
engine at its default value of 1000 and is passed into this scanner for true
dimensions. The Rust scanner parses decimal, octal, hexadecimal, and
character-constant integers for
register indices and expression factors, and reads native typed register
variables directly from engine state. Active \\count, \\dimen, \\skip,
\\muskip, and \\toks values and all five *def aliases use Rust-owned
sparse tables and group history; the VM register components have been removed
from CompilerState. Other internal-value forms still fall back through
Texlang's parser API. Prefix scope for aliases is applied to the command-map
definition and consumed there, so it cannot leak into a later register
assignment.
Expression precedence,
parentheses, and scaled-point rounding use XeTeX's e-TeX
scan_expr
as the behavior reference.
This is the first numeric-scanning port, not a claim that TeX's full
scan_dimen contract has moved. The compatibility reference is XeTeX's
xetex_scan_dimen and scan_glue,
which inherit the base TeX scanner and add XeTeX-specific behavior.
The engine now owns \\mag (default 1000) and feeds it to the Rust scanner
for true dimensions. Global PDF/page scaling and XeTeX's magnification-freeze
behavior are still outside this slice.
- Execution state: source input stack, token scanner, category codes,
control-sequence table, grouping/save stack, registers, and recoverable TeX
errors. Migrate one primitive family at a time from
texlangwhile the old path remains available for comparison. - TeX lists and modes: horizontal, vertical, and math modes; boxes, glue, kerns, penalties, insertions, and math noads. These are the engine's shared intermediate representation, not document-parser marker events.
- Typesetting algorithms: paragraph line breaking, math-list conversion, page building, and output routines over those lists. Compare dimensions, break choices, and diagnostics with XeTeX fixtures.
- Fonts and shaping: Unicode font selection, OpenType MATH data, shaping, script runs, and glyph positioning. Keep font file decoding separate from TeX's font and layout decisions.
- Output and live compilation: export one positioned page tree to PDF and preview. Cache phase results only where the incoming TeX state is part of the cache key; edits to macros, registers, catcodes, or package inputs must invalidate dependent work.
- LaTeX format and packages: load the format and expand package support on the completed engine. Track package behavior separately from engine primitives.
Port acceptance record
Each ported behavior needs a small record containing the XeTeX source section or algorithm reference, input fixture, expected token/list/box result, diagnostics, font assumptions, and observed XeLaTeX output. Compare generated PDF pages and diagnostic locations, not just whether a command name is recognized. Keep the same TeX Live format, packages, and fonts on both sides so the comparison isolates engine behavior. Unsupported cases must be identified as such while the live application remains runnable during migration.
The fixed-box page breaker uses the integer badness approximation in the
badness routine of tex.web. This preserves TeX's discrete page-break costs where the previous floating-point approximation could select a different candidate near a tie. engine::dimension now scans explicit \kern dimensions and \hskip/\vskip glue, then carries those values into horizontal runs or vertical page nodes; token-level internal-value scanning still uses the compatibility parser over Rust-owned \dimen and \skip tables. Horizontal kerns participate in text and inline-math line layout; vertical kerns participate in page breaking and positioned output. Leading vertical kerns are discarded with other top-of-page material, following vert_break. texrra-core::math_mode::validate_math_delimiters validates inline/display math scopes, matching closes, \tag placement, and \par inside math. Outer vertical/horizontal transitions remain in the application builder, and the page builder still lacks TeX's output routine, insertions, and complete vertical-list execution.
Current rewrite status
CompilerState now delegates engine semantics to
texrra-core::state::EngineSemanticState through the TeXEngineState
adapter: catcodes, math codes, assignment scope, macros, native-command
meanings, environments, and group save/restore live in the core. The adapter
retains source I/O and register values that still use Texlang types. Texlang
still owns the main execution loop and fallback dispatch, so this is a concrete
Rust-core extraction step rather than a completed XeTeX rewrite.
The project-owned primitive map now handles \\par and \\newline directly:
they emit typed paragraph and line-break events without routing through the
Texlang script-output component or compatibility-prelude aliases.
texrra-core::math_lowering calls the core math-scope validator before
constructing expression trees. Outer vertical and horizontal mode transitions
remain outside the core.
The math tree now distinguishes first-row baselines for top-level display
alignments from math-axis-centered baselines for nested alignment and matrix
boxes. An outer equation preserves an inner aligned, split, matrix, or
array node. The axis height uses the family-2 font selected for the active math
style when that font has an OpenType MATH axis constant, and falls back to the
configured default metric otherwise. This follows XeTeX's make_vcenter
baseline contract. The frontend captures the math-family table when the
environment begins, so the axis metric comes from family 2 at the environment's
entry state instead of being inferred from whichever font appears in a cell.
The Rust math path also parses XeTeX's infix fraction variants \\over,
\\atop, \\choose, \\above, \\overwithdelims, \\atopwithdelims,
and \\abovewithdelims. Delimiter variants carry both scanned glyphs and
sizing settings through the typed event stream, then use the shared scalable
delimiter layout around the same fraction node. XeTeX scans both delimiters
before the explicit dimension in \\abovewithdelims, matching the Rust
scanner order (source).
Ruled fractions center the bar on the font's AxisHeight; the fraction box
accounts for half the rule thickness on each side, so OpenType MATH minimum
gaps are measured to the bar's ink edges (MATH constants).
Inline math uses the paragraph's Knuth–Plass line breaker. The expanded stream
snapshots \binoppenalty and \relpenalty (defaults 700 and 500) so
assignments affect only subsequent math atoms. Break penalties follow binary
and relation noads; punctuation does not add a breakpoint, and a penalty is
suppressed immediately before a relation noad, following XeTeX's math-list
conversion (xetex.web).
texrra-core::math_list::plan_inline_math now owns the per-sequence style
and math-skip state, explicit math glue and penalties, and automatic binary or
relation break decisions. It returns a backend-neutral plan containing formula
expressions, active styles, nested-list contexts, mu glue, and break penalties;
the application measures formulas, converts mu units, and feeds Knuth–Plass.
The \penalty primitive now emits a typed penalty event. In inline math it
becomes a zero-width math-list node; in Rust-owned paragraph layout it becomes
a horizontal penalty, and in vertical mode it is passed to the Rust page
breaker, following the penalty-node handling in tex.web. The compatibility
macros \allowbreak and \nobreak expand to penalties 0 and 10000. An
explicit penalty immediately after a relation or binary noad supersedes the
automatic break penalty there.
Horizontal \\hskip scans a full glue value, including plus/minus
amounts and fil orders. texrra-core::glue::TeXGlue is the engine-owned
value used by paragraph and math lists; engine::glue re-exports it for
existing scanner code. Explicit horizontal glue
stretches or shrinks with its line and retains TeX's glue-order priority.
Vertical \\vskip also scans a full glue value and passes width, stretch,
shrink, and orders to the Rust page breaker. Positioned pages currently use its
natural width; page-level glue setting and stretch distribution remain to be
ported.
crates/texrra-core/src/mouth.rs owns the TeX input scanner and emits token
values from shared core types; src/rust_typeset/engine/mouth.rs is a
compatibility re-export. The core crate also owns category-code and math-code
types, plain TeX category-code defaults, TeX macro definitions and tables, and
macro argument/replacement algorithms. Texlang re-exports the shared
category-code and math-code types as a compatibility API. The scanner handles
line-state transitions,
control-sequence names, comments, ignored and invalid characters, ^^ notation,
and source spans without calling Texlang's lexer. CatCodeTable stores the
shared core catcode values and keeps a save stack for local assignments,
clearing saved values on global assignments. The Texlang \catcode variable
adapter mutates this same table. texrra-core::math_code::MathCodeTable owns the
per-character math-code values, while texrra-core::math_code::UnicodeMathCodeTable and
texrra-core::math_code::DelimiterCodeTable own Unicode math-code values and delimiter registrations.
Math-token lowering and the Texlang \mathcode, \Umathcode, and \delcode
adapters use the engine tables, which now own local/global assignment saves
and restore them on engine group exit. Their Texlang variable adapters opt out
of the VM save stack, avoiding two competing owners for grouping state.
Group exit restores the shared value once. Brace groups and the
\begingroup/\endgroup primitives enter and leave the engine stack, so the
live lexer observes active catcodes while reading subsequent source.
The \endlinechar variable now reads and writes the same engine-owned state;
the table preserves its value across local groups and clears saves for global
assignments.
The mouth treats values from 0 through 255 as active character codes, matching
XeTeX's end_line_char_inactive check in xetex.web.
texrra-core::assignment_scope::AssignmentScope owns \globaldefs and its group
save stack, and selects assignment scope. The engine-owned tables record the
old values for \catcode, \endlinechar, ordinary/Unicode math codes, and
delimiter codes; EngineSemanticState opens and restores these scopes with
each group. Scope selection applies positive \globaldefs values globally,
negative values locally, and zero uses the prefix command, following
the globaldefs adjustment in TeX's prefixed_command.
engine::prefix now scans \global, \long, and \outer, skips intervening
spaces and \relax, and validates targets from the command registry's tags.
The command registry remains the dispatch adapter. The prefix scanner validates
\long and \outer placement and stores those flags on engine macros.
Non-long macro argument scanning rejects \par, with the delimited-parameter
exception for a partial delimiter match; outer macros are rejected in Rust
macro-argument scans, shared braced/optional argument scans, generic Rust
token-list scans, and expanded definitions. The token-list adapter checks its
captured unexpanded tokens and preserves the existing token-register path.
Outer checks in other TeX scanner contexts remain to be ported.
Unstarred \newcommand definitions are long; starred
definitions are non-long. These rules follow TeX's long_state argument
scanner
and outer-token check.
The \bgroup/\egroup compatibility macros use the same group path.
The vendored command map has a local save stack for control-sequence and active
character definitions. Local assignments restore at group exit; global
assignments clear saved values across open groups. Active-character meanings
are included in serialized VM snapshots.
The checkpoint scanner uses the project-owned mouth for whitespace, comments,
control-sequence, and ^^ tokenization. Both preamble-start discovery and
body checkpoint discovery use it. It models direct decimal and backtick-character
\catcode assignments and direct signed-decimal/backtick \endlinechar
assignments with the same local/global save stack as runtime state. Body
checkpoints are placed at top-level paragraph tokens; discovery still stops
adding later checkpoints around \globaldefs, primitive definitions, and
verbatim-like environments. Catcode and \endlinechar changes hidden inside
arbitrary macro expansion are not visible to this locator, so preamble
checkpoint detection remains a heuristic.
The document, compatibility prelude, \input files, and .sty files now use
the project-owned mouth at runtime. \newcommand, \renewcommand,
\providecommand, \def, and \gdef definitions are stored in the
engine-owned MacroTable; texrra-core::macros scans the target, parameter
text, and grouped replacement body through a generic token-stream interface,
then parses parameter prefixes, sequential numbered parameters, delimiters,
and replacement references. texrra-core::expansion scans and substitutes arguments.
The Texlang adapter supplies the unexpanded token stream and maps engine
diagnostics back to source tokens.
\let copies engine-owned macro meanings as well
as ordinary command meanings. \edef / \xdef expand replacement tokens
inside a bounded input list and store the resulting definitions in the same
Rust table. These definitions follow local and global grouping scope. The table
stores macro names and parameter-matching token values independently of
Texlang's interned control-sequence IDs. Texlang invokes a Rust macro-expansion
hook before command lookup for both ordinary expansion and expand_once, so
the engine table decides macro expansion. Command-map entries remain reflection
markers for primitives that inspect command meanings. Replacement bodies and
scanned arguments use engine-owned EngineToken values with numeric trace IDs;
a separate adapter table maps those IDs to Texlang trace keys when producing
source diagnostics. Parameter matching, argument scanning, and replacement
instantiation operate only on engine token values in texrra-core. The
Texlang bridge converts tokens at the unexpanded-input
boundary and converts completed replacement tokens back before placing them on
the VM expansion stack. Primitive dispatch and \read still use Texlang paths. Runtime
\begin / \end now use the serialized engine-owned
EnvironmentStack; a mismatched close is rejected before its event reaches
document parsing. Non-document environments use the engine save stack for
local assignments. This is a first execution migration, not a replacement for
Texlang's general primitive expansion, execution loop, or primitive dispatch.
The current typesetting layout remains a subset. The next execution boundary is
to move remaining expandable primitives, assignments, and error handling
behind engine-owned state while preserving a comparison path against XeTeX.