Repository navigation
fix(parser): read a date as beancount does, and name every invalid date on its line - #2868
Merged
Merged
Conversation
…te 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]>
…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]>
…s-as-beancount # Conflicts: # CHANGELOG.md
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]>
…ledger/rustledger into fix/dates-extra-digits-as-beancount
…s-as-beancount # Conflicts: # CHANGELOG.md
…p 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]>
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 |
…nd 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]>
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
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]>
…ine 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]>
…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]>
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
Dates read as beancount reads them (#2808). beancount's
DATEis[0-9]{4,}[-/][0-9]+[-/][0-9]+, with the three fields read as integers, so02024-01-01,2024-001-01and2024-01-016are dates there. Our lexer took\d{4}[-/]\d{1,2}[-/]\d{1,2}, so:kk: 2024-002-02, acustomorpushmetavalue, an amount) split into a number expression, which fix(parser): report stray characters in metadata lines #2810 and fix(parser): report stray characters in transactions and postings #2817 reported as a stopgap.Now the lexer takes beancount's rule exactly, ASCII digits included (
[0-9], not Unicode\d, so2024-0١-01is no date, as in beancount). One rule,parse_date_token(throughdiagnostics::date_fields), decides whether the fields form a real date: years 1 to 9999, as Python'sdatetime.dateallows. The stopgap is gone:split_beancount_date, thepushmetasplit-date exemption, and the 440 pinned date rows in the stray-character matrix. Those rows now match beancount and are checked like any other. An out-of-range field is named as written, however long (year 99999999999999999999999 out of range, not a saturatedu64).Every invalid date named, standing for the grammar errors it causes (#2856). beancount builds a date while lexing, so a bad date is a lexer error. It is named in every position, two on one line are two errors, and the parser never sees a date token there, so nothing at or after the date gets a grammar error on top. A grammar error before the date still stands, because the parser fails there first:
balance Assets:A USD 2024-02-30isunexpected CURRENCYplus the date in bean-check, and here too.report_invalid_dates, one pass over the green tree after all other checks, applies that rule in one place. It replaces the three per-line value-date checks.eventvalue, a price, a transaction header,optionandpluginarguments, and an orphan indented line. Before, these gave a generic syntax error.customare two errors.ERROR_TOKENis kept). Only grammar errors are dropped.`2024-02-30is oneInvalid tokenthere and the date is never read. The same date after a blank is named.The pass is linear: dates are sorted, line bounds come from one forward pass, and errors are matched by binary search. A counter-based test pins it (
test_report_invalid_dates_is_linear_in_the_input).Columns in constant time.
rledger check --format jsonfound each diagnostic's column by walking its line, twice per diagnostic, so thousands of errors on one long line were quadratic. That predates this PR (40,000 stray characters on one line take 2.2 s on main), but this PR made it reachable through dates.SourceFile::line_colandLineIndexnow count characters through a table of marks every 256 bytes. The drift guard againstline_col_ingains lines longer than the stride, with multi-byte characters across the marks.FFI input. Dates built from embedder input (
rustledger-ffi-wasiinput.rs) go through the same rule, via the new publicrustledger_parser::parse_date, which takes only text the lexer reads as oneDATEtoken. So year 0 is refused there, and so are24-01-15and1-1-1, which the oldjiffpath refused and which must not load as the years 24 and 1. An invalid cost date is an error instead of silently leaving the lot undated.Completion.
rustledger-completionrecognized onlyYYYY-MM-DDat line start, so completion after a2024-1-1or02024-01-01header was missing. It now asks the lexer, through the newrustledger_parser::leading_date_len(implemented asis_valid_account_nameis, by running the lexer).normalize_date_stris removed. It was a second date rule, and nothing called it any more. The lexer's#![expect(clippy::large_stack_frames)]is removed too: with ASCII[0-9]the generated lexer frame no longer trips the lint, so the expectation went unfulfilled.Compared with bean-check 3.2.3
Probe files:
2024-002-02.5) in 8 positions (metadata,custom,pushmeta,balanceandpriceamounts, posting units, cost,@price);`or mid-file BOM after a bad date, dates glued to an invalid character, Unicode digits and overlong fields;Every file gets parse errors on the lines bean-check reports, with two exceptions that predate this PR: an indented line under a directive with a bad date still gets its own P0012, where beancount's error recovery swallows it, and a date after an unterminated
"is not named. On the #2856 shapes and the lexer-error shapes the counts match too. Elsewhere a count can differ where rledger's error recovery splits or merges an error that beancount reports once, with or without this PR (`x2024-02-30is one invalid token in beancount and two errors here). Examples:02024-01-01 open Assets:Akk: 2024-002-02kk: 20024-02-022024-01-02 event "e" 2024-02-302024-02-30 custom "x" 2024-02-31custom "x" 2024-02-30 2024-13-01custom "x" 2024-02-30 `Invalid tokencustom "x" `2024-02-30Invalid tokenonlyFuzz corpus against beancount's parser. I took the 18,176 UTF-8 inputs in
fuzz_parseandfuzz_green_eq_redthat contain a date-shaped run, parsed each with beancount'sparse_stringand withrustledger_parser::parse, and counted parse errors per file (beancount crashed on 16, which are left out). Exact agreement is rare on fuzz input either way, because the two recover from errors differently:The first push dropped every non-date error on a bad-date line; on the same files it lost 89 matches. Of the 43 still lost, most are run-on fuzz dates (
999999-9999998/993-...), where main split the date and reported a metadata-line error that happened to match beancount's count, and beancount names a year that rledger's recovery reads differently. Others are rledger grammar checks that stand in for a beancount lexer error (a one-letter flag must be followed by a space,top-level directive must start at column 0) on a line that also has a bad date. They are dropped with the other grammar errors the date reaches. Real ledgers show none of this (below).Differences in what follows a parse error predate this PR. rledger keeps a directive that has a stray token, as decided in #2802, so booking can add its own error, while beancount drops the directive.
Performance on hostile input
rledger check --format json, release builds, best of 3, run back to back (the load average was around 30, so compare ratios):customline + 40,000 ×2024-02-30`Review round 2
2024-01-02 balance Assets:A USD 2024-02-30and2024-01-02 note Assets:A 5 2024-02-30gave only P0015 where bean-check reports the misplaced currency or number as well. Now only the errors the date causes are dropped: those starting at or after the line's first bad date, and a dropped directive's whole-nodeunexpected input, unless the header grammar (first_header_defect, recorded when the converter drops the directive) fails before the date. That last part is needed because rledger reports a droppedbalance,event,openornotewith one error spanning the whole line, which by itself does not say where the parser failed. Regression rows:test_parse_keeps_a_grammar_error_before_an_invalid_date(both lines, plusopen,priceand an unclosedcustomparen, whose errors are still dropped).ACCOUNT_TYPES.rustledger-completionre-exportsrustledger_core::ACCOUNT_TYPESinstead of keeping a copy (it depends on the parser now, and so on core), and the LSP test that guarded the copy is gone.parse_date's not-a-date error no longer repeats the input, so FFI reportsInvalid date '24-01-15': not a date (...), naming it once.Review round 3
2024-01-01 open Assets:A\n\n2024-01-02 price 2024-02-30gave 2 errors to bean-check's 1, foropen,close,commodity,pad(both orders),balance,note,document,query,eventandprice. Each dropped directive now records(span start, header start, failure point), withusize::MAXwhen the header grammar finds no defect, and the header start places the error on its line.Assets:A 5 USD USD 2024-02-30,"x" 2024-02-30and a body5 2024-02-30report both errors, and2024-02-30 5only the date. One more beancount rule surfaced in the probes: an indented line after a blank line, a column-0 comment, or at the top of the file is no directive's continuation, so beancount fails at the indent (unexpected INDENT) and reports that too, even for2024-02-30 5andkk: 2024-02-30. That is matched. An indented comment is a continuation and is not a gap.test_parse_keeps_a_grammar_error_before_an_invalid_datenow has 22 rows (the dropped directives, orphan lines and body lines), each checked directly after a directive, after a blank line and after a comment line. All 66 counts, and 23 more probes, equal bean-check 3.2.3's.ACCOUNT_TYPESkeeps its type:pub const ACCOUNT_TYPES: &[&str] = &rustledger_core::ACCOUNT_TYPES;.open Assets:C USD 2024-02-30 U,SD) still gives only the date error, where bean-check also reportsInvalid token. The header check reports only its earliest defect, which here is the date, so keeping the glued one means emitting a second header error; left for a follow-up.Review round 4
unexpected inputstill started at the node span, on the blank or comment line before it:2024-01-01 open Assets:A\n; c\n2024-01-02 balance Assets:A USD 2024-02-30gave lines [2, 3] to bean-check's [3, 3]. The error now starts at the header, for every dropped directive. On the 1,844 real ledgers no error line moves (main against this branch, line lists compared).test_parse_keeps_a_grammar_error_before_an_invalid_date, in all three placements, now checks each error's line as well as the counts, and the test pins the two round-4 examples ([3, 3] and [3, 3, 4, 4]). All 68 probes match bean-check 3.2.3 on counts and lines.option,include,plugin,pushtag,poptag,pushmeta,popmetaor an org-mode* Heading, bean-check reportsunexpected INDENTplus the date (option "title" "x"\n 2024-02-30 5gives 2 errors on line 2).previous_line_is_a_gapnow knows them. Still different, and not a date question:kk: 2024-02-30after one of those undated directives gets nounexpected INDENThere, because rledger reports no error for an indented metadata line there even with a valid date (main is the same).Review round 5
previous_line_is_a_gapread raw text, so a string continuing on a line that starts with*,;, or a gap keyword (option x",pushtag y") counted as one, and the indented line after it got an extra error:2024-01-02 * "multi\n* line"\n 2024-02-30 5gave [4, 4] to bean-check's [4]. The tree walk now recordsSTRINGtokens that run over a line end, and a line starting inside one is not a gap.%and#comments are gaps (bean-check 3.2.3 gives [2, 2] after each;#notewith no blank is a tag there, so it is not one).pushtag/poptag/pushmeta/popmetabefore and after the indented line, and for the four multi-line string cases. All 11 new probes match bean-check on counts and lines; the 1,844 real ledgers give identical error lines against main; the fuzz replay (45,973 inputs) stays lossless with green == red.Review round 6
#or%line (and an earlier round a bare*) for a comment, so the indented line after it got anunexpected inputon the wrong line. To beancount a bare marker is a token. A column-0 comment is now;and anything, or*,%or#followed by at least one more character on the line, with#not starting a tag (#note,#a.bare tags). Checked against bean-check 3.2.3.!x,&xand:xare comments to beancount too, but rledger already reports an error on those lines (as main does), so they are not gaps here.option "title" "a\nb"\n 2024-02-30 5and the same withplugin,includeandpushmetagiveunexpected INDENTplus the date, as bean-check does. A transaction's multi-line narration is still no gap.!x,&x,:x, differently on its own line).option "a\nb" "c\nd"then an indented date now gets bean-check'sunexpected INDENTand the date on line 4, but not its line-1 option error, which main does not report either. One differs from both:option "title" "a\nb" "c\nd"with an indented line after it gives rledger lines [2, 4, 4], main [2, 4] and bean-check [3, 4], because beancount's error recovery after that option's syntax error swallows the indent. Left for the follow-up issue on contrived input. The test pins the matching rows (lines and counts) and that a bare marker adds nothing.Review round 7
option "a" "b" "c",option "title" "a\nb" x,include "a\nb" "c",pushmeta kk: "a\nb" "c") counted as a gap, so the indented line after it got anunexpected INDENTbean-check does not report: beancount's recovery from the broken directive swallows that line. The gap check now requires that no error starts on the directive's lines. A validplugin "a\nb" "c"still gives [3, 3].#\r,%\rand*\rare comments. flex's.takes the\r, so bean-check 3.2.3 reads them as a marker plus one character. Round 6 trimmed the\rand pinned the wrong answer. That came from my probe harness, which read files in Python text mode and so turned CRLF into LF before beancount saw it. The harness now keeps newlines as they are, and the bean-check CLI agrees: [3, 3].How to test
cargo test -p rustledger-parser --test invalid_value_dates --test stray_char_matrix.cargo test -p rustledger-parser --lib test_report_invalid_dates_is_linear_in_the_input.cargo test -p rustledger-loader --lib char_columns_agree_between_surfaces.cargo test -p rustledger-completion --lib test_classify_after_date_in_every_shape_the_parser_reads.cargo test -p rustledger-ffi-wasi --lib input_entry_to_directive.Run locally:
cargo test --all-featureson parser, loader, completion, LSP, CLI and ffi-wasi.cargo check -p rustledger-wasm --target wasm32-unknown-unknown.-D warnings(workspace, all targets), rustdoc-Dwarningsandcargo fmt --check.Other checks
.beancount/.beanplus the compatibility corpus (1,844 files), main against this branch with separate builds. No file's parse errors change, messages included.corpus_baselineandcst_baselinepass with no row moved.fuzz_parse,fuzz_green_eq_redandfuzz_parse_line, 45,973 inputs. Lossless and green == red hold everywhere.rledger checkon the 913 KB fava example ledger, measured on the first push.Closes #2808
Closes #2856
🤖 Generated with Claude Code