1 //! Utilities for validating string and char literals and turning them into
2 //! values they represent.
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.
15 /// Expected 1 char, but more than 1 were found.
18 /// Escaped '\' character without continuation.
20 /// Invalid escape character (e.g. '\z').
22 /// Raw '\r' encountered.
24 /// Raw '\r' encountered in raw string.
25 BareCarriageReturnInRawString,
26 /// Unescaped character that was expected to be escaped (e.g. raw '\t').
29 /// Numeric character escape is too short (e.g. '\x1').
31 /// Invalid character in numeric escape (e.g. '\xz')
32 InvalidCharInHexEscape,
33 /// Character code in numeric escape is non-ascii (e.g. '\xFF').
36 /// '\u' not followed by '{'.
37 NoBraceInUnicodeEscape,
38 /// Non-hexadecimal value in '\u{..}'.
39 InvalidCharInUnicodeEscape,
42 /// No closing brace in '\u{..}', e.g. '\u{12'.
43 UnclosedUnicodeEscape,
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,
53 /// Unicode escape code in byte literal.
55 /// Non-ascii character in byte literal.
57 /// Non-ascii character in byte string literal.
58 NonAsciiCharInByteString,
60 /// After a line ending with '\', the next line contains whitespace
61 /// characters that are not skipped.
62 UnskippedWhitespaceWarning,
64 /// After a line ending with '\', multiple lines are skipped.
65 MultipleSkippedLinesWarning,
69 /// Returns true for actual errors, as opposed to warnings.
70 pub fn is_fatal(&self) -> bool {
73 EscapeError::UnskippedWhitespaceWarning | EscapeError::MultipleSkippedLinesWarning
78 /// Takes a contents of a literal (without quotes) and produces a
79 /// sequence of escaped characters or errors.
80 /// Values are returned through invoking of the provided callback.
81 pub fn unescape_literal<F>(literal_text: &str, mode: Mode, callback: &mut F)
83 F: FnMut(Range<usize>, Result<char, EscapeError>),
86 Mode::Char | Mode::Byte => {
87 let mut chars = literal_text.chars();
88 let result = unescape_char_or_byte(&mut chars, mode);
89 // The Chars iterator moved forward.
90 callback(0..(literal_text.len() - chars.as_str().len()), result);
92 Mode::Str | Mode::ByteStr => unescape_str_or_byte_str(literal_text, mode, callback),
93 // NOTE: Raw strings do not perform any explicit character escaping, here we
94 // only translate CRLF to LF and produce errors on bare CR.
95 Mode::RawStr | Mode::RawByteStr => {
96 unescape_raw_str_or_byte_str(literal_text, mode, callback)
101 /// Takes a contents of a byte, byte string or raw byte string (without quotes)
102 /// and produces a sequence of bytes or errors.
103 /// Values are returned through invoking of the provided callback.
104 pub fn unescape_byte_literal<F>(literal_text: &str, mode: Mode, callback: &mut F)
106 F: FnMut(Range<usize>, Result<u8, EscapeError>),
108 assert!(mode.is_bytes());
109 unescape_literal(literal_text, mode, &mut |range, result| {
110 callback(range, result.map(byte_from_char));
114 /// Takes a contents of a char literal (without quotes), and returns an
115 /// unescaped char or an error
116 pub fn unescape_char(literal_text: &str) -> Result<char, (usize, EscapeError)> {
117 let mut chars = literal_text.chars();
118 unescape_char_or_byte(&mut chars, Mode::Char)
119 .map_err(|err| (literal_text.len() - chars.as_str().len(), err))
122 /// Takes a contents of a byte literal (without quotes), and returns an
123 /// unescaped byte or an error.
124 pub fn unescape_byte(literal_text: &str) -> Result<u8, (usize, EscapeError)> {
125 let mut chars = literal_text.chars();
126 unescape_char_or_byte(&mut chars, Mode::Byte)
128 .map_err(|err| (literal_text.len() - chars.as_str().len(), err))
131 /// What kind of literal do we parse.
132 #[derive(Debug, Clone, Copy)]
143 pub fn in_single_quotes(self) -> bool {
145 Mode::Char | Mode::Byte => true,
146 Mode::Str | Mode::ByteStr | Mode::RawStr | Mode::RawByteStr => false,
150 pub fn in_double_quotes(self) -> bool {
151 !self.in_single_quotes()
154 pub fn is_bytes(self) -> bool {
156 Mode::Byte | Mode::ByteStr | Mode::RawByteStr => true,
157 Mode::Char | Mode::Str | Mode::RawStr => false,
162 fn scan_escape(chars: &mut Chars<'_>, mode: Mode) -> Result<char, EscapeError> {
163 // Previous character was '\\', unescape what follows.
165 let second_char = chars.next().ok_or(EscapeError::LoneSlash)?;
167 let res = match second_char {
177 // Parse hexadecimal character code.
179 let hi = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
180 let hi = hi.to_digit(16).ok_or(EscapeError::InvalidCharInHexEscape)?;
182 let lo = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
183 let lo = lo.to_digit(16).ok_or(EscapeError::InvalidCharInHexEscape)?;
185 let value = hi * 16 + lo;
187 // For a byte literal verify that it is within ASCII range.
188 if !mode.is_bytes() && !is_ascii(value) {
189 return Err(EscapeError::OutOfRangeHexEscape);
191 let value = value as u8;
197 // We've parsed '\u', now we have to parse '{..}'.
199 if chars.next() != Some('{') {
200 return Err(EscapeError::NoBraceInUnicodeEscape);
203 // First character must be a hexadecimal digit.
204 let mut n_digits = 1;
205 let mut value: u32 = match chars.next().ok_or(EscapeError::UnclosedUnicodeEscape)? {
206 '_' => return Err(EscapeError::LeadingUnderscoreUnicodeEscape),
207 '}' => return Err(EscapeError::EmptyUnicodeEscape),
208 c => c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?,
211 // First character is valid, now parse the rest of the number
212 // and closing brace.
215 None => return Err(EscapeError::UnclosedUnicodeEscape),
216 Some('_') => continue,
219 return Err(EscapeError::OverlongUnicodeEscape);
222 // Incorrect syntax has higher priority for error reporting
223 // than unallowed value for a literal.
225 return Err(EscapeError::UnicodeEscapeInByte);
228 break std::char::from_u32(value).ok_or_else(|| {
229 if value > 0x10FFFF {
230 EscapeError::OutOfRangeUnicodeEscape
232 EscapeError::LoneSurrogateUnicodeEscape
238 c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?;
241 // Stop updating value since we're sure that it's is incorrect already.
244 let digit = digit as u32;
245 value = value * 16 + digit;
250 _ => return Err(EscapeError::InvalidEscape),
256 fn ascii_check(first_char: char, mode: Mode) -> Result<char, EscapeError> {
257 if mode.is_bytes() && !first_char.is_ascii() {
258 // Byte literal can't be a non-ascii character.
259 Err(EscapeError::NonAsciiCharInByte)
265 fn unescape_char_or_byte(chars: &mut Chars<'_>, mode: Mode) -> Result<char, EscapeError> {
266 let first_char = chars.next().ok_or(EscapeError::ZeroChars)?;
267 let res = match first_char {
268 '\\' => scan_escape(chars, mode),
269 '\n' | '\t' | '\'' => Err(EscapeError::EscapeOnlyChar),
270 '\r' => Err(EscapeError::BareCarriageReturn),
271 _ => ascii_check(first_char, mode),
273 if chars.next().is_some() {
274 return Err(EscapeError::MoreThanOneChar);
279 /// Takes a contents of a string literal (without quotes) and produces a
280 /// sequence of escaped characters or errors.
281 fn unescape_str_or_byte_str<F>(src: &str, mode: Mode, callback: &mut F)
283 F: FnMut(Range<usize>, Result<char, EscapeError>),
285 assert!(mode.in_double_quotes());
286 let initial_len = src.len();
287 let mut chars = src.chars();
288 while let Some(first_char) = chars.next() {
289 let start = initial_len - chars.as_str().len() - first_char.len_utf8();
291 let unescaped_char = match first_char {
293 let second_char = chars.clone().next();
296 // Rust language specification requires us to skip whitespaces
297 // if unescaped '\' character is followed by '\n'.
298 // For details see [Rust language reference]
299 // (https://doc.rust-lang.org/reference/tokens.html#string-literals).
300 skip_ascii_whitespace(&mut chars, start, callback);
303 _ => scan_escape(&mut chars, mode),
308 '"' => Err(EscapeError::EscapeOnlyChar),
309 '\r' => Err(EscapeError::BareCarriageReturn),
310 _ => ascii_check(first_char, mode),
312 let end = initial_len - chars.as_str().len();
313 callback(start..end, unescaped_char);
316 fn skip_ascii_whitespace<F>(chars: &mut Chars<'_>, start: usize, callback: &mut F)
318 F: FnMut(Range<usize>, Result<char, EscapeError>),
320 let tail = chars.as_str();
321 let first_non_space = tail
323 .position(|b| b != b' ' && b != b'\t' && b != b'\n' && b != b'\r')
324 .unwrap_or(tail.len());
325 if tail[1..first_non_space].contains('\n') {
326 // The +1 accounts for the escaping slash.
327 let end = start + first_non_space + 1;
328 callback(start..end, Err(EscapeError::MultipleSkippedLinesWarning));
330 let tail = &tail[first_non_space..];
331 if let Some(c) = tail.chars().nth(0) {
332 // For error reporting, we would like the span to contain the character that was not
333 // skipped. The +1 is necessary to account for the leading \ that started the escape.
334 let end = start + first_non_space + c.len_utf8() + 1;
335 if c.is_whitespace() {
336 callback(start..end, Err(EscapeError::UnskippedWhitespaceWarning));
339 *chars = tail.chars();
343 /// Takes a contents of a string literal (without quotes) and produces a
344 /// sequence of characters or errors.
345 /// NOTE: Raw strings do not perform any explicit character escaping, here we
346 /// only translate CRLF to LF and produce errors on bare CR.
347 fn unescape_raw_str_or_byte_str<F>(literal_text: &str, mode: Mode, callback: &mut F)
349 F: FnMut(Range<usize>, Result<char, EscapeError>),
351 assert!(mode.in_double_quotes());
352 let initial_len = literal_text.len();
354 let mut chars = literal_text.chars();
355 while let Some(curr) = chars.next() {
356 let start = initial_len - chars.as_str().len() - curr.len_utf8();
358 let result = match curr {
359 '\r' => Err(EscapeError::BareCarriageReturnInRawString),
360 c if mode.is_bytes() && !c.is_ascii() => Err(EscapeError::NonAsciiCharInByteString),
363 let end = initial_len - chars.as_str().len();
365 callback(start..end, result);
369 fn byte_from_char(c: char) -> u8 {
371 assert!(res <= u8::MAX as u32, "guaranteed because of Mode::ByteStr");
375 fn is_ascii(x: u32) -> bool {