Repository navigation
fix(parser): report stray characters in transactions and postings - #2817
Merged
Merged
Conversation
Closes #2802 (stage 3 of 3) Each posting line is checked against beancount's posting rule, a transaction has one flag, and a %, #! or #+ that is indented or mid-line inside a transaction is an error. The parse-time errors beancount's builder reports on postings are reported too (duplicate cost, date or label; # inside {{ }}; negative price; @@ without units). What beancount accepts and we did not now parses: a flag glued to its account, stacked signs (--1 USD is 1 USD), one leading comma in a cost spec. Cost merging ({*}) and cost/price currency mismatch are deliberately left as they were (see the PR). Loader cache v53, WASM cache v68. 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 |
beancount lexes % as a FLAG anywhere but a column-0 line, so ` % Assets:A
1 USD` is a flagged posting and `2024-01-01 % "x"` a transaction there; we
lexed it as a comment to the end of the line, dropping the posting. The
lexer now emits a one-character flag for a % that is not at column 0, and
the formatter's source classifier agrees. The matrix gained posting- and
transaction-flag snippets (cases() never inserts at a posting's first
character).
Also: a one-letter transaction flag glued to what follows (`P;c`, `P\r\n`)
is an error, as for a one-letter currency; the indented-comment check
skips a transaction with a byte search instead of walking it, and the
builder check no longer allocates per posting; the v53 cache note no
longer claims {*} and currency mismatches are parse errors; {*} is kept
as a correct feature beancount lacks.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The formatter's source-state drift guard now classifies PercentComment tokens too, with an idempotence fixture that mixes a column-0 % comment and % posting and transaction flags. rledger.alignAmounts treats an indented % as a posting flag, as the lexer does. An indented % now gets its Indent token on the AST path (the rewrite happens before the arms that synthesize it), and the dead PERCENT_COMMENT arms are gone. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The file (source hash unchanged) now gets beancount's parse error for a `@@` total price on a posting with no units (beancount: "Total price on a posting without units"). The row was missing from the local corpus copy, so the local strict run did not see it; CI did. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Nov 2, 2026
Merged
robcohen
added a commit
that referenced
this pull request
Nov 5, 2026
…te on its line (#2868) * fix(parser): read a date as beancount does, and name every invalid date on its line beancount's DATE is [0-9]{4,}[-/][0-9]+[-/][0-9]+ with the fields read as integers, so 02024-01-01, 2024-001-01 and 2024-01-016 are dates there. Our lexer took \d{4}[-/]\d{1,2}[-/]\d{1,2}: such a header date was an error, and a value was split into a number expression that #2810/#2817 reported as a stopgap. The lexer now takes beancount's shape, and one rule, parse_date_token (via diagnostics::date_fields), decides whether the fields form a real date (years 1 to 9999). The split-date stopgap (split_beancount_date, the pushmeta exemption, the 440 pinned matrix rows) is gone: those rows now match beancount and are checked. An invalid date is now reported wherever it stands, as beancount reports it while lexing, and stands for its line (report_invalid_dates, one pass over the green tree): event, price, transaction header, option, plugin and orphan lines name the date instead of a generic syntax error; two bad dates on one line are two errors; bad value dates under a directive with a bad date of its own are reported too. FFI input dates go through the same rule (rustledger_parser::parse_date), so year 0 is refused there and an invalid cost date is an error instead of an undated lot. Checked against bean-check 3.2.3 on 147 probe files (15 date shapes in 8 positions, the #2856 shapes, header dates): the same lines get parse errors, with the same counts. No compatibility-corpus or in-tree ledger changes (1,113 files); strict corpus baselines unchanged; the fuzz corpus replays clean (45,973 inputs, same 3 pre-existing idempotence cases as main); about 0.6% more instructions on the 913 KB example ledger. Loader cache v57, WASM cache v73. Closes #2808 Closes #2856 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(parser): keep lexer errors on a bad-date line, linear date pass, ASCII date digits Review follow-ups on the date rework: - report_invalid_dates is linear: dates sorted, line bounds from one forward pass, errors matched by binary search; counter-based test. - Diagnostic columns are found through a character-mark table, so many errors on one long line no longer make check --format json quadratic. - A bad date drops only its line's grammar errors; an error covering an ERROR_TOKEN (stray character, mid-file BOM) stands, as in beancount. A date inside a beancount invalid-token run is not named. - parse_date takes only text the lexer reads as one DATE token, so 24-01-15 and 1-1-1 are refused; new leading_date_len shares the rule. - The DATE regex uses ASCII [0-9], as beancount does. - An out-of-range date field is named as written, not saturated. - Completion recognizes every header date shape via leading_date_len. Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore: regenerate cargo-vet exemptions * fix(parser): keep a grammar error that comes before an invalid date Review round 2 on the date rework: - A bad date now drops only the grammar errors it causes: those that start at or after the line's first bad date, or a dropped directive's whole-node error when the header grammar fails at or after the date. An error before the date stands, as in beancount (`balance Assets:A USD 2024-02-30`, `note Assets:A 5 2024-02-30`). - rustledger-completion re-exports rustledger_core::ACCOUNT_TYPES instead of keeping a copy; the LSP drift test for the copy is gone. - parse_date's not-a-date error no longer repeats the input, so the FFI message names it once. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(parser): place a dropped directive's error by its header, and keep an orphan line's earlier error Review round 3 on the date rework: - A dropped directive's whole-node error spans the blank and comment lines before it, so it was not placed on its bad-date line and was kept beside the date. Each dropped directive now records its header start and the header grammar's failure point (usize::MAX when there is none). - A whole-line recovery error (an orphan indented line, a body line no posting takes) fails at its first token, or at the indent after a blank line, a column-0 comment or the top of the file, as beancount does; an error from before the date stands. - The regression test checks 22 rows directly, after a blank line and after a comment line, against bean-check 3.2.3's counts. - rustledger-completion's ACCOUNT_TYPES keeps its `&[&str]` type. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(parser): report a dropped directive's error on its header line, and more indent gaps Review round 4 on the date rework: - The whole-node error of a dropped directive now starts at the header, not at the blank or comment line its node span takes in, so it is on the line bean-check reports. - An indented line after option, include, plugin, pushtag, poptag, pushmeta, popmeta or an org-mode heading is no continuation, so it fails at the indent, as in bean-check 3.2.3. - The regression matrix asserts each error's line as well as the count. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(parser): a line inside a multi-line string is never an indent gap Review round 5 on the date rework: - previous_line_is_a_gap read raw text, so a multi-line string continuing on a line that starts with `*`, `;` or a gap keyword counted as a gap. The tree walk now records STRING tokens that run over a line end, and a line starting inside one is not a gap. - `%` and `# ` comment lines are gaps, as in bean-check 3.2.3. - Test rows for those and for pushtag, poptag, pushmeta and popmeta. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(parser): no indent gap after a bare marker, and read a string's line for the gap Review round 6 on the date rework: - A column-0 comment is `;` and anything, or `*`, `%` or `#` with at least one more character on the line and `#` not starting a tag, as in bean-check 3.2.3. A bare marker is a token there, so it is no gap. - A previous line that starts inside a multi-line string steps back to the line the string starts on, and only the no-metadata check applies there, so an indented line after a multi-line `option`, `plugin`, `include` or `pushmeta` value fails at the indent as in beancount. - Test rows for both. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(parser): a broken no-metadata directive is no indent gap, and `#\r` is a comment Review round 7 on the date rework: - A directive that takes no metadata but is itself a syntax error is no gap: beancount's recovery from it swallows the indented line after it, so it reports no unexpected INDENT there (bean-check 3.2.3). - `#\r`, `%\r` and `*\r` are comments, as flex's `.` takes the `\r`. - Test rows for both, including a valid multi-line plugin that still is a gap. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: rustledger-bot[bot] <257329324+rustledger-bot[bot]@users.noreply.github.com>
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.
Stage 3 of 3 of #2802: stray characters in transaction headers and posting lines.
What changed
postingrule (optflag account incomplete_amount cost_spec [@|@@ price]), as one recognizer next to the header and metadata ones incst/directive_header.rs(first_posting_defect). It replaces stage 1's narrower leftover-token check. A token with no place in a posting (Assets:A ! 1 USD,1 USD % x,{1 USD} {2 USD},@ 2 USD @ 3 USD,{2 & USD},{#2 USD}) used to be dropped and then deleted byrledger format; it is now an error. The transaction is kept, as for a header line (fix(parser): report stray characters in directive header lines #2805).txnis one token in beancount);2024-01-01 * * "x",!*,* A "x"were accepted.%,#!and#+that are indented or mid-line anywhere in a transaction are errors (only;starts a comment there in beancount). Before, they silently commented out the rest of the line. At column 0 they are still comments.{2, USD}is two costs), a#inside{{ }}, a negative price (evaluated by the sharedparse_arith_expr), and@@on a posting with no number for its units.!Assets:A 1 USD), a CST parser change;--1 USD= 1,2 * - 3 USD= -6). TheAMOUNTemitter takes any run of signs, and both the redAmount::is_arithmeticand the greensimple_amountroute stacked signs to the evaluator, so--1is not read as -1;{, 2 USD}), incost_spec_shape.rs.%is a flag outside column 0, as in beancount (its FLAG set is[!&#?%]):% Assets:A 1 USDand%Assets:Aare flagged postings and2024-01-01 % "x"is a transaction. We lexed%as a comment to the end of the line, so the posting was dropped in silence. The lexer now emits a one-character FLAG for a%that is not at column 0 (a column-0%line is still a comment), and the formatter's source classifier (pinned by its drift guard and a new fixture) and the LSP'srledger.alignAmountsagree. This applies everywhere, not only in transactions: an indented or mid-line%comment under any directive, in metadata or at top level is now an error, as in beancount ("unexpected FLAG"); no corpus, in-tree or doc file has one.\r, or glued to what follows (2024-01-01 P;c), is an error on any line, as beancount's[A-Z]/[ \t\n].2024-002-02 USDloaded as 2020 USD).Deviations and decisions (please review)
{*}) is accepted, by decision. beancount 3.2.3 rejects it ("Cost merging is not supported yet"); rledger implements it (average-cost merge booking). Decided: rledger keeps correct features beancount lacks; the rule is to match beancount on correctness, not on missing features. Documented atposting_builder_error, pinned bytest_parse_accepts_cost_merging_unlike_beancountand 1 matrix row.CostPriceCurrencyMismatch, with the reason), and a parse-time check reported every such sale twice (P0012 plus E4001). So this PR keeps main's behavior: a sale gets E4001, and a buy with mismatched currencies still loads. It is pinned bytest_parse_leaves_a_cost_and_price_currency_mismatch_to_bookingand 64 matrix rows. Decision pending: move the rule to parse time only, or leave it at booking. This PR does not change it.rledger formatadds that newline, after which beancount accepts the file too, so reporting it made formatting non-idempotent (found by the fuzz-corpus replay). Documented atglued_one_letter_currencyand pinned by a test.The keep-the-transaction policy and one-flag-only are the decisions you made for #2802.
Matrix (
scripts/stray-char-matrix.py, beancount 3.2.3)18 transaction snippets were added: every transaction flag form, every posting flag spaced and glued (
cases()never inserts at a posting's first character, so the flag position has bases of its own), expressions, every cost-spec shape, prices, a posting with no amount, trailing comments, an indented tags line, and CRLF. One counting rule throughout: a miss is a case beancount rejects and rledger accepts; a false error is the reverse; every non-excluded row counts.\r)The stage-3 rows left on this branch are all pinned by count in
tests/stray_char_matrix.rs:!/?/&lines (compat: column-0 :, !, & and ? lines are ignored by beancount but rejected by rledger #2779);\r(fix(parser): treat a stray \r before a line ending as trivia, as beancount does #2804);Every stage is checked now; none is unchecked.
Verification
Matrix test:
tests/stray_char_matrix.rspasses (29 tests). Copied onto main, the stage-3 tests fail.Test suites:
cargo testfor parser, core, loader, rledger, lsp, booking, query and wasm (--all-features): 210 result lines, 0 failed. Also clean:cargo clippy -D warnings(parser, rledger, lsp, loader, wasm),RUSTDOCFLAGS=-Dwarnings cargo doc --document-private-items,cargo fmt --check, andcargo check -p rustledger-wasm.Corpus baselines:
STRICT_BASELINE=1corpus_baselineandcst_baselinepass on the 732-file corpus. 7 rows ofparser-corpus.manifestmoved, all with unchanged source. Each now reports errors on exactly the lines beancount does (checked file by file):LexerErrorsInPostings(lines 17, 23, 29:unexpected RPAREN)CostEmptyComponentsCostRepeated,CostRepeatedDate,CostRepeatedLabelPriceNegative,TotalPriceInvertedThe CST baseline did not move.
False-error sweep: 662 more files (382 in-tree
.beancount/.beanand 280 doc code blocks), main vs this PR vs beancount. No line errors on this PR that main accepted and beancount accepts. 8 files changed, and each now matches beancount exactly; all 8 are lima fixtures main under-reported.Fuzz: all 42,587 UTF-8 inputs on
origin/fuzz-corpus(fuzz_parse,fuzz_green_eq_red,fuzz_parse_line) pass lossless and green == red (errors and directives), andformat_sourceis idempotent on all of them in my replay. An independent review's harness found 2 inputs (a run of BOMs, a\vinput) that are not idempotent; they fail identically on main, so they are pre-existing, not from this PR. The in-tree fuzz regressions pass.Perf: release
parse, best of 20 per run, main and branch binaries alternated 12 times, pinned to one core (taskset -c 2), medians: the 913 KBfava_investor_examples_huge-example.beancount8.84 ms on main vs 9.29 ms (+5.0%); a 2.6 MB posting-heavy synthetic ledger (16,000 transactions, each posting with a cost and a price) 49.32 ms vs 52.35 ms (+6.1%). Before this round's fixes the same method measured +28% and +19%: the indented-comment check built red nodes for every transaction, and the builder check allocated per posting.Cache: loader v53, WASM v68, pin and both fixture versions 53.
Test changes worth a look
unexpected X in a posting. The glued case still says "a currency cannot end in".format_keeps_hash_bang_lines.rs): indented#!/#+lines in a transaction and after a posting amount are errors now (beancount:unexpected FLAG/HASH). The tests assert they are reported and that the error-tolerant formatter keeps them verbatim. Theopenmetadata-block case is unchanged (deferred, see below).rledger formatdeletes the currency and price/cost annotation when a posting's units number is missing #2142 formatter test: the two@@-without-units cases are errors now (beancount: "Total price on a posting without units"), so the error-tolerant formatter copies them verbatim.TotalPriceInverted,TotalPriceWithMissing,PriceNegativeandCostRepeated*now expect a parse error, as beancount gives.green_red_propertieskeeps prices non-negative and gives a posting's cost and price one currency, weighting the error shapes ({*}, a negative difference) down so at least 25% of ledgers stay clean.pipeline_invariantsgenerates non-negative prices.Found, not fixed (follow-ups)
#!/#+lines under a non-transaction directive (anopenmetadata block): beancount rejects them; rledger still reads a comment. (An indented%there is now an error, by the lexer change above.)Closes #2802
🤖 Generated with Claude Code