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