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>(src: &str, mode: Mode, callback: &mut F)
83 F: FnMut(Range<usize>, Result<char, EscapeError>),
86 Mode::Char | Mode::Byte => {
87 let mut chars = src.chars();
88 let result = unescape_char_or_byte(&mut chars, mode == Mode::Byte);
89 // The Chars iterator moved forward.
90 callback(0..(src.len() - chars.as_str().len()), result);
92 Mode::Str | Mode::ByteStr => unescape_str_or_byte_str(src, mode == Mode::ByteStr, 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_raw_byte_str(src, mode == Mode::RawByteStr, 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>(src: &str, mode: Mode, callback: &mut F)
106 F: FnMut(Range<usize>, Result<u8, EscapeError>),
108 debug_assert!(mode.is_byte());
109 unescape_literal(src, 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(src: &str) -> Result<char, (usize, EscapeError)> {
117 let mut chars = src.chars();
118 unescape_char_or_byte(&mut chars, false).map_err(|err| (src.len() - chars.as_str().len(), err))
121 /// Takes a contents of a byte literal (without quotes), and returns an
122 /// unescaped byte or an error.
123 pub fn unescape_byte(src: &str) -> Result<u8, (usize, EscapeError)> {
124 let mut chars = src.chars();
125 unescape_char_or_byte(&mut chars, true)
127 .map_err(|err| (src.len() - chars.as_str().len(), err))
130 /// What kind of literal do we parse.
131 #[derive(Debug, Clone, Copy, PartialEq)]
142 pub fn in_double_quotes(self) -> bool {
144 Mode::Str | Mode::ByteStr | Mode::RawStr | Mode::RawByteStr => true,
145 Mode::Char | Mode::Byte => false,
149 pub fn is_byte(self) -> bool {
151 Mode::Byte | Mode::ByteStr | Mode::RawByteStr => true,
152 Mode::Char | Mode::Str | Mode::RawStr => false,
157 fn scan_escape(chars: &mut Chars<'_>, is_byte: bool) -> Result<char, EscapeError> {
158 // Previous character was '\\', unescape what follows.
159 let res = match chars.next().ok_or(EscapeError::LoneSlash)? {
169 // Parse hexadecimal character code.
171 let hi = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
172 let hi = hi.to_digit(16).ok_or(EscapeError::InvalidCharInHexEscape)?;
174 let lo = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
175 let lo = lo.to_digit(16).ok_or(EscapeError::InvalidCharInHexEscape)?;
177 let value = hi * 16 + lo;
179 // For a non-byte literal verify that it is within ASCII range.
180 if !is_byte && !is_ascii(value) {
181 return Err(EscapeError::OutOfRangeHexEscape);
183 let value = value as u8;
189 // We've parsed '\u', now we have to parse '{..}'.
191 if chars.next() != Some('{') {
192 return Err(EscapeError::NoBraceInUnicodeEscape);
195 // First character must be a hexadecimal digit.
196 let mut n_digits = 1;
197 let mut value: u32 = match chars.next().ok_or(EscapeError::UnclosedUnicodeEscape)? {
198 '_' => return Err(EscapeError::LeadingUnderscoreUnicodeEscape),
199 '}' => return Err(EscapeError::EmptyUnicodeEscape),
200 c => c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?,
203 // First character is valid, now parse the rest of the number
204 // and closing brace.
207 None => return Err(EscapeError::UnclosedUnicodeEscape),
208 Some('_') => continue,
211 return Err(EscapeError::OverlongUnicodeEscape);
214 // Incorrect syntax has higher priority for error reporting
215 // than unallowed value for a literal.
217 return Err(EscapeError::UnicodeEscapeInByte);
220 break std::char::from_u32(value).ok_or_else(|| {
221 if value > 0x10FFFF {
222 EscapeError::OutOfRangeUnicodeEscape
224 EscapeError::LoneSurrogateUnicodeEscape
230 c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?;
233 // Stop updating value since we're sure that it's incorrect already.
236 let digit = digit as u32;
237 value = value * 16 + digit;
242 _ => return Err(EscapeError::InvalidEscape),
248 fn ascii_check(c: char, is_byte: bool) -> Result<char, EscapeError> {
249 if is_byte && !c.is_ascii() {
250 // Byte literal can't be a non-ascii character.
251 Err(EscapeError::NonAsciiCharInByte)
257 fn unescape_char_or_byte(chars: &mut Chars<'_>, is_byte: bool) -> Result<char, EscapeError> {
258 let c = chars.next().ok_or(EscapeError::ZeroChars)?;
260 '\\' => scan_escape(chars, is_byte),
261 '\n' | '\t' | '\'' => Err(EscapeError::EscapeOnlyChar),
262 '\r' => Err(EscapeError::BareCarriageReturn),
263 _ => ascii_check(c, is_byte),
265 if chars.next().is_some() {
266 return Err(EscapeError::MoreThanOneChar);
271 /// Takes a contents of a string literal (without quotes) and produces a
272 /// sequence of escaped characters or errors.
273 fn unescape_str_or_byte_str<F>(src: &str, is_byte: bool, callback: &mut F)
275 F: FnMut(Range<usize>, Result<char, EscapeError>),
277 let mut chars = src.chars();
279 // The `start` and `end` computation here is complicated because
280 // `skip_ascii_whitespace` makes us to skip over chars without counting
281 // them in the range computation.
282 while let Some(c) = chars.next() {
283 let start = src.len() - chars.as_str().len() - c.len_utf8();
284 let result = match c {
286 match chars.clone().next() {
288 // Rust language specification requires us to skip whitespaces
289 // if unescaped '\' character is followed by '\n'.
290 // For details see [Rust language reference]
291 // (https://doc.rust-lang.org/reference/tokens.html#string-literals).
292 skip_ascii_whitespace(&mut chars, start, callback);
295 _ => scan_escape(&mut chars, is_byte),
300 '"' => Err(EscapeError::EscapeOnlyChar),
301 '\r' => Err(EscapeError::BareCarriageReturn),
302 _ => ascii_check(c, is_byte),
304 let end = src.len() - chars.as_str().len();
305 callback(start..end, result);
308 fn skip_ascii_whitespace<F>(chars: &mut Chars<'_>, start: usize, callback: &mut F)
310 F: FnMut(Range<usize>, Result<char, EscapeError>),
312 let tail = chars.as_str();
313 let first_non_space = tail
315 .position(|b| b != b' ' && b != b'\t' && b != b'\n' && b != b'\r')
316 .unwrap_or(tail.len());
317 if tail[1..first_non_space].contains('\n') {
318 // The +1 accounts for the escaping slash.
319 let end = start + first_non_space + 1;
320 callback(start..end, Err(EscapeError::MultipleSkippedLinesWarning));
322 let tail = &tail[first_non_space..];
323 if let Some(c) = tail.chars().nth(0) {
324 // For error reporting, we would like the span to contain the character that was not
325 // skipped. The +1 is necessary to account for the leading \ that started the escape.
326 let end = start + first_non_space + c.len_utf8() + 1;
327 if c.is_whitespace() {
328 callback(start..end, Err(EscapeError::UnskippedWhitespaceWarning));
331 *chars = tail.chars();
335 /// Takes a contents of a string literal (without quotes) and produces a
336 /// sequence of characters or errors.
337 /// NOTE: Raw strings do not perform any explicit character escaping, here we
338 /// only translate CRLF to LF and produce errors on bare CR.
339 fn unescape_raw_str_or_raw_byte_str<F>(src: &str, is_byte: bool, callback: &mut F)
341 F: FnMut(Range<usize>, Result<char, EscapeError>),
343 let mut chars = src.chars();
345 // The `start` and `end` computation here matches the one in
346 // `unescape_str_or_byte_str` for consistency, even though this function
347 // doesn't have to worry about skipping any chars.
348 while let Some(c) = chars.next() {
349 let start = src.len() - chars.as_str().len() - c.len_utf8();
350 let result = match c {
351 '\r' => Err(EscapeError::BareCarriageReturnInRawString),
352 c if is_byte && !c.is_ascii() => Err(EscapeError::NonAsciiCharInByteString),
355 let end = src.len() - chars.as_str().len();
356 callback(start..end, result);
360 fn byte_from_char(c: char) -> u8 {
362 debug_assert!(res <= u8::MAX as u32, "guaranteed because of Mode::ByteStr");
366 fn is_ascii(x: u32) -> bool {