Repository navigation
fix(format): keep unparsable text inside a directive in the error-tolerant formatter - #2801
Merged
Merged
Conversation
…erant formatter format_source (behind the FFI component's best-effort format.source / format.file) rebuilds each directive from its typed values. Text the parser could not read into one is part of no value, so it was deleted and the parse error went with it: `2024-01-01 open Assets:A junk` became `2024-01-01 open Assets:A`, and likewise for junk after a transaction header, a posting or a metadata value, a stray `"` or `*`, or a `!` after `pushtag`. format_source now takes the parser's own error list (one full parse instead of the bare tree parse) and copies every directive that overlaps an error span verbatim, as top-level ERROR_NODEs already are (#1335). The error list is used rather than a scan for ERROR_TOKENs: errors come from many rules, and a token scan misses e.g. `pushtag!`. Directives without errors are formatted exactly as before. A seeded property test mutates canonical snippets of every directive kind and checks that a broken file keeps its non-whitespace text in order, keeps its error lines, and formats idempotently. On main its first counterexample is `pushtagjunk #t\n` -> `pushtag #t\n`. Closes #2794 Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 29, 2026
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 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 |
…arse
A broken directive is copied verbatim through emit_error_node, which
trimmed trailing whitespace on every line of its text, including lines
inside a multi-line STRING, so the string's value changed ("SELECT\n 1 \n"
lost its spaces, and a \r\n inside a CRLF file's string lost its \r). The
trim now walks tokens and never reaches into a string.
canonicalize_directives has already parsed the emitter's text and checked
it is error-free, so it formats that tree instead of calling
format_source_grouped, which parsed it again only to find no errors.
Also records that indented directives in a broken file are now copied
verbatim and keep their error (#2795), with a test, and narrows the
CHANGELOG's LSP claim to whole-document formatting (range formatting is
#2803).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…or node The token-walk trim in emit_error_node strips a whitespace-only line at the edge of an error node before its leading and trailing blank lines are counted, so the line is no longer emitted both as a gap and as an empty line of the node. Closes #2796 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The token-walk trim called trim_end on the whole output buffer, so on a blank line it also ate the newline ending the line before, and every blank line inside an error node or a verbatim-copied directive was deleted. The trim now stops at the start of the current line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
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
format_source(the error-tolerant formatter behind the FFI component's best-effortformat.source/format.file, rustfava's default) no longer deletes unparsable text inside a directive. A directive that holds a parse error is copied verbatim, the same way a top-levelERROR_NODEalready is (#1335).2024-01-01 open Assets:A junk\n2024-01-02 open Assets:B\n2024-01-01 open Assets:A\n2024-01-02 open Assets:B\n(errors 1 -> 0)2024-01-01 open Assets:A* h\n2024-01-01 open Assets:A\n2024-01-01 open Assets:A"2024-01-01 open Assets:A\n2024-01-01 open Assets:A"\nWhy
emit_directiverebuilds a directive from its typed values. Text the parser could not read into one is part of no value, so it was dropped, and the parse error disappeared with it. That breaks the #1335 rule that format never deletes the author's text.Approach and trade-off
format_source_groupednow runs the full parse (parse_without_occurrences) instead of the bare tree parse, so it has the parser's own error list. The error spans are merged into sorted ranges (ErrorRanges), and the top-level walk copies any directive whose range overlaps one verbatim, through the existingERROR_NODEpath (same blank-line and indentation handling).ERROR_TOKENs: I tried the token scan first, and the property test below broke it at once.pushtag! #tis a parse error with noERROR_TOKEN(the!is a flag token), and the rebuild dropped the!. Errors come from many rules (error tokens, header defects, catch-all body lines, shape checks), and a second classifier in the formatter would drift from them (Canonical-Function Discipline).*inAssets:A* h, the!above). Copying verbatim is the only option that keeps every byte for sure. The cost is that the rest of a broken directive is not normalized: a broken transaction keeps its own spacing until the error is fixed. The directives around it are still formatted (pinned bytest_format_source_formats_the_directives_around_a_broken_one).format_sourcenow pays for the conversion pass. On a 913 KB corpus file (fava_investor_examples_huge-example.beancount), a release-build time per call went from 17.0 ms to 25.6 ms. The hot clean-file paths do not go throughformat_source:rledger format(try_format_source), LSP formatting and FFIformat.sourceon a clean file all useformat_source_with_parsed, which is unchanged.canonicalize_directives(used byrledger add/extract, BQLPRINTand FFIformat.entry/format.entries/format.loaded) does not pay it either: it already holds an error-free parse, so it formats that tree directly instead of parsing again.format_node/format_node_groupedtake only a tree, which does not carry its errors, so they still rebuild every directive. Their rustdoc now says so and points broken input atformat_source. Their callers only pass clean trees.Tests
crates/rustledger-parser/tests/format_keeps_error_lines.rs(reuseserror_lines/assert_unchanged): the three issue cases with exact output, junk after a transaction header, after a posting, after transaction, posting andopenmetadata values, mid-line error tokens (open,price, posting,pushtag!), and a broken transaction between formatted ones.Property test
test_format_source_keeps_every_byte_of_a_broken_file: proptest with a fixed seed (RngSeed::Fixed(2794)), 512 cases, no failure file, runs in about 0.1 s. It joins canonical snippets of every directive kind (transactions with tags, links, metadata, cost and price included) and inserts junk (junk,",*,* h,!,@,{,},~,#,^,$, ...) at random offsets. For inputs with parse errors it asserts:Only inputs where every insertion lands on a line with a parse error are checked. The parser silently accepts some stray characters inside an otherwise valid directive (see "Found, not fixed" below). The formatter drops those with no error reported, which is a parser leniency and not this bug.
Fails on main. The first counterexample:
"pushtagjunk #t\n"->"pushtag #t\n". The new example tests also fail on main, e.g."2024-01-01 * \"p\" junk\n Assets:A 1 USD\n Assets:B\n"->"2024-01-01 * \"p\"\n Assets:A 1 USD\n Assets:B\n"with the error lines going from 2 to 0.An exhaustive single-insertion sweep over the same snippets and junk (18,678 inputs with the insertion on an error line): 8,056 failures on main, 0 with this fix.
FFI:
convert::format_source_tests::test_format_source_keeps_unparsable_text_in_a_directivepins this at theformat.sourceentry point.Clean-file output unchanged
format_sourceover 1,068.beancountfiles (the 731-file compatibility corpus and the in-tree fixtures), main vs this branch: all 992 files without parse errors give byte-identical output. 45 of the 75 broken files changed.)posting amount,open Assets:Bank:Current*,open Expenses:Groceries!).cst::format::tests(including the idempotence matrix),format_compat,pipeline_invariants, and the LSPformattests, which includelsp_matches_format_source.Baselines
corpus_baselineandcst_baselinepass unchanged. They fingerprint parser output and the CST, and this PR does not touch the parser. The formatter has no corpus baseline (retired in #1284, pertests/baselines/README.md). The CI corpus format gates runrledger format, which refuses files with parse errors, so they cannot see this change.Found, not fixed (follow-ups)
2024-01-01 open Assets:A U*SDformats toopen Assets:A U,SD, andopen! Assets:A,close! Assets:A,open Assets:A USD @andprice HOOL ? 10 USDall lose a character. Because the file parses clean,rledger formatis affected too. Beancount rejects these.textDocument/rangeFormatting's parse-error fallback (format_node_range) refuses only when the range covers anERROR_NODE, so a selected directive that holds an error token is rebuilt and loses that token, the same as this bug.How to test
An indented directive is reported as an error, so it is copied verbatim too and keeps that error instead of being dedented and silently repaired. That settles #2795 in favor of copying it unchanged;
test_format_source_keeps_an_indented_directive_an_errorpins it.Trailing whitespace in a copied directive is trimmed only outside strings, so a multi-line string keeps its value (including a
\r\ninside a string in a CRLF file).canonicalize_directivesformats the tree it has already parsed instead of parsing the emitter text a second time. The same token-walk trim also stops a whitespace-only line beside an error node from coming out as two blank lines (#2796).Closes #2794
Closes #2795
Closes #2796
🤖 Generated with Claude Code