Skip to content

fix(parser): ignore column-0 !, &, ? and : lines and report bare markers, as beancount does - #2877

Merged
robcohen merged 7 commits into
mainfrom
fix/column0-flag-lines
Nov 7, 2026
Merged

robcohen merged 7 commits into
mainfrom
fix/column0-flag-lines

Conversation

@robcohen

@robcohen robcohen commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

What changed

Beancount's lexer ignores a whole line that starts at column 0 with *, :, # or a flag character (^[\*\:\#]/. and ^{FLAGS}/., with FLAGS [!&#?%]). rledger now does the same:

  • A column-0 !, &, ? or : line is a comment. It was a P0012 error, so rledger check, query and format refused files that bean-check accepts. The line becomes one comment token, like a column-0 # comment, and it is never lexed, so a " on it opens no string.
  • A bare marker is an error on its own line, for every marker. A bare marker has its line ending, or the end of the file, right after it. Both beancount rules need one more character on the line (flex's .), so bean-check reports unexpected FLAG / HASH / ASTERISK / COLON there. rledger used to read a bare #, % or * line as a comment. A \r counts as the extra character, so a bare marker on a CRLF line is still ignored, as in beancount.
  • An indented line after an ignored line is unexpected INDENT, as it is after any column-0 comment.

Implementation:

  • logos_lexer::beancount_ignores_line is now the one rule for which column-0 lines beancount ignores. The lexer's column-0 #/!/&/?/:/% arms use it. convert::is_section_marker (the * heading) and previous_line_is_a_gap used to re-derive the rule inline; they now call it.

  • In the formatter, the line-ending state machine treats a column-0 !, &, ? or : as a comment. There is a new drift-guard fixture (flag_line_quote_then_string).

  • Stray-character matrix: the 192 pinned known_column_0_divergence rows now match beancount and are checked. The pin is removed. The TSV is unchanged, because beancount's verdicts did not move.

  • LSP: the balance_lens_neutral_when_parse_errors_skip_validation fixture used a column-0 !!! syntax garbage line as its parse error. That line is now a comment, as in bean-check (which reports nothing on it), so the fixture uses @@@ syntax garbage, which both tools reject.

  • Parse caches: loader CACHE_VERSION 58 (with FIXTURE_VERSION to match), WASM CACHE_VERSION 74 (with LOADER_CACHE_VERSION_PIN 58). Both are named in the CHANGELOG.

  • Formatter: a lone marker that beancount ignores only because of the whitespace or \r after it (#\r\n, !\r\n, %\r\n, *\r\n, * , *\t) keeps one space after the marker. Without it, trimming the line or folding its CRLF would leave a bare-marker error. This covers comment tokens (push_comment_text, at all five emission sites), * headings in emit_error_node, and crlf_to_lf_outside_strings, which format_source runs before parsing. bean-format keeps such lines' trailing whitespace but folds the \r away in Python's text mode, which breaks them, so this keeps a space instead of matching bean-format. A marker that was already bare stays bare and stays an error.

#2872 rows covered

  • !x, &x, :x column-0 lines (also with CRLF): bean-check 3 3, rledger was 2 3, now 3 3.
  • A bare #, % or * line: bean-check also reports the marker on its own line, rledger did not, now it does (also for bare !, &, ?, :).

The other #2872 rows are not touched here.

Known difference (for #2872, not fixed here): rledger reports every line of a run of consecutive bare markers (!\n#\n*\n: lines 2, 3, 4), but bean-check's error recovery reports only the first (line 2).

Why

Issue #2779: the decision was to match beancount.

How to test

cargo test -p rustledger-parser --all-features --test column0_marker_lines --test stray_char_matrix --test invalid_value_dates
cargo test -p rustledger-parser --all-features --lib beancount_ignores_line

Verification done:

  • I compared bean-check 3.2.3 with this branch on 60+ probe files: each marker with x, x, "q and bare, LF and CRLF, at EOF, inside a transaction, inside a multi-line string, and followed by an indented bad date. Both report parse errors on the same lines, with the same counts. Three kinds of probe still differ, and none of them comes from this change: they behave the same with a ; comment in place of the marker, or they are another Parse-error recovery differences from bean-check around invalid dates and column-0 markers #2872 row. They are a comment line between a transaction header and its postings, a #a b tag line, and a file-leading BOM.
  • Parse errors on all 1,113 in-tree and compat-corpus ledgers, main vs branch: one file differs. parser-lima/examples_data_full.beancount loses its three P0012 errors on lines 5-7, an org-mode :PROPERTIES: / :END: drawer, and bean-check reports nothing there either. That file is also the one baseline change: its rows in tests/baselines/parser-corpus.manifest and cst-corpus.manifest are updated (source hash unchanged; the parser-output hash, and the CST token-sequence and node-shape hashes, move because the three drawer lines are now comment trivia instead of error nodes). The rows were taken from a run of scripts/regen-corpus-baselines.sh, but only this row: the local corpus differs from CI's frozen copy on about 20 other files, so the rest of the regenerated manifest was discarded.
  • cargo test --workspace --all-features --no-fail-fast (after review round 1; the round-1 clippy-only refactor was then re-tested on parser, lsp, the CLI, loader, wasm and ffi-component), cargo clippy --all-features --all-targets -- -D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps, cargo fmt --check.

Review round 1

  1. The LSP code_lens fixture used !!! syntax garbage, which is now a comment. It now uses @@@ syntax garbage. Both corpus manifests are updated for parser-lima/examples_data_full.beancount. Only that row is taken from the regenerated output, and the parser-output hash now equals the one CI reported (076e637db4fd727d). The earlier claim that the CST manifest does not move was wrong and is corrected above.
  2. rledger format no longer turns an ignored lone-marker line into a bare-marker error (see the Formatter bullet). New fixtures cover #, !, &, ?, :, % and * followed by \r\n, a space or a tab, plus #\r\r\n, * \t and *\r \r\n. Each one is tested mid-file, at EOF, and at EOF without a final newline. The tests check parse preservation and idempotence for format_source and try_format_source, and parse preservation for whole-file range formatting with format_parsed_range, the LSP path; range formatting refuses an ERROR_NODE * heading, so it cannot break one. crlf_to_lf_keeps_the_lexer_line_structure gained the CRLF cases. With the CLI, all 14 <marker>\r\n probes (mid-file and at EOF), * \n and *\t\n give 0 errors after one rledger format -i and after a second one.
  3. is_flag_line_comment cannot call beancount_ignores_line: advance_source_state is a const fn over one char and a peek. The rule's doc now lists it as a deliberate char-level mirror, with a cross-reference at both sites. The existing source_state_classification_agrees_with_lexer guard pins agreement.
  4. The consecutive-bare-marker difference is listed above as a known difference for Parse-error recovery differences from bean-check around invalid dates and column-0 markers #2872.

Review round 2

  1. LSP format-on-save on a file with parse errors uses surface_cleanup_edits, and its clean_line trimmed # to #. It now keeps one space when the trim would turn a line beancount ignores into one it does not. The check uses rustledger_parser::logos_lexer::beancount_ignores_line, which is now public for this; its doc lists its users. A new test surface_cleanup_keeps_whitespace_marker_lines_ignored covers all 7 markers with a space, a tab and mixed whitespace, LF and CRLF. The error count stays 1, and a bare marker is left alone. Other formatting paths were checked: WASM, FFI, the CLI and the MCP format tool all go through the parser formatter, and none has a trailing-whitespace stripper of its own.
  2. crlf_to_lf_outside_strings found the current output line with an rfind over the whole output for every \r, which made a long line of stray \rs quadratic. It now keeps the line start as a running index. A counter test, crlf_to_lf_lone_marker_check_is_linear, runs the reviewer's ; + 160k a + 160k \r input and a #\r + 160k \r input.
  3. format_source and the non-folding paths now agree on #\r \r\n, # c\r \r\n, #\t\r\n, * c\r \r\n and on #\r / # c\r \r at EOF, so the byte-identity claim holds. The fix is in the lexer: its whole-line cut, line_end_before_newline, now ends before the stray-\r run at the line end (a [ \t\r] run from a \r on), and that run is exactly what the CRLF fold drops. Spaces and tabs before the run's first \r stay in the comment, as before. These cases were added to crlf_to_lf_keeps_the_lexer_line_structure, which asserts try_format_source == format_source. The bean-format deviation is noted in the CHANGELOG and with a "stricter than bean-format" comment at crlf_to_lf_outside_strings.

Verification for this round:

  • cargo test --workspace --all-features --no-fail-fast passes.
  • clippy -D warnings, rustdoc -Dwarnings and cargo fmt --check are clean.
  • Corpus format comparison, main vs branch, rledger format --no-ledger on 1,113 in-tree and compat ledgers: the output is byte-identical on all of them, and the exit codes match (the run listed 1,136 paths, because 23 in-tree compat fixtures were listed once from each checkout; of those runs, 1,042 formatted and 94 were refused for parse errors, on both).

Review round 3

  1. crlf_to_lf_lone_marker_check_is_linear could not fail: it counted the bytes pushed per step, which is at most one per input char. The line-start lookup is now OutLine::start_in, which scans only what was pushed since its last call and counts the bytes it scans. I checked that the test can now fail: with the old rfind put back inside start_in, it counts 25,600,320,000 bytes on the 320,003-byte input and fails. With the fix restored, it passes.
  2. LSP clean_line: a first line of BOM + # (with a parse error elsewhere) was trimmed to BOM + #, a bare-marker error. The BOM is now left out of the beancount_ignores_line check and kept in the output. The new test surface_cleanup_keeps_whitespace_marker_line_after_bom_ignored covers every marker, with a space and with a tab.
  3. The ledger counts above are corrected to 1,113 unique files. The runs listed 1,136 paths, because 23 in-tree compat fixtures were listed once from each checkout.

Verification: parser and LSP tests, clippy -D warnings, rustdoc -Dwarnings and cargo fmt --check all pass.

Closes #2779

🤖 Generated with Claude Code

…ers, as beancount does

Beancount's lexer ignores a whole line that starts at column 0 with `*`,
`:`, `#` or a flag character (`^[\*\:\#]/.` and `^{FLAGS}/.`, with
`FLAGS [!&#?%]`). rledger reported a `!`, `&`, `?` or `:` line as P0012,
so check, query and format refused files bean-check accepts (an org-mode
`:PROPERTIES:` drawer in the compat corpus, for one). Both rules need one
more character on the line (flex's `.`, which a `\r` satisfies), so a bare
marker is a token and an error there; rledger read a bare `#`, `%` or `*`
line as a comment.

- One rule, `logos_lexer::beancount_ignores_line`, decides which column-0
  lines beancount ignores. The lexer's column-0 arms use it: a `!`, `&`,
  `?` or `:` line is one comment token, like a `#` comment, and is never
  lexed (a `"` there opens no string); a bare `#` or `%` stays its own
  token. `is_section_marker` (the `*` heading) and `previous_line_is_a_gap`
  (an indented line after an ignored line is `unexpected INDENT`) call it
  instead of re-deriving it.
- Formatter: the line-ending state machine treats a column-0 `!`, `&`, `?`
  or `:` as a comment, with a drift-guard fixture.
- Stray-character matrix: the 192 pinned column-0 rows now match beancount
  and are checked; the pin is gone. The TSV is unchanged.
- Loader CACHE_VERSION 58, WASM 74.
- Tests (checked against bean-check 3.2.3), CHANGELOG.

Closes #2779

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

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 43.9ms ± 1.1ms 582.3ms ± 9.8ms 13.3x 42.8 MB / 51.0 MB
investment 68.7ms ± 3.2ms 2136.5ms ± 9.1ms 31.1x 59.0 MB / 58.9 MB
fifo 66.1ms ± 0.8ms 12216.0ms ± 79.7ms 184.8x 54.8 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 45.4ms ± 2.6ms 43.9ms ± 1.1ms -3.2% ✅ within noise 42.6 MB → 42.8 MB (+0.6%)
investment 67.2ms ± 0.7ms 68.7ms ± 3.2ms +2.3% ✅ within noise 56.9 MB → 59.0 MB (+3.6%)
fifo 65.8ms ± 0.7ms 66.1ms ± 0.8ms +0.5% ✅ within noise 53.0 MB → 54.8 MB (+3.5%)

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

@github-actions

github-actions Bot commented Nov 6, 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

robcohen and others added 2 commits November 6, 2026 13:03
…ixtures #2779 moved

Review round 1 and CI on the #2779 change:

- Formatter: a lone column-0 marker that beancount ignores only because of
  the whitespace or `\r` after it (`#\r\n`, `*\r\n`, `* `, `*\t`) became a
  bare-marker error after `rledger format`, which trimmed the whitespace or
  folded the CRLF away. Such a line now keeps one space after the marker,
  in comment emission (`push_comment_text`, all five sites), `*` headings
  in `emit_error_node`, and `crlf_to_lf_outside_strings`. bean-format folds
  the `\r` away (Python text mode), so it is not matched here. A marker that
  was already bare stays an error. Fixtures cover every marker with
  `\r\n`, a space and a tab, mid-file and at EOF, through format_source,
  try_format_source, a second pass and range formatting.
- The formatter's `is_flag_line_comment` is documented as a deliberate
  char-level mirror of `beancount_ignores_line`, at both sites.
- LSP: the code_lens parse-error fixture used a column-0 `!!!` line, now a
  comment as in beancount; it uses `@@@` instead.
- Corpus baselines: the parser-output and CST rows for
  parser-lima/examples_data_full.beancount (its `:PROPERTIES:` drawer is
  now comment trivia). Only that row was taken from the regenerated
  manifests; the local corpus differs from CI's on other files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… fold CRLF in linear time

Review round 2 on the #2779 change:

- LSP: format-on-save on a file with parse errors falls back to
  `surface_cleanup_edits`, whose `clean_line` trimmed `# ` to `#`, a
  bare-marker error. It now keeps one space when the trim turns a line
  beancount ignores into one it does not, by the shared rule
  `logos_lexer::beancount_ignores_line`, now public for this. Tested for
  every marker with a space, a tab and mixed whitespace, LF and CRLF.
- `crlf_to_lf_outside_strings` found the current output line with an
  `rfind` over the whole output for every `\r`, quadratic on a long line of
  stray `\r`s. It now keeps the line start as a running index, with a
  counter test on the reviewer's input.
- The lexer's whole-line cut (`line_end_before_newline`) ends before the
  stray-`\r` run (`[ \t\r]` from a `\r` on) at the line end, which is the
  trivia `crlf_to_lf_outside_strings` drops, so `format_source` and
  `try_format_source` agree on `#\r \r\n`, `# c\r \r\n` and `#\r ` at EOF.
- Note at `crlf_to_lf_outside_strings` and in the CHANGELOG: stricter than
  bean-format, which folds `#\r\n` to `#\n`, a line bean-check rejects.

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

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.48980% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/format.rs 98.79% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

…eep a BOM-led marker line ignored in LSP cleanup

Review round 3 on the #2779 change:

- `crlf_to_lf_lone_marker_check_is_linear` counted the bytes pushed per
  step, which cannot exceed one per input char, so restoring the old
  `rfind` still passed. The line-start lookup is now `OutLine::start_in`,
  which scans only what was pushed since its last call and counts what it
  scans. With the `rfind` restored there, the test counts 25,600,320,000
  bytes on a 320,003-byte input and fails.
- LSP `clean_line`: a file's first line `BOM + "# "` was trimmed to
  `BOM + "#"`, a bare-marker error. The BOM is left out of the
  `beancount_ignores_line` check and kept in the output, with a test for
  every marker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) November 6, 2026 22:03
@robcohen
robcohen disabled auto-merge November 6, 2026 22:04
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.

compat: column-0 :, !, & and ? lines are ignored by beancount but rejected by rledger

1 participant