Skip to content

compiler: \xspace conditional trailing space - #506

Merged
GoKubar merged 3 commits into
mainfrom
agent/daniel-muse-lead/xspace
Sep 15, 2026
Merged

GoKubar merged 3 commits into
mainfrom
agent/daniel-muse-lead/xspace

Conversation

@d-q222

@d-q222 d-q222 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Scope

Fixes #496. \xspace (xspace.sty) previously errored unknown_command with a misleading did-you-mean-\hspace/\vspace suggestion. crates/compiler/src/parser.rs + regenerated inventory artifacts (project script, not hand-edited).

Mechanism: the expansion pass already flattens every macro call into one token stream before the parser runs, so the token right after \xspace's position already IS whatever follows the macro invocation site — no macro-boundary tracking needed. A fired space flips the just-consumed \xspace token to Space in place via the existing token_mut copy-on-write/undo-log helper (verified this is a genuine pre-existing mechanism, not invented — same one other in-place token edits already use), so a stream borrowed from the expansion cache is lent and undone exactly as it already is elsewhere. A separate resolve_xspace pre-pass handles headings/captions/style arguments, which go through a different flattened-token code path that never reaches the main loop.

Exclusion set implemented: }, another control sequence, and , . ! ? ; : ' / — matches the real xspace.sty semantics. This claim was wrong (see Update below) — fixed in a later commit.

Overlap check

git branch -a --list '*xspace*' — no other branch. coord.py claims — GH-XSPACE held only by me, --branch set.

Test results

Full cargo test in crates/compiler (fresh CARGO_TARGET_DIR, untruncated): 57/57 test binaries ok, 0 failures (lib: 343 passed, incl. 4 new: word-following, punctuation/group/command-suppression, heading/style-argument path, silent package load).

Mutation check (independently re-run by the reviewer): with the space-firing condition forced off, xspace_before_a_word_inserts_exactly_one_space fails (expected ... exactly one word space ...: 90.49 vs 90.49 — i.e. glued, no space); restored with a fresh build, all 4 new tests pass.

Not done

\xspace inside math mode still reports the existing not supported in math mode diagnostic (a pre-existing, differently-coded error; spaces are meaningless in math anyway) — a math-mode no-op arm was judged out of this lane's file scope (math.rs) and left for a follow-up if wanted. \xspaceaddexceptions (customizing the exclusion set) not implemented.

Update (review fix)

Two real gaps found by review, both fixed: (1) the exception set was missing ~, -, ) (xspace.sty's real set is , . ' / ? ; : ! ~ - )), checked against the first character of the following Word token since the lexer folds these into it; (2) "any control sequence suppresses the space" was wrong — real xspace only suppresses before a short explicit list (\footnote, \footnotemark, \bgroup, \egroup, control space), so ordinary commands like \textbf/\emph/\relax now correctly DO get the space, matching real pdflatex \wd measurements. The old test asserting no-space-before-\textbf (which locked in the wrong behavior) was replaced. Also regenerated the stale supported.rs/docs/user/compiler.md one-line description, which still described the old (wrong) rule after the fix. See PR comments for full verification detail (mutation checks, entry-point repro).

🤖 Generated with Claude Code

\xspace at the end of a macro body inserts a word space unless the
token following the call is }, another command, or , . ! ? ; : ' /.
The expansion pass already flattens macro calls, so the next token in
the parser stream is the post-call token: the consumed \xspace token
is flipped to Space in place (main loop) or pre-resolved in flat
heading/caption/style content. \usepackage{xspace} is now silent.

Implementation-Agent: muse-spark-1.3-contributor
@d-q222

d-q222 commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

daniel-parent review (subagent)

Verdict: CHANGES NEEDED

Mechanical precheck (muse-precheck.sh 506): no hard-rule violations, no vendor/ edits, inventory copies identical, no other branch/PR touches \xspace itself (the flagged "overlapping open PRs" are just the routine shared-file churn on parser.rs/supported.rs/supported-latex.json/docs/user/compiler.md that every open compiler PR right now causes — not a real conflict). coord.py claims shows GH-XSPACE correctly state=closed by daniel-muse-lead (closed when the PR opened, per protocol) — the precheck's "no active claim" warning is a false alarm from checking only currently-open claims.

I built real xspace.sty (v1.13, 2014, TeX Live 2026) with pdflatex and dumped hboxes (\showbox) / measured \wd diffs to check this PR's model against actual xspace semantics. Two real correctness gaps:

  1. Missing punctuation exceptions. crates/compiler/src/parser.rs:1367-1372 only suppresses the space before , . ! ? ; : ' /. Real xspace.sty's exception character set (\@xspace@exceptions@tlp) is , . ' / ? ; : ! ~ - ) — this PR is missing ~, -, and ). Since the lexer treats any of these as ordinary printable characters (is_special in lexer.rs only special-cases \ { } % $ ^ _), a hyphen/paren/tilde right after \xspace gets folded into the following Word token, so xspace_inserts_space's word.chars().next() check never sees them as exceptions and wrongly fires a space. Confirmed via real pdflatex hbox dumps:

    • \newcommand{\foo}{Foo\xspace} then \foo-bar → real: Foo and -bar glued directly, no glue node at all. This compiler: inserts a space (- isn't in the excluded set) → wrong "Foo -bar".
    • (\foo) → real: no glue before ). This compiler: inserts a space → wrong "(Foo )".
    • \foo~bar → real: exactly one glue node (from ~'s own interword space; xspace itself contributes nothing). This compiler: adds its own space on top → doubled gap.
  2. More significant: "any control sequence → no space" does not match real xspace. crates/compiler/src/parser.rs:1361 treats every Command token as suppressing the space. Real xspace only suppresses before a short explicit list (\footnote, \footnotemark, \/, control-space) or after recursively expanding an unknown macro to see what it resolves to — ordinary commands still get the space. Verified by measuring \wd differences in real pdflatex/xspace.sty (12pt default class):

    • \foo\textbf{bar} vs Foo\textbf{bar} (no \xspace): width diff = 218453sp = exactly one interword space. Real xspace inserts the space before \textbf{...}.
    • Same result for \foo\relax bar (diff = 218453sp) and a plain user macro expanding to a word (diff = 200248sp, nonzero).

    This PR's own new test xspace_before_group_end_command_or_punctuation_inserts_nothing's "command" case (in the diff, the \foo\textbf{bar} → false assertion) locks in exactly the wrong behavior — it passes only because the implementation is self-consistent, not because it matches real LaTeX. This will misfire for the ordinary case of any abbreviation macro followed by a formatting command (\eg\textbf{...}, \eg\emph{...}, etc.), which is a common real-world pattern \xspace is specifically meant to handle.

Given (1) and (2), the PR body's claim "Exclusion set implemented: }, another control sequence, and , . ! ? ; : ' / — matches the real xspace.sty semantics" is not accurate and should be corrected or the implementation fixed.

Test results (independently re-run): checked out the PR head in a detached worktree (CARGO_TARGET_DIR=target-review3). The 4 new xspace tests pass in isolation (cargo test --lib xspace: 4 passed, 0 failed) — but they only exercise the (incorrect) suppression rule above. A full cargo test --manifest-path crates/compiler/Cargo.toml run got through the entire lib suite and essentially every integration test file with zero failures; I had to kill one long-running, unrelated robustness.rs stress test (no_generated_source_panics_the_parser_or_layout) after several minutes due to shared-machine CPU contention — that's an environment artifact from killing it myself, not a reported test failure, and it's unrelated to \xspace.

Slice 1 claimed the rule matched real xspace.sty semantics; it did not.
Two gaps, both fixed in xspace_inserts_space (crates/compiler/src/parser.rs):

- Punctuation: add ~, - and ) to the exception set (real
  \@Xspace@exceptions@tlp), checked against the FIRST CHARACTER of the
  following Word token since the lexer folds them into it; control-space
  (\ , lexed as the one-character word " ") likewise suppresses.
- Commands: only footnote/footnotemark/bgroup/egroup/space suppress.
  Ordinary commands (\textbf, \emph, \today, \relax, user macros) get the
  space, as real xspace does.

Tests: xspace_before_group_end_command_or_punctuation_inserts_nothing
loses its wrong no-space-before-\textbf case (renamed
..._group_end_or_punctuation_...); new
xspace_before_tilde_hyphen_or_paren_inserts_nothing and
xspace_before_ordinary_commands_inserts_space cover \foo-bar, (\foo),
\foo~bar, \foo\ , \foo\textbf{bar} (typed-space equivalence),
\foo\today (one-word_space layout shift), \foo\relax bar, \foo\baz and
unspaced \footnote/\footnotemark marks. Full crates/compiler suite green.

Implementation-Agent: muse-spark-1.3-contributor
The prior slice's fix corrected xspace's exception set and command
allowlist but left supported.rs's/docs/user/compiler.md's one-line
description describing the old, now-incorrect rule ("another command"
instead of the short explicit allowlist; missing ~ - )). Regenerated
via render_supported_latex.sh so the inventory prose matches the fix.

Implementation-Agent: muse-spark-1.3-contributor
Commit-Executor: daniel-muse-lead (Claude Sonnet)
@d-q222

d-q222 commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Fix pushed (`dea0c8bd`) addressing both review findings, plus a follow-up doc regen (`2b641cb2`).

  • Problem 1 (missing `~`/`-`/`)` exceptions): fixed, checked against the first character of the following `Word` token (the lexer folds these into it).
  • Problem 2 ("any command suppresses"): replaced with the real explicit allowlist (`footnote`/`footnotemark`/`bgroup`/`egroup`/`space`). The old test asserting no-space-before-`\textbf` (which locked in the wrong behavior) was removed/replaced.
  • Caught independently before publishing: the fix left `supported.rs`'s and `docs/user/compiler.md`'s one-line xspace description describing the OLD, now-incorrect rule. Regenerated via `render_supported_latex.sh`.

Independently verified: `cargo test --lib xspace` 6/6 pass, `cargo test --test supported_latex` 8/8 pass (confirms the regen matches, including `generated_artifacts_are_current`). Mutation check (fresh `CARGO_TARGET_DIR`): reverted the `~`/`-`/`)` exceptions → `xspace_before_tilde_hyphen_or_paren_inserts_nothing` FAILED exactly as expected; restored → passes.

One honest caveat the lane found and documented: in this compiler, a space immediately before `\textbf{...}` never reaches layout regardless of whether it's typed or xspace-fired (a group-boundary quirk affecting every `word \cmd{...}` in this compiler, out of this fix's scope) — so problem 2's fix is verified via `\today`/plain-word cases where the shift IS observable, not via `\textbf`.

@d-q222

d-q222 commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

daniel-parent review (subagent)

Verdict: CHANGES NEEDED

This is a re-review of the current head (2b641cb2, worktree fetched via pull/506/head).

Mechanical precheck (muse-precheck.sh 506)

No hard-rule violations, no vendor/ edits. apps/mac/.../supported-latex.json and crates/compiler/supported/supported-latex.json copies are identical. The "no active claim" warning is the same false alarm as last time — coord.py claims shows GH-XSPACE correctly closed by daniel-muse-lead when the PR opened. The listed "overlapping open PRs" are all the routine shared-file churn every open compiler PR causes on parser.rs/supported.rs/supported-latex.json/docs/user/compiler.md — none actually touch \xspace. PR body checklist ok, CI 10/11 success (1 queued).

Earlier findings — resolution

Finding 1 (missing punctuation exceptions ~, -, )): FIXED. xspace_inserts_space (parser.rs:1368) now matches all of , . ' / ? ; : ! ~ - ) plus a literal space (for control-space \ , which lexes as a one-character Word(" ")) on the Word's first character. New test xspace_before_tilde_hyphen_or_paren_inserts_nothing pins \foo-bar → ["Foo","-bar"] glued, (\foo) → no gap before ), \foo~bar → no doubled gap, \foo\ → no doubled gap. I independently verified with real pdflatex + xspace.sty (see below): every one of these cases now matches real TeX exactly.

Finding 2 (the bigger one — "any control sequence suppresses" was wrong): FIXED. The command-suppression arm is now a closed list — "footnote" | "footnotemark" | "bgroup" | "egroup" | "space" — matching xspace.sty's actual \@xspace@exceptions@tlp reachable-as-a-named-command subset. Every other command (falls to Some(_) => return true) now correctly fires the space. New test xspace_before_ordinary_commands_inserts_space checks the decision function directly (textbf, emph, today, relax, a made-up name, and cite all fire; only footnote/footnotemark suppress) plus layout-level equivalence (\foo\today's date sits exactly one word space right of the xspace-free version; \foo\textbf{bar} lays out byte-identically, in both flags and x_pt, to a typed Foo \textbf{bar}). This is exactly the gap flagged last time and it's gone — the previous self-consistent-but-wrong xspace_before_group_end_command_or_punctuation_inserts_nothing test that asserted "before a command → false" has been replaced/corrected (renamed to ..._or_punctuation_inserts_nothing, its "command" case removed, doc comment explicitly calls out the correction).

The PR body's exclusion-set line was also corrected: it now reads "}, another control sequence, and , . ! ? ; : ' /" in the description text attached to the command inventory entries (which additionally lists ~ - ) and the exception command list), matching the actual behavior. (One nit, not a correctness bug: the top-of-body "Scope" prose line still says the plain shorter set — see new finding 1 below.)

Correctness vs real pdflatex (independently re-run)

Built real xspace.sty via TeX Live pdflatex, \sbox/\wd-diff harness, 19 cases in one document ((\foo), group-end, all 11 punctuation/exception marks, tilde/hyphen, ordinary commands \textbf/\relax/user-macro, and the \footnote exception). Real DIFF (pt) vs FlashTeX's implemented decision:

case real pdflatex FlashTeX impl
\foo bar vs glued +3.333pt (one space) fires (matches)
\foo bar vs typed space 0.0pt (identical) fires (matches)
, . ! ? ; : ' / ~ - ) } 0.0pt vs glued (all 12) suppressed (matches, all 12)
\foo\textbf{bar} vs typed space 0.0pt (identical) fires (matches)
\foo\relax bar vs typed space 0.0pt fires (matches)
\foo\baz (user macro) vs typed space 0.0pt fires (matches)
\foo\footnote{n} vs glued 0.0pt (suppressed) suppressed (matches)

All 19/19 match. This is a real, independent confirmation of both fixes — not just re-reading the new tests.

Tests fail without the change (confirmed)

Mutation-tested in the worktree: forced xspace_inserts_space to return false unconditionally → 4/6 xspace tests fail (..._inserts_exactly_one_space, ..._group_end_or_punctuation..., ..._ordinary_commands..., ..._heading_and_style_arguments). Forced it to return true unconditionally → the other 4 fail (..._group_end_or_punctuation..., ..._ordinary_commands..., ..._tilde_hyphen_or_paren..., ..._heading_and_style_arguments) — together all 6 tests are killed by at least one mutant, so they're not vacuous. Reverted before removing the worktree; git diff --stat confirmed clean afterward.

Repro requirement — a real gap in the instruction, not the PR

cargo test -p flashtex-compiler --lib xspace: 6/6 pass (up from 4 last review). cargo test --test supported_latex (crates/compiler): 8/8 pass, including generated_artifacts_are_current and every_inventory_entry_compiles_without_an_unsupported_diagnostic — the latter is a real, non-mocked compile of a document invoking \xspace through the actual fixed crate.

I could not get a real flashtex build/flashtex check (the shipped CLI) to demonstrate this, and confirmed why: crates/flashtex-cli/Cargo.toml hard-points flashtex-compiler = { path = "../render-pipeline/vendor/compiler" } — a byte-for-byte frozen pin (crates/render-pipeline/vendor/VENDORING.md) that predates every currently-open compiler PR, \xspace included. Built flashtex --version/flashtex supported --json from the worktree and confirmed: 858 commands (the pre-PR count), no xspace entry — the installed CLI genuinely cannot see this fix, by design, until a separate vendor re-pin happens. That's out of scope for this PR (and out of scope for me — vendor/ is off-limits). As the closest faithful substitute I built and ran crates/compiler's own standalone worker binary (crates/compiler/src/main.rs, no vendor dependency) directly: flashtex-compiler --supported json → 859 commands, xspace present, matching the PR's claimed +1 text-mode command. This is a process note for whoever wrote the review checklist (every compiler-only PR right now has this same limitation), not a mark against #506.

Other checklist items

  • (a) vendor/ untouched — confirmed, no diff.
  • (d) Body claims — accurate against the current diff (see the one nit below).
  • (f) Vocabulary — xspace was never in KNOWN_UNIMPLEMENTED_COMMANDS (crates/compiler/src/vocabulary.rs) on main or on this branch, so there was nothing to remove; not a gap.
  • (g) Generated artifacts — ran crates/compiler/scripts/render_supported_latex.sh in the worktree: zero diff against the PR's committed docs/user/compiler.md, crates/compiler/supported/{supported-latex.json,coverage.md}, and the mac copy stayed in sync (sync-supported-latex.sh: bundled copy is current). Confirmed regenerated, not hand-edited.

New findings

  1. Minor, non-blocking: the PR body's "Scope" section still states the exclusion set as "}, another control sequence, and , . ! ? ; : ' /" — that's the old, now-superseded rule from before this round's fix. The generated inventory descriptions (which the body itself quotes further down under a different heading) correctly say , . ! ? ; : ! ~ - ) plus the closed command list. Since this is PR body prose (not code or generated content) and doesn't gate anything, I'm not blocking on it, but the author should fix the stale sentence before merge so it doesn't mislead a future reader diffing the body against the code.

No other new issues found. Both substantive findings from the last round are genuinely fixed and independently verified against real pdflatex/xspace.sty and mutation-tested; the only outstanding item is the one-line body-text edit above. Once that's updated (or the author confirms it's intentional, which I don't think it is), this is ready — I'm not aware of anything else standing in the way.

@d-q222

d-q222 commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

daniel-parent review (subagent)

Verdict: READY

Re-review of current head 2b641cb2 (worktree fetched via pull/506/head, matches headRefOid).

Resolution of the prior review thread

The most recent prior comment (07:31:01Z) already confirmed both substantive round-1 findings (missing ~ - ) exceptions; "any control sequence suppresses" being wrong) as genuinely fixed and independently verified against real pdflatex (19/19 cases), leaving exactly one non-blocking nit open: the PR body's top-of-body "Scope" prose still stated the old, superseded exclusion set. That is now fixed — the current PR body has that sentence struck through (~~Exclusion set implemented: ... matches the real xspace.sty semantics.~~) with "This claim was wrong (see Update below) — fixed in a later commit", plus an accurate "## Update (review fix)" section describing the real fix. No outstanding body-text discrepancies found.

Mechanical precheck (muse-precheck.sh 506)

No hard-rule violations, no forbidden-path (Muse scope) hits, both supported-latex.json copies identical. Confirmed independently via git diff --stat origin/main...HEAD -- vendor/ (empty) and the full 5-file diff stat matching gh pr diff exactly (supported-latex.json x2, parser.rs, supported.rs, docs/user/compiler.md) — no vendor/ changes. The "no active claim" warning and "overlapping open PRs" list are the same known false alarms as the prior two rounds (claim correctly closed by daniel-muse-lead; overlapping files are routine shared-inventory churn, none touch \xspace itself).

Independent pdflatex oracle (fresh, this round)

Built real xspace.sty via TeX Live pdflatex with a corrected glued-vs-typed-space \wd-diff harness (\newcommand{\foo}{bar\xspace}):

case vs typed-space reference vs glued reference
\foo world 0.0pt (identical) +3.333pt (one interword space)
\foo. −3.333pt (suppressed) 0.0pt (identical, glued)
\foo, and −3.333pt (suppressed) 0.0pt (identical, glued)

Confirms real xspace.sty semantics exactly as the PR claims: fires before a word, suppresses before ./,.

Built the PR and ran the real compile pathway on the same three snippets

Beyond re-running the unit tests, I built crates/compiler's standalone JSON-Lines worker binary (src/main.rs, the real production entry point, independent of the frozen vendor/ pin) and fed it actual compile requests for the three required snippets via stdin/stdout, comparing item x_pt positions:

  • \foo bar → Foo@72, bar@93.49 — byte-identical to typed Foo bar (Foo@72, bar@93.49), and distinguishable from glued Foobar (single item). Space correctly inserted.
  • \foo. → Foo@72, .@90.49 — gap of 18.49pt equals Foo's own glyph width (no space added). Space correctly suppressed before period.
  • \foo, and → Foo@72, ,@90.49 (same 18.49pt gap, no space before comma), and@96.49 (the ordinary typed space after the comma is correctly preserved, untouched by xspace).

This matches the pdflatex oracle pattern exactly and is a genuine end-to-end confirmation, not just internal-helper unit tests.

Operational note, not a PR defect: my first attempt at this used the shared CARGO_TARGET_DIR=target-review-muse2 per the review instructions, and produced a binary that incorrectly reported \xspace as unknown_command (byte-for-byte the pre-fix diagnostic), despite being linked from a correctly-checked-out PR worktree and despite the lib unit tests passing moments earlier in that same target dir. Rebuilding in a fully isolated, non-shared target dir fixed it immediately and reproducibly (confirmed the lib tests and supported_latex integration tests too, to rule out a false-positive pass from the same corruption). This looks like stale/corrupted incremental-build state from concurrent use of the shared target dir, not a code issue — but it's worth flagging: a reviewer relying solely on the shared dir could currently see a false "regression to the old bug" for reasons that have nothing to do with the PR. Recommend whoever owns target-review-muse2 either serializes bin-target builds harder or reviewers double-check anything that looks like a pre-fix regression with a scratch target dir before reporting it.

Tests not vacuous (verified via git history, given review-only tooling)

I can't hand-mutate the worktree (review-only: no Edit/Write in the repo or any worktree of it), so I verified non-vacuousness by reading the actual historical diff between the PR's first commit (0349eceb, the buggy initial implementation) and the fix commit (dea0c8bd):

  • Old code: Some(TokenKind::Command(_)) | Some(TokenKind::RBrace) | ... => return false (any command suppressed) — directly contradicts xspace_before_ordinary_commands_inserts_space's assertions that textbf/emph/today/relax/baz/cite all fire.
  • Old code's punctuation set was , . ! ? ; : ' / only — directly contradicts xspace_before_tilde_hyphen_or_paren_inserts_nothing's assertions that ~, -, ), and control-space all suppress.

Both new tests pin exactly the two real bugs found and fixed across this review, so they are not vacuous. This corroborates the live mutation-and-revert runs already reported in the prior two review rounds.

Build/test in worktree (step 6)

cargo test -p flashtex-compiler --lib xspace (isolated target dir, to sidestep the shared-dir issue above): 6/6 pass. cargo test --test supported_latex: 8/8 pass, including generated_artifacts_are_current and every_inventory_entry_compiles_without_an_unsupported_diagnostic. --supported json reports 308 text-mode commands including xspace, matching the doc's claimed 307→308 bump.

Conclusion

No hard-rule violations. Both substantive findings from earlier rounds are genuinely fixed and now confirmed by three independent methods (real pdflatex oracle, real end-to-end compile-protocol run, and the existing unit/integration suite) rather than re-reading the prior review's word for it. The one remaining body-text nit from last round is fixed. Tests are meaningful, not vacuous. No vendor/ changes. OK to mark ready.

@d-q222
d-q222 marked this pull request as ready for review September 15, 2026 09:25
@GoKubar
GoKubar merged commit 97143ac into main Sep 15, 2026
21 checks passed
@GoKubar
GoKubar deleted the agent/daniel-muse-lead/xspace branch September 16, 2026 04:16
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.

compiler: \xspace (package recognized, command unimplemented)

2 participants