nash_parse/string.rs
1//! String literal parsing for Nash.
2//!
3//! Ported from Elm's `Parse/String.hs`.
4
5use crate::error::{Escape, StringError};
6use crate::{Col, Parser, Row};
7
8/// Internal result type for string parsing.
9enum StringResult<'a> {
10 Ok(&'a str),
11 Err(StringError, Row, Col),
12}
13
14impl<'a> Parser<'a> {
15 /// Parse a string literal with custom error constructors.
16 ///
17 /// Mirrors Elm's `String.string`:
18 /// ```haskell
19 /// string :: (Row -> Col -> x) -> (E.String -> Row -> Col -> x) -> Parser x ES.String
20 /// ```
21 ///
22 /// Handles both single-line (`"..."`) and multi-line (`"""..."""`) strings.
23 pub fn string_literal<E>(
24 &mut self,
25 to_expectation: impl FnOnce(Row, Col) -> E,
26 to_error: impl FnOnce(StringError, Row, Col) -> E,
27 ) -> Result<&'a str, E> {
28 let (row, col) = self.position();
29
30 // Must start with double quote
31 if self.peek() != Some(b'"') {
32 return Err(to_expectation(row, col));
33 }
34
35 self.advance(); // consume first "
36
37 // Check for multi-line string (""")
38 if self.peek() == Some(b'"') {
39 self.advance(); // consume second "
40
41 if self.peek() == Some(b'"') {
42 self.advance(); // consume third "
43 // Multi-line string
44 let result = self.chomp_multi_string(nash_region::Position::new(row, col));
45 match result {
46 StringResult::Ok(s) => Ok(s),
47 StringResult::Err(e, r, c) => Err(to_error(e, r, c)),
48 }
49 } else {
50 // Empty string ""
51 Ok(self.alloc_str(""))
52 }
53 } else {
54 // Single-line string
55 let result = self.chomp_single_string(nash_region::Position::new(row, col));
56 match result {
57 StringResult::Ok(s) => Ok(s),
58 StringResult::Err(e, r, c) => Err(to_error(e, r, c)),
59 }
60 }
61 }
62
63 /// Parse a single-line string (content after opening `"`).
64 fn chomp_single_string(&mut self, opening: nash_region::Position) -> StringResult<'a> {
65 let start_pos = self.pos;
66 let mut needs_escape = false;
67
68 loop {
69 match self.peek() {
70 None => {
71 // End of file without closing quote
72 return StringResult::Err(
73 StringError::EndlessSingle(opening),
74 self.row(),
75 self.col(),
76 );
77 }
78 Some(b'\n') => {
79 // Newline in single-line string
80 return StringResult::Err(
81 StringError::EndlessSingle(opening),
82 self.row(),
83 self.col(),
84 );
85 }
86 Some(b'"') => {
87 // End of string
88 let end_pos = self.pos;
89 self.advance(); // consume closing "
90
91 if needs_escape {
92 // Build escaped string
93 return self.build_escaped_string(start_pos, end_pos, false);
94 } else {
95 // Return slice directly
96 let bytes = &self.src[start_pos..end_pos];
97 let s = std::str::from_utf8(bytes)
98 .expect("source slice must end at UTF-8 boundaries");
99 return StringResult::Ok(s);
100 }
101 }
102 Some(b'\\') => {
103 needs_escape = true;
104 self.advance(); // consume backslash
105
106 match self.eat_escape() {
107 EscapeResult::Normal(width) => {
108 self.advance_by(width);
109 }
110 EscapeResult::Unicode(delta) => {
111 self.advance_by(delta);
112 }
113 EscapeResult::Problem(escape) => {
114 return StringResult::Err(
115 StringError::Escape(escape),
116 self.row(),
117 self.col(),
118 );
119 }
120 EscapeResult::EndOfFile => {
121 return StringResult::Err(
122 StringError::EndlessSingle(opening),
123 self.row(),
124 self.col(),
125 );
126 }
127 }
128 }
129 Some(b) => {
130 // Regular character - advance by UTF-8 width
131 let width = utf8_char_width(b);
132 self.advance_by(width);
133 }
134 }
135 }
136 }
137
138 /// Parse a multi-line string (content after opening `"""`).
139 fn chomp_multi_string(&mut self, opening: nash_region::Position) -> StringResult<'a> {
140 let start_pos = self.pos;
141 let mut needs_escape = false;
142
143 loop {
144 match self.peek() {
145 None => {
146 return StringResult::Err(
147 StringError::EndlessMulti(opening),
148 self.row(),
149 self.col(),
150 );
151 }
152 Some(b'"') => {
153 // Check for closing """
154 if self.peek_at(1) == Some(b'"') && self.peek_at(2) == Some(b'"') {
155 let end_pos = self.pos;
156 self.advance_by(3); // consume closing """
157
158 if needs_escape {
159 return self.build_escaped_string(start_pos, end_pos, true);
160 } else {
161 let bytes = &self.src[start_pos..end_pos];
162 let s = std::str::from_utf8(bytes)
163 .expect("source slice must end at UTF-8 boundaries");
164 return StringResult::Ok(s);
165 }
166 } else {
167 self.advance();
168 }
169 }
170 Some(b'\n') => {
171 // Newlines are allowed in multi-line strings
172 needs_escape = true; // We'll normalize to \n
173 self.advance();
174 }
175 Some(b'\r') => {
176 // Carriage return - skip it (normalize to just \n)
177 needs_escape = true;
178 self.advance();
179 }
180 Some(b'\\') => {
181 needs_escape = true;
182 self.advance();
183
184 match self.eat_escape() {
185 EscapeResult::Normal(width) => {
186 self.advance_by(width);
187 }
188 EscapeResult::Unicode(delta) => {
189 self.advance_by(delta);
190 }
191 EscapeResult::Problem(escape) => {
192 return StringResult::Err(
193 StringError::Escape(escape),
194 self.row(),
195 self.col(),
196 );
197 }
198 EscapeResult::EndOfFile => {
199 return StringResult::Err(
200 StringError::EndlessMulti(opening),
201 self.row(),
202 self.col(),
203 );
204 }
205 }
206 }
207 Some(b) => {
208 let width = utf8_char_width(b);
209 self.advance_by(width);
210 }
211 }
212 }
213 }
214
215 /// Process escape sequences and build the final string.
216 fn build_escaped_string(&self, start: usize, end: usize, is_multi: bool) -> StringResult<'a> {
217 let mut result = String::new();
218 let mut pos = start;
219
220 while pos < end {
221 let b = self.src[pos];
222
223 if b == b'\\' {
224 pos += 1;
225 if pos >= end {
226 break;
227 }
228
229 match self.src[pos] {
230 b'n' => {
231 result.push('\n');
232 pos += 1;
233 }
234 b'r' => {
235 result.push('\r');
236 pos += 1;
237 }
238 b't' => {
239 result.push('\t');
240 pos += 1;
241 }
242 b'"' => {
243 result.push('"');
244 pos += 1;
245 }
246 b'\'' => {
247 result.push('\'');
248 pos += 1;
249 }
250 b'\\' => {
251 result.push('\\');
252 pos += 1;
253 }
254 b'u' => {
255 pos += 1; // skip 'u'
256 if pos < end && self.src[pos] == b'{' {
257 pos += 1; // skip '{'
258 let hex_start = pos;
259 while pos < end && self.src[pos] != b'}' {
260 pos += 1;
261 }
262 let hex_str = std::str::from_utf8(&self.src[hex_start..pos])
263 .expect("source slice must end at UTF-8 boundaries");
264 if let Ok(code) = u32::from_str_radix(hex_str, 16)
265 && let Some(c) = char::from_u32(code)
266 {
267 result.push(c);
268 }
269 pos += 1; // skip '}'
270 }
271 }
272 _ => {
273 pos += 1;
274 }
275 }
276 } else if is_multi && b == b'\r' {
277 // Skip carriage returns in multi-line strings
278 pos += 1;
279 } else if is_multi && b == b'\n' {
280 result.push('\n');
281 pos += 1;
282 } else {
283 // Regular UTF-8 character
284 let width = utf8_char_width(b);
285 let char_bytes = &self.src[pos..pos + width];
286 let s = std::str::from_utf8(char_bytes)
287 .expect("source slice must end at UTF-8 boundaries");
288 result.push_str(s);
289 pos += width;
290 }
291 }
292
293 StringResult::Ok(self.alloc_str(&result))
294 }
295
296 /// Parse an escape sequence after the backslash.
297 fn eat_escape(&self) -> EscapeResult {
298 match self.peek() {
299 None => EscapeResult::EndOfFile,
300 Some(b'n') | Some(b'r') | Some(b't') | Some(b'"') | Some(b'\'') | Some(b'\\') => {
301 EscapeResult::Normal(1)
302 }
303 Some(b'u') => self.eat_unicode(),
304 Some(_) => EscapeResult::Problem(Escape::Unknown),
305 }
306 }
307
308 /// Parse a unicode escape sequence `\u{...}`.
309 fn eat_unicode(&self) -> EscapeResult {
310 // Position is at 'u', need to check for '{'
311 if self.peek_at(1) != Some(b'{') {
312 return EscapeResult::Problem(Escape::BadUnicodeFormat(2));
313 }
314
315 // Count hex digits
316 let mut offset = 2; // past 'u{'
317 let mut num_digits = 0;
318 let mut code: u32 = 0;
319
320 loop {
321 match self.peek_at(offset) {
322 None => {
323 return EscapeResult::Problem(Escape::BadUnicodeFormat(offset));
324 }
325 Some(b'}') => {
326 break;
327 }
328 Some(b) if b.is_ascii_hexdigit() => {
329 let digit = if b.is_ascii_digit() {
330 (b - b'0') as u32
331 } else if (b'a'..=b'f').contains(&b) {
332 (b - b'a' + 10) as u32
333 } else {
334 (b - b'A' + 10) as u32
335 };
336 // Saturation keeps an oversized escape invalid without overflowing.
337 code = code.saturating_mul(16).saturating_add(digit);
338 num_digits += 1;
339 offset += 1;
340 }
341 Some(_) => {
342 return EscapeResult::Problem(Escape::BadUnicodeFormat(offset));
343 }
344 }
345 }
346
347 // Check code validity
348 if code > 0x10FFFF {
349 return EscapeResult::Problem(Escape::BadUnicodeCode(offset + 1));
350 }
351
352 // Check digit count (must be 4-6)
353 if !(4..=6).contains(&num_digits) {
354 return EscapeResult::Problem(Escape::BadUnicodeLength {
355 code: offset + 1,
356 expected: if num_digits < 4 { 4 } else { 6 },
357 actual: num_digits,
358 });
359 }
360
361 // Return total length including 'u', '{', digits, '}'
362 EscapeResult::Unicode(offset + 1)
363 }
364}
365
366/// Result of parsing an escape sequence.
367enum EscapeResult {
368 /// Normal escape like \n, width is 1
369 Normal(usize),
370 /// Unicode escape \u{...}, delta is total chars consumed
371 Unicode(usize),
372 /// End of file during escape
373 EndOfFile,
374 /// Invalid escape
375 Problem(Escape),
376}
377
378/// Get the width of a UTF-8 character from its first byte.
379#[inline]
380fn utf8_char_width(b: u8) -> usize {
381 if b < 0x80 {
382 1
383 } else if b < 0xE0 {
384 2
385 } else if b < 0xF0 {
386 3
387 } else {
388 4
389 }
390}