]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lexer/src/unescape.rs
Auto merge of #89343 - Mark-Simulacrum:no-args-queries, r=cjgillot
[rust.git] / compiler / rustc_lexer / src / unescape.rs
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.
56     NonAsciiCharInByte,
57     /// Non-ascii character in byte string literal.
58     NonAsciiCharInByteString,
59
60     /// After a line ending with '\', the next line contains whitespace
61     /// characters that are not skipped.
62     UnskippedWhitespaceWarning,
63
64     /// After a line ending with '\', multiple lines are skipped.
65     MultipleSkippedLinesWarning,
66 }
67
68 impl EscapeError {
69     /// Returns true for actual errors, as opposed to warnings.
70     pub fn is_fatal(&self) -> bool {
71         match self {
72             EscapeError::UnskippedWhitespaceWarning => false,
73             EscapeError::MultipleSkippedLinesWarning => false,
74             _ => true,
75         }
76     }
77 }
78
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)
83 where
84     F: FnMut(Range<usize>, Result<char, EscapeError>),
85 {
86     match mode {
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);
92         }
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)
98         }
99     }
100 }
101
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)
106 where
107     F: FnMut(Range<usize>, Result<u8, EscapeError>),
108 {
109     assert!(mode.is_bytes());
110     unescape_literal(literal_text, mode, &mut |range, result| {
111         callback(range, result.map(byte_from_char));
112     })
113 }
114
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))
121 }
122
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)
128         .map(byte_from_char)
129         .map_err(|err| (literal_text.len() - chars.as_str().len(), err))
130 }
131
132 /// What kind of literal do we parse.
133 #[derive(Debug, Clone, Copy)]
134 pub enum Mode {
135     Char,
136     Str,
137     Byte,
138     ByteStr,
139     RawStr,
140     RawByteStr,
141 }
142
143 impl Mode {
144     pub fn in_single_quotes(self) -> bool {
145         match self {
146             Mode::Char | Mode::Byte => true,
147             Mode::Str | Mode::ByteStr | Mode::RawStr | Mode::RawByteStr => false,
148         }
149     }
150
151     pub fn in_double_quotes(self) -> bool {
152         !self.in_single_quotes()
153     }
154
155     pub fn is_bytes(self) -> bool {
156         match self {
157             Mode::Byte | Mode::ByteStr | Mode::RawByteStr => true,
158             Mode::Char | Mode::Str | Mode::RawStr => false,
159         }
160     }
161 }
162
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),
172             _ => {
173                 if mode.is_bytes() && !first_char.is_ascii() {
174                     // Byte literal can't be a non-ascii character.
175                     return Err(EscapeError::NonAsciiCharInByte);
176                 }
177                 Ok(first_char)
178             }
179         };
180     }
181
182     // Previous character is '\\', try to unescape it.
183
184     let second_char = chars.next().ok_or(EscapeError::LoneSlash)?;
185
186     let res = match second_char {
187         '"' => '"',
188         'n' => '\n',
189         'r' => '\r',
190         't' => '\t',
191         '\\' => '\\',
192         '\'' => '\'',
193         '0' => '\0',
194
195         'x' => {
196             // Parse hexadecimal character code.
197
198             let hi = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
199             let hi = hi.to_digit(16).ok_or(EscapeError::InvalidCharInHexEscape)?;
200
201             let lo = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
202             let lo = lo.to_digit(16).ok_or(EscapeError::InvalidCharInHexEscape)?;
203
204             let value = hi * 16 + lo;
205
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);
209             }
210             let value = value as u8;
211
212             value as char
213         }
214
215         'u' => {
216             // We've parsed '\u', now we have to parse '{..}'.
217
218             if chars.next() != Some('{') {
219                 return Err(EscapeError::NoBraceInUnicodeEscape);
220             }
221
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)?,
228             };
229
230             // First character is valid, now parse the rest of the number
231             // and closing brace.
232             loop {
233                 match chars.next() {
234                     None => return Err(EscapeError::UnclosedUnicodeEscape),
235                     Some('_') => continue,
236                     Some('}') => {
237                         if n_digits > 6 {
238                             return Err(EscapeError::OverlongUnicodeEscape);
239                         }
240
241                         // Incorrect syntax has higher priority for error reporting
242                         // than unallowed value for a literal.
243                         if mode.is_bytes() {
244                             return Err(EscapeError::UnicodeEscapeInByte);
245                         }
246
247                         break std::char::from_u32(value).ok_or_else(|| {
248                             if value > 0x10FFFF {
249                                 EscapeError::OutOfRangeUnicodeEscape
250                             } else {
251                                 EscapeError::LoneSurrogateUnicodeEscape
252                             }
253                         })?;
254                     }
255                     Some(c) => {
256                         let digit =
257                             c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?;
258                         n_digits += 1;
259                         if n_digits > 6 {
260                             // Stop updating value since we're sure that it's is incorrect already.
261                             continue;
262                         }
263                         let digit = digit as u32;
264                         value = value * 16 + digit;
265                     }
266                 };
267             }
268         }
269         _ => return Err(EscapeError::InvalidEscape),
270     };
271     Ok(res)
272 }
273
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);
279     }
280     Ok(res)
281 }
282
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)
286 where
287     F: FnMut(Range<usize>, Result<char, EscapeError>),
288 {
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();
294
295         let unescaped_char = match first_char {
296             '\\' => {
297                 let second_char = chars.clone().next();
298                 match second_char {
299                     Some('\n') => {
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);
305                         continue;
306                     }
307                     _ => scan_escape(first_char, &mut chars, mode),
308                 }
309             }
310             '\n' => Ok('\n'),
311             '\t' => Ok('\t'),
312             _ => scan_escape(first_char, &mut chars, mode),
313         };
314         let end = initial_len - chars.as_str().len();
315         callback(start..end, unescaped_char);
316     }
317
318     fn skip_ascii_whitespace<F>(chars: &mut Chars<'_>, start: usize, callback: &mut F)
319     where
320         F: FnMut(Range<usize>, Result<char, EscapeError>),
321     {
322         let tail = chars.as_str();
323         let first_non_space = tail
324             .bytes()
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));
331         }
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));
339             }
340         }
341         *chars = tail.chars();
342     }
343 }
344
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)
350 where
351     F: FnMut(Range<usize>, Result<char, EscapeError>),
352 {
353     assert!(mode.in_double_quotes());
354     let initial_len = literal_text.len();
355
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();
359
360         let result = match curr {
361             '\r' => Err(EscapeError::BareCarriageReturnInRawString),
362             c if mode.is_bytes() && !c.is_ascii() => Err(EscapeError::NonAsciiCharInByteString),
363             c => Ok(c),
364         };
365         let end = initial_len - chars.as_str().len();
366
367         callback(start..end, result);
368     }
369 }
370
371 fn byte_from_char(c: char) -> u8 {
372     let res = c as u32;
373     assert!(res <= u8::MAX as u32, "guaranteed because of Mode::ByteStr");
374     res as u8
375 }
376
377 fn is_ascii(x: u32) -> bool {
378     x <= 0x7F
379 }