Skip to content

compiler: adopt tex-expansion (round 2) as an expansion pass before the parser - #108

Merged
jay3332 merged 19 commits into
mainfrom
agent/kabir-claude/compiler-tex-expansion
Sep 13, 2026
Merged

jay3332 merged 19 commits into
mainfrom
agent/kabir-claude/compiler-tex-expansion

Conversation

@GoKubar

@GoKubar GoKubar commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Commander assignment (issue #2): adopt crates/tex-expansion into crates/compiler as 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 in crates/tex-expansion/CONTRACT.md, "Host integration additions").

Design (crates/compiler/src/expansion.rs)

  • Engine runs over the entry document (and \input/\include files, resolved by the pass with the parser's own path/cycle/depth rules and messages); output is converted back to the parser's Tokens. The parser's inline \newcommand machinery (define/expand/scopes, recursion limit) is removed.
  • Pass-through: unknown control sequences, braces, math shifts reach the parser with exact spans; the parser's BUILT_INS are host commands (so \newcommand{\section} errors, \renewcommand works). \begin{x}→\x from the engine is rebuilt as \begin,{,x,} with exact piece spans.
  • Spans: direct tokens keep their bytes; replacement-text tokens carry the outermost invocation's \name span (unchanged contract) and a definition span; Parsed::expansions = (invocation, definition) runs.
  • Catcode-sensitive regions: \verb, verbatim/verbatim*/lstlisting bodies, \url/\href URLs 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_argument now fast-forwards instead of re-tokenizing, which previously discarded every later macro expansion).
  • Host prelude: \: un-defined (latex.ltx only uses it inside \@ifnextchar; found by render-pipeline math_spacers); \arraystretch captured at \begin{tabular} (LaTeX's read point); \setlength/\label/\verb un-defined so the parser keeps them.
  • Diagnostics: engine messages (TeX/LaTeX texts) mapped with spans; parser-duplicated ones filtered; a runaway (step limit) names the looping invocation and the rest of the document is typeset unexpanded.
  • Incremental: parse_project keeps a per-thread cache for entries ≥ 4 KB without \input: IncrementalExpander checkpoints + converted-stream marks, prefix reuse and shifted-suffix splice; tests/expansion_incremental.rs proves cached == full after 300 random structural edits and a typing/line-deletion run. Tokens shared with the parser as Rc<Vec<_>>; structure queries (\begin{document}, preamble, \bibitem prescan) read the expanded stream (two fewer tokenizer passes).

tex-expansion fixes found by the compiler suites/oracle: \newcommand errors 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)

  • compiler cargo test --release: 354/0/4 → 356/0/4 (+2 equivalence tests)
  • tex-expansion: 55 unit + 3 incremental-equivalence + oracle (415 cases) green
  • HW1: 3 pages, 3 warnings → identical; HW2: 4 pages, 4 warnings → identical (laid-out text, positions, spans byte-identical on all 9 real-world fixtures)
  • 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)
  • Compiler-level warm keystroke p50 (interleaved A/B, 3 rounds): HW1 0.76–0.84 → 0.89–0.98 ms (+~0.11 ms, open), HW2 0.79–0.85 → 0.78–0.83 ms (parity), 500 KB 33–36 → 27–31 ms (~−17%)
  • render-pipeline against the new compiler (scratch path build; vendor not re-pinned): tests 93/0/1 → 93/0/1; FT-065 perf_bench replies byte-identical (HW1/HW2 compile replies identical after normalising the scratch binary path in a font-search diagnostic; all 10 500 KB scenario digests identical). Render-level HW type-paragraph p50 +~0.2 ms (+v2 +~0.3 ms) under load, 3 interleaved rounds; cache threshold 4 KB vs 16 KB made no consistent difference. 500 KB render keystrokes on main are ~5 s (FT-065 render optimisations are not on main) → no measurable change.

Follow-ups

  • render-pipeline: drop the macro_body/token_gap re-parse of \newcommand bodies (adapter.rs ~1995–2190) in favour of Parsed::expansions definition spans when re-pinning.
  • HW1 residual +0.1 ms: r2 checkpoint snapshot/compare clones the whole state (denser checkpoints measured slower); structurally shared scopes in tex-expansion.
  • Rc::make_mut in tabular cell mutation clones the token stream once per parse for table documents.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

GoKubar and others added 19 commits September 13, 2026 01:43
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
…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
@GoKubar

GoKubar commented Sep 13, 2026

Copy link
Copy Markdown
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, \DeclareMathOperator in the engine, and the release-mode supported-inventory fix. Gate tables are in #130. Leaving this PR open for the Commander to close.

🤖 Generated with Claude Code

@jay3332
jay3332 merged commit 3eb5556 into main Sep 13, 2026
@GoKubar
GoKubar deleted the agent/kabir-claude/compiler-tex-expansion branch September 13, 2026 18:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants