Skip to content

fix(parser): lex an account component with any non-ASCII start, as beancount does - #2908

Merged
robcohen merged 8 commits into
mainfrom
fix/non-ascii-account-start
Nov 10, 2026
Merged

robcohen merged 8 commits into
mainfrom
fix/non-ascii-account-start

Conversation

@robcohen

@robcohen robcohen commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

The beancount rule

beancount 3.2.3, lexer.l:

ACCOUNTTYPE  ([A-Z]|{UTF-8-ONLY})([A-Za-z0-9\-]|{UTF-8-ONLY})*
ACCOUNTNAME  ([A-Z0-9]|{UTF-8-ONLY})([A-Za-z0-9\-]|{UTF-8-ONLY})*
ACCOUNT      {ACCOUNTTYPE}(:{ACCOUNTNAME})+

So any non-ASCII character can start or continue any component. Its grammar then checks every account it lexed (Builder.account) with valid_account_regexp. That check is regex.match (anchored at the start only) of (name_assets|...)(:[\p{Lu}\p{Nd}][\p{L}\p{Nd}\-]*)+, and on failure it reports Invalid account name. This works out to:

  • the root is one of the configured roots. A root name must start with \p{Lu} (is_valid_root, ACC_COMP_TYPE_RE).
  • the first sub-component starts with \p{Lu} or \p{Nd}.
  • because it is a prefix match, the rest of the name, including later components, takes anything the lexer takes.

What changed

  • Lexer (logos_lexer.rs): the Account token follows beancount's rule. There is one documented exception: a BOM does not start an account. It stays the layout-transparent mid-file BOM error token, so the BomInDirectiveBody handling for concatenated files is unchanged. beancount rejects that line too.
  • is_valid_account_name (the canonical rule, still lexer-backed) now also applies beancount's name check: the root starts with \p{Lu}, and the first sub-component starts with \p{Lu} or \p{Nd}. Characters are classified by a small logos enum, so the Unicode tables are the lexer's own. It is the rule for an account a ledger holds: the validator's E1005 (Open check, unknown-account references, metadata and custom values), FFI entry.create, a budget's quoted account and the CLI's --account go through it. Configuration values that beancount checks with its stricter account.is_valid family (the currency_accounts plugin base account, the account_* and name_* options) use the new is_valid_account_name_strict (see "Review round 1").
  • Deliberate deviation kept from [Bug]: rledger format error on Unicode accounts #816 (PR fix: support full Unicode in account names (Cyrillic, CJK, Arabic, etc.) #817): a caseless (\p{Lo}) or titlecase (\p{Lt}) start stays valid, so Assets:日本 and 資産:現金 load. beancount rejects both. This is documented at the function and pinned by tests.
  • Validator and FFI messages now describe the rule.
  • Loader cache v66, WASM cache v87, with the fixture-version notes (WASM v85 went to fix(validate)!: pad from one shared plan as beancount does, and drop E2004 #2898, and loader v65 with WASM v86 to fix(parser)!: require a flag or txn after a transaction's date, as beancount does #2909, while this PR was open), plus a CHANGELOG entry.

bean-check 3.2.3 vs rledger (2024-01-01 open <name>)

Name bean-check main this PR
Assets:٣ ok P0012 invalid token ok
Assets:٣Foo ok P0012 ok
Assets:A٣ ok ok ok
Assets:3 ok ok ok
Assets:Ünï / Assets:Ä ok ok ok
Assets:éclair (lowercase start) Invalid account name P0012 E1005
Assets:日本 (Lo) Invalid account name ok ok (#816 extension)
Assets:Dž (Lt) Invalid account name ok ok (#816 extension)
Assets:😀, Assets:😀A Invalid account name P0012 E1005
Assets:A😀 ok ok ok
Assets:̈A (combining mark start) Invalid account name P0012 E1005
Assets:² (No), Assets:Ⅰ (Nl) Invalid account name P0012 E1005
Assets:A:日本 ok ok ok
Assets:A:éclair, Assets:٣:é ok P0012 ok
Ünï:A (root not configured) Invalid account name E1005 E1005
Équité:A, Équité:٣ with option "name_equity" "Équité" ok ok / P0012 ok
Équité:éclair with that option Invalid account name P0012 E1005
posting to an unopened Assets:éclair Invalid account name + unknown account P0012 E1005

Parse-error parity (scripts/compat-parse-error-parity.py)

Source main this PR
compat 488 / 491 488 / 491
tracked 381 / 384 381 / 384
matrix 50,705 / 66,256 50,705 / 66,256
fuzz 25,312 / 44,192 26,170 / 44,192
all 76,886 / 111,323 77,744 / 111,323

Of the 1,104 pinned mismatches that changed, 938 now match and 166 changed category; 80 inputs that matched now mismatch, so the net gain is 858. The manifest is repinned with --update and --check passes. The 80 are fuzz garbage lines where an account now lexes ahead of an invalid token (e.g. FáTTT晒:<U+1680>\x1b): 61 are recovery cases, where rledger reports the line's recovery error alongside the invalid token while beancount is still in bison error recovery from an earlier line and reports only the invalid token (the existing rl-top-level-line / recovery class), and 12 come from a BOM inside a name (P0026). That BOM behavior predates this PR (open Assets:A\u{feff}B passes bean-check, rledger reports P0026) and is tracked in #2910. No real ledger is affected.

Stray-character matrix

Regenerated with beancount 3.2.3: stray_char_matrix.tsv is byte-identical, so no row moved. All of its inserted characters are ASCII, and the ASCII side of the account rule is unchanged.

Downstream checks

  • Currency vs account: every other token (currency, number, date, keyword, tag, link, key) starts with an ASCII character, so a non-ASCII start is never ambiguous. The ASCII side of the rule is unchanged.
  • Formatter: rledger format output (stdout, stderr and exit code) is byte-identical to main on all 1,136 git-tracked and compat ledgers.
  • LSP: new tests cover references (3 uses, each range is the whole Assets:٣Foo), rename (2 edits) and semantic tokens (one account token, length 11). Completion is string-based over the parsed account list, so it picks the account up.
  • BQL: leaf, parent, root(account, 2) and account_depth on Assets:٣Foo:éx match bean-query.
  • WASM / FFI: both call is_valid_account_name (FFI builds ledger directives, so it takes the ledger rule); the WASM cache is bumped with its loader pin.
  • STRICT parser and CST corpus baselines: unchanged, both pass.

Review round 1

Two call sites had become looser than beancount, because they used the grammar's prefix check where beancount uses its full-match account.is_valid family. Both are fixed with one new canonical check, rustledger_parser::is_valid_account_name_strict, next to is_valid_account_name. It runs is_valid_account_name first, so it is still lexer-backed, and then fully matches every component against beancount's [\p{Lu}\p{Nd}][\p{L}\p{Nd}-]* (\p{Lu} only for the root), using the same logos Unicode tables. It keeps the \p{Lo}/\p{Lt} start of #816 on every component, consistent with the ledger rule, so option "name_liabilities" "負債" stays usable.

Site beancount check Before this round Now
currency_accounts plugin base account account.is_valid, falls back to Equity:CurrencyAccounts "Equity:CA:é" created Equity:CA:é:USD falls back, as bean-query shows
account_* options is_valid_leaf "Conv:😀", "Rounding:éclair", "Conv😀" accepted E7002, as bean-check's Invalid leaf account name
name_* options is_valid_root "A😀" accepted E7008, as bean-check's Invalid root account name

Each verdict was checked against beancount 3.2.3. Accepted on both sides: Equity:٣, Equity:CA:٣x, leaves ٣, Conv:٣, Conv:A-b, and roots Équité, Ünï, É-1. Rejected on both sides: the values in the table, plus Equity:CA:😀, Equity:C😀 and Conv:A_b. Differs only through #816: Equity:CA:日本, leaf 日本 and root 日本.

The other callers take accounts as ledger text, where beancount uses the grammar check, so they keep is_valid_account_name: the validator, FFI entry.create, a budget's quoted account and the CLI's lint --account. beancount calls is_valid_leaf and is_valid_root only from those options, and is_valid from that plugin and from account.walk, which document discovery uses (see round 2).

The LSP's word boundaries were widened in this round; round 2 replaced that approach (see below).

The new tests (strict predicate, plugin, both option kinds, LSP word) each fail with the previous call site. I merged main for #2898, which took WASM cache v85, so this PR moved to WASM v86 then (after #2909, it is loader v66 and WASM v87 with the pin at 66; each version has one note).

Review round 2

  • Document discovery (option "documents"). beancount's find_documents walks the tree with account.walk, which yields only directories whose path passes account.is_valid (after NFKC normalization) and skips every other directory silently. Before this PR no such directory could match an opened account; now one can (Assets:A:éclair). document_discovery.rs now takes a directory only when is_valid_account_name_strict holds for its account path, and otherwise skips it with no document and no warning, as beancount does. The test document_discovery_takes_only_strictly_valid_account_directories opens Assets:A:éclair, Assets:A:B😀, Assets:٣:é and Assets:Ok, with a dated file under each and under Assets/misc. bean-check finds 1 Document (Assets:Ok) with no diagnostics, and so does rledger now. Before this round rledger found 4 and also warned about Assets:misc.
    • NFKC normalization was left out in this round and added in round 3 (see below).
    • Follow-up: rledger doctor directories (cmd/doctor/directories.rs:61) uses its own "first character is uppercase" heuristic instead of this rule.
  • LSP word boundaries. Round 1's is_word_char treated every non-ASCII character as a word character, so in prose 、, 。, NBSP and curly quotes joined words. It is back to its old letters/digits/:/-/_ rule. Whole accounts now come from the parser's token span: a new ParseResult::account_at (the account counterpart of currency_at) is preferred in get_symbol_at_position, and call and type hierarchy now go through get_symbol_at_position too. I dropped round 1's is_account_name_char, since nothing uses it now. New tests cover a whole Assets:A😀̈B symbol, "昼食、渋谷" (both the symbol and the selection range give 昼食) and ; from Assets:Cash、Assets:Bank (gives Assets:Cash). The two prose tests fail with round 1's is_word_char.
  • Removed an em-dash from a doc comment in options.rs.
  • Invalid name_* / account_* option values still being applied is tracked in fix(loader): an invalid name_* or account_* option value is applied; beancount keeps the default #2911 and left out of this PR.

Review round 3

  • Document discovery normalizes like account.walk (significant). The account path built from the directory names is now NFKC-normalized (unicode-normalization, already a workspace dependency) before the strict check. A decomposed Liabilities/Ünï (as macOS stores it) and a fullwidth Expenses/Ok (Expenses:Ok) are found, as in beancount. Round 2 had dropped them silently; on main they only warned. The loader test now covers both cases. bean-check finds Assets:Ok, Expenses:Ok and Liabilities:Ünï with no diagnostics, and rledger matches. The [Bug]: rledger format error on Unicode accounts #816 divergence is noted at the site and pinned in the test: Assets/日本 is discovered here (with open Assets:日本), while beancount skips it.
  • Selection range nesting. Inside an ACCOUNT token the word expansion is skipped and the colon-delimited segment is the innermost range. The word scan crossed : but stopped at an emoji or mark, so open Assets:A😀B at 0:16 gave 16-24 < 16-22 < 16-27. For an account made only of word characters, the scan took the whole token and added no level, so ASCII behavior is unchanged. A new test asserts that every range contains the one before it, at five cursor positions.
  • WASM mirror. rustledger-wasm's get_symbol_at_position now tries account_at first, then currency_at, then the word scan, as the LSP does. It has a test for Assets:A😀̈B at every column.
  • Trailing colon. In both LSP and WASM, a word that starts on an account token is that token, so open Assets:Bank: gives Assets:Bank at columns 16, 27 and 28. Before, column 28 gave Assets:Bank: from the word scan.
  • account_at uses partition_point. A parser test pins that account_occurrences are sorted and non-overlapping, and that the binary search agrees with a linear scan at every byte of a ledger with accounts in every position.
  • CHANGELOG. The entry now covers the discovery change: directories that are valid ledger accounts but fail the strict rule (Assets/A/éclair) are not discovered; NFD and fullwidth names are matched; and lowercase, space and underscore directories lost the rledger-only [Compat]: on-disk documents posted to non-existent accounts trigger "Invalid reference to unknown account" #1434 warning and are now silent, as in beancount. The option documents: discovered documents on accounts only auto_accounts opens are dropped #2649 entry's "skipped with a warning" now says it applies only to strictly valid names (and its em-dash is now a colon).

Each new test fails without its fix.

How to test

New tests, each of which fails without the lexer change:

  • is_valid_account_name_matches_beancount (parser)
  • test_e1005_matches_beancount_on_non_ascii_component_starts (validate)
  • the three *_non_ascii_digit_* LSP tests

The full workspace tests, clippy -D warnings, cargo doc -Dwarnings, cargo fmt --check, the STRICT baselines and the harness --check all pass.

Closes #2906

🤖 Generated with Claude Code

…ancount does

beancount 3.2.3's lexer lets any non-ASCII character start an account
component (`{UTF-8-ONLY}` in ACCOUNTTYPE / ACCOUNTNAME), and its grammar
then checks each account it lexed with `valid_account_regexp`, a
`regex.match` of `(roots)(:[\p{Lu}\p{Nd}][\p{L}\p{Nd}-]*)+`. So
`Assets:٣` and `Assets:٣Foo` are valid there, and `Assets:éclair`,
`Assets:😀` or `Assets:²` are one account token that is an `Invalid
account name`. rledger required every component to start with
`\p{Lu}\p{Lo}\p{Lt}` or an ASCII digit, so valid ledgers using such
names failed to parse.

- Lexer: the Account token is beancount's rule, except that a BOM does
  not start an account (it stays the layout-transparent mid-file BOM
  error).
- `is_valid_account_name` (the canonical rule, still lexer-backed) adds
  beancount's name check: the root starts with `\p{Lu}`, the first
  sub-component with `\p{Lu}` or `\p{Nd}`, and later components take
  anything the lexer takes (the regex is a prefix match). The
  `\p{Lo}`/`\p{Lt}` start from #816 stays accepted, documented. The
  validator reports a rejected name as E1005 through it, as before.
- LSP references, rename and semantic tokens cover such an account.
- Parse-error parity: 77,744 of 111,323 inputs match, from 76,886;
  compat 488 and tracked 381 unchanged. Manifest repinned. The 80 fuzz
  inputs that moved away are garbage lines where an account now lexes
  before an invalid token and rledger reports the line's recovery
  error beside it, while beancount's bison recovery stays quiet.
- Formatter output is byte-identical to main on all 1,136 in-tree and
  compat ledgers; the stray-character matrix regenerates unchanged.

Loader cache v64, WASM cache v85.

Closes #2906

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

codecov Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.93048% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-lsp/src/handlers/utils.rs 96.05% 3 Missing ⚠️
...tes/rustledger-lsp/src/handlers/semantic_tokens.rs 95.23% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 39.0ms ± 2.4ms 477.9ms ± 6.6ms 12.3x 43.0 MB / 51.0 MB
investment 54.6ms ± 1.9ms 1679.4ms ± 38.2ms 30.7x 59.2 MB / 58.9 MB
fifo 51.1ms ± 1.4ms 8710.8ms ± 168.6ms 170.3x 45.1 MB / 58.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 38.2ms ± 2.1ms 39.0ms ± 2.4ms +1.9% ✅ within noise 42.7 MB → 43.0 MB (+0.8%)
investment 56.6ms ± 3.0ms 54.6ms ± 1.9ms -3.5% ✅ within noise 59.0 MB → 59.2 MB (+0.4%)
fifo 51.3ms ± 1.8ms 51.1ms ± 1.4ms -0.4% ✅ within noise 45.0 MB → 45.1 MB (+0.3%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 1.4ms, investment 1.6ms, fifo 1.0ms), 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 9, 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 3 commits November 9, 2026 08:25
…trict rule

Review round 1 on #2908. beancount checks configuration values with
`account.is_valid` / `is_valid_leaf` / `is_valid_root`, a FULL match:
every component starts with `\p{Lu}` (or `\p{Nd}` after the root) and
holds only `[\p{L}\p{Nd}-]`. The grammar's prefix check that
`is_valid_account_name` now mirrors is looser, so two call sites went
looser than beancount:

- the `currency_accounts` plugin took `"Equity:CA:é"` as its base
  account; beancount falls back to `Equity:CurrencyAccounts`.
- the `account_*` options took `"Conv:😀"` and `"Rounding:éclair"`,
  which beancount rejects (`Invalid leaf account name`); the `name_*`
  options took `"A😀"` (`Invalid root account name`).

Add `rustledger_parser::is_valid_account_name_strict` next to
`is_valid_account_name` (it runs that first, so it is still
lexer-backed, then checks every component's start and characters with
the same logos tables), keeping the `\p{Lo}`/`\p{Lt}` start of #816 on
every component. Use it at the plugin and option sites. The other
callers take ledger accounts (validator, FFI builder, budget, CLI
`--account`) and keep the grammar rule, as beancount does.

The LSP's `is_word_char` now takes every character the `Account` token
takes, through a new lexer-backed `is_account_name_char`, so the word
under the cursor is the whole account (`Assets:A😀`, combining marks).

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

# Conflicts:
#	CHANGELOG.md
#	crates/rustledger-validate/tests/validation_integration_test.rs
#	crates/rustledger-wasm/src/cache.rs
clippy's too_long_first_doc_paragraph.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…, and keep LSP words out of prose

Review round 2 on #2908.

- Document discovery: beancount's `find_documents` walks with
  `account.walk`, which yields only directories whose path passes
  `account.is_valid` and skips the rest in silence. Since this PR a
  ledger can open `Assets:A:éclair`, so the plugin found documents
  beancount does not. It now takes a directory only when
  `is_valid_account_name_strict` holds (bean-check: 1 Document of 4 in
  the new loader test, no warning for `Assets/misc`). The NFKC
  normalization `walk` applies is noted, not mirrored (predates #2906).
- LSP: round 1 made `is_word_char` take every non-ASCII character, so
  prose words ran across `、`, `。` and NBSP. It is back to letters,
  digits, `:`, `-` and `_`; `get_symbol_at_position` now prefers the
  parsed account token at the cursor (new `ParseResult::account_at`,
  the counterpart of `currency_at`), and call and type hierarchy go
  through it. The unused `is_account_name_char` is dropped.
- Drop an em-dash from an `options.rs` doc comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen and others added 3 commits November 9, 2026 10:58
… ranges, and read whole accounts in WASM

Review round 3 on #2908.

- Document discovery NFKC-normalizes the account path built from the
  directory names before the strict check, as beancount's
  `account.walk` does, so a decomposed (macOS) `Liabilities/Ünï` and a
  fullwidth `Expenses/Ok` are found again (bean-check: 3 Documents in
  the loader test). The #816 divergence (`Assets/日本` is discovered
  here) is noted and pinned.
- Selection range: no word expansion inside an ACCOUNT token, whose
  colon-delimited segment is the innermost range; the word scan crossed
  `:` but stopped at an emoji, so the ranges did not nest.
- WASM `get_symbol_at_position` prefers `account_at`, as the LSP does.
- LSP and WASM: a word that starts on an account is that account, so
  `open Assets:Bank:` gives `Assets:Bank` past the trailing colon too.
- `account_at` binary-searches the occurrences; a test pins that they
  are sorted and agree with a linear scan.
- CHANGELOG: the discovery change, and the #2649 entry's warning now
  applies only to strictly valid directory names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… scan cannot cross it

Review round 4 on #2908. Right after the trailing colon of
`open Assets:A😀B:` both editors returned `B:`: the token lookup at
the cursor misses (the account ends at the colon) and the backward word
scan stops at the emoji. When the character before the cursor is a
`:`, the account ending there is the symbol, in the LSP and WASM
alike. CHANGELOG gains the editor-side changes of #2906.

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

# Conflicts:
#	crates/rustledger-loader/src/cache.rs
#	crates/rustledger-wasm/src/cache.rs
#	tests/baselines/parse-error-parity.manifest
robcohen added a commit that referenced this pull request Nov 10, 2026
WASM cache v88: v86 is #2905's on main, v87 is claimed by #2908.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit 880e530 into main Nov 10, 2026
73 of 74 checks passed
@robcohen
robcohen deleted the fix/non-ascii-account-start branch November 10, 2026 06:11
robcohen added a commit that referenced this pull request Nov 10, 2026
Brings in #2908 (strict account validator; loader v66, WASM v87),
#2919 and #2924. Keeps this branch at loader v68 / WASM v90 with one
note per version, drops the merged warn_if_invalid_root (rejection now
goes through check_root), and adds the issue's `A😀` root to the
rejected-name tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 10, 2026
Brings in #2919's linear merge_padding_into_sorted (with the
tolerance_multiplier threaded through), #2908 and #2924. WASM cache
v88, loader pin 66.

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.

compat(parser): account components starting with a non-ASCII digit or other non-letter are valid in beancount but rejected

1 participant