Skip to main content

mago_syntax_core/
utils.rs

1use mago_allocator::prelude::*;
2
3use crate::input::Input;
4use crate::number_separator;
5
6/// Parses a PHP literal string, handling all escape sequences, and allocates the result in an arena.
7///
8/// # Returns
9///
10/// An `Option` containing the parsed `&'arena str` or `None` if the input is invalid.
11///
12/// # Panics
13///
14/// Panics if internal assumptions about character parsing are violated (e.g., invalid hex or octal digits
15/// after validation). This should not occur with valid PHP strings.
16pub fn parse_literal_string_in<'arena, A>(
17    arena: &'arena A,
18    s: &'arena [u8],
19    quote_char: Option<u8>,
20    has_quote: bool,
21) -> Option<&'arena [u8]>
22where
23    A: Arena,
24{
25    if s.is_empty() {
26        return Some(b"");
27    }
28
29    let s = if has_quote
30        && (s.starts_with(b"b\"") || s.starts_with(b"b'") || s.starts_with(b"B\"") || s.starts_with(b"B'"))
31    {
32        &s[1..]
33    } else {
34        s
35    };
36
37    let (quote_char, content) = if let Some(quote_char) = quote_char {
38        (Some(quote_char), s)
39    } else if !has_quote {
40        (None, s)
41    } else if s.starts_with(b"\"") && s.ends_with(b"\"") && s.len() >= 2 {
42        (Some(b'"'), &s[1..s.len() - 1])
43    } else if s.starts_with(b"'") && s.ends_with(b"'") && s.len() >= 2 {
44        (Some(b'\''), &s[1..s.len() - 1])
45    } else {
46        return None;
47    };
48
49    if !content.contains(&b'\\') {
50        return Some(content);
51    }
52
53    let mut result = Vec::with_capacity_in(content.len(), arena);
54    let mut i = 0;
55
56    while i < content.len() {
57        let b = content[i];
58        if b != b'\\' {
59            result.push(b);
60            i += 1;
61            continue;
62        }
63
64        let next_index = i + 1;
65        let Some(&next) = content.get(next_index) else {
66            result.push(b'\\');
67            i += 1;
68            continue;
69        };
70
71        // Most escapes consume two bytes (`\` + the next byte). The hex and octal
72        // forms scan additional digit bytes and update `i` themselves.
73        let mut consumed = 2;
74
75        match next {
76            b'\\' => result.push(b'\\'),
77            b'\'' if quote_char == Some(b'\'') => result.push(b'\''),
78            b'"' if quote_char == Some(b'"') => result.push(b'"'),
79            b'$' if quote_char == Some(b'"') => result.push(b'$'),
80            b'n' if quote_char == Some(b'"') => result.push(b'\n'),
81            b't' if quote_char == Some(b'"') => result.push(b'\t'),
82            b'r' if quote_char == Some(b'"') => result.push(b'\r'),
83            b'v' if quote_char == Some(b'"') => result.push(0x0B),
84            b'e' if quote_char == Some(b'"') => result.push(0x1B),
85            b'f' if quote_char == Some(b'"') => result.push(0x0C),
86            b'x' if quote_char == Some(b'"') => {
87                let mut hex_val = 0u8;
88                let mut hex_len = 0;
89                let mut j = i + 2;
90                while hex_len < 2 && j < content.len() {
91                    let c = content[j];
92                    let digit = if c.is_ascii_digit() {
93                        c - b'0'
94                    } else if (b'a'..=b'f').contains(&c) {
95                        c - b'a' + 10
96                    } else if (b'A'..=b'F').contains(&c) {
97                        c - b'A' + 10
98                    } else {
99                        break;
100                    };
101                    hex_val = hex_val * 16 + digit;
102                    hex_len += 1;
103                    j += 1;
104                }
105                if hex_len > 0 {
106                    result.push(hex_val);
107                    consumed = 2 + hex_len;
108                } else {
109                    // Invalid `\x` sequence, treat as literal `\x`
110                    result.push(b'\\');
111                    result.push(b'x');
112                }
113            }
114            b'u' if quote_char == Some(b'"') && content.get(i + 2) == Some(&b'{') => {
115                let mut code_point = 0u32;
116                let mut hex_len = 0;
117                let mut overflowed = false;
118                let mut j = i + 3;
119                while j < content.len() {
120                    let c = content[j];
121                    let digit = if c.is_ascii_digit() {
122                        c - b'0'
123                    } else if (b'a'..=b'f').contains(&c) {
124                        c - b'a' + 10
125                    } else if (b'A'..=b'F').contains(&c) {
126                        c - b'A' + 10
127                    } else {
128                        break;
129                    };
130
131                    match code_point.checked_mul(16).and_then(|value| value.checked_add(u32::from(digit))) {
132                        Some(value) => code_point = value,
133                        None => {
134                            overflowed = true;
135                            break;
136                        }
137                    }
138
139                    hex_len += 1;
140                    j += 1;
141                }
142
143                if hex_len > 0 && !overflowed && content.get(j) == Some(&b'}') && code_point <= 0x10_FFFF {
144                    match code_point {
145                        0x0000..=0x007F => result.push(code_point as u8),
146                        0x0080..=0x07FF => {
147                            result.push(0xC0 | (code_point >> 6) as u8);
148                            result.push(0x80 | (code_point & 0x3F) as u8);
149                        }
150                        0x0800..=0xFFFF => {
151                            result.push(0xE0 | (code_point >> 12) as u8);
152                            result.push(0x80 | ((code_point >> 6) & 0x3F) as u8);
153                            result.push(0x80 | (code_point & 0x3F) as u8);
154                        }
155                        _ => {
156                            result.push(0xF0 | (code_point >> 18) as u8);
157                            result.push(0x80 | ((code_point >> 12) & 0x3F) as u8);
158                            result.push(0x80 | ((code_point >> 6) & 0x3F) as u8);
159                            result.push(0x80 | (code_point & 0x3F) as u8);
160                        }
161                    }
162
163                    consumed = (j + 1) - i;
164                } else {
165                    // Invalid `\u{...}` sequence, return None to indicate failure to parse.
166                    return None;
167                }
168            }
169            c if quote_char == Some(b'"') && c.is_ascii_digit() => {
170                let mut octal_val = 0u16;
171                let mut octal_len = 0;
172                let mut j = i + 1;
173                while octal_len < 3 && j < content.len() {
174                    let d = content[j];
175                    if d.is_ascii_digit() && d <= b'7' {
176                        octal_val = octal_val * 8 + u16::from(d - b'0');
177                        octal_len += 1;
178                        j += 1;
179                    } else {
180                        break;
181                    }
182                }
183                if octal_len > 0 {
184                    // Truncate to u8 (matches PHP behavior for octal sequences > 255)
185                    result.push(octal_val as u8);
186                    consumed = 1 + octal_len;
187                } else {
188                    result.push(b'\\');
189                    result.push(next);
190                }
191            }
192            _ => {
193                // Unrecognized escape sequence
194                result.push(b'\\');
195                result.push(next);
196            }
197        }
198
199        i += consumed;
200    }
201
202    Some(result.leak())
203}
204
205/// Parses a PHP literal float, handling underscore separators.
206#[inline]
207#[must_use]
208pub fn parse_literal_float(value: &[u8]) -> Option<f64> {
209    if memchr::memchr(b'_', value).is_none() {
210        return std::str::from_utf8(value).ok()?.parse::<f64>().ok();
211    }
212
213    let mut buf = [0u8; 64];
214    let mut len = 0;
215
216    for &b in value {
217        if b != b'_' {
218            if len < 64 {
219                buf[len] = b;
220                len += 1;
221            } else {
222                let source: std::vec::Vec<u8> = value.iter().copied().filter(|&b| b != b'_').collect();
223                return std::str::from_utf8(&source).ok()?.parse::<f64>().ok();
224            }
225        }
226    }
227
228    std::str::from_utf8(&buf[..len]).ok()?.parse::<f64>().ok()
229}
230
231/// Parses a PHP literal integer with support for binary, octal, decimal, and hex.
232///
233/// Optimized to use byte-level iteration instead of Unicode chars.
234#[inline]
235#[must_use]
236pub fn parse_literal_integer(bytes: &[u8]) -> Option<u64> {
237    if bytes.is_empty() {
238        return None;
239    }
240
241    let (radix, start) = match bytes {
242        [b'0', b'x' | b'X', ..] => (16u128, 2),
243        [b'0', b'o' | b'O', ..] => (8u128, 2),
244        [b'0', b'b' | b'B', ..] => (2u128, 2),
245        [b'0', _, ..] if bytes[1..].iter().all(|&b| b == b'_' || (b'0'..=b'7').contains(&b)) => (8u128, 1), // Legacy octal
246        [b'0', _, ..] => (10u128, 0), // Invalid octal (contains 8/9), treat as decimal
247        _ => (10u128, 0),
248    };
249
250    let mut result: u128 = 0;
251    let mut has_digits = false;
252
253    for &b in &bytes[start..] {
254        if b == b'_' {
255            continue;
256        }
257
258        let digit = if b.is_ascii_digit() {
259            (b - b'0') as u128
260        } else if (b'a'..=b'f').contains(&b) {
261            (b - b'a' + 10) as u128
262        } else if (b'A'..=b'F').contains(&b) {
263            (b - b'A' + 10) as u128
264        } else {
265            return None;
266        };
267
268        if digit >= radix {
269            return None;
270        }
271
272        has_digits = true;
273
274        result = match result.checked_mul(radix) {
275            Some(r) => r,
276            None => return Some(u64::MAX),
277        };
278
279        result = match result.checked_add(digit) {
280            Some(r) => r,
281            None => return Some(u64::MAX),
282        };
283    }
284
285    if !has_digits {
286        return None;
287    }
288
289    Some(result.min(u64::MAX as u128) as u64)
290}
291
292/// Parses a PHP literal integer's magnitude as an `f64`.
293///
294/// This is how PHP widens an integer literal that overflows the platform `int` into a float: it
295/// reflects the real magnitude rather than clamping at `u64::MAX` like [`parse_literal_integer`].
296/// Supports binary (`0b`), octal (`0o`/legacy `0`), decimal, and hexadecimal (`0x`), matching the
297/// base detection of [`parse_literal_integer`].
298#[inline]
299#[must_use]
300pub fn parse_literal_integer_as_float(bytes: &[u8]) -> Option<f64> {
301    if bytes.is_empty() {
302        return None;
303    }
304
305    let (radix, start) = match bytes {
306        [b'0', b'x' | b'X', ..] => (16u128, 2),
307        [b'0', b'o' | b'O', ..] => (8u128, 2),
308        [b'0', b'b' | b'B', ..] => (2u128, 2),
309        [b'0', _, ..] if bytes[1..].iter().all(|&b| b == b'_' || (b'0'..=b'7').contains(&b)) => (8u128, 1),
310        _ => (10u128, 0),
311    };
312
313    if radix == 10 {
314        return parse_literal_float(bytes);
315    }
316
317    let mut result: u128 = 0;
318    let mut has_digits = false;
319
320    for &b in &bytes[start..] {
321        if b == b'_' {
322            continue;
323        }
324
325        let digit = if b.is_ascii_digit() {
326            (b - b'0') as u128
327        } else if (b'a'..=b'f').contains(&b) {
328            (b - b'a' + 10) as u128
329        } else if (b'A'..=b'F').contains(&b) {
330            (b - b'A' + 10) as u128
331        } else {
332            return None;
333        };
334
335        if digit >= radix {
336            return None;
337        }
338
339        has_digits = true;
340        result = match result.checked_mul(radix).and_then(|value| value.checked_add(digit)) {
341            Some(value) => value,
342            None => return Some(f64::INFINITY),
343        };
344    }
345
346    if !has_digits {
347        return None;
348    }
349
350    Some(result as f64)
351}
352
353/// Lookup table for identifier start characters (a-z, A-Z, _)
354/// Index by byte value, true if valid start of identifier
355static IS_IDENT_START: [bool; 256] = {
356    let mut table = [false; 256];
357    let mut i = 0u8;
358    loop {
359        table[i as usize] = matches!(i, b'a'..=b'z' | b'A'..=b'Z' | b'_');
360        if i == 255 {
361            break;
362        }
363        i += 1;
364    }
365
366    table
367};
368
369/// Lookup table for identifier continuation characters (a-z, A-Z, 0-9, _, or >= 0x80)
370/// Index by byte value, true if valid part of identifier
371static IS_IDENT_PART: [bool; 256] = {
372    let mut table = [false; 256];
373    let mut i = 0u8;
374    loop {
375        table[i as usize] = matches!(i, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | 0x80..=0xFF);
376        if i == 255 {
377            break;
378        }
379        i += 1;
380    }
381    table
382};
383
384/// Check if a byte can start an identifier (a-z, A-Z, _)
385#[inline(always)]
386#[must_use]
387pub const fn is_start_of_identifier(byte: &u8) -> bool {
388    IS_IDENT_START[*byte as usize]
389}
390
391/// Check if a byte can be part of an identifier (a-z, A-Z, 0-9, _, or >= 0x80)
392#[inline(always)]
393#[must_use]
394pub const fn is_part_of_identifier(byte: &u8) -> bool {
395    IS_IDENT_PART[*byte as usize]
396}
397
398/// Scans an identifier starting at `offset` in the byte slice and returns the length.
399///
400/// Assumes the first byte is already validated as a start of identifier.
401/// Returns the total length of the identifier (including the first byte).
402/// Stops at the first byte that is not a valid identifier character.
403#[inline(always)]
404#[must_use]
405pub fn scan_identifier_length(bytes: &[u8], offset: usize) -> usize {
406    let mut len = 1;
407    let remaining = &bytes[offset + 1..];
408
409    for &b in remaining {
410        if IS_IDENT_PART[b as usize] {
411            len += 1;
412        } else {
413            break;
414        }
415    }
416
417    len
418}
419
420/// Reads a sequence of bytes representing digits in a specific numerical base.
421///
422/// This utility function iterates through the input byte slice, consuming bytes
423/// as long as they represent valid digits for the given `base`. It handles
424/// decimal digits ('0'-'9') and hexadecimal digits ('a'-'f', 'A'-'F').
425///
426/// It stops consuming at the first byte that is not a valid digit character,
427/// or is a digit character whose value is greater than or equal to the specified `base`
428/// (e.g., '8' in base 8, or 'A' in base 10).
429///
430/// This function is primarily intended as a helper for lexer implementations
431/// when tokenizing the digit part of number literals (binary, octal, decimal, hexadecimal).
432///
433/// # Arguments
434///
435/// * `input` - A byte slice starting at the potential first digit of the number.
436/// * `base` - The numerical base (e.g., 2, 8, 10, 16) to use for validating digits.
437///   Must be between 2 and 36 (inclusive) for hex characters to be potentially valid.
438///
439/// # Returns
440///
441/// The number of bytes (`usize`) consumed from the beginning of the `input` slice
442/// that constitute a valid sequence of digits for the specified `base`. Returns 0 if
443/// the first byte is not a valid digit for the base.
444#[inline]
445pub fn read_digits_of_base(input: &Input, offset: usize, base: u8) -> usize {
446    if base == 16 {
447        read_digits_with(input, offset, u8::is_ascii_hexdigit)
448    } else {
449        let max = b'0' + base;
450
451        read_digits_with(input, offset, |b| b >= &b'0' && b < &max)
452    }
453}
454
455#[inline]
456fn read_digits_with<F>(input: &Input, offset: usize, is_digit: F) -> usize
457where
458    F: Fn(&u8) -> bool,
459{
460    let bytes = input.bytes;
461    let total = input.length;
462    let start = input.offset;
463    let mut pos = start + offset; // Compute the absolute position.
464
465    while pos < total {
466        let current = bytes[pos];
467        if is_digit(&current) {
468            pos += 1;
469        } else if pos + 1 < total && bytes[pos] == number_separator!() && is_digit(&bytes[pos + 1]) {
470            pos += 2; // Skip the separator and the digit.
471        } else {
472            break;
473        }
474    }
475
476    // Return the relative length from the start of the current position.
477    pos - start
478}
479
480#[cfg(test)]
481mod tests {
482    use mago_allocator::LocalArena;
483
484    use super::*;
485
486    macro_rules! parse_int {
487        ($input:expr, $expected:expr) => {
488            assert_eq!(parse_literal_integer($input), $expected);
489        };
490    }
491
492    #[test]
493    fn literal_string_parts_without_escapes_borrow_their_bytes() {
494        let arena = LocalArena::new();
495        for content in [b"a\"b'c".as_slice(), b"<p class=\"value\">text</p>\n", b"\xff\"\r\n'"] {
496            for quote in [None, Some(b'\''), Some(b'"')] {
497                let Some(value) = parse_literal_string_in(&arena, content, quote, false) else {
498                    panic!("String parts without escapes should parse");
499                };
500                assert_eq!(value, content);
501                assert_eq!(value.as_ptr(), content.as_ptr());
502            }
503        }
504    }
505
506    #[test]
507    fn quoted_literals_keep_plain_quotes_and_binary_prefixes() {
508        let arena = LocalArena::new();
509        for (input, start) in [
510            (b"'a\"b'".as_slice(), 1),
511            (b"\"a'b\"", 1),
512            (b"b'a\"b'", 2),
513            (b"B\"a'b\"", 2),
514            (b"\"a\"b\"", 1),
515            (b"'a'b'", 1),
516        ] {
517            let Some(value) = parse_literal_string_in(&arena, input, None, true) else {
518                panic!("Quoted literals without escapes should parse");
519            };
520            let content = &input[start..input.len() - 1];
521            assert_eq!(value, content);
522            assert_eq!(value.as_ptr(), content.as_ptr());
523        }
524        for input in [b"'".as_slice(), b"b\"", b"\"missing", b"'mismatch\""] {
525            assert_eq!(parse_literal_string_in(&arena, input, None, true), None);
526        }
527    }
528
529    #[test]
530    fn test_unicode_escape_in_double_quoted() {
531        let arena = LocalArena::new();
532
533        assert_eq!(parse_literal_string_in(&arena, b"A\\u{1F600}", Some(b'"'), false), Some(&b"A\xF0\x9F\x98\x80"[..]),);
534        assert_eq!(parse_literal_string_in(&arena, b"\\u{41}", Some(b'"'), false), Some(&b"A"[..]));
535        assert_eq!(parse_literal_string_in(&arena, b"\\u{E9}", Some(b'"'), false), Some(&b"\xC3\xA9"[..]));
536        assert_eq!(parse_literal_string_in(&arena, b"\\u{D800}", Some(b'"'), false), Some(&b"\xED\xA0\x80"[..]));
537        assert_eq!(parse_literal_string_in(&arena, b"\\u{}", Some(b'"'), false), None);
538        assert_eq!(parse_literal_string_in(&arena, b"\\u{12", Some(b'"'), false), None);
539        assert_eq!(parse_literal_string_in(&arena, b"\\u{ZZ}", Some(b'"'), false), None);
540        assert_eq!(parse_literal_string_in(&arena, b"\\u{110000}", Some(b'"'), false), None);
541        assert_eq!(parse_literal_string_in(&arena, b"\\uABC", Some(b'"'), false), Some(&b"\\uABC"[..]));
542        assert_eq!(parse_literal_string_in(&arena, b"\\u{41}", Some(b'\''), false), Some(&b"\\u{41}"[..]));
543        assert_eq!(parse_literal_string_in(&arena, b"\\x", Some(b'"'), false), Some(&b"\\x"[..]));
544        assert_eq!(parse_literal_string_in(&arena, b"\\q", Some(b'"'), false), Some(&b"\\q"[..]));
545    }
546
547    #[test]
548    fn test_parse_literal_integer() {
549        parse_int!(b"123", Some(123));
550        parse_int!(b"0", Some(0));
551        parse_int!(b"0b1010", Some(10));
552        parse_int!(b"0o17", Some(15));
553        parse_int!(b"0x1A3F", Some(6719));
554        parse_int!(b"0XFF", Some(255));
555        parse_int!(b"0_1_2_3", Some(83));
556        parse_int!(b"0b1_0_1_0", Some(10));
557        parse_int!(b"0o1_7", Some(15));
558        parse_int!(b"0x1_A_3_F", Some(6719));
559        parse_int!(b"", None);
560        parse_int!(b"0xGHI", None);
561        parse_int!(b"0b102", None);
562        parse_int!(b"0o89", None);
563    }
564
565    #[test]
566    fn test_parse_literal_integer_as_float() {
567        assert_eq!(parse_literal_integer_as_float(b"0"), Some(0.0));
568        assert_eq!(parse_literal_integer_as_float(b"255"), Some(255.0));
569        assert_eq!(parse_literal_integer_as_float(b"0xff"), Some(255.0));
570        assert_eq!(parse_literal_integer_as_float(b"0o17"), Some(15.0));
571        assert_eq!(parse_literal_integer_as_float(b"017"), Some(15.0));
572        assert_eq!(parse_literal_integer_as_float(b"0b101"), Some(5.0));
573        assert_eq!(parse_literal_integer_as_float(b"1_000"), Some(1000.0));
574        assert_eq!(parse_literal_integer_as_float(b"111111111111111111111"), Some(1.111_111_111_111_111_1e20));
575        assert_eq!(parse_literal_integer_as_float(b"0xFFFFFFFFFFFFFFFF0"), Some(2.951_479_051_793_528_3e20));
576        assert_eq!(parse_literal_integer_as_float(&[b'9'; 400]), Some(f64::INFINITY));
577        assert_eq!(parse_literal_integer_as_float(b""), None);
578        assert_eq!(parse_literal_integer_as_float(b"0xGHI"), None);
579        assert_eq!(parse_literal_integer_as_float(b"0b102"), None);
580    }
581}