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