Skip to main content

rustledger_parser/
logos_lexer.rs

1//! SIMD-accelerated lexer using Logos.
2//!
3//! This module provides a fast tokenizer for Beancount syntax using the Logos crate,
4//! which generates a DFA-based lexer with SIMD optimizations where available.
5
6use logos::Logos;
7use std::fmt;
8use std::ops::Range;
9
10// The leading-BOM strip happens at the `parse()` entry boundary (see
11// `crate::bom::strip_leading`). By the time the lexer runs, the source
12// is BOM-free at byte 0 by construction. Any U+FEFF byte the lexer
13// encounters is therefore mid-file and unrecognized — logos's default
14// error path emits a `Token::Error` for it, and the parser's existing
15// error classifier (which searches `error_text` for U+FEFF) surfaces
16// the dedicated `ParseErrorKind::BomInDirectiveBody` diagnostic.
17//
18// No BOM-aware lexer callback, no `Token::Bom` variant, and no
19// BOM regex in the Token enum — but the `Err(()) => ...` arm in
20// `tokenize` DOES contain one mid-file-BOM special case: it preserves
21// `at_line_start` and advances `last_newline_end` past leading BOM
22// bytes in the error span, so indented content on the same logical
23// line still emits an `Indent` token. That logic lives in the
24// `apply_err_layout_transparency` helper below and is unit-tested
25// directly (including the multi-BOM coalesced-Err case that logos
26// doesn't produce from real input today but might in the future).
27
28/// A span in the source code (byte offsets).
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct Span {
31    /// Start byte offset (inclusive).
32    pub start: usize,
33    /// End byte offset (exclusive).
34    pub end: usize,
35}
36
37impl From<Range<usize>> for Span {
38    fn from(range: Range<usize>) -> Self {
39        Self {
40            start: range.start,
41            end: range.end,
42        }
43    }
44}
45
46impl From<Span> for Range<usize> {
47    fn from(span: Span) -> Self {
48        span.start..span.end
49    }
50}
51
52/// Token types produced by the Logos lexer.
53///
54/// Horizontal whitespace is emitted as a first-class [`Token::Whitespace`]
55/// token (was previously skipped via `#[logos(skip r"[ \t]+")]`). The
56/// existing [`tokenize`] entry point filters whitespace out for
57/// backward-compat with the AST-style parser; the new
58/// [`tokenize_lossless`] entry point keeps them so the CST can
59/// reconstruct source byte-for-byte. Both paths share the same Logos
60/// implementation — there is exactly one tokenization pass per file.
61#[derive(Logos, Debug, Clone, PartialEq, Eq)]
62pub enum Token<'src> {
63    /// Horizontal whitespace (`[ \t]+`). Significant for the CST and
64    /// for the existing indent post-processing in [`tokenize`]; both
65    /// callers handle this variant.
66    #[regex(r"[ \t]+")]
67    Whitespace(&'src str),
68    // ===== Literals =====
69    /// A date in YYYY-MM-DD, YYYY-M-D, YYYY/MM/DD, or YYYY/M/D format.
70    /// Single-digit month and day are accepted (e.g., 2024-1-5).
71    #[regex(r"\d{4}[-/]\d{1,2}[-/]\d{1,2}")]
72    Date(&'src str),
73
74    /// A number with optional thousands separators and decimals.
75    /// Examples: 123, 1,234.56, 1234.5678, 1. (trailing decimal)
76    /// Negative numbers are handled as unary minus (`-` token + number)
77    /// to allow subtraction expressions like `3-2` to parse correctly.
78    /// Python beancount v3 requires an integer part before the decimal point.
79    /// Leading decimals like `.50` are rejected per the beancount v3 spec.
80    #[regex(r"(\d{1,3}(,\d{3})*|\d+)(\.\d*)?")]
81    Number(&'src str),
82
83    /// A double-quoted string (handles escape sequences).
84    /// The slice includes the quotes.
85    #[regex(r#""([^"\\]|\\.)*""#)]
86    String(&'src str),
87
88    /// An account name like Assets:Bank:Checking, Капитал:Retained-Earnings,
89    /// or 资产:银行:支票.
90    ///
91    /// The first component starts with an uppercase letter (`\p{Lu}`), a
92    /// letter without case like CJK ideographs (`\p{Lo}`), or a titlecase
93    /// letter (`\p{Lt}`). Sub-components may also start with a digit.
94    /// Subsequent characters can be any Unicode letter, digit, or hyphen.
95    ///
96    /// Note: The beancount v3 spec restricts the first character to ASCII
97    /// `[A-Z]`, but this is an artifact of the C flex lexer's poor Unicode
98    /// support, not a meaningful language design choice (see
99    /// beancount/beancount#161, #398, #733).
100    ///
101    /// The account type prefix is validated later against options (`name_assets`, etc.).
102    #[regex(r"[\p{Lu}\p{Lo}\p{Lt}][\p{L}0-9-]*(:([\p{Lu}\p{Lo}\p{Lt}0-9][\p{L}0-9-]*)+)+")]
103    Account(&'src str),
104
105    /// A currency/commodity code like USD, EUR, AAPL, BTC, or single-char tickers like T, V, F.
106    /// Uppercase letters, can contain digits, apostrophes, dots, underscores, hyphens.
107    /// Single-character currencies (e.g., T for AT&T, V for Visa) are valid NYSE/NASDAQ tickers.
108    /// Note: Single-char currencies are disambiguated from transaction flags in the parser.
109    /// Also supports `/` prefix for options/futures contracts (e.g., `/ESM24`, `/LOX21_211204_P100.25`).
110    /// The `/` prefix requires an uppercase letter first to avoid matching `/1.14` as currency.
111    /// Priority 3 ensures Currency wins over Flag for single uppercase letters.
112    #[regex(r"/[A-Z][A-Z0-9'._-]*|[A-Z][A-Z0-9'._-]*", priority = 3)]
113    Currency(&'src str),
114
115    /// A tag like #tag-name.
116    #[regex(r"#[a-zA-Z0-9-_/.]+")]
117    Tag(&'src str),
118
119    /// A link like ^link-name.
120    #[regex(r"\^[a-zA-Z0-9-_/.]+")]
121    Link(&'src str),
122
123    // ===== Keywords =====
124    // Using #[token] for exact matches (higher priority than regex)
125    /// The `txn` keyword for transactions.
126    #[token("txn")]
127    Txn,
128    /// The `balance` directive keyword.
129    #[token("balance")]
130    Balance,
131    /// The `open` directive keyword.
132    #[token("open")]
133    Open,
134    /// The `close` directive keyword.
135    #[token("close")]
136    Close,
137    /// The `commodity` directive keyword.
138    #[token("commodity")]
139    Commodity,
140    /// The `pad` directive keyword.
141    #[token("pad")]
142    Pad,
143    /// The `event` directive keyword.
144    #[token("event")]
145    Event,
146    /// The `query` directive keyword.
147    #[token("query")]
148    Query,
149    /// The `note` directive keyword.
150    #[token("note")]
151    Note,
152    /// The `document` directive keyword.
153    #[token("document")]
154    Document,
155    /// The `price` directive keyword.
156    #[token("price")]
157    Price,
158    /// The `custom` directive keyword.
159    #[token("custom")]
160    Custom,
161    /// The `option` directive keyword.
162    #[token("option")]
163    Option_,
164    /// The `include` directive keyword.
165    #[token("include")]
166    Include,
167    /// The `plugin` directive keyword.
168    #[token("plugin")]
169    Plugin,
170    /// The `pushtag` directive keyword.
171    #[token("pushtag")]
172    Pushtag,
173    /// The `poptag` directive keyword.
174    #[token("poptag")]
175    Poptag,
176    /// The `pushmeta` directive keyword.
177    #[token("pushmeta")]
178    Pushmeta,
179    /// The `popmeta` directive keyword.
180    #[token("popmeta")]
181    Popmeta,
182    /// The `TRUE` boolean literal (also True, true).
183    #[token("TRUE")]
184    #[token("True")]
185    #[token("true")]
186    True,
187    /// The `FALSE` boolean literal (also False, false).
188    #[token("FALSE")]
189    #[token("False")]
190    #[token("false")]
191    False,
192    /// The `NULL` literal.
193    #[token("NULL")]
194    Null,
195
196    // ===== Punctuation =====
197    // Order matters: longer tokens first
198    /// Double left brace `{{` for cost specifications (legacy total cost).
199    #[token("{{")]
200    LDoubleBrace,
201    /// Double right brace `}}` for cost specifications.
202    #[token("}}")]
203    RDoubleBrace,
204    /// Left brace with hash `{#` for total cost (new syntax).
205    #[token("{#")]
206    LBraceHash,
207    /// Left brace `{` for cost specifications.
208    #[token("{")]
209    LBrace,
210    /// Right brace `}` for cost specifications.
211    #[token("}")]
212    RBrace,
213    /// Left parenthesis `(` for expressions.
214    #[token("(")]
215    LParen,
216    /// Right parenthesis `)` for expressions.
217    #[token(")")]
218    RParen,
219    /// Double at-sign `@@` for total cost.
220    #[token("@@")]
221    AtAt,
222    /// At-sign `@` for unit cost.
223    #[token("@")]
224    At,
225    /// Colon `:` separator.
226    #[token(":")]
227    Colon,
228    /// Comma `,` separator.
229    #[token(",")]
230    Comma,
231    /// Tilde `~` for tolerance.
232    #[token("~")]
233    Tilde,
234    /// Pipe `|` for deprecated payee/narration separator.
235    #[token("|")]
236    Pipe,
237    /// Plus `+` operator.
238    #[token("+")]
239    Plus,
240    /// Minus `-` operator.
241    #[token("-")]
242    Minus,
243    /// Star `*` for cleared transactions and multiplication.
244    #[token("*")]
245    Star,
246    /// Slash `/` for division.
247    #[token("/")]
248    Slash,
249
250    // ===== Transaction Flags =====
251    /// Pending flag `!` for incomplete transactions.
252    #[token("!")]
253    Pending,
254
255    /// Other transaction flags: P S T C U R M ? &
256    /// Note: # and % are handled as comments when followed by space
257    #[regex(r"[PSTCURM?&]")]
258    Flag(&'src str),
259
260    // ===== Structural =====
261    /// Newline (significant in Beancount for directive boundaries).
262    #[regex(r"\r?\n")]
263    Newline,
264
265    /// A comment starting with semicolon.
266    /// The slice includes the semicolon.
267    #[regex(r";[^\n\r]*", allow_greedy = true)]
268    Comment(&'src str),
269
270    /// Hash token `#` used as separator in cost specs: `{per_unit # total currency}`
271    /// Note: In Python beancount, `#` is only a comment at the START of a line.
272    /// Mid-line `# text` is NOT a comment - it's either a cost separator or syntax error.
273    /// Start-of-line hash comments are handled in post-processing (tokenize function).
274    #[token("#")]
275    Hash,
276
277    /// A percent comment (ledger-style).
278    /// Python beancount accepts % as a comment character for ledger compatibility.
279    #[regex(r"%[^\n\r]*", allow_greedy = true)]
280    PercentComment(&'src str),
281
282    /// Shebang line at start of file (e.g., #!/usr/bin/env bean-web).
283    /// Treated as a comment-like directive to skip.
284    #[regex(r"#![^\n\r]*", allow_greedy = true)]
285    Shebang(&'src str),
286
287    /// Emacs org-mode directive (e.g., "#+STARTUP: showall").
288    /// These are Emacs configuration lines that should be skipped.
289    #[regex(r"#\+[^\n\r]*", allow_greedy = true)]
290    EmacsDirective(&'src str),
291
292    /// A metadata key (identifier followed by colon).
293    /// Examples: filename:, lineno:, custom-key:, nameOnCard:
294    /// The slice includes the trailing colon. Keys must start with a lowercase ASCII letter
295    /// per the beancount v3 spec. Keys starting with uppercase are rejected.
296    #[regex(r"[a-z][a-zA-Z0-9_-]*:")]
297    MetaKey(&'src str),
298
299    /// Indentation token (inserted by post-processing, not by Logos).
300    /// Contains the number of leading spaces.
301    /// This is a placeholder - actual indentation detection happens in [`tokenize`].
302    Indent(usize),
303
304    /// Deep indentation (3+ spaces) - used for posting-level metadata.
305    DeepIndent(usize),
306
307    /// Error token for unrecognized input.
308    /// Contains the invalid source text for better error messages.
309    Error(&'src str),
310}
311
312impl Token<'_> {
313    /// Returns true if this is a transaction flag (* or !).
314    /// Single-character currencies (e.g., T, P, C) can also be used as flags.
315    pub const fn is_txn_flag(&self) -> bool {
316        match self {
317            Self::Star | Self::Pending | Self::Flag(_) | Self::Hash => true,
318            // Single-char currencies can be used as transaction flags
319            Self::Currency(s) => s.len() == 1,
320            _ => false,
321        }
322    }
323
324    /// Returns true if this is a keyword that starts a directive.
325    pub const fn is_directive_keyword(&self) -> bool {
326        matches!(
327            self,
328            Self::Txn
329                | Self::Balance
330                | Self::Open
331                | Self::Close
332                | Self::Commodity
333                | Self::Pad
334                | Self::Event
335                | Self::Query
336                | Self::Note
337                | Self::Document
338                | Self::Price
339                | Self::Custom
340                | Self::Option_
341                | Self::Include
342                | Self::Plugin
343                | Self::Pushtag
344                | Self::Poptag
345                | Self::Pushmeta
346                | Self::Popmeta
347        )
348    }
349}
350
351impl fmt::Display for Token<'_> {
352    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
353        match self {
354            Self::Date(s) => write!(f, "{s}"),
355            Self::Number(s) => write!(f, "{s}"),
356            Self::String(s) => write!(f, "{s}"),
357            Self::Account(s) => write!(f, "{s}"),
358            Self::Currency(s) => write!(f, "{s}"),
359            Self::Tag(s) => write!(f, "{s}"),
360            Self::Link(s) => write!(f, "{s}"),
361            Self::Txn => write!(f, "txn"),
362            Self::Balance => write!(f, "balance"),
363            Self::Open => write!(f, "open"),
364            Self::Close => write!(f, "close"),
365            Self::Commodity => write!(f, "commodity"),
366            Self::Pad => write!(f, "pad"),
367            Self::Event => write!(f, "event"),
368            Self::Query => write!(f, "query"),
369            Self::Note => write!(f, "note"),
370            Self::Document => write!(f, "document"),
371            Self::Price => write!(f, "price"),
372            Self::Custom => write!(f, "custom"),
373            Self::Option_ => write!(f, "option"),
374            Self::Include => write!(f, "include"),
375            Self::Plugin => write!(f, "plugin"),
376            Self::Pushtag => write!(f, "pushtag"),
377            Self::Poptag => write!(f, "poptag"),
378            Self::Pushmeta => write!(f, "pushmeta"),
379            Self::Popmeta => write!(f, "popmeta"),
380            Self::True => write!(f, "TRUE"),
381            Self::False => write!(f, "FALSE"),
382            Self::Null => write!(f, "NULL"),
383            Self::LDoubleBrace => write!(f, "{{{{"),
384            Self::RDoubleBrace => write!(f, "}}}}"),
385            Self::LBraceHash => write!(f, "{{#"),
386            Self::LBrace => write!(f, "{{"),
387            Self::RBrace => write!(f, "}}"),
388            Self::LParen => write!(f, "("),
389            Self::RParen => write!(f, ")"),
390            Self::AtAt => write!(f, "@@"),
391            Self::At => write!(f, "@"),
392            Self::Colon => write!(f, ":"),
393            Self::Comma => write!(f, ","),
394            Self::Tilde => write!(f, "~"),
395            Self::Pipe => write!(f, "|"),
396            Self::Plus => write!(f, "+"),
397            Self::Minus => write!(f, "-"),
398            Self::Star => write!(f, "*"),
399            Self::Slash => write!(f, "/"),
400            Self::Pending => write!(f, "!"),
401            Self::Flag(s) => write!(f, "{s}"),
402            Self::Whitespace(s) => write!(f, "{s}"),
403            Self::Newline => write!(f, "\\n"),
404            Self::Comment(s) => write!(f, "{s}"),
405            Self::Hash => write!(f, "#"),
406            Self::PercentComment(s) => write!(f, "{s}"),
407            Self::Shebang(s) => write!(f, "{s}"),
408            Self::EmacsDirective(s) => write!(f, "{s}"),
409            Self::MetaKey(s) => write!(f, "{s}"),
410            Self::Indent(n) => write!(f, "<indent:{n}>"),
411            Self::DeepIndent(n) => write!(f, "<deep-indent:{n}>"),
412            Self::Error(s) => {
413                // Strip any embedded U+FEFF bytes (a mid-file BOM
414                // captured into a lexer error span) so diagnostics
415                // rendering this token stay human-readable. LSP problem
416                // panels, CLI stderr, and GitHub-rendered bug reports
417                // all silently drop or strip literal BOM bytes — the
418                // `<BOM>` placeholder makes the failure mode visible.
419                //
420                // Streamed (rather than `s.replace(...)`) so this
421                // Display impl is zero-allocation. LSP problem panels
422                // re-render diagnostics on every keystroke during
423                // interactive editing; a `String` allocation per
424                // render showed up in flame graphs for files with
425                // many BOM-containing Token::Error tokens. The fast
426                // path (no BOM in `s`) is one `f.write_str(s)` call.
427                if s.contains(crate::bom::BOM_CHAR) {
428                    let mut chunks = s.split(crate::bom::BOM_CHAR);
429                    // Interleave chunks with "<BOM>" between them.
430                    // `split` yields N+1 chunks for N matches, so the
431                    // first chunk is emitted as-is and each subsequent
432                    // chunk gets a `<BOM>` prefix. Final output is
433                    // chunk0 + "<BOM>" + chunk1 + "<BOM>" + chunkN —
434                    // matching the (allocating) `s.replace(...)`
435                    // behavior exactly.
436                    if let Some(first) = chunks.next() {
437                        f.write_str(first)?;
438                    }
439                    for chunk in chunks {
440                        f.write_str("<BOM>")?;
441                        f.write_str(chunk)?;
442                    }
443                    Ok(())
444                } else {
445                    f.write_str(s)
446                }
447            }
448        }
449    }
450}
451
452/// Apply mid-file BOM layout-transparency rules to lexer-state from
453/// inside the `Err` arm of `tokenize`.
454///
455/// A mid-file BOM (U+FEFF) is layout-transparent: it produces an
456/// error diagnostic via the parser's classifier, but must NOT clobber
457/// `at_line_start` or move `last_newline_end` past the BOM, otherwise
458/// the next token on the same logical line (e.g. an indented posting
459/// from a concatenated Windows file) loses its indent classification
460/// and the parser mistypes it. Leading-BOM is handled at the
461/// `crate::parse` boundary and never reaches this code path; only
462/// mid-file BOMs that survived the strip do.
463///
464/// We use `trim_start_matches` (rather than `starts_with` + a single
465/// `BOM_LEN` advance) so a multi-BOM run — e.g., a hypothetical
466/// coalesced `\u{FEFF}\u{FEFF}` Err span from a triple-concatenated
467/// Windows file — is ENTIRELY layout-transparent. Advancing
468/// `last_newline_end` past only the first BOM but then clobbering
469/// `at_line_start` because of the second BOM would cascade into
470/// misclassifying the next real token. The contract is: every BOM
471/// byte is layout-transparent; `at_line_start` is preserved iff the
472/// entire error span is BOM bytes; `last_newline_end` advances past
473/// the full run of leading BOMs.
474///
475/// Extracted as a private helper so the multi-BOM defensive code path
476/// can be unit-tested independently of logos's emission strategy.
477/// Today logos emits one Err per unrecognized char, so the coalesced
478/// path is unreachable from real input; the unit tests at the bottom
479/// of this file feed the helper synthetic `invalid_text` values that
480/// exercise the coalesced case directly.
481fn apply_err_layout_transparency(
482    invalid_text: &str,
483    span_start: usize,
484    at_line_start: &mut bool,
485    last_newline_end: &mut usize,
486) {
487    // Round-17 fix: the contract documented above says "every BOM
488    // byte is layout-transparent" — i.e., a span like
489    // `\u{FEFF}@@\u{FEFF}` should classify its non-BOM bytes for the
490    // at_line_start decision, not its BOM bytes. The previous impl
491    // only inspected the LEADING run of BOMs and clobbered
492    // `at_line_start` for any non-empty tail. That sub-case worked
493    // because a coalesced span starting with BOM + non-BOM tail
494    // really does break the indent contract. But a coalesced span
495    // like `@@\u{FEFF}` (non-BOM head followed by BOM tail) would
496    // also clobber — the BOM in the tail is layout-transparent per
497    // contract, but the head is real content so the clobber is
498    // already correct. The genuinely-wrong case (currently
499    // unreachable but reachable under a future logos upgrade that
500    // coalesces error sequences) is when the ENTIRE span is BOMs,
501    // possibly interleaved with whitespace: those should be fully
502    // layout-transparent. We now extract the LEADING run of BOM
503    // bytes for `last_newline_end` advancement, and consult the
504    // FULL invalid_text minus all BOM bytes for the at_line_start
505    // decision.
506    let after_leading_bom = invalid_text.trim_start_matches(crate::bom::BOM_CHAR);
507    let leading_bom_bytes = invalid_text.len() - after_leading_bom.len();
508    if leading_bom_bytes > 0 && *at_line_start && span_start == *last_newline_end {
509        *last_newline_end = span_start + leading_bom_bytes;
510    }
511
512    // Any non-BOM byte ANYWHERE in the span is "real content" for
513    // indent purposes. An all-BOM span (possibly interleaving BOMs
514    // at any position) leaves `at_line_start` untouched. The
515    // previous `is_empty()` check on JUST the after-leading-BOM
516    // tail had a latent gap for a coalesced `@<BOM>` span: the
517    // leading run is empty, so the `else` arm clobbered — which
518    // happens to be correct for that case, but the path was
519    // accidental rather than principled. Walking the whole span
520    // makes the rule explicit.
521    let has_non_bom_byte = invalid_text.chars().any(|c| c != crate::bom::BOM_CHAR);
522    if has_non_bom_byte {
523        *at_line_start = false;
524    }
525}
526
527/// Whether `name` is a valid beancount account name.
528///
529/// This is the CANONICAL account-name rule, shared by every surface that
530/// admits account names (the validator's Open check, the loader's
531/// `account_*`/`name_*` option guards, the FFI directive builder).
532///
533/// Implemented by running the actual lexer and requiring that `name` lex
534/// to exactly one [`Token::Account`] spanning the whole input, so this
535/// predicate CANNOT drift from what the parser accepts: an account name
536/// is valid if and only if it round-trips through the language. (Before
537/// this existed, the validator and loader each hand-implemented the rule
538/// with different accepted character sets, and accounts that could never
539/// be parsed back could enter through synthesized-directive surfaces.)
540///
541/// The rule, per the `Account` token regex: two or more `:`-separated
542/// components; the root starts with an uppercase (`\p{Lu}`), caseless
543/// (`\p{Lo}`), or titlecase (`\p{Lt}`) letter; sub-components may also
544/// start with an ASCII digit; remaining characters are Unicode letters,
545/// ASCII digits, or `-`.
546#[must_use]
547pub fn is_valid_account_name(name: &str) -> bool {
548    let mut lexer = Token::lexer(name);
549    let Some(Ok(Token::Account(_))) = lexer.next() else {
550        return false;
551    };
552    lexer.span() == (0..name.len()) && lexer.next().is_none()
553}
554
555/// Tokenize source code into a vector of (Token, Span) pairs for the
556/// AST-style parser.
557///
558/// Filters out [`Token::Whitespace`] (mid-line horizontal whitespace)
559/// but otherwise emits everything the lexer produces, with
560/// post-processing for line-start `#` comments and indentation.
561/// Callers that need a fully-lossless token stream (the CST builder)
562/// use [`tokenize_lossless`] instead.
563pub fn tokenize(source: &str) -> Vec<(Token<'_>, Span)> {
564    tokenize_inner(source, /* keep_whitespace = */ false)
565}
566
567/// Tokenize source code losslessly: every byte of `source` appears in
568/// exactly one emitted `(Token, Span)` entry. This is the input to
569/// the CST builder.
570///
571/// Differs from [`tokenize`] in that [`Token::Whitespace`] tokens are
572/// preserved (the AST-style parser drops them; the CST keeps them so
573/// the round-trip stays byte-identical).
574pub fn tokenize_lossless(source: &str) -> Vec<(Token<'_>, Span)> {
575    tokenize_inner(source, /* keep_whitespace = */ true)
576}
577
578/// Upper bound on the up-front token-vector reservation (see `tokenize_inner` /
579/// `lossless_kind_tokens`). ~4M entries (~100 MB for a `(kind, span)` tuple) is
580/// far above any real ledger's token count, but stops a pathological input from
581/// turning `source.len() / 4` into a multi-GB reservation.
582pub(crate) const TOKEN_CAPACITY_CAP: usize = 4 << 20;
583
584fn tokenize_inner(source: &str, keep_whitespace: bool) -> Vec<(Token<'_>, Span)> {
585    // Pre-size to avoid reallocation churn. A beancount token averages ~4 bytes
586    // of source (dates, numbers, currencies, whitespace runs), so `len / 4` is a
587    // close estimate of the token count. Profiling showed the unsized `Vec`
588    // reallocating ~17× — the single largest lexer allocation (see the
589    // `profiling` data branch). Capped so a pathological input (e.g. a huge
590    // whitespace/comment run that lexes to few tokens) can't amplify into a
591    // multi-GB up-front reservation — the parser must handle malformed input
592    // gracefully; beyond the cap the `Vec` just grows normally.
593    let mut tokens = Vec::with_capacity((source.len() / 4).min(TOKEN_CAPACITY_CAP));
594    let mut lexer = Token::lexer(source);
595    let mut at_line_start = true;
596    let mut last_newline_end = 0usize;
597
598    while let Some(result) = lexer.next() {
599        let span = lexer.span();
600
601        if !keep_whitespace && matches!(result, Ok(Token::Whitespace(_))) {
602            // AST-path drops mid-line whitespace; the CST path keeps
603            // it. Layout-relevant whitespace (start-of-line indentation,
604            // BOM error spans) is handled by the dedicated arms below
605            // regardless of which path we are on.
606            continue;
607        }
608
609        match result {
610            Ok(Token::Newline) => {
611                tokens.push((Token::Newline, span.clone().into()));
612                at_line_start = true;
613                last_newline_end = span.end;
614            }
615            Ok(Token::Hash) if at_line_start && span.start == last_newline_end => {
616                // Hash at very start of line (no indentation) is a comment
617                // Find end of line and create a comment token for the whole line
618                let comment_start = span.start;
619                let line_end = source[span.end..]
620                    .find('\n')
621                    .map_or(source.len(), |i| span.end + i);
622                let comment_text = &source[comment_start..line_end];
623                tokens.push((
624                    Token::Comment(comment_text),
625                    Span {
626                        start: comment_start,
627                        end: line_end,
628                    },
629                ));
630                // Skip lexer tokens until we reach the newline
631                while let Some(peek_result) = lexer.next() {
632                    let peek_span = lexer.span();
633                    let peek_end = peek_span.end;
634                    if peek_result == Ok(Token::Newline) {
635                        tokens.push((Token::Newline, peek_span.into()));
636                        at_line_start = true;
637                        last_newline_end = peek_end;
638                        break;
639                    }
640                    // Skip other tokens on the comment line
641                }
642            }
643            Ok(token) => {
644                // Check for indentation at line start
645                if at_line_start && span.start > last_newline_end {
646                    // Count leading whitespace between last newline and this token
647                    // Tabs count as indentation (treat 1 tab as 4 spaces for counting purposes)
648                    let leading = &source[last_newline_end..span.start];
649                    let mut space_count = 0;
650                    let mut char_count = 0;
651                    for c in leading.chars() {
652                        match c {
653                            ' ' => {
654                                space_count += 1;
655                                char_count += 1;
656                            }
657                            '\t' => {
658                                space_count += 4; // Treat tab as 4 spaces
659                                char_count += 1;
660                            }
661                            _ => break,
662                        }
663                    }
664                    // Python beancount accepts 1+ space for metadata indentation
665                    if space_count >= 1 {
666                        let indent_start = last_newline_end;
667                        let indent_end = last_newline_end + char_count;
668                        // Use DeepIndent for 3+ spaces (posting metadata level).
669                        // Python beancount allows flexible indentation where posting
670                        // metadata just needs to be more indented than the posting.
671                        // Common patterns: 2-space posting / 4-space meta, or
672                        // 1-space posting / 3-space meta (as in beancount_reds_plugins).
673                        let indent_token = if space_count >= 3 {
674                            Token::DeepIndent(space_count)
675                        } else {
676                            Token::Indent(space_count)
677                        };
678                        tokens.push((
679                            indent_token,
680                            Span {
681                                start: indent_start,
682                                end: indent_end,
683                            },
684                        ));
685                    }
686                }
687                at_line_start = false;
688                tokens.push((token, span.into()));
689            }
690            Err(()) => {
691                // Lexer error - produce an Error token with the invalid source text.
692                let invalid_text = &source[span.clone()];
693                apply_err_layout_transparency(
694                    invalid_text,
695                    span.start,
696                    &mut at_line_start,
697                    &mut last_newline_end,
698                );
699                tokens.push((Token::Error(invalid_text), span.into()));
700            }
701        }
702    }
703
704    tokens
705}
706
707#[cfg(test)]
708mod tests {
709    use super::*;
710
711    #[test]
712    fn test_tokenize_date() {
713        let tokens = tokenize("2024-01-15");
714        assert_eq!(tokens.len(), 1);
715        assert!(matches!(tokens[0].0, Token::Date("2024-01-15")));
716    }
717
718    #[test]
719    fn test_tokenize_date_single_digit_month() {
720        // Single-digit month should be tokenized as Date
721        let tokens = tokenize("2024-1-15");
722        assert_eq!(tokens.len(), 1);
723        assert!(matches!(tokens[0].0, Token::Date("2024-1-15")));
724    }
725
726    #[test]
727    fn test_tokenize_date_single_digit_day() {
728        // Single-digit day should be tokenized as Date
729        let tokens = tokenize("2024-01-5");
730        assert_eq!(tokens.len(), 1);
731        assert!(matches!(tokens[0].0, Token::Date("2024-01-5")));
732    }
733
734    #[test]
735    fn test_tokenize_date_single_digit_month_and_day() {
736        // Single-digit month and day should be tokenized as Date
737        let tokens = tokenize("2024-1-1");
738        assert_eq!(tokens.len(), 1);
739        assert!(matches!(tokens[0].0, Token::Date("2024-1-1")));
740    }
741
742    #[test]
743    fn test_tokenize_date_slash_separator_single_digit() {
744        // Slash separator with single-digit parts
745        let tokens = tokenize("2024/1/5");
746        assert_eq!(tokens.len(), 1);
747        assert!(matches!(tokens[0].0, Token::Date("2024/1/5")));
748    }
749
750    #[test]
751    fn test_tokenize_number() {
752        let tokens = tokenize("1234.56");
753        assert_eq!(tokens.len(), 1);
754        assert!(matches!(tokens[0].0, Token::Number("1234.56")));
755
756        // Negative numbers are now Minus + Number (enables subtraction expressions)
757        let tokens = tokenize("-1,234.56");
758        assert_eq!(tokens.len(), 2);
759        assert!(matches!(tokens[0].0, Token::Minus));
760        assert!(matches!(tokens[1].0, Token::Number("1,234.56")));
761    }
762
763    #[test]
764    fn test_tokenize_account() {
765        let tokens = tokenize("Assets:Bank:Checking");
766        assert_eq!(tokens.len(), 1);
767        assert!(matches!(
768            tokens[0].0,
769            Token::Account("Assets:Bank:Checking")
770        ));
771    }
772
773    #[test]
774    fn test_tokenize_account_unicode() {
775        // Unicode uppercase letters and CJK characters are valid at the
776        // start of account components. Emoji and symbols are not.
777
778        // Non-letter (emoji) after valid ASCII start — still invalid
779        let tokens = tokenize("Assets:CORP✨");
780        assert!(
781            !matches!(tokens[0].0, Token::Account("Assets:CORP✨")),
782            "Unicode emoji in account name should not tokenize as a valid Account"
783        );
784        assert!(
785            tokens.iter().any(|(t, _)| matches!(t, Token::Error(_))),
786            "Unicode emoji should produce at least one Error token"
787        );
788
789        // CJK sub-component start — now valid (CJK ideographs are \p{Lo})
790        let tokens = tokenize("Assets:沪深300");
791        assert!(
792            matches!(tokens[0].0, Token::Account("Assets:沪深300")),
793            "CJK characters at the start of a sub-component should tokenize as Account"
794        );
795
796        // Full CJK sub-component — valid
797        let tokens = tokenize("Assets:日本銀行");
798        assert!(
799            matches!(tokens[0].0, Token::Account("Assets:日本銀行")),
800            "CJK sub-component should tokenize as Account"
801        );
802
803        // Cyrillic account type — valid (Cyrillic uppercase is \p{Lu})
804        let tokens = tokenize("Капитал:Retained");
805        assert!(
806            matches!(tokens[0].0, Token::Account("Капитал:Retained")),
807            "Cyrillic-starting account should tokenize as Account"
808        );
809
810        // Fully CJK account — valid
811        let tokens = tokenize("资产:银行:支票");
812        assert!(
813            matches!(tokens[0].0, Token::Account("资产:银行:支票")),
814            "Fully CJK account should tokenize as Account"
815        );
816    }
817
818    /// Regression for issue #736/#739: Unicode letters AFTER an ASCII start
819    /// in account sub-components are valid per the beancount v3 spec.
820    #[test]
821    fn test_tokenize_account_unicode_letters_after_ascii_start() {
822        // French: É after ASCII start
823        let tokens = tokenize("Assets:Banque-Épargne");
824        assert!(
825            matches!(tokens[0].0, Token::Account("Assets:Banque-Épargne")),
826            "accented Latin letter after ASCII start should tokenize as Account, got: {tokens:?}"
827        );
828
829        // German: ü after ASCII start
830        let tokens = tokenize("Assets:Müller");
831        assert!(
832            matches!(tokens[0].0, Token::Account("Assets:Müller")),
833            "German umlaut after ASCII start should tokenize as Account, got: {tokens:?}"
834        );
835
836        // Mixed CJK after ASCII start — letters are allowed
837        let tokens = tokenize("Assets:CorpJP日本");
838        assert!(
839            matches!(tokens[0].0, Token::Account("Assets:CorpJP日本")),
840            "CJK letters after ASCII start should tokenize as Account, got: {tokens:?}"
841        );
842    }
843
844    #[test]
845    fn test_tokenize_currency() {
846        let tokens = tokenize("USD");
847        assert_eq!(tokens.len(), 1);
848        assert!(matches!(tokens[0].0, Token::Currency("USD")));
849    }
850
851    #[test]
852    fn test_tokenize_single_char_currency() {
853        // Single-char NYSE/NASDAQ tickers: T (AT&T), V (Visa), F (Ford), X (US Steel)
854        let tokens = tokenize("T");
855        assert_eq!(tokens.len(), 1);
856        assert!(matches!(tokens[0].0, Token::Currency("T")));
857
858        let tokens = tokenize("V");
859        assert_eq!(tokens.len(), 1);
860        assert!(matches!(tokens[0].0, Token::Currency("V")));
861
862        let tokens = tokenize("F");
863        assert_eq!(tokens.len(), 1);
864        assert!(matches!(tokens[0].0, Token::Currency("F")));
865    }
866
867    #[test]
868    fn test_single_char_currency_is_txn_flag() {
869        // Single-char currencies should be recognized as potential transaction flags
870        let token = Token::Currency("T");
871        assert!(token.is_txn_flag());
872
873        // Multi-char currencies should NOT be transaction flags
874        let token = Token::Currency("USD");
875        assert!(!token.is_txn_flag());
876    }
877
878    #[test]
879    fn test_tokenize_string() {
880        let tokens = tokenize(r#""Hello, World!""#);
881        assert_eq!(tokens.len(), 1);
882        assert!(matches!(tokens[0].0, Token::String(r#""Hello, World!""#)));
883    }
884
885    #[test]
886    fn test_tokenize_keywords() {
887        let tokens = tokenize("txn balance open close");
888        assert_eq!(tokens.len(), 4);
889        assert!(matches!(tokens[0].0, Token::Txn));
890        assert!(matches!(tokens[1].0, Token::Balance));
891        assert!(matches!(tokens[2].0, Token::Open));
892        assert!(matches!(tokens[3].0, Token::Close));
893    }
894
895    #[test]
896    fn test_tokenize_tag_and_link() {
897        let tokens = tokenize("#my-tag ^my-link");
898        assert_eq!(tokens.len(), 2);
899        assert!(matches!(tokens[0].0, Token::Tag("#my-tag")));
900        assert!(matches!(tokens[1].0, Token::Link("^my-link")));
901    }
902
903    #[test]
904    fn test_tokenize_comment() {
905        let tokens = tokenize("; This is a comment");
906        assert_eq!(tokens.len(), 1);
907        assert!(matches!(tokens[0].0, Token::Comment("; This is a comment")));
908    }
909
910    #[test]
911    fn test_tokenize_indentation() {
912        let tokens = tokenize("txn\n  Assets:Bank 100 USD");
913        // Should have: Txn, Newline, Indent, Account, Number, Currency
914        assert!(tokens.iter().any(|(t, _)| matches!(t, Token::Indent(_))));
915    }
916
917    /// `Token::Error`'s Display impl strips embedded BOM bytes — if a
918    /// mid-file U+FEFF gets captured into a lexer error span, the
919    /// diagnostic still renders human-readably. The leading-BOM case
920    /// is handled at the `crate::parse` boundary (see `crate::bom`),
921    /// so this defensive measure only matters for mid-file BOMs that
922    /// fall into the lexer's default error path.
923    #[test]
924    fn test_display_token_error_strips_embedded_bom() {
925        let payload = "foo\u{FEFF}bar";
926        let s = format!("{}", Token::Error(payload));
927        assert_eq!(s, "foo<BOM>bar");
928        assert!(!s.contains(crate::bom::BOM_CHAR));
929    }
930
931    /// A mid-file BOM (any U+FEFF not at strict byte 0) reaches the
932    /// lexer with no special handling — there is no BOM regex on the
933    /// Token enum anymore. Logos's default error path emits `Token::Error`
934    /// for the unrecognized byte; the parser's error classifier (which
935    /// searches `error_text` for U+FEFF) surfaces the dedicated
936    /// diagnostic on the parser side. This test pins the lexer side:
937    /// some `Token::Error` appears in the stream containing the BOM byte.
938    #[test]
939    fn test_tokenize_mid_file_bom_falls_into_error_path() {
940        // Note: this test calls `tokenize` directly with the BOM byte
941        // present in the source — it does NOT go through `parse`, which
942        // would have stripped a strict-byte-0 BOM. So we put the BOM
943        // mid-source to bypass the strip.
944        let source = "2024-01-01 open Assets:Bank USD\n\u{FEFF}";
945        let tokens = tokenize(source);
946        let has_bom_in_error = tokens.iter().any(|(t, _)| {
947            if let Token::Error(s) = t {
948                s.contains(crate::bom::BOM_CHAR)
949            } else {
950                false
951            }
952        });
953        assert!(
954            has_bom_in_error,
955            "mid-file BOM should fall into `Token::Error`, got: {tokens:?}"
956        );
957    }
958
959    /// Layout-transparency contract for mid-file BOM: a BOM at line
960    /// start followed by indented content (the
961    /// `cat windows-a.bean windows-b.bean` concatenation case) must
962    /// NOT swallow the indent on the next token. The Err arm in
963    /// `tokenize` recognizes `Token::Error("\u{FEFF}")` and preserves
964    /// `at_line_start` + advances `last_newline_end` so the next
965    /// real token still gets its `Token::Indent` emission.
966    ///
967    /// Without this special case, the Err arm sets `at_line_start =
968    /// false` like for any other lex error, the indented posting
969    /// fails to produce an Indent token, and the parser misclassifies
970    /// the posting as a top-level directive — producing cascading
971    /// errors instead of the targeted BOM diagnostic.
972    #[test]
973    fn test_mid_file_bom_at_line_start_preserves_following_indent() {
974        // First a directive, then newline, then mid-file BOM, then
975        // indented posting-like content. `tokenize` is called directly
976        // (bypassing parse's strip-at-entry) so the BOM is mid-file.
977        let source = "2024-01-01 open Assets:Bank USD\n\u{FEFF}  meta-key: \"v\"\n";
978        let tokens = tokenize(source);
979        // The Token::Error for the BOM must be present.
980        let has_bom_error = tokens.iter().any(|(t, _)| {
981            if let Token::Error(s) = t {
982                *s == crate::bom::BOM
983            } else {
984                false
985            }
986        });
987        assert!(
988            has_bom_error,
989            "expected Token::Error(\"\\u{{FEFF}}\") in stream, got: {tokens:?}"
990        );
991        // Critically: the indent for the 2-space metadata line must
992        // survive — it should be a Token::Indent(2), not absorbed.
993        let has_indent_2 = tokens.iter().any(|(t, _)| matches!(t, Token::Indent(2)));
994        assert!(
995            has_indent_2,
996            "mid-file BOM at line start must not swallow the following Indent; got: {tokens:?}"
997        );
998        // And the metadata key tokenizes normally on the same line.
999        assert!(
1000            tokens
1001                .iter()
1002                .any(|(t, _)| matches!(t, Token::MetaKey("meta-key:"))),
1003            "expected MetaKey after BOM-prefixed indent, got: {tokens:?}"
1004        );
1005    }
1006
1007    /// Consecutive BOMs at line start (logos emits each as its own
1008    /// Err) ALL preserve layout-transparency. The Err arm uses
1009    /// `trim_start_matches(BOM_CHAR)` to find non-BOM content, so a
1010    /// triple-concatenated Windows file producing `\n\u{FEFF}\u{FEFF}`
1011    /// at line start, followed by indented content, still emits the
1012    /// `Indent` for the metadata line. Without the `trim_start_matches`
1013    /// approach (using a single-BOM length check instead), the second
1014    /// BOM would either not advance `last_newline_end` correctly or
1015    /// would clobber `at_line_start`, breaking the indent walk on the
1016    /// next real token.
1017    #[test]
1018    fn test_consecutive_mid_file_boms_preserve_layout() {
1019        let source = "2024-01-01 open Assets:Bank USD\n\u{FEFF}\u{FEFF}  meta-key: \"v\"\n";
1020        let tokens = tokenize(source);
1021        // Both BOMs should appear as Token::Error.
1022        let bom_error_count = tokens
1023            .iter()
1024            .filter(|(t, _)| matches!(t, Token::Error(s) if *s == crate::bom::BOM))
1025            .count();
1026        assert_eq!(
1027            bom_error_count, 2,
1028            "expected 2 Token::Error(BOM) tokens, got: {tokens:?}"
1029        );
1030        // And the indent on the line containing the BOMs must survive.
1031        let has_indent_2 = tokens.iter().any(|(t, _)| matches!(t, Token::Indent(2)));
1032        assert!(
1033            has_indent_2,
1034            "consecutive mid-file BOMs at line start must not swallow following indent; \
1035             got: {tokens:?}"
1036        );
1037        assert!(
1038            tokens
1039                .iter()
1040                .any(|(t, _)| matches!(t, Token::MetaKey("meta-key:"))),
1041            "expected MetaKey after consecutive-BOM-prefixed indent, got: {tokens:?}"
1042        );
1043    }
1044
1045    // ===== Direct tests of `apply_err_layout_transparency` =====
1046    //
1047    // These tests exercise the helper independently of logos's
1048    // emission strategy. Today logos emits one Err per unrecognized
1049    // char, so the multi-BOM-in-one-Err code path (the
1050    // `trim_start_matches` loop's motivating case) is unreachable
1051    // from real input. The tests below feed the helper synthetic
1052    // invalid_text values so the defensive code is actually
1053    // validated rather than documentation-only.
1054
1055    /// Coalesced double-BOM at line start: must advance
1056    /// `last_newline_end` past BOTH bytes and keep `at_line_start`.
1057    /// Pins the contract `trim_start_matches` exists to provide.
1058    #[test]
1059    fn err_layout_transparency_coalesced_double_bom_at_line_start() {
1060        let invalid_text = "\u{FEFF}\u{FEFF}";
1061        let span_start = 10;
1062        let mut at_line_start = true;
1063        let mut last_newline_end = 10;
1064        apply_err_layout_transparency(
1065            invalid_text,
1066            span_start,
1067            &mut at_line_start,
1068            &mut last_newline_end,
1069        );
1070        assert!(
1071            at_line_start,
1072            "all-BOM error span must preserve at_line_start"
1073        );
1074        assert_eq!(
1075            last_newline_end,
1076            10 + 2 * crate::bom::BOM_LEN,
1077            "last_newline_end must advance past BOTH BOMs, not just the first"
1078        );
1079    }
1080
1081    /// Coalesced BOM + trailing content: `at_line_start` clobbers (real
1082    /// content follows the BOM run); `last_newline_end` still
1083    /// advances past the BOM portion only.
1084    #[test]
1085    fn err_layout_transparency_coalesced_bom_with_trailing_content() {
1086        let invalid_text = "\u{FEFF}\u{FEFF}xyz";
1087        let span_start = 10;
1088        let mut at_line_start = true;
1089        let mut last_newline_end = 10;
1090        apply_err_layout_transparency(
1091            invalid_text,
1092            span_start,
1093            &mut at_line_start,
1094            &mut last_newline_end,
1095        );
1096        assert!(
1097            !at_line_start,
1098            "trailing non-BOM content must clobber at_line_start"
1099        );
1100        assert_eq!(
1101            last_newline_end,
1102            10 + 2 * crate::bom::BOM_LEN,
1103            "last_newline_end advances past leading BOMs, NOT past trailing content"
1104        );
1105    }
1106
1107    /// Non-BOM error: standard clobber.
1108    #[test]
1109    fn err_layout_transparency_non_bom_clobbers() {
1110        let invalid_text = "garbage";
1111        let mut at_line_start = true;
1112        let mut last_newline_end = 10;
1113        apply_err_layout_transparency(invalid_text, 10, &mut at_line_start, &mut last_newline_end);
1114        assert!(!at_line_start);
1115        assert_eq!(last_newline_end, 10, "non-BOM error must not advance");
1116    }
1117
1118    /// All-BOM error span but NOT at line start (e.g., BOM appears
1119    /// mid-line after some content): `at_line_start` was already
1120    /// false, the inner advance guard fails, and nothing changes.
1121    #[test]
1122    fn err_layout_transparency_all_bom_not_at_line_start_is_noop() {
1123        let invalid_text = "\u{FEFF}\u{FEFF}";
1124        let span_start = 20;
1125        let mut at_line_start = false; // mid-line
1126        let mut last_newline_end = 10;
1127        apply_err_layout_transparency(
1128            invalid_text,
1129            span_start,
1130            &mut at_line_start,
1131            &mut last_newline_end,
1132        );
1133        assert!(!at_line_start);
1134        assert_eq!(last_newline_end, 10, "guard prevents stale advance");
1135    }
1136
1137    /// Complementary to the previous test: the inner `at_line_start &&
1138    /// span_start == last_newline_end` guard has two clauses. The
1139    /// `*_not_at_line_start_*` test above exercises the first
1140    /// (`at_line_start = false`); THIS test pins the second
1141    /// (span doesn't begin at `last_newline_end`).
1142    ///
1143    /// Without exercising both clauses independently, a refactor that
1144    /// flipped `&&` to `||` would not be caught — either clause alone
1145    /// suffices to suppress the advance.
1146    #[test]
1147    fn err_layout_transparency_all_bom_span_mismatch_is_noop() {
1148        let invalid_text = "\u{FEFF}\u{FEFF}";
1149        // at_line_start IS true (the first clause's condition holds)…
1150        let mut at_line_start = true;
1151        // …but span_start (20) != last_newline_end (10), so the
1152        // second clause's condition fails. Combined: the advance
1153        // must NOT fire.
1154        let span_start = 20;
1155        let mut last_newline_end = 10;
1156        apply_err_layout_transparency(
1157            invalid_text,
1158            span_start,
1159            &mut at_line_start,
1160            &mut last_newline_end,
1161        );
1162        assert!(
1163            at_line_start,
1164            "all-BOM error span must preserve at_line_start regardless of span-vs-last-newline match"
1165        );
1166        assert_eq!(
1167            last_newline_end, 10,
1168            "span_start != last_newline_end must prevent stale advance"
1169        );
1170    }
1171
1172    /// Round-17/18: the contract "every BOM byte is layout-
1173    /// transparent" covers BOMs at ANY position in a coalesced error
1174    /// span, not just the leading run. Pre-round-17 the
1175    /// implementation only inspected the leading BOM run for the
1176    /// `at_line_start` decision — a coalesced span like
1177    /// `@@<BOM>` (non-BOM head, BOM tail) was clobbered by the
1178    /// leading-only logic even though the trailing BOM should have
1179    /// been transparent (and the leading `@@` would correctly
1180    /// clobber on its own). The fixed implementation walks the
1181    /// whole span: ANY non-BOM byte clobbers; only an all-BOM span
1182    /// (in any arrangement) preserves `at_line_start`.
1183    ///
1184    /// These tests cover the interleaved shapes the round-17
1185    /// contract claims to handle: BOM-only-tail, BOM-in-middle,
1186    /// and the recently-flagged "BOM-only in any arrangement"
1187    /// preservation guarantee.
1188    #[test]
1189    fn err_layout_transparency_bom_only_in_any_arrangement_preserves() {
1190        // All-BOM coalesced span — preserves at_line_start AND
1191        // advances last_newline_end past the leading run.
1192        let mut at_line_start = true;
1193        let mut last_newline_end = 10;
1194        apply_err_layout_transparency(
1195            "\u{FEFF}\u{FEFF}",
1196            10, // span_start == last_newline_end → advance fires
1197            &mut at_line_start,
1198            &mut last_newline_end,
1199        );
1200        assert!(at_line_start, "all-BOM span preserves at_line_start");
1201        assert_eq!(
1202            last_newline_end, 16,
1203            "leading BOM run advances last_newline_end past both BOM bytes \
1204             (each BOM is 3 UTF-8 bytes)"
1205        );
1206    }
1207
1208    /// Non-BOM head clobbers `at_line_start`. Pre-round-17 also did
1209    /// this (correctly); pinning prevents a regression that re-
1210    /// introduces a BOM-only-trim that misses non-BOM head bytes.
1211    #[test]
1212    fn err_layout_transparency_non_bom_head_clobbers() {
1213        let mut at_line_start = true;
1214        let mut last_newline_end = 0;
1215        apply_err_layout_transparency("@@\u{FEFF}", 10, &mut at_line_start, &mut last_newline_end);
1216        assert!(
1217            !at_line_start,
1218            "non-BOM head ('@@') clobbers at_line_start regardless of trailing BOM"
1219        );
1220    }
1221
1222    /// BOM head + non-BOM tail clobbers (because of the tail).
1223    /// Pre-round-17 the leading-only logic was correct here too;
1224    /// pinning ensures no regression that flips to leading-only.
1225    #[test]
1226    fn err_layout_transparency_bom_head_non_bom_tail_clobbers() {
1227        let mut at_line_start = true;
1228        let mut last_newline_end = 10;
1229        apply_err_layout_transparency("\u{FEFF}@@", 10, &mut at_line_start, &mut last_newline_end);
1230        assert!(
1231            !at_line_start,
1232            "non-BOM tail ('@@') clobbers at_line_start even though span starts with BOM"
1233        );
1234        assert_eq!(
1235            last_newline_end, 13,
1236            "leading BOM run STILL advances last_newline_end past the BOM"
1237        );
1238    }
1239
1240    /// Non-BOM in the middle of a BOM-flanked span clobbers. THIS
1241    /// is the case the round-17 docstring specifically claimed to
1242    /// cover; pre-round-17 the same outcome held (leading BOMs
1243    /// trimmed, non-empty tail clobbered) but only by accident.
1244    /// The fixed `has_non_bom_byte = chars().any(|c| c != BOM)`
1245    /// walks the whole span and makes the case explicit.
1246    #[test]
1247    fn err_layout_transparency_bom_flanking_non_bom_clobbers() {
1248        let mut at_line_start = true;
1249        let mut last_newline_end = 10;
1250        apply_err_layout_transparency(
1251            "\u{FEFF}@@\u{FEFF}",
1252            10,
1253            &mut at_line_start,
1254            &mut last_newline_end,
1255        );
1256        assert!(
1257            !at_line_start,
1258            "non-BOM middle ('@@') clobbers at_line_start"
1259        );
1260        assert_eq!(
1261            last_newline_end, 13,
1262            "leading BOM run advances last_newline_end past the leading BOM only"
1263        );
1264    }
1265
1266    #[test]
1267    fn test_tokenize_transaction_line() {
1268        let source = "2024-01-15 * \"Grocery Store\" #food\n  Expenses:Food 50.00 USD";
1269        let tokens = tokenize(source);
1270
1271        // Check key tokens are present
1272        assert!(tokens.iter().any(|(t, _)| matches!(t, Token::Date(_))));
1273        assert!(tokens.iter().any(|(t, _)| matches!(t, Token::Star)));
1274        assert!(tokens.iter().any(|(t, _)| matches!(t, Token::String(_))));
1275        assert!(tokens.iter().any(|(t, _)| matches!(t, Token::Tag(_))));
1276        assert!(tokens.iter().any(|(t, _)| matches!(t, Token::Newline)));
1277        assert!(
1278            tokens
1279                .iter()
1280                .any(|(t, _)| matches!(t, Token::Indent(_) | Token::DeepIndent(_)))
1281        );
1282        assert!(tokens.iter().any(|(t, _)| matches!(t, Token::Account(_))));
1283        assert!(tokens.iter().any(|(t, _)| matches!(t, Token::Number(_))));
1284        assert!(tokens.iter().any(|(t, _)| matches!(t, Token::Currency(_))));
1285    }
1286
1287    #[test]
1288    fn test_tokenize_metadata_key() {
1289        let tokens = tokenize("filename:");
1290        assert_eq!(tokens.len(), 1);
1291        assert!(matches!(tokens[0].0, Token::MetaKey("filename:")));
1292    }
1293
1294    #[test]
1295    fn test_tokenize_punctuation() {
1296        let tokens = tokenize("{ } @ @@ , ~");
1297        let token_types: Vec<_> = tokens.iter().map(|(t, _)| t.clone()).collect();
1298        assert!(token_types.contains(&Token::LBrace));
1299        assert!(token_types.contains(&Token::RBrace));
1300        assert!(token_types.contains(&Token::At));
1301        assert!(token_types.contains(&Token::AtAt));
1302        assert!(token_types.contains(&Token::Comma));
1303        assert!(token_types.contains(&Token::Tilde));
1304    }
1305
1306    #[test]
1307    fn is_valid_account_name_matches_lexer_rule() {
1308        use super::is_valid_account_name as ok;
1309        // Valid: standard, unicode roots/components, digit-start SUB-component,
1310        // hyphens, deep nesting.
1311        assert!(ok("Assets:Cash"));
1312        assert!(ok("Assets:US:BofA:Checking"));
1313        assert!(ok("Assets:2024-Bonus"));
1314        assert!(ok("Активы:Наличные")); // Cyrillic (\p{Lu} root)
1315        assert!(ok("資産:現金")); // CJK (\p{Lo} root)
1316        assert!(ok("Assets:Ægir")); // non-ASCII uppercase start
1317        // Invalid: single component (roots alone are not accounts).
1318        assert!(!ok("Assets"));
1319        // Invalid: digit-start ROOT (sub-components may, roots may not).
1320        assert!(!ok("1Assets:Cash"));
1321        // Invalid: lowercase starts (ASCII and non-ASCII).
1322        assert!(!ok("assets:Cash"));
1323        assert!(!ok("Assets:cash"));
1324        assert!(!ok("Assets:\u{e9}cash")); // é — lowercase letter start
1325        // Invalid: characters outside letters/digits/hyphen.
1326        assert!(!ok("Assets:Ca sh"));
1327        assert!(!ok("Assets:Cash!"));
1328        assert!(!ok("Assets:N\u{2116}1")); // № (numero sign, So)
1329        assert!(!ok("Assets:Cash\u{1F600}")); // emoji
1330        assert!(!ok("Assets:Ca_sh")); // underscore is currency-only
1331        // Invalid: structural.
1332        assert!(!ok(""));
1333        assert!(!ok("Assets:"));
1334        assert!(!ok(":Cash"));
1335        assert!(!ok("Assets::Cash"));
1336        assert!(!ok(" Assets:Cash"));
1337        assert!(!ok("Assets:Cash "));
1338        assert!(!ok("Assets:Cash\nAssets:Two"));
1339    }
1340}