• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Utilities for validating string and char literals and turning them into
2 //! values they represent.
3 
4 use std::ops::Range;
5 use std::str::Chars;
6 
7 #[cfg(test)]
8 mod tests;
9 
10 /// Errors and warnings that can occur during string unescaping.
11 #[derive(Debug, PartialEq, Eq)]
12 pub enum EscapeError {
13     /// Expected 1 char, but 0 were found.
14     ZeroChars,
15     /// Expected 1 char, but more than 1 were found.
16     MoreThanOneChar,
17 
18     /// Escaped '\' character without continuation.
19     LoneSlash,
20     /// Invalid escape character (e.g. '\z').
21     InvalidEscape,
22     /// Raw '\r' encountered.
23     BareCarriageReturn,
24     /// Raw '\r' encountered in raw string.
25     BareCarriageReturnInRawString,
26     /// Unescaped character that was expected to be escaped (e.g. raw '\t').
27     EscapeOnlyChar,
28 
29     /// Numeric character escape is too short (e.g. '\x1').
30     TooShortHexEscape,
31     /// Invalid character in numeric escape (e.g. '\xz')
32     InvalidCharInHexEscape,
33     /// Character code in numeric escape is non-ascii (e.g. '\xFF').
34     OutOfRangeHexEscape,
35 
36     /// '\u' not followed by '{'.
37     NoBraceInUnicodeEscape,
38     /// Non-hexadecimal value in '\u{..}'.
39     InvalidCharInUnicodeEscape,
40     /// '\u{}'
41     EmptyUnicodeEscape,
42     /// No closing brace in '\u{..}', e.g. '\u{12'.
43     UnclosedUnicodeEscape,
44     /// '\u{_12}'
45     LeadingUnderscoreUnicodeEscape,
46     /// More than 6 characters in '\u{..}', e.g. '\u{10FFFF_FF}'
47     OverlongUnicodeEscape,
48     /// Invalid in-bound unicode character code, e.g. '\u{DFFF}'.
49     LoneSurrogateUnicodeEscape,
50     /// Out of bounds unicode character code, e.g. '\u{FFFFFF}'.
51     OutOfRangeUnicodeEscape,
52 
53     /// Unicode escape code in byte literal.
54     UnicodeEscapeInByte,
55     /// Non-ascii character in byte literal, byte string literal, or raw byte string literal.
56     NonAsciiCharInByte,
57 
58     /// After a line ending with '\', the next line contains whitespace
59     /// characters that are not skipped.
60     UnskippedWhitespaceWarning,
61 
62     /// After a line ending with '\', multiple lines are skipped.
63     MultipleSkippedLinesWarning,
64 }
65 
66 impl EscapeError {
67     /// Returns true for actual errors, as opposed to warnings.
is_fatal(&self) -> bool68     pub fn is_fatal(&self) -> bool {
69         !matches!(
70             self,
71             EscapeError::UnskippedWhitespaceWarning | EscapeError::MultipleSkippedLinesWarning
72         )
73     }
74 }
75 
76 /// Takes a contents of a literal (without quotes) and produces a
77 /// sequence of escaped characters or errors.
78 /// Values are returned through invoking of the provided callback.
unescape_literal<F>(src: &str, mode: Mode, callback: &mut F) where F: FnMut(Range<usize>, Result<char, EscapeError>),79 pub fn unescape_literal<F>(src: &str, mode: Mode, callback: &mut F)
80 where
81     F: FnMut(Range<usize>, Result<char, EscapeError>),
82 {
83     match mode {
84         Mode::Char | Mode::Byte => {
85             let mut chars = src.chars();
86             let res = unescape_char_or_byte(&mut chars, mode == Mode::Byte);
87             callback(0..(src.len() - chars.as_str().len()), res);
88         }
89         Mode::Str | Mode::ByteStr => unescape_str_common(src, mode, callback),
90 
91         Mode::RawStr | Mode::RawByteStr => {
92             unescape_raw_str_or_raw_byte_str(src, mode == Mode::RawByteStr, callback)
93         }
94         Mode::CStr | Mode::RawCStr => unreachable!(),
95     }
96 }
97 
98 /// A unit within CStr. Must not be a nul character.
99 pub enum CStrUnit {
100     Byte(u8),
101     Char(char),
102 }
103 
104 impl From<u8> for CStrUnit {
from(value: u8) -> Self105     fn from(value: u8) -> Self {
106         CStrUnit::Byte(value)
107     }
108 }
109 
110 impl From<char> for CStrUnit {
from(value: char) -> Self111     fn from(value: char) -> Self {
112         CStrUnit::Char(value)
113     }
114 }
115 
unescape_c_string<F>(src: &str, mode: Mode, callback: &mut F) where F: FnMut(Range<usize>, Result<CStrUnit, EscapeError>),116 pub fn unescape_c_string<F>(src: &str, mode: Mode, callback: &mut F)
117 where
118     F: FnMut(Range<usize>, Result<CStrUnit, EscapeError>),
119 {
120     if mode == Mode::RawCStr {
121         unescape_raw_str_or_raw_byte_str(
122             src,
123             mode.characters_should_be_ascii(),
124             &mut |r, result| callback(r, result.map(CStrUnit::Char)),
125         );
126     } else {
127         unescape_str_common(src, mode, callback);
128     }
129 }
130 
131 /// Takes a contents of a char literal (without quotes), and returns an
132 /// unescaped char or an error.
unescape_char(src: &str) -> Result<char, EscapeError>133 pub fn unescape_char(src: &str) -> Result<char, EscapeError> {
134     unescape_char_or_byte(&mut src.chars(), false)
135 }
136 
137 /// Takes a contents of a byte literal (without quotes), and returns an
138 /// unescaped byte or an error.
unescape_byte(src: &str) -> Result<u8, EscapeError>139 pub fn unescape_byte(src: &str) -> Result<u8, EscapeError> {
140     unescape_char_or_byte(&mut src.chars(), true).map(byte_from_char)
141 }
142 
143 /// What kind of literal do we parse.
144 #[derive(Debug, Clone, Copy, PartialEq)]
145 pub enum Mode {
146     Char,
147     Str,
148     Byte,
149     ByteStr,
150     RawStr,
151     RawByteStr,
152     CStr,
153     RawCStr,
154 }
155 
156 impl Mode {
in_double_quotes(self) -> bool157     pub fn in_double_quotes(self) -> bool {
158         match self {
159             Mode::Str
160             | Mode::ByteStr
161             | Mode::RawStr
162             | Mode::RawByteStr
163             | Mode::CStr
164             | Mode::RawCStr => true,
165             Mode::Char | Mode::Byte => false,
166         }
167     }
168 
169     /// Non-byte literals should have `\xXX` escapes that are within the ASCII range.
ascii_escapes_should_be_ascii(self) -> bool170     pub fn ascii_escapes_should_be_ascii(self) -> bool {
171         match self {
172             Mode::Char | Mode::Str | Mode::RawStr => true,
173             Mode::Byte | Mode::ByteStr | Mode::RawByteStr | Mode::CStr | Mode::RawCStr => false,
174         }
175     }
176 
177     /// Whether characters within the literal must be within the ASCII range
characters_should_be_ascii(self) -> bool178     pub fn characters_should_be_ascii(self) -> bool {
179         match self {
180             Mode::Byte | Mode::ByteStr | Mode::RawByteStr => true,
181             Mode::Char | Mode::Str | Mode::RawStr | Mode::CStr | Mode::RawCStr => false,
182         }
183     }
184 
185     /// Byte literals do not allow unicode escape.
is_unicode_escape_disallowed(self) -> bool186     pub fn is_unicode_escape_disallowed(self) -> bool {
187         match self {
188             Mode::Byte | Mode::ByteStr | Mode::RawByteStr => true,
189             Mode::Char | Mode::Str | Mode::RawStr | Mode::CStr | Mode::RawCStr => false,
190         }
191     }
192 
prefix_noraw(self) -> &'static str193     pub fn prefix_noraw(self) -> &'static str {
194         match self {
195             Mode::Byte | Mode::ByteStr | Mode::RawByteStr => "b",
196             Mode::CStr | Mode::RawCStr => "c",
197             Mode::Char | Mode::Str | Mode::RawStr => "",
198         }
199     }
200 }
201 
scan_escape<T: From<u8> + From<char>>( chars: &mut Chars<'_>, mode: Mode, ) -> Result<T, EscapeError>202 fn scan_escape<T: From<u8> + From<char>>(
203     chars: &mut Chars<'_>,
204     mode: Mode,
205 ) -> Result<T, EscapeError> {
206     // Previous character was '\\', unescape what follows.
207     let res = match chars.next().ok_or(EscapeError::LoneSlash)? {
208         '"' => b'"',
209         'n' => b'\n',
210         'r' => b'\r',
211         't' => b'\t',
212         '\\' => b'\\',
213         '\'' => b'\'',
214         '0' => b'\0',
215 
216         'x' => {
217             // Parse hexadecimal character code.
218 
219             let hi = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
220             let hi = hi.to_digit(16).ok_or(EscapeError::InvalidCharInHexEscape)?;
221 
222             let lo = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
223             let lo = lo.to_digit(16).ok_or(EscapeError::InvalidCharInHexEscape)?;
224 
225             let value = hi * 16 + lo;
226 
227             if mode.ascii_escapes_should_be_ascii() && !is_ascii(value) {
228                 return Err(EscapeError::OutOfRangeHexEscape);
229             }
230 
231             value as u8
232         }
233 
234         'u' => return scan_unicode(chars, mode.is_unicode_escape_disallowed()).map(Into::into),
235         _ => return Err(EscapeError::InvalidEscape),
236     };
237     Ok(res.into())
238 }
239 
scan_unicode( chars: &mut Chars<'_>, is_unicode_escape_disallowed: bool, ) -> Result<char, EscapeError>240 fn scan_unicode(
241     chars: &mut Chars<'_>,
242     is_unicode_escape_disallowed: bool,
243 ) -> Result<char, EscapeError> {
244     // We've parsed '\u', now we have to parse '{..}'.
245 
246     if chars.next() != Some('{') {
247         return Err(EscapeError::NoBraceInUnicodeEscape);
248     }
249 
250     // First character must be a hexadecimal digit.
251     let mut n_digits = 1;
252     let mut value: u32 = match chars.next().ok_or(EscapeError::UnclosedUnicodeEscape)? {
253         '_' => return Err(EscapeError::LeadingUnderscoreUnicodeEscape),
254         '}' => return Err(EscapeError::EmptyUnicodeEscape),
255         c => c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?,
256     };
257 
258     // First character is valid, now parse the rest of the number
259     // and closing brace.
260     loop {
261         match chars.next() {
262             None => return Err(EscapeError::UnclosedUnicodeEscape),
263             Some('_') => continue,
264             Some('}') => {
265                 if n_digits > 6 {
266                     return Err(EscapeError::OverlongUnicodeEscape);
267                 }
268 
269                 // Incorrect syntax has higher priority for error reporting
270                 // than unallowed value for a literal.
271                 if is_unicode_escape_disallowed {
272                     return Err(EscapeError::UnicodeEscapeInByte);
273                 }
274 
275                 break std::char::from_u32(value).ok_or_else(|| {
276                     if value > 0x10FFFF {
277                         EscapeError::OutOfRangeUnicodeEscape
278                     } else {
279                         EscapeError::LoneSurrogateUnicodeEscape
280                     }
281                 });
282             }
283             Some(c) => {
284                 let digit: u32 = c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?;
285                 n_digits += 1;
286                 if n_digits > 6 {
287                     // Stop updating value since we're sure that it's incorrect already.
288                     continue;
289                 }
290                 value = value * 16 + digit;
291             }
292         };
293     }
294 }
295 
296 #[inline]
ascii_check(c: char, characters_should_be_ascii: bool) -> Result<char, EscapeError>297 fn ascii_check(c: char, characters_should_be_ascii: bool) -> Result<char, EscapeError> {
298     if characters_should_be_ascii && !c.is_ascii() {
299         // Byte literal can't be a non-ascii character.
300         Err(EscapeError::NonAsciiCharInByte)
301     } else {
302         Ok(c)
303     }
304 }
305 
unescape_char_or_byte(chars: &mut Chars<'_>, is_byte: bool) -> Result<char, EscapeError>306 fn unescape_char_or_byte(chars: &mut Chars<'_>, is_byte: bool) -> Result<char, EscapeError> {
307     let c = chars.next().ok_or(EscapeError::ZeroChars)?;
308     let res = match c {
309         '\\' => scan_escape(chars, if is_byte { Mode::Byte } else { Mode::Char }),
310         '\n' | '\t' | '\'' => Err(EscapeError::EscapeOnlyChar),
311         '\r' => Err(EscapeError::BareCarriageReturn),
312         _ => ascii_check(c, is_byte),
313     }?;
314     if chars.next().is_some() {
315         return Err(EscapeError::MoreThanOneChar);
316     }
317     Ok(res)
318 }
319 
320 /// Takes a contents of a string literal (without quotes) and produces a
321 /// sequence of escaped characters or errors.
unescape_str_common<F, T: From<u8> + From<char>>(src: &str, mode: Mode, callback: &mut F) where F: FnMut(Range<usize>, Result<T, EscapeError>),322 fn unescape_str_common<F, T: From<u8> + From<char>>(src: &str, mode: Mode, callback: &mut F)
323 where
324     F: FnMut(Range<usize>, Result<T, EscapeError>),
325 {
326     let mut chars = src.chars();
327 
328     // The `start` and `end` computation here is complicated because
329     // `skip_ascii_whitespace` makes us to skip over chars without counting
330     // them in the range computation.
331     while let Some(c) = chars.next() {
332         let start = src.len() - chars.as_str().len() - c.len_utf8();
333         let res = match c {
334             '\\' => {
335                 match chars.clone().next() {
336                     Some('\n') => {
337                         // Rust language specification requires us to skip whitespaces
338                         // if unescaped '\' character is followed by '\n'.
339                         // For details see [Rust language reference]
340                         // (https://doc.rust-lang.org/reference/tokens.html#string-literals).
341                         skip_ascii_whitespace(&mut chars, start, &mut |range, err| {
342                             callback(range, Err(err))
343                         });
344                         continue;
345                     }
346                     _ => scan_escape::<T>(&mut chars, mode),
347                 }
348             }
349             '\n' => Ok(b'\n'.into()),
350             '\t' => Ok(b'\t'.into()),
351             '"' => Err(EscapeError::EscapeOnlyChar),
352             '\r' => Err(EscapeError::BareCarriageReturn),
353             _ => ascii_check(c, mode.characters_should_be_ascii()).map(Into::into),
354         };
355         let end = src.len() - chars.as_str().len();
356         callback(start..end, res.map(Into::into));
357     }
358 }
359 
skip_ascii_whitespace<F>(chars: &mut Chars<'_>, start: usize, callback: &mut F) where F: FnMut(Range<usize>, EscapeError),360 fn skip_ascii_whitespace<F>(chars: &mut Chars<'_>, start: usize, callback: &mut F)
361 where
362     F: FnMut(Range<usize>, EscapeError),
363 {
364     let tail = chars.as_str();
365     let first_non_space = tail
366         .bytes()
367         .position(|b| b != b' ' && b != b'\t' && b != b'\n' && b != b'\r')
368         .unwrap_or(tail.len());
369     if tail[1..first_non_space].contains('\n') {
370         // The +1 accounts for the escaping slash.
371         let end = start + first_non_space + 1;
372         callback(start..end, EscapeError::MultipleSkippedLinesWarning);
373     }
374     let tail = &tail[first_non_space..];
375     if let Some(c) = tail.chars().nth(0) {
376         if c.is_whitespace() {
377             // For error reporting, we would like the span to contain the character that was not
378             // skipped. The +1 is necessary to account for the leading \ that started the escape.
379             let end = start + first_non_space + c.len_utf8() + 1;
380             callback(start..end, EscapeError::UnskippedWhitespaceWarning);
381         }
382     }
383     *chars = tail.chars();
384 }
385 
386 /// Takes a contents of a string literal (without quotes) and produces a
387 /// sequence of characters or errors.
388 /// NOTE: Raw strings do not perform any explicit character escaping, here we
389 /// only produce errors on bare CR.
unescape_raw_str_or_raw_byte_str<F>(src: &str, is_byte: bool, callback: &mut F) where F: FnMut(Range<usize>, Result<char, EscapeError>),390 fn unescape_raw_str_or_raw_byte_str<F>(src: &str, is_byte: bool, callback: &mut F)
391 where
392     F: FnMut(Range<usize>, Result<char, EscapeError>),
393 {
394     let mut chars = src.chars();
395 
396     // The `start` and `end` computation here matches the one in
397     // `unescape_str_or_byte_str` for consistency, even though this function
398     // doesn't have to worry about skipping any chars.
399     while let Some(c) = chars.next() {
400         let start = src.len() - chars.as_str().len() - c.len_utf8();
401         let res = match c {
402             '\r' => Err(EscapeError::BareCarriageReturnInRawString),
403             _ => ascii_check(c, is_byte),
404         };
405         let end = src.len() - chars.as_str().len();
406         callback(start..end, res);
407     }
408 }
409 
410 #[inline]
byte_from_char(c: char) -> u8411 pub fn byte_from_char(c: char) -> u8 {
412     let res = c as u32;
413     debug_assert!(res <= u8::MAX as u32, "guaranteed because of Mode::ByteStr");
414     res as u8
415 }
416 
is_ascii(x: u32) -> bool417 fn is_ascii(x: u32) -> bool {
418     x <= 0x7F
419 }
420