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 #[error("numeric character escape is too short")]
32 TooShortHexEscape,
33 #[error("invalid character in numeric character escape: `{0}`")]
34 InvalidCharInHexEscape(char),
35 #[error("out of range hex escape")]
36 OutOfRangeHexEscape,
37 #[error("non-ASCII character in byte string literal")]
38 NonAsciiInByteString(char),
39 #[error("unicode escape in byte string")]
40 UnicodeEscapeInByteString,
41}
42
43impl EscapeError {
44 pub fn label(self) -> &'static str {
46 match self {
47 Self::UnknownEscape(_) => "unknown character escape",
48 Self::LoneBackslash => "expected an escape character after `\\`",
49 Self::NoBraceInUnicodeEscape => "expected `{` after `\\u`, as in `\\u{1F600}`",
50 Self::UnclosedUnicodeEscape => "missing closing `}`",
51 Self::EmptyUnicodeEscape => "this escape must have at least 1 hex digit",
52 Self::InvalidCharInUnicodeEscape(_) => "not a hexadecimal digit",
53 Self::OverlongUnicodeEscape => "must have at most 6 hex digits",
54 Self::InvalidUnicodeEscape => "not a valid unicode scalar value",
55 Self::TooShortHexEscape => "a hex escape takes two digits, as in `\\x7F`",
56 Self::InvalidCharInHexEscape(_) => "not a hexadecimal digit",
57 Self::OutOfRangeHexEscape => "must be at most `\\x7F` in a string",
58 Self::NonAsciiInByteString(_) => "write non-ASCII bytes as hex escapes, like `\\xFF`",
59 Self::UnicodeEscapeInByteString => "write bytes as hex escapes, like `\\xFF`",
60 }
61 }
62}
63
64pub fn unescape_str(src: &str, mut callback: impl FnMut(Range<usize>, Result<char, EscapeError>)) {
67 unescape(src, Mode::Str, |range, result| {
68 let result = result.map(|code| char::from_u32(code).expect("decoded a valid char"));
69 callback(range, result);
70 });
71}
72
73pub fn unescape_bytes(src: &str, mut callback: impl FnMut(Range<usize>, Result<u8, EscapeError>)) {
76 unescape(src, Mode::Bytes, |range, result| {
77 let result = result.map(|code| u8::try_from(code).expect("decoded a byte"));
78 callback(range, result);
79 });
80}
81
82#[derive(Clone, Copy, PartialEq, Eq)]
84enum Mode {
85 Str,
87 Bytes,
89}
90
91fn unescape(
94 src: &str,
95 mode: Mode,
96 mut callback: impl FnMut(Range<usize>, Result<u32, EscapeError>),
97) {
98 let offset = |rest: &Chars<'_>| src.len() - rest.as_str().len();
99 let mut chars = src.chars();
100 loop {
101 let start = offset(&chars);
102 let result = match chars.next() {
103 None => return,
104 Some('\\') => scan_escape(&mut chars, mode),
105 Some(c) if mode == Mode::Bytes && !c.is_ascii() => {
106 Err(EscapeError::NonAsciiInByteString(c))
107 }
108 Some(c) => Ok(c.into()),
109 };
110 callback(start..offset(&chars), result);
111 }
112}
113
114fn scan_escape(chars: &mut Chars<'_>, mode: Mode) -> Result<u32, EscapeError> {
116 let c = match chars.next().ok_or(EscapeError::LoneBackslash)? {
117 'n' => '\n',
118 'r' => '\r',
119 't' => '\t',
120 '0' => '\0',
121 '\\' => '\\',
122 '"' => '"',
123 '\'' => '\'',
124 'x' => return scan_hex(chars, mode),
125 'u' if mode == Mode::Bytes => return Err(EscapeError::UnicodeEscapeInByteString),
126 'u' => return scan_unicode(chars).map(u32::from),
127 other => return Err(EscapeError::UnknownEscape(other)),
128 };
129 Ok(c.into())
130}
131
132fn scan_hex(chars: &mut Chars<'_>, mode: Mode) -> Result<u32, EscapeError> {
134 let mut value = 0;
135 for _ in 0..2 {
136 let c = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
137 let digit = c
138 .to_digit(16)
139 .ok_or(EscapeError::InvalidCharInHexEscape(c))?;
140 value = value * 16 + digit;
141 }
142 if mode == Mode::Str && value > 0x7F {
143 return Err(EscapeError::OutOfRangeHexEscape);
144 }
145 Ok(value)
146}
147
148fn scan_unicode(chars: &mut Chars<'_>) -> Result<char, EscapeError> {
150 if chars.next() != Some('{') {
151 return Err(EscapeError::NoBraceInUnicodeEscape);
152 }
153 let mut value = 0u32;
154 let mut digits = 0;
155 loop {
156 match chars.next() {
157 None => return Err(EscapeError::UnclosedUnicodeEscape),
158 Some('}') => break,
159 Some(c) => {
160 let digit = c
161 .to_digit(16)
162 .ok_or(EscapeError::InvalidCharInUnicodeEscape(c))?;
163 digits += 1;
164 if digits > 6 {
165 return Err(EscapeError::OverlongUnicodeEscape);
166 }
167 value = value * 16 + digit;
168 }
169 }
170 }
171 if digits == 0 {
172 return Err(EscapeError::EmptyUnicodeEscape);
173 }
174 char::from_u32(value).ok_or(EscapeError::InvalidUnicodeEscape)
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180
181 fn unescape(src: &str) -> Vec<(Range<usize>, Result<char, EscapeError>)> {
182 let mut out = Vec::new();
183 unescape_str(src, |range, result| out.push((range, result)));
184 out
185 }
186
187 fn unescape_ok(src: &str) -> String {
188 unescape(src)
189 .into_iter()
190 .map(|(_, result)| result.expect("valid escape"))
191 .collect()
192 }
193
194 #[test]
195 fn plain_text_passes_through() {
196 assert_eq!(unescape_ok("Hello, {}! α"), "Hello, {}! α");
197 }
198
199 #[test]
200 fn simple_escapes() {
201 assert_eq!(unescape_ok(r#"a\nb\tc\r\0\\\"\'"#), "a\nb\tc\r\0\\\"'");
202 }
203
204 #[test]
205 fn unicode_escapes() {
206 assert_eq!(unescape_ok(r"\u{41}\u{1F600}"), "A😀");
207 }
208
209 #[test]
210 fn ranges_cover_whole_escapes() {
211 let ranges: Vec<_> = unescape(r"a\nα").into_iter().map(|(r, _)| r).collect();
212 assert_eq!(ranges, [0..1, 1..3, 3..5]);
213 }
214
215 #[test]
216 fn hex_escapes() {
217 assert_eq!(unescape_ok(r"\x41\x7f"), "A\x7f");
218 }
219
220 #[test]
221 fn byte_strings() {
222 let mut bytes = Vec::new();
223 unescape_bytes(r"a\xff\n", |_, result| bytes.push(result.unwrap()));
224 assert_eq!(bytes, [b'a', 0xff, b'\n']);
225 let error = |src| {
226 let mut first = None;
227 unescape_bytes(src, |_, result| {
228 first = first.or(result.err());
229 });
230 first
231 };
232 assert_eq!(error("é"), Some(EscapeError::NonAsciiInByteString('é')));
233 assert_eq!(
234 error(r"\u{41}"),
235 Some(EscapeError::UnicodeEscapeInByteString)
236 );
237 }
238
239 #[test]
240 fn errors() {
241 let error = |src| unescape(src).into_iter().find_map(|(_, r)| r.err());
242 assert_eq!(error(r"\q"), Some(EscapeError::UnknownEscape('q')));
243 assert_eq!(error("\\"), Some(EscapeError::LoneBackslash));
244 assert_eq!(error(r"\u41"), Some(EscapeError::NoBraceInUnicodeEscape));
245 assert_eq!(error(r"\u{41"), Some(EscapeError::UnclosedUnicodeEscape));
246 assert_eq!(error(r"\u{}"), Some(EscapeError::EmptyUnicodeEscape));
247 assert_eq!(
248 error(r"\u{4g}"),
249 Some(EscapeError::InvalidCharInUnicodeEscape('g'))
250 );
251 assert_eq!(
252 error(r"\u{1000000}"),
253 Some(EscapeError::OverlongUnicodeEscape)
254 );
255 assert_eq!(error(r"\u{D800}"), Some(EscapeError::InvalidUnicodeEscape));
256 assert_eq!(error(r"\x8"), Some(EscapeError::TooShortHexEscape));
257 assert_eq!(
258 error(r"\xg0"),
259 Some(EscapeError::InvalidCharInHexEscape('g'))
260 );
261 assert_eq!(error(r"\x80"), Some(EscapeError::OutOfRangeHexEscape));
262 }
263}