Repository navigation
compiler: adopt tex-expansion (round 2) as an expansion pass before the parser - #108
Merged
Merged
Conversation
New crate crates/tex-expansion implementing catcodes+tokenizer, def/edef/gdef/xdef/let/futurelet, expandafter/noexpand/csname, TeX and e-TeX conditionals (if/ifx/ifnum/ifdim/ifodd/ifcase/newif/unless), grouping with global/aftergroup, count/dimen/skip/toks registers with countdef family and numexpr/dimexpr, and a LaTeX layer (newcommand/renewcommand/provide, newenvironment, counters, @ifnextchar/@ifstar/@namedef/@nameuse). 45 unit tests passing. Implementation-Agent: Claude Fable 5.1 (subagent kabir-claude KC-101, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Fable 5.1 <[email protected]>
…orpus
Fixes found via a 108-case oracle corpus run against real tex/etex/pdflatex:
bare grouping braces must not appear in the content-token stream (matches
real main-control semantics, not \write's scan_toks semantics); \the\dimen
must render via TeX's print_scaled algorithm, not raw sp; \numexpr division
rounds to nearest (ties away from zero); \ifcase must keep skipping on a
negative selector; \setcounter/\addtocounter values may contain expandable
constructs like \value{...}; \count's "..." hex parsing.
Adds tests/oracle/ (generator script + committed manifest.json + expected
fixtures, gitignored tmp/) and CONTRACT.md proposing the crates/compiler
adoption path, known deviations from real TeX, and what's done vs not.
47 unit tests + 108/108 oracle cases green.
Implementation-Agent: Claude Fable 5.1 (subagent kabir-claude KC-101, mac-m5pro-kabir)
Commit-Executor: Claude Code direct Git
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Uncommitted progress from the Fable round-2 session (KC-101 r2), saved when the session was paused to stay inside the 5-hour usage window. Not reviewed or re-tested; resume from here. Implementation-Agent: Claude Fable 5.1 (headless agent kabir-claude KC-101 r2, mac-m5pro-kabir) Commit-Executor: Claude Opus 5 (coordinator session, direct Git) Co-Authored-By: Claude Fable 5.1 <[email protected]> Co-Authored-By: Claude Opus 5 <[email protected]>
…' into agent/kabir-claude/compiler-tex-expansion
…-case oracle) WIP, pushed early on coordinator request; not final. Known open item at this commit: one unit/incremental test run hung after the conditional test-phase change (under investigation); grouping braces not yet emitted. Review fixes to 7dae933: \ifcsname/\@ifundefined true after group restore (is_defined), print_cs spacing per tex.web 262, \detokenize doubles #, \protect/let-to-relax emitted as \relax, incremental checkpoint diag/label offsets were relative after restore, \outer recovery loop in parameter text (Missing { inserted), prefix errors ("You can't use a prefix with"), \newcommand optional args built as LaTeX does (\@Protected@testopt + \\foo[#1]), \newcommand on a defined name keeps the old meaning, zero-arg commands not \long, \expanded, \pdfstrcmp, \eTeXversion, coefficient dimens (.5\dimen0), extra-} argument recovery, \fi during a test inserts \relax, INITEX constructor. Adds oracle modes latex-write/latex-doc/*-err, incremental equivalence tests, keystroke bench, smoke and kernel probes. Implementation-Agent: Claude Opus 5 (subagent kabir-claude KC-101 r2, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
… origins, host commands, \input sources) Additive, default-off options needed to run the engine as a pass in front of crates/compiler's parser: set_emit_grouping keeps catcode-1/2 and \begingroup/\endgroup tokens in the output (after the grouping side effect); next_content_token_with_origin reports the outermost macro invocation span of each token; declare_host_command marks a host-typeset command as defined; push_input/open_input_ids support \input; macro_replacement_text reads a parameterless macro. \newcommand on a defined command now keeps the existing definition (LaTeX's \@notdefinable behaviour). Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
…mpiler-tex-expansion
…sion Grouping braces (explicit and implicit \bgroup/\egroup) and \begingroup/\endgroup are now emitted in the output stream with their source spans (coordinator request from KC-110/PR #96); \aftergroup tokens follow the closing brace. API-compatible: is_group_token() added for consumers that want content only. Nested expansion (edef bodies, macro calls) now counts toward max_expansion_steps, fixing a hang found by the incremental random-edit test; finished token lists are popped before pushing so tail recursion does not grow the input stack. Tests: 52 unit, 3 incremental equivalence, 415/415 oracle. Implementation-Agent: Claude Opus 5 (subagent kabir-claude KC-101 r2, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
…/I-O, \input via host reader Lexer: physical line breaks stand for \endlinechar (incl. -1 and non-EOL catcodes such as \obeylines), CRLF counts once, trailing spaces stripped (input_ln), ^^M inside a line discards the rest, ^^ notation resolved in control-sequence names, fixed a length underflow that made ^^ notation panic past byte 0. INITEX mode (kernel probe only): TeX/e-TeX/pdfTeX parameters as registers, \immediate/\write/\openout/\message/\errmessage/\read stand-ins, \eTeXversion/\eTeXrevision/\jobname. Engine::set_file_reader makes \input read files (otherwise it still passes through). Tests: 55 unit, 3 incremental equivalence, 415/415 oracle. Implementation-Agent: Claude Opus 5 (subagent kabir-claude KC-101 r2, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
…oup tokens Physical line breaks are recognised by the lexer, so the catcode tables no longer mark \n as end-of-line; ^^J inside \write/\typeout text is an ordinary character as in real TeX. With this the latex.ltx probe loads texsys.cfg, expl3.ltx and expl3-code.tex and reaches line 1147. Implementation-Agent: Claude Opus 5 (subagent kabir-claude KC-101 r2, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
…e ignores group tokens CONTRACT.md documents the round-2 API, output-stream contract (grouping tokens), oracle modes (415/415), \long/\outer, counters, \fnsymbol mapping, incremental design and latency (500 KB: p50 5.9 ms, p95 115 ms), smoke over origin/main (42/44 clean) and the latex.ltx kernel probe (line 1147/22470, 130/310 primitives missing, mostly typesetting). Implementation-Agent: Claude Opus 5 (subagent kabir-claude KC-101 r2, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
crates/compiler/src/expansion.rs drives flashtex-tex-expansion over the entry document and its \input/\include files and converts the engine's output back into the parser's tokens. Unknown control sequences and grouping braces pass through with exact spans; replacement-text tokens carry the invocation span and their definition span (Parsed::expansions). \verb, verbatim/lstlisting bodies, \url/\href URL arguments and enumitem \Roman*-style label markers are hidden from the engine by same-length blanking. The parser's inline \newcommand machinery is removed; \arraystretch comes from the pass. tex-expansion fixes found by the compiler suites: ^^ notation length past byte 0 (panic / runaway on fuzz input), a line-ending % produced \par, step limit now bounds every raw read, \newcommand reports LaTeX's kernel errors (non-command name, argument count, undeclared #n). Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
Replaces #88's crate with round 2 (grouping tokens, endlinechar lexer, \input reader, checkpoints). The compiler pass is adapted to it and the host API is re-applied on top, additively: - Engine::next_content_token_with_origin (invocation origins), declare_host_command (Primitive::Host), run_host_prelude, push_input, open_input_ids, input_position, set_emit_unbalanced_close; - IncrementalExpander::with_host / origins(); - \newcommand errors with pdflatex's texts (oracle-checked): Missing control sequence inserted. / You already have nine parameters. / Illegal parameter number in definition of \x. Compiler side: host prelude captures \arraystretch at \begin{tabular} and un-defines \setlength/\label/\verb so the parser keeps them; r2's verbatim end, \begingroup/\endgroup/\relax and parser-duplicated diagnostics are handled; recovery evidence regenerated (LaTeX message texts, \loop is now a kernel macro so the runaway case uses \recurse). Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
…n incremental fixes
Large entry documents (>= 16 KB, no \input/\include) keep a thread-local
ExpansionCache: an IncrementalExpander over the blanked text plus the
converted stream with clean marks, so a keystroke re-expands from the nearest
checkpoint and re-converts only up to where the old suffix can be spliced
back (spans shifted). Tokens are shared with the parser as Rc<Vec<_>>.
\arraystretch records are attributed to their marker token so they are kept,
regenerated or spliced exactly like tokens. A document that hits the step
limit is re-expanded from scratch until it no longer does.
tests/expansion_incremental.rs: cached == full (tokens, spans, diagnostics,
arraystretch) over 300 random structural edits and a typing/line-deletion run.
tex-expansion IncrementalExpander (round 2): reused suffix tokens are moved
instead of cloned and carried checkpoints get lazy span shifts (500 KB
keystroke edit 5.0 ms -> 0.9 ms p50); an edit that changes the line count no
longer converges onto old diagnostics that embed a line number ("Incomplete
\iffalse; all text was ignored after line N" kept a stale N).
Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption, mac-m5pro-kabir)
Commit-Executor: Claude Code direct Git
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
parse_project no longer tokenizes the entry twice more after expansion: has_document_environment, preamble_source and bib::prescan read the expanded tokens the parser walks (prescan is generic over Borrow<Token>; its \bibitem numbering now matches exactly the \bibitems P::bib_cursor meets, including macro-produced ones and none under \iffalse). Measured 500 KB parse_project 13.6 -> 8.8 ms p50. Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
…st path HW1/HW2-sized documents now re-expand through the incremental cache (cached keystroke ~0.17-0.21 ms vs ~0.23-0.27 ms from scratch); the converter maps entry-document spans without a hash lookup. Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
…expansion pass Denser checkpoints for small documents (every 256-320 bytes) were measured slower on HW1/HW2 than the fixed interval: each checkpoint clones and compares the engine's whole assignment state. README: the expansion pass, definition spans (Parsed::expansions), verbatim/URL masking, the incremental cache, and the incremental-safety rules that follow from expansion running every revision. Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
…for the compiler adoption Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
latex.ltx (and the r2 kernel prelude) leave \: as an internal \@ifnextchar helper; real LaTeX later redefines it as a medium math space. Without this, $a\: b$ expanded into kernel internals (render-pipeline math_spacers failed against the new compiler). Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption, mac-m5pro-kabir) Commit-Executor: Claude Code direct Git Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
This was referenced Sep 13, 2026
Contributor
Author
|
Superseded by #130 (draft): the same adoption, merged onto current main, with the HW1 keystroke regression removed. Compiler HW1 session p50 is now at or below main (4 rounds). Render-level FT-065 typing is at or below main, with identical digests. Changes: the kernel prelude source id (HW1 keystrokes never converged), copy-on-write engine state, 512-byte checkpoints, the lent token stream, 🤖 Generated with Claude Code |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Commander assignment (issue #2): adopt
crates/tex-expansionintocrates/compileras a compiler-owned pass before the parser.Engine version: tex-expansion round 2 (
agent/kabir-claude/tex-expansion-r2-opus@ e476dba, PR #98) merged in, replacing #88's crate, with additive host-integration API on top (listed incrates/tex-expansion/CONTRACT.md, "Host integration additions").Design (
crates/compiler/src/expansion.rs)\input/\includefiles, resolved by the pass with the parser's own path/cycle/depth rules and messages); output is converted back to the parser'sTokens. The parser's inline\newcommandmachinery (define/expand/scopes, recursion limit) is removed.BUILT_INSare host commands (so\newcommand{\section}errors,\renewcommandworks).\begin{x}→\xfrom the engine is rebuilt as\begin,{,x,}with exact piece spans.\namespan (unchanged contract) and a definition span;Parsed::expansions=(invocation, definition)runs.\verb,verbatim/verbatim*/lstlistingbodies,\url/\hrefURLs and enumitem\Roman*label markers are blanked in a private copy (offsets unchanged) so the engine never interprets them; the parser still reads raw source there (url_argumentnow fast-forwards instead of re-tokenizing, which previously discarded every later macro expansion).\:un-defined (latex.ltx only uses it inside\@ifnextchar; found by render-pipeline math_spacers);\arraystretchcaptured at\begin{tabular}(LaTeX's read point);\setlength/\label/\verbun-defined so the parser keeps them.parse_projectkeeps a per-thread cache for entries ≥ 4 KB without\input:IncrementalExpandercheckpoints + converted-stream marks, prefix reuse and shifted-suffix splice;tests/expansion_incremental.rsproves cached == full after 300 random structural edits and a typing/line-deletion run. Tokens shared with the parser asRc<Vec<_>>; structure queries (\begin{document}, preamble,\bibitemprescan) read the expanded stream (two fewer tokenizer passes).tex-expansion fixes found by the compiler suites/oracle:
\newcommanderrors with pdflatex's texts; incremental edit suffix moved not cloned + lazy checkpoint shifts (500 KB edit 5.0→0.9 ms); stale line numbers in reused diagnostics after a line-count-changing edit.Gates (before = main 8e85309, after = this branch)
cargo test --release: 354/0/4 → 356/0/4 (+2 equivalence tests)tools/real-world-corpus(compiler producer): 9/9 same status and pages; diagnostics 132 → 131 (cv: parser-invented "macro \entry received an empty required argument" gone)Follow-ups
macro_body/token_gapre-parse of\newcommandbodies (adapter.rs ~1995–2190) in favour ofParsed::expansionsdefinition spans when re-pinning.Rc::make_mutin tabular cell mutation clones the token stream once per parse for table documents.🤖 Generated with Claude Code
https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu