Skip to main content

parsec_js/
text.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! What a token's text means: an identifier's name with its escapes
5//! decoded, a string's or template's value in UTF-16 code units, a
6//! number's value, and those values written out as JSON.
7
8use std::borrow::Cow;
9use std::fmt::Write;
10
11/// An IdentifierName's StringValue: `a` and `\u{61}` decoded.
12pub fn ident_name(raw: &str) -> Cow<'_, str> {
13    if !raw.contains('\\') {
14        return Cow::Borrowed(raw);
15    }
16    let mut out = String::with_capacity(raw.len());
17    let b = raw.as_bytes();
18    let mut i = 0;
19    while i < b.len() {
20        if b[i] == b'\\' && b.get(i + 1) == Some(&b'u') {
21            let (value, len) = unicode_escape(&raw[i + 2..]);
22            if let Some(c) = value.and_then(char::from_u32) {
23                out.push(c);
24            }
25            i += 2 + len;
26        } else {
27            let c = raw[i..].chars().next().unwrap_or('\0');
28            out.push(c);
29            i += c.len_utf8().max(1);
30        }
31    }
32    Cow::Owned(out)
33}
34
35/// The value of the hex digits after `\u`, four or in braces, and how
36/// many bytes they took.
37fn unicode_escape(s: &str) -> (Option<u32>, usize) {
38    let b = s.as_bytes();
39    if b.first() == Some(&b'{') {
40        let end = b.iter().position(|&c| c == b'}').unwrap_or(b.len());
41        let value = u32::from_str_radix(&s[1..end], 16).ok();
42        (value, (end + 1).min(b.len()))
43    } else {
44        // Up to four hex digits, which a tagged template's invalid escape
45        // (`\u/0é`) may stop short of.
46        let end = b
47            .iter()
48            .take(4)
49            .take_while(|c| c.is_ascii_hexdigit())
50            .count();
51        let value = u32::from_str_radix(&s[..end], 16).ok().filter(|_| end == 4);
52        (value, end)
53    }
54}
55
56fn push_char(out: &mut Vec<u16>, c: char) {
57    let mut buf = [0; 2];
58    out.extend_from_slice(c.encode_utf16(&mut buf));
59}
60
61fn push_code_point(out: &mut Vec<u16>, cp: u32) {
62    match char::from_u32(cp) {
63        Some(c) => push_char(out, c),
64        // A lone surrogate, which a JavaScript string can hold.
65        None => out.push(cp as u16),
66    }
67}
68
69fn is_line_terminator(c: char) -> bool {
70    matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}')
71}
72
73/// A string literal's value, from its text without the quotes, as
74/// UTF-16 code units: it can hold a lone surrogate (`"\uD800"`), which no
75/// Rust string can.
76pub fn string_value(body: &str) -> Vec<u16> {
77    let mut out = Vec::with_capacity(body.len());
78    let mut chars = body.char_indices().peekable();
79    while let Some((i, c)) = chars.next() {
80        if c != '\\' {
81            push_char(&mut out, c);
82            continue;
83        }
84        let Some((_, e)) = chars.next() else { break };
85        match e {
86            'b' => out.push(8),
87            'f' => out.push(12),
88            'n' => out.push(10),
89            'r' => out.push(13),
90            't' => out.push(9),
91            'v' => out.push(11),
92            '\r' => {
93                chars.next_if(|&(_, c)| c == '\n');
94            }
95            '\n' | '\u{2028}' | '\u{2029}' => {}
96            'x' => {
97                let hex = body.get(i + 2..i + 4).unwrap_or("");
98                out.push(u16::from_str_radix(hex, 16).unwrap_or(0));
99                chars.next();
100                chars.next();
101            }
102            'u' => {
103                let (value, len) = unicode_escape(&body[i + 2..]);
104                push_code_point(&mut out, value.unwrap_or(0));
105                for _ in 0..len {
106                    chars.next();
107                }
108            }
109            '0'..='7' => {
110                // LegacyOctalEscapeSequence: up to three digits from 0-3,
111                // two from 4-7, and a lone \0 is NUL.
112                let max = if e <= '3' { 3 } else { 2 };
113                let mut value = e as u32 - '0' as u32;
114                let mut n = 1;
115                while n < max {
116                    match chars.peek() {
117                        Some(&(_, d @ '0'..='7')) => {
118                            value = value * 8 + (d as u32 - '0' as u32);
119                            chars.next();
120                            n += 1;
121                        }
122                        _ => break,
123                    }
124                }
125                out.push(value as u16);
126            }
127            other => push_char(&mut out, other),
128        }
129    }
130    out
131}
132
133/// A template part's cooked value, from its text between delimiters, or
134/// `None` if it has an escape that isn't one. A CR or CRLF in the text is
135/// an LF in the value.
136pub fn template_cooked(body: &str) -> Option<Vec<u16>> {
137    let mut out = Vec::with_capacity(body.len());
138    let mut chars = body.char_indices().peekable();
139    while let Some((i, c)) = chars.next() {
140        if c == '\r' {
141            chars.next_if(|&(_, c)| c == '\n');
142            out.push(10);
143            continue;
144        }
145        if c != '\\' {
146            push_char(&mut out, c);
147            continue;
148        }
149        let Some((_, e)) = chars.next() else { break };
150        match e {
151            'b' => out.push(8),
152            'f' => out.push(12),
153            'n' => out.push(10),
154            'r' => out.push(13),
155            't' => out.push(9),
156            'v' => out.push(11),
157            '\r' => {
158                chars.next_if(|&(_, c)| c == '\n');
159            }
160            c if is_line_terminator(c) => {}
161            '0' if !chars.peek().is_some_and(|&(_, d)| d.is_ascii_digit()) => out.push(0),
162            '0'..='9' => return None,
163            'x' => {
164                let hex = body.get(i + 2..i + 4)?;
165                out.push(u16::from_str_radix(hex, 16).ok()?);
166                chars.next();
167                chars.next();
168            }
169            'u' => {
170                let (value, len) = unicode_escape(&body[i + 2..]);
171                let value = value.filter(|&v| v <= 0x10_FFFF)?;
172                if !body[i + 2..].starts_with('{') && len < 4 {
173                    return None;
174                }
175                push_code_point(&mut out, value);
176                for _ in 0..len {
177                    chars.next();
178                }
179            }
180            other => push_char(&mut out, other),
181        }
182    }
183    Some(out)
184}
185
186/// A template part's raw value: its text, with each CR or CRLF an LF.
187pub fn template_raw(body: &str) -> Cow<'_, str> {
188    if !body.contains('\r') {
189        return Cow::Borrowed(body);
190    }
191    Cow::Owned(body.replace("\r\n", "\n").replace('\r', "\n"))
192}
193
194/// Writes UTF-16 `units` as a JSON string, the way `JSON.stringify`
195/// does: a lone surrogate as `\udxxx`, a control character as an escape,
196/// everything else as itself.
197pub fn write_json_units(out: &mut String, units: &[u16]) {
198    out.push('"');
199    for c in char::decode_utf16(units.iter().copied()) {
200        match c {
201            Ok(c) => push_json_char(out, c),
202            Err(e) => {
203                let _ = write!(out, "\\u{:04x}", e.unpaired_surrogate());
204            }
205        }
206    }
207    out.push('"');
208}
209
210/// Writes `s` as a JSON string.
211pub fn write_json_str(out: &mut String, s: &str) {
212    out.push('"');
213    for c in s.chars() {
214        push_json_char(out, c);
215    }
216    out.push('"');
217}
218
219fn push_json_char(out: &mut String, c: char) {
220    match c {
221        '"' => out.push_str("\\\""),
222        '\\' => out.push_str("\\\\"),
223        '\u{8}' => out.push_str("\\b"),
224        '\u{c}' => out.push_str("\\f"),
225        '\n' => out.push_str("\\n"),
226        '\r' => out.push_str("\\r"),
227        '\t' => out.push_str("\\t"),
228        c if (c as u32) < 0x20 => {
229            let _ = write!(out, "\\u{:04x}", c as u32);
230        }
231        c => out.push(c),
232    }
233}
234
235/// The digits of a numeric literal without its separators and prefix,
236/// and its radix.
237fn digits(raw: &str) -> (String, u32) {
238    let lower = raw.as_bytes().get(1).map(u8::to_ascii_lowercase);
239    let (radix, body) = match (raw.as_bytes().first(), lower) {
240        (Some(b'0'), Some(b'x')) => (16, &raw[2..]),
241        (Some(b'0'), Some(b'o')) => (8, &raw[2..]),
242        (Some(b'0'), Some(b'b')) => (2, &raw[2..]),
243        // A legacy octal literal: all its digits are octal ones.
244        (Some(b'0'), Some(b'0'..=b'7')) if raw.bytes().all(|c| (b'0'..=b'7').contains(&c)) => {
245            (8, &raw[1..])
246        }
247        _ => (10, raw),
248    };
249    (body.chars().filter(|&c| c != '_').collect(), radix)
250}
251
252/// A NumericLiteral's value (not a BigInt's), rounded as the spec says.
253pub fn number_value(raw: &str) -> f64 {
254    let (digits, radix) = digits(raw);
255    if radix == 10 {
256        return digits.parse().unwrap_or(f64::NAN);
257    }
258    // Exact up to 128 bits, and rounded once from there; past that, a
259    // value this long is far outside anything a test or a bundle holds.
260    let mut value: u128 = 0;
261    let mut overflow = 1.0;
262    for c in digits.chars() {
263        let d = c.to_digit(radix).unwrap_or(0) as u128;
264        match value
265            .checked_mul(radix as u128)
266            .and_then(|v| v.checked_add(d))
267        {
268            Some(v) if overflow == 1.0 => value = v,
269            _ => overflow *= radix as f64,
270        }
271    }
272    value as f64 * overflow
273}
274
275/// A BigInt literal's value in decimal, as acorn's `bigint` field has it.
276pub fn bigint_decimal(raw: &str) -> String {
277    let (digits, radix) = digits(raw.strip_suffix('n').unwrap_or(raw));
278    if radix == 10 {
279        return digits;
280    }
281    // Base 10^9 limbs, least significant first.
282    let mut limbs: Vec<u32> = vec![0];
283    for c in digits.chars() {
284        let mut carry = c.to_digit(radix).unwrap_or(0) as u64;
285        for limb in &mut limbs {
286            let v = *limb as u64 * radix as u64 + carry;
287            *limb = (v % 1_000_000_000) as u32;
288            carry = v / 1_000_000_000;
289        }
290        if carry > 0 {
291            limbs.push(carry as u32);
292        }
293    }
294    let mut out = String::new();
295    let mut iter = limbs.iter().rev();
296    let _ = write!(out, "{}", iter.next().unwrap_or(&0));
297    for limb in iter {
298        let _ = write!(out, "{limb:09}");
299    }
300    out
301}
302
303/// `x` as JavaScript's Number::toString writes it, which is what
304/// `JSON.stringify` writes for a finite number.
305pub fn write_js_number(out: &mut String, x: f64) {
306    if !x.is_finite() {
307        out.push_str("null");
308        return;
309    }
310    if x == 0.0 {
311        out.push('0');
312        return;
313    }
314    if x < 0.0 {
315        out.push('-');
316    }
317    // Rust's `{:e}` gives the shortest digits that read back as `x`.
318    let e = format!("{:e}", x.abs());
319    let (mantissa, exp) = e.split_once('e').unwrap_or((&e, "0"));
320    let digits: String = mantissa.chars().filter(|&c| c != '.').collect();
321    let k = digits.len() as i32;
322    let n = exp.parse::<i32>().unwrap_or(0) + 1;
323    if k <= n && n <= 21 {
324        out.push_str(&digits);
325        out.extend(std::iter::repeat_n('0', (n - k) as usize));
326    } else if 0 < n && n <= 21 {
327        out.push_str(&digits[..n as usize]);
328        out.push('.');
329        out.push_str(&digits[n as usize..]);
330    } else if -6 < n && n <= 0 {
331        out.push_str("0.");
332        out.extend(std::iter::repeat_n('0', (-n) as usize));
333        out.push_str(&digits);
334    } else {
335        out.push_str(&digits[..1]);
336        if k > 1 {
337            out.push('.');
338            out.push_str(&digits[1..]);
339        }
340        let _ = write!(out, "e{}{}", if n > 0 { '+' } else { '-' }, (n - 1).abs());
341    }
342}
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347
348    fn number(x: f64) -> String {
349        let mut s = String::new();
350        write_js_number(&mut s, x);
351        s
352    }
353
354    #[test]
355    fn numbers_print_as_javascript_prints_them() {
356        for (x, s) in [
357            (1.0, "1"),
358            (0.1, "0.1"),
359            (123.456, "123.456"),
360            (1e21, "1e+21"),
361            (1e20, "100000000000000000000"),
362            (5e-7, "5e-7"),
363            (0.000001, "0.000001"),
364            (1.5e-10, "1.5e-10"),
365            (-2.5, "-2.5"),
366            (f64::INFINITY, "null"),
367            (2f64.powi(53), "9007199254740992"),
368        ] {
369            assert_eq!(number(x), s);
370        }
371    }
372
373    #[test]
374    fn number_values() {
375        assert_eq!(number_value("0x1_0"), 16.0);
376        assert_eq!(number_value("017"), 15.0);
377        assert_eq!(number_value("019"), 19.0);
378        assert_eq!(number_value("0b101"), 5.0);
379        assert_eq!(number_value(".5e1"), 5.0);
380        assert_eq!(number_value("1_000.5"), 1000.5);
381        assert_eq!(
382            number_value("0xFFFFFFFFFFFFFFFFFF"),
383            4722366482869645213696.0
384        );
385        assert_eq!(bigint_decimal("0x1_0n"), "16");
386        assert_eq!(
387            bigint_decimal("0xFFFFFFFFFFFFFFFFFFFFn"),
388            "1208925819614629174706175"
389        );
390        assert_eq!(bigint_decimal("12n"), "12");
391    }
392
393    #[test]
394    fn string_values() {
395        let s = |body: &str| String::from_utf16(&string_value(body)).unwrap();
396        assert_eq!(s(r"a\nb"), "a\nb");
397        assert_eq!(s(r"\x41B\u{43}"), "ABC");
398        assert_eq!(s("a\\\r\nb"), "ab");
399        assert_eq!(s(r"\101\0\8"), "A\u{0}8");
400        assert_eq!(s(r"\q"), "q");
401        assert_eq!(string_value(r"\uD800"), [0xD800]);
402        let mut out = String::new();
403        write_json_units(&mut out, &string_value(r"\uD800\u0001\x22é"));
404        assert_eq!(out, r#""\ud800\u0001\"é""#);
405    }
406
407    #[test]
408    fn template_values() {
409        let c = |body: &str| template_cooked(body).map(|u| String::from_utf16(&u).unwrap());
410        assert_eq!(c("a\r\nb\rc").as_deref(), Some("a\nb\nc"));
411        assert_eq!(c(r"\01"), None);
412        assert_eq!(c(r"\xg"), None);
413        assert_eq!(c(r"\u{110000}"), None);
414        assert_eq!(c(r"\0"), Some("\0".into()));
415        // Found by the parse fuzz target: an escape cut short before a
416        // character of more than one byte.
417        assert_eq!(c("\\u/00\u{e1}g"), None);
418        assert_eq!(c("\\u00\u{e1}"), None);
419        assert_eq!(template_raw("a\r\nb\r"), "a\nb\n");
420        assert_eq!(ident_name(r"ab\u{63}"), "abc");
421    }
422}