quickjs-parse 0.8.0

ECMAScript 2025 lexer, AST and parser for the pure-Rust QuickJS port
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Token definitions for ECMAScript 2025.
//!
//! The lexer keeps the token stream small and borrowed-free: identifiers and
//! strings own their decoded value, numeric literals keep enough information for
//! `js-value` to build a `Number`/`BigInt`, and template literals carry both the
//! cooked (escape-expanded) and raw source text, because tagged templates need
//! the raw form and `undefined`-cooked chunks when an escape is invalid.

use std::fmt;

/// Byte offset, line (1-based) and column (1-based) of a source position.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Position {
    /// Byte offset from the start of the source.
    pub offset: u32,
    /// 1-based line number.
    pub line: u32,
    /// 1-based column, counted in UTF-16 code units like a JS engine's
    /// `SyntaxError` positions.
    pub column: u32,
}

impl Position {
    /// A position at the very start of a source.
    pub const START: Position = Position {
        offset: 0,
        line: 1,
        column: 1,
    };
}

/// Half-open source range.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Span {
    /// First covered position.
    pub start: Position,
    /// One past the last covered position.
    pub end: Position,
}

impl Span {
    /// A zero-width span at the very start of a source.
    pub const fn start() -> Span {
        Span {
            start: Position::START,
            end: Position::START,
        }
    }

    /// Create a span from two positions.
    pub fn new(start: Position, end: Position) -> Span {
        Span { start, end }
    }
}

/// A reserved word that is a keyword in every context (ES2025 §12.7.2), plus
/// `enum` (always reserved).
///
/// Context-sensitive words (`let`, `static`, `yield`, `await`, `async`, `of`,
/// `get`, `set`, `from`, `as`, `target`, …) are *not* keywords here: they are
/// identifiers whose meaning the parser decides, exactly like an engine does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Keyword {
    /// `break`
    Break,
    /// `case`
    Case,
    /// `catch`
    Catch,
    /// `class`
    Class,
    /// `const`
    Const,
    /// `continue`
    Continue,
    /// `debugger`
    Debugger,
    /// `default`
    Default,
    /// `delete`
    Delete,
    /// `do`
    Do,
    /// `else`
    Else,
    /// `enum` (reserved in all modes)
    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,
}

impl Keyword {
    /// Look up a reserved word.
    pub fn lookup(s: &str) -> Option<Keyword> {
        use Keyword::*;
        Some(match s {
            "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,
            _ => return None,
        })
    }

    /// The source text of the keyword.
    pub fn as_str(self) -> &'static str {
        use Keyword::*;
        match self {
            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",
        }
    }

    /// Whether the word is a *future reserved word in strict mode* only
    /// (ES2025 §12.7.2): legal as an identifier in sloppy code.
    pub fn is_strict_reserved(word: &str) -> bool {
        matches!(
            word,
            "implements"
                | "interface"
                | "let"
                | "package"
                | "private"
                | "protected"
                | "public"
                | "static"
                | "yield"
        )
    }
}

impl fmt::Display for Keyword {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Every punctuator in ECMAScript 2025, longest-first where it matters.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
pub enum Punct {
    LBrace,
    RBrace,
    LParen,
    RParen,
    LBracket,
    RBracket,
    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,
    Colon,
    Eq,
    PlusEq,
    MinusEq,
    StarEq,
    SlashEq,
    PercentEq,
    StarStarEq,
    ShlEq,
    ShrEq,
    UShrEq,
    AmpEq,
    PipeEq,
    CaretEq,
    AmpAmpEq,
    PipePipeEq,
    QuestionQuestionEq,
    Arrow,
    Ellipsis,
    Dot,
    QuestionDot,
    Hash,
}

impl Punct {
    /// The source text of the punctuator.
    pub fn as_str(self) -> &'static str {
        use Punct::*;
        match self {
            LBrace => "{",
            RBrace => "}",
            LParen => "(",
            RParen => ")",
            LBracket => "[",
            RBracket => "]",
            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 => "?",
            Colon => ":",
            Eq => "=",
            PlusEq => "+=",
            MinusEq => "-=",
            StarEq => "*=",
            SlashEq => "/=",
            PercentEq => "%=",
            StarStarEq => "**=",
            ShlEq => "<<=",
            ShrEq => ">>=",
            UShrEq => ">>>=",
            AmpEq => "&=",
            PipeEq => "|=",
            CaretEq => "^=",
            AmpAmpEq => "&&=",
            PipePipeEq => "||=",
            QuestionQuestionEq => "??=",
            Arrow => "=>",
            Ellipsis => "...",
            Dot => ".",
            QuestionDot => "?.",
            Hash => "#",
        }
    }

    /// Whether the punctuator ends a statement for Automatic Semicolon
    /// Insertion purposes (used by the parser; `}` is handled separately).
    pub fn is_asi_boundary(self) -> bool {
        matches!(self, Punct::Semicolon | Punct::RBrace)
    }
}

/// The value of a numeric literal.
#[derive(Debug, Clone, PartialEq)]
pub enum NumberLiteral {
    /// Integer that fits in `i32` (and in 53 bits of precision): kept exact.
    Int(i32),
    /// Any other double.
    Float(f64),
}

/// A BigInt literal: the source digits and their radix, kept raw so that
/// `js-value` can build the arbitrary-precision integer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BigIntLiteral {
    /// Digits without prefix, separators or the `n` suffix.
    pub digits: String,
    /// 2, 8, 10 or 16.
    pub radix: u32,
}

/// Which part of a template literal a token is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TemplateKind {
    /// `` `text` `` — no substitution.
    NoSubstitution,
    /// `` `text${ `` — the template continues after the substitution.
    Head,
    /// `}text${` — middle chunk.
    Middle,
    /// `` }text` `` — last chunk.
    Tail,
}

/// A template literal chunk.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateToken {
    /// Which chunk this is.
    pub kind: TemplateKind,
    /// Escape-expanded text, `None` for an invalid escape sequence (only legal
    /// in tagged templates, where `cooked` is `undefined`).
    pub cooked: Option<String>,
    /// Source text between the delimiters, verbatim.
    pub raw: String,
}

/// A lexical token.
#[derive(Debug, Clone, PartialEq)]
pub enum TokenKind {
    /// End of input.
    Eof,
    /// Identifier (including context-sensitive words like `let`/`await`).
    Ident(String),
    /// Reserved word.
    Keyword(Keyword),
    /// Numeric literal.
    Number(NumberLiteral),
    /// BigInt literal.
    BigInt(BigIntLiteral),
    /// String literal with escapes already decoded.
    String(String),
    /// Regular expression literal (needs a re-scan from `/`).
    RegExp {
        /// Pattern source, without the slashes.
        pattern: String,
        /// Flag letters, without validation (the compiler validates them).
        flags: String,
    },
    /// Template literal chunk.
    Template(TemplateToken),
    /// Punctuator.
    Punct(Punct),
}

impl TokenKind {
    /// A short human readable description, used in parser error messages.
    pub fn describe(&self) -> String {
        match self {
            TokenKind::Eof => "end of input".to_string(),
            TokenKind::Ident(name) => format!("identifier '{name}'"),
            TokenKind::Keyword(kw) => format!("'{kw}'"),
            TokenKind::Number(n) => match n {
                NumberLiteral::Int(v) => format!("number '{v}'"),
                NumberLiteral::Float(v) => format!("number '{v}'"),
            },
            TokenKind::BigInt(b) => format!("BigInt literal '{}n'", b.digits),
            TokenKind::String(_) => "string literal".to_string(),
            TokenKind::RegExp { .. } => "regular expression".to_string(),
            TokenKind::Template(_) => "template literal".to_string(),
            TokenKind::Punct(p) => format!("'{}'", p.as_str()),
        }
    }

    /// If this is a punctuator, return it.
    pub fn as_punct(&self) -> Option<Punct> {
        match self {
            TokenKind::Punct(p) => Some(*p),
            _ => None,
        }
    }

    /// If this is a keyword, return it.
    pub fn as_keyword(&self) -> Option<Keyword> {
        match self {
            TokenKind::Keyword(kw) => Some(*kw),
            _ => None,
        }
    }

    /// Whether the token starts an expression (used to decide `/` == division
    /// versus regex in error recovery paths).
    pub fn is_identifier(&self) -> bool {
        matches!(self, TokenKind::Ident(_))
    }
}

/// A token plus where it came from.
#[derive(Debug, Clone, PartialEq)]
pub struct Token {
    /// Token payload.
    pub kind: TokenKind,
    /// Source range of the token.
    pub span: Span,
    /// Whether a line terminator appeared between the previous token and this
    /// one (drives Automatic Semicolon Insertion and restricted productions).
    pub newline_before: bool,
    /// Whether the token's spelling used a `\u` escape.
    ///
    /// A contextual keyword written with one is only an identifier: `{\u0067et x() {}}` is
    /// not a getter. Reserved words are rejected by the lexer instead, so this only has to
    /// answer for the handful of words that mean something by position.
    pub escaped: bool,
}

impl Token {
    /// Whether this token ends a statement, for ASI.
    pub fn is_eof(&self) -> bool {
        matches!(self.kind, TokenKind::Eof)
    }
}