Skip to main content

js_parse/
token.rs

1//! Token definitions for ECMAScript 2025.
2//!
3//! The lexer keeps the token stream small and borrowed-free: identifiers and
4//! strings own their decoded value, numeric literals keep enough information for
5//! `js-value` to build a `Number`/`BigInt`, and template literals carry both the
6//! cooked (escape-expanded) and raw source text, because tagged templates need
7//! the raw form and `undefined`-cooked chunks when an escape is invalid.
8
9use std::fmt;
10
11use crate::wtf8::Wtf8;
12
13/// Byte offset, line (1-based) and column (1-based) of a source position.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub struct Position {
16    /// Byte offset from the start of the source.
17    pub offset: u32,
18    /// 1-based line number.
19    pub line: u32,
20    /// 1-based column, counted in UTF-16 code units like a JS engine's
21    /// `SyntaxError` positions.
22    pub column: u32,
23}
24
25impl Position {
26    /// A position at the very start of a source.
27    pub const START: Position = Position {
28        offset: 0,
29        line: 1,
30        column: 1,
31    };
32}
33
34/// Half-open source range.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub struct Span {
37    /// First covered position.
38    pub start: Position,
39    /// One past the last covered position.
40    pub end: Position,
41}
42
43impl Span {
44    /// A zero-width span at the very start of a source.
45    pub const fn start() -> Span {
46        Span {
47            start: Position::START,
48            end: Position::START,
49        }
50    }
51
52    /// Create a span from two positions.
53    pub fn new(start: Position, end: Position) -> Span {
54        Span { start, end }
55    }
56}
57
58/// A reserved word that is a keyword in every context (ES2025 §12.7.2), plus
59/// `enum` (always reserved).
60///
61/// Context-sensitive words (`let`, `static`, `yield`, `await`, `async`, `of`,
62/// `get`, `set`, `from`, `as`, `target`, …) are *not* keywords here: they are
63/// identifiers whose meaning the parser decides, exactly like an engine does.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
65pub enum Keyword {
66    /// `break`
67    Break,
68    /// `case`
69    Case,
70    /// `catch`
71    Catch,
72    /// `class`
73    Class,
74    /// `const`
75    Const,
76    /// `continue`
77    Continue,
78    /// `debugger`
79    Debugger,
80    /// `default`
81    Default,
82    /// `delete`
83    Delete,
84    /// `do`
85    Do,
86    /// `else`
87    Else,
88    /// `enum` (reserved in all modes)
89    Enum,
90    /// `export`
91    Export,
92    /// `extends`
93    Extends,
94    /// `false`
95    False,
96    /// `finally`
97    Finally,
98    /// `for`
99    For,
100    /// `function`
101    Function,
102    /// `if`
103    If,
104    /// `import`
105    Import,
106    /// `in`
107    In,
108    /// `instanceof`
109    Instanceof,
110    /// `new`
111    New,
112    /// `null`
113    Null,
114    /// `return`
115    Return,
116    /// `super`
117    Super,
118    /// `switch`
119    Switch,
120    /// `this`
121    This,
122    /// `throw`
123    Throw,
124    /// `true`
125    True,
126    /// `try`
127    Try,
128    /// `typeof`
129    Typeof,
130    /// `var`
131    Var,
132    /// `void`
133    Void,
134    /// `while`
135    While,
136    /// `with`
137    With,
138}
139
140impl Keyword {
141    /// Look up a reserved word.
142    pub fn lookup(s: &str) -> Option<Keyword> {
143        use Keyword::*;
144        Some(match s {
145            "break" => Break,
146            "case" => Case,
147            "catch" => Catch,
148            "class" => Class,
149            "const" => Const,
150            "continue" => Continue,
151            "debugger" => Debugger,
152            "default" => Default,
153            "delete" => Delete,
154            "do" => Do,
155            "else" => Else,
156            "enum" => Enum,
157            "export" => Export,
158            "extends" => Extends,
159            "false" => False,
160            "finally" => Finally,
161            "for" => For,
162            "function" => Function,
163            "if" => If,
164            "import" => Import,
165            "in" => In,
166            "instanceof" => Instanceof,
167            "new" => New,
168            "null" => Null,
169            "return" => Return,
170            "super" => Super,
171            "switch" => Switch,
172            "this" => This,
173            "throw" => Throw,
174            "true" => True,
175            "try" => Try,
176            "typeof" => Typeof,
177            "var" => Var,
178            "void" => Void,
179            "while" => While,
180            "with" => With,
181            _ => return None,
182        })
183    }
184
185    /// The source text of the keyword.
186    pub fn as_str(self) -> &'static str {
187        use Keyword::*;
188        match self {
189            Break => "break",
190            Case => "case",
191            Catch => "catch",
192            Class => "class",
193            Const => "const",
194            Continue => "continue",
195            Debugger => "debugger",
196            Default => "default",
197            Delete => "delete",
198            Do => "do",
199            Else => "else",
200            Enum => "enum",
201            Export => "export",
202            Extends => "extends",
203            False => "false",
204            Finally => "finally",
205            For => "for",
206            Function => "function",
207            If => "if",
208            Import => "import",
209            In => "in",
210            Instanceof => "instanceof",
211            New => "new",
212            Null => "null",
213            Return => "return",
214            Super => "super",
215            Switch => "switch",
216            This => "this",
217            Throw => "throw",
218            True => "true",
219            Try => "try",
220            Typeof => "typeof",
221            Var => "var",
222            Void => "void",
223            While => "while",
224            With => "with",
225        }
226    }
227
228    /// Whether the word is a *future reserved word in strict mode* only
229    /// (ES2025 §12.7.2): legal as an identifier in sloppy code.
230    pub fn is_strict_reserved(word: &str) -> bool {
231        matches!(
232            word,
233            "implements"
234                | "interface"
235                | "let"
236                | "package"
237                | "private"
238                | "protected"
239                | "public"
240                | "static"
241                | "yield"
242        )
243    }
244}
245
246impl fmt::Display for Keyword {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        f.write_str(self.as_str())
249    }
250}
251
252/// Every punctuator in ECMAScript 2025, longest-first where it matters.
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
254#[allow(missing_docs)]
255pub enum Punct {
256    LBrace,
257    RBrace,
258    LParen,
259    RParen,
260    LBracket,
261    RBracket,
262    Semicolon,
263    Comma,
264    Lt,
265    Gt,
266    LtEq,
267    GtEq,
268    EqEq,
269    NotEq,
270    EqEqEq,
271    NotEqEq,
272    Plus,
273    Minus,
274    Star,
275    Slash,
276    Percent,
277    StarStar,
278    PlusPlus,
279    MinusMinus,
280    Shl,
281    Shr,
282    UShr,
283    Amp,
284    Pipe,
285    Caret,
286    Bang,
287    Tilde,
288    AmpAmp,
289    PipePipe,
290    QuestionQuestion,
291    Question,
292    Colon,
293    Eq,
294    PlusEq,
295    MinusEq,
296    StarEq,
297    SlashEq,
298    PercentEq,
299    StarStarEq,
300    ShlEq,
301    ShrEq,
302    UShrEq,
303    AmpEq,
304    PipeEq,
305    CaretEq,
306    AmpAmpEq,
307    PipePipeEq,
308    QuestionQuestionEq,
309    Arrow,
310    Ellipsis,
311    Dot,
312    QuestionDot,
313    Hash,
314}
315
316impl Punct {
317    /// The source text of the punctuator.
318    pub fn as_str(self) -> &'static str {
319        use Punct::*;
320        match self {
321            LBrace => "{",
322            RBrace => "}",
323            LParen => "(",
324            RParen => ")",
325            LBracket => "[",
326            RBracket => "]",
327            Semicolon => ";",
328            Comma => ",",
329            Lt => "<",
330            Gt => ">",
331            LtEq => "<=",
332            GtEq => ">=",
333            EqEq => "==",
334            NotEq => "!=",
335            EqEqEq => "===",
336            NotEqEq => "!==",
337            Plus => "+",
338            Minus => "-",
339            Star => "*",
340            Slash => "/",
341            Percent => "%",
342            StarStar => "**",
343            PlusPlus => "++",
344            MinusMinus => "--",
345            Shl => "<<",
346            Shr => ">>",
347            UShr => ">>>",
348            Amp => "&",
349            Pipe => "|",
350            Caret => "^",
351            Bang => "!",
352            Tilde => "~",
353            AmpAmp => "&&",
354            PipePipe => "||",
355            QuestionQuestion => "??",
356            Question => "?",
357            Colon => ":",
358            Eq => "=",
359            PlusEq => "+=",
360            MinusEq => "-=",
361            StarEq => "*=",
362            SlashEq => "/=",
363            PercentEq => "%=",
364            StarStarEq => "**=",
365            ShlEq => "<<=",
366            ShrEq => ">>=",
367            UShrEq => ">>>=",
368            AmpEq => "&=",
369            PipeEq => "|=",
370            CaretEq => "^=",
371            AmpAmpEq => "&&=",
372            PipePipeEq => "||=",
373            QuestionQuestionEq => "??=",
374            Arrow => "=>",
375            Ellipsis => "...",
376            Dot => ".",
377            QuestionDot => "?.",
378            Hash => "#",
379        }
380    }
381
382    /// Whether the punctuator ends a statement for Automatic Semicolon
383    /// Insertion purposes (used by the parser; `}` is handled separately).
384    pub fn is_asi_boundary(self) -> bool {
385        matches!(self, Punct::Semicolon | Punct::RBrace)
386    }
387}
388
389/// The value of a numeric literal.
390#[derive(Debug, Clone, PartialEq)]
391pub enum NumberLiteral {
392    /// Integer that fits in `i32` (and in 53 bits of precision): kept exact.
393    Int(i32),
394    /// Any other double.
395    Float(f64),
396}
397
398/// A BigInt literal: the source digits and their radix, kept raw so that
399/// `js-value` can build the arbitrary-precision integer.
400#[derive(Debug, Clone, PartialEq, Eq)]
401pub struct BigIntLiteral {
402    /// Digits without prefix, separators or the `n` suffix.
403    pub digits: String,
404    /// 2, 8, 10 or 16.
405    pub radix: u32,
406}
407
408/// Which part of a template literal a token is.
409#[derive(Debug, Clone, Copy, PartialEq, Eq)]
410pub enum TemplateKind {
411    /// `` `text` `` — no substitution.
412    NoSubstitution,
413    /// `` `text${ `` — the template continues after the substitution.
414    Head,
415    /// `}text${` — middle chunk.
416    Middle,
417    /// `` }text` `` — last chunk.
418    Tail,
419}
420
421/// A template literal chunk.
422#[derive(Debug, Clone, PartialEq, Eq)]
423pub struct TemplateToken {
424    /// Which chunk this is.
425    pub kind: TemplateKind,
426    /// Escape-expanded text, `None` for an invalid escape sequence (only legal
427    /// in tagged templates, where `cooked` is `undefined`).
428    pub cooked: Option<Wtf8>,
429    /// Source text between the delimiters, verbatim.
430    pub raw: String,
431}
432
433/// A lexical token.
434#[derive(Debug, Clone, PartialEq)]
435pub enum TokenKind {
436    /// End of input.
437    Eof,
438    /// Identifier (including context-sensitive words like `let`/`await`).
439    Ident(String),
440    /// Reserved word.
441    Keyword(Keyword),
442    /// Numeric literal.
443    Number(NumberLiteral),
444    /// BigInt literal.
445    BigInt(BigIntLiteral),
446    /// String literal with escapes already decoded.
447    ///
448    /// A [`Wtf8`] rather than a `String`: a literal may hold an unpaired surrogate
449    /// (`"\uD800"`), which `String` cannot represent at all.
450    String(Wtf8),
451    /// Regular expression literal (needs a re-scan from `/`).
452    RegExp {
453        /// Pattern source, without the slashes.
454        pattern: String,
455        /// Flag letters, without validation (the compiler validates them).
456        flags: String,
457    },
458    /// Template literal chunk.
459    Template(TemplateToken),
460    /// Punctuator.
461    Punct(Punct),
462}
463
464impl TokenKind {
465    /// A short human readable description, used in parser error messages.
466    pub fn describe(&self) -> String {
467        match self {
468            TokenKind::Eof => "end of input".to_string(),
469            TokenKind::Ident(name) => format!("identifier '{name}'"),
470            TokenKind::Keyword(kw) => format!("'{kw}'"),
471            TokenKind::Number(n) => match n {
472                NumberLiteral::Int(v) => format!("number '{v}'"),
473                NumberLiteral::Float(v) => format!("number '{v}'"),
474            },
475            TokenKind::BigInt(b) => format!("BigInt literal '{}n'", b.digits),
476            TokenKind::String(_) => "string literal".to_string(),
477            TokenKind::RegExp { .. } => "regular expression".to_string(),
478            TokenKind::Template(_) => "template literal".to_string(),
479            TokenKind::Punct(p) => format!("'{}'", p.as_str()),
480        }
481    }
482
483    /// If this is a punctuator, return it.
484    pub fn as_punct(&self) -> Option<Punct> {
485        match self {
486            TokenKind::Punct(p) => Some(*p),
487            _ => None,
488        }
489    }
490
491    /// If this is a keyword, return it.
492    pub fn as_keyword(&self) -> Option<Keyword> {
493        match self {
494            TokenKind::Keyword(kw) => Some(*kw),
495            _ => None,
496        }
497    }
498
499    /// Whether the token starts an expression (used to decide `/` == division
500    /// versus regex in error recovery paths).
501    pub fn is_identifier(&self) -> bool {
502        matches!(self, TokenKind::Ident(_))
503    }
504}
505
506/// A token plus where it came from.
507#[derive(Debug, Clone, PartialEq)]
508pub struct Token {
509    /// Token payload.
510    pub kind: TokenKind,
511    /// Source range of the token.
512    pub span: Span,
513    /// Whether a line terminator appeared between the previous token and this
514    /// one (drives Automatic Semicolon Insertion and restricted productions).
515    pub newline_before: bool,
516    /// Whether the token's spelling used a `\u` escape.
517    ///
518    /// A contextual keyword written with one is only an identifier: `{\u0067et x() {}}` is
519    /// not a getter. Reserved words are rejected by the lexer instead, so this only has to
520    /// answer for the handful of words that mean something by position.
521    pub escaped: bool,
522}
523
524impl Token {
525    /// Whether this token ends a statement, for ASI.
526    pub fn is_eof(&self) -> bool {
527        matches!(self.kind, TokenKind::Eof)
528    }
529}