rustc_lexer/
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
22// tidy-alphabetical-start
23// We want to be able to build this crate with a stable compiler,
24// so no `#![feature]` attributes should be added.
25#![deny(unstable_features)]
26// tidy-alphabetical-end
27
28mod cursor;
29
30#[cfg(test)]
31mod tests;
32
33use LiteralKind::*;
34use TokenKind::*;
35use cursor::EOF_CHAR;
36pub use cursor::{Cursor, FrontmatterAllowed};
37use unicode_properties::UnicodeEmoji;
38pub use unicode_xid::UNICODE_VERSION as UNICODE_XID_VERSION;
39
40/// Parsed token.
41/// It doesn't contain information about data that has been parsed,
42/// only the type of the token and its size.
43#[derive(Debug)]
44pub struct Token {
45    pub kind: TokenKind,
46    pub len: u32,
47}
48
49impl Token {
50    fn new(kind: TokenKind, len: u32) -> Token {
51        Token { kind, len }
52    }
53}
54
55/// Enum representing common lexeme types.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum TokenKind {
58    /// A line comment, e.g. `// comment`.
59    LineComment {
60        doc_style: Option<DocStyle>,
61    },
62
63    /// A block comment, e.g. `/* block comment */`.
64    ///
65    /// Block comments can be recursive, so a sequence like `/* /* */`
66    /// will not be considered terminated and will result in a parsing error.
67    BlockComment {
68        doc_style: Option<DocStyle>,
69        terminated: bool,
70    },
71
72    /// Any whitespace character sequence.
73    Whitespace,
74
75    Frontmatter {
76        has_invalid_preceding_whitespace: bool,
77        invalid_infostring: bool,
78    },
79
80    /// An identifier or keyword, e.g. `ident` or `continue`.
81    Ident,
82
83    /// An identifier that is invalid because it contains emoji.
84    InvalidIdent,
85
86    /// A raw identifier, e.g. "r#ident".
87    RawIdent,
88
89    /// An unknown literal prefix, like `foo#`, `foo'`, `foo"`. Excludes
90    /// literal prefixes that contain emoji, which are considered "invalid".
91    ///
92    /// Note that only the
93    /// prefix (`foo`) is included in the token, not the separator (which is
94    /// lexed as its own distinct token). In Rust 2021 and later, reserved
95    /// prefixes are reported as errors; in earlier editions, they result in a
96    /// (allowed by default) lint, and are treated as regular identifier
97    /// tokens.
98    UnknownPrefix,
99
100    /// An unknown prefix in a lifetime, like `'foo#`.
101    ///
102    /// Like `UnknownPrefix`, only the `'` and prefix are included in the token
103    /// and not the separator.
104    UnknownPrefixLifetime,
105
106    /// A raw lifetime, e.g. `'r#foo`. In edition < 2021 it will be split into
107    /// several tokens: `'r` and `#` and `foo`.
108    RawLifetime,
109
110    /// Guarded string literal prefix: `#"` or `##`.
111    ///
112    /// Used for reserving "guarded strings" (RFC 3598) in edition 2024.
113    /// Split into the component tokens on older editions.
114    GuardedStrPrefix,
115
116    /// Literals, e.g. `12u8`, `1.0e-40`, `b"123"`. Note that `_` is an invalid
117    /// suffix, but may be present here on string and float literals. Users of
118    /// this type will need to check for and reject that case.
119    ///
120    /// See [LiteralKind] for more details.
121    Literal {
122        kind: LiteralKind,
123        suffix_start: u32,
124    },
125
126    /// A lifetime, e.g. `'a`.
127    Lifetime {
128        starts_with_number: bool,
129    },
130
131    /// `;`
132    Semi,
133    /// `,`
134    Comma,
135    /// `.`
136    Dot,
137    /// `(`
138    OpenParen,
139    /// `)`
140    CloseParen,
141    /// `{`
142    OpenBrace,
143    /// `}`
144    CloseBrace,
145    /// `[`
146    OpenBracket,
147    /// `]`
148    CloseBracket,
149    /// `@`
150    At,
151    /// `#`
152    Pound,
153    /// `~`
154    Tilde,
155    /// `?`
156    Question,
157    /// `:`
158    Colon,
159    /// `$`
160    Dollar,
161    /// `=`
162    Eq,
163    /// `!`
164    Bang,
165    /// `<`
166    Lt,
167    /// `>`
168    Gt,
169    /// `-`
170    Minus,
171    /// `&`
172    And,
173    /// `|`
174    Or,
175    /// `+`
176    Plus,
177    /// `*`
178    Star,
179    /// `/`
180    Slash,
181    /// `^`
182    Caret,
183    /// `%`
184    Percent,
185
186    /// Unknown token, not expected by the lexer, e.g. "№"
187    Unknown,
188
189    /// End of input.
190    Eof,
191}
192
193#[derive(Clone, Copy, Debug, PartialEq, Eq)]
194pub enum DocStyle {
195    Outer,
196    Inner,
197}
198
199/// Enum representing the literal types supported by the lexer.
200///
201/// Note that the suffix is *not* considered when deciding the `LiteralKind` in
202/// this type. This means that float literals like `1f32` are classified by this
203/// type as `Int`. (Compare against `rustc_ast::token::LitKind` and
204/// `rustc_ast::ast::LitKind`).
205#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
206pub enum LiteralKind {
207    /// `12_u8`, `0o100`, `0b120i99`, `1f32`.
208    Int { base: Base, empty_int: bool },
209    /// `12.34f32`, `1e3`, but not `1f32`.
210    Float { base: Base, empty_exponent: bool },
211    /// `'a'`, `'\\'`, `'''`, `';`
212    Char { terminated: bool },
213    /// `b'a'`, `b'\\'`, `b'''`, `b';`
214    Byte { terminated: bool },
215    /// `"abc"`, `"abc`
216    Str { terminated: bool },
217    /// `b"abc"`, `b"abc`
218    ByteStr { terminated: bool },
219    /// `c"abc"`, `c"abc`
220    CStr { terminated: bool },
221    /// `r"abc"`, `r#"abc"#`, `r####"ab"###"c"####`, `r#"a`. `None` indicates
222    /// an invalid literal.
223    RawStr { n_hashes: Option<u8> },
224    /// `br"abc"`, `br#"abc"#`, `br####"ab"###"c"####`, `br#"a`. `None`
225    /// indicates an invalid literal.
226    RawByteStr { n_hashes: Option<u8> },
227    /// `cr"abc"`, "cr#"abc"#", `cr#"a`. `None` indicates an invalid literal.
228    RawCStr { n_hashes: Option<u8> },
229}
230
231/// `#"abc"#`, `##"a"` (fewer closing), or even `#"a` (unterminated).
232///
233/// Can capture fewer closing hashes than starting hashes,
234/// for more efficient lexing and better backwards diagnostics.
235#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
236pub struct GuardedStr {
237    pub n_hashes: u32,
238    pub terminated: bool,
239    pub token_len: u32,
240}
241
242#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
243pub enum RawStrError {
244    /// Non `#` characters exist between `r` and `"`, e.g. `r##~"abcde"##`
245    InvalidStarter { bad_char: char },
246    /// The string was not terminated, e.g. `r###"abcde"##`.
247    /// `possible_terminator_offset` is the number of characters after `r` or
248    /// `br` where they may have intended to terminate it.
249    NoTerminator { expected: u32, found: u32, possible_terminator_offset: Option<u32> },
250    /// More than 255 `#`s exist.
251    TooManyDelimiters { found: u32 },
252}
253
254/// Base of numeric literal encoding according to its prefix.
255#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
256pub enum Base {
257    /// Literal starts with "0b".
258    Binary = 2,
259    /// Literal starts with "0o".
260    Octal = 8,
261    /// Literal doesn't contain a prefix.
262    Decimal = 10,
263    /// Literal starts with "0x".
264    Hexadecimal = 16,
265}
266
267/// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun",
268/// but shebang isn't a part of rust syntax.
269pub fn strip_shebang(input: &str) -> Option<usize> {
270    // Shebang must start with `#!` literally, without any preceding whitespace.
271    // For simplicity we consider any line starting with `#!` a shebang,
272    // regardless of restrictions put on shebangs by specific platforms.
273    if let Some(input_tail) = input.strip_prefix("#!") {
274        // Ok, this is a shebang but if the next non-whitespace token is `[`,
275        // then it may be valid Rust code, so consider it Rust code.
276        let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| {
277            !matches!(
278                tok,
279                TokenKind::Whitespace
280                    | TokenKind::LineComment { doc_style: None }
281                    | TokenKind::BlockComment { doc_style: None, .. }
282            )
283        });
284        if next_non_whitespace_token != Some(TokenKind::OpenBracket) {
285            // No other choice than to consider this a shebang.
286            return Some(2 + input_tail.lines().next().unwrap_or_default().len());
287        }
288    }
289    None
290}
291
292/// Validates a raw string literal. Used for getting more information about a
293/// problem with a `RawStr`/`RawByteStr` with a `None` field.
294#[inline]
295pub fn validate_raw_str(input: &str, prefix_len: u32) -> Result<(), RawStrError> {
296    debug_assert!(!input.is_empty());
297    let mut cursor = Cursor::new(input, FrontmatterAllowed::No);
298    // Move past the leading `r` or `br`.
299    for _ in 0..prefix_len {
300        cursor.bump().unwrap();
301    }
302    cursor.raw_double_quoted_string(prefix_len).map(|_| ())
303}
304
305/// Creates an iterator that produces tokens from the input string.
306pub fn tokenize(input: &str) -> impl Iterator<Item = Token> {
307    let mut cursor = Cursor::new(input, FrontmatterAllowed::No);
308    std::iter::from_fn(move || {
309        let token = cursor.advance_token();
310        if token.kind != TokenKind::Eof { Some(token) } else { None }
311    })
312}
313
314/// True if `c` is considered a whitespace according to Rust language definition.
315/// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html)
316/// for definitions of these classes.
317pub fn is_whitespace(c: char) -> bool {
318    // This is Pattern_White_Space.
319    //
320    // Note that this set is stable (ie, it doesn't change with different
321    // Unicode versions), so it's ok to just hard-code the values.
322
323    matches!(
324        c,
325        // Usual ASCII suspects
326        '\u{0009}'   // \t
327        | '\u{000A}' // \n
328        | '\u{000B}' // vertical tab
329        | '\u{000C}' // form feed
330        | '\u{000D}' // \r
331        | '\u{0020}' // space
332
333        // NEXT LINE from latin1
334        | '\u{0085}'
335
336        // Bidi markers
337        | '\u{200E}' // LEFT-TO-RIGHT MARK
338        | '\u{200F}' // RIGHT-TO-LEFT MARK
339
340        // Dedicated whitespace characters from Unicode
341        | '\u{2028}' // LINE SEPARATOR
342        | '\u{2029}' // PARAGRAPH SEPARATOR
343    )
344}
345
346/// True if `c` is valid as a first character of an identifier.
347/// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for
348/// a formal definition of valid identifier name.
349pub fn is_id_start(c: char) -> bool {
350    // This is XID_Start OR '_' (which formally is not a XID_Start).
351    c == '_' || unicode_xid::UnicodeXID::is_xid_start(c)
352}
353
354/// True if `c` is valid as a non-first character of an identifier.
355/// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for
356/// a formal definition of valid identifier name.
357pub fn is_id_continue(c: char) -> bool {
358    unicode_xid::UnicodeXID::is_xid_continue(c)
359}
360
361/// The passed string is lexically an identifier.
362pub fn is_ident(string: &str) -> bool {
363    let mut chars = string.chars();
364    if let Some(start) = chars.next() {
365        is_id_start(start) && chars.all(is_id_continue)
366    } else {
367        false
368    }
369}
370
371impl Cursor<'_> {
372    /// Parses a token from the input string.
373    pub fn advance_token(&mut self) -> Token {
374        let Some(first_char) = self.bump() else {
375            return Token::new(TokenKind::Eof, 0);
376        };
377
378        let token_kind = match first_char {
379            c if matches!(self.frontmatter_allowed, FrontmatterAllowed::Yes)
380                && is_whitespace(c) =>
381            {
382                let mut last = first_char;
383                while is_whitespace(self.first()) {
384                    let Some(c) = self.bump() else {
385                        break;
386                    };
387                    last = c;
388                }
389                // invalid frontmatter opening as whitespace preceding it isn't newline.
390                // combine the whitespace and the frontmatter to a single token as we shall
391                // error later.
392                if last != '\n' && self.as_str().starts_with("---") {
393                    self.bump();
394                    self.frontmatter(true)
395                } else {
396                    Whitespace
397                }
398            }
399            '-' if matches!(self.frontmatter_allowed, FrontmatterAllowed::Yes)
400                && self.as_str().starts_with("--") =>
401            {
402                // happy path
403                self.frontmatter(false)
404            }
405            // Slash, comment or block comment.
406            '/' => match self.first() {
407                '/' => self.line_comment(),
408                '*' => self.block_comment(),
409                _ => Slash,
410            },
411
412            // Whitespace sequence.
413            c if is_whitespace(c) => self.whitespace(),
414
415            // Raw identifier, raw string literal or identifier.
416            'r' => match (self.first(), self.second()) {
417                ('#', c1) if is_id_start(c1) => self.raw_ident(),
418                ('#', _) | ('"', _) => {
419                    let res = self.raw_double_quoted_string(1);
420                    let suffix_start = self.pos_within_token();
421                    if res.is_ok() {
422                        self.eat_literal_suffix();
423                    }
424                    let kind = RawStr { n_hashes: res.ok() };
425                    Literal { kind, suffix_start }
426                }
427                _ => self.ident_or_unknown_prefix(),
428            },
429
430            // Byte literal, byte string literal, raw byte string literal or identifier.
431            'b' => self.c_or_byte_string(
432                |terminated| ByteStr { terminated },
433                |n_hashes| RawByteStr { n_hashes },
434                Some(|terminated| Byte { terminated }),
435            ),
436
437            // c-string literal, raw c-string literal or identifier.
438            'c' => self.c_or_byte_string(
439                |terminated| CStr { terminated },
440                |n_hashes| RawCStr { n_hashes },
441                None,
442            ),
443
444            // Identifier (this should be checked after other variant that can
445            // start as identifier).
446            c if is_id_start(c) => self.ident_or_unknown_prefix(),
447
448            // Numeric literal.
449            c @ '0'..='9' => {
450                let literal_kind = self.number(c);
451                let suffix_start = self.pos_within_token();
452                self.eat_literal_suffix();
453                TokenKind::Literal { kind: literal_kind, suffix_start }
454            }
455
456            // Guarded string literal prefix: `#"` or `##`
457            '#' if matches!(self.first(), '"' | '#') => {
458                self.bump();
459                TokenKind::GuardedStrPrefix
460            }
461
462            // One-symbol tokens.
463            ';' => Semi,
464            ',' => Comma,
465            '.' => Dot,
466            '(' => OpenParen,
467            ')' => CloseParen,
468            '{' => OpenBrace,
469            '}' => CloseBrace,
470            '[' => OpenBracket,
471            ']' => CloseBracket,
472            '@' => At,
473            '#' => Pound,
474            '~' => Tilde,
475            '?' => Question,
476            ':' => Colon,
477            '$' => Dollar,
478            '=' => Eq,
479            '!' => Bang,
480            '<' => Lt,
481            '>' => Gt,
482            '-' => Minus,
483            '&' => And,
484            '|' => Or,
485            '+' => Plus,
486            '*' => Star,
487            '^' => Caret,
488            '%' => Percent,
489
490            // Lifetime or character literal.
491            '\'' => self.lifetime_or_char(),
492
493            // String literal.
494            '"' => {
495                let terminated = self.double_quoted_string();
496                let suffix_start = self.pos_within_token();
497                if terminated {
498                    self.eat_literal_suffix();
499                }
500                let kind = Str { terminated };
501                Literal { kind, suffix_start }
502            }
503            // Identifier starting with an emoji. Only lexed for graceful error recovery.
504            c if !c.is_ascii() && c.is_emoji_char() => self.invalid_ident(),
505            _ => Unknown,
506        };
507        if matches!(self.frontmatter_allowed, FrontmatterAllowed::Yes)
508            && !matches!(token_kind, Whitespace)
509        {
510            // stop allowing frontmatters after first non-whitespace token
511            self.frontmatter_allowed = FrontmatterAllowed::No;
512        }
513        let res = Token::new(token_kind, self.pos_within_token());
514        self.reset_pos_within_token();
515        res
516    }
517
518    /// Given that one `-` was eaten, eat the rest of the frontmatter.
519    fn frontmatter(&mut self, has_invalid_preceding_whitespace: bool) -> TokenKind {
520        debug_assert_eq!('-', self.prev());
521
522        let pos = self.pos_within_token();
523        self.eat_while(|c| c == '-');
524
525        // one `-` is eaten by the caller.
526        let length_opening = self.pos_within_token() - pos + 1;
527
528        // must be ensured by the caller
529        debug_assert!(length_opening >= 3);
530
531        // whitespace between the opening and the infostring.
532        self.eat_while(|ch| ch != '\n' && is_whitespace(ch));
533
534        // copied from `eat_identifier`, but allows `.` in infostring to allow something like
535        // `---Cargo.toml` as a valid opener
536        if is_id_start(self.first()) {
537            self.bump();
538            self.eat_while(|c| is_id_continue(c) || c == '.');
539        }
540
541        self.eat_while(|ch| ch != '\n' && is_whitespace(ch));
542        let invalid_infostring = self.first() != '\n';
543
544        let mut s = self.as_str();
545        let mut found = false;
546        let mut size = 0;
547        while let Some(closing) = s.find(&"-".repeat(length_opening as usize)) {
548            let preceding_chars_start = s[..closing].rfind("\n").map_or(0, |i| i + 1);
549            if s[preceding_chars_start..closing].chars().all(is_whitespace) {
550                // candidate found
551                self.bump_bytes(size + closing);
552                // in case like
553                // ---cargo
554                // --- blahblah
555                // or
556                // ---cargo
557                // ----
558                // combine those stuff into this frontmatter token such that it gets detected later.
559                self.eat_until(b'\n');
560                found = true;
561                break;
562            } else {
563                s = &s[closing + length_opening as usize..];
564                size += closing + length_opening as usize;
565            }
566        }
567
568        if !found {
569            // recovery strategy: a closing statement might have preceding whitespace/newline
570            // but not have enough dashes to properly close. In this case, we eat until there,
571            // and report a mismatch in the parser.
572            let mut rest = self.as_str();
573            // We can look for a shorter closing (starting with four dashes but closing with three)
574            // and other indications that Rust has started and the infostring has ended.
575            let mut potential_closing = rest
576                .find("\n---")
577                // n.b. only in the case where there are dashes, we move the index to the line where
578                // the dashes start as we eat to include that line. For other cases those are Rust code
579                // and not included in the frontmatter.
580                .map(|x| x + 1)
581                .or_else(|| rest.find("\nuse "))
582                .or_else(|| rest.find("\n//!"))
583                .or_else(|| rest.find("\n#!["));
584
585            if potential_closing.is_none() {
586                // a less fortunate recovery if all else fails which finds any dashes preceded by whitespace
587                // on a standalone line. Might be wrong.
588                while let Some(closing) = rest.find("---") {
589                    let preceding_chars_start = rest[..closing].rfind("\n").map_or(0, |i| i + 1);
590                    if rest[preceding_chars_start..closing].chars().all(is_whitespace) {
591                        // candidate found
592                        potential_closing = Some(closing);
593                        break;
594                    } else {
595                        rest = &rest[closing + 3..];
596                    }
597                }
598            }
599
600            if let Some(potential_closing) = potential_closing {
601                // bump to the potential closing, and eat everything on that line.
602                self.bump_bytes(potential_closing);
603                self.eat_until(b'\n');
604            } else {
605                // eat everything. this will get reported as an unclosed frontmatter.
606                self.eat_while(|_| true);
607            }
608        }
609
610        Frontmatter { has_invalid_preceding_whitespace, invalid_infostring }
611    }
612
613    fn line_comment(&mut self) -> TokenKind {
614        debug_assert!(self.prev() == '/' && self.first() == '/');
615        self.bump();
616
617        let doc_style = match self.first() {
618            // `//!` is an inner line doc comment.
619            '!' => Some(DocStyle::Inner),
620            // `////` (more than 3 slashes) is not considered a doc comment.
621            '/' if self.second() != '/' => Some(DocStyle::Outer),
622            _ => None,
623        };
624
625        self.eat_until(b'\n');
626        LineComment { doc_style }
627    }
628
629    fn block_comment(&mut self) -> TokenKind {
630        debug_assert!(self.prev() == '/' && self.first() == '*');
631        self.bump();
632
633        let doc_style = match self.first() {
634            // `/*!` is an inner block doc comment.
635            '!' => Some(DocStyle::Inner),
636            // `/***` (more than 2 stars) is not considered a doc comment.
637            // `/**/` is not considered a doc comment.
638            '*' if !matches!(self.second(), '*' | '/') => Some(DocStyle::Outer),
639            _ => None,
640        };
641
642        let mut depth = 1usize;
643        while let Some(c) = self.bump() {
644            match c {
645                '/' if self.first() == '*' => {
646                    self.bump();
647                    depth += 1;
648                }
649                '*' if self.first() == '/' => {
650                    self.bump();
651                    depth -= 1;
652                    if depth == 0 {
653                        // This block comment is closed, so for a construction like "/* */ */"
654                        // there will be a successfully parsed block comment "/* */"
655                        // and " */" will be processed separately.
656                        break;
657                    }
658                }
659                _ => (),
660            }
661        }
662
663        BlockComment { doc_style, terminated: depth == 0 }
664    }
665
666    fn whitespace(&mut self) -> TokenKind {
667        debug_assert!(is_whitespace(self.prev()));
668        self.eat_while(is_whitespace);
669        Whitespace
670    }
671
672    fn raw_ident(&mut self) -> TokenKind {
673        debug_assert!(self.prev() == 'r' && self.first() == '#' && is_id_start(self.second()));
674        // Eat "#" symbol.
675        self.bump();
676        // Eat the identifier part of RawIdent.
677        self.eat_identifier();
678        RawIdent
679    }
680
681    fn ident_or_unknown_prefix(&mut self) -> TokenKind {
682        debug_assert!(is_id_start(self.prev()));
683        // Start is already eaten, eat the rest of identifier.
684        self.eat_while(is_id_continue);
685        // Known prefixes must have been handled earlier. So if
686        // we see a prefix here, it is definitely an unknown prefix.
687        match self.first() {
688            '#' | '"' | '\'' => UnknownPrefix,
689            c if !c.is_ascii() && c.is_emoji_char() => self.invalid_ident(),
690            _ => Ident,
691        }
692    }
693
694    fn invalid_ident(&mut self) -> TokenKind {
695        // Start is already eaten, eat the rest of identifier.
696        self.eat_while(|c| {
697            const ZERO_WIDTH_JOINER: char = '\u{200d}';
698            is_id_continue(c) || (!c.is_ascii() && c.is_emoji_char()) || c == ZERO_WIDTH_JOINER
699        });
700        // An invalid identifier followed by '#' or '"' or '\'' could be
701        // interpreted as an invalid literal prefix. We don't bother doing that
702        // because the treatment of invalid identifiers and invalid prefixes
703        // would be the same.
704        InvalidIdent
705    }
706
707    fn c_or_byte_string(
708        &mut self,
709        mk_kind: fn(bool) -> LiteralKind,
710        mk_kind_raw: fn(Option<u8>) -> LiteralKind,
711        single_quoted: Option<fn(bool) -> LiteralKind>,
712    ) -> TokenKind {
713        match (self.first(), self.second(), single_quoted) {
714            ('\'', _, Some(single_quoted)) => {
715                self.bump();
716                let terminated = self.single_quoted_string();
717                let suffix_start = self.pos_within_token();
718                if terminated {
719                    self.eat_literal_suffix();
720                }
721                let kind = single_quoted(terminated);
722                Literal { kind, suffix_start }
723            }
724            ('"', _, _) => {
725                self.bump();
726                let terminated = self.double_quoted_string();
727                let suffix_start = self.pos_within_token();
728                if terminated {
729                    self.eat_literal_suffix();
730                }
731                let kind = mk_kind(terminated);
732                Literal { kind, suffix_start }
733            }
734            ('r', '"', _) | ('r', '#', _) => {
735                self.bump();
736                let res = self.raw_double_quoted_string(2);
737                let suffix_start = self.pos_within_token();
738                if res.is_ok() {
739                    self.eat_literal_suffix();
740                }
741                let kind = mk_kind_raw(res.ok());
742                Literal { kind, suffix_start }
743            }
744            _ => self.ident_or_unknown_prefix(),
745        }
746    }
747
748    fn number(&mut self, first_digit: char) -> LiteralKind {
749        debug_assert!('0' <= self.prev() && self.prev() <= '9');
750        let mut base = Base::Decimal;
751        if first_digit == '0' {
752            // Attempt to parse encoding base.
753            match self.first() {
754                'b' => {
755                    base = Base::Binary;
756                    self.bump();
757                    if !self.eat_decimal_digits() {
758                        return Int { base, empty_int: true };
759                    }
760                }
761                'o' => {
762                    base = Base::Octal;
763                    self.bump();
764                    if !self.eat_decimal_digits() {
765                        return Int { base, empty_int: true };
766                    }
767                }
768                'x' => {
769                    base = Base::Hexadecimal;
770                    self.bump();
771                    if !self.eat_hexadecimal_digits() {
772                        return Int { base, empty_int: true };
773                    }
774                }
775                // Not a base prefix; consume additional digits.
776                '0'..='9' | '_' => {
777                    self.eat_decimal_digits();
778                }
779
780                // Also not a base prefix; nothing more to do here.
781                '.' | 'e' | 'E' => {}
782
783                // Just a 0.
784                _ => return Int { base, empty_int: false },
785            }
786        } else {
787            // No base prefix, parse number in the usual way.
788            self.eat_decimal_digits();
789        }
790
791        match self.first() {
792            // Don't be greedy if this is actually an
793            // integer literal followed by field/method access or a range pattern
794            // (`0..2` and `12.foo()`)
795            '.' if self.second() != '.' && !is_id_start(self.second()) => {
796                // might have stuff after the ., and if it does, it needs to start
797                // with a number
798                self.bump();
799                let mut empty_exponent = false;
800                if self.first().is_ascii_digit() {
801                    self.eat_decimal_digits();
802                    match self.first() {
803                        'e' | 'E' => {
804                            self.bump();
805                            empty_exponent = !self.eat_float_exponent();
806                        }
807                        _ => (),
808                    }
809                }
810                Float { base, empty_exponent }
811            }
812            'e' | 'E' => {
813                self.bump();
814                let empty_exponent = !self.eat_float_exponent();
815                Float { base, empty_exponent }
816            }
817            _ => Int { base, empty_int: false },
818        }
819    }
820
821    fn lifetime_or_char(&mut self) -> TokenKind {
822        debug_assert!(self.prev() == '\'');
823
824        let can_be_a_lifetime = if self.second() == '\'' {
825            // It's surely not a lifetime.
826            false
827        } else {
828            // If the first symbol is valid for identifier, it can be a lifetime.
829            // Also check if it's a number for a better error reporting (so '0 will
830            // be reported as invalid lifetime and not as unterminated char literal).
831            is_id_start(self.first()) || self.first().is_ascii_digit()
832        };
833
834        if !can_be_a_lifetime {
835            let terminated = self.single_quoted_string();
836            let suffix_start = self.pos_within_token();
837            if terminated {
838                self.eat_literal_suffix();
839            }
840            let kind = Char { terminated };
841            return Literal { kind, suffix_start };
842        }
843
844        if self.first() == 'r' && self.second() == '#' && is_id_start(self.third()) {
845            // Eat "r" and `#`, and identifier start characters.
846            self.bump();
847            self.bump();
848            self.bump();
849            self.eat_while(is_id_continue);
850            return RawLifetime;
851        }
852
853        // Either a lifetime or a character literal with
854        // length greater than 1.
855        let starts_with_number = self.first().is_ascii_digit();
856
857        // Skip the literal contents.
858        // First symbol can be a number (which isn't a valid identifier start),
859        // so skip it without any checks.
860        self.bump();
861        self.eat_while(is_id_continue);
862
863        match self.first() {
864            // Check if after skipping literal contents we've met a closing
865            // single quote (which means that user attempted to create a
866            // string with single quotes).
867            '\'' => {
868                self.bump();
869                let kind = Char { terminated: true };
870                Literal { kind, suffix_start: self.pos_within_token() }
871            }
872            '#' if !starts_with_number => UnknownPrefixLifetime,
873            _ => Lifetime { starts_with_number },
874        }
875    }
876
877    fn single_quoted_string(&mut self) -> bool {
878        debug_assert!(self.prev() == '\'');
879        // Check if it's a one-symbol literal.
880        if self.second() == '\'' && self.first() != '\\' {
881            self.bump();
882            self.bump();
883            return true;
884        }
885
886        // Literal has more than one symbol.
887
888        // Parse until either quotes are terminated or error is detected.
889        loop {
890            match self.first() {
891                // Quotes are terminated, finish parsing.
892                '\'' => {
893                    self.bump();
894                    return true;
895                }
896                // Probably beginning of the comment, which we don't want to include
897                // to the error report.
898                '/' => break,
899                // Newline without following '\'' means unclosed quote, stop parsing.
900                '\n' if self.second() != '\'' => break,
901                // End of file, stop parsing.
902                EOF_CHAR if self.is_eof() => break,
903                // Escaped slash is considered one character, so bump twice.
904                '\\' => {
905                    self.bump();
906                    self.bump();
907                }
908                // Skip the character.
909                _ => {
910                    self.bump();
911                }
912            }
913        }
914        // String was not terminated.
915        false
916    }
917
918    /// Eats double-quoted string and returns true
919    /// if string is terminated.
920    fn double_quoted_string(&mut self) -> bool {
921        debug_assert!(self.prev() == '"');
922        while let Some(c) = self.bump() {
923            match c {
924                '"' => {
925                    return true;
926                }
927                '\\' if self.first() == '\\' || self.first() == '"' => {
928                    // Bump again to skip escaped character.
929                    self.bump();
930                }
931                _ => (),
932            }
933        }
934        // End of file reached.
935        false
936    }
937
938    /// Attempt to lex for a guarded string literal.
939    ///
940    /// Used by `rustc_parse::lexer` to lex for guarded strings
941    /// conditionally based on edition.
942    ///
943    /// Note: this will not reset the `Cursor` when a
944    /// guarded string is not found. It is the caller's
945    /// responsibility to do so.
946    pub fn guarded_double_quoted_string(&mut self) -> Option<GuardedStr> {
947        debug_assert!(self.prev() != '#');
948
949        let mut n_start_hashes: u32 = 0;
950        while self.first() == '#' {
951            n_start_hashes += 1;
952            self.bump();
953        }
954
955        if self.first() != '"' {
956            return None;
957        }
958        self.bump();
959        debug_assert!(self.prev() == '"');
960
961        // Lex the string itself as a normal string literal
962        // so we can recover that for older editions later.
963        let terminated = self.double_quoted_string();
964        if !terminated {
965            let token_len = self.pos_within_token();
966            self.reset_pos_within_token();
967
968            return Some(GuardedStr { n_hashes: n_start_hashes, terminated: false, token_len });
969        }
970
971        // Consume closing '#' symbols.
972        // Note that this will not consume extra trailing `#` characters:
973        // `###"abcde"####` is lexed as a `GuardedStr { n_end_hashes: 3, .. }`
974        // followed by a `#` token.
975        let mut n_end_hashes = 0;
976        while self.first() == '#' && n_end_hashes < n_start_hashes {
977            n_end_hashes += 1;
978            self.bump();
979        }
980
981        // Reserved syntax, always an error, so it doesn't matter if
982        // `n_start_hashes != n_end_hashes`.
983
984        self.eat_literal_suffix();
985
986        let token_len = self.pos_within_token();
987        self.reset_pos_within_token();
988
989        Some(GuardedStr { n_hashes: n_start_hashes, terminated: true, token_len })
990    }
991
992    /// Eats the double-quoted string and returns `n_hashes` and an error if encountered.
993    fn raw_double_quoted_string(&mut self, prefix_len: u32) -> Result<u8, RawStrError> {
994        // Wrap the actual function to handle the error with too many hashes.
995        // This way, it eats the whole raw string.
996        let n_hashes = self.raw_string_unvalidated(prefix_len)?;
997        // Only up to 255 `#`s are allowed in raw strings
998        match u8::try_from(n_hashes) {
999            Ok(num) => Ok(num),
1000            Err(_) => Err(RawStrError::TooManyDelimiters { found: n_hashes }),
1001        }
1002    }
1003
1004    fn raw_string_unvalidated(&mut self, prefix_len: u32) -> Result<u32, RawStrError> {
1005        debug_assert!(self.prev() == 'r');
1006        let start_pos = self.pos_within_token();
1007        let mut possible_terminator_offset = None;
1008        let mut max_hashes = 0;
1009
1010        // Count opening '#' symbols.
1011        let mut eaten = 0;
1012        while self.first() == '#' {
1013            eaten += 1;
1014            self.bump();
1015        }
1016        let n_start_hashes = eaten;
1017
1018        // Check that string is started.
1019        match self.bump() {
1020            Some('"') => (),
1021            c => {
1022                let c = c.unwrap_or(EOF_CHAR);
1023                return Err(RawStrError::InvalidStarter { bad_char: c });
1024            }
1025        }
1026
1027        // Skip the string contents and on each '#' character met, check if this is
1028        // a raw string termination.
1029        loop {
1030            self.eat_until(b'"');
1031
1032            if self.is_eof() {
1033                return Err(RawStrError::NoTerminator {
1034                    expected: n_start_hashes,
1035                    found: max_hashes,
1036                    possible_terminator_offset,
1037                });
1038            }
1039
1040            // Eat closing double quote.
1041            self.bump();
1042
1043            // Check that amount of closing '#' symbols
1044            // is equal to the amount of opening ones.
1045            // Note that this will not consume extra trailing `#` characters:
1046            // `r###"abcde"####` is lexed as a `RawStr { n_hashes: 3 }`
1047            // followed by a `#` token.
1048            let mut n_end_hashes = 0;
1049            while self.first() == '#' && n_end_hashes < n_start_hashes {
1050                n_end_hashes += 1;
1051                self.bump();
1052            }
1053
1054            if n_end_hashes == n_start_hashes {
1055                return Ok(n_start_hashes);
1056            } else if n_end_hashes > max_hashes {
1057                // Keep track of possible terminators to give a hint about
1058                // where there might be a missing terminator
1059                possible_terminator_offset =
1060                    Some(self.pos_within_token() - start_pos - n_end_hashes + prefix_len);
1061                max_hashes = n_end_hashes;
1062            }
1063        }
1064    }
1065
1066    fn eat_decimal_digits(&mut self) -> bool {
1067        let mut has_digits = false;
1068        loop {
1069            match self.first() {
1070                '_' => {
1071                    self.bump();
1072                }
1073                '0'..='9' => {
1074                    has_digits = true;
1075                    self.bump();
1076                }
1077                _ => break,
1078            }
1079        }
1080        has_digits
1081    }
1082
1083    fn eat_hexadecimal_digits(&mut self) -> bool {
1084        let mut has_digits = false;
1085        loop {
1086            match self.first() {
1087                '_' => {
1088                    self.bump();
1089                }
1090                '0'..='9' | 'a'..='f' | 'A'..='F' => {
1091                    has_digits = true;
1092                    self.bump();
1093                }
1094                _ => break,
1095            }
1096        }
1097        has_digits
1098    }
1099
1100    /// Eats the float exponent. Returns true if at least one digit was met,
1101    /// and returns false otherwise.
1102    fn eat_float_exponent(&mut self) -> bool {
1103        debug_assert!(self.prev() == 'e' || self.prev() == 'E');
1104        if self.first() == '-' || self.first() == '+' {
1105            self.bump();
1106        }
1107        self.eat_decimal_digits()
1108    }
1109
1110    // Eats the suffix of the literal, e.g. "u8".
1111    fn eat_literal_suffix(&mut self) {
1112        self.eat_identifier();
1113    }
1114
1115    // Eats the identifier. Note: succeeds on `_`, which isn't a valid
1116    // identifier.
1117    fn eat_identifier(&mut self) {
1118        if !is_id_start(self.first()) {
1119            return;
1120        }
1121        self.bump();
1122
1123        self.eat_while(is_id_continue);
1124    }
1125}