Skip to content

fix(parser): form and report invalid tokens as beancount's lexer does - #2903

Merged
robcohen merged 6 commits into
mainfrom
fix/lexer-invalid-tokens
Nov 9, 2026
Merged

robcohen merged 6 commits into
mainfrom
fix/lexer-invalid-tokens

Conversation

@robcohen

@robcohen robcohen commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

beancount's rule

From beancount 3.2.3's lexer.l: when no other rule matches at a position, the catch-all . rule does unput and BEGIN(INVALID), and <INVALID>[^ \t\n\r]+ takes everything from that character up to the next space, tab, \r or \n as one token, reports Invalid token: '...' and returns YYerror. Flex's longest match means the run starts at the first character no rule reads, so a valid token before it on the same word stays a token (Assets:A'b is ACCOUNT then Invalid token: ''b'), and a lone capital is a token only before a blank ([A-Z]/[ \t\n]), so R\x04 and Assets:a are invalid from the capital on. The lexer builds that error itself, so every invalid token is reported whatever the grammar is doing. The grammar sees only YYerror, so it adds a syntax error for a line only when it failed at a readable token before the first invalid one ("plugin "p" "c": unexpected STRING, then Invalid token: 'p"'), and bison's recovery reports nothing more for the rest of the statement.

The change

Lexer (logos_lexer.rs)

  • A logos error runs to the next space, tab, \r or \n, as INVALID does. A " or ; glued into the run opens no string and no comment.
  • A failed string scan ends at its run, not at the end of its line. Lexing resumes after the run. The line-at-a-time guard (fix(parser): an unterminated quote hides every directive after it behind one error #2784) is kept, and the comment explains why quote pairing cannot change.
  • A lone capital (Currency/Flag of one letter) glued to a run that holds an error starts that error. A lookahead on a cloned lexer finds it, and a clean run is remembered, so the scan stays linear (counter test added). A capital glued only to valid tokens ({1 V, ...}, T#!) is still a token, and the existing glued-one-letter rules report it, as before.
  • Number is [0-9], as in beancount. Before, \d meant any Unicode digit, so kk: ५ was dropped with no error.
  • Two errors keep their own extent, on purpose: a mid-file BOM (layout-transparent, so a concatenated file's next directive still parses under BomInDirectiveBody) and a \r with more of its line after it (rledger's existing stricter rule).

Error counting (convert.rs, green.rs, txn_header.rs)

  • A directive the converter dropped, whose header grammar (first_header_defect) first fails at the invalid token, reports it once: the whole-node error stands for it and names it.
  • Header, metadata and posting checks still report a defect before the line's first invalid token (report_defects_before), where they used to skip any line that had an error.
  • A transaction-header defect at an invalid token is not reported a second time.
  • Each invalid token on an ERROR_NODE line gets its own error. The line error stands for the first one when what precedes it is something the grammar reads (nothing, or a date). This is shared by both parse paths.
  • quiet_after_invalid_tokens: no error after the first invalid token on its line, except other invalid tokens, invalid dates and BOMs. On an indented line, a construct check that contains the token is dropped too (cost spec, expression, trailing tokens).
  • A pushtag/poptag/pushmeta/popmeta with an invalid token on its header changes no state, as beancount never reduces it.

Formatter (format.rs): the line-ending helpers (crlf_to_lf_outside_strings, lf_to_crlf_outside_strings, cr_outside_strings_present) now read string literals from the lexer (StringLiterals) instead of from the character-level SourceState mirror. That mirror could not follow the new run rule (x"a b" is no string) without lexing, so I removed it along with its agreement tests, following the canonical-function rule.

Harness numbers (scripts/compat-parse-error-parity.py, fuzz pin 9bc79f4, local compat copy of 491 files)

main is origin/main at d2a0ee5 (#2897 included); "this PR" is after review round 2.

Source Inputs main this PR
compat 491 486 (99.0%) 488 (99.4%)
tracked 384 378 (98.4%) 381 (99.2%)
matrix 66256 40511 (61.1%) 50705 (76.5%)
fuzz 44192 16143 (36.5%) 25312 (57.3%)
all 111323 57518 (51.7%) 76886 (69.1%)
Category main this PR
lexer-token-split 22299 11943
lexer-tokens-merged 12672 2054
rl-indented-line 13089 15736
more-on-line 2779 1433
rl-top-level-line 1625 2030
off-by-one 427 417
rl-misses-line 201 138
eof 113 91
bc-only / rl-only / fewer-on-line 79 / 68 / 12 78 / 68 / 12

20,346 inputs now match that did not. 982 that matched no longer do (fuzz 956, matrix 26), and none of them are compat or tracked:

  • fuzz, with non-ASCII text (826): mostly rledger's narrower account-component start (compat(parser): account components starting with a non-ASCII digit or other non-letter are valid in beancount but rejected #2906), where beancount sees a valid ACCOUNT and rledger an invalid token; the rest are the recovery shape below on lines that also hold non-ASCII characters. Before, these matched by coincidence.
  • fuzz, pure ASCII (130): bison's 3-token recovery. After an error on one line beancount stays quiet on the next lines' grammar errors and reports only their invalid tokens, while rledger now also reports a grammar error that comes before an invalid token (review item 1, which is what beancount reports outside that window). That is recovery-model work (Parse-error recovery differences from bean-check around invalid dates and column-0 markers #2872 part 2).
  • matrix 15: ope"n Assets:A\n kk: "v". The quote used to swallow the next line as a string; the indented line after the broken header is now reported, the same recovery shape.
  • matrix 7: balance ... 1.00 .~ 0.01 USD and (1 + 2)" * 3 USD, where a construct error before or at the token stands alongside it.
  • matrix 4: {#t. rledger lexes {# as one token where beancount reads { then the tag #t.

The growth of rl-indented-line / rl-top-level-line is the same recovery-model shape, now visible because the invalid tokens are right. tests/baselines/parse-error-parity.manifest is re-pinned with --update (compat/tracked rows only improve); --check reports no regressions.

Downstream checks

  • Formatter: format_source output is hash-identical to main on all 1018 clean ledgers (compat corpus + every tracked .beancount/.bean), and on CRLF copies of all of them. No ledger changed between clean and errors.
  • Validators (is_valid_account_name, is_valid_currency, leading_date_len) only run the lexer on candidate names. The lone-capital lookahead and runs never apply to a fully valid token, and the workspace tests pass.
  • LSP: no semantic-token or diagnostic code keys on ERROR_TOKEN extents (selection_range only ranks it lowest). The two surface_cleanup_* tests now expect @@@ junk to be 2 errors (beancount: unexpected ATAT and Invalid token: 'junk').
  • Stray-character matrix: stray_char_matrix.rs passes unchanged. No accept/reject verdict moved, so the TSV is untouched.
  • Corpus baselines (STRICT): only the rows that drifted are updated: 8 parser, 7 CST, all files that already had parse errors. examples_data_full changes only its token sequence. Green and red agree (parse_green_eq_red_corpus, the fuzz corpus tests and every new test check it).
  • CLI snapshot check_parse_errors_text: this is not valid beancount {{{ }} now reports is, not, valid and beancount too. That is 5 errors on the line, as beancount reports.
  • Loader CACHE_VERSION 63, WASM 84 (fix(parser): report a repeated metadata key on a transaction or posting, keeping the first value #2897 holds 62/82, merged; fix(validate)!: pad from one shared plan as beancount does, and drop E2004 #2898 holds WASM 83), with one note each.

Design questions (not changed here)

  1. Account component start (now compat(parser): account components starting with a non-ASCII digit or other non-letter are valid in beancount but rejected #2906): beancount takes any non-ASCII character to start an account component. rledger takes only \p{Lu}\p{Lo}\p{Lt} (documented as deliberate). This accounts for most of the non-ASCII fuzz rows above. Matching beancount would change accept/reject on input, so I left it alone.
  2. {# followed by a tag character: beancount lexes it as { + TAG, so {#t reports unexpected LCURL. rledger's LBraceHash takes {#, and changing that would affect the total-cost syntax.
  3. Mid-file BOM: beancount reads \ufeff2024-01-01 as one invalid token and drops the directive. rledger keeps the BOM layout-transparent, which is deliberate.

Also filed: #2905, a transaction with no flag is accepted (which explains 2024-01-02 "x" $).

Review round 1

  • Construct checks the grammar fails before (quiet_after_invalid_tokens): a construct error that contains the invalid token on an indented line (unclosed cost spec, expression, trailing tokens) is dropped only when the line's posting or metadata grammar reaches the token (indented_grammar_reaches, the first_posting_defect / first_meta_defect rules on the line's tokens up to it), the indented counterpart of header_fails_here. Assets:A 1 VV {}{$ is again unexpected LCURL-style plus the invalid token (2, as bean-check), and so are {(7# \x00 and {+5/50+82333333{\x00; {2 .USD} stays the token alone. Tests: test_parse_keeps_a_construct_error_where_the_grammar_fails_before_the_token.
  • Errors anchored at the directive start: beancount checks a booking method and repeated metadata keys when it builds the directive, which it never does for a statement holding an invalid token. 2024-01-02 open Assets:C$;comment "x" no longer adds P0025 (only Invalid token: '$;comment'), and a transaction with an invalid token anywhere in it gets no repeated-key error from fix(parser): report a repeated metadata key on a transaction or posting, keeping the first value #2897's check (the interaction showed up after merging main: 2024-01-01 * $ + xn: 1 + xn: 2 is the token alone in bean-check). The other directive-anchored errors were checked: unclosed/absent pushtag/pushmeta already follow the no-state-change rule, transaction-header builder checks (too many strings) are already skipped at an invalid token, posting builder errors and unevaluable metadata are gated on the line having no prior error, and InvalidAccount is a line-level classification. Tests: test_parse_reports_no_booking_method_on_a_header_with_an_invalid_token, test_parse_reports_no_repeated_key_in_a_transaction_with_an_invalid_token.
  • Regression split in the harness section is corrected (it credited every fuzz regression to the account-start question).
  • Nits: cr_outside_strings_present streams the lexer and stops at the first \r outside a string (it still returns at once with no \r). After merging main the v63 loader note names v62 as its predecessor and the WASM v84 note names v83 (fix(validate)!: pad from one shared plan as beancount does, and drop E2004 #2898).
  • Merged origin/main (fix(parser): report a repeated metadata key on a transaction or posting, keeping the first value #2897: loader 62, WASM 82). This PR keeps loader 63 / WASM 84.
  • Rerun: parser, LSP, loader and WASM tests, strict corpus/CST baselines, clippy -D warnings, cargo doc -Dwarnings, cargo fmt --check, and the harness --check, all clean.

Review round 2

  • Header walk past leading trivia (regression vs main, fixed): header_has_invalid_token stopped at the node's first NEWLINE, and a blank line before a directive is a leading NEWLINE of that node, so in normal file layout it never reached the header. It now reads the header through header_line_tokens, the walk the header check uses (it skips leading whitespace, blank and comment lines), so there is one copy. After a preceding directive and a blank line, or a comment line, open Assets:C$;comment "x" gets no P0025, pushtag #t $x / pushmeta kk: "v" $x push nothing (the later pop is of an absent tag/key), and poptag #t $x / popmeta kk: $x pop nothing (the push stays open), each as bean-check reports. Test: test_parse_a_header_after_a_blank_or_comment_line_is_read_for_invalid_tokens. The other header walks that look for a NEWLINE (header_line_tokens, the pushmeta value check, single_line_directive_span, the duplicate-key header scan) already skip leading trivia first.
  • open with an invalid token on a metadata line: the booking-method check now asks holds_an_invalid_token for the whole node, as the repeated-key check does for transactions, since beancount never builds the statement. open Assets:C USD "BAD" + kk: $x reports only the token (line 2); the directive is kept without the booking method. Test: test_parse_reports_no_booking_method_with_an_invalid_token_on_a_metadata_line.
  • Nits: StringLiterals streams its spans from the lexer, and cr_outside_strings_present uses it rather than a copy of its span logic (it still stops at the first \r outside a string). The WASM v84 note says "an older blob", so it reads right whichever of this PR and fix(validate)!: pad from one shared plan as beancount does, and drop E2004 #2898 lands first.
  • Harness: 4 more inputs match (76,886); the manifest is re-pinned with --update and --check is clean. Parser, loader, LSP and WASM tests, strict corpus/CST baselines, clippy -D warnings, cargo doc -Dwarnings and cargo fmt --check pass.

How to test

cargo test -p rustledger-parser --test invalid_token --test unterminated_quote --test indented_star_line
cargo test -p rustledger-parser --lib test_tokenize_lossless_lone_capital_lookahead_is_linear
STRICT_BASELINE=1 cargo test -p rustledger-parser --test corpus_baseline --test cst_baseline
cargo build --release -p rustledger-loader --no-default-features --example parse_error_lines
python3 -I scripts/compat-parse-error-parity.py --rledger target/release/examples/parse_error_lines \
    --fuzz-dir DIR --fuzz-commit 9bc79f4f35f52c50813164f43307e7d151d70d8c \
    --compat-dir tests/compatibility/files --check

Full workspace tests, clippy -D warnings, cargo doc -Dwarnings and cargo fmt --check pass locally. The one failure was python_plugin_wasi::ag_rledger_carries_the_runtime_download_and_compile_notices, an HTTP 504 while downloading the CPython runtime, which is unrelated.

Refs #2872 (does not close it).

🤖 Generated with Claude Code

beancount 3.2.3's lexer has one catch-all rule: at a character no other
rule takes (`.` -> INVALID state) it takes everything up to the next
space, tab, `\r` or `\n` (`<INVALID>[^ \t\n\r]+`) as ONE token and reports
`Invalid token: '...'`. Its grammar sees only YYerror for it, so it adds a
syntax error only when it failed at a readable token before the first
invalid one, and every invalid token on a line is reported.

- Lexer: a logos error runs to the next blank, a glued `"` or `;` included
  (no string, no comment). A failed string scan ends at its run, not the
  line end. A lone capital glued to a run with an error starts it, as
  beancount lexes `[A-Z]` alone only before a blank. Number is `[0-9]`, not
  Unicode `\d`. A mid-file BOM and a mid-line `\r` keep their own extent.
- Errors: a dropped directive whose header grammar fails at the invalid
  token reports it once; header, posting and metadata checks still report
  a defect before the first invalid token; each invalid token on an
  ERROR_NODE line gets its own error; nothing else is reported after the
  first invalid token on its line; a txn header defect at an invalid token
  is not reported twice. pushtag/poptag/pushmeta/popmeta with an invalid
  token change no state.
- Formatter line-ending helpers read string literals from the lexer
  instead of a character-level mirror (which could not follow the new run).

Parse-error parity (scripts/compat-parse-error-parity.py): 77,012 of
111,323 inputs match, from 57,520; compat 485 -> 487, tracked 376 -> 379.
Manifest repinned. Loader cache v63, WASM cache v84.

Refs #2872

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

github-actions Bot commented Nov 9, 2026

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

@codecov

codecov Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.50372% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/convert.rs 99.57% 1 Missing ⚠️
crates/rustledger-parser/src/logos_lexer.rs 98.66% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

Merges origin/main (#2897: loader cache v62, WASM v82). This branch keeps
loader v63 and WASM v84; their notes now name v62 and v83 as predecessors.

Review round 1 on #2903:
- quiet_after_invalid_tokens drops a construct check that contains the
  invalid token on an indented line only when the line's posting or
  metadata grammar reaches that token (indented_grammar_reaches). Where the
  grammar fails first (`1 VV {}{$`: `unexpected LCURL`, then the token),
  both errors stand, as in beancount.
- An `open` with an invalid token on its header gets no booking-method
  error (P0025), and a transaction with an invalid token anywhere in it
  gets no repeated-metadata-key error: beancount never builds either.
- cr_outside_strings_present streams the lexer and stops at the first
  `\r` outside a string.
- Parse-error parity manifest re-pinned with --update; --check is clean.
  76,882 of 111,323 inputs match beancount 3.2.3 (main: 57,518).

Refs #2872

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 51.1ms ± 0.5ms 794.5ms ± 4.9ms 15.6x 43.0 MB / 51.1 MB
investment 77.0ms ± 0.4ms 2880.8ms ± 12.9ms 37.4x 55.2 MB / 59.1 MB
fifo 75.4ms ± 1.7ms 14446.8ms ± 26.8ms 191.6x 55.1 MB / 59.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 50.2ms ± 0.3ms 51.1ms ± 0.5ms +1.8% ✅ within noise 42.8 MB → 43.0 MB (+0.3%)
investment 76.3ms ± 0.9ms 77.0ms ± 0.4ms +1.0% ✅ within noise 57.0 MB → 55.2 MB (-3.2%)
fifo 74.1ms ± 1.9ms 75.4ms ± 1.7ms +1.8% ✅ within noise 55.0 MB → 55.1 MB (+0.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.3ms, investment 0.5ms, fifo 1.2ms), 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

robcohen and others added 4 commits November 9, 2026 02:09
…or invalid tokens

Review round 2 on #2903:
- header_has_invalid_token stopped at the first NEWLINE child, and a blank
  line before a directive is a leading NEWLINE of its node, so in normal
  layout it never reached the header: `open ... $;c "x"` after a blank
  line still got P0025, and `pushtag #t $x` still pushed. It now reads the
  header through header_line_tokens, the walk the header check uses.
- An `open` with an invalid token anywhere in it (a metadata line too)
  gets no booking-method error (holds_an_invalid_token, as transactions);
  the directive is kept without the booking method.
- StringLiterals streams its spans, and cr_outside_strings_present uses
  it instead of a copy of its span logic.
- The WASM v84 note names "an older blob", whatever lands first.
- Parity manifest re-pinned (4 more inputs match); --check is clean.

Refs #2872

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The compat corpus copy CI caches (content 0f70e7780250, the current
upstream file) now matches beancount 3.2.3; it was pinned
lexer-tokens-merged, which the parity job reports as a stale pin.

Refs #2872

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The corpus copy CI caches (source 33eef955, the current upstream file)
holds invalid tokens (`zwyyy456`) this branch now reports as beancount
does, so its parser-output hash moves. Regenerated with that file in
place; only this row changes, and its CST row does not.

Refs #2872

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit 65c66ad into main Nov 9, 2026
67 of 68 checks passed
@robcohen
robcohen deleted the fix/lexer-invalid-tokens branch November 9, 2026 11:43
robcohen added a commit that referenced this pull request Nov 9, 2026
Resolves the WASM cache and CHANGELOG conflicts with #2903: v84 is
#2872's (loader v63), and this branch's note moves to v85 over loader
v63 (v83 was never released). Both sides of the CHANGELOG are kept.

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.

1 participant