]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lexer/src/unescape.rs
Rollup merge of #89347 - TaKO8Ki:crate-or-module-typo, r=estebank
[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         !matches!(
72             self,
73             EscapeError::UnskippedWhitespaceWarning | EscapeError::MultipleSkippedLinesWarning
74         )
75     }
76 }
77
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)
82 where
83     F: FnMut(Range<usize>, Result<char, EscapeError>),
84 {
85     match mode {
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);
91         }
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)
97         }
98     }
99 }
100
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)
105 where
106     F: FnMut(Range<usize>, Result<u8, EscapeError>),
107 {
108     assert!(mode.is_bytes());
109     unescape_literal(literal_text, mode, &mut |range, result| {
110         callback(range, result.map(byte_from_char));
111     })
112 }
113
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))
120 }
121
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)
127         .map(byte_from_char)
128         .map_err(|err| (literal_text.len() - chars.as_str().len(), err))
129 }
130
131 /// What kind of literal do we parse.
132 #[derive(Debug, Clone, Copy)]
133 pub enum Mode {
134     Char,
135     Str,
136     Byte,
137     ByteStr,
138     RawStr,
139     RawByteStr,
140 }
141
142 impl Mode {
143     pub fn in_single_quotes(self) -> bool {
144         match self {
145             Mode::Char | Mode::Byte => true,
146             Mode::Str | Mode::ByteStr | Mode::RawStr | Mode::RawByteStr => false,
147         }
148     }
149
150     pub fn in_double_quotes(self) -> bool {
151         !self.in_single_quotes()
152     }
153
154     pub fn is_bytes(self) -> bool {
155         match self {
156             Mode::Byte | Mode::ByteStr | Mode::RawByteStr => true,
157             Mode::Char | Mode::Str | Mode::RawStr => false,
158         }
159     }
160 }
161
162 fn scan_escape(first_char: char, chars: &mut Chars<'_>, mode: Mode) -> Result<char, EscapeError> {
163     if first_char != '\\' {
164         // Previous character was not a slash, and we don't expect it to be
165         // an escape-only character.
166         return match first_char {
167             '\t' | '\n' => Err(EscapeError::EscapeOnlyChar),
168             '\r' => Err(EscapeError::BareCarriageReturn),
169             '\'' if mode.in_single_quotes() => Err(EscapeError::EscapeOnlyChar),
170             '"' if mode.in_double_quotes() => Err(EscapeError::EscapeOnlyChar),
171             _ => {
172                 if mode.is_bytes() && !first_char.is_ascii() {
173                     // Byte literal can't be a non-ascii character.
174                     return Err(EscapeError::NonAsciiCharInByte);
175                 }
176                 Ok(first_char)
177             }
178         };
179     }
180
181     // Previous character is '\\', try to unescape it.
182
183     let second_char = chars.next().ok_or(EscapeError::LoneSlash)?;
184
185     let res = match second_char {
186         '"' => '"',
187         'n' => '\n',
188         'r' => '\r',
189         't' => '\t',
190         '\\' => '\\',
191         '\'' => '\'',
192         '0' => '\0',
193
194         'x' => {
195             // Parse hexadecimal character code.
196
197             let hi = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
198             let hi = hi.to_digit(16).ok_or(EscapeError::InvalidCharInHexEscape)?;
199
200             let lo = chars.next().ok_or(EscapeError::TooShortHexEscape)?;
201             let lo = lo.to_digit(16).ok_or(EscapeError::InvalidCharInHexEscape)?;
202
203             let value = hi * 16 + lo;
204
205             // For a byte literal verify that it is within ASCII range.
206             if !mode.is_bytes() && !is_ascii(value) {
207                 return Err(EscapeError::OutOfRangeHexEscape);
208             }
209             let value = value as u8;
210
211             value as char
212         }
213
214         'u' => {
215             // We've parsed '\u', now we have to parse '{..}'.
216
217             if chars.next() != Some('{') {
218                 return Err(EscapeError::NoBraceInUnicodeEscape);
219             }
220
221             // First character must be a hexadecimal digit.
222             let mut n_digits = 1;
223             let mut value: u32 = match chars.next().ok_or(EscapeError::UnclosedUnicodeEscape)? {
224                 '_' => return Err(EscapeError::LeadingUnderscoreUnicodeEscape),
225                 '}' => return Err(EscapeError::EmptyUnicodeEscape),
226                 c => c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?,
227             };
228
229             // First character is valid, now parse the rest of the number
230             // and closing brace.
231             loop {
232                 match chars.next() {
233                     None => return Err(EscapeError::UnclosedUnicodeEscape),
234                     Some('_') => continue,
235                     Some('}') => {
236                         if n_digits > 6 {
237                             return Err(EscapeError::OverlongUnicodeEscape);
238                         }
239
240                         // Incorrect syntax has higher priority for error reporting
241                         // than unallowed value for a literal.
242                         if mode.is_bytes() {
243                             return Err(EscapeError::UnicodeEscapeInByte);
244                         }
245
246                         break std::char::from_u32(value).ok_or_else(|| {
247                             if value > 0x10FFFF {
248                                 EscapeError::OutOfRangeUnicodeEscape
249                             } else {
250                                 EscapeError::LoneSurrogateUnicodeEscape
251                             }
252                         })?;
253                     }
254                     Some(c) => {
255                         let digit =
256                             c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?;
257                         n_digits += 1;
258                         if n_digits > 6 {
259                             // Stop updating value since we're sure that it's is incorrect already.
260                             continue;
261                         }
262                         let digit = digit as u32;
263                         value = value * 16 + digit;
264                     }
265                 };
266             }
267         }
268         _ => return Err(EscapeError::InvalidEscape),
269     };
270     Ok(res)
271 }
272
273 fn unescape_char_or_byte(chars: &mut Chars<'_>, mode: Mode) -> Result<char, EscapeError> {
274     let first_char = chars.next().ok_or(EscapeError::ZeroChars)?;
275     let res = scan_escape(first_char, chars, mode)?;
276     if chars.next().is_some() {
277         return Err(EscapeError::MoreThanOneChar);
278     }
279     Ok(res)
280 }
281
282 /// Takes a contents of a string literal (without quotes) and produces a
283 /// sequence of escaped characters or errors.
284 fn unescape_str_or_byte_str<F>(src: &str, mode: Mode, callback: &mut F)
285 where
286     F: FnMut(Range<usize>, Result<char, EscapeError>),
287 {
288     assert!(mode.in_double_quotes());
289     let initial_len = src.len();
290     let mut chars = src.chars();
291     while let Some(first_char) = chars.next() {
292         let start = initial_len - chars.as_str().len() - first_char.len_utf8();
293
294         let unescaped_char = match first_char {
295             '\\' => {
296                 let second_char = chars.clone().next();
297                 match second_char {
298                     Some('\n') => {
299                         // Rust language specification requires us to skip whitespaces
300                         // if unescaped '\' character is followed by '\n'.
301                         // For details see [Rust language reference]
302                         // (https://doc.rust-lang.org/reference/tokens.html#string-literals).
303                         skip_ascii_whitespace(&mut chars, start, callback);
304                         continue;
305                     }
306                     _ => scan_escape(first_char, &mut chars, mode),
307                 }
308             }
309             '\n' => Ok('\n'),
310             '\t' => Ok('\t'),
311             _ => scan_escape(first_char, &mut chars, mode),
312         };
313         let end = initial_len - chars.as_str().len();
314         callback(start..end, unescaped_char);
315     }
316
317     fn skip_ascii_whitespace<F>(chars: &mut Chars<'_>, start: usize, callback: &mut F)
318     where
319         F: FnMut(Range<usize>, Result<char, EscapeError>),
320     {
321         let tail = chars.as_str();
322         let first_non_space = tail
323             .bytes()
324             .position(|b| b != b' ' && b != b'\t' && b != b'\n' && b != b'\r')
325             .unwrap_or(tail.len());
326         if tail[1..first_non_space].contains('\n') {
327             // The +1 accounts for the escaping slash.
328             let end = start + first_non_space + 1;
329             callback(start..end, Err(EscapeError::MultipleSkippedLinesWarning));
330         }
331         let tail = &tail[first_non_space..];
332         if let Some(c) = tail.chars().next() {
333             // For error reporting, we would like the span to contain the character that was not
334             // skipped.  The +1 is necessary to account for the leading \ that started the escape.
335             let end = start + first_non_space + c.len_utf8() + 1;
336             if c.is_whitespace() {
337                 callback(start..end, Err(EscapeError::UnskippedWhitespaceWarning));
338             }
339         }
340         *chars = tail.chars();
341     }
342 }
343
344 /// Takes a contents of a string literal (without quotes) and produces a
345 /// sequence of characters or errors.
346 /// NOTE: Raw strings do not perform any explicit character escaping, here we
347 /// only translate CRLF to LF and produce errors on bare CR.
348 fn unescape_raw_str_or_byte_str<F>(literal_text: &str, mode: Mode, callback: &mut F)
349 where
350     F: FnMut(Range<usize>, Result<char, EscapeError>),
351 {
352     assert!(mode.in_double_quotes());
353     let initial_len = literal_text.len();
354
355     let mut chars = literal_text.chars();
356     while let Some(curr) = chars.next() {
357         let start = initial_len - chars.as_str().len() - curr.len_utf8();
358
359         let result = match curr {
360             '\r' => Err(EscapeError::BareCarriageReturnInRawString),
361             c if mode.is_bytes() && !c.is_ascii() => Err(EscapeError::NonAsciiCharInByteString),
362             c => Ok(c),
363         };
364         let end = initial_len - chars.as_str().len();
365
366         callback(start..end, result);
367     }
368 }
369
370 fn byte_from_char(c: char) -> u8 {
371     let res = c as u32;
372     assert!(res <= u8::MAX as u32, "guaranteed because of Mode::ByteStr");
373     res as u8
374 }
375
376 fn is_ascii(x: u32) -> bool {
377     x <= 0x7F
378 }