Repository navigation
fix(parser): report stray characters in directive header lines - #2805
Merged
Merged
Conversation
Each non-transaction converter read the fields it wanted from the header line and ignored the rest, so `2024-01-01 open! Assets:A` loaded clean and `rledger format` deleted the `!`, and `open Assets:A U*SD` loaded as the currency list `U,SD`. A new `cst::directive_header` module checks each header line against beancount 3.2.3's grammar (one recognizer per directive, from grammar.y) from the shared directive loop, so the green and red paths cannot diverge. The error is reported and the directive is kept, as for a tag on an `open` (#1949). Matching beancount's accept/reject verdict exactly also means: one leading comma in a currency list is valid (and `rledger format` now keeps it); only `;` starts a comment mid-line; a one-letter currency must be followed by whitespace; a custom value cannot be NULL; and the balance spellings `1.00 USD ~ 0.01 USD` / `1.00 USD ~ 0.01` (accepted on purpose by #2193) are syntax errors. rustledger-core's formatter and `Display for Balance` now write a tolerance as `1.00 ~ 0.01 USD`, the form both parsers read. scripts/stray-char-matrix.py records beancount's verdict on 13,498 single-character insertions; tests/stray_char_matrix.rs checks rledger against the 9,897 header-line cases without Python: 2,143 disagreed on main, none now. Three parser-corpus baseline rows move, each a new error beancount also reports. Loader cache v50, WASM cache v65. Part of #2802 (stage 1 of 3). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
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?
|
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Review of the first commit. The lexer required a letter right after the slash, so `/6J` (a futures symbol, beancount's own example) lexed as `/`, `6`, `J`: `price HOOL 10 /6J` loaded clean as `10 / 6` in `J`, and the header check then rejected `commodity /6J`, which beancount accepts. The `/` form now uses beancount's regex, and longest match decides it against `Slash` as flex does (`10/4` stays a division). The matrix gains five `/`-currency snippets (16,405 cases; 12,849 on header lines, all matching beancount except 60 column-0 #2779 rows), plus explicit tests. The header check walks green children into a buffer reused across directives and reads it as a slice: +3 to +5% on 400k price/balance lines, down from +12.8%. The spec no longer shows the `1000 USD ~ 0.01` form, and the CHANGELOG states the #2779 exception and the cache bumps. Part of #2802 (stage 1 of 3). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 29, 2026
The plain currency form was `[A-Z][A-Z0-9'._-]*`, so `commodity CAC_`, `price HOOL. 10 USD` or `open Assets:A USD_,EUR` loaded clean while bean-check rejects them. Both currency alternatives are now beancount's rules exactly: `[A-Z][A-Z0-9'._-]*[A-Z0-9]` or one capital letter. The trailing character is left over and is an error, matching bean-check. The matrix adds `/ _ - ' .`, a letter and a digit to its characters (23,160 cases) and parses each in a forked child, since beancount segfaults on `1./00`. Account-name rejections are excluded like option names (rledger reports both at load). 17,709 header cases match beancount; 60 column-0 #2779 rows and 126 dates with an extra digit (beancount's looser DATE rule) are pinned as known divergences. Part of #2802 (stage 1 of 3). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 29, 2026
Review of 66a43b7. Ending a currency at its last letter or digit made `1 USD-` lex as `USD` then `-`, and the posting converter reads only its amount, cost and price, so the posting loaded clean as `1 USD` (main reported the currency `USD-`). A flat token after a posting's AMOUNT, COST_SPEC or PRICE_ANNOTATION is now an error, matching bean-check's `unexpected MINUS`. It runs from the shared loop over green children; on the stage-3 matrix rows it adds no false error and closes 133 misses. Also: a missing-token header defect points at the last token on the line instead of an empty span at its end, so a bare `pushtag` at EOF is copied verbatim and `format_source` is idempotent on it; a character glued to the end of a currency is named (`a currency cannot end in `_``), without slicing inside a multibyte character (that panicked on fuzz-corpus input, now in-tree under fuzz/regressions). Part of #2802 (stage 1 of 3). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of 3812321. The posting check said "a currency cannot end in X" for any token touching the end of an amount (`1-`, `{1 USD}-`, `1 USD+`, `1 USD)`); it now does so only when the amount ends in a CURRENCY and the stray character is one a currency may hold inside it. The currency-tail message falls back to the generic one when the word is glued to a non-ASCII character (`ÜSD_` named `SD`). Part of #2802 (stage 1 of 3). Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.
What changed
Stage 1 of #2802: a stray character on a non-transaction directive's header line is now a parse error, as it is in beancount. Before this PR, rledger accepted it without a word, and
rledger formatthen deleted it.2024-01-01 open! Assets:Aformatdeletes the!unexpected "!" in the open directive: expected an account2024-01-01 open Assets:A USD @formatdeletes the@@2024-01-01 price HOOL ? 10 USDformatdeletes the??2024-01-01 open Assets:A U*SDU,SDU2024-01-01 close! Assets:Aformatdeletes the!!2024-01-01 commodity /6JJ/6J, as in beancount2024-01-01 price HOOL 10 /6J10 / 6inJ, formatted10 / 6 J10 /6JCause. The CST parser groups a header line into flat tokens, and each
convert_*reads the fields it needs and ignores the rest.Fix. A new module,
cst/directive_header.rs, holds one small recognizer per directive, taken from beancount 3.2.3'sgrammar.y. It coversopen,close,commodity,pad,balance,price,event,query,note,document,custom,option,include,plugin,pushtag/poptagandpushmeta/popmeta.parse_via_cst_inner. The non-transaction converters are shared by the green and red paths (only transactions have a green fast path), so no green mirror is needed and the two paths cannot diverge.reject_tags_and_linkskeeps one ([Bug]:openaccepts a trailing tag or link that beancount rejects (and thatcloserejects) #1949), so one stray character does not cascade into unopened-account errors.rledger formatrefuses the file. The error-tolerant formatter copies the directive verbatim (fix(format): keep unparsable text inside a directive in the error-tolerant formatter #2801).parseon 400kpriceandbalancelines (the worst case, every directive checked), best of 7:main542.7 ms; the first version of this PR 612.0 ms (+12.8%); now 558.6 to 572.1 ms across three runs (+3 to +5%). Transaction-heavy ledgers pay almost nothing, since transactions are not checked here.Following beancount exactly
The rule for this PR is to match beancount's accept/reject verdict unless that would cause a correctness problem. Error positions and messages may differ. That rule decided the following. The comma and the
/-currency rows make rledger accept what beancount accepts; the rest are stricter than before, and all are beancount's behavior:/-currency may have a digit right after the slash. beancount's lexer rule is\/[A-Z0-9'._-]*[A-Z]([A-Z0-9'._-]*[A-Z0-9])?, and its own comment uses/6J(a futures symbol). Ours required a letter first, so/6Jlexed as/,6,J:price /6J 10 USDloaded as a price ofJ, andprice HOOL 10 /6J,balance Assets:A 1 /6Jandcustom "b" 1 /6Jloaded clean as10 / 6inJ. The lexer now uses beancount's regex for the/form (logos_lexer.rs); longest match decides between it andSlashexactly as flex does, so10 /6Jis an amount and10/4is still a division.is_valid_currencyruns the lexer, so it follows. Fuzz check: all 42,083 inputs of thefuzz-corpusbranch (fuzz_parse,fuzz_green_eq_red,fuzz_parse_line) replay clean through the lossless and green==red invariants andformat_source, andformat_sourceis idempotent on every one of them; both corpus baselines are unchanged by the lexer change.[A-Z][A-Z0-9'._-]*[A-Z0-9]or one capital letter; ours was[A-Z][A-Z0-9'._-]*, socommodity CAC_,price HOOL_ 10 USD(andHOOL',HOOL.),price HOOL 10 CAC-,open Assets:A USD_,EURand a postingAssets:A 1 CAC_loaded clean, while bean-check reportsInvalid tokenorunexpected MINUS. The lexer now uses beancount's rule for both currency forms; the trailing character is left over and is an error, matching bean-check on every case. Inner punctuation is unchanged (NT.TO,BRK-B,TLT_040921C144,USD.5), and quotes in strings are not affected.is_valid_currencyruns the lexer, so its callers (CSV importer,rledger price,rledger extract) now refuse such a currency instead of writing one bean-check rejects.1 USD-lex asUSDthen-, and the posting converter reads only its amount, cost and price, soAssets:A 1 USD-loaded clean as1 USDandrledger formatwrote that back (main reportedE3001, currencyUSD-). A flat token after a posting'sAMOUNT,COST_SPECorPRICE_ANNOTATIONis now reported (unexpected "-" after the posting amount: a currency cannot end in `-`), matching bean-check'sunexpected MINUSon1 USD-,1 HOOL @ 2 USD-,1 HOOL @@ 2 USD-,{2 USD} @ 3 USD-,-1 USD-,1 USD--,1 USD- ; c,1 USD+, and the spaced1 USD -and1 USD *that main already accepted silently. It runs from the shared loop over green children, so green and red agree; comment kinds on posting lines stay stage 3. Over the stage-3 matrix rows it adds no false error (the same 31 rows as onmain); stage-3 misses go from 743 onmainto 594.commodity CAC_reportsunexpected `_` after the currency `CAC`: a currency cannot end in `_`instead ofunexpected input.opencurrency list is valid, becausecurrency_list COMMA currencyreduces from%empty:open Assets:A , USD,EUR. rledger already accepted it, butrledger formatdeleted the comma. The formatter now keeps it, emitted as,USD,EUR. Two leading commas are an error.;starts a comment in the middle of a line. beancount lexes%as a FLAG token, and#!/#+asHASHfollowed by a flag orPLUS. Our lexer reads all three as a comment to the end of the line, which silently commented out the rest of the header (open Assets:A % USD). After a header's first token they are now reported. Column-0%,#!and#+lines are unchanged.[A-Z]/[ \t\n]), soU,SDandV, USDare invalid tokens there.customvalue cannot beNULL.custom_valuehas noNONE.~ 0.001 0.02 USDuses 0.001 #2193).balance Assets:A 1.00 USD ~ 0.01 USD,0.25 + 0.75 USD ~ 0.01 USDand1.00 USD ~ 0.01were accepted on purpose. Each has one reading, but no correctness reason requires accepting them, and beancount rejects them, so they are now syntax errors. The directive is kept with its one reading.docs/reference/compatibility.mdsection 6 and its pinned test,balance_tolerance_accepts_one_reading_and_diagnoses_none.rustledger-core's directive formatter wrote tolerances as1000.00 USD ~ 0.01, a form neither parser reads. It now writes1000.00 ~ 0.01 USD. This is the text behindcanonicalize_directives, sorledger add/extract, BQLPRINTand FFIformat.entrywere writing it.Display for Balanceand thefuzz_parse_linegenerator also moved to beancount's form.balance_with_arithmetic_and_toleranceidempotence fixture now uses beancount's spelling.spec/impl/decimals.md,spec/project/glossary.md, andspec/core/syntax.md(nowNumber ~ Tolerance Currency).Within the matrix, no other header-line disagreement with beancount remains. Misplaced thousands separators (
price HOOL 1,23,4.50 USD) were already an error here, and beancount rejects them too (Invalid number format).The matrix
scripts/stray-char-matrix.pyruns beancount 3.2.3 in the compat container./-currencies such as/6Jand/6E_X), it inserts each of! @ ? * ~ ^ $ & | { } ( ) , # % " / _ - ' .plus a letterAand a digit0at every byte offset, bare and, after a space, followed by a space. That gives 23,160 inputs. Each is parsed in a forked child, because beancount's C parser segfaults on some of them (1./00, a division by zero); a crash is no verdict and is excluded.crates/rustledger-parser/tests/data/stray_char_matrix.tsv(about 24 KB, one expectation character per case).crates/rustledger-parser/tests/stray_char_matrix.rsregenerates the same inputs, so it needs no Python, and checks rledger against every verdict.Stage-1 rows: 17,895 header-line cases. 789 rows are excluded (681 of them stage-1 rows), where beancount crashed or rejected an option name or an account name (
AAssets:A,A-ssets:A). rledger rejects an unknown option name at load time (E7001), and an invalid account name in most directives, but NOT in acustomvalue:2024-01-01 custom "budget" AAssets:A "x" 10 USD TRUE(alsoA-ssets:A,Assets0:A; 19 rows) gives "No errors found" in rledger while beancount reportsInvalid account name. That is a separate gap, tracked outside this PR.main!?&lines beancount ignores (#2779)02024-01-01,2024-001-01), which beancount's[0-9]{4,}[-/][0-9]+[-/][0-9]+accepts and our date lexer does notrledger formatloses textopen! ..., leading comma)All stages, counted the same way: every non-excluded row of the current matrix, compared with beancount's verdict. A miss is a row beancount rejects and rledger accepts; a false error is the reverse.
main/ this PRmain/ this PROnly stage 1 is checked by the test; stages 2 and 3 are generated for the later PRs. The stage-3 misses drop because of the posting-amount check below.
Found, left for stage 3
Checked against bean-check 3.2.3 and
rledgeron this branch (all also onmain):%,#!or#+after a posting amount (Assets:A 1 USD % c): beancount reports a syntax error; rledger reads a comment.{*}and{1 USD, *}: beancount reportsCost merging is not supported yet; rledger parses them.1 HOOL {1 USD} {2 USD},1 HOOL @ 2 USD @ 3 USD): beancount reports a syntax error; rledger parses them, andrledger formatdrops the second one, so text is lost.!Assets:A 1 USD): beancount ACCEPTS it, and rledger reportsunexpected input, a false error (the spaced! Assets:A 1 USDis accepted by both).Fixed during review
format_sourcewas not idempotent on a barepushtag,poptag,pushmeta,popmeta,option,includeorpluginat the end of a file with no newline (pushtagformatted topushtag, then topushtag). The missing-token error had an empty span at the very end, which overlaps no directive, so the directive was rebuilt instead of copied. A defect at the end of a line now points at the last token on it.fuzz/regressions/fuzz_parse/currency-tail-multibyte-2802.Corpus baselines
Three
parser-corpus.manifestrows move, all with unchanged source hashes. Each is a new error that beancount also reports:parser-lima/examples_data_error-duplicates.beancountopen Expenses:Technology NZD NZD GBPunexpected CURRENCY, expecting end of file or EOLparser-lima/examples_data_error-parse.beancountopen Assets:Bank:Current*,open Expenses:Groceries!unexpected ASTERISK/unexpected FLAGparser-lima/test-cases_ParserEntryTypes.BalanceWithCost.beancountbalance ... 10 MSFT {45.30 USD}unexpected LCURLThe CST manifest does not move.
Caches
Parse output changes, so the cache versions are bumped:
CACHE_VERSION49 to 50;CACHE_VERSION64 to 65;LOADER_CACHE_VERSION_PINto 50;FIXTURE_VERSIONs to 50.No archived layout moves.
Decisions (the user's)
**) an error.How to test
The matrix tests in
stray_char_matrix.rsfail onmain, for example:open! ...loses the!;option "title"! "T"./6Jtest (it also fails with only the lexer change reverted).To regenerate the expectations:
podman run --rm -i --userns=keep-id -v "$PWD:$PWD:Z" --workdir "$PWD" rustledger-compat:latest python3 -I scripts/stray-char-matrix.py > crates/rustledger-parser/tests/data/stray_char_matrix.tsvPart of #2802 (stage 1 of 3).
🤖 Generated with Claude Code