Repository navigation
fix(parser): treat a stray \r before a line ending as trivia, as beancount does - #2804
Merged
Merged
Conversation
…count does
A line ending in `\r\r\n`, or a file ending in a lone `\r`, was a parse
error ("unexpected input"; two errors on a transaction header) while
bean-check 3.2.3 accepts it: beancount skips `\r` as whitespace, but our
`Newline` token (`\r?\n`) claims only the `\r` right before the `\n`, so
any other one became an error token.
- Lexer (`TokenIter::stray_cr_trivia_end`): a `[ \t\r]` run that contains
a `\r` and reaches the line ending (stopping before the `\r` of a
`\r\n`) or the end of the source is one `Whitespace` token. The bytes
stay in the token stream and the CST.
- `line_end_before_newline` (column-0 `#` comments, `*` headings, the cut
of an unterminated string) also ends before such a run, so a comment's
text no longer carries the stray bytes.
- Formatter: `crlf_to_lf_outside_strings` drops such a run instead of
folding each `\r` into a `\n`, which added a blank line that ended a
transaction. `stray_cr_run` mirrors the lexer; a drift guard pins it.
- A `\r` with more of the line after it stays an error (stricter than
beancount, documented at both sites): the formatter folds that `\r`
into a line break, which keeps classic-Mac files formattable.
- Loader cache v49, WASM cache v64 (parser output changed).
Closes #2774
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 |
… its line A long [ \t\r] run followed by more of its line was rescanned from each of its \r bytes, each scan failing at the same byte: O(N^2), over 120 s on 1 MB. The end of a failed scan is now remembered and tokens inside it skip the scan, so each byte is scanned at most once. A cfg(test) counter pins the scanned bytes as linear. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen
enabled auto-merge (squash)
October 29, 2026 13:54
robcohen
added a commit
that referenced
this pull request
Oct 29, 2026
Brings in #2804. The only conflict was CHANGELOG.md (both added an entry at the top of Fixed); both are kept. Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Nov 29, 2026
` Assets:A 10 USD @@\r 9 EUR` and ` Assets:A 10\r USD` are clean in beancount 3.2.3, which reads a `\r` that is not part of a CRLF line end as a blank. rledger reported the `\r` as an error of its own (P3, kept from when the formatter folded a bare `\r` into a line break, #2804), and the parser then dropped what followed it from the posting (the price, the units), so the transaction also failed to book. The lexer now turns any `[ \t\r]` run holding a stray `\r` into `Whitespace` trivia once the line has a token. A run that starts its line keeps its error (beancount does not take it as an indent, so it reads the line as unindented), unless it ends the line or the token after it is an error anyway. With mid-line runs always trivia, the longer needed: a line-start run peeks one token. P3 in compatibility.md and the overlay doc say only the line-start case now. Parse-error parity: 122,478 of 123,394 (was 122,378); the 13 inputs that newly mismatch read the same as with a space for the `\r`. Loader cache v85, WASM cache v167. Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Nov 29, 2026
` Assets:A 10 USD @@\r 9 EUR` and ` Assets:A 10\r USD` are clean in beancount 3.2.3, which reads a `\r` that is not part of a CRLF line end as a blank. rledger reported the `\r` as an error of its own (P3, kept from when the formatter folded a bare `\r` into a line break, #2804), and the parser then dropped what followed it from the posting (the price, the units), so the transaction also failed to book. The lexer now turns any `[ \t\r]` run holding a stray `\r` into `Whitespace` trivia once the line has a token. A run that starts its line keeps its error (beancount does not take it as an indent, so it reads the line as unindented), unless it ends the line or the token after it is an error anyway. With mid-line runs always trivia, the longer needed: a line-start run peeks one token. P3 in compatibility.md and the overlay doc say only the line-start case now. Parse-error parity: 122,478 of 123,394 (was 122,378); the 13 inputs that newly mismatch read the same as with a space for the `\r`. Loader cache v85, WASM cache v167. Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Nov 29, 2026
` Assets:A 10 USD @@\r 9 EUR` and ` Assets:A 10\r USD` are clean in beancount 3.2.3, which reads a `\r` that is not part of a CRLF line end as a blank. rledger reported the `\r` as an error of its own (P3, kept from when the formatter folded a bare `\r` into a line break, #2804), and the parser then dropped what followed it from the posting (the price, the units), so the transaction also failed to book. The lexer now turns any `[ \t\r]` run holding a stray `\r` into `Whitespace` trivia once the line has a token. A run that starts its line keeps its error (beancount does not take it as an indent, so it reads the line as unindented), unless it ends the line or the token after it is an error anyway. With mid-line runs always trivia, the longer needed: a line-start run peeks one token. P3 in compatibility.md and the overlay doc say only the line-start case now. Parse-error parity: 122,478 of 123,394 (was 122,378); the 13 inputs that newly mismatch read the same as with a space for the `\r`. Loader cache v85, WASM cache v167. Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Nov 29, 2026
…3099) ` Assets:A 10 USD @@\r 9 EUR` and ` Assets:A 10\r USD` are clean in beancount 3.2.3, which reads a `\r` that is not part of a CRLF line end as a blank. rledger reported the `\r` as an error of its own (P3, kept from when the formatter folded a bare `\r` into a line break, #2804), and the parser then dropped what followed it from the posting (the price, the units), so the transaction also failed to book. The lexer now turns any `[ \t\r]` run holding a stray `\r` into `Whitespace` trivia once the line has a token. A run that starts its line keeps its error (beancount does not take it as an indent, so it reads the line as unindented), unless it ends the line or the token after it is an error anyway. With mid-line runs always trivia, the longer needed: a line-start run peeks one token. P3 in compatibility.md and the overlay doc say only the line-start case now. Parse-error parity: 122,478 of 123,394 (was 122,378); the 13 inputs that newly mismatch read the same as with a space for the `\r`. Loader cache v85, WASM cache v167. 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
TokenIter::stray_cr_trivia_end,crates/rustledger-parser/src/logos_lexer.rs): when the lexer produces aWhitespacetoken or a lone-\rerror, the whole[ \t\r]run starting there becomes oneWhitespacetoken if it contains a\rand reaches the line ending or the end of the source. The scan stops before the\rof a\r\n, so that pair stays in theNewlineas on every other CRLF line. The\rbytes stay in the token stream and the CST as trivia. An ordinaryWhitespacetoken costs one byte comparison, and the scan only moves forward over bytes the run then consumes.line_end_before_newline(column-0#comments,*headings, the cut of an unterminated string) also ends before such a run. The stray bytes become the sameWhitespacetrivia instead of comment text, so# note\r\r\nis nowComment("# note"),Whitespace("\r"),Newline(it wasComment("# note\r")). The fix(parser): a column-0 # comment with CRLF line endings breaks the next directive #2769 lib test is updated to match.crlf_to_lf_outside_strings,crates/rustledger-parser/src/cst/format.rs): a stray run is dropped instead of having each\rturned into a\n. The old fold added a blank line, which ends a transaction, soformat_sourcecut the postings off a transaction whose header ended in\r\r\n.try_format_source(whatrledger formatcalls) formats the parsed tree and did not hit this, so the two entry points disagreed.stray_cr_runmirrors the lexer rule, and the two sites point at each other. Any other bare\ris still folded into a line break (classic-Mac files).crlf_to_lf_keeps_the_lexer_line_structuretest checks that each stray-\rsource parses clean, still parses to the same directives after the fold, and gives the same output fromtry_format_sourceandformat_source. There is a newIDEMPOTENCE_MATRIXfixturestray_cr_before_line_ending(*,#,#!,;with a", metadata, posting, trailing\rat EOF), sosource_state_classification_agrees_with_lexer, the idempotence tests and the round-trip fidelity tests run on these shapes too. There is also a newparse_green_eq_red_corpusentry.CACHE_VERSION48 -> 49, WASM 63 -> 64 (pin and fixture versions follow).### Fixedentry.Why: beancount's behaviour, measured
Beancount's lexer has
[ \t\r]+ { }(whitespace) and\nas EOL, and its indent rule is^[ \t]+/[^ \t\r\n]. I ranbean-check3.2.3 in the compat container, and also calledbeancount.parser.parse_stringto see the parse errors and entries. Files use CRLF unless noted.main\r\r\non anopenline\r\r\non a;comment line\r\r\non a posting line\r\r\non a transaction header\r\r\non a metadata line (key: "v")" \r\n"\r\r\r\n," \r\r\n","\r \r\n"\r\r\non posting metadata\r\r\nin an otherwise-LF file\rat EOF (no\n),\r\rat EOF, a file that is just\r\r\r\nafter%,#!,#+\r\r\nafter a column-0#comment, an org*heading\r\r\nline of its own,\r\r\r\n\r\nat file start\rinside a string ("a\rb")a\rb\r-only line endings (classic Mac)unexpected DATE)\r\r\n(blank line) inside a transactionunexpected INDENT, same as\r\n)\r\n)\rinside a posting's indentation (\rAssets...,\r Assets...)unexpected ACCOUNT)\r(open\rAssets:Cash,Assets:Cash\rUSD,Cash\r; c)\rat column 0 before a directive (\r2024-01-01 open ...)\rinside a;comment with more text after itbean-checkexits 1 on a garbage line in the same setup, so its exit 0 above means something.Deliberately stricter than beancount
A
\rwith more of the line after it stays an error. Beancount reads it as a token separator. We don't, because the formatter folds a bare\rinto a line break: that is what letsrledger formatrepair classic-Mac (\r-only) files, and you cannot tell the two cases apart byte by byte. If we acceptedopen\rAssets:Cash,rledger checkwould pass a file thatformat_sourcethen splits into two broken lines. The AGENTS.md deviation checklist is covered: the rustdoc onstray_cr_trivia_endand onstray_cr_runnames the beancount behaviour and the reason, andtest_parse_cr_with_more_of_the_line_after_it_stays_an_errorpins the exact errors. A\rat column 0 before content is part of the same rule. Accepting it would also take CST indentation changes, because the parser reads any line-startWHITESPACEas an indent.Test evidence
crates/rustledger-parser/tests/stray_cr.rs(8 tests): one assertion per issue-table row, plus the extra shapes beancount accepts. Each asserts an empty error list and the exact parsed directives (accounts, narration, metadata keys on opens and postings). They also check the exactWhitespace/Newlinetokens and spans, and that a;comment's value has no\r. The shapes beancount rejects are pinned with exact errors, and so is the deliberate deviation. Every case also checks that the lossless token stream has no gaps or overlaps, thatparse_structured(..).text()equals the source, and that greenparseequalsparse_red_only(directives and errors).try_format_sourceon each stray variant gives the same output as on the plain CRLF file.crlf_hash_comment.rs: the;control now covers\r\r\nand\r\r\r\ntoo (onmainit could only cover\n/\r\n).origin/main: with the base lexer and formatter, 7 of the 8stray_crtests fail, and so does the extendedcrlf_hash_commenttest. The one that passes pins the deviation, whichmainalready errors on. With the new lexer but the old fold,crlf_to_lf_keeps_the_lexer_line_structureandformatting_preserves_the_parsed_directives(on the new fixture) fail.fuzz-corpusbranch, 42,083 UTF-8 inputs fromfuzz_parse,fuzz_green_eq_red,fuzz_parse_line), using a throwaway harness that is not committed:fuzz_targets/common/lossless.rschecks, and green and red agree on directives, errors, comments and options.\nand no"or\r, I made a variant with every\nreplaced by\r\r\n. All of them pass the same checks. Each one parses to the same directives (spans aside) and the same error kinds as the plain CRLF variant. Each one also gives the sameformat_sourceoutput, andtry_format_source == format_sourcewherever it parses clean.nix develop):cargo test -p rustledger-parser --all-features,cargo test -p rustledger-loaderandcargo test -p rustledger-wasm --lib cachegave 58test result: ok, 0FAILED, 1,111 tests passed.cargo test -p rustledger-lsp --all-features --libalso passed (323 tests; semantic tokens use the AST-pathtokenize). Also clean:cargo clippy -p rustledger-parser --all-features --all-targets -- -D warnings,cargo fmt --all --check,RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser --no-deps.Baseline / cache impact
STRICT_BASELINE=1corpus_baseline::parser_output_matches_baselineandcst_baseline::cst_output_matches_baselineboth pass on the local corpus (731 files). No corpus file contains a\rbyte at all, so no entry can move. CI's fresh fetch is the authoritative run. My local copy has 9 upstream-changed files and 15 missing ones, which are skipped with the usual info and warning lines.\rbefore a line ending used to parse with errors and now parses clean with all its directives. The WASM cache archivesparse_errors, so a v63 blob would keep serving the old errors. Loader v49 / WASM v64, following fix(parser): an unterminated quote hides every directive after it behind one error #2784 / fix(parser): end a column-0 # comment before the CRLF that follows it #2773.Interactions and not in this PR
%;{#!/{#+misclassified) is untouched. The new fixture has no%line because the classifier ignoresPercentCommentuntil test(format): the line-ending drift guard skips % comments; {#! and {#+ are misclassified #2780. The%case is covered bycrlf_to_lf_keeps_the_lexer_line_structureinstead.main: a column-0#comment or org heading with a\rmid-line (# a\rb) parses clean but is split byformat_source's bare-\rfold. This PR does not change that, and the rustdoc ofadvance_source_statenow says so.How to test
Closes #2774
🤖 Generated with Claude Code