]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lexer/src/lib.rs
Rollup merge of #99880 - compiler-errors:escape-ascii-is-not-exact-size-iterator...
[rust.git] / compiler / rustc_lexer / src / lib.rs
1 //! Low-level Rust lexer.
2 //!
3 //! The idea with `rustc_lexer` is to make a reusable library,
4 //! by separating out pure lexing and rustc-specific concerns, like spans,
5 //! error reporting, and interning.  So, rustc_lexer operates directly on `&str`,
6 //! produces simple tokens which are a pair of type-tag and a bit of original text,
7 //! and does not report errors, instead storing them as flags on the token.
8 //!
9 //! Tokens produced by this lexer are not yet ready for parsing the Rust syntax.
10 //! For that see [`rustc_parse::lexer`], which converts this basic token stream
11 //! into wide tokens used by actual parser.
12 //!
13 //! The purpose of this crate is to convert raw sources into a labeled sequence
14 //! of well-known token types, so building an actual Rust token stream will
15 //! be easier.
16 //!
17 //! The main entity of this crate is the [`TokenKind`] enum which represents common
18 //! lexeme types.
19 //!
20 //! [`rustc_parse::lexer`]: ../rustc_parse/lexer/index.html
21 #![deny(rustc::untranslatable_diagnostic)]
22 #![deny(rustc::diagnostic_outside_of_impl)]
23 // We want to be able to build this crate with a stable compiler, so no
24 // `#![feature]` attributes should be added.
25
26 mod cursor;
27 pub mod unescape;
28
29 #[cfg(test)]
30 mod tests;
31
32 pub use crate::cursor::Cursor;
33
34 use self::LiteralKind::*;
35 use self::TokenKind::*;
36 use crate::cursor::EOF_CHAR;
37 use std::convert::TryFrom;
38
39 /// Parsed token.
40 /// It doesn't contain information about data that has been parsed,
41 /// only the type of the token and its size.
42 #[derive(Debug)]
43 pub struct Token {
44     pub kind: TokenKind,
45     pub len: u32,
46 }
47
48 impl Token {
49     fn new(kind: TokenKind, len: u32) -> Token {
50         Token { kind, len }
51     }
52 }
53
54 /// Enum representing common lexeme types.
55 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
56 pub enum TokenKind {
57     // Multi-char tokens:
58     /// "// comment"
59     LineComment { doc_style: Option<DocStyle> },
60     /// `/* block comment */`
61     ///
62     /// Block comments can be recursive, so the sequence like `/* /* */`
63     /// will not be considered terminated and will result in a parsing error.
64     BlockComment { doc_style: Option<DocStyle>, terminated: bool },
65     /// Any whitespace characters sequence.
66     Whitespace,
67     /// "ident" or "continue"
68     /// At this step keywords are also considered identifiers.
69     Ident,
70     /// Like the above, but containing invalid unicode codepoints.
71     InvalidIdent,
72     /// "r#ident"
73     RawIdent,
74     /// An unknown prefix like `foo#`, `foo'`, `foo"`. Note that only the
75     /// prefix (`foo`) is included in the token, not the separator (which is
76     /// lexed as its own distinct token). In Rust 2021 and later, reserved
77     /// prefixes are reported as errors; in earlier editions, they result in a
78     /// (allowed by default) lint, and are treated as regular identifier
79     /// tokens.
80     UnknownPrefix,
81     /// "12_u8", "1.0e-40", "b"123"". See `LiteralKind` for more details.
82     Literal { kind: LiteralKind, suffix_start: u32 },
83     /// "'a"
84     Lifetime { starts_with_number: bool },
85
86     // One-char tokens:
87     /// ";"
88     Semi,
89     /// ","
90     Comma,
91     /// "."
92     Dot,
93     /// "("
94     OpenParen,
95     /// ")"
96     CloseParen,
97     /// "{"
98     OpenBrace,
99     /// "}"
100     CloseBrace,
101     /// "["
102     OpenBracket,
103     /// "]"
104     CloseBracket,
105     /// "@"
106     At,
107     /// "#"
108     Pound,
109     /// "~"
110     Tilde,
111     /// "?"
112     Question,
113     /// ":"
114     Colon,
115     /// "$"
116     Dollar,
117     /// "="
118     Eq,
119     /// "!"
120     Bang,
121     /// "<"
122     Lt,
123     /// ">"
124     Gt,
125     /// "-"
126     Minus,
127     /// "&"
128     And,
129     /// "|"
130     Or,
131     /// "+"
132     Plus,
133     /// "*"
134     Star,
135     /// "/"
136     Slash,
137     /// "^"
138     Caret,
139     /// "%"
140     Percent,
141
142     /// Unknown token, not expected by the lexer, e.g. "№"
143     Unknown,
144
145     /// End of input.
146     Eof,
147 }
148
149 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
150 pub enum DocStyle {
151     Outer,
152     Inner,
153 }
154
155 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
156 pub enum LiteralKind {
157     /// "12_u8", "0o100", "0b120i99"
158     Int { base: Base, empty_int: bool },
159     /// "12.34f32", "0b100.100"
160     Float { base: Base, empty_exponent: bool },
161     /// "'a'", "'\\'", "'''", "';"
162     Char { terminated: bool },
163     /// "b'a'", "b'\\'", "b'''", "b';"
164     Byte { terminated: bool },
165     /// ""abc"", ""abc"
166     Str { terminated: bool },
167     /// "b"abc"", "b"abc"
168     ByteStr { terminated: bool },
169     /// "r"abc"", "r#"abc"#", "r####"ab"###"c"####", "r#"a". `None` indicates
170     /// an invalid literal.
171     RawStr { n_hashes: Option<u8> },
172     /// "br"abc"", "br#"abc"#", "br####"ab"###"c"####", "br#"a". `None`
173     /// indicates an invalid literal.
174     RawByteStr { n_hashes: Option<u8> },
175 }
176
177 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
178 pub enum RawStrError {
179     /// Non `#` characters exist between `r` and `"`, e.g. `r##~"abcde"##`
180     InvalidStarter { bad_char: char },
181     /// The string was not terminated, e.g. `r###"abcde"##`.
182     /// `possible_terminator_offset` is the number of characters after `r` or
183     /// `br` where they may have intended to terminate it.
184     NoTerminator { expected: u32, found: u32, possible_terminator_offset: Option<u32> },
185     /// More than 255 `#`s exist.
186     TooManyDelimiters { found: u32 },
187 }
188
189 /// Base of numeric literal encoding according to its prefix.
190 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
191 pub enum Base {
192     /// Literal starts with "0b".
193     Binary,
194     /// Literal starts with "0o".
195     Octal,
196     /// Literal starts with "0x".
197     Hexadecimal,
198     /// Literal doesn't contain a prefix.
199     Decimal,
200 }
201
202 /// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun",
203 /// but shebang isn't a part of rust syntax.
204 pub fn strip_shebang(input: &str) -> Option<usize> {
205     // Shebang must start with `#!` literally, without any preceding whitespace.
206     // For simplicity we consider any line starting with `#!` a shebang,
207     // regardless of restrictions put on shebangs by specific platforms.
208     if let Some(input_tail) = input.strip_prefix("#!") {
209         // Ok, this is a shebang but if the next non-whitespace token is `[`,
210         // then it may be valid Rust code, so consider it Rust code.
211         let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| {
212             !matches!(
213                 tok,
214                 TokenKind::Whitespace
215                     | TokenKind::LineComment { doc_style: None }
216                     | TokenKind::BlockComment { doc_style: None, .. }
217             )
218         });
219         if next_non_whitespace_token != Some(TokenKind::OpenBracket) {
220             // No other choice than to consider this a shebang.
221             return Some(2 + input_tail.lines().next().unwrap_or_default().len());
222         }
223     }
224     None
225 }
226
227 /// Validates a raw string literal. Used for getting more information about a
228 /// problem with a `RawStr`/`RawByteStr` with a `None` field.
229 #[inline]
230 pub fn validate_raw_str(input: &str, prefix_len: u32) -> Result<(), RawStrError> {
231     debug_assert!(!input.is_empty());
232     let mut cursor = Cursor::new(input);
233     // Move past the leading `r` or `br`.
234     for _ in 0..prefix_len {
235         cursor.bump().unwrap();
236     }
237     cursor.raw_double_quoted_string(prefix_len).map(|_| ())
238 }
239
240 /// Creates an iterator that produces tokens from the input string.
241 pub fn tokenize(input: &str) -> impl Iterator<Item = Token> + '_ {
242     let mut cursor = Cursor::new(input);
243     std::iter::from_fn(move || {
244         let token = cursor.advance_token();
245         if token.kind != TokenKind::Eof { Some(token) } else { None }
246     })
247 }
248
249 /// True if `c` is considered a whitespace according to Rust language definition.
250 /// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html)
251 /// for definitions of these classes.
252 pub fn is_whitespace(c: char) -> bool {
253     // This is Pattern_White_Space.
254     //
255     // Note that this set is stable (ie, it doesn't change with different
256     // Unicode versions), so it's ok to just hard-code the values.
257
258     matches!(
259         c,
260         // Usual ASCII suspects
261         '\u{0009}'   // \t
262         | '\u{000A}' // \n
263         | '\u{000B}' // vertical tab
264         | '\u{000C}' // form feed
265         | '\u{000D}' // \r
266         | '\u{0020}' // space
267
268         // NEXT LINE from latin1
269         | '\u{0085}'
270
271         // Bidi markers
272         | '\u{200E}' // LEFT-TO-RIGHT MARK
273         | '\u{200F}' // RIGHT-TO-LEFT MARK
274
275         // Dedicated whitespace characters from Unicode
276         | '\u{2028}' // LINE SEPARATOR
277         | '\u{2029}' // PARAGRAPH SEPARATOR
278     )
279 }
280
281 /// True if `c` is valid as a first character of an identifier.
282 /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for
283 /// a formal definition of valid identifier name.
284 pub fn is_id_start(c: char) -> bool {
285     // This is XID_Start OR '_' (which formally is not a XID_Start).
286     c == '_' || unicode_xid::UnicodeXID::is_xid_start(c)
287 }
288
289 /// True if `c` is valid as a non-first character of an identifier.
290 /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for
291 /// a formal definition of valid identifier name.
292 pub fn is_id_continue(c: char) -> bool {
293     unicode_xid::UnicodeXID::is_xid_continue(c)
294 }
295
296 /// The passed string is lexically an identifier.
297 pub fn is_ident(string: &str) -> bool {
298     let mut chars = string.chars();
299     if let Some(start) = chars.next() {
300         is_id_start(start) && chars.all(is_id_continue)
301     } else {
302         false
303     }
304 }
305
306 impl Cursor<'_> {
307     /// Parses a token from the input string.
308     pub fn advance_token(&mut self) -> Token {
309         let first_char = match self.bump() {
310             Some(c) => c,
311             None => return Token::new(TokenKind::Eof, 0),
312         };
313         let token_kind = match first_char {
314             // Slash, comment or block comment.
315             '/' => match self.first() {
316                 '/' => self.line_comment(),
317                 '*' => self.block_comment(),
318                 _ => Slash,
319             },
320
321             // Whitespace sequence.
322             c if is_whitespace(c) => self.whitespace(),
323
324             // Raw identifier, raw string literal or identifier.
325             'r' => match (self.first(), self.second()) {
326                 ('#', c1) if is_id_start(c1) => self.raw_ident(),
327                 ('#', _) | ('"', _) => {
328                     let res = self.raw_double_quoted_string(1);
329                     let suffix_start = self.pos_within_token();
330                     if res.is_ok() {
331                         self.eat_literal_suffix();
332                     }
333                     let kind = RawStr { n_hashes: res.ok() };
334                     Literal { kind, suffix_start }
335                 }
336                 _ => self.ident_or_unknown_prefix(),
337             },
338
339             // Byte literal, byte string literal, raw byte string literal or identifier.
340             'b' => match (self.first(), self.second()) {
341                 ('\'', _) => {
342                     self.bump();
343                     let terminated = self.single_quoted_string();
344                     let suffix_start = self.pos_within_token();
345                     if terminated {
346                         self.eat_literal_suffix();
347                     }
348                     let kind = Byte { terminated };
349                     Literal { kind, suffix_start }
350                 }
351                 ('"', _) => {
352                     self.bump();
353                     let terminated = self.double_quoted_string();
354                     let suffix_start = self.pos_within_token();
355                     if terminated {
356                         self.eat_literal_suffix();
357                     }
358                     let kind = ByteStr { terminated };
359                     Literal { kind, suffix_start }
360                 }
361                 ('r', '"') | ('r', '#') => {
362                     self.bump();
363                     let res = self.raw_double_quoted_string(2);
364                     let suffix_start = self.pos_within_token();
365                     if res.is_ok() {
366                         self.eat_literal_suffix();
367                     }
368                     let kind = RawByteStr { n_hashes: res.ok() };
369                     Literal { kind, suffix_start }
370                 }
371                 _ => self.ident_or_unknown_prefix(),
372             },
373
374             // Identifier (this should be checked after other variant that can
375             // start as identifier).
376             c if is_id_start(c) => self.ident_or_unknown_prefix(),
377
378             // Numeric literal.
379             c @ '0'..='9' => {
380                 let literal_kind = self.number(c);
381                 let suffix_start = self.pos_within_token();
382                 self.eat_literal_suffix();
383                 TokenKind::Literal { kind: literal_kind, suffix_start }
384             }
385
386             // One-symbol tokens.
387             ';' => Semi,
388             ',' => Comma,
389             '.' => Dot,
390             '(' => OpenParen,
391             ')' => CloseParen,
392             '{' => OpenBrace,
393             '}' => CloseBrace,
394             '[' => OpenBracket,
395             ']' => CloseBracket,
396             '@' => At,
397             '#' => Pound,
398             '~' => Tilde,
399             '?' => Question,
400             ':' => Colon,
401             '$' => Dollar,
402             '=' => Eq,
403             '!' => Bang,
404             '<' => Lt,
405             '>' => Gt,
406             '-' => Minus,
407             '&' => And,
408             '|' => Or,
409             '+' => Plus,
410             '*' => Star,
411             '^' => Caret,
412             '%' => Percent,
413
414             // Lifetime or character literal.
415             '\'' => self.lifetime_or_char(),
416
417             // String literal.
418             '"' => {
419                 let terminated = self.double_quoted_string();
420                 let suffix_start = self.pos_within_token();
421                 if terminated {
422                     self.eat_literal_suffix();
423                 }
424                 let kind = Str { terminated };
425                 Literal { kind, suffix_start }
426             }
427             // Identifier starting with an emoji. Only lexed for graceful error recovery.
428             c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => {
429                 self.fake_ident_or_unknown_prefix()
430             }
431             _ => Unknown,
432         };
433         let res = Token::new(token_kind, self.pos_within_token());
434         self.reset_pos_within_token();
435         res
436     }
437
438     fn line_comment(&mut self) -> TokenKind {
439         debug_assert!(self.prev() == '/' && self.first() == '/');
440         self.bump();
441
442         let doc_style = match self.first() {
443             // `//!` is an inner line doc comment.
444             '!' => Some(DocStyle::Inner),
445             // `////` (more than 3 slashes) is not considered a doc comment.
446             '/' if self.second() != '/' => Some(DocStyle::Outer),
447             _ => None,
448         };
449
450         self.eat_while(|c| c != '\n');
451         LineComment { doc_style }
452     }
453
454     fn block_comment(&mut self) -> TokenKind {
455         debug_assert!(self.prev() == '/' && self.first() == '*');
456         self.bump();
457
458         let doc_style = match self.first() {
459             // `/*!` is an inner block doc comment.
460             '!' => Some(DocStyle::Inner),
461             // `/***` (more than 2 stars) is not considered a doc comment.
462             // `/**/` is not considered a doc comment.
463             '*' if !matches!(self.second(), '*' | '/') => Some(DocStyle::Outer),
464             _ => None,
465         };
466
467         let mut depth = 1usize;
468         while let Some(c) = self.bump() {
469             match c {
470                 '/' if self.first() == '*' => {
471                     self.bump();
472                     depth += 1;
473                 }
474                 '*' if self.first() == '/' => {
475                     self.bump();
476                     depth -= 1;
477                     if depth == 0 {
478                         // This block comment is closed, so for a construction like "/* */ */"
479                         // there will be a successfully parsed block comment "/* */"
480                         // and " */" will be processed separately.
481                         break;
482                     }
483                 }
484                 _ => (),
485             }
486         }
487
488         BlockComment { doc_style, terminated: depth == 0 }
489     }
490
491     fn whitespace(&mut self) -> TokenKind {
492         debug_assert!(is_whitespace(self.prev()));
493         self.eat_while(is_whitespace);
494         Whitespace
495     }
496
497     fn raw_ident(&mut self) -> TokenKind {
498         debug_assert!(self.prev() == 'r' && self.first() == '#' && is_id_start(self.second()));
499         // Eat "#" symbol.
500         self.bump();
501         // Eat the identifier part of RawIdent.
502         self.eat_identifier();
503         RawIdent
504     }
505
506     fn ident_or_unknown_prefix(&mut self) -> TokenKind {
507         debug_assert!(is_id_start(self.prev()));
508         // Start is already eaten, eat the rest of identifier.
509         self.eat_while(is_id_continue);
510         // Known prefixes must have been handled earlier. So if
511         // we see a prefix here, it is definitely an unknown prefix.
512         match self.first() {
513             '#' | '"' | '\'' => UnknownPrefix,
514             c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => {
515                 self.fake_ident_or_unknown_prefix()
516             }
517             _ => Ident,
518         }
519     }
520
521     fn fake_ident_or_unknown_prefix(&mut self) -> TokenKind {
522         // Start is already eaten, eat the rest of identifier.
523         self.eat_while(|c| {
524             unicode_xid::UnicodeXID::is_xid_continue(c)
525                 || (!c.is_ascii() && unic_emoji_char::is_emoji(c))
526                 || c == '\u{200d}'
527         });
528         // Known prefixes must have been handled earlier. So if
529         // we see a prefix here, it is definitely an unknown prefix.
530         match self.first() {
531             '#' | '"' | '\'' => UnknownPrefix,
532             _ => InvalidIdent,
533         }
534     }
535
536     fn number(&mut self, first_digit: char) -> LiteralKind {
537         debug_assert!('0' <= self.prev() && self.prev() <= '9');
538         let mut base = Base::Decimal;
539         if first_digit == '0' {
540             // Attempt to parse encoding base.
541             let has_digits = match self.first() {
542                 'b' => {
543                     base = Base::Binary;
544                     self.bump();
545                     self.eat_decimal_digits()
546                 }
547                 'o' => {
548                     base = Base::Octal;
549                     self.bump();
550                     self.eat_decimal_digits()
551                 }
552                 'x' => {
553                     base = Base::Hexadecimal;
554                     self.bump();
555                     self.eat_hexadecimal_digits()
556                 }
557                 // Not a base prefix.
558                 '0'..='9' | '_' | '.' | 'e' | 'E' => {
559                     self.eat_decimal_digits();
560                     true
561                 }
562                 // Just a 0.
563                 _ => return Int { base, empty_int: false },
564             };
565             // Base prefix was provided, but there were no digits
566             // after it, e.g. "0x".
567             if !has_digits {
568                 return Int { base, empty_int: true };
569             }
570         } else {
571             // No base prefix, parse number in the usual way.
572             self.eat_decimal_digits();
573         };
574
575         match self.first() {
576             // Don't be greedy if this is actually an
577             // integer literal followed by field/method access or a range pattern
578             // (`0..2` and `12.foo()`)
579             '.' if self.second() != '.' && !is_id_start(self.second()) => {
580                 // might have stuff after the ., and if it does, it needs to start
581                 // with a number
582                 self.bump();
583                 let mut empty_exponent = false;
584                 if self.first().is_digit(10) {
585                     self.eat_decimal_digits();
586                     match self.first() {
587                         'e' | 'E' => {
588                             self.bump();
589                             empty_exponent = !self.eat_float_exponent();
590                         }
591                         _ => (),
592                     }
593                 }
594                 Float { base, empty_exponent }
595             }
596             'e' | 'E' => {
597                 self.bump();
598                 let empty_exponent = !self.eat_float_exponent();
599                 Float { base, empty_exponent }
600             }
601             _ => Int { base, empty_int: false },
602         }
603     }
604
605     fn lifetime_or_char(&mut self) -> TokenKind {
606         debug_assert!(self.prev() == '\'');
607
608         let can_be_a_lifetime = if self.second() == '\'' {
609             // It's surely not a lifetime.
610             false
611         } else {
612             // If the first symbol is valid for identifier, it can be a lifetime.
613             // Also check if it's a number for a better error reporting (so '0 will
614             // be reported as invalid lifetime and not as unterminated char literal).
615             is_id_start(self.first()) || self.first().is_digit(10)
616         };
617
618         if !can_be_a_lifetime {
619             let terminated = self.single_quoted_string();
620             let suffix_start = self.pos_within_token();
621             if terminated {
622                 self.eat_literal_suffix();
623             }
624             let kind = Char { terminated };
625             return Literal { kind, suffix_start };
626         }
627
628         // Either a lifetime or a character literal with
629         // length greater than 1.
630
631         let starts_with_number = self.first().is_digit(10);
632
633         // Skip the literal contents.
634         // First symbol can be a number (which isn't a valid identifier start),
635         // so skip it without any checks.
636         self.bump();
637         self.eat_while(is_id_continue);
638
639         // Check if after skipping literal contents we've met a closing
640         // single quote (which means that user attempted to create a
641         // string with single quotes).
642         if self.first() == '\'' {
643             self.bump();
644             let kind = Char { terminated: true };
645             Literal { kind, suffix_start: self.pos_within_token() }
646         } else {
647             Lifetime { starts_with_number }
648         }
649     }
650
651     fn single_quoted_string(&mut self) -> bool {
652         debug_assert!(self.prev() == '\'');
653         // Check if it's a one-symbol literal.
654         if self.second() == '\'' && self.first() != '\\' {
655             self.bump();
656             self.bump();
657             return true;
658         }
659
660         // Literal has more than one symbol.
661
662         // Parse until either quotes are terminated or error is detected.
663         loop {
664             match self.first() {
665                 // Quotes are terminated, finish parsing.
666                 '\'' => {
667                     self.bump();
668                     return true;
669                 }
670                 // Probably beginning of the comment, which we don't want to include
671                 // to the error report.
672                 '/' => break,
673                 // Newline without following '\'' means unclosed quote, stop parsing.
674                 '\n' if self.second() != '\'' => break,
675                 // End of file, stop parsing.
676                 EOF_CHAR if self.is_eof() => break,
677                 // Escaped slash is considered one character, so bump twice.
678                 '\\' => {
679                     self.bump();
680                     self.bump();
681                 }
682                 // Skip the character.
683                 _ => {
684                     self.bump();
685                 }
686             }
687         }
688         // String was not terminated.
689         false
690     }
691
692     /// Eats double-quoted string and returns true
693     /// if string is terminated.
694     fn double_quoted_string(&mut self) -> bool {
695         debug_assert!(self.prev() == '"');
696         while let Some(c) = self.bump() {
697             match c {
698                 '"' => {
699                     return true;
700                 }
701                 '\\' if self.first() == '\\' || self.first() == '"' => {
702                     // Bump again to skip escaped character.
703                     self.bump();
704                 }
705                 _ => (),
706             }
707         }
708         // End of file reached.
709         false
710     }
711
712     /// Eats the double-quoted string and returns `n_hashes` and an error if encountered.
713     fn raw_double_quoted_string(&mut self, prefix_len: u32) -> Result<u8, RawStrError> {
714         // Wrap the actual function to handle the error with too many hashes.
715         // This way, it eats the whole raw string.
716         let n_hashes = self.raw_string_unvalidated(prefix_len)?;
717         // Only up to 255 `#`s are allowed in raw strings
718         match u8::try_from(n_hashes) {
719             Ok(num) => Ok(num),
720             Err(_) => Err(RawStrError::TooManyDelimiters { found: n_hashes }),
721         }
722     }
723
724     fn raw_string_unvalidated(&mut self, prefix_len: u32) -> Result<u32, RawStrError> {
725         debug_assert!(self.prev() == 'r');
726         let start_pos = self.pos_within_token();
727         let mut possible_terminator_offset = None;
728         let mut max_hashes = 0;
729
730         // Count opening '#' symbols.
731         let mut eaten = 0;
732         while self.first() == '#' {
733             eaten += 1;
734             self.bump();
735         }
736         let n_start_hashes = eaten;
737
738         // Check that string is started.
739         match self.bump() {
740             Some('"') => (),
741             c => {
742                 let c = c.unwrap_or(EOF_CHAR);
743                 return Err(RawStrError::InvalidStarter { bad_char: c });
744             }
745         }
746
747         // Skip the string contents and on each '#' character met, check if this is
748         // a raw string termination.
749         loop {
750             self.eat_while(|c| c != '"');
751
752             if self.is_eof() {
753                 return Err(RawStrError::NoTerminator {
754                     expected: n_start_hashes,
755                     found: max_hashes,
756                     possible_terminator_offset,
757                 });
758             }
759
760             // Eat closing double quote.
761             self.bump();
762
763             // Check that amount of closing '#' symbols
764             // is equal to the amount of opening ones.
765             // Note that this will not consume extra trailing `#` characters:
766             // `r###"abcde"####` is lexed as a `RawStr { n_hashes: 3 }`
767             // followed by a `#` token.
768             let mut n_end_hashes = 0;
769             while self.first() == '#' && n_end_hashes < n_start_hashes {
770                 n_end_hashes += 1;
771                 self.bump();
772             }
773
774             if n_end_hashes == n_start_hashes {
775                 return Ok(n_start_hashes);
776             } else if n_end_hashes > max_hashes {
777                 // Keep track of possible terminators to give a hint about
778                 // where there might be a missing terminator
779                 possible_terminator_offset =
780                     Some(self.pos_within_token() - start_pos - n_end_hashes + prefix_len);
781                 max_hashes = n_end_hashes;
782             }
783         }
784     }
785
786     fn eat_decimal_digits(&mut self) -> bool {
787         let mut has_digits = false;
788         loop {
789             match self.first() {
790                 '_' => {
791                     self.bump();
792                 }
793                 '0'..='9' => {
794                     has_digits = true;
795                     self.bump();
796                 }
797                 _ => break,
798             }
799         }
800         has_digits
801     }
802
803     fn eat_hexadecimal_digits(&mut self) -> bool {
804         let mut has_digits = false;
805         loop {
806             match self.first() {
807                 '_' => {
808                     self.bump();
809                 }
810                 '0'..='9' | 'a'..='f' | 'A'..='F' => {
811                     has_digits = true;
812                     self.bump();
813                 }
814                 _ => break,
815             }
816         }
817         has_digits
818     }
819
820     /// Eats the float exponent. Returns true if at least one digit was met,
821     /// and returns false otherwise.
822     fn eat_float_exponent(&mut self) -> bool {
823         debug_assert!(self.prev() == 'e' || self.prev() == 'E');
824         if self.first() == '-' || self.first() == '+' {
825             self.bump();
826         }
827         self.eat_decimal_digits()
828     }
829
830     // Eats the suffix of the literal, e.g. "_u8".
831     fn eat_literal_suffix(&mut self) {
832         self.eat_identifier();
833     }
834
835     // Eats the identifier.
836     fn eat_identifier(&mut self) {
837         if !is_id_start(self.first()) {
838             return;
839         }
840         self.bump();
841
842         self.eat_while(is_id_continue);
843     }
844 }