Skip to main content

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