Skip to main content

solar_parse/lexer/unescape/
mod.rs

1//! Utilities for validating string and char literals and turning them into values they represent.
2
3use alloy_primitives::hex;
4use solar_ast::Span;
5use solar_data_structures::trustme;
6use solar_interface::{BytePos, Session};
7use std::{borrow::Cow, ops::Range, slice, str::Chars};
8
9mod errors;
10pub use errors::EscapeError;
11pub(crate) use errors::emit_unescape_error;
12
13pub use solar_ast::StrKind;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16enum UnescapedUnit {
17    Byte(u8),
18    CodePoint(u32),
19}
20
21impl UnescapedUnit {
22    fn code_point(self) -> u32 {
23        match self {
24            Self::Byte(byte) => byte as u32,
25            Self::CodePoint(code) => code,
26        }
27    }
28
29    fn write(self, dst: &mut [u8]) -> usize {
30        match self {
31            Self::Byte(byte) => {
32                dst[0] = byte;
33                1
34            }
35            // NOTE: We can't use `char::encode_utf8` because `code` can be an invalid unicode
36            // code.
37            Self::CodePoint(code) => super::utf8::encode_utf8_raw(code, dst).len(),
38        }
39    }
40}
41
42pub fn parse_string_literal<'a>(
43    src: &'a str,
44    kind: StrKind,
45    lit_span: Span,
46    sess: &Session,
47) -> (Cow<'a, [u8]>, bool) {
48    let mut has_error = false;
49    let content_start = lit_span.lo() + BytePos(1) + BytePos(kind.prefix().len() as u32);
50    let bytes = try_parse_string_literal(src, kind, |range, error| {
51        has_error = true;
52        let (start, end) = (range.start as u32, range.end as u32);
53        let lo = content_start + BytePos(start);
54        let hi = lo + BytePos(end - start);
55        let span = Span::new(lo, hi);
56        emit_unescape_error(&sess.dcx, src, span, range, error);
57    });
58    (bytes, has_error)
59}
60
61/// Parses a string literal (without quotes) into a byte array.
62/// `f` is called for each escape error.
63#[instrument(name = "parse_string_literal", level = "trace", skip_all)]
64pub fn try_parse_string_literal<F>(src: &str, kind: StrKind, f: F) -> Cow<'_, [u8]>
65where
66    F: FnMut(Range<usize>, EscapeError),
67{
68    let mut bytes = if needs_unescape(src, kind) {
69        Cow::Owned(parse_literal_unescape(src, kind, f))
70    } else {
71        Cow::Borrowed(src.as_bytes())
72    };
73    if kind == StrKind::Hex {
74        // Currently this should never fail, but it's a good idea to check anyway.
75        if let Ok(decoded) = hex::decode(&bytes) {
76            bytes = Cow::Owned(decoded);
77        }
78    }
79    bytes
80}
81
82#[cold]
83fn parse_literal_unescape<F>(src: &str, kind: StrKind, f: F) -> Vec<u8>
84where
85    F: FnMut(Range<usize>, EscapeError),
86{
87    let mut bytes = Vec::with_capacity(src.len());
88    parse_literal_unescape_into(src, kind, f, &mut bytes);
89    bytes
90}
91
92fn parse_literal_unescape_into<F>(src: &str, kind: StrKind, mut f: F, dst_buf: &mut Vec<u8>)
93where
94    F: FnMut(Range<usize>, EscapeError),
95{
96    // `src.len()` is enough capacity for the unescaped string, so we can just use a slice.
97    // SAFETY: The buffer is never read from.
98    debug_assert!(dst_buf.is_empty());
99    debug_assert!(dst_buf.capacity() >= src.len());
100    let mut dst = unsafe { slice::from_raw_parts_mut(dst_buf.as_mut_ptr(), dst_buf.capacity()) };
101    unescape_literal_unchecked(src, kind, |range, res| match res {
102        Ok(c) => {
103            let written = c.write(dst);
104
105            // SAFETY: Unescaping guarantees that the final unescaped byte array is shorter than
106            // the initial string.
107            debug_assert!(dst.len() >= written);
108            let advanced = unsafe { dst.get_unchecked_mut(written..) };
109
110            // SAFETY: I don't know why this triggers E0521.
111            dst = unsafe { trustme::decouple_lt_mut(advanced) };
112        }
113        Err(e) => f(range, e),
114    });
115    unsafe { dst_buf.set_len(dst_buf.capacity() - dst.len()) };
116}
117
118/// Unescapes the contents of a string literal (without quotes).
119///
120/// The callback is invoked with a range and either a unicode code point or an error.
121#[instrument(level = "debug", skip_all)]
122pub fn unescape_literal<F>(src: &str, kind: StrKind, mut callback: F)
123where
124    F: FnMut(Range<usize>, Result<u32, EscapeError>),
125{
126    if needs_unescape(src, kind) {
127        unescape_literal_unchecked(src, kind, |range, res| {
128            callback(range, res.map(UnescapedUnit::code_point));
129        });
130    } else {
131        for (i, ch) in src.char_indices() {
132            callback(i..i + ch.len_utf8(), Ok(ch as u32));
133        }
134    }
135}
136
137/// Unescapes the contents of a string literal (without quotes).
138///
139/// See [`unescape_literal`] for more details.
140fn unescape_literal_unchecked<F>(src: &str, kind: StrKind, callback: F)
141where
142    F: FnMut(Range<usize>, Result<UnescapedUnit, EscapeError>),
143{
144    match kind {
145        StrKind::Str | StrKind::Unicode => {
146            unescape_str(src, matches!(kind, StrKind::Unicode), callback)
147        }
148        StrKind::Hex => unescape_hex_str(src, callback),
149    }
150}
151
152/// Fast-path check for whether a string literal needs to be unescaped or errors need to be
153/// reported.
154fn needs_unescape(src: &str, kind: StrKind) -> bool {
155    fn needs_unescape_chars(src: &str) -> bool {
156        memchr::memchr3(b'\\', b'\n', b'\r', src.as_bytes()).is_some()
157    }
158
159    match kind {
160        StrKind::Str => needs_unescape_chars(src) || !src.is_ascii(),
161        StrKind::Unicode => needs_unescape_chars(src),
162        StrKind::Hex => !src.len().is_multiple_of(2) || !hex::check_raw(src),
163    }
164}
165
166fn scan_escape(chars: &mut Chars<'_>) -> Result<UnescapedUnit, EscapeError> {
167    // Previous character was '\\', unescape what follows.
168    // https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityLexer.EscapeSequence
169    // Note that hex and unicode escape codes are not validated since string literals are allowed
170    // to contain invalid UTF-8.
171    let unit = match chars.next().ok_or(EscapeError::LoneSlash)? {
172        // Both quotes are always valid escapes.
173        '\'' => UnescapedUnit::CodePoint('\'' as u32),
174        '"' => UnescapedUnit::CodePoint('"' as u32),
175
176        '\\' => UnescapedUnit::CodePoint('\\' as u32),
177        'n' => UnescapedUnit::CodePoint('\n' as u32),
178        'r' => UnescapedUnit::CodePoint('\r' as u32),
179        't' => UnescapedUnit::CodePoint('\t' as u32),
180
181        'x' => {
182            // Parse hexadecimal character code.
183            let mut value = 0;
184            for _ in 0..2 {
185                let d = chars.next().ok_or(EscapeError::HexEscapeTooShort)?;
186                let d = d.to_digit(16).ok_or(EscapeError::InvalidHexEscape)?;
187                value = value * 16 + d;
188            }
189            UnescapedUnit::Byte(value as u8)
190        }
191
192        'u' => {
193            // Parse hexadecimal unicode character code.
194            let mut value = 0;
195            for _ in 0..4 {
196                let d = chars.next().ok_or(EscapeError::UnicodeEscapeTooShort)?;
197                let d = d.to_digit(16).ok_or(EscapeError::InvalidUnicodeEscape)?;
198                value = value * 16 + d;
199            }
200            UnescapedUnit::CodePoint(value)
201        }
202
203        _ => return Err(EscapeError::InvalidEscape),
204    };
205    Ok(unit)
206}
207
208/// Unescape characters in a string literal.
209///
210/// See [`unescape_literal`] for more details.
211fn unescape_str<F>(src: &str, is_unicode: bool, mut callback: F)
212where
213    F: FnMut(Range<usize>, Result<UnescapedUnit, EscapeError>),
214{
215    let mut chars = src.chars();
216    while let Some(c) = chars.next() {
217        let start = src.len() - chars.as_str().len() - c.len_utf8();
218        let res = match c {
219            '\\' => match chars.clone().next() {
220                Some('\r') if chars.clone().nth(1) == Some('\n') => {
221                    chars.next();
222                    chars.next();
223                    continue;
224                }
225                Some('\n') => {
226                    chars.next();
227                    continue;
228                }
229                _ => scan_escape(&mut chars),
230            },
231            '\n' => Err(EscapeError::StrNewline),
232            '\r' => {
233                if chars.clone().next() == Some('\n') {
234                    continue;
235                }
236                Err(EscapeError::BareCarriageReturn)
237            }
238            c if !is_unicode && !c.is_ascii() => Err(EscapeError::StrNonAsciiChar),
239            c => Ok(UnescapedUnit::CodePoint(c as u32)),
240        };
241        let end = src.len() - chars.as_str().len();
242        callback(start..end, res);
243    }
244}
245
246/// Unescape characters in a hex string literal.
247///
248/// See [`unescape_literal`] for more details.
249fn unescape_hex_str<F>(src: &str, mut callback: F)
250where
251    F: FnMut(Range<usize>, Result<UnescapedUnit, EscapeError>),
252{
253    let mut chars = src.char_indices();
254    if src.starts_with("0x") || src.starts_with("0X") {
255        chars.next();
256        chars.next();
257        callback(0..2, Err(EscapeError::HexPrefix));
258    }
259
260    let count = chars.clone().filter(|(_, c)| c.is_ascii_hexdigit()).count();
261    if !count.is_multiple_of(2) {
262        callback(0..src.len(), Err(EscapeError::HexOddDigits));
263        return;
264    }
265
266    let mut emit_underscore_errors = true;
267    let mut allow_underscore = false;
268    let mut even = true;
269    for (start, c) in chars {
270        let res = match c {
271            '_' => {
272                if emit_underscore_errors && (!allow_underscore || !even) {
273                    // Don't spam errors for multiple underscores.
274                    emit_underscore_errors = false;
275                    Err(EscapeError::HexBadUnderscore)
276                } else {
277                    allow_underscore = false;
278                    continue;
279                }
280            }
281            c if !c.is_ascii_hexdigit() => Err(EscapeError::HexNotHexDigit),
282            c => Ok(UnescapedUnit::CodePoint(c as u32)),
283        };
284
285        if res.is_ok() {
286            even = !even;
287            allow_underscore = true;
288        }
289
290        let end = start + c.len_utf8();
291        callback(start..end, res);
292    }
293
294    if emit_underscore_errors && src.len() > 1 && src.ends_with('_') {
295        callback(src.len() - 1..src.len(), Err(EscapeError::HexBadUnderscore));
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302    use EscapeError::*;
303
304    type ExErr = (Range<usize>, EscapeError);
305
306    #[track_caller]
307    fn check_parse(kind: StrKind, src: &str, expected: &[u8]) {
308        let out = try_parse_string_literal(src, kind, |_, e| panic!("{e:?}"));
309        assert_eq!(&*out, expected, "{kind:?}: {src:?}");
310    }
311
312    #[track_caller]
313    fn check_unescape(kind: StrKind, src: &str, expected: &str) {
314        let mut out = String::new();
315        unescape_literal(src, kind, |_, c| out.push(char::try_from(c.unwrap()).unwrap()));
316        assert_eq!(out, expected, "{kind:?}: {src:?}");
317    }
318
319    fn check(kind: StrKind, src: &str, expected_str: &str, expected_errs: &[ExErr]) {
320        let panic_str = format!("{kind:?}: {src:?}");
321
322        let mut ok = String::with_capacity(src.len());
323        let mut errs = Vec::with_capacity(expected_errs.len());
324        unescape_literal(src, kind, |range, c| match c {
325            Ok(c) => ok.push(char::try_from(c).unwrap()),
326            Err(e) => errs.push((range, e)),
327        });
328        assert_eq!(errs, expected_errs, "{panic_str}");
329        assert_eq!(ok, expected_str, "{panic_str}");
330
331        let mut errs2 = Vec::with_capacity(errs.len());
332        let out = try_parse_string_literal(src, kind, |range, e| {
333            errs2.push((range, e));
334        });
335        assert_eq!(errs2, errs, "{panic_str}");
336        if kind == StrKind::Hex {
337            assert_eq!(hex::encode(out), expected_str, "{panic_str}");
338        } else {
339            assert_eq!(hex::encode(out), hex::encode(expected_str), "{panic_str}");
340        }
341    }
342
343    #[test]
344    fn unescape_str() {
345        let cases: &[(&str, &str, &[ExErr])] = &[
346            ("", "", &[]),
347            (" ", " ", &[]),
348            ("\t", "\t", &[]),
349            (" \t ", " \t ", &[]),
350            ("foo", "foo", &[]),
351            ("hello world", "hello world", &[]),
352            (r"\", "", &[(0..1, LoneSlash)]),
353            (r"\\", "\\", &[]),
354            (r"\\\", "\\", &[(2..3, LoneSlash)]),
355            (r"\\\\", "\\\\", &[]),
356            (r"\\ ", "\\ ", &[]),
357            (r"\\ \", "\\ ", &[(3..4, LoneSlash)]),
358            (r"\\ \\", "\\ \\", &[]),
359            (r"\x", "", &[(0..2, HexEscapeTooShort)]),
360            (r"\x1", "", &[(0..3, HexEscapeTooShort)]),
361            (r"\xz", "", &[(0..3, InvalidHexEscape)]),
362            (r"\xzf", "f", &[(0..3, InvalidHexEscape)]),
363            (r"\xzz", "z", &[(0..3, InvalidHexEscape)]),
364            (r"\x69", "\x69", &[]),
365            (r"\u", "", &[(0..2, UnicodeEscapeTooShort)]),
366            (r"\u1", "", &[(0..3, UnicodeEscapeTooShort)]),
367            (r"\uz", "", &[(0..3, InvalidUnicodeEscape)]),
368            (r"\uzf", "f", &[(0..3, InvalidUnicodeEscape)]),
369            (r"\u12", "", &[(0..4, UnicodeEscapeTooShort)]),
370            (r"\u123", "", &[(0..5, UnicodeEscapeTooShort)]),
371            (r"\u1234", "\u{1234}", &[]),
372            (r"\u00e8", "è", &[]),
373            (r"\r", "\r", &[]),
374            (r"\t", "\t", &[]),
375            (r"\n", "\n", &[]),
376            (r"\n\n", "\n\n", &[]),
377            (r"\ ", "", &[(0..2, InvalidEscape)]),
378            (r"\?", "", &[(0..2, InvalidEscape)]),
379            ("\r\n", "", &[(1..2, StrNewline)]),
380            ("\n", "", &[(0..1, StrNewline)]),
381            ("\\\n", "", &[]),
382            ("\\\na", "a", &[]),
383            ("\\\n  a", "  a", &[]),
384            ("a \\\n  b", "a   b", &[]),
385            ("a\\n\\\n  b", "a\n  b", &[]),
386            ("a\\t\\\n  b", "a\t  b", &[]),
387            ("a\\n \\\n  b", "a\n   b", &[]),
388            ("a\\n \\\n \tb", "a\n  \tb", &[]),
389            ("a\\t \\\n  b", "a\t   b", &[]),
390            ("\\\n \t a", " \t a", &[]),
391            (" \\\n \t a", "  \t a", &[]),
392            ("\\\n \t a\n", " \t a", &[(6..7, StrNewline)]),
393            ("\\\n   \t   ", "   \t   ", &[]),
394            (" \\\n   \t   ", "    \t   ", &[]),
395            (" he\\\n \\\nllo \\\n wor\\\nld", " he llo  world", &[]),
396            ("\\\n\na\\\nb", "ab", &[(2..3, StrNewline)]),
397            ("\\\n \na\\\nb", " ab", &[(3..4, StrNewline)]),
398            ("\\\n \n\na\\\nb", " ab", &[(3..4, StrNewline), (4..5, StrNewline)]),
399            ("a\\\n \n \t \nb\\\nc", "a  \t bc", &[(4..5, StrNewline), (8..9, StrNewline)]),
400        ];
401        for &(src, expected_str, expected_errs) in cases {
402            check(StrKind::Str, src, expected_str, expected_errs);
403            check(StrKind::Unicode, src, expected_str, expected_errs);
404        }
405
406        check_unescape(StrKind::Str, r"\xE8", "è");
407        check_unescape(StrKind::Unicode, r"\xE8", "è");
408        check_parse(StrKind::Str, r"\xE8", b"\xE8");
409        check_parse(StrKind::Unicode, r"\xE8", b"\xE8");
410        check_parse(StrKind::Str, r"\u00e8", "è".as_bytes());
411        check_parse(StrKind::Unicode, r"\u00e8", "è".as_bytes());
412        check_parse(StrKind::Str, r"\xE8\u00e8", b"\xE8\xc3\xa8");
413        check_parse(StrKind::Unicode, r"\xE8\u00e8", b"\xE8\xc3\xa8");
414    }
415
416    #[test]
417    fn line_continuation_before_form_feed() {
418        check(StrKind::Str, "\\\n\x0cafter", "\x0cafter", &[]);
419        check(StrKind::Str, "\\\r\n \t\x0cafter", " \t\x0cafter", &[]);
420    }
421
422    #[test]
423    fn line_continuation_before_vertical_tab() {
424        check(StrKind::Str, "\\\n\x0bafter", "\x0bafter", &[]);
425    }
426
427    #[test]
428    fn line_continuation_before_bare_carriage_return() {
429        check(StrKind::Str, "\\\n\rafter", "after", &[(2..3, BareCarriageReturn)]);
430    }
431
432    #[test]
433    fn unescape_unicode_str() {
434        let cases: &[(&str, &str, &[ExErr], &[ExErr])] = &[
435            ("è", "è", &[], &[(0..2, StrNonAsciiChar)]),
436            ("😀", "😀", &[], &[(0..4, StrNonAsciiChar)]),
437        ];
438        for &(src, expected_str, e1, e2) in cases {
439            check(StrKind::Unicode, src, expected_str, e1);
440            check(StrKind::Str, src, "", e2);
441        }
442
443        check_parse(StrKind::Unicode, "😃, 😭,\\\n and 😈", "😃, 😭, and 😈".as_bytes());
444    }
445
446    #[test]
447    fn unescape_hex_str() {
448        let cases: &[(&str, &str, &[ExErr])] = &[
449            ("", "", &[]),
450            ("z", "", &[(0..1, HexNotHexDigit)]),
451            ("\n", "", &[(0..1, HexNotHexDigit)]),
452            ("  11", "11", &[(0..1, HexNotHexDigit), (1..2, HexNotHexDigit)]),
453            ("0x", "", &[(0..2, HexPrefix)]),
454            ("0X", "", &[(0..2, HexPrefix)]),
455            ("0x11", "11", &[(0..2, HexPrefix)]),
456            ("0X11", "11", &[(0..2, HexPrefix)]),
457            ("1", "", &[(0..1, HexOddDigits)]),
458            ("12", "12", &[]),
459            ("123", "", &[(0..3, HexOddDigits)]),
460            ("1234", "1234", &[]),
461            ("_", "", &[(0..1, HexBadUnderscore)]),
462            ("_11", "11", &[(0..1, HexBadUnderscore)]),
463            ("_11_", "11", &[(0..1, HexBadUnderscore)]),
464            ("11_", "11", &[(2..3, HexBadUnderscore)]),
465            ("11_22", "1122", &[]),
466            ("11__", "11", &[(3..4, HexBadUnderscore)]),
467            ("11__22", "1122", &[(3..4, HexBadUnderscore)]),
468            ("1_2", "12", &[(1..2, HexBadUnderscore)]),
469        ];
470        for &(src, expected_str, expected_errs) in cases {
471            check(StrKind::Hex, src, expected_str, expected_errs);
472        }
473    }
474}