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