Skip to content

compiler: adopt tex-expansion (r2) without the HW1 keystroke regression (supersedes #108) - #130

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

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

Conversation

@GoKubar

@GoKubar GoKubar commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Supersedes #108. Commander assignment (issue #2): the tex-expansion adoption, with the HW1 keystroke regression removed and rebased onto current main.

Base: main 1d4604d4, merged in; the only conflict was in the first merge. Scope: crates/compiler and crates/tex-expansion. crates/render-pipeline/vendor/* is untouched; render-pipeline was verified in a scratch copy only. Also regenerated: the generated "Supported LaTeX" section of docs/user/compiler.md, produced by crates/compiler/scripts/render_supported_latex.sh and enforced by tests/supported_latex.rs.

What changed since #108

  1. Merge conflict in parser.rs, from FT-061: amsmath inline constructs (genfrac/binom, \big, phantoms, operators, substack, smallmatrix, dcases) — corpus 20/42 -> 40/42 #103's \DeclareMathOperator. FT-061: amsmath inline constructs (genfrac/binom, \big, phantoms, operators, substack, smallmatrix, dcases) — corpus 20/42 -> 40/42 #103's parser arm used the parser macro table that this PR removes. \DeclareMathOperator is now a host-prelude definition in the engine: \newcommand\cmd{\operatorname{text}}, or \operatorname* when starred. The Commander's design call allows this when the engine models the command faithfully. Checked against main's FT-061: amsmath inline constructs (genfrac/binom, \big, phantoms, operators, substack, smallmatrix, dcases) — corpus 20/42 -> 40/42 #103 output on 6 cases (fixture 30, plain, starred with limits: true, overriding \sin, spaced arguments, redefinition): the parsed blocks are identical. The only difference is the redefinition diagnostic. It now uses LaTeX's own text ("Command \tr already defined.") and points at the second declaration (bytes 61..62); main reports 30..55. The three definition names keep a no-op dispatch arm, so the supported inventory still matches the parser arms.
  2. Root cause of most of the HW1 regression: the kernel prelude was lexed as source 0, the same id as the document. Its macro spans therefore aliased document bytes 0–4 KB. Any edit in that range shifted those spans in the old checkpoints, so HW1 keystrokes never converged (converged_at: None): the whole rest of the document was re-expanded on every keystroke. The prelude now has its own source id, and HW1 typing converges at the next checkpoint.
  3. Copy-on-write engine state (tex-expansion/src/scopes.rs). Every table is a CowMap: 2^k copy-on-write chunks behind a copy-on-write chunk table, with FxHash inside. The save stack is made of copy-on-write frames, integer parameters are an array, and counter reset lists sit behind Rc. A snapshot only bumps reference counts. Each chunk and frame stores an upper bound on the end offsets of its document spans, and a shift never changes a span that ends before its edit start. State::eq_mapped uses this to skip shared chunks below the bound and compares the rest entry by entry, without allocating shifted copies. The old path rebuilt the whole state for every comparison.
  4. Checkpoints every 512 bytes (previously 2048). Denser checkpoints are cheap now.
  5. No per-parse copy of the token stream for glued-word splits (\\[3pt]Next, \\*, \cmidrule(lr)). On HW1 this copy was about 3.6% of keystroke samples. P::token_mut borrows the stream from the thread's cache and edits it in place with an undo log. The stream is restored before it goes back, and a cache whose stream never came back is rebuilt. Covered by tests/expansion_lend.rs.
  6. Prelude-raised engine diagnostics are reported at document bytes. Before, they had no span.
  7. Supported inventory. In release builds, canonical_names_outside_the_inventory_are_diagnosed failed on the branch while passing on main. The engine runs 24 canonical kernel commands without a diagnostic (\newcounter, \setcounter, \newenvironment, \providecommand, \AtBeginDocument, \long, \space, \jobname, and others), but the inventory did not list them. They are now listed as Origin::Expansion, with their argument shapes and engine behaviour. Kernel coverage goes from 104 to 128 of 410.

Not done: task item 4, a fast path that skips expansion when nothing macro-related changed. The regression was gone without it, and I did not want to add it without an equivalence proof.

Gates: main 1d4604d4 vs. this branch

Same machine (M5 Pro), with other agents building; the load average is recorded for each measurement.

Gate main branch
compiler cargo test --release 370/0/4 373/0/4 (+2 expansion equivalence, +1 lend)
compiler cargo test (debug) fails canonical_names… (a debug_assert on \and) and aborts robustness::deeply_nested_input… (stack overflow) the same two, plus the release gate above
tex-expansion cargo test --release — 55 unit, 3 incremental-equivalence and the oracle suite, all green (the oracle covers 415 cases per #108)
real-world corpus, compiler producer, 9 fixtures (main 3f7fd9b1 vs. branch 72e35eda; no compiler source changes since) 125 diagnostics 124: the cv false positive "macro \entry received an empty required argument" is gone. Status and pages match on all 9; every other message and span is identical.
render-pipeline cargo test --release (scratch copy with the branch compiler vendored) 135/0/1 135/0/1
FT-065 perf_bench reply digests (HW1/HW2, 20 scenarios, 3 rounds) — identical in every round; the round-1 --verify-fresh reported no mismatch
edit_latency_bench reply digests (HW1 and 500 KB) — identical

Compiler level: warm keystroke, edit_latency_bench session p50 (ms)

4 rounds in alternating order, load 4.6–5.8.

scenario main (4 rounds) branch (4 rounds)
HW1 type paragraph 0.852 0.798 0.773 0.789 0.842 0.774 0.716 0.752
HW1 inline math 0.896 0.835 0.780 0.754 0.700 0.735 0.711 0.709
HW1 display eq 0.828 0.815 0.739 0.757 0.694 0.722 0.706 0.703
HW1 delete/restore 0.794 0.715 0.721 0.740 0.670 0.680 0.697 0.690
500 KB type paragraph 25.8 25.5 23.5 23.4 17.1 17.5 17.7 17.2
500 KB delete/restore 30.8 35.9 29.9 33.5 23.5 23.2 22.4 22.9

HW1 protocol-path p50: main 0.917–1.037, branch 0.853–0.912. HW1 "type paragraph" session p50 after each step, measured in same-run A/B pairs: merged #108 0.97–1.11 → prelude source id 0.86–0.92 → copy-on-write state 0.78–0.83 → 512 B checkpoints and lent stream 0.72–0.87. Main ranged 0.75–0.85 in those runs.

Render level: FT-065 perf_bench p50 (ms)

3 interleaved rounds, load 3.6–4.1.

scenario main branch
HW1 type-paragraph 1.21 1.09 1.10 1.07 1.05 0.98
HW1 type-inline-math 1.15 1.08 1.03 0.99 0.94 0.93
HW1 type-paragraph +v2 1.92 1.68 1.69 1.88 1.55 1.54
HW2 type-paragraph 1.32 1.23 1.37 1.11 1.08 1.11
HW2 type-paragraph +v2 1.91 1.73 1.87 1.73 1.58 1.61
HW1 full 2.41 2.37 2.35 2.43 2.20 2.19

Render-pipeline follow-ups

These are for the Commander's re-pin and are not part of this PR.

  • adapter.rs re-parses \newcommand bodies in macro_body/token_gap (around L1995–2190). That can be replaced by the definition spans in Parsed::expansions.
  • From compiler: adopt tex-expansion (round 2) as an expansion pass before the parser #108: \begin{…}/\end{…} no longer put engine group tokens into the parser stream, and a stray } is passed through, so the parser reports "Too many }'s" at its position. With the scratch vendor copy, render-pipeline tests are unchanged (135/0/1).
  • The compiler now depends on ../tex-expansion, so the re-pin must also add vendor/tex-expansion.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

GoKubar and others added 30 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
Conflict in crates/compiler/src/parser.rs: main added a parser-level
\DeclareMathOperator next to the parser's macro table, which this branch
replaces with the expansion pass. \DeclareMathOperator is now a host
prelude definition (\newcommand\cmd{\operatorname{text}}, starred form
\operatorname*), and the definition names keep a no-op dispatch arm so the
supported-LaTeX inventory still equals the parser arms.

Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption r2, mac-m5pro-kabir)
Commit-Executor: Claude Code direct Git
Co-Authored-By: Claude Opus 5 <[email protected]>
The kernel prelude was lexed as source 0, the same id as the user's
document, so its macros' spans aliased document bytes 0..~4 KB. An
incremental edit in that range shifted those spans in the old run's
checkpoint states, the states never compared equal, and every HW1-sized
keystroke re-expanded the whole rest of the document (converged_at: None).
The compiler also mapped those spans into the entry document as bogus
definition spans. Now HW1 typing converges at the next checkpoint.

Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption r2, mac-m5pro-kabir)
Commit-Executor: Claude Code direct Git
Co-Authored-By: Claude Opus 5 <[email protected]>
…ison

Checkpoints cloned the whole assignment state (every macro name and
meaning, registers, save stack) and convergence rebuilt an old state with
shifted spans just to compare it; on HW1 that comparison was the largest
single cost of a keystroke.

- Scopes tables are CowMaps: 2^k copy-on-write chunks behind a
  copy-on-write chunk table, FxHash inside. A snapshot bumps reference
  counts; the first write to a chunk after it copies that chunk only.
- Each chunk and save-stack frame carries an upper bound on the end of
  the document spans it stores. Every span shift is the identity below
  its edit start, so the comparison skips chunks that are the same
  allocation on both sides and lie below the bound, and compares the rest
  entry by entry without building mapped copies (State::eq_mapped).
- map_spans shares chunks the shift cannot change.
- Integer parameters are an array; counter reset lists are behind Rc.

Behaviour unchanged: 55 expand, 3 incremental equivalence, oracle suites
pass; compiler suites unchanged (363 passed); edit_latency_bench reply
digests identical to main.

Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption r2, mac-m5pro-kabir)
Commit-Executor: Claude Code direct Git
Co-Authored-By: Claude Opus 5 <[email protected]>
With copy-on-write engine state a checkpoint costs a few reference-count
bumps and a convergence check compares only what the two runs assigned
since they diverged, so denser checkpoints now pay for themselves: a
keystroke re-expands at most about two intervals of source instead of
restarting up to 2 KB earlier. Compiler suites unchanged (363 passed).

Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption r2, mac-m5pro-kabir)
Commit-Executor: Claude Code direct Git
Co-Authored-By: Claude Opus 5 <[email protected]>
A LaTeX error raised at a token of a kernel or host prelude macro body
(e.g. \newcommand inside the host's \DeclareMathOperator) carried a
prelude span, which the compiler cannot map, so the diagnostic had no
location. State::prelude_source_end marks prelude source ids (preludes
run before any document input); such spans are reported at the document
invocation being expanded, or at the last token read from source text
when look-ahead (\@ifnextchar's \futurelet) dropped the origin.
\DeclareMathOperator{\tr}{..} twice now reports at the second
declaration. tex-expansion suites green; compiler 366 passed.

Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption r2, mac-m5pro-kabir)
Commit-Executor: Claude Code direct Git
Co-Authored-By: Claude Opus 5 <[email protected]>
The parser splits a few glued words in place (\\[3pt]Next, a row's
\\*, \cmidrule(lr)). The stream is shared with the expansion cache,
so each such edit went through Rc::make_mut and copied the whole token
stream: on HW1 about 3.6% of a keystroke's samples.

P::token_mut now borrows the stream from this thread's cache when the
cache holds the same allocation (lend_cached_tokens), edits it in place
with an undo log, and P::restore_tokens undoes every edit before the
stream goes back (return_cached_tokens) and before preamble_source reads
it. A cache whose stream was never returned is rebuilt, not reused. The
local Expansion no longer keeps a second reference. Compiler suites
unchanged (366 passed).

Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption r2, mac-m5pro-kabir)
Commit-Executor: Claude Code direct Git
Co-Authored-By: Claude Opus 5 <[email protected]>
tests/expansion_lend.rs types, deletes and edits around glued words
(\\[2pt]Next, \\*, \cmidrule(lr)) in a 4 KB+ document through the
warm parse_project cache and checks every revision against a parse on a
fresh thread. CONTRACT.md describes the copy-on-write state, the kernel
prelude source id and prelude diagnostics; the compiler README describes
512-byte checkpoints, the lent stream and \DeclareMathOperator.

Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption r2, mac-m5pro-kabir)
Commit-Executor: Claude Code direct Git
Co-Authored-By: Claude Opus 5 <[email protected]>
In release builds supported_latex::canonical_names_outside_the_inventory_
are_diagnosed failed on this branch (main passes): with the expansion
pass, \newcounter, \setcounter, \newenvironment, \providecommand,
\AtBeginDocument, \long, \space, \jobname and 16 more kernel names are
executed by the engine without a diagnostic, but were not in the
supported inventory. (Debug builds hid it behind a pre-existing
debug_assert that fires on main too.)

supported.rs gains Origin::Expansion and EXPANSION_COMMANDS with each
command's argument shape and engine behaviour; the generated artefacts
are regenerated with scripts/render_supported_latex.sh (kernel coverage
104 -> 128 of 410). The text-arms equality test skips expansion-pass
entries; the behaviour probes still compile each one. Release suite:
373 passed, 0 failed (main 370/0).

Implementation-Agent: Claude Opus 5 (subagent kabir-claude tex-expansion adoption r2, mac-m5pro-kabir)
Commit-Executor: Claude Code direct Git
Co-Authored-By: Claude Opus 5 <[email protected]>
@jay3332
jay3332 merged commit 2e4cc89 into main Sep 13, 2026
11 of 18 checks passed
@jay3332

jay3332 commented Sep 13, 2026

Copy link
Copy Markdown
Member

Merged to main via integration/2026-09-13j (Commander).

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