Skip to content

fix(parser): read a mid-line #! or #+ as a # and the token after it, as beancount does - #2974

Merged
robcohen merged 4 commits into
mainfrom
fix/bom-glued-cost
Nov 14, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/bom-glued-cost

Conversation

@robcohen

@robcohen robcohen commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

What

Part 2 of #2928 (part 1 was #2931). A #! or #+ that does not start its line is now a # and the token after it, as in beancount, instead of one comment-like token running to the end of the line.

  • Lexer (logos_lexer.rs):

    • A Shebang / EmacsDirective token not at column 0 (at_line_start && span.start == last_newline_end is false) is rewritten to Hash, and the lexer resumes right after the #, exactly as the mid-line % rewrite does. The ! then lexes as a FLAG, the + as a PLUS, and the rest of the line as usual. An indented one still gets its Indent.
    • error_later_in_run lexes on past a # the same way, so a lone capital glued to #!x still makes its run one invalid token (A#!x, as in beancount).
    • A column-0 #! / #+ line is still one comment token, as beancount skips it (^[\*\:\#]/.).
  • CST recovery: the mid-line SHEBANG / EMACS_DIRECTIVE special cases are removed, since those tokens now only occur at column 0:

    • the transaction header's #! / #+ defect in txn_header::first_header_defect;
    • indented_comment_check (and its helper flatten_green_matching) in convert.rs;
    • the two-character defect range in directive_header. A header defect at a mid-line # keeps the "Only ; starts a comment in the middle of a line" hint (defect_message now names HASH instead of the two removed kinds).
  • The formatter's string scan already runs the lexer (StringLiterals), so it follows the new lexing; two stale comments there are updated.

  • Diagnostics (name_mid_line_hash_comments, round 1): the line's error names the #! / #+. It is a shared post-pass beside name_misspelled_booleans. It finds each mid-line marker with the lexer itself. Where the marker leads its line (after its indentation), it rewrites the line's first error at or before the # to point at the two characters, with unexpected "#+": only ;starts a comment that is indented or in the middle of a line;#+ starts one only at the beginning of a line. A defect already reported at the # itself (a posting's or a directive header's) is widened to both characters and keeps the same hint. After another token on the line, an error before the # is that token's and is left alone (round 2). Only messages and spans move, on the same line, so no count changes. This replaces the old indented_comment_check message, which named the marker only inside a transaction; it now also reaches a top-level indented line and a directive's metadata, which main read as comments. Pinned with exact message and span in tests/mid_line_hash_bang.rs.

Why

beancount's lexer skips a # line only at column 0. Anywhere else it reads # as HASH and ! / + as FLAG / PLUS, and keeps lexing, so every invalid token later on the line is its own Invalid token error, even after the grammar has given up. rledger read the whole rest of the line as one token, so:

  • invalid tokens after a mid-line #! / #+ went unreported;
  • an indented #+STARTUP / #! line was a comment, where beancount reports it.

Before / after (bean-check 3.2.3; parse errors per line)

Input bean-check 3.2.3 main this PR
2024-01-02 * "x" #!cd 2 1 2
2024-01-02 * "x" #+cd 2 1 2
2024-01-02 * "x" #!c<BOM>d 2 1 2
2024-01-01 open Assets:A #!x 2 1 2
Assets:A 1 USD #!x (posting) 2 1 2
#!x under a transaction, after its postings 2 1 2
#+m in an open's metadata 2 0 2
#+STARTUP: showall (indented, top level) 2 0 2
2024-01-01 note Assets:A "n" #!x $y 3 1 3
2024-01-02 * "p" #! \x11 2 1 2
2024-01-02 "x" #+ y (no flag) 2 1 2
2024-01-02 * "x" #!, #+, #!"y", #! ; c, #!/7 1 1 1 (unchanged)
#! note, #+ note in a transaction 1 1 1 (unchanged)
column-0 #!x / #+y lines 0 0 0 (unchanged)

In an open's metadata, the metadata line after the #+m line is then one error more than in beancount, as it already is on main after any other invalid indented line ( $m); that is beancount's recovery after an error line (#2872).

One field changes with the count: 2024-01-02 * "p" #!x now holds an invalid token (x) after its lone string, so the #2932 rule keeps p as the payee with an empty narration, as it does before any other invalid token (test_parse_invalid_token_after_a_mid_line_hash_bang_keeps_the_payee). Error-free ledgers are unaffected except for indented #! / #+ lines, which are now parse errors as in beancount.

Parse-error parity

compat-parse-error-parity.py at the pinned fuzz commit 9bc79f4f, manifest updated with --update:

  • 78,500 of 111,323 inputs match beancount, from 78,478 on main.
  • 71 newly match (62 fuzz, 9 matrix); 159 mismatches change category (all fuzz); 49 regress (all fuzz).
  • tracked and compat are unchanged.
  • The 49 regressions, checked one by one against beancount 3.2.3. A regressed line is one where main matched beancount and this branch does not; each was also counted standing alone (under a bare 2024-01-02 * header when indented). Corrected in review round 1:
    • 35: every regressed line counts as beancount does when it stands alone, and only in context does rledger report more. That is beancount's recovery after an earlier error line (Parse-error recovery differences from bean-check around invalid dates and column-0 markers #2872), which the old one-token #! / #+ happened to offset by hiding the rest of its line. One of them, 7ce689fbe0fa (regressed line poptag#+a:...), also ends with a BOM inside an invalid run on an indented line ( x<BOM>: bean-check 2, rledger 1 on main and here), a pre-existing difference the review pointed at; its regressed line itself counts as beancount alone.
    • 12: the regressed line holds a bare mid-line \r, which rledger reports on purpose and beancount takes as a blank (fix(parser): a stray \r before the line ending is a parse error; bean-check accepts it #2774, stray_cr_trivia_end). In 7 the \r stands right before a #! (k\r#!x: bean-check 2, main 2, here 3), in 4 it comes after a #+ on the line ({ #+.a\r}), and in 1 the line has no marker, but main's count there matched beancount only through a #! elsewhere in the input. In each, main's #! / #+ comment hid a token and so offset the \r error.
    • 2: a lone capital glued to the token after it, which beancount starts an invalid run with. 2615-2-3!!X!!#+++02 (bean-check 2, here 1, main 2): the rest of the run all lexes, so rledger keeps the capital as a token. A@#!!@"\x12... (e29ba079a13b): the run holds a " whose string runs onto the next lines, which error_later_in_run counts as a token that lexes, so the quote opens a multi-line string that swallows three lines that bean-check reports. That second one is pre-existing (A@"x\nfoo": bean-check 1 error on each line, main and here only line 1), and is now compat(parser): a lone capital glued to a quote opens a multi-line string where beancount reads one invalid token #2977.

BOM combination matrix

  • bom_combination_matrix.tsv is unchanged: it holds beancount's and main's counts, neither of which this PR moves.
  • The generated lists (known, matching, texts) are rewritten by the test itself with BOM_MATRIX_UPDATE=1 BOM_MATRIX_RELABEL=1. 85 rows that now count a line further from beancount than recorded get a known-list reason: every one of them holds a mid-line #! / #+, and what it hid is now read and counted by that row's causes.
  • The hand-kept worse_than_main list:
    • drops 341 lines that are no longer further from beancount than main;
    • relabels 31 lines from bom-glued-to-account&mid-line-hash-bang to bom-glued-to-account (their #! / #+ part is gone);
    • adds 51 lines that a mid-line #! / #+ used to mask on main.
  • holds gains one fallback, main_read_less: a further-than-main line also holds when main's count is exactly what rledger counts with each mid-line #! / #+ and the rest of its line cut off (hash_bang_cut), as main read them, and that cut moves the line's count. hash_bang_cut finds the markers with the lexer, so it never cuts inside a string or a ; comment (round 1). It accepts a line whatever its cause, which its doc says: it explains why main was closer, while the known list still names why rledger differs from beancount. Six listed lines rely on it. Both helpers have unit tests (test_hash_bang_cut_cuts_only_past_a_lines_start, test_holds_takes_a_line_main_read_less_of).

Caches

  • Loader CACHE_VERSION 73 to 74. That cache is saved only for an error-free load. But a ledger with an indented #+ / #! line loaded with no error on v73 and is now a parse error, so a v73 blob would keep serving the old error-free load. The two layout tripwires move to 74; no archived layout changes.
  • WASM CACHE_VERSION 110 to 112, LOADER_CACHE_VERSION_PIN 74. Both payloads archive parse errors and directives. v111 is held by fix(wasm)!: give a validation finding the hint rledger check gives it #2973.

Corpus

rledger check --no-cache and rledger doctor parse -v over all 337 tracked *.beancount files: byte-identical between main (f785188cc68) and this branch.

How to test

cargo test -p rustledger-parser --all-features
cargo test -p rustledger-parser --lib test_tokenize_hash_bang_and_hash_plus_are_a_hash_outside_column_0
cargo test -p rustledger-parser --test txn_header_invalid_token_fields --test txn_header_conformance \
  --test stray_char_matrix --test structured_directives --test format_keeps_hash_bang_lines
cargo test -p rustledger-parser --test bom_combination_matrix
cargo test -p rustledger-loader --all-features
cargo test -p rustledger-wasm --all-features
cargo test -p rustledger-lsp --all-features

Gates run locally: cargo fmt --all --check, clippy --all-features --all-targets -D warnings on parser, loader and wasm, RUSTDOCFLAGS=-Dwarnings cargo doc --no-deps on the same, and the parser, loader, wasm and lsp test suites with --all-features.

Not in this PR

Review round 1

  1. Restored and widened the #! / #+ message (see "Diagnostics" above); pinned in tests/mid_line_hash_bang.rs under a posting, at the top level ( #+STARTUP: showall, and after a column-0 #+TITLE line), in an open's metadata, and on posting and header lines.
  2. Corrected the attribution of the 49 parity regressions (above): 35 recovery (Parse-error recovery differences from bean-check around invalid dates and column-0 markers #2872), 12 bare mid-line \r (fix(parser): a stray \r before the line ending is a parse error; bean-check accepts it #2774), 2 lone capital.
  3. Opened compat(parser): a lone capital glued to a quote opens a multi-line string where beancount reads one invalid token #2977 for the pre-existing error_later_in_run multi-line string hole.
  4. Removed the unreachable Shebang / EmacsDirective arms of invalid_runs (its text always starts with a blank), and updated the is_comment_token rustdoc.
  5. The CHANGELOG entry names the restored message and the cache bumps (loader v74, WASM v112).
  6. Tightened hash_bang_cut (lexer-found markers only) and main_read_less (the cut must move the line's count), and documented that it accepts a line whatever its cause. The matrix lists did not change.

Parse-error counts per line do not move in this round (only messages and spans, on the same line), so the parity manifest and the BOM matrix data are unchanged.

Review round 2

  1. The rename took the first unexpected input anywhere on the line before the #, so an earlier real error ($x in Assets:A 1 USD $x #+y, open Assets:A ÜÜ #!x, a stray \r before #!x, a line led by $x, true, k: true or é) was moved onto the marker, and the error list could leave start order. Now only a marker that leads its line renames the line's error; otherwise only a defect at the # itself is widened. Per-line counts on every repro match bean-check 3.2.3 (bean-check / this PR: $x #+y in a posting 2 / 2, open Assets:A $x #+y 2 / 2, \r#!x 2 / 2, k: true #+y 3 / 3).
  2. Tests in tests/mid_line_hash_bang.rs: an earlier bad token keeps its own error over its span, the stray \r keeps its error, errors stay sorted by start, a #! inside a string renames nothing ( kk: "a #!x" $y, * "a #!x" $y), and the #+ of <BOM> #+x is bytes 5..7. With the rename now limited to a leading marker or an error at the # itself, a #! in a string or comment can never lead its line nor carry an error at its #, so a raw byte scan for markers would give the same result; the lexer stays the source of the markers so the rule has one definition.

Closes #2928

🤖 Generated with Claude Code

…r it, as beancount does

A `#!` or `#+` that does not start its line was one comment-like token
(`Shebang` / `EmacsDirective`) running to the end of the line. beancount
skips a `#` line only at column 0 (`^[\*\:\#]/.`); anywhere else it lexes
a `#` (HASH), then a `!` (FLAG) or a `+` (PLUS), and the rest of the line
as usual. So every invalid token after a mid-line `#!` went unreported
(`2024-01-02 * "x" #!cd` is two errors in bean-check 3.2.3, one here),
and an indented `#+STARTUP` or `#!` line, under a directive or a posting,
was skipped as a comment where beancount reports it.

- Lexer: a `Shebang` / `EmacsDirective` token not at column 0 is rewritten
  to `Hash`, and the lexer resumes right after the `#`, as the mid-line `%`
  rewrite does. `error_later_in_run` lexes on past a `#` the same way, so
  a lone capital glued to `#!x` still makes the run one invalid token.
- CST recovery: the mid-line SHEBANG / EMACS_DIRECTIVE special cases are
  gone (the transaction header's `#!` defect, `indented_comment_check`, the
  two-character defect range), since those tokens now occur at column 0
  only. A header defect at a `#` keeps the "only `;` starts a comment in
  the middle of a line" hint.

Parse-error parity (pinned fuzz corpus 9bc79f4): 78,500 of 111,323
inputs match beancount, from 78,478: 71 newly match, 49 regress. 48 of
the 49 count each differing line as beancount does when the line stands
alone (beancount's recovery after an earlier error line, #2872), and the
other is a lone capital glued to tokens that all lex (`X!!#+++02`).
`tracked` and `compat` are unchanged. The BOM combination matrix keeps its
beancount and main columns; its generated lists are updated with
`BOM_MATRIX_UPDATE=1 BOM_MATRIX_RELABEL=1`, the hand-kept worse-than-main
list drops 341 lines no longer further from beancount than main and gains
51 that a hidden `#!` / `#+` used to mask, and a line main counted closer
only because it did not read past a mid-line `#!` / `#+` is verified as
such (`main_read_less`).

Caches: loader v74 and WASM v112. A ledger with an indented `#+` line
loaded with no error before, so an error-free v73 loader blob of it is
stale too. (WASM v111 is held by #2973.)

Refs #2928

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 13, 2026 16:26
@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 56.0ms ± 6.7ms 812.4ms ± 4.4ms 14.5x 44.3 MB / 51.2 MB
investment 78.1ms ± 0.9ms 2958.9ms ± 18.4ms 37.9x 47.2 MB / 59.0 MB
fifo 76.2ms ± 1.5ms 14973.0ms ± 116.7ms 196.5x 49.2 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 53.1ms ± 0.7ms 56.0ms ± 6.7ms +5.4% ✅ within noise 45.2 MB → 44.3 MB (-1.9%)
investment 79.7ms ± 0.9ms 78.1ms ± 0.9ms -2.0% ✅ within noise 47.1 MB → 47.2 MB (+0.2%)
fifo 77.7ms ± 1.2ms 76.2ms ± 1.5ms -2.0% ✅ within noise 49.1 MB → 49.2 MB (+0.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 3.0ms, investment 0.6ms, fifo 0.9ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@codecov

codecov Bot commented Nov 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 826
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 3 commits November 13, 2026 11:39
Review round 1 of #2974.

- Removing `indented_comment_check` lost the message that named an
  indented `#!` / `#+`: the line's error became the generic `unexpected
  input` at the indentation. `name_mid_line_hash_comments`, a shared
  post-pass beside `name_misspelled_booleans`, finds each mid-line marker
  with the lexer itself (a `#` followed right away by its `!` or `+`, so
  never one in a string or a comment) and rewrites the line's first error
  at or before the `#` to point at the two characters and say that only
  `;` starts a comment that is indented or in the middle of a line. A
  defect already reported at the `#` (a posting's, a directive header's)
  is widened to both characters with the same hint. Only messages and
  spans move, on the same line, so every count stays beancount's. The
  hint now also reaches a top-level indented line and a directive's
  metadata, which main read as comments. Pinned by
  `tests/mid_line_hash_bang.rs` (exact message and span under a posting,
  at the top level, after a column-0 `#+TITLE` line, in an `open`'s
  metadata, and on posting and header lines).
- The `Shebang` / `EmacsDirective` arms of `invalid_runs` are gone: its
  text starts with a blank, so a `#!` there is mid-line. The
  `is_comment_token` rustdoc no longer calls an indented `#+STARTUP`
  comment trivia.
- BOM matrix harness: `hash_bang_cut` finds the markers with the lexer,
  so it no longer cuts inside a string or a comment, and `main_read_less`
  also requires the cut to move the line's count; its doc says it accepts
  a line whatever its cause. The matrix test passes with no list change.
- CHANGELOG: the entry names the restored message and the cache bumps.

Refs #2928

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… marker leads the line

Review round 2 of #2974.

`name_mid_line_hash_comments` renamed the first generic `unexpected input`
anywhere on the line before the `#`, so an earlier real error on the line
(`$x` in `  Assets:A  1 USD $x #+y`, `open Assets:A ÜÜ #!x`, a stray `\r`
before `#!x`, a line led by `$x`, `true`, `k: true` or `é`) was moved onto
the marker and its own report vanished, and the error list could leave its
start order. Now the line's error is renamed only when the marker leads its
line (after its indentation); otherwise only a defect reported at the `#`
itself is widened. Only blanks lie between the line start and a leading
marker, so the list stays sorted.

Tests in `tests/mid_line_hash_bang.rs`: an earlier bad token keeps its own
error over its span (posting, `open` header, a line led by `$x`, metadata),
a stray `\r` before `#!x` keeps its error, a `#!` inside a string renames
nothing, errors stay sorted by start, and the `#+` of `<BOM>  #+x` is bytes
5..7. Per-line counts match bean-check 3.2.3 on every repro.

Refs #2928

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit cb48d6d into main Nov 14, 2026
67 of 68 checks passed
@robcohen
robcohen deleted the fix/bom-glued-cost branch November 14, 2026 03:47
robcohen added a commit that referenced this pull request Nov 14, 2026
…s an invalid token (#2975)

A transaction whose posting holds an invalid token is kept under error
recovery (#2932) with what recovery could read of it, so a posting's
price or cost after the token is gone (`1 HOOL <BOM>{2 USD}`,
`1 HOOL \x11@ 2 USD`, `1 HOOL $x{2 USD}`). The transaction then did not
balance, and every surface reported two `E3001` beside the token's parse
error, where bean-check 3.2.3 reports the token alone: beancount's grammar
never builds such a transaction.

The late balance check now asks, only once it has found a residual,
whether the transaction holds an invalid token, by the parser's own rule:
`rustledger_parser::transaction_holds_invalid_token` parses the
transaction's own text (its directive span) and applies
`holds_an_invalid_token`, the rule the duplicate-metadata check already
skips such a transaction by. The text comes through `SourceLines`, which
every surface already hands the validator: `SourceLines::with_text` /
`text`, filled by `rustledger_loader::source_lines_overlaid` from the
source map and from an editor's buffers (whose text is now kept), and by
the new `source_lines_of_text` for an LSP buffer validated outside a
ledger. Without the text (dropped, or a synthesized transaction) the
residual is reported as before. A ledger that balances never reads its
source here.

The parse output is unchanged. Pinned by a surface-agreement case (CLI,
loader, WASM, FFI, LSP) for `{`, `@`, `@@`, BOM-led, BOM-glued, control
character and invalid-run shapes beside a transaction that really does
not balance, by `test_transaction_holds_invalid_token_reads_the_parsers_rule`,
and by a loader test of the text access.

Caches: WASM v113 (its payloads archive validation findings; v111 is held
by #2973 and v112 by #2974). Loader v73, unchanged: every affected source
has a parse error, and that cache is saved only for an error-free load.

Closes #2954

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

compat(parser): an invalid run should swallow a following quote, #! or #+ mid-line, as beancount's lexer does

1 participant