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 {
72 EscapeError::UnskippedWhitespaceWarning => false,
73 EscapeError::MultipleSkippedLinesWarning => false,
79 /// Takes a contents of a literal (without quotes) and produces a
80 /// sequence of escaped characters or errors.
81 /// Values are returned through invoking of the provided callback.
82 pub fn unescape_literal<F>(literal_text: &str, mode: Mode, callback: &mut F)
84 F: FnMut(Range<usize>, Result<char, EscapeError>),
87 Mode::Char | Mode::Byte => {
88 let mut chars = literal_text.chars();
89 let result = unescape_char_or_byte(&mut chars, mode);
90 // The Chars iterator moved forward.
91 callback(0..(literal_text.len() - chars.as_str().len()), result);
93 Mode::Str | Mode::ByteStr => unescape_str_or_byte_str(literal_text, mode, callback),
94 // NOTE: Raw strings do not perform any explicit character escaping, here we
95 // only translate CRLF to LF and produce errors on bare CR.
96 Mode::RawStr | Mode::RawByteStr => {
97 unescape_raw_str_or_byte_str(literal_text, mode, callback)
102 /// Takes a contents of a byte, byte string or raw byte string (without quotes)
103 /// and produces a sequence of bytes or errors.
104 /// Values are returned through invoking of the provided callback.
105 pub fn unescape_byte_literal<F>(literal_text: &str, mode: Mode, callback: &mut F)
107 F: FnMut(Range<usize>, Result<u8, EscapeError>),
109 assert!(mode.is_bytes());
110 unescape_literal(literal_text, mode, &mut |range, result| {
111 callback(range, result.map(byte_from_char));
115 /// Takes a contents of a char literal (without quotes), and returns an
116 /// unescaped char or an error
117 pub fn unescape_char(literal_text: &str) -> Result<char, (usize, EscapeError)> {
118 let mut chars = literal_text.chars();
119 unescape_char_or_byte(&mut chars, Mode::Char)
120 .map_err(|err| (literal_text.len() - chars.as_str().len(), err))
123 /// Takes a contents of a byte literal (without quotes), and returns an
124 /// unescaped byte or an error.
125 pub fn unescape_byte(literal_text: &str) -> Result<u8, (usize, EscapeError)> {
126 let mut chars = literal_text.chars();
127 unescape_char_or_byte(&mut chars, Mode::Byte)
129 .map_err(|err| (literal_text.len() - chars.as_str().len(), err))
132 /// What kind of literal do we parse.
133 #[derive(Debug, Clone, Copy)]
144 pub fn in_single_quotes(self) -> bool {
146 Mode::Char | Mode::Byte => true,
147 Mode::Str | Mode::ByteStr | Mode::RawStr | Mode::RawByteStr => false,
151 pub fn in_double_quotes(self) -> bool {
152 !self.in_single_quotes()
155 pub fn is_bytes(self) -> bool {
157 Mode::Byte | Mode::ByteStr | Mode::RawByteStr => true,
158 Mode::Char | Mode::Str | Mode::RawStr => false,
163 fn scan_escape(first_char: char, chars: &mut Chars<'_>, mode: Mode) -> Result<char, EscapeError> {
164 if first_char != '\\' {
165 // Previous character was not a slash, and we don't expect it to be
166 // an escape-only character.
167 return match first_char {
168 '\t' | '\n' => Err(EscapeError::EscapeOnlyChar),
169 '\r' => Err(EscapeError::BareCarriageReturn),
170 '\'' if mode.in_single_quotes() => Err(EscapeError::EscapeOnlyChar),
171 '"' if mode.in_double_quotes() => Err(EscapeError::EscapeOnlyChar),
173 if mode.is_bytes() && !first_char.is_ascii() {
174 // Byte literal can't be a non-ascii character.
175 return Err(EscapeError::NonAsciiCharInByte);
182 // Previous character is '\\', try to unescape it.
184 let second_char = chars.next().ok_or(EscapeError::LoneSlash)?;
186 let res = match second_char {
196 // Parse hexadecimal character code.
198 let hi = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
199 let hi = hi.to_digit(16).ok_or(EscapeError::InvalidCharInHexEscape)?;
201 let lo = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
202 let lo = lo.to_digit(16).ok_or(EscapeError::InvalidCharInHexEscape)?;
204 let value = hi * 16 + lo;
206 // For a byte literal verify that it is within ASCII range.
207 if !mode.is_bytes() && !is_ascii(value) {
208 return Err(EscapeError::OutOfRangeHexEscape);
210 let value = value as u8;
216 // We've parsed '\u', now we have to parse '{..}'.
218 if chars.next() != Some('{') {
219 return Err(EscapeError::NoBraceInUnicodeEscape);
222 // First character must be a hexadecimal digit.
223 let mut n_digits = 1;
224 let mut value: u32 = match chars.next().ok_or(EscapeError::UnclosedUnicodeEscape)? {
225 '_' => return Err(EscapeError::LeadingUnderscoreUnicodeEscape),
226 '}' => return Err(EscapeError::EmptyUnicodeEscape),
227 c => c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?,
230 // First character is valid, now parse the rest of the number
231 // and closing brace.
234 None => return Err(EscapeError::UnclosedUnicodeEscape),
235 Some('_') => continue,
238 return Err(EscapeError::OverlongUnicodeEscape);
241 // Incorrect syntax has higher priority for error reporting
242 // than unallowed value for a literal.
244 return Err(EscapeError::UnicodeEscapeInByte);
247 break std::char::from_u32(value).ok_or_else(|| {
248 if value > 0x10FFFF {
249 EscapeError::OutOfRangeUnicodeEscape
251 EscapeError::LoneSurrogateUnicodeEscape
257 c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?;
260 // Stop updating value since we're sure that it's is incorrect already.
263 let digit = digit as u32;
264 value = value * 16 + digit;
269 _ => return Err(EscapeError::InvalidEscape),
274 fn unescape_char_or_byte(chars: &mut Chars<'_>, mode: Mode) -> Result<char, EscapeError> {
275 let first_char = chars.next().ok_or(EscapeError::ZeroChars)?;
276 let res = scan_escape(first_char, chars, mode)?;
277 if chars.next().is_some() {
278 return Err(EscapeError::MoreThanOneChar);
283 /// Takes a contents of a string literal (without quotes) and produces a
284 /// sequence of escaped characters or errors.
285 fn unescape_str_or_byte_str<F>(src: &str, mode: Mode, callback: &mut F)
287 F: FnMut(Range<usize>, Result<char, EscapeError>),
289 assert!(mode.in_double_quotes());
290 let initial_len = src.len();
291 let mut chars = src.chars();
292 while let Some(first_char) = chars.next() {
293 let start = initial_len - chars.as_str().len() - first_char.len_utf8();
295 let unescaped_char = match first_char {
297 let second_char = chars.clone().next();
300 // Rust language specification requires us to skip whitespaces
301 // if unescaped '\' character is followed by '\n'.
302 // For details see [Rust language reference]
303 // (https://doc.rust-lang.org/reference/tokens.html#string-literals).
304 skip_ascii_whitespace(&mut chars, start, callback);
307 _ => scan_escape(first_char, &mut chars, mode),
312 _ => scan_escape(first_char, &mut chars, mode),
314 let end = initial_len - chars.as_str().len();
315 callback(start..end, unescaped_char);
318 fn skip_ascii_whitespace<F>(chars: &mut Chars<'_>, start: usize, callback: &mut F)
320 F: FnMut(Range<usize>, Result<char, EscapeError>),
322 let tail = chars.as_str();
323 let first_non_space = tail
325 .position(|b| b != b' ' && b != b'\t' && b != b'\n' && b != b'\r')
326 .unwrap_or(tail.len());
327 if tail[1..first_non_space].contains('\n') {
328 // The +1 accounts for the escaping slash.
329 let end = start + first_non_space + 1;
330 callback(start..end, Err(EscapeError::MultipleSkippedLinesWarning));
332 let tail = &tail[first_non_space..];
333 if let Some(c) = tail.chars().nth(0) {
334 // For error reporting, we would like the span to contain the character that was not
335 // skipped. The +1 is necessary to account for the leading \ that started the escape.
336 let end = start + first_non_space + c.len_utf8() + 1;
337 if c.is_whitespace() {
338 callback(start..end, Err(EscapeError::UnskippedWhitespaceWarning));
341 *chars = tail.chars();
345 /// Takes a contents of a string literal (without quotes) and produces a
346 /// sequence of characters or errors.
347 /// NOTE: Raw strings do not perform any explicit character escaping, here we
348 /// only translate CRLF to LF and produce errors on bare CR.
349 fn unescape_raw_str_or_byte_str<F>(literal_text: &str, mode: Mode, callback: &mut F)
351 F: FnMut(Range<usize>, Result<char, EscapeError>),
353 assert!(mode.in_double_quotes());
354 let initial_len = literal_text.len();
356 let mut chars = literal_text.chars();
357 while let Some(curr) = chars.next() {
358 let start = initial_len - chars.as_str().len() - curr.len_utf8();
360 let result = match curr {
361 '\r' => Err(EscapeError::BareCarriageReturnInRawString),
362 c if mode.is_bytes() && !c.is_ascii() => Err(EscapeError::NonAsciiCharInByteString),
365 let end = initial_len - chars.as_str().len();
367 callback(start..end, result);
371 fn byte_from_char(c: char) -> u8 {
373 assert!(res <= u8::MAX as u32, "guaranteed because of Mode::ByteStr");
377 fn is_ascii(x: u32) -> bool {