1use std::ops::Range;
9use std::str::Chars;
10
11use thiserror::Error;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
14pub enum EscapeError {
15 #[error("unknown character escape: `{0}`")]
16 UnknownEscape(char),
17 #[error("incomplete escape sequence")]
18 LoneBackslash,
19 #[error("incorrect unicode escape sequence")]
20 NoBraceInUnicodeEscape,
21 #[error("unterminated unicode escape")]
22 UnclosedUnicodeEscape,
23 #[error("empty unicode escape")]
24 EmptyUnicodeEscape,
25 #[error("invalid character in unicode escape: `{0}`")]
26 InvalidCharInUnicodeEscape(char),
27 #[error("overlong unicode escape")]
28 OverlongUnicodeEscape,
29 #[error("invalid unicode character escape")]
30 InvalidUnicodeEscape,
31}
32
33impl EscapeError {
34 pub fn label(self) -> &'static str {
36 match self {
37 Self::UnknownEscape(_) => "unknown character escape",
38 Self::LoneBackslash => "expected an escape character after `\\`",
39 Self::NoBraceInUnicodeEscape => "expected `{` after `\\u`, as in `\\u{1F600}`",
40 Self::UnclosedUnicodeEscape => "missing closing `}`",
41 Self::EmptyUnicodeEscape => "this escape must have at least 1 hex digit",
42 Self::InvalidCharInUnicodeEscape(_) => "not a hexadecimal digit",
43 Self::OverlongUnicodeEscape => "must have at most 6 hex digits",
44 Self::InvalidUnicodeEscape => "not a valid unicode scalar value",
45 }
46 }
47}
48
49pub fn unescape_str(src: &str, mut callback: impl FnMut(Range<usize>, Result<char, EscapeError>)) {
52 let offset = |rest: &Chars<'_>| src.len() - rest.as_str().len();
53 let mut chars = src.chars();
54 loop {
55 let start = offset(&chars);
56 let result = match chars.next() {
57 None => return,
58 Some('\\') => scan_escape(&mut chars),
59 Some(c) => Ok(c),
60 };
61 callback(start..offset(&chars), result);
62 }
63}
64
65fn scan_escape(chars: &mut Chars<'_>) -> Result<char, EscapeError> {
67 let c = match chars.next().ok_or(EscapeError::LoneBackslash)? {
68 'n' => '\n',
69 'r' => '\r',
70 't' => '\t',
71 '0' => '\0',
72 '\\' => '\\',
73 '"' => '"',
74 '\'' => '\'',
75 'u' => return scan_unicode(chars),
76 other => return Err(EscapeError::UnknownEscape(other)),
77 };
78 Ok(c)
79}
80
81fn scan_unicode(chars: &mut Chars<'_>) -> Result<char, EscapeError> {
83 if chars.next() != Some('{') {
84 return Err(EscapeError::NoBraceInUnicodeEscape);
85 }
86 let mut value = 0u32;
87 let mut digits = 0;
88 loop {
89 match chars.next() {
90 None => return Err(EscapeError::UnclosedUnicodeEscape),
91 Some('}') => break,
92 Some(c) => {
93 let digit = c
94 .to_digit(16)
95 .ok_or(EscapeError::InvalidCharInUnicodeEscape(c))?;
96 digits += 1;
97 if digits > 6 {
98 return Err(EscapeError::OverlongUnicodeEscape);
99 }
100 value = value * 16 + digit;
101 }
102 }
103 }
104 if digits == 0 {
105 return Err(EscapeError::EmptyUnicodeEscape);
106 }
107 char::from_u32(value).ok_or(EscapeError::InvalidUnicodeEscape)
108}
109
110#[cfg(test)]
111mod tests {
112 use super::*;
113
114 fn unescape(src: &str) -> Vec<(Range<usize>, Result<char, EscapeError>)> {
115 let mut out = Vec::new();
116 unescape_str(src, |range, result| out.push((range, result)));
117 out
118 }
119
120 fn unescape_ok(src: &str) -> String {
121 unescape(src)
122 .into_iter()
123 .map(|(_, result)| result.expect("valid escape"))
124 .collect()
125 }
126
127 #[test]
128 fn plain_text_passes_through() {
129 assert_eq!(unescape_ok("Hello, {}! α"), "Hello, {}! α");
130 }
131
132 #[test]
133 fn simple_escapes() {
134 assert_eq!(unescape_ok(r#"a\nb\tc\r\0\\\"\'"#), "a\nb\tc\r\0\\\"'");
135 }
136
137 #[test]
138 fn unicode_escapes() {
139 assert_eq!(unescape_ok(r"\u{41}\u{1F600}"), "A😀");
140 }
141
142 #[test]
143 fn ranges_cover_whole_escapes() {
144 let ranges: Vec<_> = unescape(r"a\nα").into_iter().map(|(r, _)| r).collect();
145 assert_eq!(ranges, [0..1, 1..3, 3..5]);
146 }
147
148 #[test]
149 fn errors() {
150 let error = |src| unescape(src).into_iter().find_map(|(_, r)| r.err());
151 assert_eq!(error(r"\q"), Some(EscapeError::UnknownEscape('q')));
152 assert_eq!(error("\\"), Some(EscapeError::LoneBackslash));
153 assert_eq!(error(r"\u41"), Some(EscapeError::NoBraceInUnicodeEscape));
154 assert_eq!(error(r"\u{41"), Some(EscapeError::UnclosedUnicodeEscape));
155 assert_eq!(error(r"\u{}"), Some(EscapeError::EmptyUnicodeEscape));
156 assert_eq!(
157 error(r"\u{4g}"),
158 Some(EscapeError::InvalidCharInUnicodeEscape('g'))
159 );
160 assert_eq!(
161 error(r"\u{1000000}"),
162 Some(EscapeError::OverlongUnicodeEscape)
163 );
164 assert_eq!(error(r"\u{D800}"), Some(EscapeError::InvalidUnicodeEscape));
165 }
166}