Repository navigation
fix(parser): form and report invalid tokens as beancount's lexer does - #2903
Merged
Merged
Conversation
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]>
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Codecov Report❌ Patch coverage is
📢 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]>
Contributor
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
…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]>
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
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]>
This was referenced Nov 9, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
beancount's rule
From beancount 3.2.3's
lexer.l: when no other rule matches at a position, the catch-all.rule doesunputandBEGIN(INVALID), and<INVALID>[^ \t\n\r]+takes everything from that character up to the next space, tab,\ror\nas one token, reportsInvalid token: '...'and returnsYYerror. 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'bisACCOUNTthenInvalid token: ''b'), and a lone capital is a token only before a blank ([A-Z]/[ \t\n]), soR\x04andAssets:aare 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 onlyYYerror, 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, thenInvalid token: 'p"'), and bison's recovery reports nothing more for the rest of the statement.The change
Lexer (
logos_lexer.rs)\ror\n, asINVALIDdoes. A"or;glued into the run opens no string and no comment.Currency/Flagof 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.Numberis[0-9], as in beancount. Before,\dmeant any Unicode digit, sokk: ५was dropped with no error.BomInDirectiveBody) and a\rwith more of its line after it (rledger's existing stricter rule).Error counting (
convert.rs,green.rs,txn_header.rs)first_header_defect) first fails at the invalid token, reports it once: the whole-node error stands for it and names it.report_defects_before), where they used to skip any line that had an error.ERROR_NODEline 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).pushtag/poptag/pushmeta/popmetawith 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-levelSourceStatemirror. 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 pin9bc79f4, local compat copy of 491 files)mainis origin/main atd2a0ee5(#2897 included); "this PR" is after review round 2.lexer-token-splitlexer-tokens-mergedrl-indented-linemore-on-linerl-top-level-lineoff-by-onerl-misses-lineeofbc-only/rl-only/fewer-on-line20,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:
ACCOUNTand rledger an invalid token; the rest are the recovery shape below on lines that also hold non-ASCII characters. Before, these matched by coincidence.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.balance ... 1.00 .~ 0.01 USDand(1 + 2)" * 3 USD, where a construct error before or at the token stands alongside it.{#t. rledger lexes{#as one token where beancount reads{then the tag#t.The growth of
rl-indented-line/rl-top-level-lineis the same recovery-model shape, now visible because the invalid tokens are right.tests/baselines/parse-error-parity.manifestis re-pinned with--update(compat/tracked rows only improve);--checkreports no regressions.Downstream checks
format_sourceoutput 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.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.ERROR_TOKENextents (selection_rangeonly ranks it lowest). The twosurface_cleanup_*tests now expect@@@ junkto be 2 errors (beancount:unexpected ATATandInvalid token: 'junk').stray_char_matrix.rspasses unchanged. No accept/reject verdict moved, so the TSV is untouched.examples_data_fullchanges only its token sequence. Green and red agree (parse_green_eq_red_corpus, the fuzz corpus tests and every new test check it).check_parse_errors_text:this is not valid beancount {{{ }}now reportsis,not,validandbeancounttoo. That is 5 errors on the line, as beancount reports.CACHE_VERSION63, 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)
\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.{#followed by a tag character: beancount lexes it as{+TAG, so{#treportsunexpected LCURL. rledger'sLBraceHashtakes{#, and changing that would affect the total-cost syntax.\ufeff2024-01-01as 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
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, thefirst_posting_defect/first_meta_defectrules on the line's tokens up to it), the indented counterpart ofheader_fails_here.Assets:A 1 VV {}{$is againunexpected LCURL-style plus the invalid token (2, as bean-check), and so are{(7# \x00and{+5/50+82333333{\x00;{2 .USD}stays the token alone. Tests:test_parse_keeps_a_construct_error_where_the_grammar_fails_before_the_token.2024-01-02 open Assets:C$;comment "x"no longer adds P0025 (onlyInvalid 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: 2is the token alone in bean-check). The other directive-anchored errors were checked: unclosed/absentpushtag/pushmetaalready 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, andInvalidAccountis 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.cr_outside_strings_presentstreams the lexer and stops at the first\routside 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).-D warnings,cargo doc -Dwarnings,cargo fmt --check, and the harness--check, all clean.Review round 2
header_has_invalid_tokenstopped at the node's firstNEWLINE, and a blank line before a directive is a leadingNEWLINEof that node, so in normal file layout it never reached the header. It now reads the header throughheader_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" $xpush nothing (the later pop is of an absent tag/key), andpoptag #t $x/popmeta kk: $xpop 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 aNEWLINE(header_line_tokens, thepushmetavalue check,single_line_directive_span, the duplicate-key header scan) already skip leading trivia first.openwith an invalid token on a metadata line: the booking-method check now asksholds_an_invalid_tokenfor the whole node, as the repeated-key check does for transactions, since beancount never builds the statement.open Assets:C USD "BAD"+kk: $xreports 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.StringLiteralsstreams its spans from the lexer, andcr_outside_strings_presentuses it rather than a copy of its span logic (it still stops at the first\routside 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.--updateand--checkis clean. Parser, loader, LSP and WASM tests, strict corpus/CST baselines, clippy-D warnings,cargo doc -Dwarningsandcargo fmt --checkpass.How to test
Full workspace tests, clippy
-D warnings,cargo doc -Dwarningsandcargo fmt --checkpass locally. The one failure waspython_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