Repository navigation
refactor: route currency-name checks through the lexer's rule - #2874
Merged
Merged
Conversation
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]>
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Contributor
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
`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]>
…onical # Conflicts: # CHANGELOG.md
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
enabled auto-merge (squash)
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed
Every currency-name check now follows the lexer's own
Currencyrule (#2807, canonical-function discipline).is_currency_likecalls the lexer-backedrustledger_parser::is_valid_currency. The LSP'sis_currency_like_simple(2 to 5 uppercase characters) is removed; hover and completion-resolve ask the canonical instead.ParseResult::currency_at(offset)returns the parser's currency token at a byte offset. The LSP'sget_symbol_at_positionand the WASM editor's equivalent use it before the old word scan. The word scan stopped at/and., so on/6Jit saw only6J. 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/6Jand onBRK.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_commoditystays a deliberate copy and is documented at both sites:/[A-Z0-9'._-]*[A-Z]([A-Z0-9'._-]*[A-Z0-9])?|[A-Z]([A-Z0-9'._-]*[A-Z0-9])?, minus theTRUE/FALSE/NULLkeywords.is_valid_currencyname each other and give a revisit condition.amount_from_str_currency_matches_lexer(inrustledger-parser) comparesAmount::from_strwithis_valid_currencyon every string of up to 5 characters overA T P 0 ' . _ - / a : É(TandPare flag letters). It also checks the issue's shapes (/6J,/ESM24,USD_,A,C_,HOOL'), each one-letter flag letterPSTCURM, and the keywords.Behavior notes
Amount::from_strnow accepts/6Jand/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 BQLCONVERT('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.Amountparsing I checked: plugins and the FFI do not callAmount::from_str.rledger add'sparse_amount(crates/rustledger/src/cmd/add_cmd/parsing.rs) has its ownis_currency_charsplitter and does not validate the currency at all. It is left alone here and is a candidate follow-up.T) as a currency, because the lexer does. A one-letter transaction or posting flag is not one (see Review round 1).CONVERT's string form now rejectsTRUE,FALSEandNULLas 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
I ran tests for core, parser, LSP, WASM and query (
--all-features), plus clippy-D warnings,cargo doc -Dwarnings,cargo fmt --checkandcargo check -p rustledger-wasm --target wasm32-unknown-unknown.Closes #2807
Review round 1
Transaction flags were counted as currencies (significant). A one-letter flag (
Tin2024-01-16 T "Transfer",Pbefore a posting's account) lexes as aCURRENCYtoken, and the parser recorded it incurrency_occurrences. Once the 2-character minimum was gone, references, highlight, hover, definition and linked editing on a currencyTalso hit theTflag. Hovering aPflag showed "Currency: P" even with no such currency. Rename already had this bug on main.Transaction::flag/Posting::flagdirectly. The green walker mirrors those two accessors inflag_child_index, and the comments at both sites point to each other.parse_green_eq_red_corpusgains five flag shapes, andfuzz_green_eq_redalready comparescurrency_occurrences. Thecurrency_occurrencesrustdoc states the rule.ParseResult::is_flag_at(offset)(renamedis_currency_flag_atand 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.Tflag next to a currencyT, plusPflags with no currencyP. LSP: references, document highlight, linked editing, hover, rename (prepare and edits), go-to-definition, andget_symbol_at_positionon UTF-16 and UTF-8. WASM: references, hover, definition and the symbol lookup. Parser:currency_occurrences(green and red) andis_flag_at, with and without a BOM.ParsedLedgerPayload,LedgerPayload) storescurrency_occurrences. The loader parses withparse_without_occurrences, and WASMfromCachereparses 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
TandP, and the named shapes include every flag letterPSTCURMplusTT. If a lexer change let a flag token beatCurrencyfor 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_referencesnow walks the parser's currency token spans, as the LSP does. It no longer runs a text search per directive line, so aBonopen Assets:X BRK.B,Bno longer lands insideBRK.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) andis_definitionare kept, and new tests pin them.Duplicate
LineIndex.get_symbol_at_positionnow takes the handler'sLineIndex. 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-depsand the--all-features --document-private-itemsvariant,cargo fmt --check,cargo check -p rustledger-wasm --target wasm32-unknown-unknown.Review round 2
txnkeyword hover regressed (significant).is_flag_atreturned true for every flag thatTransaction::flagreads, includingTXN_KW. So the word-scan fallback in both editors returned no symbol ontxn, and hover never reached the keyword info. Main shows "## Transaction" at characters 12-13 of2024-01-03 txn "Broker" "Buy"; this PR showed nothing.ParseResult::is_currency_flag_at. It is now true only for a one-letter flag that lexes as aCURRENCYtoken.*,!,#,FLAGletters andtxnare false: none of them can be read as a currency, andtxnhas to stay a word for its keyword hover. The rustdoc says so, and so do the LSP and WASMget_symbol_at_positiondocs.test_hover_keywords_unchanged_by_flag_skip(LSP) andtest_get_hover_info_keywords_unchanged_by_flag_skip(WASM).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.txncase 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.is_currency_flag_atis false ontxn,*and!flags.WASM currency references were quadratic (significant). For every match,
first_in_holderscannedcurrency_occurrencesfrom the start. It now usespartition_pointon span start, which works because occurrences are in source order, and it runs only forcommodityandpriceholders. New testtest_get_references_currency_is_not_quadratic: 60k matches acrosscommodity,price,openand 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_referencesnow documents that a metadata currency gets its directive's context: "commodity" (not a definition) inside acommodity, and "price amount" inside aprice.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-depsand the--all-features --document-private-itemsvariant,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