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