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 unicode_properties::UnicodeEmoji;
34pub use unicode_xid::UNICODE_VERSION as UNICODE_XID_VERSION;
35
36use self::LiteralKind::*;
37use self::TokenKind::*;
38use crate::cursor::EOF_CHAR;
39pub use crate::cursor::{Cursor, FrontmatterAllowed};
40
41/// Parsed token.
42/// It doesn't contain information about data that has been parsed,
43/// only the type of the token and its size.
44#[derive(Debug)]
45pub struct Token {
46    pub kind: TokenKind,
47    pub len: u32,
48}
49
50impl Token {
51    fn new(kind: TokenKind, len: u32) -> Token {
52        Token { kind, len }
53    }
54}
55
56/// Enum representing common lexeme types.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum TokenKind {
59    /// A line comment, e.g. `// comment`.
60    LineComment {
61        doc_style: Option<DocStyle>,
62    },
63
64    /// A block comment, e.g. `/* block comment */`.
65    ///
66    /// Block comments can be recursive, so a sequence like `/* /* */`
67    /// will not be considered terminated and will result in a parsing error.
68    BlockComment {
69        doc_style: Option<DocStyle>,
70        terminated: bool,
71    },
72
73    /// Any whitespace character sequence.
74    Whitespace,
75
76    Frontmatter {
77        has_invalid_preceding_whitespace: bool,
78        invalid_infostring: bool,
79    },
80
81    /// An identifier or keyword, e.g. `ident` or `continue`.
82    Ident,
83
84    /// An identifier that is invalid because it contains emoji.
85    InvalidIdent,
86
87    /// A raw identifier, e.g. "r#ident".
88    RawIdent,
89
90    /// An unknown literal prefix, like `foo#`, `foo'`, `foo"`. Excludes
91    /// literal prefixes that contain emoji, which are considered "invalid".
92    ///
93    /// Note that only the
94    /// prefix (`foo`) is included in the token, not the separator (which is
95    /// lexed as its own distinct token). In Rust 2021 and later, reserved
96    /// prefixes are reported as errors; in earlier editions, they result in a
97    /// (allowed by default) lint, and are treated as regular identifier
98    /// tokens.
99    UnknownPrefix,
100
101    /// An unknown prefix in a lifetime, like `'foo#`.
102    ///
103    /// Like `UnknownPrefix`, only the `'` and prefix are included in the token
104    /// and not the separator.
105    UnknownPrefixLifetime,
106
107    /// A raw lifetime, e.g. `'r#foo`. In edition < 2021 it will be split into
108    /// several tokens: `'r` and `#` and `foo`.
109    RawLifetime,
110
111    /// Guarded string literal prefix: `#"` or `##`.
112    ///
113    /// Used for reserving "guarded strings" (RFC 3598) in edition 2024.
114    /// Split into the component tokens on older editions.
115    GuardedStrPrefix,
116
117    /// Literals, e.g. `12u8`, `1.0e-40`, `b"123"`. Note that `_` is an invalid
118    /// suffix, but may be present here on string and float literals. Users of
119    /// this type will need to check for and reject that case.
120    ///
121    /// See [LiteralKind] for more details.
122    Literal {
123        kind: LiteralKind,
124        suffix_start: u32,
125    },
126
127    /// A lifetime, e.g. `'a`.
128    Lifetime {
129        starts_with_number: bool,
130    },
131
132    /// `;`
133    Semi,
134    /// `,`
135    Comma,
136    /// `.`
137    Dot,
138    /// `(`
139    OpenParen,
140    /// `)`
141    CloseParen,
142    /// `{`
143    OpenBrace,
144    /// `}`
145    CloseBrace,
146    /// `[`
147    OpenBracket,
148    /// `]`
149    CloseBracket,
150    /// `@`
151    At,
152    /// `#`
153    Pound,
154    /// `~`
155    Tilde,
156    /// `?`
157    Question,
158    /// `:`
159    Colon,
160    /// `$`
161    Dollar,
162    /// `=`
163    Eq,
164    /// `!`
165    Bang,
166    /// `<`
167    Lt,
168    /// `>`
169    Gt,
170    /// `-`
171    Minus,
172    /// `&`
173    And,
174    /// `|`
175    Or,
176    /// `+`
177    Plus,
178    /// `*`
179    Star,
180    /// `/`
181    Slash,
182    /// `^`
183    Caret,
184    /// `%`
185    Percent,
186
187    /// Unknown token, not expected by the lexer, e.g. "№"
188    Unknown,
189
190    /// End of input.
191    Eof,
192}
193
194#[derive(Clone, Copy, Debug, PartialEq, Eq)]
195pub enum DocStyle {
196    Outer,
197    Inner,
198}
199
200/// Enum representing the literal types supported by the lexer.
201///
202/// Note that the suffix is *not* considered when deciding the `LiteralKind` in
203/// this type. This means that float literals like `1f32` are classified by this
204/// type as `Int`. (Compare against `rustc_ast::token::LitKind` and
205/// `rustc_ast::ast::LitKind`).
206#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
207pub enum LiteralKind {
208    /// `12_u8`, `0o100`, `0b120i99`, `1f32`.
209    Int { base: Base, empty_int: bool },
210    /// `12.34f32`, `1e3`, but not `1f32`.
211    Float { base: Base, empty_exponent: bool },
212    /// `'a'`, `'\\'`, `'''`, `';`
213    Char { terminated: bool },
214    /// `b'a'`, `b'\\'`, `b'''`, `b';`
215    Byte { terminated: bool },
216    /// `"abc"`, `"abc`
217    Str { terminated: bool },
218    /// `b"abc"`, `b"abc`
219    ByteStr { terminated: bool },
220    /// `c"abc"`, `c"abc`
221    CStr { terminated: bool },
222    /// `r"abc"`, `r#"abc"#`, `r####"ab"###"c"####`, `r#"a`. `None` indicates
223    /// an invalid literal.
224    RawStr { n_hashes: Option<u8> },
225    /// `br"abc"`, `br#"abc"#`, `br####"ab"###"c"####`, `br#"a`. `None`
226    /// indicates an invalid literal.
227    RawByteStr { n_hashes: Option<u8> },
228    /// `cr"abc"`, "cr#"abc"#", `cr#"a`. `None` indicates an invalid literal.
229    RawCStr { n_hashes: Option<u8> },
230}
231
232/// `#"abc"#`, `##"a"` (fewer closing), or even `#"a` (unterminated).
233///
234/// Can capture fewer closing hashes than starting hashes,
235/// for more efficient lexing and better backwards diagnostics.
236#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
237pub struct GuardedStr {
238    pub n_hashes: u32,
239    pub terminated: bool,
240    pub token_len: u32,
241}
242
243#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
244pub enum RawStrError {
245    /// Non `#` characters exist between `r` and `"`, e.g. `r##~"abcde"##`
246    InvalidStarter { bad_char: char },
247    /// The string was not terminated, e.g. `r###"abcde"##`.
248    /// `possible_terminator_offset` is the number of characters after `r` or
249    /// `br` where they may have intended to terminate it.
250    NoTerminator { expected: u32, found: u32, possible_terminator_offset: Option<u32> },
251    /// More than 255 `#`s exist.
252    TooManyDelimiters { found: u32 },
253}
254
255/// Base of numeric literal encoding according to its prefix.
256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
257pub enum Base {
258    /// Literal starts with "0b".
259    Binary = 2,
260    /// Literal starts with "0o".
261    Octal = 8,
262    /// Literal doesn't contain a prefix.
263    Decimal = 10,
264    /// Literal starts with "0x".
265    Hexadecimal = 16,
266}
267
268/// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun",
269/// but shebang isn't a part of rust syntax.
270pub fn strip_shebang(input: &str) -> Option<usize> {
271    // Shebang must start with `#!` literally, without any preceding whitespace.
272    // For simplicity we consider any line starting with `#!` a shebang,
273    // regardless of restrictions put on shebangs by specific platforms.
274    if let Some(input_tail) = input.strip_prefix("#!") {
275        // Ok, this is a shebang but if the next non-whitespace token is `[`,
276        // then it may be valid Rust code, so consider it Rust code.
277        let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| {
278            !matches!(
279                tok,
280                TokenKind::Whitespace
281                    | TokenKind::LineComment { doc_style: None }
282                    | TokenKind::BlockComment { doc_style: None, .. }
283            )
284        });
285        if next_non_whitespace_token != Some(TokenKind::OpenBracket) {
286            // No other choice than to consider this a shebang.
287            return Some(2 + input_tail.lines().next().unwrap_or_default().len());
288        }
289    }
290    None
291}
292
293/// Validates a raw string literal. Used for getting more information about a
294/// problem with a `RawStr`/`RawByteStr` with a `None` field.
295#[inline]
296pub fn validate_raw_str(input: &str, prefix_len: u32) -> Result<(), RawStrError> {
297    debug_assert!(!input.is_empty());
298    let mut cursor = Cursor::new(input, FrontmatterAllowed::No);
299    // Move past the leading `r` or `br`.
300    for _ in 0..prefix_len {
301        cursor.bump().unwrap();
302    }
303    cursor.raw_double_quoted_string(prefix_len).map(|_| ())
304}
305
306/// Creates an iterator that produces tokens from the input string.
307pub fn tokenize(input: &str) -> impl Iterator<Item = Token> {
308    let mut cursor = Cursor::new(input, FrontmatterAllowed::No);
309    std::iter::from_fn(move || {
310        let token = cursor.advance_token();
311        if token.kind != TokenKind::Eof { Some(token) } else { None }
312    })
313}
314
315/// True if `c` is considered a whitespace according to Rust language definition.
316/// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html)
317/// for definitions of these classes.
318pub fn is_whitespace(c: char) -> bool {
319    // This is Pattern_White_Space.
320    //
321    // Note that this set is stable (ie, it doesn't change with different
322    // Unicode versions), so it's ok to just hard-code the values.
323
324    matches!(
325        c,
326        // Usual ASCII suspects
327        '\u{0009}'   // \t
328        | '\u{000A}' // \n
329        | '\u{000B}' // vertical tab
330        | '\u{000C}' // form feed
331        | '\u{000D}' // \r
332        | '\u{0020}' // space
333
334        // NEXT LINE from latin1
335        | '\u{0085}'
336
337        // Bidi markers
338        | '\u{200E}' // LEFT-TO-RIGHT MARK
339        | '\u{200F}' // RIGHT-TO-LEFT MARK
340
341        // Dedicated whitespace characters from Unicode
342        | '\u{2028}' // LINE SEPARATOR
343        | '\u{2029}' // PARAGRAPH SEPARATOR
344    )
345}
346
347/// True if `c` is valid as a first character of an identifier.
348/// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for
349/// a formal definition of valid identifier name.
350pub fn is_id_start(c: char) -> bool {
351    // This is XID_Start OR '_' (which formally is not a XID_Start).
352    c == '_' || unicode_xid::UnicodeXID::is_xid_start(c)
353}
354
355/// True if `c` is valid as a non-first character of an identifier.
356/// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for
357/// a formal definition of valid identifier name.
358pub fn is_id_continue(c: char) -> bool {
359    unicode_xid::UnicodeXID::is_xid_continue(c)
360}
361
362/// The passed string is lexically an identifier.
363pub fn is_ident(string: &str) -> bool {
364    let mut chars = string.chars();
365    if let Some(start) = chars.next() {
366        is_id_start(start) && chars.all(is_id_continue)
367    } else {
368        false
369    }
370}
371
372impl Cursor<'_> {
373    /// Parses a token from the input string.
374    pub fn advance_token(&mut self) -> Token {
375        let first_char = match self.bump() {
376            Some(c) => c,
377            None => return Token::new(TokenKind::Eof, 0),
378        };
379
380        let token_kind = match first_char {
381            c if matches!(self.frontmatter_allowed, FrontmatterAllowed::Yes)
382                && is_whitespace(c) =>
383            {
384                let mut last = first_char;
385                while is_whitespace(self.first()) {
386                    let Some(c) = self.bump() else {
387                        break;
388                    };
389                    last = c;
390                }
391                // invalid frontmatter opening as whitespace preceding it isn't newline.
392                // combine the whitespace and the frontmatter to a single token as we shall
393                // error later.
394                if last != '\n' && self.as_str().starts_with("---") {
395                    self.bump();
396                    self.frontmatter(true)
397                } else {
398                    Whitespace
399                }
400            }
401            '-' if matches!(self.frontmatter_allowed, FrontmatterAllowed::Yes)
402                && self.as_str().starts_with("--") =>
403            {
404                // happy path
405                self.frontmatter(false)
406            }
407            // Slash, comment or block comment.
408            '/' => match self.first() {
409                '/' => self.line_comment(),
410                '*' => self.block_comment(),
411                _ => Slash,
412            },
413
414            // Whitespace sequence.
415            c if is_whitespace(c) => self.whitespace(),
416
417            // Raw identifier, raw string literal or identifier.
418            'r' => match (self.first(), self.second()) {
419                ('#', c1) if is_id_start(c1) => self.raw_ident(),
420                ('#', _) | ('"', _) => {
421                    let res = self.raw_double_quoted_string(1);
422                    let suffix_start = self.pos_within_token();
423                    if res.is_ok() {
424                        self.eat_literal_suffix();
425                    }
426                    let kind = RawStr { n_hashes: res.ok() };
427                    Literal { kind, suffix_start }
428                }
429                _ => self.ident_or_unknown_prefix(),
430            },
431
432            // Byte literal, byte string literal, raw byte string literal or identifier.
433            'b' => self.c_or_byte_string(
434                |terminated| ByteStr { terminated },
435                |n_hashes| RawByteStr { n_hashes },
436                Some(|terminated| Byte { terminated }),
437            ),
438
439            // c-string literal, raw c-string literal or identifier.
440            'c' => self.c_or_byte_string(
441                |terminated| CStr { terminated },
442                |n_hashes| RawCStr { n_hashes },
443                None,
444            ),
445
446            // Identifier (this should be checked after other variant that can
447            // start as identifier).
448            c if is_id_start(c) => self.ident_or_unknown_prefix(),
449
450            // Numeric literal.
451            c @ '0'..='9' => {
452                let literal_kind = self.number(c);
453                let suffix_start = self.pos_within_token();
454                self.eat_literal_suffix();
455                TokenKind::Literal { kind: literal_kind, suffix_start }
456            }
457
458            // Guarded string literal prefix: `#"` or `##`
459            '#' if matches!(self.first(), '"' | '#') => {
460                self.bump();
461                TokenKind::GuardedStrPrefix
462            }
463
464            // One-symbol tokens.
465            ';' => Semi,
466            ',' => Comma,
467            '.' => Dot,
468            '(' => OpenParen,
469            ')' => CloseParen,
470            '{' => OpenBrace,
471            '}' => CloseBrace,
472            '[' => OpenBracket,
473            ']' => CloseBracket,
474            '@' => At,
475            '#' => Pound,
476            '~' => Tilde,
477            '?' => Question,
478            ':' => Colon,
479            '$' => Dollar,
480            '=' => Eq,
481            '!' => Bang,
482            '<' => Lt,
483            '>' => Gt,
484            '-' => Minus,
485            '&' => And,
486            '|' => Or,
487            '+' => Plus,
488            '*' => Star,
489            '^' => Caret,
490            '%' => Percent,
491
492            // Lifetime or character literal.
493            '\'' => self.lifetime_or_char(),
494
495            // String literal.
496            '"' => {
497                let terminated = self.double_quoted_string();
498                let suffix_start = self.pos_within_token();
499                if terminated {
500                    self.eat_literal_suffix();
501                }
502                let kind = Str { terminated };
503                Literal { kind, suffix_start }
504            }
505            // Identifier starting with an emoji. Only lexed for graceful error recovery.
506            c if !c.is_ascii() && c.is_emoji_char() => self.invalid_ident(),
507            _ => Unknown,
508        };
509        if matches!(self.frontmatter_allowed, FrontmatterAllowed::Yes)
510            && !matches!(token_kind, Whitespace)
511        {
512            // stop allowing frontmatters after first non-whitespace token
513            self.frontmatter_allowed = FrontmatterAllowed::No;
514        }
515        let res = Token::new(token_kind, self.pos_within_token());
516        self.reset_pos_within_token();
517        res
518    }
519
520    /// Given that one `-` was eaten, eat the rest of the frontmatter.
521    fn frontmatter(&mut self, has_invalid_preceding_whitespace: bool) -> TokenKind {
522        debug_assert_eq!('-', self.prev());
523
524        let pos = self.pos_within_token();
525        self.eat_while(|c| c == '-');
526
527        // one `-` is eaten by the caller.
528        let length_opening = self.pos_within_token() - pos + 1;
529
530        // must be ensured by the caller
531        debug_assert!(length_opening >= 3);
532
533        // whitespace between the opening and the infostring.
534        self.eat_while(|ch| ch != '\n' && is_whitespace(ch));
535
536        // copied from `eat_identifier`, but allows `.` in infostring to allow something like
537        // `---Cargo.toml` as a valid opener
538        if is_id_start(self.first()) {
539            self.bump();
540            self.eat_while(|c| is_id_continue(c) || c == '.');
541        }
542
543        self.eat_while(|ch| ch != '\n' && is_whitespace(ch));
544        let invalid_infostring = self.first() != '\n';
545
546        let mut s = self.as_str();
547        let mut found = false;
548        while let Some(closing) = s.find(&"-".repeat(length_opening as usize)) {
549            let preceding_chars_start = s[..closing].rfind("\n").map_or(0, |i| i + 1);
550            if s[preceding_chars_start..closing].chars().all(is_whitespace) {
551                // candidate found
552                self.bump_bytes(closing);
553                // in case like
554                // ---cargo
555                // --- blahblah
556                // or
557                // ---cargo
558                // ----
559                // combine those stuff into this frontmatter token such that it gets detected later.
560                self.eat_until(b'\n');
561                found = true;
562                break;
563            } else {
564                s = &s[closing + length_opening as usize..];
565            }
566        }
567
568        if !found {
569            // recovery strategy: a closing statement might have precending 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}