1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//! Canonical UTF-8 BOM handling — single source of truth.
//!
//! # Why this module exists
//!
//! Earlier iterations spread BOM-aware logic across three layers:
//!
//! 1. A `bom_filter` callback on the lexer that decided which BOMs were
//! "leading" (skip) vs. "mid-file" (emit as an error token).
//! 2. An indent-walker arm in `tokenize()` that tried to keep mid-file
//! BOMs layout-transparent by adjusting `last_newline_end`.
//! 3. A `source.starts_with('\u{FEFF}')` check in `format_source` to
//! decide whether to re-prepend a BOM on output.
//!
//! Each of those three encoded the same concept ("the source had a
//! leading BOM") with a different predicate. Every round-trip-fidelity
//! bug we hit traced back to two of them disagreeing — most recently a
//! pair of regressions where the lexer accepted a leading-whitespace-
//! then-BOM input but the formatter dropped the BOM on output.
//!
//! # The architecture
//!
//! A UTF-8 BOM is a *serialization* concern, not a *parsing* concern.
//! It carries no semantic meaning to beancount. So:
//!
//! * `strip_leading` runs ONCE at the parser's public entry. The lexer,
//! parser, indent walker, and every other internal layer operate on a
//! source that is BOM-free by construction.
//! * The parser records whether a BOM was stripped in
//! `ParseResult::has_leading_bom`. That flag is the *only* source of
//! truth downstream. No layer inspects the BOM byte directly.
//! * `restore_leading` runs ONCE at the formatter's public exit, gated
//! on the flag, restoring byte-stable round-trip identity.
//!
//! # Mid-file BOMs
//!
//! Because the leading BOM is stripped before lexing, any U+FEFF byte
//! the lexer encounters is by construction mid-file and unrecognized.
//! Logos produces a `Token::Error` for it, and the parser's existing
//! error classifier (`error_text.contains('\u{FEFF}')`) surfaces the
//! dedicated diagnostic.
//!
//! # Span coordinates
//!
//! The parser preserves the *original-source* coordinate frame for all
//! spans it returns: if a directive starts at byte 3 of the original
//! source (because the file began with a 3-byte BOM), its span starts
//! at 3. The parser shifts every span up by `BOM_LEN` after running the
//! inner parser on the stripped source. Callers (LSP, FFI, doctor) see
//! coordinates that index into the source they passed in, with no need
//! to be BOM-aware themselves.
/// The UTF-8 byte-order mark (`EF BB BF`).
pub const BOM: &str = "\u{FEFF}";
/// The same BOM as a `char`.
///
/// Use this for `char`-typed predicates like `s.contains(BOM_CHAR)`
/// or `match c { BOM_CHAR => ... }` instead of open-coding
/// `'\u{FEFF}'` — that scatters the BOM concept across every
/// detection site and re-creates the contract drift this module
/// exists to prevent.
pub const BOM_CHAR: char = '\u{FEFF}';
/// Byte length of [`BOM`] in UTF-8 (always 3).
///
/// Used by `parse()` to shift spans back into the original-source
/// coordinate frame after running the inner parser on the
/// BOM-stripped view. Inlined as a const so the compiler can constant-
/// fold the shift arithmetic.
pub const BOM_LEN: usize = BOM.len;
/// Strip a strict-byte-0 leading BOM, returning `(stripped, had_bom)`.
///
/// "Strict byte 0" means the BOM must be the very first bytes of the
/// source. A BOM preceded by ANY content (whitespace, another
/// character, anything) is by definition mid-file and is left in place
/// for the lexer's error path to surface — that's not a "leading BOM"
/// no matter how innocuous the preceding bytes look.
///
/// ```
/// # use rustledger_parser::bom::{strip_leading, BOM};
/// let with_bom = format!("{BOM}2024-01-01 open Assets:Bank\n");
/// let (stripped, had_bom) = strip_leading(&with_bom);
/// assert!(had_bom);
/// assert_eq!(stripped, "2024-01-01 open Assets:Bank\n");
///
/// let (stripped, had_bom) = strip_leading("2024-01-01 open Assets:Bank\n");
/// assert!(!had_bom);
/// assert_eq!(stripped, "2024-01-01 open Assets:Bank\n");
/// ```
/// Re-prepend a leading BOM if `had_bom`. Idempotent: a call where
/// `formatted` already starts with a BOM returns the input unchanged.
///
/// Takes and returns an owned `String` so the no-BOM path (the
/// overwhelming majority of files) returns the input with zero
/// reallocation and zero byte copies.
///
/// The BOM-prepend path is one allocation (guaranteed by the explicit
/// `reserve(BOM_LEN)` before `insert_str`) plus an O(n) memmove of the
/// existing bytes by 3 positions. Without the explicit reserve,
/// `format_source`'s typically-tight-capacity `String` would force
/// `insert_str` to grow the buffer first AND THEN shift — two passes
/// over the bytes instead of one.
///
/// ```
/// # use rustledger_parser::bom::{restore_leading, BOM};
/// let body = "2024-01-01 open Assets:Bank\n".to_string();
///
/// // No BOM requested → return as-is.
/// let out = restore_leading(body.clone(), false);
/// assert_eq!(out, body);
///
/// // BOM requested and not present → prepend.
/// let out = restore_leading(body.clone(), true);
/// assert!(out.starts_with(BOM));
/// assert_eq!(&out[BOM.len()..], body);
///
/// // BOM requested and already present → idempotent no-op.
/// let with_bom = format!("{BOM}{body}");
/// let out = restore_leading(with_bom.clone(), true);
/// assert_eq!(out, with_bom);
/// ```