Skip to content

refactor: route currency-name checks through the lexer's rule - #2874

Merged
robcohen merged 5 commits into
mainfrom
refactor/currency-canonical
Nov 6, 2026
Merged

robcohen merged 5 commits into
mainfrom
refactor/currency-canonical

Conversation

@robcohen

@robcohen robcohen commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

What changed

Every currency-name check now follows the lexer's own Currency rule (#2807, canonical-function discipline).

  • LSP and WASM editor: is_currency_like calls the lexer-backed rustledger_parser::is_valid_currency. The LSP's is_currency_like_simple (2 to 5 uppercase characters) is removed; hover and completion-resolve ask the canonical instead.
  • Symbol under the cursor: the new ParseResult::currency_at(offset) returns the parser's currency token at a byte offset. The LSP's get_symbol_at_position and the WASM editor's equivalent use it before the old word scan. The word scan stopped at / and ., so on /6J it saw only 6J. That is why rename, references and linked editing failed on / currencies even with a correct name check. They now work, and so do document highlight, hover and go-to-definition, on /6J and on BRK.B. Linked editing's word pattern is now [A-Z/][A-Z0-9'._-]*.
  • Amount::from_str (rustledger-core): core cannot depend on the parser, which depends on core. Following the AGENTS.md preference order, is_valid_commodity stays a deliberate copy and is documented at both sites:
    • The copy mirrors the lexer regex /[A-Z0-9'._-]*[A-Z]([A-Z0-9'._-]*[A-Z0-9])?|[A-Z]([A-Z0-9'._-]*[A-Z0-9])?, minus the TRUE/FALSE/NULL keywords.
    • The doc comments on the copy and on is_valid_currency name each other and give a revisit condition.
    • The drift guard amount_from_str_currency_matches_lexer (in rustledger-parser) compares Amount::from_str with is_valid_currency on every string of up to 5 characters over A T P 0 ' . _ - / a : É (T and P are flag letters). It also checks the issue's shapes (/6J, /ESM24, USD_, A, C_, HOOL'), each one-letter flag letter PSTCURM, and the keywords.

Behavior notes

  • Amount::from_str now accepts /6J and /ESM24, and rejects a trailing - or _ (USD_). Its 24-character cap is gone, because the lexer has none. Its only caller is the string form of BQL CONVERT('100 USD', 'EUR'), a rustledger extension ([Feature]: Converter (add string input to convert()) #1179) with no beancount equivalent, so it now accepts exactly the currencies a ledger can contain.
  • Other Amount parsing I checked: plugins and the FFI do not call Amount::from_str. rledger add's parse_amount (crates/rustledger/src/cmd/add_cmd/parsing.rs) has its own is_currency_char splitter and does not validate the currency at all. It is left alone here and is a candidate follow-up.
  • The LSP now treats a single-letter currency that appears in the document (such as T) as a currency, because the lexer does. A one-letter transaction or posting flag is not one (see Review round 1).
  • BQL CONVERT's string form now rejects TRUE, FALSE and NULL as currencies (CONVERT('100 TRUE', 'USD') is an error), because the lexer reads them as keywords. It now accepts currency names longer than 24 characters, as a ledger does.

How to test

cargo test -p rustledger-parser -- amount_from_str_currency_matches_lexer currency_at parse_green_eq_red
cargo test -p rustledger-core test_amount_from_str_currency_matches_lexer_shapes
cargo test -p rustledger-lsp --all-features -- slash_currency get_symbol_at_position one_letter
cargo test -p rustledger-wasm --all-features -- slash_currency get_symbol_at_position one_letter cost_and_price keywords_unchanged not_quadratic

I ran tests for core, parser, LSP, WASM and query (--all-features), plus clippy -D warnings, cargo doc -Dwarnings, cargo fmt --check and cargo check -p rustledger-wasm --target wasm32-unknown-unknown.

Closes #2807

Review round 1

Transaction flags were counted as currencies (significant). A one-letter flag (T in 2024-01-16 T "Transfer", P before a posting's account) lexes as a CURRENCY token, and the parser recorded it in currency_occurrences. Once the 2-character minimum was gone, references, highlight, hover, definition and linked editing on a currency T also hit the T flag. Hovering a P flag showed "Currency: P" even with no such currency. Rename already had this bug on main.

  • Parser: both walkers now leave the flag token out. The red walker asks Transaction::flag / Posting::flag directly. The green walker mirrors those two accessors in flag_child_index, and the comments at both sites point to each other. parse_green_eq_red_corpus gains five flag shapes, and fuzz_green_eq_red already compares currency_occurrences. The currency_occurrences rustdoc states the rule.
  • New ParseResult::is_flag_at(offset) (renamed is_currency_flag_at and narrowed in round 2). When there is no currency token under the cursor, the LSP and WASM editors fall back to a word scan. That scan now returns no symbol if the word starts on a flag, so the flag cannot resolve to the currency of the same name.
  • Regression tests for a T flag next to a currency T, plus P flags with no currency P. LSP: references, document highlight, linked editing, hover, rename (prepare and edits), go-to-definition, and get_symbol_at_position on UTF-16 and UTF-8. WASM: references, hover, definition and the symbol lookup. Parser: currency_occurrences (green and red) and is_flag_at, with and without a BOM.
  • No cache bump. Neither the loader cache nor the WASM cache (ParsedLedgerPayload, LedgerPayload) stores currency_occurrences. The loader parses with parse_without_occurrences, and WASM fromCache reparses the source for editor features. Directives and errors do not change. So no WASM 74 or loader 58 number is needed here, and nothing collides with fix(parser): ignore column-0 !, &, ? and : lines and report bare markers, as beancount does #2877 or refactor: one rule for when a query answers despite load errors #2881.

Drift-guard alphabet. It now includes T and P, and the named shapes include every flag letter PSTCURM plus TT. If a lexer change let a flag token beat Currency for a single letter, the guard would trip.

CONVERT changes documented. The keyword rejection and the dropped 24-character cap are now in the CHANGELOG and in the behavior notes above.

WASM references on one-letter currencies. find_currency_references now walks the parser's currency token spans, as the LSP does. It no longer runs a text search per directive line, so a B on open Assets:X BRK.B,B no longer lands inside BRK.B. The token walk also picks up cost and price-annotation currencies, which the text search missed. Contexts (commodity, open, balance, price / price amount, posting) and is_definition are kept, and new tests pin them.

Duplicate LineIndex. get_symbol_at_position now takes the handler's LineIndex. Definition, document highlight and linked editing build one index per request instead of two. Hover, references and rename build the index at the call site; their per-file collectors build their own, as before.

Verification: cargo test -p rustledger-parser -p rustledger-lsp -p rustledger-core -p rustledger-query -p rustledger-wasm --all-features (3050 passed, 0 failed), cargo clippy --all-features --all-targets -- -D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps and the --all-features --document-private-items variant, cargo fmt --check, cargo check -p rustledger-wasm --target wasm32-unknown-unknown.

Review round 2

txn keyword hover regressed (significant). is_flag_at returned true for every flag that Transaction::flag reads, including TXN_KW. So the word-scan fallback in both editors returned no symbol on txn, and hover never reached the keyword info. Main shows "## Transaction" at characters 12-13 of 2024-01-03 txn "Broker" "Buy"; this PR showed nothing.

  • The method is renamed ParseResult::is_currency_flag_at. It is now true only for a one-letter flag that lexes as a CURRENCY token. *, !, #, FLAG letters and txn are false: none of them can be read as a currency, and txn has to stay a word for its keyword hover. The rustdoc says so, and so do the LSP and WASM get_symbol_at_position docs.
  • New tests: test_hover_keywords_unchanged_by_flag_skip (LSP) and test_get_hover_info_keywords_unchanged_by_flag_skip (WASM).
    • They hover every directive keyword (option, plugin, include, open, commodity, balance, pad, event, note, document, query, custom, price, txn, close) at the word's start, start+1 and end. The result must equal the keyword-info function's output.
    • They also cover the review's txn case at characters 12 and 13.
    • * and ! as header and posting flags hover as nothing, as on main: neither is a word character, so the word scan never yields them.
  • The parser test now also asserts is_currency_flag_at is false on txn, * and ! flags.

WASM currency references were quadratic (significant). For every match, first_in_holder scanned currency_occurrences from the start. It now uses partition_point on span start, which works because occurrences are in source order, and it runs only for commodity and price holders. New test test_get_references_currency_is_not_quadratic: 60k matches across commodity, price, open and commodity metadata, with a loose 5 s bound. In a debug test build the walk takes about 90 ms. With the old scan put back temporarily, it took about 12.9 s and failed the bound.

Nit: find_currency_references now documents that a metadata currency gets its directive's context: "commodity" (not a definition) inside a commodity, and "price amount" inside a price.

Verification on 112b1988309: cargo test -p rustledger-parser -p rustledger-lsp -p rustledger-core -p rustledger-query -p rustledger-wasm --all-features (3053 passed, 0 failed), cargo clippy --all-features --all-targets -- -D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps and the --all-features --document-private-items variant, cargo fmt --check, cargo check -p rustledger-wasm --target wasm32-unknown-unknown. Still no cache bump: nothing here touches cached output.

🤖 Generated with Claude Code

Three helpers classified currency names with textual rules of their own
and disagreed with the lexer (#2807): rustledger-core's
`is_valid_commodity` (behind `Amount::from_str`, the string form of BQL
`CONVERT`), the LSP's `is_currency_like` and the WASM editor's. All three
rejected `/6J` and `/ESM24`; `Amount::from_str` also accepted a trailing
`-` or `_` and capped a name at 24 characters, which the lexer does not.

- LSP and WASM: call the lexer-backed `rustledger_parser::is_valid_currency`
  (the LSP's `is_currency_like_simple` is gone too, hover and completion
  resolve now ask the canonical). The symbol under the cursor is the
  parser's own currency token when there is one, via the new
  `ParseResult::currency_at`: the word scan stopped at `/` and `.`, so
  rename, references, linked editing, highlights, hover and go-to-definition
  could not reach `/6J` or `BRK.B`. Linked editing's word pattern admits
  the `/` form.
- rustledger-core cannot depend on the parser, so `is_valid_commodity` is a
  documented copy of the lexer's regex (keywords excluded), cross-referenced
  from `is_valid_currency`, and pinned by the drift guard
  `amount_from_str_currency_matches_lexer`, which compares
  `Amount::from_str` with `is_valid_currency` on every string of up to five
  characters over an alphabet covering each class the rule distinguishes,
  plus the shapes that broke.

`Amount::from_str` has one caller, BQL `CONVERT('<n> <cur>', ...)`, a
rustledger extension with no beancount equivalent; it now accepts exactly
the currencies the parser accepts.

Closes #2807

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

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 50.2ms ± 3.9ms 634.2ms ± 10.4ms 12.6x 42.7 MB / 51.0 MB
investment 74.6ms ± 1.3ms 2354.6ms ± 14.7ms 31.5x 59.0 MB / 59.0 MB
fifo 72.9ms ± 1.7ms 13187.7ms ± 63.4ms 181.0x 54.8 MB / 59.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 49.3ms ± 1.6ms 50.2ms ± 3.9ms +1.9% ✅ within noise 41.9 MB → 42.7 MB (+1.8%)
investment 74.7ms ± 1.3ms 74.6ms ± 1.3ms -0.1% ✅ within noise 58.7 MB → 59.0 MB (+0.4%)
fifo 73.0ms ± 1.2ms 72.9ms ± 1.7ms -0.2% ✅ within noise 54.8 MB → 54.8 MB (-0.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 1.9ms, investment 0.8ms, fifo 0.9ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 826
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 4 commits November 6, 2026 12:27
`Amount::from_str` does not resolve from a private item's doc in
`amount.rs` (FromStr is not in scope there), which failed the
private-items documentation job.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A one-letter transaction or posting flag (`T` in `2024-01-16 T "x"`)
lexes as a CURRENCY token, so the parser recorded it in
`currency_occurrences`. With the 2-char minimum gone from the editor
checks, references, highlight, hover, definition and linked editing on a
currency `T` reached every `T` flag, and a `P` flag hovered as
"Currency: P". Rename already did this on main.

- Parser: both walkers leave the flag token out. Red asks
  `Transaction::flag` / `Posting::flag`; green mirrors them in
  `flag_child_index`, pinned by the green/red corpus test.
  `ParseResult::is_flag_at` lets the editor word-scan fallback skip a
  flag.
- LSP: `get_symbol_at_position` takes the handler's `LineIndex` and
  returns no symbol on a flag.
- WASM: the same flag skip, and currency references come from the
  parser's token spans, so `B` on `open Assets:X BRK.B,B` no longer
  lands inside `BRK.B`.
- Drift guard alphabet gains the flag letters `T` and `P`.
- CHANGELOG notes the CONVERT keyword and length changes.

No cache bump: neither the loader nor the WASM cache stores
`currency_occurrences`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…inear

Round 2 review of the flag exclusion.

- `ParseResult::is_flag_at` was true for every flag `Transaction::flag`
  reads, `txn` included, so the editor word-scan fallback returned no
  symbol on `txn` and its keyword hover went blank in the LSP and WASM.
  It is now `is_currency_flag_at`, true only for a one-letter flag that
  lexes as a CURRENCY token. Tests pin every directive keyword's hover
  (and `*` / `!`, which are not words) in both editors.
- The WASM `find_currency_references` rescanned `currency_occurrences`
  from the start for every match. The first-token check now uses a
  binary search and runs only for `commodity` and `price`. A 60k-match
  test takes about 90 ms in a debug build, against about 13 s with the
  old scan.
- Document that metadata currencies get their directive's context.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) November 6, 2026 22:02
@robcohen
robcohen merged commit f4fcdc4 into main Nov 6, 2026
61 of 63 checks passed
@robcohen
robcohen deleted the refactor/currency-canonical branch November 6, 2026 22:02
robcohen added a commit that referenced this pull request Nov 6, 2026
#2874 keeps one-letter transaction and posting flags out of
`ParseResult::currency_occurrences`, which the parser corpus manifest
hashes. On fava/tests_data_example.beancount two `P` flags leave the
list: the header flag of `2012-12-17 P "Payee" "Narration"` (bytes
2263..2264) and the posting flag of `P Expenses:Food` (bytes
2444..2445). Every other field of the canonical payload is
byte-identical, the source hash is unchanged, and the CST manifest does
not move.

Co-authored-by: Claude Opus 5.5 <[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.

refactor: currency-name helpers disagree with the lexer

1 participant