parsec-js 0.3.0

JavaScript for Parsec: a parser for ECMAScript 2025 scripts and modules to a syntax tree with a span on every node, ESTree JSON out, and the lexer under it.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 James Conway

//! Tokens: a kind, a few flags and a span. Nothing in one points into the
//! heap; what a token says is in the source, at its span.

use parsec_base::Span;

/// One token: what it is, what the lexer noticed about it, and where it
/// is. 12 bytes, with no allocation behind it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Token {
    pub kind: Kind,
    pub flags: Flags,
    pub span: Span,
}

impl Token {
    /// The token's text in `src`, the source it came from.
    pub fn text(self, src: &str) -> &str {
        self.span.text(src)
    }

    /// Whether a line terminator, or a comment holding one, came between
    /// this token and the last one that wasn't a comment. Automatic
    /// semicolon insertion and restricted productions like `return`
    /// ⟨newline⟩ turn on it.
    pub fn newline_before(self) -> bool {
        self.flags.contains(Flags::NEWLINE_BEFORE)
    }

    pub fn is_trivia(self) -> bool {
        self.kind.is_trivia()
    }
}

/// What the lexer noticed about a token that its kind doesn't say.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Flags(u8);

impl Flags {
    /// A line terminator came before the token; see [`Token::newline_before`].
    pub const NEWLINE_BEFORE: Flags = Flags(1);
    /// An identifier, string or template part with a backslash escape in
    /// it, so its value isn't its text. An escaped identifier is never a
    /// [`Kind::Keyword`]: `\u0076ar` is [`Kind::Ident`] with this flag,
    /// which the parser has to reject where `var` would be reserved.
    pub const ESCAPED: Flags = Flags(2);
    /// A legacy octal literal (`017`), a decimal literal with a leading
    /// zero (`08`), or a string with a legacy octal escape (`"\01"`,
    /// `"\8"`): allowed in sloppy scripts, a syntax error in strict code.
    /// The lexer can't tell whether a script is strict, so it flags these
    /// and leaves the error to the parser; in a module, which is always
    /// strict, it reports them itself.
    pub const LEGACY_OCTAL: Flags = Flags(4);
    /// A template part with an escape that isn't one (`` `\01` ``,
    /// `` `\xg` ``). A tagged template allows it, and its cooked value is
    /// `undefined`; anywhere else it's a syntax error, which the parser
    /// reports, since only it knows whether the template is tagged.
    pub const INVALID_ESCAPE: Flags = Flags(8);

    pub const fn empty() -> Flags {
        Flags(0)
    }

    pub const fn contains(self, other: Flags) -> bool {
        self.0 & other.0 == other.0
    }

    pub const fn union(self, other: Flags) -> Flags {
        Flags(self.0 | other.0)
    }

    pub fn insert(&mut self, other: Flags) {
        self.0 |= other.0;
    }
}

/// What kind of token it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Kind {
    /// The end of the input; the lexer gives it again on every call after.
    Eof,
    /// `#!` at the very start of the input, to the end of the line.
    Hashbang,
    /// `// ...`, to the end of the line.
    LineComment,
    /// `/* ... */`.
    BlockComment,
    /// Annex B's `<!--`, to the end of the line, in scripts only.
    HtmlOpenComment,
    /// Annex B's `-->` at the start of a line, to its end, in scripts only.
    HtmlCloseComment,
    /// An IdentifierName that isn't a keyword spelled plainly.
    Ident,
    /// An IdentifierName spelled as one of these words, with no escapes.
    Keyword(Keyword),
    /// `#name`, a private name.
    PrivateName,
    /// A NumericLiteral that isn't a BigInt.
    Number,
    /// A NumericLiteral ending in `n`.
    BigInt,
    /// A StringLiteral, quotes included.
    String,
    /// A NoSubstitutionTemplate: `` `...` ``.
    Template,
    /// A TemplateHead: `` `...${ ``.
    TemplateHead,
    /// A TemplateMiddle: `}...${`.
    TemplateMiddle,
    /// A TemplateTail: `` }...` ``.
    TemplateTail,
    /// A RegularExpressionLiteral, `/body/flags`. The lexer checks the
    /// flags; the body is checked against the pattern grammar later.
    RegExp,
    Punct(Punct),
    /// A character that starts no token, or a `\` that starts no escape.
    /// The lexer has reported it.
    Invalid,
}

impl Kind {
    /// Comments and the hashbang: the tokens a parser skips.
    pub const fn is_trivia(self) -> bool {
        matches!(
            self,
            Kind::Hashbang
                | Kind::LineComment
                | Kind::BlockComment
                | Kind::HtmlOpenComment
                | Kind::HtmlCloseComment
        )
    }
}

macro_rules! words {
    ($(#[$m:meta])* $name:ident { $($variant:ident = $text:literal,)* }) => {
        $(#[$m])*
        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
        pub enum $name {
            $($variant,)*
        }

        impl $name {
            /// Every one, in order.
            #[allow(dead_code)] // Only Keyword's is used, to build its hash table.
            pub(crate) const ALL: &'static [$name] = &[$($name::$variant,)*];

            /// Its spelling.
            pub const fn as_str(self) -> &'static str {
                match self {
                    $($name::$variant => $text,)*
                }
            }

            /// The one spelled `text`, if there is one.
            #[allow(clippy::should_implement_trait)]
            pub fn from_str(text: &str) -> Option<$name> {
                Some(match text {
                    $($text => $name::$variant,)*
                    _ => return None,
                })
            }
        }
    };
}

words! {
    /// The words a parser treats specially: every ReservedWord, the ones
    /// strict code reserves, and the contextual ones (`async`, `of`,
    /// `get` and the rest), which are identifiers wherever they aren't
    /// keywords. Which a word is, where, is the parser's to decide;
    /// [`Keyword::is_reserved`] says which are ReservedWords.
    Keyword {
        Await = "await",
        Break = "break",
        Case = "case",
        Catch = "catch",
        Class = "class",
        Const = "const",
        Continue = "continue",
        Debugger = "debugger",
        Default = "default",
        Delete = "delete",
        Do = "do",
        Else = "else",
        Enum = "enum",
        Export = "export",
        Extends = "extends",
        False = "false",
        Finally = "finally",
        For = "for",
        Function = "function",
        If = "if",
        Import = "import",
        In = "in",
        Instanceof = "instanceof",
        New = "new",
        Null = "null",
        Return = "return",
        Super = "super",
        Switch = "switch",
        This = "this",
        Throw = "throw",
        True = "true",
        Try = "try",
        Typeof = "typeof",
        Var = "var",
        Void = "void",
        While = "while",
        With = "with",
        Yield = "yield",
        // Reserved in strict code.
        Let = "let",
        Static = "static",
        Implements = "implements",
        Interface = "interface",
        Package = "package",
        Private = "private",
        Protected = "protected",
        Public = "public",
        // Contextual.
        As = "as",
        Async = "async",
        From = "from",
        Get = "get",
        Meta = "meta",
        Of = "of",
        Set = "set",
        Target = "target",
    }
}

impl Keyword {
    /// Whether it's one of the spec's ReservedWords. `await` and `yield`
    /// are among them, though each is an identifier in some places.
    pub const fn is_reserved(self) -> bool {
        (self as u8) <= (Keyword::Yield as u8)
    }

    /// The keyword spelled `b`, found with one table lookup and one
    /// comparison: the lexer asks this of every identifier it reads.
    pub(crate) fn from_bytes(b: &[u8]) -> Option<Keyword> {
        if !(2..=10).contains(&b.len()) {
            return None;
        }
        let k = KEYWORDS[keyword_hash(b)]?;
        (k.as_str().as_bytes() == b).then_some(k)
    }

    /// [`Keyword::from_bytes`] of the first `len` bytes of `rest`, with
    /// no call, which would have the lexer save registers for it: given
    /// 16 bytes, the word is compared to the spelling as one masked
    /// `u128`, and a byte at a time in the last 16 of the input.
    #[inline(always)]
    pub(crate) fn from_prefix(rest: &[u8], len: usize) -> Option<Keyword> {
        let word = rest.get(..len)?;
        if !(2..=10).contains(&len) {
            return None;
        }
        let h = keyword_hash(word);
        let k = KEYWORDS[h]?;
        let same = match rest.first_chunk::<16>() {
            // The bytes past the word are masked off: a word shorter than
            // the keyword has zeros where it has letters, and a longer one
            // letters where it has zeros.
            Some(chunk) => {
                u128::from_le_bytes(*chunk) & (u128::MAX >> (128 - 8 * len)) == SPELLINGS[h]
            }
            None => {
                let text = k.as_bytes();
                text.len() == len && text.iter().zip(word).all(|(x, y)| x == y)
            }
        };
        same.then_some(k)
    }

    /// Its spelling, from a table rather than a call.
    fn as_bytes(self) -> &'static [u8] {
        TEXT[self as usize]
    }

    /// Whether strict code reserves it beyond the ReservedWords.
    pub const fn is_strict_reserved(self) -> bool {
        (self as u8) > (Keyword::Yield as u8) && (self as u8) <= (Keyword::Public as u8)
    }
}

/// A hash of a word of two bytes or more that no two keywords share,
/// which building [`KEYWORDS`] checks.
const fn keyword_hash(b: &[u8]) -> usize {
    (b[0] as usize + b[1] as usize * 6 + b[b.len() - 1] as usize * 21 + b.len()) & 255
}

/// Each keyword at its hash.
static KEYWORDS: [Option<Keyword>; 256] = {
    let mut table = [None; 256];
    let mut i = 0;
    while i < Keyword::ALL.len() {
        let k = Keyword::ALL[i];
        let h = keyword_hash(k.as_str().as_bytes());
        assert!(table[h].is_none(), "two keywords share a hash");
        table[h] = Some(k);
        i += 1;
    }
    table
};

/// Each keyword's spelling, by its number.
static TEXT: [&[u8]; Keyword::ALL.len()] = {
    let mut table: [&[u8]; Keyword::ALL.len()] = [&[]; Keyword::ALL.len()];
    let mut i = 0;
    while i < Keyword::ALL.len() {
        table[i] = Keyword::ALL[i].as_str().as_bytes();
        i += 1;
    }
    table
};

/// The spelling of the keyword at each hash in [`KEYWORDS`], as the
/// little-endian `u128` of its bytes.
static SPELLINGS: [u128; 256] = {
    let mut table = [0; 256];
    let mut i = 0;
    while i < 256 {
        if let Some(k) = KEYWORDS[i] {
            let b = k.as_str().as_bytes();
            let mut j = 0;
            while j < b.len() {
                table[i] |= (b[j] as u128) << (8 * j);
                j += 1;
            }
        }
        i += 1;
    }
    table
};

words! {
    /// A Punctuator, DivPunctuator or RightBracePunctuator.
    Punct {
        LBrace = "{",
        RBrace = "}",
        LParen = "(",
        RParen = ")",
        LBracket = "[",
        RBracket = "]",
        Dot = ".",
        Ellipsis = "...",
        Semicolon = ";",
        Comma = ",",
        Lt = "<",
        Gt = ">",
        LtEq = "<=",
        GtEq = ">=",
        EqEq = "==",
        NotEq = "!=",
        EqEqEq = "===",
        NotEqEq = "!==",
        Plus = "+",
        Minus = "-",
        Star = "*",
        Slash = "/",
        Percent = "%",
        StarStar = "**",
        PlusPlus = "++",
        MinusMinus = "--",
        Shl = "<<",
        Shr = ">>",
        UShr = ">>>",
        Amp = "&",
        Pipe = "|",
        Caret = "^",
        Bang = "!",
        Tilde = "~",
        AmpAmp = "&&",
        PipePipe = "||",
        QuestionQuestion = "??",
        Question = "?",
        QuestionDot = "?.",
        Colon = ":",
        Eq = "=",
        PlusEq = "+=",
        MinusEq = "-=",
        StarEq = "*=",
        SlashEq = "/=",
        PercentEq = "%=",
        StarStarEq = "**=",
        ShlEq = "<<=",
        ShrEq = ">>=",
        UShrEq = ">>>=",
        AmpEq = "&=",
        PipeEq = "|=",
        CaretEq = "^=",
        AmpAmpEq = "&&=",
        PipePipeEq = "||=",
        QuestionQuestionEq = "??=",
        Arrow = "=>",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn keywords_by_hash() {
        for &k in Keyword::ALL {
            assert_eq!(Keyword::from_bytes(k.as_str().as_bytes()), Some(k));
            assert_eq!(k.as_bytes(), k.as_str().as_bytes());
            // With 16 bytes to read and without, before what can follow.
            for after in ["", " ", "(", "x", "                "] {
                for pad in ["", "                "] {
                    let s = format!("{}{after}{pad}", k.as_str());
                    let len = k.as_str().len();
                    assert_eq!(Keyword::from_prefix(s.as_bytes(), len), Some(k), "{s:?}");
                }
            }
        }
        for word in [
            "",
            "a",
            "x",
            "lets",
            "yiel",
            "constructor",
            "Await",
            "awaiT",
            "of_",
            "ofs",
        ] {
            assert_eq!(
                Keyword::from_bytes(word.as_bytes()),
                Keyword::from_str(word),
                "{word}"
            );
            for pad in ["", " ", "                "] {
                let s = format!("{word}{pad}");
                assert_eq!(
                    Keyword::from_prefix(s.as_bytes(), word.len()),
                    Keyword::from_str(word),
                    "{s:?}"
                );
            }
        }
    }
}