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