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