Files
texrra-engine/docs/NATIVE_EXECUTION_CORE.md

27 KiB
Raw Permalink Blame History

Route-D native execution bootstrap — 2026-11-01

2026-11-02 更新:G1 与 W1-S1–S7及W2-S1累积完整验收 1266 / 0、CLI28,见 P2-M1 进度 与 原始字节输入。 原样 kernel 仍529 overfullrule,完整入口仍 pdfoutput;格式尚未启动成功。 原生语言/断字已接通,W1字体单位与连字重构依赖W2。 整数TFM底座已验收,继续动态字体接线, 页面等W3–W7仍未完成。 以下较早验收和边界属于历史记录,以最新状态为准。

The native bootstrap, extended macro/integer, job/stream and quantity slices are accepted: 1204 workspace tests passed, 0 failed, with 90 real pdfTeX INITEX token/parameter probes, 101 dimension/glue comparisons, 119 paragraph comparisons, 205 box packing comparisons, 117 math geometry/list and 88 math break comparisons, 100 interline vlist and 64 page-ownership comparisons, 58 display vlist, 36 page and 24 quantity/mode/pack cases, 12 real filesystem byte comparisons, 2816 font-slot predicates + four font queries, 61 diagnostic and 267 dimension/missing-count cases, 438 accent DVI geometry and 28 mutable-hyphen timing cases, 452 delimiter DVI geometry cases and 256 default-code/nine state/seven group readbacks, and a selected/discarded shipout oracle. This is a bootstrap kernel with native measured paragraphs, nested hbox/vbox/vtop and inline noad construction, not complete TeX or LaTeX format execution.

Ownership and entry points

The implementation is in crates/texrra-tex-core/src/execution:

File Responsibility
mod.rs owned token/category/source/event types; strict paragraph lowering
mouth.rs lazy physical-line scanner, dynamic categories, ^^ conversion
state.rs command meanings, macro token bodies, scoped save stack, integers
engine.rs input stack, token expansion, primitive execution, diagnostics
job.rs explicit job timestamp, stream metadata and typed output whatsits
registers.rs typed dimensions/glue/mu glue, orders and TeX decimal printing
engine/quantities.rs fixed-point quantity scanning and register arithmetic
parameters.rs, paragraph.rs, engine/paragraphs.rs scoped parameters, native text nodes, actual line breaking and command execution
diagnostics.rs, engine/diagnostics.rs owned semantic box/list trees, actual breadth/depth printer and showbox event/output
boxes.rs, engine/boxes.rs nested modes, box registers, actual hpack/vpackage and diagnostics
math.rs, engine/math.rs native math tokens/fields/noads, families, conversion and actual penalties
fonts.rs, engine/fonts.rs actual TFM/Type1 slot/encoding state, font predicates and missing-character diagnostics
math_delimiter.rs actual font-family size search, TFM variants/recipes and axis-centered raw component geometry
math_accent.rs actual resource skew kerns, cramped clean fields, accent variants, scripts and frozen geometry
engine/display.rs display mode transitions, shifted measured math boxes, actual penalties/skips and paragraph continuation
paragraph.rs, engine/paragraphs.rs selected discretionary flags and summed interline/club/widow/broken penalties into actual vlist/page consumers

The CLI host in src/native_job.rs owns the real local clock and filesystem handles; it has no macro/template or alternate-engine implementation.

It imports no texrra-core, Texlang, rust_typeset or old semantic frontend. The host chooses a SourceProvider; the executor never launches a TeX engine. Source characters become tokens once. Macro bodies retain definition-time categories; active characters and control symbols have different namespaces.

SourceProvider -> lazy mouth -> input/expansion stack -> scoped native state
                                      |
                                      v
                              typed execution events
                                      |
                                      v
                         Route-D paragraph/page lists -> SVG/PDF

Executed characters build native glyph/glue nodes with exact embedded TFM metrics; paragraph parameters are consumed at their actual construction stage. See native paragraph scope and verification. Control sequences are not printed into a new LaTeX string and reparsed. A regression changes backslash to category Other and verifies that documentclass stays raw text through painting; the actual OT1 slot92 paints quotedblleft, rather than a substituted Unicode backslash. Category-Other byte32 paints its genuine slot; category-Space remains glue. Unsupported commands/modes, resources, shaping and out-of-range byte-font characters fail with source diagnostics.

cargo run --release -- native examples/native-bootstrap/main.tex /tmp/bootstrap.pdf
cargo run --release -- native --initex path/to/bootstrap.tex /tmp/bootstrap.pdf
cargo run --release -- native --initex --etex examples/native-bootstrap/etex.tex /tmp/etex.pdf

The native CLI returns before construction of the server/v1 compiler. Unsupported commands never dispatch to v1 or the transitional Route-D string frontend. No output PDF is overwritten on execution/lowering failure; an empty bootstrap job produces messages and no PDF. Default native mode supplies usual TeX text categories but no plain/LaTeX macros. The initex option uses INITEX initial categories, with braces/parameter/math characters initially Other. The explicit etex flag selects State::with_etex / Profile::EtexBootstrap. The base bootstrap does not expose eTeXversion or the new extended expansion primitives. This partial profile is separate from any future complete pdfTeX or XeTeX product profile.

Existing HTTP/project preview and PDF routes still use the transitional Route-D frontend. They were not switched to this incomplete kernel. There is no automatic native-to-string/v1 fallback. Their replacement requires native format and mode/list coverage, not capability guessing over source text.

Implemented semantic slice

  • Physical CR/LF/CRLF lines, trailing-space trimming, comments, blank-line par, control words/symbols, active characters, ^^ encoding and UTF-8 byte spans. The later input profile slice retains original bytes and decodes explicit TeX8Bit or UnicodeScalar input in the same native mouth. This is not full pdfTeX/XeTeX format or font conformance. endlinechar is frozen when a physical line is read. Category changes affect unread input, including control-word lookahead.
  • Local/global definitions and register/category assignments; save entries are removed at every enclosing level on global assignment. globaldefs and typed simple/semisimple group closing are honored.
  • def/gdef/edef/xdef, long, let, consecutive parameters, literal prefixes, balanced undelimited/delimited arguments, nested definitions and doubled #. ifx compares semantic token meanings, not source locations.
  • Hash-brace parameter syntax consumes its delimiter brace and appends it to the replacement, including the no-argument and literal-delimiter cases.
  • expandafter, noexpand, csname/endcsname, string, number/the. Explicit spaces inside csname are retained. Message printing follows current categories.
  • count/countdef, signed decimal/octal/uppercase hexadecimal/character constants, catcode queries/assignments, endlinechar/globaldefs, advance, multiply/divide with TeX bounds and truncation toward zero.
  • chardef has distinct character-given meaning for integer reads, ifx and character execution. newlinechar/escapechar are scoped integer parameters and affect diagnostic/token printing in their respective roles.
  • mathchardef stores a distinct 15-bit mathematical character meaning, with integer/the/number/let/ifx/meaning and scoped/global semantics. Executing it consumes the actual class/family/slot in native math mode and errors outside it.
  • inputlineno uses the physical mouth/input stack, restores caller positions across nested input, and retains the final scanner position for explicit continuation/shipout I/O. Macro definition/call spans are not substituted.
  • dimen/dimendef, skip/skipdef, muskip/muskipdef supply native typed registers, scopes, aliases, assignment, advance/multiply/divide, the/number and ifdim. Scanning uses exact fixed-point absolute units/internal units/mu and ordered stretch/shrink, with overflow/unit checks and TeX decimal printing.
  • time/day/month/year read the explicit host snapshot, with local/global scoped assignments. The CLI captures one actual local timestamp per job; library reads without a supplied time or assignment error rather than using fake values.
  • toks/toksdef, local/global assignment and copying preserve token categories, provenance and save-stack restores; the in definition/message expansion copies register tokens without recursively expanding them.
  • iftrue/iffalse/ifx/ifnum/ifdim/ifdefined/if/ifcat/ifodd/ifcsname/ifeof, ifcase/or, else/fi. if/ifcat normalize non-character commands as TeX does, including noexpanded active tokens; ifcsname does not create an undefined name. Skipped branches are scanned without macro expansion or assignments. ifvmode/ifhmode inspect actual current mode. ifinner reflects restricted-horizontal/internal-vertical nesting and native math mode; ifmmode reads the actual math frame. ifvoid/ifhbox/ifvbox execute against actual box registers. iffontchar scans actual font selectors/current font/three-size math families and queries real TFM slot presence, with resource dependencies and operand bounds.
  • Native box/list construction and diagnostics are accepted; see native boxes. hbox/vbox/vtop, setbox/box/copy, wd/ht/dp, prevdepth, vskip/kern/penalty, rules, glue orders, vbadness/vfuzz/boxmaxdepth/hfuzz and actual badness have consumers.
  • Native inline math tokens, mathcodes/active meanings/fam, fields/scripts/styles, real font families and noad conversion; generated binop/rel penalties feed actual paragraph breaking. Natural hpack checks update real badness. See native math scope and limits.
  • Actual paragraph-to-vlist interline/club/widow/broken penalties, frozen at par completion from selected line breaks. Zero sums are omitted; all applicable terms add, including club/widow for two lines. The strict native page consumer receives actual penalty nodes; see interline scope.
  • Native unnumbered display mode: actual display-widow paragraph completion, natural-width/visible pre-display sizing, normal/short skips, pre/post penalties, shifted hpack, depth propagation and unindented continuation. Native page glue packaging and best-candidate fire_up consume the same lists. MathChar and trailing italic kern remain separate semantic nodes; see native display scope.
  • Native raw CMR10 OT1 slots through lig/kern and Type1 export, real OT1/OML/OMS/OMX resource metadata and TFM char_exists. Scoped tracinglostchars/tracingonline (62 typed parameters total) consume actual missing text/math/hyphen characters; log/terminal observers preserve timing and propagate errors, with fatal PDF protection. Unknown resources and present-but-unsupported text shaping remain errors. See font diagnostics and 128-slot raster evidence.
  • Resource-owned mutable skewchar/hyphenchar integers, separate from selectors; strictly global TeX mutation, first-load scoped defaults and repeated-load reuse. Defaultskewchar has real consumers. Native mathaccent owns a real noad field, fetches actual fonts and TFM skew/variant/x-height metrics, handles scripts/ cramped fields and freezes raw glyph geometry. Explicit/literal/automatic hyphen timing uses actual font state. See font-state/accent scope.
  • Scoped delcode tables and delimiter/left/right fields, owned MathLeft group lists, two-pass extent/original-style sizing with actual delimiterfactor/ delimitershortfall and null-space consumers. Actual family/TFM variant and extensible searches skip missing candidates without false missing-character diagnostics; component allocation is bounded. Invalid code-table arithmetic targets return errors. Shared odd-sp fraction/reboxing rounding now preserves TeX declared depth versus actual glyph baselines. See delimiter scope.
  • Showboxbreadth/showboxdepth and showbox inspect real registers without moving, repacking or ending the paragraph. Original nodes/settings, selected line material and named vertical glue are retained before paint lowering. Real recursive printing includes breadth/depth markers, byte/ligature/font names, glue/kern/penalty/discretionary semantics and source spans. Semantic-only box views avoid exponential paint-tree duplication. Latest actual font definition identifiers, restricted hbox hyphen behavior and INITEX newlinechar=0 match independent TeX probes. Event::ShowBox and optional paired live observers deliver actual transcript/terminal bodies and shared newline transitions. The noninteractive CLI exports the continued PDF then returns show status 1; fatal errors still protect existing output. Compound math/glue inspection remains explicitly unsupported pending owned structure; see scope.
  • Scoped byte-index sfcode with real INITEX defaults, internal quantity reads, global restoration, state JSON and per-slot dependencies. Actual character construction (including omitted glyphs) updates list-owned spacefactor using TeX zero/low/high transitions. Original spaceskip/xspaceskip node subtypes survive paragraph/hpack/export/diagnostic lowering. Three tests add 256 default/eight state, 132 exact list and nine raw-slot/timing comparisons; see scope and sentence-spacing PDF gate.
  • input/endinput, message/errmessage and end; host-controlled file lookup. The CLI resolver shares working/source-directory lookup and optional .tex suffix, not full Kpathsea. errmessage is terminal; interactive error recovery is absent.
  • openin/closein/read and ifeof use actual host streams and TeX's just-open, final-line and EOF distinctions. openout/write/closeout support real immediate file/log/terminal output and typed deferred whatsits. meaning exposes actual native meanings; control characters print through TeX notation/newlinechar. Message delivery to the CLI occurs live, preserving order with writes.

The explicit e-TeX bootstrap profile additionally implements:

  • protected macro definitions, with semantic ifx flags and normal execution; definition/message expansion preserves them, while integer, conditional and csname scanners still expand them. Protection is a per-scanner context, not a global disable-expansion flag.
  • unexpanded, detokenize and the modern expanded primitive. Balanced group scans accept expanded/aliased opening braces; detokenize preserves control word separators and escapechar. Unexpanded output executes normally when returned to the main input stream.
  • numexpr: signed integer factors, nested expressions/parentheses, precedence, rounded division (half away from zero), combined multiply/divide scaling, integer overflow/division-by-zero checks and bounded scanner recursion.
  • unless; count/toks register numbers 0..32767 (base bootstrap: 0..255); currentgrouplevel/currentgrouptype report actual native save-stack groups.
  • readline supplies raw Other/Space tokens without expanding comments, braces or superscript escapes, unlike normal read tokenization.
  • eTeXversion/eTeXrevision are read-only internal target-interface quantities (2 / .6), available only with this explicit profile. They are not LaTeX replacement macros, and are not evidence of complete e-TeX conformance.

The profile is deliberately named EtexBootstrap: dimension/glue/mu expressions, font-relative/magnification units, remaining layout/page parameters, outer/scanner restrictions, marks, general mode/list state and other extensions are still missing. Deferred I/O has an explicit native shipout-I/O API, but the demo CLI rejects pending whatsits until real mode/list integration; it does not discard or flush them at EOF. No unsupported primitive returns a success value or dispatches to the transitional/v1 engine. See job time and I/O details. See native quantity scope and evidence for exact unit, type/coercion, printing and unsupported-layout boundaries.

Execution retains source files, definition/argument spans and effective call sites, reads of categories/meanings/registers/sources, and incoming/outgoing state fingerprints. Trusted execution snapshots roundtrip through JSON and Executor::from_execution reuses a bootstrap environment with source identity. This is not a stable native format image or a TeX binary fmt loader. IoState contains logical metadata, not OS handles; open-stream continuations require the same live host. Refresh the host time snapshot for a new job. Read-key sets/fingerprints alone do not authorize incremental cache reuse. Native mid-job checkpointing and glyph-to-source maps remain future work. Limits bound execution steps, input depth and individual/output token lists. Synchronous value/expression/expansion recursion is clamped to 32 (or a stricter configured input depth); deep adversarial input fails with a diagnostic rather than overflowing Rust's test-thread stack. This is not full TeX capacity.

Validation and real format boundary

cargo test --workspace --offline -- --test-threads=1
cargo test -p texrra-tex-core --offline --test execution_native -- --nocapture
cargo test --offline --test native_execution
cargo fmt --all -- --check
git diff --check
python3 scripts/probe-native-format.py --binary target/release/texrra \
  --texmf /usr/share/texlive/texmf-dist \
  --json /tmp/texrra-native-execution/format-probe-final.json
  • Six mouth regressions, twelve execution integration tests containing 90 actual pdfTeX -ini -etex probes, seven job/core tests, five quantity/state tests containing 101 real dimension/glue probes, five paragraph tests containing 119 real INITEX comparisons, four box tests containing 205 real packing comparisons, six math tests with 117 geometry/list and 88 paragraph-break comparisons plus a pack-state oracle, four interline tests with 100 vlist and 64 page-ownership cases, five display tests with 58 vlist, 36 page and 24 quantity/mode/pack cases, four font tests with 2816 slot predicates + four font queries, 61 diagnostic cases and 267 dimension/ missing-count cases, and eighteen CLI tests pass. The new 25-word PDF and 128-slot OT1 raster gates also pass. Four new font-state tests add exact integer/global/load/scanner readback, 438 accent DVI geometry and 28 mutable-hyphen timing cases, plus strict serialization/resource/field errors. The 54-word PDF gate and complete-accent ink gate pass. Four delimiter tests add 452 exact DVI cases, 256 default-code/nine state/seven group readbacks, strict capacity/range/group errors and a 61-word PDF/full- delimiter ink gate. Earlier gates and 1sp/0.02bp tolerances remain unchanged. Twelve real filesystem comparisons check bytes; an independent box/shipout probe verifies late expansion and discarded nodes. The extra probes include protected macros in four scanner contexts, token register copying, rounded/scaled expression arithmetic, conditionals, hash-brace macros and readonly version quantities. Negative tests cover missing primitives, unsupported expression families, bounds, prefixes and nesting limits.
  • Coverage includes frozen categories, semantic ifx, global restore entries, delimiters/long arguments, expansion-list barriers, integer bounds, inactive input branches, provenance, snapshot reuse, bounded failures and PDF text.
  • Four diagnostic tests add 152 recursive box/list, 24 paragraph-list and 24 byte-printer exact INITEX cases, plus deep-copy/JSON, source span, aliases/scopes/font names, capacity and sink-failure checks. The new fifth native_job_io test verifies real channels, show status and continued PDF; native_execution remains 12 tests. The release five-show/19-word PDF gate requires exact bodies and intentional nonzero status without weakening existing status-zero or geometry gates.
  • Final full workspace: 1204 passed / 0 failed. An earlier bootstrap run encountered the existing server.log temporary-directory NotFound race. The final serial run passed; server implementation/tests were not changed.
  • Final-release arXiv regression retains the math D gate: three pages, rule y error +0.1035625bp, identical 144dpi formula ink bounds.
  • The native sample exports one PDF page with correct local/global register behavior; its PDF text was extracted and its raster inspected.

The unmodified LaTeX2e 2025-11-01 patch 0 entry is pinned in tests/fixtures/native-format-entry.json:

tex/latex/base/latex.ltx
sha256 95c2ef02c2d92aa29e4a77a5e5a7d9f25b5589143d1e879fb80ffa0b20be1e6d

Real format startup has not passed. The native extended-language profile passes the original e-TeX guard (previous blocker: line 114), reads texsys.cfg, writes texsys.aux with actual job date/time, reads it back, and passes the source's own directory/file equality test. It now stops at latex.ltx:526:1: undefined native control sequence: errorcontextlines, after actual missing-character/resource consumers and unnumbered display/paragraph/page consumers, advancing from mathchardef at 326 and dimension definitions at 347. Mathematical constants, generic allocators, maxdimen/hideskip and zero dimensions/glue execute natively. No guard or input source was rewritten. The CLI regression checks this actual boundary, allocator logs, auxiliary readback and absence of PDF output; the audit verifies the entry hash, nonzero native exit, structured first_blocker and format_boot_passed=false. Only the entry source is pinned; transitive files, configuration and fonts are not certified.

Next work

  1. Follow P2-M1: real format and unmodified article. Begin W0 with complete reference/input/font closure and general native resource lookup. Actual pdflatex.ini currently fails to resolve pdftexconfig.tex; its PDF configuration fails at pdfoutput. The direct latex.ltx boundary is still errorcontextlines at 526. Do not equate those entry points or bypass PDF/true-unit/page consumers with host defaults. G1 remains paused. Its actual input-context/errorcontextlines/show/showthe dependencies are planned within W1; no unused flags or fabricated backtrace. Broader math/showlists diagnostics require owned structure and stay bounded by actual stage needs, rather than replacing format/font/page work. Accepted native box/list diagnostics, native delimiter fields and TFM assembly, resource-owned font integers, mathaccent and missing-glyph consumers already use actual state; see font-state scope and diagnostic scope. Never register unused defaults or substitute fonts. Native display, interline penalties, native inline math, boxes/vpack and paragraphs are accepted slices. Do not register dummy values, rewrite capability guards or simulate LaTeX macros. Complete code tables, quantity expressions, font/magnification state, outer/scanner restrictions and remaining conditionals with independent INITEX oracles.
  2. Extend accepted native display/inline/paragraph/box modes through equation numbers/alignments, remaining math primitives/fields, unboxing/vsplit, whatsits and output/shipout. Measured lists are frozen; page/canvas settings remain host policy. Preserve direct measured geometry and integrate actual output whatsits without a source-string adapter or artificial end-of-job I/O flush.
  3. Pin the full format input closure and implement versioned native dump/load; then boot the real format and an unmodified minimal article.
  4. Add dependency versions, resumable input/mode checkpoints, cancellation and source maps before native execution caching or default HTTP migration.
  5. Close the measured font/format gaps through native font state, TFM/VF/ encoding/map resolution and real NFSS/format execution. The existing arXiv text uses Liberation Serif/Mono versus reference Nimbus Roman/SFTT1000; math acceptance is not full text/format fidelity. See font and format audit.

Current sfcode evidence: /tmp/texrra-native-sfcode/; full workspace/release, three new core tests, nine PDF gates, diagnostic job, three ink gates, format probe and Math D are recorded there. Eighteen CLI tests include the retained first-showbox regression; G1 context work remains paused/incomplete. Earlier box/list diagnostic evidence: /tmp/texrra-native-diagnostics/; see scope/gates. Final logs: accepted-workspace.log, accepted-release.log, accepted-core.log and accepted-cli.log in that directory. Earlier delimiter evidence: /tmp/texrra-native-delimiters/; see scope/gates. Final logs: /tmp/texrra-native-delimiters/accepted-workspace.log and /tmp/texrra-native-delimiters/accepted-release.log. Earlier font-state/accent evidence: /tmp/texrra-native-skew/; see scope/gates. Final logs: /tmp/texrra-native-skew/accepted-workspace.log and /tmp/texrra-native-skew/accepted-release.log. Earlier font-slot evidence: /tmp/texrra-native-fonts/; see scope/gates. Final logs: /tmp/texrra-native-fonts-accepted-workspace.log and /tmp/texrra-native-fonts-accepted-release.log. Earlier display evidence: /tmp/texrra-native-display/; see scope/gates. Final logs: /tmp/texrra-native-display-accepted-workspace.log and /tmp/texrra-native-display-accepted-release.log. Earlier interline evidence: /tmp/texrra-native-interline/; see scope/gates. Final logs: /tmp/texrra-native-interline-workspace.log and /tmp/texrra-native-interline-release.log. Earlier math evidence: /tmp/texrra-native-math/; see math scope/gates. Final logs: /tmp/texrra-native-math-accepted-workspace.log and /tmp/texrra-native-math-accepted-release.log. Earlier box evidence: /tmp/texrra-native-vpack/; see box scope and gates. Earlier paragraph evidence: /tmp/texrra-native-paragraph/; see scope, gates and commands. Earlier quantity evidence: /tmp/texrra-native-registers/ contains quantities.pdf/png/txt/log, format-probe-final.json, arxiv-regression.pdf and math-regression.json. Logs: /tmp/texrra-register-workspace.log, /tmp/texrra-register-core-tests.log, /tmp/texrra-register-cli-tests.log and /tmp/texrra-register-release.log. Earlier evidence remains under /tmp/texrra-native-job/, /tmp/texrra-etex/ and /tmp/texrra-native-execution/; font/format differences remain open.