Skip to main content

parsec_js/
token.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Tokens: a kind, a few flags and a span. Nothing in one points into the
5//! heap; what a token says is in the source, at its span.
6
7use parsec_base::Span;
8
9/// One token: what it is, what the lexer noticed about it, and where it
10/// is. 12 bytes, with no allocation behind it.
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12pub struct Token {
13    pub kind: Kind,
14    pub flags: Flags,
15    pub span: Span,
16}
17
18impl Token {
19    /// The token's text in `src`, the source it came from.
20    pub fn text(self, src: &str) -> &str {
21        self.span.text(src)
22    }
23
24    /// Whether a line terminator, or a comment holding one, came between
25    /// this token and the last one that wasn't a comment. Automatic
26    /// semicolon insertion and restricted productions like `return`
27    /// ⟨newline⟩ turn on it.
28    pub fn newline_before(self) -> bool {
29        self.flags.contains(Flags::NEWLINE_BEFORE)
30    }
31
32    pub fn is_trivia(self) -> bool {
33        self.kind.is_trivia()
34    }
35}
36
37/// What the lexer noticed about a token that its kind doesn't say.
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
39pub struct Flags(u8);
40
41impl Flags {
42    /// A line terminator came before the token; see [`Token::newline_before`].
43    pub const NEWLINE_BEFORE: Flags = Flags(1);
44    /// An identifier, string or template part with a backslash escape in
45    /// it, so its value isn't its text. An escaped identifier is never a
46    /// [`Kind::Keyword`]: `\u0076ar` is [`Kind::Ident`] with this flag,
47    /// which the parser has to reject where `var` would be reserved.
48    pub const ESCAPED: Flags = Flags(2);
49    /// A legacy octal literal (`017`), a decimal literal with a leading
50    /// zero (`08`), or a string with a legacy octal escape (`"\01"`,
51    /// `"\8"`): allowed in sloppy scripts, a syntax error in strict code.
52    /// The lexer can't tell whether a script is strict, so it flags these
53    /// and leaves the error to the parser; in a module, which is always
54    /// strict, it reports them itself.
55    pub const LEGACY_OCTAL: Flags = Flags(4);
56    /// A template part with an escape that isn't one (`` `\01` ``,
57    /// `` `\xg` ``). A tagged template allows it, and its cooked value is
58    /// `undefined`; anywhere else it's a syntax error, which the parser
59    /// reports, since only it knows whether the template is tagged.
60    pub const INVALID_ESCAPE: Flags = Flags(8);
61
62    pub const fn empty() -> Flags {
63        Flags(0)
64    }
65
66    pub const fn contains(self, other: Flags) -> bool {
67        self.0 & other.0 == other.0
68    }
69
70    pub const fn union(self, other: Flags) -> Flags {
71        Flags(self.0 | other.0)
72    }
73
74    pub fn insert(&mut self, other: Flags) {
75        self.0 |= other.0;
76    }
77}
78
79/// What kind of token it is.
80#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
81pub enum Kind {
82    /// The end of the input; the lexer gives it again on every call after.
83    Eof,
84    /// `#!` at the very start of the input, to the end of the line.
85    Hashbang,
86    /// `// ...`, to the end of the line.
87    LineComment,
88    /// `/* ... */`.
89    BlockComment,
90    /// Annex B's `<!--`, to the end of the line, in scripts only.
91    HtmlOpenComment,
92    /// Annex B's `-->` at the start of a line, to its end, in scripts only.
93    HtmlCloseComment,
94    /// An IdentifierName that isn't a keyword spelled plainly.
95    Ident,
96    /// An IdentifierName spelled as one of these words, with no escapes.
97    Keyword(Keyword),
98    /// `#name`, a private name.
99    PrivateName,
100    /// A NumericLiteral that isn't a BigInt.
101    Number,
102    /// A NumericLiteral ending in `n`.
103    BigInt,
104    /// A StringLiteral, quotes included.
105    String,
106    /// A NoSubstitutionTemplate: `` `...` ``.
107    Template,
108    /// A TemplateHead: `` `...${ ``.
109    TemplateHead,
110    /// A TemplateMiddle: `}...${`.
111    TemplateMiddle,
112    /// A TemplateTail: `` }...` ``.
113    TemplateTail,
114    /// A RegularExpressionLiteral, `/body/flags`. The lexer checks the
115    /// flags; the body is checked against the pattern grammar later.
116    RegExp,
117    Punct(Punct),
118    /// A character that starts no token, or a `\` that starts no escape.
119    /// The lexer has reported it.
120    Invalid,
121}
122
123impl Kind {
124    /// Comments and the hashbang: the tokens a parser skips.
125    pub const fn is_trivia(self) -> bool {
126        matches!(
127            self,
128            Kind::Hashbang
129                | Kind::LineComment
130                | Kind::BlockComment
131                | Kind::HtmlOpenComment
132                | Kind::HtmlCloseComment
133        )
134    }
135}
136
137macro_rules! words {
138    ($(#[$m:meta])* $name:ident { $($variant:ident = $text:literal,)* }) => {
139        $(#[$m])*
140        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
141        pub enum $name {
142            $($variant,)*
143        }
144
145        impl $name {
146            /// Every one, in order.
147            #[allow(dead_code)] // Only Keyword's is used, to build its hash table.
148            pub(crate) const ALL: &'static [$name] = &[$($name::$variant,)*];
149
150            /// Its spelling.
151            pub const fn as_str(self) -> &'static str {
152                match self {
153                    $($name::$variant => $text,)*
154                }
155            }
156
157            /// The one spelled `text`, if there is one.
158            #[allow(clippy::should_implement_trait)]
159            pub fn from_str(text: &str) -> Option<$name> {
160                Some(match text {
161                    $($text => $name::$variant,)*
162                    _ => return None,
163                })
164            }
165        }
166    };
167}
168
169words! {
170    /// The words a parser treats specially: every ReservedWord, the ones
171    /// strict code reserves, and the contextual ones (`async`, `of`,
172    /// `get` and the rest), which are identifiers wherever they aren't
173    /// keywords. Which a word is, where, is the parser's to decide;
174    /// [`Keyword::is_reserved`] says which are ReservedWords.
175    Keyword {
176        Await = "await",
177        Break = "break",
178        Case = "case",
179        Catch = "catch",
180        Class = "class",
181        Const = "const",
182        Continue = "continue",
183        Debugger = "debugger",
184        Default = "default",
185        Delete = "delete",
186        Do = "do",
187        Else = "else",
188        Enum = "enum",
189        Export = "export",
190        Extends = "extends",
191        False = "false",
192        Finally = "finally",
193        For = "for",
194        Function = "function",
195        If = "if",
196        Import = "import",
197        In = "in",
198        Instanceof = "instanceof",
199        New = "new",
200        Null = "null",
201        Return = "return",
202        Super = "super",
203        Switch = "switch",
204        This = "this",
205        Throw = "throw",
206        True = "true",
207        Try = "try",
208        Typeof = "typeof",
209        Var = "var",
210        Void = "void",
211        While = "while",
212        With = "with",
213        Yield = "yield",
214        // Reserved in strict code.
215        Let = "let",
216        Static = "static",
217        Implements = "implements",
218        Interface = "interface",
219        Package = "package",
220        Private = "private",
221        Protected = "protected",
222        Public = "public",
223        // Contextual.
224        As = "as",
225        Async = "async",
226        From = "from",
227        Get = "get",
228        Meta = "meta",
229        Of = "of",
230        Set = "set",
231        Target = "target",
232    }
233}
234
235impl Keyword {
236    /// Whether it's one of the spec's ReservedWords. `await` and `yield`
237    /// are among them, though each is an identifier in some places.
238    pub const fn is_reserved(self) -> bool {
239        (self as u8) <= (Keyword::Yield as u8)
240    }
241
242    /// The keyword spelled `b`, found with one table lookup and one
243    /// comparison: the lexer asks this of every identifier it reads.
244    pub(crate) fn from_bytes(b: &[u8]) -> Option<Keyword> {
245        if !(2..=10).contains(&b.len()) {
246            return None;
247        }
248        let k = KEYWORDS[keyword_hash(b)]?;
249        (k.as_str().as_bytes() == b).then_some(k)
250    }
251
252    /// [`Keyword::from_bytes`] of the first `len` bytes of `rest`, with
253    /// no call, which would have the lexer save registers for it: given
254    /// 16 bytes, the word is compared to the spelling as one masked
255    /// `u128`, and a byte at a time in the last 16 of the input.
256    #[inline(always)]
257    pub(crate) fn from_prefix(rest: &[u8], len: usize) -> Option<Keyword> {
258        let word = rest.get(..len)?;
259        if !(2..=10).contains(&len) {
260            return None;
261        }
262        let h = keyword_hash(word);
263        let k = KEYWORDS[h]?;
264        let same = match rest.first_chunk::<16>() {
265            // The bytes past the word are masked off: a word shorter than
266            // the keyword has zeros where it has letters, and a longer one
267            // letters where it has zeros.
268            Some(chunk) => {
269                u128::from_le_bytes(*chunk) & (u128::MAX >> (128 - 8 * len)) == SPELLINGS[h]
270            }
271            None => {
272                let text = k.as_bytes();
273                text.len() == len && text.iter().zip(word).all(|(x, y)| x == y)
274            }
275        };
276        same.then_some(k)
277    }
278
279    /// Its spelling, from a table rather than a call.
280    fn as_bytes(self) -> &'static [u8] {
281        TEXT[self as usize]
282    }
283
284    /// Whether strict code reserves it beyond the ReservedWords.
285    pub const fn is_strict_reserved(self) -> bool {
286        (self as u8) > (Keyword::Yield as u8) && (self as u8) <= (Keyword::Public as u8)
287    }
288}
289
290/// A hash of a word of two bytes or more that no two keywords share,
291/// which building [`KEYWORDS`] checks.
292const fn keyword_hash(b: &[u8]) -> usize {
293    (b[0] as usize + b[1] as usize * 6 + b[b.len() - 1] as usize * 21 + b.len()) & 255
294}
295
296/// Each keyword at its hash.
297static KEYWORDS: [Option<Keyword>; 256] = {
298    let mut table = [None; 256];
299    let mut i = 0;
300    while i < Keyword::ALL.len() {
301        let k = Keyword::ALL[i];
302        let h = keyword_hash(k.as_str().as_bytes());
303        assert!(table[h].is_none(), "two keywords share a hash");
304        table[h] = Some(k);
305        i += 1;
306    }
307    table
308};
309
310/// Each keyword's spelling, by its number.
311static TEXT: [&[u8]; Keyword::ALL.len()] = {
312    let mut table: [&[u8]; Keyword::ALL.len()] = [&[]; Keyword::ALL.len()];
313    let mut i = 0;
314    while i < Keyword::ALL.len() {
315        table[i] = Keyword::ALL[i].as_str().as_bytes();
316        i += 1;
317    }
318    table
319};
320
321/// The spelling of the keyword at each hash in [`KEYWORDS`], as the
322/// little-endian `u128` of its bytes.
323static SPELLINGS: [u128; 256] = {
324    let mut table = [0; 256];
325    let mut i = 0;
326    while i < 256 {
327        if let Some(k) = KEYWORDS[i] {
328            let b = k.as_str().as_bytes();
329            let mut j = 0;
330            while j < b.len() {
331                table[i] |= (b[j] as u128) << (8 * j);
332                j += 1;
333            }
334        }
335        i += 1;
336    }
337    table
338};
339
340words! {
341    /// A Punctuator, DivPunctuator or RightBracePunctuator.
342    Punct {
343        LBrace = "{",
344        RBrace = "}",
345        LParen = "(",
346        RParen = ")",
347        LBracket = "[",
348        RBracket = "]",
349        Dot = ".",
350        Ellipsis = "...",
351        Semicolon = ";",
352        Comma = ",",
353        Lt = "<",
354        Gt = ">",
355        LtEq = "<=",
356        GtEq = ">=",
357        EqEq = "==",
358        NotEq = "!=",
359        EqEqEq = "===",
360        NotEqEq = "!==",
361        Plus = "+",
362        Minus = "-",
363        Star = "*",
364        Slash = "/",
365        Percent = "%",
366        StarStar = "**",
367        PlusPlus = "++",
368        MinusMinus = "--",
369        Shl = "<<",
370        Shr = ">>",
371        UShr = ">>>",
372        Amp = "&",
373        Pipe = "|",
374        Caret = "^",
375        Bang = "!",
376        Tilde = "~",
377        AmpAmp = "&&",
378        PipePipe = "||",
379        QuestionQuestion = "??",
380        Question = "?",
381        QuestionDot = "?.",
382        Colon = ":",
383        Eq = "=",
384        PlusEq = "+=",
385        MinusEq = "-=",
386        StarEq = "*=",
387        SlashEq = "/=",
388        PercentEq = "%=",
389        StarStarEq = "**=",
390        ShlEq = "<<=",
391        ShrEq = ">>=",
392        UShrEq = ">>>=",
393        AmpEq = "&=",
394        PipeEq = "|=",
395        CaretEq = "^=",
396        AmpAmpEq = "&&=",
397        PipePipeEq = "||=",
398        QuestionQuestionEq = "??=",
399        Arrow = "=>",
400    }
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406
407    #[test]
408    fn keywords_by_hash() {
409        for &k in Keyword::ALL {
410            assert_eq!(Keyword::from_bytes(k.as_str().as_bytes()), Some(k));
411            assert_eq!(k.as_bytes(), k.as_str().as_bytes());
412            // With 16 bytes to read and without, before what can follow.
413            for after in ["", " ", "(", "x", "                "] {
414                for pad in ["", "                "] {
415                    let s = format!("{}{after}{pad}", k.as_str());
416                    let len = k.as_str().len();
417                    assert_eq!(Keyword::from_prefix(s.as_bytes(), len), Some(k), "{s:?}");
418                }
419            }
420        }
421        for word in [
422            "",
423            "a",
424            "x",
425            "lets",
426            "yiel",
427            "constructor",
428            "Await",
429            "awaiT",
430            "of_",
431            "ofs",
432        ] {
433            assert_eq!(
434                Keyword::from_bytes(word.as_bytes()),
435                Keyword::from_str(word),
436                "{word}"
437            );
438            for pad in ["", " ", "                "] {
439                let s = format!("{word}{pad}");
440                assert_eq!(
441                    Keyword::from_prefix(s.as_bytes(), word.len()),
442                    Keyword::from_str(word),
443                    "{s:?}"
444                );
445            }
446        }
447    }
448}