Repository navigation
feat(parser): #1262 phase 2.1a structured CST for 14 single-line directives - #1272
Merged
Merged
Conversation
…ctives Phase 2.1a of the parser-CST migration. PR 2.1 of the phase plan is split into PR 2.1a (this commit, 14 single-line directives) and PR 2.1b (TRANSACTION header + body parsing in PR 2.2). Splitting keeps each PR focused, mechanically uniform per directive, and limits the corpus baseline churn surface per PR. ## What this commit ships - **14 specific directive `SyntaxKind` variants**: OPEN_DIRECTIVE, CLOSE_DIRECTIVE, BALANCE_DIRECTIVE, PAD_DIRECTIVE, EVENT_DIRECTIVE, QUERY_DIRECTIVE, NOTE_DIRECTIVE, DOCUMENT_DIRECTIVE, PRICE_DIRECTIVE, COMMODITY_DIRECTIVE, PUSHTAG_DIRECTIVE, POPTAG_DIRECTIVE, PUSHMETA_DIRECTIVE, POPMETA_DIRECTIVE. The generic DIRECTIVE umbrella kind from phase 2.0 is retained for error-recovery wrappers and shape- uniform tests. - **`parse_structured(source) -> SyntaxNode`** alongside the phase- 1 `parse_flat`. Streaming over the lossless token stream: identifies each top-level token as either starting a recognized directive (DATE-keyword or top-level keyword pattern) or flowing through as flat content. For recognized directives, opens a node of the appropriate `*_DIRECTIVE` kind, drains pending leading trivia INSIDE the new node (rule 2 of the Directive-Terminator Rule), consumes tokens through the terminator NEWLINE (rule 1), and closes. File-leading trivia flushes to SOURCE_FILE per rule 3; file-trailing per rule 4. - **Re-exported as `parse_structured`** from `cst` and `lib`. `parse_flat` retained for round-trip-only tests. - **27 source-driven integration tests** at `crates/rustledger-parser/tests/structured_directives.rs`: one test per directive kind asserting exact element sequence, plus 6 trivia-policy tests asserting the Directive-Terminator Rule corollaries on real source, plus pass-through tests for TRANSACTION, OPTION, and mixed recognized/unrecognized files. - **Corpus baseline switched to `parse_structured`.** The `tests/baselines/cst-corpus.manifest` file regenerated: `token_seq_blake3` column byte-identical to phase 2.0 (no token classification change), `node_shape_blake3` column churns for every file containing any recognized directive (~half the corpus). 714 entries pass strict-mode. - **`every_kind_partitions_token_xor_node` and `nodes_are_not_tokens`** updated with the 14 new node kinds. ## What this commit does NOT add - TRANSACTION header recognition. Phase 2.1b ships this paired with PR 2.2's posting body parsing. - Edge directives (OPTION, INCLUDE, PLUGIN, CUSTOM). Phase 2.3. - Per-directive metadata sub-line wrapping. A future PR adds META_ENTRY structure inside each directive that carries indented `key: "value"` lines. - Typed-AST surface. Phase 3.1 adds wrappers like `Open::account()` over the new directive nodes. ## Verified - 171 unit + 4 + 1 + 1 + 55 + 27 + 2 doctests pass. - `cargo check --workspace --all-features --all-targets` clean. - `cargo clippy -p rustledger-parser --tests -- -D warnings` clean. - `cargo fmt --all --check` clean. - `cargo deny check bans` clean. - `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser --no-deps` clean. - `STRICT_BASELINE=1 cargo test -p rustledger-parser --test cst_baseline` passes against the regenerated 714-file manifest. Refs #1262. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
There was a problem hiding this comment.
Pull request overview
Adds phase 2.1a structured CST emission for 14 single-line Beancount directives by introducing dedicated SyntaxKind node variants and a new parse_structured builder, plus integration tests and baseline updates to gate token-vs-node stability.
Changes:
- Introduce 14 new
*_DIRECTIVEnode kinds and exportparse_structuredpublicly. - Implement
parse_structured(source) -> SyntaxNodeto wrap recognized directive lines while preserving the lossless round-trip contract. - Add source-driven integration tests for directive shapes + trivia attachment policy; update CST corpus baseline gate to use
parse_structured.
Reviewed changes
Copilot reviewed 6 out of 7 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/rustledger-parser/tests/structured_directives.rs | New integration tests asserting structured directive node shapes + trivia attachment behavior. |
| crates/rustledger-parser/tests/cst_baseline.rs | Switch baseline fingerprinting to parse_structured and clarify token-vs-node hash semantics. |
| crates/rustledger-parser/src/lib.rs | Re-export parse_structured from the crate root. |
| crates/rustledger-parser/src/cst/syntax_kind.rs | Add 14 new directive node SyntaxKind variants and include them in kind classification tests. |
| crates/rustledger-parser/src/cst/parser.rs | Implement parse_structured and directive recognition logic on top of the lossless token stream. |
| crates/rustledger-parser/src/cst/mod.rs | Re-export parse_structured from the cst module. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Contributor
📊 Benchmark Results
vs main branch (2026-06-05)
What do these numbers mean?
|
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
…ss-line keyword shapes Deep review of v1 (commit bbb6f6b) surfaced two correctness findings; both fixed here. ## Finding A: multi-line directive scope mismatch v1 closed recognized directives at the header NEWLINE, leaving indented metadata sub-lines (` name: "value"`) orphaned as flat SOURCE_FILE children. This contradicts the multi-line clause of the Directive-Terminator Rule documented in cst::trivia (v5): "a multi-line directive's last content token is the last content token of its LAST sub-line, not the header." Concrete failure: `2024-01-01 commodity HOOL\n name: "Hooli"\n` produced a COMMODITY_DIRECTIVE containing only the header, while `[WS, META_KEY, WS, STRING, NEWLINE]` floated under SOURCE_FILE. v2 introduces `emit_directive_body`, which consumes the header through its terminator NEWLINE per rule 1, then keeps consuming any `WHITESPACE + META_KEY` indented metadata sub-lines that follow. The directive node now spans the full multi-line scope. The metadata is still flat inside (no META_ENTRY structural wrapper); PR 2.2 will wrap each sub-line. Stopping condition: anything other than `WHITESPACE + META_KEY` at the next position terminates the directive (a blank-line NEWLINE, an indented comment, top-level content, EOF). The blank-line case is tested in `blank_line_between_metadata_lines_ terminates_directive` and confirms rule 2 still fires (next directive gets leading NEWLINE). ## Finding B: identifier walks past NEWLINE v1's `identify_single_line_directive` walked j forward past any `is_trivia()` token to find the keyword after a DATE. NEWLINE is trivia, so a malformed `2024-01-01\nopen Assets:Cash` was wrongly identified as OPEN_DIRECTIVE — but emit_through_terminator stops at the first NEWLINE, leaving OPEN_DIRECTIVE containing only `[DATE, NEWLINE]` and orphaning `open Assets:Cash` as a flat unrecognized line. Tree structure was wrong even though bytes round-tripped. v2 restricts the walk to `SyntaxKind::WHITESPACE` only — the only trivia kind that legally separates content tokens on a single line. Pinned by `malformed_date_then_keyword_on_next_ line_is_not_a_directive`. ## What changes for the corpus baseline - token_seq_blake3: byte-identical to phase 2.0 (the contract the manifest split was designed to enforce). No token classification changed; this PR only wraps tokens in structural nodes. - node_shape_blake3: churns more than v1 because directives carrying metadata now wrap their metadata too. Files that use OPEN/CLOSE/COMMODITY/etc. with metadata see deeper per-file shapes. ## Tests 4 new regression tests in tests/structured_directives.rs: - commodity_with_metadata_wraps_full_multi_line_directive - open_with_multiple_metadata_lines_wraps_all_inside_directive - directive_with_metadata_then_next_directive - blank_line_between_metadata_lines_terminates_directive - malformed_date_then_keyword_on_next_line_is_not_a_directive Plus the v1 tests still pass unchanged (the multi-line logic is backward-compatible: single-line directives without metadata take the same path as before — emit_directive_body's metadata loop terminates on first iteration). ## Verified - 32 structured-directive tests + 171 unit + 4 + 1 + 1 + 55 + 2 doctest = all pass. - cargo check workspace, clippy -D warnings, fmt check, deny check bans, RUSTDOCFLAGS=-Dwarnings cargo doc — all clean. - STRICT_BASELINE=1 cargo test ... cst_baseline passes against the regenerated 714-file manifest. Refs #1262. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…e directive Round-2 review of v2 surfaced one real correctness bug: an indented `;`-comment between two metadata entries silently closed the directive early and orphaned every subsequent metadata entry as a direct child of SOURCE_FILE — including bare META_KEY tokens. ## The failure Source: ``` 2024-01-01 open Assets:Cash k1: "v1" ; doc comment for k2 k2: "v2" ``` v2 walk: after `k1` consumed, `is_indented_meta_line` saw `WHITESPACE + COMMENT` (not `WHITESPACE + META_KEY`), returned false. OPEN_DIRECTIVE closed containing only `k1`. The outer loop drained the comment as flat trivia under SOURCE_FILE, encountered the META_KEY for `k2` as a non-trivia top-level token, `identify_single_line_directive` returned None (no META_KEY arm), and the unrecognized-line branch emitted the `k2` sub-line as flat tokens directly under SOURCE_FILE. End state: a bare META_KEY sat as a direct child of SOURCE_FILE, `k2` was detached from its owning directive, and a typed AST walking OPEN_DIRECTIVE would silently miss the second metadata entry the user wrote. Bytes still round-tripped but the tree contradicted the multi-line clause of the Directive-Terminator Rule. Beancount users commonly put `; ...` lines between metadata for documentation. This is realistic input, not a fuzzed edge case. ## The fix Renamed `is_indented_meta_line` to `is_indented_directive_continuation` and widened it: a continuation sub-line is recognized as `WHITESPACE` followed by either `META_KEY` (the existing metadata case) OR `COMMENT` / `PERCENT_COMMENT` (the new indented-comment case). Anything else — a blank line, non-indented content, EOF — still terminates. The known limitation around blank-line-separated metadata blocks stays (` k1: v\n\n k2: v` still orphans k2). PR 2.2's META_ENTRY grammar will likely subsume this when it introduces per-sub-line structural wrapping. ## Test `indented_comment_between_metadata_lines_stays_inside_directive` pins the fix: the OPEN_DIRECTIVE must contain header + k1 + indented comment + k2, with NO bare META_KEY appearing as a direct child of SOURCE_FILE. ## Verified - 33 structured-directive tests + 171 unit + 4+1+1+55+2 doctest pass. - cargo check workspace, clippy -D warnings, fmt check, RUSTDOCFLAGS=-Dwarnings cargo doc, deny check bans — all clean. - STRICT_BASELINE=1 cargo test ... cst_baseline passes (manifest unchanged — the fix changes only WHICH tokens land inside the directive node, not the node-enter sequence the manifest hashes). Refs #1262. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…rior metadata
Round-3 review of v3 caught a real regression introduced by v2's
widening of the multi-line-directive continuation predicate.
## The regression
v3 widened `is_indented_directive_continuation` from
`WS + META_KEY` to also accept `WS + COMMENT` and
`WS + PERCENT_COMMENT`. This fixed the comment-between-metadata
case (v2 finding) but became overbroad: any indented comment
following a directive — regardless of whether the directive had
ANY metadata — got absorbed into the directive. Two trivia-rule
violations:
**Rule 2 violation.** Source:
```
2024-01-01 open Assets:Cash
; mid-file comment
2024-01-02 close Assets:Cash
```
Per rule 2 (cst/trivia.rs lines 26-31), mid-file comments
between two directives lead the NEXT directive. v3 absorbed the
indented comment into OPEN_DIRECTIVE instead. CLOSE_DIRECTIVE
had no leading trivia.
**Rule 4 violation.** Source:
```
2024-01-01 open Assets:Cash
; trailing indented comment
```
Per rule 4 (cst/trivia.rs lines 40-44), trivia AFTER the last
directive's terminator NEWLINE attaches to SOURCE_FILE. v3
absorbed the indented trailing comment into OPEN_DIRECTIVE,
contradicting the documented symmetric-with-rule-3 intent ("a
copyright comment at the top is not part of the first directive
... same at EOF").
The inconsistency was visible from a single example: identical
input with the trailing comment unindented produces the correct
SOURCE_FILE attachment (test rule_4_trailing_comment_block_under
_source_file already passes), but adding two spaces to the
comment silently flipped the attachment under v3 — same trivia
class, two different homes based on whitespace.
## The fix
Track whether the current directive's body has observed at least
one `META_KEY` since the header NEWLINE. Gate the
COMMENT/PERCENT_COMMENT branches of
is_indented_directive_continuation on that flag.
- `WS + META_KEY` still continues unconditionally (preserves v2
metadata behavior).
- `WS + COMMENT` and `WS + PERCENT_COMMENT` continue ONLY after
a META_KEY has appeared in the body (preserves v3's fix for
comments BETWEEN metadata entries).
- Before any metadata, an indented comment correctly behaves as
inter-directive trivia (rule 2) or file-trailing (rule 4).
The v3 test `indented_comment_between_metadata_lines_stays_inside
_directive` still passes — its comment is preceded by k1's
META_KEY, so the gated predicate still admits it.
## Tests
Two new regression tests pin the fix:
- `indented_comment_after_no_metadata_directive_leads_next_directive`
- `indented_comment_at_eof_after_no_metadata_directive_is_file_
trailing`
Both would fail under v3 (rule 2 + rule 4 violations) and pass
under v4.
## Verified
- 35 structured-directive tests + 171 unit + 4+1+1+55+2 doctest
pass.
- cargo check workspace, clippy -D warnings, fmt check, deny
check bans, RUSTDOCFLAGS=-Dwarnings cargo doc — all clean.
- STRICT_BASELINE=1 cargo test ... cst_baseline passes (manifest
unchanged — node-enter sequence is invariant to the
inside-or-outside-the-directive question).
Refs #1262.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…continuation Round-3 review surfaced a v4 regression where indented `;`-comments following a header-only directive over-attached into the directive (violating rules 2 and 4). v4 fixed that with a per-line `body_has_meta` flag — but the per-line flag couldn't see metadata that came AFTER an indented comment, so the "documentation-comment-for-the-following-field" idiom orphaned the metadata it introduced. ## The v4 gap Source: ``` 2024-01-01 open Assets:Cash ; documentation for the next field description: "main checking" ``` v4 walk: header consumed. First continuation check is for the indented comment with `body_has_meta=false`. The gate is closed, so the predicate returns false and the directive closes after the header. The outer loop then drains `WS, COMMENT, NEWLINE` as pending trivia, encounters the indented `WS+META_KEY` for `description`, fails identify_single_line_directive (META_KEY is not a top-level directive shape), takes the unrecognized-line branch, and emits the metadata as flat orphan tokens under SOURCE_FILE. Same orphaning class as the v2 finding, different trigger. ## The v5 fix Replace `body_has_meta` (per-line observed-so-far) with `block_has_meta` (prospectively computed once at the start of the body). The new helper `upcoming_indented_block_has_meta` walks the upcoming indented-content block — including past indented-comment lines — and returns true iff at least one `WS META_KEY` sub-line exists somewhere in the block. If yes, all indented `;`/`%` comments in the block are continuations (including BEFORE the first META_KEY, the doc-comment-for-the-following-field case). If no, an indented comment is inter-directive trivia (rule 2) or file-trailing trivia (rule 4) and stays out of the directive (v4 behavior on the rule-2/rule-4 cases preserved). ## Tests New regression test `indented_comment_before_first_metadata_stays_inside_directive` pins the doc-comment-for-the-following-field case. Previously failing tests `indented_comment_after_no_metadata_directive_leads_next_directive` and `indented_comment_at_eof_after_no_metadata_directive_is_file_trailing` still pass — the prospective scan correctly returns false for those header-only directive cases. ## Round-4 review on v5 A 4th deep review on v5 surfaced no further findings. Termination, performance (O(N) per directive, O(total) per file), EOF mid-scan, PERCENT_COMMENT parity, comment-run-only behavior, and round-trip property all verified. One sub-case the review noted but did not flag as a bug: indented comments AFTER the last metadata but BEFORE the next directive get absorbed into the preceding directive (the gate is sticky-true once a META_KEY is seen). This matches the "doc-comment idiom" mental model (indented = attached to the preceding metadata block) and is consistent with how users format metadata documentation. Unpinned by tests; a follow-up PR can refine if needed. ## Verified - 36 structured-directive tests + 171 unit + 4+1+1+55+2 doctest pass. - cargo check workspace, clippy -D warnings, fmt check, deny check bans, RUSTDOCFLAGS=-Dwarnings cargo doc — all clean. - STRICT_BASELINE=1 cargo test ... cst_baseline passes (manifest unchanged — node-enter sequence invariant to which-tokens- inside-which-directive). Refs #1262. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…en_first_content Copilot review caught: the inline comment at parse_structured says pending trivia is file-leading until the first directive is recognized. The flag actually flips on ANY first non-trivia content, recognized or unrecognized. The behavior is correct per Roslyn (trivia after a content line associates with the following content); only the comment was inaccurate. Updated to describe the actual trigger. Refs #1262. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This was referenced Jun 5, 2026
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.
Summary
Phase 2.1a of #1262: structured CST emission for 14 single-line directive types.
What this PR adds
SyntaxKindvariants:OPEN_DIRECTIVE,CLOSE_DIRECTIVE,BALANCE_DIRECTIVE,PAD_DIRECTIVE,EVENT_DIRECTIVE,QUERY_DIRECTIVE,NOTE_DIRECTIVE,DOCUMENT_DIRECTIVE,PRICE_DIRECTIVE,COMMODITY_DIRECTIVE,PUSHTAG_DIRECTIVE,POPTAG_DIRECTIVE,PUSHMETA_DIRECTIVE,POPMETA_DIRECTIVE. The genericDIRECTIVEumbrella kind from phase 2.0 is retained for error-recovery wrappers and shape-uniform tests.parse_structured(source) -> SyntaxNode— streaming structural parser over the lossless token stream. Recognizes each top-level directive shape (DATE+keyword for the 10 dated ones; standalone keyword for the 4 push/pop ones), opens an appropriate*_DIRECTIVEnode, applies the Directive-Terminator Rule (trivia attaches per phase 2.0's policy), and closes at the terminator NEWLINE. Unrecognized lines (TRANSACTION, OPTION, INCLUDE, PLUGIN, CUSTOM) flow through as flatSOURCE_FILEchildren — pass-through bytes preserved, no node wrapping until later PRs cover them.crates/rustledger-parser/tests/structured_directives.rs: one per directive type asserting exact child sequences, plus 6 trivia-policy tests verifying the Directive-Terminator Rule corollaries on real Beancount source, plus pass-through tests for TRANSACTION/OPTION/mixed files.parse_structuredattests/baselines/cst-corpus.manifest. Thetoken_seq_blake3column is byte-identical to phase 2.0 (no token-classification change — the contract from the manifest split holds). Thenode_shape_blake3column churns for every corpus file containing any recognized directive (~half the corpus). 714 entries pass strict-mode.every_kind_partitions_token_xor_nodeandnodes_are_not_tokensupdated with all 14 new node kinds.What this PR does NOT add
key: "value"lines after a directive) — left flat for a future PR that introducesMETA_ENTRYstructure.Open::account()accessors) — phase 3.1.The Directive-Terminator Rule, applied
Each recognized directive node spans content tokens + same-line trailing trivia + terminator NEWLINE per phase 2.0's Directive-Terminator Rule. Source-driven tests cover all five corollaries:
rule_1_same_line_trailing_comment_inside_directiverule_2_blank_line_leads_following_directiverule_3_copyright_header_under_source_filerule_4_trailing_comment_block_under_source_filerule_5_unterminated_final_directiverule_5_unterminated_with_same_line_trailing_triviaVerified
cargo check --workspace --all-features --all-targetsclean.cargo clippy -p rustledger-parser --tests -- -D warningsclean.cargo fmt --all --checkclean.cargo deny check bansclean.RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser --no-depsclean.STRICT_BASELINE=1 cargo test -p rustledger-parser --test cst_baselinepasses against the regenerated 714-file manifest.Test plan
Refs #1262.
🤖 Generated with Claude Code