Skip to content

feat(parser): #1262 phase 4.1 — opinionated CST-backed formatter - #1284

Merged
robcohen merged 11 commits into
mainfrom
feat/cst-phase-4-1-opinionated-formatter
Jun 9, 2026
Merged

robcohen merged 11 commits into
mainfrom
feat/cst-phase-4-1-opinionated-formatter

Conversation

@robcohen

@robcohen robcohen commented Jun 8, 2026

Copy link
Copy Markdown
Member

Summary

Phase 4.1 of the CST migration tracked in #1262 — the formatter rewrite that completes the parser→AST→formatter rebuild and fixes the original destructive-formatting bug in #1252.

The new formatter is a pure fn format_source(&str) -> String: it reparses the source into a CST and emits text in one canonical form per AST shape. Equivalent ASTs produce byte-identical output; idempotence (f(f(x)) == f(x)) follows trivially. No FormatConfig, no knobs — one canonical form for the whole codebase.

This replaces the legacy format_source(source, &ParseResult, &FormatConfig) orchestrator that reordered, re-emitted, and (per #1252) destructively rewrote parts of the source. The legacy 538-line module is deleted; every caller (CLI, LSP, FFI, WASM) is moved to the new entry point.

Canonical form (locked in #1262's PR-4 decision comment)

Item Form
Indent inside a directive body 2 spaces; tabs converted
Blank lines between directives exactly 1
Blank lines inside a directive 0
Number lexical form strip thousands separators; preserve user's decimal-place count
Comment content preserved verbatim
Comment positions normalized per attachment slot (file-leading, inter-directive, header-trailing, posting-trailing)
Cost spec spacing {cost CCY} (no inner padding)
Tag/link order on transaction header source order, after the strings
Posting alignment bean-format-style: numbers right-justified in a file-wide field; currency column uniform
Trailing newline at EOF always exactly one
Line endings LF only (CRLF inputs normalized)
Leading BOM dropped

bean-format byte-identity is an explicit non-goal — rledger format declares its own canonical form. Users can pin one tool or the other.

Coverage

  • 42 unit tests in cst::format::tests cover all 19 directive kinds (Open, Close, Commodity, Note, Event, Query, Pad, Document, Price, Balance, Custom, Option, Include, Plugin, Pushtag, Poptag, Pushmeta, Popmeta, Transaction) plus alignment, postings with cost specs and price annotations, posting metadata, arithmetic amounts, and idempotence.
  • Workspace-wide test suite passes (parser, LSP, FFI, WASM, CLI).
  • cargo clippy --workspace --all-targets -- -D warnings clean.
  • RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps clean.

Commits

  1. phase 4.1a — opinionated CST-backed formatter — adds crate::cst::format with format_source and format_node. Legacy entry stays in place for the next commit's caller sweep.
  2. phase 4.1b — switch source-level formatter to the CST path — moves every caller to the new signature, deletes the legacy crates/rustledger-parser/src/format.rs (538 lines), the dead crates/rustledger/src/format.rs re-export module, and the two test suites that pinned the OLD canonical form (corpus_baseline_format.rs, format_compat.rs). +397/-1523 net.

Out of scope

  • Typed-directive synthesis (rustledger_core::format::format_directives) stays in rustledger-core for callers that build a directive from scratch (rledger add, importer extract, FFI format.entry endpoint). That's a different shape of input.
  • Bean-format compat fixtures — to be reviewed and either rebaselined for the new canonical form or deleted in a follow-up PR.
  • The posting.span workaround from fix(lsp): use posting.span in formatters, preserving metadata (closes #1142) #1156 can now be retired in a follow-up — the CST has the spans natively.

Test plan

  • cargo test --workspace --no-fail-fast — all green
  • cargo clippy --workspace --all-targets -- -D warnings — clean
  • RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps — clean
  • rledger format end-to-end on a fixture
  • LSP textDocument/formatting and textDocument/rangeFormatting regression suites
  • FFI format.source / format.file / format.entry routes (typed-directive routes unchanged)
  • WASM format() and ParsedLedger::format()
  • Doctor rledger doctor roundtrip — BOM-prefixed files now correctly reflow (canonical form drops the BOM)

🤖 Generated with Claude Code

robcohen and others added 2 commits June 8, 2026 11:40
Adds cst::format::format_source_v2 (and format_node) — a pure
&str → String formatter that reparses internally and emits one
canonical form per AST shape. Equivalent ASTs produce byte-identical
output; idempotence (f(f(x)) == f(x)) follows trivially.

This is the gofmt-style replacement for the legacy format_source
that took (source, ParseResult, FormatConfig) and re-emitted via
the AST-driven rustledger_core::format path. The legacy entry
stays in place this commit; the next commit sweeps callers and
deletes the old code paths.

Coverage: 42 unit tests cover all 19 directive kinds (Open, Close,
Commodity, Note, Event, Query, Pad, Document, Price, Balance,
Custom, Option, Include, Plugin, Pushtag, Poptag, Pushmeta,
Popmeta, Transaction) plus alignment, postings with cost specs
and price annotations, posting metadata, arithmetic amounts, and
idempotence.

Canonical-form decisions (per the PR-4 decision comment on #1262):
- Indent inside a directive body: 2 spaces.
- Blank lines between directives: exactly 1.
- Number lexical form: thousands separators dropped, decimal
  count preserved.
- Cost spec spacing: {cost CCY} (no inner padding).
- Trailing newline at EOF: always exactly one.
- Line endings: LF; CRLF inputs normalized.
- Leading BOM: dropped.
- Tag/link order on transaction header: source order, after the
  strings.

No FormatConfig parameter — one canonical form, no knobs.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sweep every caller of the source-level format pipeline to the
opinionated CST-backed entry point and delete the legacy
implementation that fed it.

Caller changes — all collapse from
  format_source(source, &parse_result, &FormatConfig::default())
down to
  format_source(source)

- crates/rustledger/src/cmd/format.rs: rledger format. Drops
  bean-format-style alignment flags (-c, -w, -W, --indent) — no
  longer meaningful under the one-canonical-form policy.
- crates/rustledger/src/cmd/doctor/roundtrip.rs: rledger doctor.
  BOM roundtrip test now asserts reflow (canonical form drops the
  leading BOM, per the decision in #1262).
- crates/rustledger-lsp/src/handlers/formatting.rs and
  range_formatting.rs: textDocument/formatting,
  textDocument/rangeFormatting. The shared format_document path
  also loses its FormatConfig argument; handlers/utils.rs drops
  document_format_config along with it.
- crates/rustledger-lsp/src/handlers/execute_command.rs:
  rledger.alignAmounts workspace command.
- crates/rustledger-ffi-wasi/src/jsonrpc/router.rs: format.source
  and format.file JSON-RPC entries.
- crates/rustledger-wasm/src/api.rs and parsed_ledger.rs: WASM
  format() / ParsedLedger::format().

Deletions
- crates/rustledger-parser/src/format.rs: the legacy 538-line
  (source, ParseResult, FormatConfig) -> String orchestrator.
- crates/rustledger/src/format.rs: thin re-export module — no
  external consumer remained.
- crates/rustledger-parser/tests/corpus_baseline_format.rs: 75
  fixtures pinned the OLD canonical form against the corpus.
  Replaced in spirit by the in-module cst::format tests (42 unit
  cases pinning the NEW canonical form).
- crates/rustledger/tests/format_compat.rs: cross-path check
  between format_source and format_directives. The bean-format
  compat half is now an explicit non-goal; the directive-list
  half is still tested in parser_integration_test.rs.

Formatter alignment was upgraded to bean-format-style two-axis
right-justification so the currency column is uniform file-wide
even when individual numbers differ in width or sign. Comment
preservation was added for file-level, inter-directive (leading
trivia of the next directive), same-line trailing (header line),
and posting-trailing slots.

CRLF range-formatting note: the previous LSP test pinned partial-
line CRLF range edits, but the canonical form rewrites every CRLF
to LF, which makes per-line edits multi-line by construction
(and the inside-selection filter drops them). The test now uses
a whole-document selection, the supported recipe; users wanting
per-line edits on a CRLF file should normalize via
textDocument/formatting first.

Closes the source-level half of the formatter rewrite tracked in
#1262. Typed-directive synthesis (rustledger_core::format::
format_directives) is intentionally retained for callers that
build a directive from scratch (rledger add, importer extract,
FFI format.entry endpoint) — a different shape of input and out
of scope here.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner June 8, 2026 10:19
Copilot AI review requested due to automatic review settings June 8, 2026 10:19
@codecov

codecov Bot commented Jun 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 41.91176% with 79 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/format.rs 4.16% 69 Missing ⚠️
crates/rustledger/src/cmd/add_cmd/mod.rs 0.00% 6 Missing ⚠️
...tes/rustledger-lsp/src/handlers/execute_command.rs 81.81% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR completes phase 4.1 of the CST migration (#1262) by replacing the legacy AST-driven, configurable whole-file formatter with an opinionated CST-backed formatter (rustledger_parser::format_source(&str) -> String) and switching all entry points (CLI/LSP/FFI/WASM/doctor) to the new API.

Changes:

  • Added a CST-backed canonical formatter (crates/rustledger-parser/src/cst/format.rs) and exposed format_source / format_node from rustledger-parser.
  • Updated CLI/LSP/FFI/WASM/doctor callers to use the new formatter signature; removed legacy FormatConfig/alignment/indent knobs from the CLI config surface.
  • Deleted the legacy formatter implementation and older compatibility/baseline test suites tied to the previous canonical form.

Reviewed changes

Copilot reviewed 19 out of 19 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
crates/rustledger-parser/src/cst/format.rs New canonical CST-backed formatter implementation + unit tests.
crates/rustledger-parser/src/cst/mod.rs Exposes the new formatter module/functions.
crates/rustledger-parser/src/lib.rs Re-exports format_source/format_node from the CST module; removes legacy format module.
crates/rustledger-parser/src/format.rs Removes the legacy whole-source formatter.
crates/rustledger-parser/tests/corpus_baseline_format.rs Removes old formatter baseline gate tied to legacy canonical output.
crates/rustledger/src/cmd/format.rs CLI now routes formatting through rustledger_parser::format_source(&str).
crates/rustledger/src/cmd/doctor/roundtrip.rs Doctor roundtrip now uses the new formatter; BOM expectation updated.
crates/rustledger/src/config.rs Removes commands.format.indent config; updates config tests accordingly.
crates/rustledger/src/bin/rledger.rs Removes application of format-indent default from config.
crates/rustledger/src/lib.rs Removes pub mod format.
crates/rustledger/src/format.rs Deletes the rustledger_core::format re-export module.
crates/rustledger-lsp/src/handlers/utils.rs Removes FormatConfig plumbing helper.
crates/rustledger-lsp/src/handlers/formatting.rs LSP document formatting now uses canonical format_source(&str).
crates/rustledger-lsp/src/handlers/range_formatting.rs Range formatting updated to the new formatting pipeline; CRLF-selection test adjusted.
crates/rustledger-lsp/src/handlers/execute_command.rs Align-amounts command now uses canonical format_source(&str).
crates/rustledger-wasm/src/api.rs WASM format() now uses canonical format_source(&str).
crates/rustledger-wasm/src/parsed_ledger.rs WASM ParsedLedger::format() now uses canonical format_source(&str).
crates/rustledger-ffi-wasi/src/jsonrpc/router.rs FFI format route now uses canonical format_source(&str).
crates/rustledger/tests/format_compat.rs Removes legacy bean-format compatibility tests tied to old canonical output.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/rustledger/src/cmd/format.rs Resolved
@github-actions

github-actions Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 38.6ms ± 0.7ms 25.5 MB
beancount 804.6ms ± 6.8ms 50.6 MB
Comparison 20.8x faster 2.0x less

vs main branch (2026-06-08)

Metric main this PR Change
Time 35.4ms 38.6ms +9.0% 🟡
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

A high-effort code review surfaced ten correctness, invariant, and
UX bugs across the formatter and its callers. This commit fixes
every one. All changes ship with regression tests where the bug
shape is a function input/output pair.

## Formatter correctness (crates/rustledger-parser/src/cst/format.rs)

1. emit_custom: the post-seen_type match arm skipped every DATE
   token, silently dropping legitimate date-typed value arguments
   from custom directives. Removed the DATE skip — the leading
   directive date is already handled by the seen_type=false phase.

2. format_cost_spec: only branched on cs.is_total() (L_DOUBLE_BRACE)
   and emitted single-brace for the L_BRACE_HASH opener too,
   silently rewriting per-unit-plus-total to plain per-unit cost.
   Now uses cs.is_per_unit_plus_total() to emit the {# opener and
   adds a single space before the first inner token.

3. format_cost_spec: the catch-all arm inserted a space before
   every non-trivia token including COMMA. Now keeps the comma
   tight to the preceding token.

4. emit_meta_entries_of: passed META_ENTRY source text through
   verbatim (only trim_start), so two equivalent ASTs produced
   different output bytes, violating the gofmt-style invariant
   declared in the file rustdoc. Replaced with a tokenized
   canonical emit that walks non-trivia tokens with single-space
   separation and runs NUMBER values through canonical_number.
   The posting-metadata and transaction-metadata call sites
   route through the same helper.

6. format_node: the top-level walk inserted a blank-line separator
   before every emitted item including comments, breaking
   section-header blocks. Now tracks whether the previous emitted
   item was a directive and only inserts the blank when
   transitioning into another directive.

## Caller / CI / UX fixes

5. .github/workflows/parser-baselines.yml and
   scripts/regen-corpus-baselines.sh referenced the deleted
   corpus_baseline_format test target; CI would have failed on
   this branch. Removed the dead references along with the
   orphan tests/baselines/format-corpus.manifest and the matching
   README sections. The opinionated formatter has its own
   canonical-form unit tests in cst::format::tests instead.

7. rledger format --check used trim() == trim() which masks
   leading/trailing blank-line differences that the canonical
   form rewrites in --in-place mode. Now uses byte equality.

8. LSP textDocument/rangeFormatting: format_source always emits
   LF, so on a CRLF file every diff edit spanned at least two
   lines and got filtered out by the inside-range guard. Per-line
   range formatting silently returned None. format_document now
   detects CRLF in the input and re-injects CR before every
   emitted LF so the diff only fires on actual canonical-form
   changes. The per-line CRLF range-format test is restored.

9. rledger.alignAmounts: applied canonical-form edits (blank-line
   collapse, BOM strip, comment normalization) under a command
   label that promised align amounts. Now filters edits via a
   heuristic (edit_touches_posting_line: indented line beginning
   with an optional flag and then a capital-letter account name)
   and falls back to the No amounts to align message when no
   alignment-changing edit survives.

10. FFI format.entry / format.entries (and CLI rledger add,
    rledger extract): kept calling the legacy
    core::format::format_directives directly while format.source /
    rledger format / WASM format used the new opinionated CST
    pipeline. Two endpoints in the same toolchain rendered the
    same logical directive with different canonical forms. Now
    canonical_format_directives composes the two: synthesize via
    the typed-directive emitter, then run the result through
    rustledger_parser::format_source for the canonical pass. The
    same two-pass pattern wires into add_cmd and extract_cmd.

## Coverage

Six new regression tests in cst::format::tests pin findings 1-4
and 6. The crlf range-formatting fix restores the per-line CRLF
test that was rewritten as a workaround in the previous commit.
Workspace tests: 74 test crates, zero failures. Clippy clean with
-D warnings. cargo doc clean with RUSTDOCFLAGS=-Dwarnings.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@github-actions

github-actions Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 99%
Total Files 792
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 8 commits June 8, 2026 17:16
Round-2 deep review surfaced ten correctness and architecture
issues introduced by (or remaining after) the first fix commit.
This commit addresses every one. Seven new regression tests pin
the formatter bugs by their exact failure shape.

Findings 1-3: formatter correctness in cst/format.rs
1. Bare-CR line endings dropped directives because the lexer
   doesn't treat bare \r as a terminator; classic-Mac files
   lost every directive after the first. Added a
   normalize_line_endings pre-parse pass folding CRLF and bare
   CR to LF.
2. emit_meta_entry inserted space after unary +/-
   (key: -5.00 USD -> key: - 5.00 USD). Rewired through
   write_expression_tokens so the spacing rule is shared with
   postings, balance, price, and cost specs.
3. format_cost_spec had the same unary bug AND missed COMMA
   tightness for non-trivial token sequences. Collected the
   inner tokens and routed through the same helper; extended
   write_expression_tokens to keep COMMA tight against the
   preceding token.

Findings 4-6: LSP / FFI correctness
4. LSP CRLF preservation rewrote LFs inside multi-line string
   literals. The lexer admits raw LF in a quoted string per the
   STRING regex; the blanket str::replace mutated user data.
   Replaced with lf_to_crlf_outside_strings, a quote-aware
   state machine that only rewrites LFs outside string literals.
5. alignAmounts heuristic accepted only ASCII flag chars
   {!,*,#} and is_ascii_uppercase. Expanded the flag set to the
   full lexer envelope {!,*,#,?,&,P,S,T,C,U,R,M} and switched
   to char::is_uppercase so non-Latin account names (Активы,
   Καθαρό) are recognized.
6. canonical_format_directives swallowed parse errors silently
   when the legacy synthesize step produced text the new parser
   couldn't fully accept. Added an explicit parse-error guard:
   re-parse the legacy output first, bail with a descriptive
   error if parsing fails. Same guard applied in
   rledger add (canonical_format_directive helper) and
   rledger extract.

Findings 7-8: CLI UX
7. CLI --check on a CRLF file correctly fails (LF-only canonical
   form) but the diff output was confusing — no per-line hunks
   under the diff header. emit_diff now detects the CRLF-only
   case and surfaces an explicit normalization message.
8. --diff emitted empty hunks on trailing-newline-only deltas.
   emit_diff now detects this case and prints a clear
   'leading/trailing whitespace only' message.

Finding 9: architecture
9. Documented the two-emitter coupling between core::format
   (parser-clean intermediate) and cst::format (final canonical
   output) in the latter's module rustdoc, with a Known coupling
   section listing every call site and noting the eventual fix
   (a typed-directive emit path on cst::format that bypasses the
   source round-trip).

Coverage: seven new regression tests in cst::format::tests pin
findings 1-3. Workspace tests: zero failures across all crates.
Clippy clean with -D warnings. cargo doc clean with
RUSTDOCFLAGS=-Dwarnings.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
A third high-effort code review surfaced 10 bugs and architecture
issues. This commit addresses every one. Four new regression tests
pin the specific failure shapes; a 26-fixture idempotence matrix
and a 26-fixture canonicalize_directives round-trip property test
cover the broader gofmt invariants the prior reviews said were
missing.

Findings 1-2 (LSP CRLF handling):

1. lf_to_crlf_outside_strings's flat in-string-only state machine
   flipped on the first quote inside a `;` comment, leaving every
   subsequent newline as LF on a Windows file. Extended to a
   tri-state SourceState (Code / InString / InComment) that
   respects the lexer's STRING regex AND its comment-to-EOL rule.

2. Same root cause as 1: normalize_line_endings folded CRLF to LF
   uniformly, including inside string literals. A Windows-authored
   multi-line `"line1...line2"` lost the CR inside the string on
   the round-trip. Now uses the same SourceState walker so the
   user's bytes inside a string are preserved.

Findings 3-4 (LSP alignAmounts heuristic):

3. char::is_uppercase only matches Lu; CJK, Hebrew, Arabic,
   Devanagari accounts (all Lo) parse as ACCOUNT tokens but the
   heuristic still rejected them. Replaced is_uppercase with
   `!first.is_lowercase()` which correctly admits both uppercase
   letters AND case-less letters.

4. The hardcoded posting-flag char set missed the 19 single-char
   Latin uppercase letters that Beancount accepts as currency-as-
   flag. Removed the hardcoded set entirely — the new
   discriminator is the single rule "indented line whose first
   non-whitespace char is not `;`, `%`, or lowercase letter",
   which covers postings with flags of every shape AND non-Latin
   account names by construction.

Findings 5-6 (CLI emit_diff messaging):

5. The trailing-whitespace message said "extra trailing newlines"
   regardless of direction. Now compares trailing_newline_count on
   both sides and emits one of three correctly-directional
   messages: "missing final newline", "extra trailing newlines",
   or "leading/trailing whitespace .lines() strips".

6. The CRLF-only short-circuit only matched files with exactly
   CRLF terminators; mixed-CR files (CRLF + bare CR) fell through
   and showed the wrong message. Now strips both CRLF and bare CR
   before checking equality, and emits a unified "line endings"
   message.

Finding 7 (helper duplication):

7. The synth-then-canonicalize pipeline was reimplemented in THREE
   places (router.rs, add_cmd, extract_cmd). Added the single
   source of truth as rustledger_parser::canonicalize_directives,
   exported alongside format_source. The three call sites now
   reduce to a single call each. extract_cmd's bespoke
   format_directive_lines + render_lines loop collapses to
   canonicalize_directives because the canonical pass adds
   inter-directive blanks anyway.

Finding 8 (lf_to_crlf_outside_strings location):

8. The helper was LSP-private even though its correctness depends
   on the lexer's STRING and comment rules. Moved to
   rustledger_parser::cst::format alongside format_source, where a
   future lexer change to either rule forces co-evaluation. The
   LSP imports it via rustledger_parser::lf_to_crlf_outside_strings.

Finding 9 (helper name):

9. Renamed write_expression_tokens to write_canonical_token_sequence
   to reflect its current role as the SINGLE dispatcher for ALL
   canonical-spacing emit paths (balance/price arithmetic, AMOUNT
   subnodes, cost-spec interiors, metadata values). The rustdoc
   now explicitly warns that adding a new SyntaxKind to the
   formatter implies thinking about its effect on every call site.

Finding 10 (test coverage):

10. Added IDEMPOTENCE_MATRIX (26 hand-curated fixtures covering
    every directive kind plus the high-risk edge cases from the
    prior reviews) and two property tests over it:

    - idempotence_matrix asserts the gofmt invariant
      format_source(format_source(x)) == format_source(x) on every
      fixture.
    - canonicalize_directives_roundtrips_every_synthesized_directive
      asserts the typed-directive shim's round-trip stability:
      Directive -> canonicalize_directives -> parse -> same
      directive count, zero parse errors.

Coverage: 60 formatter unit tests pass (incl. 4 new explicit
regressions for the CRLF/comment fixes + the 26-fixture matrix
running through 2 property tests). Workspace tests pass with zero
failures. Clippy clean with -D warnings. cargo doc clean with
RUSTDOCFLAGS=-Dwarnings.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
A fourth high-effort code review surfaced 10 bugs and architecture
issues. This commit addresses every one. Four new explicit
regression tests pin the round-4 failure shapes, eleven new
fixtures extend the IDEMPOTENCE_MATRIX to cover the directive
variants the previous matrix missed, and a coverage assertion
prevents future silent-skip regressions.

Findings 1+2 (CLI --diff messaging):

1. The "extra trailing newlines" branch in emit_diff's match was
   dead code: when orig has more trailing newlines than formatted,
   orig.lines() and fmt.lines() counts differ, so the per-line
   "removed" loop fires hunks and sets printed_hunk=true. The
   match never ran. Hoisted the trailing-newline detection BEFORE
   the per-line loop using trim_end_matches comparison so all
   three directional messages now fire correctly.

2. The CRLF fast path used a flat str::replace that stripped every
   CR including those preserved inside string literals. Files with
   CR-in-string + outside-string CRLF fell through and showed the
   wrong message. emit_diff now uses the new public
   crlf_to_lf_outside_strings helper, which mirrors the
   formatter's string-aware normalization.

Finding 3 (SHEBANG/EMACS state machine):

3. SourceState's Code-state opener detection covered ; and % but
   not #!... (SHEBANG) or #+... (EMACS_DIRECTIVE) at line start.
   An unbalanced quote inside such a line trapped the walker in
   InString forever, the same failure class the round-3 fix
   solved for ; / %. Added at_line_start tracking and #! / #+
   opener recognition to advance_source_state, the new shared
   helper.

Findings 4+6 (canonicalize_directives correctness):

4. The function guarded on parse errors but not on directive count
   drift. A future Directive variant whose legacy text the CST
   parser silently swallows as comments / error-recovery trivia
   would round-trip to truncated output with no error. Added a
   CountMismatch check: collect the input iterator, compare
   against reparsed.directives.len().

6. CanonicalizeError lacked non_exhaustive, so adding the new
   CountMismatch variant would have been a SemVer-breaking
   change. Added the attribute; downstream match statements must
   now use a wildcard arm and additive variants are non-breaking
   forever after.

Finding 5 (matrix coverage):

5. IDEMPOTENCE_MATRIX skewed toward Transaction edge cases and
   missed 11 directive variants. Added one fixture per missing
   variant: Close, Commodity, Note, Event, Query, Pad, Document,
   Pushtag, Poptag, Pushmeta, Popmeta. The
   canonicalize_directives_roundtrips_every_synthesized_directive
   test now exercises every Directive variant the formatter emits.

Finding 7 (canonicalize_directives double-parse):

7. The hot path parsed the synthesized intermediate twice: once
   for the error guard, once inside format_source. Both are the
   same parser. Documented the architectural decision (the
   ParseResult-doesn't-expose-CST cross-crate API gap) and kept
   the structure clear; the perf-saving fold requires a
   ParseResult API change which is out of scope. Left a code
   comment naming the optimization opportunity.

Finding 8 (property test silent skip):

8. The round-trip property test silently skipped any fixture with
   parse errors or zero directives, masking parser regressions
   that drop directives. Added an exercised counter and a final
   assert that exercised >= ROUNDTRIP_MIN_COVERAGE (25 today,
   raised when fixtures are added). A parser regression that
   drops directives from previously-clean fixtures now fails the
   test instead of silently passing.

Finding 9 (API organization):

9. Added a pub mod format sub-module re-export in
   crates/rustledger-parser/src/lib.rs that groups the formatter
   surface (format_source, format_node, canonicalize_directives,
   CanonicalizeError, lf_to_crlf_outside_strings,
   crlf_to_lf_outside_strings). Consumers can now write
   use rustledger_parser::format::*. The flat crate-root
   re-exports stay for backwards compatibility; new code should
   prefer the namespace.

Finding 10 (state machine duplication):

10. The SourceState transition logic was duplicated inline in
    normalize_line_endings and lf_to_crlf_outside_strings.
    Factored out advance_source_state, called by both walkers.
    Future lexer rule changes (raw strings, new comment lexemes,
    escape semantics) now have a single update point. Renamed
    the private helper to the public crlf_to_lf_outside_strings
    to mirror its dual.

Coverage: 64 formatter unit tests pass (4 new explicit
regressions for SHEBANG / EMACS / mid-line hash / CountMismatch +
the 37-fixture matrix running through 2 property tests with a
coverage-floor assertion). Workspace tests pass with zero
failures. Clippy clean with -D warnings. cargo doc clean with
RUSTDOCFLAGS=-Dwarnings.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
A fifth high-effort code review surfaced 10 bugs and architecture
issues. This commit addresses every one. Three new explicit
regression tests, two new structural tests, a renamed coverage
floor, and a parser-vs-state-machine property test together close
the silent-skip and silent-divergence classes.

Findings 1-3 (line-ending walkers):

1. crlf_to_lf_outside_strings (public, also used by format_source
   on every pre-parse pass) misclassified the SHEBANG/EMACS line
   on BOM-bearing files. The BOM consumed the at_line_start=true
   credit, so #+title at byte 1 was treated as Code and a stray
   quote later trapped the walker in InString. Fixed by stripping
   the leading BOM before the walk and re-prepending it verbatim
   on output. Same fix mirrored in lf_to_crlf_outside_strings.

2. emit_diff produced a silent diff (only --- / +++ headers, no
   message, no hunks) when input had BOTH CRLF line endings AND a
   missing trailing newline. The round-4 rewrite split the
   line-ending check and the trailing-newline check into
   mutually-exclusive early returns. Combined the checks into a
   single pass.

3. emit_diff fast path missed BOM-bearing CRLF files because
   crlf_to_lf_outside_strings preserved the BOM while format_source
   stripped it. Fixed as part of the merged check above: strip the
   BOM from the original before comparison.

Findings 4-6 (canonicalize_directives correctness + UX):

4. DirectiveCountMismatch Display message exposed implementation
   vocabulary (legacy emitter, new parser) to FFI consumers.
   Rewrote to a user-facing message naming rledger as the bug
   owner instead.

5. ROUNDTRIP_MIN_COVERAGE was a magic constant 25. Replaced with
   a derived floor: matrix length minus known-zero-directive
   fixture count.

6. Added canonicalize_directives_positive_count_check to cover
   the success arm of the count guard. The Display test already
   covers the error arm.

Finding 7 (lf_to_crlf perf):

7. The round-4 refactor was allocating a Vec of chars eagerly.
   Rewrote both helpers as streaming Peekable Chars walkers.

Finding 8 (dual API surface):

8. Removed the flat crate-root re-exports of the formatter
   symbols. Sole import path is now rustledger_parser::format::{}.
   Migrated every consumer.

Finding 9 (compile-time fixture coverage):

9. Added _directive_variant_fixture_coverage with an exhaustive
   match over Directive variants. The function never runs but
   must compile, so adding a new variant breaks the build unless
   the author also adds a fixture.

Finding 10 (lexer / state-machine divergence):

10. Added source_state_classification_agrees_with_lexer that
    walks every fixture through the lexer and through
    advance_source_state and asserts byte-by-byte agreement on
    the string/comment classification.

Coverage: 67 formatter unit tests pass. Workspace tests pass with
zero failures. Clippy clean with -D warnings. cargo doc clean
with RUSTDOCFLAGS=-Dwarnings.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
A sixth high-effort code review surfaced 10 bugs and architecture
issues. This commit addresses every one. The state machine now
matches the lexer mid-line, the test suite verifies semantic
fixture coverage (not just name resolution), and the formatter
API has a single sealed import path.

Findings 1-2 (concrete correctness):

1. ROUNDTRIP_KNOWN_ZERO_DIRECTIVE_FIXTURES was 8 but runtime probe
   showed only 7 fixtures legitimately skip the round-trip body.
   The over-count gave the silent-skip guard 1 fixture of slack
   (expected 29 vs the achievable 30). Reduced to 7 today; bumped
   back to 8 after adding the new EMACS-directive fixture which
   produces a parse error and is also legitimately skipped.

2. emit_diff reported the CR-folded cause on every file containing
   a CR, even when crlf_to_lf_outside_strings deliberately
   preserved the CR (e.g. CR inside a string literal). Now derives
   the cause from whether the helper actually returned an Owned
   Cow with bytes different from the input.

Finding 3 (sealed cst path):

3. Round-5 advertised rustledger_parser::format as the sole
   formatter import path but the cst module still re-exported the
   same symbols. Three paths resolved (format::*, cst::*,
   cst::format::*). Demoted pub mod format to pub(crate) inside
   cst and removed the cst-level re-exports. Sole path is now
   rustledger_parser::format::*.

Findings 4 and 8 (double-parse, eager collect):

4. canonicalize_directives still double-parses the synthesized
   intermediate. Closing the gap requires either a try_format_source
   variant or a ParseResult::syntax_node accessor — both are
   cross-crate API changes out of scope here. Kept as a known
   limitation with a code comment explaining the architectural fix.

8. canonicalize_directives still collects the input iterator to
   get the count. Tightening the signature to ExactSizeIterator
   would affect every consumer; deferred as a perf follow-up.

Finding 5 (semantic fixture coverage):

5. directive_variant_fixture_names_resolve_in_matrix used to only
   verify that the fixture name existed in IDEMPOTENCE_MATRIX.
   A contributor mapping Hedge to a comment-only fixture would
   compile, resolve, and ship Hedge with zero coverage. Now parses
   each named fixture and asserts the parsed directive matches the
   expected variant via a string-to-variant table.

Finding 6 (precise transition-byte skip):

6. The lexer-agreement property test skipped every quote slash
   semicolon slash percent byte, masking a real state-machine bug
   at any non-opener occurrence of those chars. Replaced with
   classify_source_bytes_with_transitions which returns the
   precise set of byte indices where a transition fires. The test
   skips only those indices and asserts agreement everywhere else.

Finding 7 (#!/#+ mid-line):

7. advance_source_state required at_line_start for SHEBANG and
   EMACS_DIRECTIVE detection, but the lexer regexes have no
   line-start anchor. Removed the gate so the state machine
   matches the lexer on mid-line cases. Added a fixture exercising
   the case.

Finding 9 (CountMismatch and future pragmas):

9. The count check uses parse_result.directives.len() but a
   future Directive variant whose legacy text parses to a
   different ParseResult collection (e.g. pragmas) would always
   trigger DirectiveCountMismatch. Added a comment naming this
   requirement and pointing the next maintainer at the
   compile-time _directive_variant_fixture_coverage match where
   the variant set is pinned.

Finding 10 (stale doc references):

10. Swept stale flat-path references in code comments (3 files)
    to the new namespaced path.

Coverage: 67 formatter unit tests pass (incl. the lexer-agreement
test with precise transition-byte skipping, the per-variant
semantic check, and the new EMACS-mid-line fixture). Workspace
tests pass with zero failures. Clippy clean with -D warnings.
cargo doc clean with RUSTDOCFLAGS=-Dwarnings.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1. ROUNDTRIP_KNOWN_ZERO_DIRECTIVE_FIXTURES doc corrected. An
   exhaustive probe against the live parser confirmed the actual
   zero-directive fixtures (8 total) include bare_cr_input (the
   parser does not treat bare CR as a directive terminator), which
   the prior comment omitted. The old EMACS fixture was incorrectly
   listed as zero; the new fixture (round-7 finding #2) genuinely
   parses to 1 directive, so the documentation now lists the real 8.
   The constant stays at 8.

2. emacs_directive_mid_line_following_directive replaced with
   emacs_directive_mid_line_with_quote. The old fixture put #+ at
   column 0 of line 2 (line START) and so did not exercise the
   mid-line state-machine path that was supposed to be its job. The
   new fixture genuinely places #+stray \"q mid-line: an incorrect
   state machine that gated the SHEBANG / EMACS_DIRECTIVE opener on
   at_line_start would stay in Code at the #+ byte, flip to InString
   on the following \" and trap there for the rest of the file.

3. Dead at_line_start parameter removed from advance_source_state
   and all call sites. The parameter was kept for forward
   compatibility but the lexers SHEBANG and EMACS_DIRECTIVE regexes
   carry no line-start anchor, so the state machine MUST treat #!
   and #+ as comment openers anywhere.

4. Variant -> fixture mapping unified through
   DIRECTIVE_VARIANT_FIXTURE_MAP. Previously the compile-time
   exhaustiveness match and the runtime semantic check carried two
   independent transcriptions of the same 12-entry map. They are
   now both driven from a single const slice; the compile-time
   match calls a const fixture_for_variant() lookup helper.

5. Stale at line start only language stripped from the
   lf_to_crlf_outside_strings rustdoc.

6. classify_source_bytes_with_transitions narrowed to only skip
   OPENING transitions and the InComment -> Code newline. The
   InString -> Code transition (closing quote) is no longer
   skipped: both state machine and lexer agree on that byte, so
   skipping it would silently mask any future state-machine bug at
   a closing-quote byte.

7. Cow side-channel replaced with explicit
   cr_outside_strings_present predicate. The CLIs emit_diff
   previously detected CR folded outside strings by matching
   crlf_to_lf_outside_strings::Cow::Owned vs the input bytes,
   conflating allocation behavior with semantic change.

8. try_format_source added as a public companion to format_source.
   Tooling that refuses to rewrite a file with parse errors
   previously had to call parse out-of-band and pair it with
   format_source. The helper makes the contract explicit and the
   CLI now uses it directly.

9. canonicalize_directives signature tightened to require
   I::IntoIter: ExactSizeIterator. The shim no longer materializes
   a Vec just to take the input count: len() comes off the iterator
   directly. Every existing call site already satisfies the bound.

10. Stale rustledger_parser::cst::format reference in
    rustledger/src/cmd/doctor/roundtrip.rs swept to
    rustledger_parser::format. Round-6 sealed cst::format as
    pub(crate) but missed this rustdoc backtick.

Verified: cargo test (parser + lsp + ffi + rustledger), cargo
clippy -- -D warnings, and RUSTDOCFLAGS=-Dwarnings cargo doc
--no-deps all clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two real bugs surfaced by the Copilot bot review, both
correctness regressions the prior fix rounds had missed:

1. emit_amount_expression silently dropped leading unary signs
   and opening parens in BALANCE / PRICE directives.

   The skip_while predicate was tokens kind != NUMBER, which
   meant a leading MINUS / PLUS / L_PAREN was treated as part of
   the directive header and skipped. Concrete data corruption:

     - 2024-01-15 balance Assets:A -1.00 USD
         formatted to: 2024-01-15 balance Assets:A 1.00 USD
         A debit assertion silently became a credit assertion.

     - 2024-01-15 price USD -1.00 EUR
         formatted to: 2024-01-15 price USD 1.00 EUR
         The whole quote sign flipped.

     - 2024-01-15 balance Assets:A (1 + 2) USD
         formatted to: 2024-01-15 balance Assets:A 1 + 2) USD USD
         Paren imbalance plus duplicate CURRENCY token.

   Widened the skip_while predicate to also break on PLUS,
   MINUS, and L_PAREN: the three tokens (besides NUMBER) that
   can legitimately begin an expression. Pinned each shape via
   byte-exact format_source assertions AND added the same three
   inputs to IDEMPOTENCE_MATRIX so the property tests
   (idempotence + canonicalize round-trip) catch any future
   regression.

2. collect_trailing_comment dropped same-line trailing comments
   at EOF when the file had no final newline.

   The function used ? on the header-terminating NEWLINE index,
   returning None for a directive that ran to end-of-file
   without a terminating NEWLINE child. The canonical formatter
   restores the trailing newline, so callers do not notice the
   missing newline, but the comment was already gone.

     Input  2024-01-15 open Assets:A ; trailing (no final NL)
     Output 2024-01-15 open Assets:A
     The "; trailing" comment vanished.

   Replaced the ? with unwrap_or(tokens.len()) so the backwards
   scan falls back to "from EOF". Pinned via a byte-exact
   format_source assertion AND a new
   trailing_comment_no_final_newline fixture in
   IDEMPOTENCE_MATRIX.

The two remaining Copilot concerns were not real:

- format_cost_spec's {# ... } marker IS preserved (a prior
  round added the is_per_unit_plus_total branch and the
  transaction_with_per_unit_plus_total_cost fixture). Probed
  byte-exact and confirmed.

- cmd/format.rs --check is already byte-exact, not .trim().
  A prior round landed that fix.

Verified: cargo test (parser + rustledger), cargo clippy
-D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc --no-deps all
clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen merged commit 3160e89 into main Jun 9, 2026
40 of 41 checks passed
@robcohen
robcohen deleted the feat/cst-phase-4-1-opinionated-formatter branch June 9, 2026 06:54
robcohen added a commit that referenced this pull request Jun 9, 2026
…ve-formatting fixtures (#1292)

* test(parser): #1262 phase 4.2 — format-compat suite with 30 destructive-formatting fixtures

Phase 4.2 of the CST migration: pin the formatter's promise on every
historical destructive-formatting bug class with file-pair golden
fixtures (input.bean / expected.bean) and a runtime-walking harness.

The file-pair shape complements the inline IDEMPOTENCE_MATRIX in
crates/rustledger-parser/src/cst/format.rs::tests:

- IDEMPOTENCE_MATRIX pins per-rule canonical-form behavior via
  property-style tests (idempotence, lexer agreement, round-trip
  through canonicalize_directives). Hand-edited in code review.

- tests/format_compat/cases/ is the user-facing contract surface.
  Browse the directory to see what rledger format promises on a
  given input. Reviewers can read input.bean and expected.bean side
  by side without running the test runner.

Both layers are load-bearing. The file-pair layer is the one
external users will read when they want to understand what the
formatter will do to their file.

## Coverage

30 fixtures across the bug classes that have caused destructive
formatting historically:

- issue_1252_destructive_repro — full reproducer from lutzky's
  issue. Pins the trailing-comment, pushtag/poptag, and
  cross-directive-tag-migration fixes from PR #1284.
- trailing_comment_on_directive_header, trailing_comment_eof_no_newline,
  posting_trailing_comment — the trailing-comment preservation
  rule from PR #1284 round-7 (Copilot #1).
- balance_leading_unary_minus_preserves_sign,
  balance_leading_parenthesized_expression,
  price_leading_unary_minus_preserves_sign,
  posting_arithmetic_with_parens — the sign-preservation rule
  from PR #1284 round-7 (Copilot #2).
- cost_spec_per_unit_plus_total_marker — pins the {# ... } marker
  preservation (Copilot #3 false-alarm).
- cost_spec_with_negative_amount, cost_spec_with_comma_and_date —
  cost-spec interior canonical form.
- pushtag_poptag_pair_preserved, pushmeta_popmeta_pair_preserved —
  pragma directives survive a round-trip.
- transaction_tags_and_links_source_order — source-order rule on
  transaction headers.
- multiline_note_string_preserved, non_latin_account_names —
  Unicode and multi-line string interior preservation.
- section_header_comments_tight, comment_with_unbalanced_quote —
  inter-directive comment positioning and state-machine
  agreement on stray quotes.
- metadata_unary_minus_value, metadata_arithmetic_value —
  metadata value canonical form.
- multiple_trailing_blank_lines_collapsed, missing_final_newline_added,
  bom_dropped — file-level whitespace canonicalization.
- crlf_outside_strings_folded, crlf_inside_strings_preserved —
  CRLF line-ending rule.
- balance_assertion_with_metadata, transaction_with_pending_flag,
  custom_directive_with_date_value, document_with_tags_and_links,
  options_includes_plugins_block — per-directive shape pins.

## Harness

tests/format_compat.rs walks tests/format_compat/cases/ at runtime
and asserts three properties per fixture:

1. format_source(input) == expected — the byte-exact contract.
2. format_source(expected) == expected — idempotence: re-formatting
   canonical text is a no-op.
3. parse(expected).errors is empty — the canonical output is itself
   parseable.

Asserts MIN_FIXTURES = 24 as a coverage floor so a future
contributor deleting cases by accident fails CI instead of
silently dropping the regression net.

## Authoring

A new fixture is two files: input.bean (what the user typed) and
expected.bean (what the formatter promises). The
bootstrap_format_compat example reads input.bean for every case
and writes expected.bean by running format_source on it. After
the initial bootstrap, expected.bean is the golden contract; the
example refuses to overwrite unless BOOTSTRAP_OVERWRITE=1 is set,
which keeps a stray re-run from silently re-baselining a fixture
whose expected output was hand-edited to pin a deliberate
canonical-form choice.

## Verified

- cargo test -p rustledger-parser — all 230+ tests pass including
  the new format_compat test
- cargo clippy -p rustledger-parser --all-features --all-targets
  -- -D warnings — clean
- RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser --no-deps
  — clean

Refs #1262.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address all 10 findings from the round-1 PR-1292 review

1. Stage-1 mismatch in format_compat.rs no longer `continue`s past
   the idempotence and parser-clean checks. All three stages run
   independently per fixture; a malformed expected.bean paired with
   a non-matching formatter output now surfaces both failures
   instead of hiding the unparsable golden file.

2. MIN_FIXTURES count floor (24 vs 30 actual) replaced with a
   REQUIRED_FIXTURES name-set. The count floor was too loose -
   six load-bearing fixtures could be silently deleted while
   passing CI. The name-set check forces removal of a critical
   bug-class fixture to be a deliberate, reviewable edit to the
   constant, not a silent disappearance from the cases directory.

3. Empty subdirectories no longer count toward the fixture set.
   The discovery filter requires each entry to actually contain
   input.bean, so a stray `mkdir` without a `git add` cannot mask
   coverage loss from a parallel deletion.

4. .gitattributes adds `crates/rustledger-parser/tests/format_compat/
   cases/**/*.bean -text` so a Windows contributor with
   core.autocrlf=true sees the CRLF-bearing fixtures
   (crlf_outside_strings_folded, crlf_inside_strings_preserved)
   byte-for-byte as committed. Without this, the literal \r bytes
   inside the in-string-CR fixture would be silently normalized on
   checkout and the test would either fail mysteriously or pass
   for the wrong reason.

5. README "Bump it when you add cases" rewritten to match the
   harness rustdoc: adding cases is free, only retiring a required
   fixture changes REQUIRED_FIXTURES.

6. issue_1252_destructive_repro narrative cleaned up. The previous
   input had load-bearing comments ("Commas should stay",
   "bean-format does not remove plus signs, neither should rledger
   format") that became passive-aggressive once the expected.bean
   pinned the opposite behavior. The fixture now pins ONLY the
   destructive-bug fixes (trailing comments, pushtag/poptag,
   cross-directive tag migration). The canonical-form choices on
   commas and unary `+` move to two dedicated fixtures:

   - commas_stripped_per_canonical_form
   - unary_plus_stripped_per_canonical_form

   These document the PR-4 decision explicitly and link the
   dispute back to #1252 in their input.bean comments. If the
   team later flips one of these choices, exactly one fixture's
   expected.bean changes - the historical destructive-bug pin
   stays stable.

7. posting_with_interleaved_metadata fixture added to cover the
   #1142 bug class (per-posting metadata interleaved between
   postings of the same transaction). The harness rustdoc claimed
   #1142 coverage but no fixture exercised the shape;
   balance_assertion_with_metadata only puts metadata on a balance
   directive, not interleaved between transaction postings.

8. README "what belongs here vs IDEMPOTENCE_MATRIX" section
   narrowed to acknowledge the overlap. Roughly half of the
   file-pair fixtures are reviewable mirrors of inline-matrix
   entries; the other half (issue_1252 repro, BOM, CRLF, pragma
   blocks, canonical-form-choice fixtures, posting-interleaved-
   metadata) are genuinely-new coverage shapes that don't fit the
   inline-string format ergonomically. Both layers are kept, the
   file-pair layer is the user-facing contract surface.

9. escape_for_diff no longer pass-throughs non-`\n\r\t` control
   bytes. NUL / BEL / VT / FF / DEL now render via
   `char::escape_debug` as visible escape sequences, so a fixture
   mismatch whose only delta is a stray control byte renders
   visibly in the failure output instead of looking byte-identical
   to the maintainer.

10. Bootstrap example gains BOOTSTRAP_FIXTURE=<name> for scoped
    re-baselining. The default (no env vars) skips fixtures with
    existing expected.bean. BOOTSTRAP_FIXTURE rewrites exactly
    one named fixture; an unknown name exits non-zero before
    touching any file. BOOTSTRAP_OVERWRITE=1 still rewrites the
    whole suite but the summary line warns to review `git diff`
    carefully before committing. The previous shape made
    BOOTSTRAP_OVERWRITE=1 the only way to re-baseline ANY fixture,
    which silently rebaselines unrelated golden files.

Verified: cargo test -p rustledger-parser (230+ tests including
the new format_compat shape), cargo clippy -p rustledger-parser
--all-features --all-targets -- -D warnings, RUSTDOCFLAGS=-Dwarnings
cargo doc -p rustledger-parser --no-deps. All clean. The harness
also passes with a bogus empty subdir present in cases/ (filter
confirmed).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address Copilot inline review comments on PR #1292

Replace `filter_map(Result::ok)` in the format-compat harness and the
bootstrap example with explicit `unwrap_or_else(|e| panic!(...))` on
each `read_dir` entry. Per-entry errors now panic with a diagnostic
instead of being silently dropped, matching the convention in
`tests/baseline_common::walk`.

The previous shape was a recall hole. If a permission or filesystem
fault hit one fixture directory (e.g. a stale `.partial` upload from
a backup tool, an inaccessible sub-tree on a CI runner), the entry
would be discarded with no diagnostic. The harness would still
pass the count floor and the bootstrap would print "wrote N files"
as if the run was complete, hiding the silent coverage drop.

Copilot's third comment (about missing `.gitattributes` rule for the
CRLF fixtures) was already addressed in the round-1 review fixes
(commit 30adb81). The bot's review fired against the pre-fix
commit; that finding is moot.

Verified: cargo test -p rustledger-parser --test format_compat,
cargo clippy -p rustledger-parser --all-features --all-targets
-- -D warnings. All clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address all 10 findings from the round-2 PR-1292 review

1. escape_for_diff now routes everything outside ASCII-printable
   through `char::escape_debug`, which renders BOM (U+FEFF), zero-
   width spaces (U+200B..=U+200D, U+2060), C1 controls
   (U+0080..=U+009F), and other format-category codepoints as
   visible `\u{...}` escapes. The previous shape passed those bytes
   through verbatim, so a regression that stopped stripping the
   BOM would have rendered `--- expected ---` and `--- got ---`
   panels byte-identical to the eye - undermining the bom_dropped
   fixture's whole purpose. Printable non-ASCII Unicode (Cyrillic,
   CJK, Greek, etc.) still passes through unchanged because
   escape_debug preserves printable categories.

2. `present_names` is now built via `to_string_lossy().into_owned()`
   instead of `.to_str().map(String::from)`. The previous shape
   silently dropped non-UTF-8 directory names from the set, so a
   present-but-non-UTF-8-named REQUIRED fixture would have been
   falsely reported as missing. Aligns with the bootstrap example's
   name-extraction policy.

3. REQUIRED_FIXTURES check now runs against the RAW directory
   listing (every subdir), not the filtered-for-input.bean set.
   A required fixture whose directory exists but is missing
   input.bean now surfaces as `[name] missing input.bean` in the
   per-fixture failure log, not as the misleading "required
   fixture missing from cases dir" assert. The two failure shapes
   correspond to two distinct contributor mistakes (forgot to
   create the dir vs. forgot to `git add` the input file); the
   error message now disambiguates them.

4. Bootstrap summary branch order swapped: target_fixture is
   checked BEFORE overwrite_all, so the combined
   `BOOTSTRAP_OVERWRITE=1 BOOTSTRAP_FIXTURE=<name>` invocation
   prints "only the named fixture's expected.bean was rewritten"
   instead of the previous misleading "rewritten across the whole
   suite". The actual write behavior was already correct; only
   the summary line was lying.

5. MIRROR_PAIRS constant added to tests/format_compat.rs listing
   17 (file_pair_name, matrix_name) bug-class twins across the
   file-pair suite and the inline IDEMPOTENCE_MATRIX. The
   integration test asserts every file_pair_name exists as a
   directory under cases/. A new inline unit test
   `idempotence_matrix_mirrors_format_compat_pairs` in
   cst::format::tests asserts every matrix_name exists in
   IDEMPOTENCE_MATRIX. A one-sided deletion now requires editing
   both lists (or fails CI on the unedited side), enforcing the
   "two audience" coverage coupling the README's split design
   previously left as documentation-only.

6. REQUIRED_FIXTURES grew from 20 to 25 entries. Promoted from
   non-required:
   - multiline_note_string_preserved (string-literal interior
     preservation, classic destructive-formatting class)
   - balance_assertion_with_metadata (per-directive metadata
     attachment, sibling of #1142)
   - transaction_tags_and_links_source_order (tag/link ordering
     preservation, sibling of #1252)
   - metadata_unary_minus_value (sign preservation on metadata
     values)
   - non_latin_account_names (Unicode column-alignment correctness)

   Each was identifiably load-bearing for a regression class but
   could previously be deleted without tripping the floor check.

7. Stale rustdoc on `canonicalize_directives` in cst/format.rs
   disambiguated. The reference to "the deleted format_compat
   test" was ambiguous now that PR #1292 reintroduces a
   format_compat test in a different crate. Rustdoc now names
   the OLD test (crates/rustledger/tests/format_compat.rs,
   deleted in phase 4.1) explicitly and clarifies the new
   file-pair suite does NOT exercise canonicalize_directives'
   reparse-error path.

8. Stages 2 and 3 of the harness now run inside `catch_unwind`.
   A panic in format_source or parse on a pathological expected
   no longer aborts the entire test and discards the stage-1
   failures recorded for earlier fixtures in the same loop. The
   panic is recorded as a per-fixture failure with a clear
   message ("format_source is contracted to be total over
   arbitrary input; this is a bug") so the contributor knows
   the regression is in the formatter, not the fixture.

9. Bootstrap's BOOTSTRAP_FIXTURE validation now requires the
   target fixture's input.bean to exist before allowing any I/O.
   The previous shape exited 0 with "wrote 0, missing input 1"
   on a BOOTSTRAP_FIXTURE=name where `cases/name/` was an empty
   directory (no input.bean), which a contributor could misread
   as "bootstrap succeeded". The new check exits with code 3 and
   a clear "directory has no input.bean" message. Distinct from
   the existing code 2 "directory does not exist" path.

10. issue_1252_destructive_repro/input.bean now opens with a
    cross-reference comment pointing forward to the
    commas_stripped and unary_plus_stripped sibling fixtures.
    A reviewer auditing the #1252 fixture no longer reads the
    `commas_stripped/input.bean` claim that "the dispute is
    tracked in #1252" and then finds zero comma cases in the
    #1252 fixture itself.

Verified: cargo test -p rustledger-parser (231+ tests; new
idempotence_matrix_mirrors_format_compat_pairs unit test green),
cargo clippy -p rustledger-parser --all-features --all-targets
-- -D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc
-p rustledger-parser --no-deps. All clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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.

2 participants