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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
//! String literal parsing for Nash.
//!
//! Ported from Elm's `Parse/String.hs`.
use crate::error::{Escape, StringError};
use crate::{Col, Parser, Row};
/// Internal result type for string parsing.
enum StringResult<'a> {
Ok(&'a str),
Err(StringError, Row, Col),
}
impl<'a> Parser<'a> {
/// Parse a string literal with custom error constructors.
///
/// Mirrors Elm's `String.string`:
/// ```haskell
/// string :: (Row -> Col -> x) -> (E.String -> Row -> Col -> x) -> Parser x ES.String
/// ```
///
/// Handles both single-line (`"..."`) and multi-line (`"""..."""`) strings.
pub fn string_literal<E>(
&mut self,
to_expectation: impl FnOnce(Row, Col) -> E,
to_error: impl FnOnce(StringError, Row, Col) -> E,
) -> Result<&'a str, E> {
let (row, col) = self.position();
// Must start with double quote
if self.peek() != Some(b'"') {
return Err(to_expectation(row, col));
}
self.advance(); // consume first "
// Check for multi-line string (""")
if self.peek() == Some(b'"') {
self.advance(); // consume second "
if self.peek() == Some(b'"') {
self.advance(); // consume third "
// Multi-line string
let result = self.chomp_multi_string(nash_region::Position::new(row, col));
match result {
StringResult::Ok(s) => Ok(s),
StringResult::Err(e, r, c) => Err(to_error(e, r, c)),
}
} else {
// Empty string ""
Ok(self.alloc_str(""))
}
} else {
// Single-line string
let result = self.chomp_single_string(nash_region::Position::new(row, col));
match result {
StringResult::Ok(s) => Ok(s),
StringResult::Err(e, r, c) => Err(to_error(e, r, c)),
}
}
}
/// Parse a single-line string (content after opening `"`).
fn chomp_single_string(&mut self, opening: nash_region::Position) -> StringResult<'a> {
let start_pos = self.pos;
let mut needs_escape = false;
loop {
match self.peek() {
None => {
// End of file without closing quote
return StringResult::Err(
StringError::EndlessSingle(opening),
self.row(),
self.col(),
);
}
Some(b'\n') => {
// Newline in single-line string
return StringResult::Err(
StringError::EndlessSingle(opening),
self.row(),
self.col(),
);
}
Some(b'"') => {
// End of string
let end_pos = self.pos;
self.advance(); // consume closing "
if needs_escape {
// Build escaped string
return self.build_escaped_string(start_pos, end_pos, false);
} else {
// Return slice directly
let bytes = &self.src[start_pos..end_pos];
let s = std::str::from_utf8(bytes)
.expect("source slice must end at UTF-8 boundaries");
return StringResult::Ok(s);
}
}
Some(b'\\') => {
needs_escape = true;
self.advance(); // consume backslash
match self.eat_escape() {
EscapeResult::Normal(width) => {
self.advance_by(width);
}
EscapeResult::Unicode(delta) => {
self.advance_by(delta);
}
EscapeResult::Problem(escape) => {
return StringResult::Err(
StringError::Escape(escape),
self.row(),
self.col(),
);
}
EscapeResult::EndOfFile => {
return StringResult::Err(
StringError::EndlessSingle(opening),
self.row(),
self.col(),
);
}
}
}
Some(b) => {
// Regular character - advance by UTF-8 width
let width = utf8_char_width(b);
self.advance_by(width);
}
}
}
}
/// Parse a multi-line string (content after opening `"""`).
fn chomp_multi_string(&mut self, opening: nash_region::Position) -> StringResult<'a> {
let start_pos = self.pos;
let mut needs_escape = false;
loop {
match self.peek() {
None => {
return StringResult::Err(
StringError::EndlessMulti(opening),
self.row(),
self.col(),
);
}
Some(b'"') => {
// Check for closing """
if self.peek_at(1) == Some(b'"') && self.peek_at(2) == Some(b'"') {
let end_pos = self.pos;
self.advance_by(3); // consume closing """
if needs_escape {
return self.build_escaped_string(start_pos, end_pos, true);
} else {
let bytes = &self.src[start_pos..end_pos];
let s = std::str::from_utf8(bytes)
.expect("source slice must end at UTF-8 boundaries");
return StringResult::Ok(s);
}
} else {
self.advance();
}
}
Some(b'\n') => {
// Newlines are allowed in multi-line strings
needs_escape = true; // We'll normalize to \n
self.advance();
}
Some(b'\r') => {
// Carriage return - skip it (normalize to just \n)
needs_escape = true;
self.advance();
}
Some(b'\\') => {
needs_escape = true;
self.advance();
match self.eat_escape() {
EscapeResult::Normal(width) => {
self.advance_by(width);
}
EscapeResult::Unicode(delta) => {
self.advance_by(delta);
}
EscapeResult::Problem(escape) => {
return StringResult::Err(
StringError::Escape(escape),
self.row(),
self.col(),
);
}
EscapeResult::EndOfFile => {
return StringResult::Err(
StringError::EndlessMulti(opening),
self.row(),
self.col(),
);
}
}
}
Some(b) => {
let width = utf8_char_width(b);
self.advance_by(width);
}
}
}
}
/// Process escape sequences and build the final string.
fn build_escaped_string(&self, start: usize, end: usize, is_multi: bool) -> StringResult<'a> {
let mut result = String::new();
let mut pos = start;
while pos < end {
let b = self.src[pos];
if b == b'\\' {
pos += 1;
if pos >= end {
break;
}
match self.src[pos] {
b'n' => {
result.push('\n');
pos += 1;
}
b'r' => {
result.push('\r');
pos += 1;
}
b't' => {
result.push('\t');
pos += 1;
}
b'"' => {
result.push('"');
pos += 1;
}
b'\'' => {
result.push('\'');
pos += 1;
}
b'\\' => {
result.push('\\');
pos += 1;
}
b'u' => {
pos += 1; // skip 'u'
if pos < end && self.src[pos] == b'{' {
pos += 1; // skip '{'
let hex_start = pos;
while pos < end && self.src[pos] != b'}' {
pos += 1;
}
let hex_str = std::str::from_utf8(&self.src[hex_start..pos])
.expect("source slice must end at UTF-8 boundaries");
if let Ok(code) = u32::from_str_radix(hex_str, 16)
&& let Some(c) = char::from_u32(code)
{
result.push(c);
}
pos += 1; // skip '}'
}
}
_ => {
pos += 1;
}
}
} else if is_multi && b == b'\r' {
// Skip carriage returns in multi-line strings
pos += 1;
} else if is_multi && b == b'\n' {
result.push('\n');
pos += 1;
} else {
// Regular UTF-8 character
let width = utf8_char_width(b);
let char_bytes = &self.src[pos..pos + width];
let s = std::str::from_utf8(char_bytes)
.expect("source slice must end at UTF-8 boundaries");
result.push_str(s);
pos += width;
}
}
StringResult::Ok(self.alloc_str(&result))
}
/// Parse an escape sequence after the backslash.
fn eat_escape(&self) -> EscapeResult {
match self.peek() {
None => EscapeResult::EndOfFile,
Some(b'n') | Some(b'r') | Some(b't') | Some(b'"') | Some(b'\'') | Some(b'\\') => {
EscapeResult::Normal(1)
}
Some(b'u') => self.eat_unicode(),
Some(_) => EscapeResult::Problem(Escape::Unknown),
}
}
/// Parse a unicode escape sequence `\u{...}`.
fn eat_unicode(&self) -> EscapeResult {
// Position is at 'u', need to check for '{'
if self.peek_at(1) != Some(b'{') {
return EscapeResult::Problem(Escape::BadUnicodeFormat(2));
}
// Count hex digits
let mut offset = 2; // past 'u{'
let mut num_digits = 0;
let mut code: u32 = 0;
loop {
match self.peek_at(offset) {
None => {
return EscapeResult::Problem(Escape::BadUnicodeFormat(offset));
}
Some(b'}') => {
break;
}
Some(b) if b.is_ascii_hexdigit() => {
let digit = if b.is_ascii_digit() {
(b - b'0') as u32
} else if (b'a'..=b'f').contains(&b) {
(b - b'a' + 10) as u32
} else {
(b - b'A' + 10) as u32
};
// Saturation keeps an oversized escape invalid without overflowing.
code = code.saturating_mul(16).saturating_add(digit);
num_digits += 1;
offset += 1;
}
Some(_) => {
return EscapeResult::Problem(Escape::BadUnicodeFormat(offset));
}
}
}
// Check code validity
if code > 0x10FFFF {
return EscapeResult::Problem(Escape::BadUnicodeCode(offset + 1));
}
// Check digit count (must be 4-6)
if !(4..=6).contains(&num_digits) {
return EscapeResult::Problem(Escape::BadUnicodeLength {
code: offset + 1,
expected: if num_digits < 4 { 4 } else { 6 },
actual: num_digits,
});
}
// Return total length including 'u', '{', digits, '}'
EscapeResult::Unicode(offset + 1)
}
}
/// Result of parsing an escape sequence.
enum EscapeResult {
/// Normal escape like \n, width is 1
Normal(usize),
/// Unicode escape \u{...}, delta is total chars consumed
Unicode(usize),
/// End of file during escape
EndOfFile,
/// Invalid escape
Problem(Escape),
}
/// Get the width of a UTF-8 character from its first byte.
#[inline]
fn utf8_char_width(b: u8) -> usize {
if b < 0x80 {
1
} else if b < 0xE0 {
2
} else if b < 0xF0 {
3
} else {
4
}
}