Skip to content

JavaScript

James Conway edited this page Nov 23, 2026 · 11 revisions

parsec-js is Parsec's JavaScript parser, written from scratch. It's a parser, not an engine: nothing in it runs code, and nothing ever will. It has the lexer from M9 and, from M10, a parser for scripts: parse_script gives a tree with a span on every node, and Ast::to_estree writes it as acorn's ESTree JSON. Both are on main, not in a release yet. This page covers the lexer; modules come next.

On this page: Install · Parsing · ESTree out · Reading tokens · Goals · Tokens · Diagnostics · Limits · Positions · Conformance · Data from scripts · What's next

Note

parsec-js ships from the next release. Until then, depend on it from Git: parsec-js = { git = "https://github.com/parsec-html/parsec" }.

Install

cargo add parsec-js

It depends on parsec-base and nothing else. You don't compile the HTML parser to use it (Architecture says why).

Parsing

use parsec_js::{Node, parse_script};

let src = "const total = items.reduce((sum, x) => sum + x, 0);";
let ast = parse_script(src).unwrap();
let Node::Program { body, .. } = *ast.node(ast.root()) else { unreachable!() };
let first = ast.get(body)[0];
assert_eq!(ast.span(first).text(src), src);
assert!(ast.to_estree(src).contains(r#""type":"ArrowFunctionExpression""#));

parse_script(src) parses a script. parse(src, &options) takes Options: source_type (SourceType::Script or SourceType::Module; a module is strict, may await at the top, and has import and export) and limits. The result is an Ast or the first syntax error as a Diagnostic.

  • The tree. Every node lives in one arena as a Node, an enum with a variant per ESTree type, addressed by NodeId. ast.node(id) reads one, ast.span(id) gives its byte range in the source, and ast.get(list) turns a List (a statement body, arguments, properties) into a slice of ids. Comments are kept on the side, in ast.comments().
  • Everything ECMAScript 2025 allows, with Annex B's additions for sloppy scripts: destructuring, classes with private names and static blocks, async functions and generators, optional chaining, automatic semicolon insertion, and in modules every import and export form, import.meta, dynamic import(), top-level await and import attributes (with { type: "json" }).
  • No backtracking. The parser chooses each / and } goal for the lexer, and reads arrow parameters and assignment patterns once, turning the cover grammar into patterns in place.

ESTree out

ast.to_estree(src) writes the tree as ESTree JSON in the shape acorn 8 gives, offsets in UTF-16 code units as JavaScript counts them, so tools written for acorn or espree can read it. to_estree_with(src, EstreeOptions { loc: true }) adds a loc on every node, as acorn's locations option does. scripts/compare-acorn.sh checks the output against acorn's: it's the same on every test262 file both parse.

Reading tokens

use parsec_js::{Goal, Kind, Lexer, SourceType};

let src = "#!/usr/bin/env node\nlet big = 1_000n; // a BigInt\n";
let mut lexer = Lexer::new(src, SourceType::Script);
let mut words = Vec::new();
loop {
    let token = lexer.next_token(Goal::RegExp);
    if token.kind == Kind::Eof {
        break;
    }
    if !token.is_trivia() {
        words.push(token.text(src));
    }
}
assert_eq!(words, ["let", "big", "=", "1_000n", ";"]);
assert!(lexer.diagnostics().is_empty());

SourceType::Script or SourceType::Module decides two things the lexer can see on its own: a module is always strict, and Annex B's HTML-like comments (<!-- and -->) work only in scripts. In a module, <!-- reads as <, !, --, as the spec says.

Goals, or why the lexer never guesses

/ is division after an expression and the start of a regular expression anywhere else. } closes a block, unless it ends a ${…} in a template. A lexer on its own can't tell which, and lexers that guess get it wrong on inputs like a = b\n/re/.test(c).

So next_token takes a Goal, the same four the spec defines:

Goal / }
Goal::Div division punctuator
Goal::RegExp regular expression punctuator
Goal::TemplateTail division rest of a template
Goal::RegExpOrTemplateTail regular expression rest of a template

The parser knows which one applies and passes it. If you use the lexer directly, Goal::RegExp is right at the start of a statement and after an operator, and Goal::Div after an identifier, a literal, ) or ].

use parsec_js::{Goal, Kind, Lexer, Punct, SourceType};

let src = "a / b; /b/g";
let mut lexer = Lexer::new(src, SourceType::Script);
let kinds: Vec<Kind> = [Goal::RegExp, Goal::Div, Goal::RegExp, Goal::Div, Goal::RegExp]
    .into_iter()
    .map(|goal| lexer.next_token(goal).kind)
    .collect();
assert_eq!(kinds[1], Kind::Punct(Punct::Slash));
assert_eq!(kinds[4], Kind::RegExp);

Tokens

A Token is 12 bytes: a Kind, Flags and a Span. Nothing is allocated per token. What a token says, a string's value or a number's, is in its text, token.text(src); decoding values is the parser's job.

  • Kinds. Identifiers, private names (#x), keywords, punctuators, numbers (every form: hex, octal, binary, BigInt, separators), strings, template parts, regular expressions, comments, the hashbang, and Kind::Invalid for what can't be read.
  • Trivia. Comments and the hashbang come back as tokens too, so tools that keep comments can. token.is_trivia() says which to skip.
  • Flags.
    • NEWLINE_BEFORE: a line break came first. Automatic semicolon insertion needs it, so token.newline_before() is a method.
    • ESCAPED: the token has a backslash escape, so its value isn't its text. An escaped keyword (var) is Kind::Ident with this flag, never Kind::Keyword.
    • LEGACY_OCTAL: 017, 08 or "\01". Allowed in sloppy scripts, an error in strict code. The lexer can't know if a script is strict, so it flags these; in a module it reports them itself.
    • INVALID_ESCAPE: a template part with an escape that isn't one (`\xg`). That's allowed in a tagged template and an error anywhere else, which only the parser can tell.

Identifiers follow Unicode 17.0's ID_Start and ID_Continue, from tables generated by scripts/gen-unicode.py, the same version as the HTML parser's \p{} tables.

Diagnostics

The lexer never fails. A token it can't read whole comes back as far as it goes, or as Kind::Invalid, and a Diagnostic says what was wrong:

for d in lexer.diagnostics() {
    println!("{} at {:?}: {}", d.code, d.span, d.message);
}

A Diagnostic (from parsec-base) has a stable code, a Severity, the Span it's about, a message and optional labels. Every Parsec parser that isn't synced from Netweir reports errors this way. take_diagnostics() hands them over and clears the list.

Limits

use parsec_js::{Lexer, Limits, SourceType};

let limits = Limits { max_input: Some(16 << 20), ..Limits::default() };
let lexer = Lexer::with_limits(src, SourceType::Script, &limits);

Lexing is linear in the input whatever the input is: 12 hostile 1 MB inputs are in the test suite, and the lex fuzz target runs nightly. max_input turns away an input before any work starts. max_depth and max_steps are for the parser.

The parser recurses at most Limits::max_depth deep, DEFAULT_MAX_DEPTH (256) when you don't say, and returns a too-deep error past it, never a stack overflow: a million nested (((( fails in linear time. Real code stays far below it; typescript.js, 9 MB, needs 53. At 256 the parser uses at most about 250 KB of stack in a release build and 700 KB in a debug one, so a higher limit needs a bigger thread, about 1 KB a level in release. max_steps bounds the tokens read, and a parse fuzz target runs nightly.

Positions

A Span is a byte range into your source, two u32s. For line and column, build a LineIndex once:

use parsec_js::LineIndex;

let index = LineIndex::ecmascript(src);
let at = index.line_col(token.span.start);        // 1-based, in characters
let at16 = index.line_col_utf16(token.span.start); // what editors and JS tools count

LineIndex::ecmascript counts line breaks as JavaScript does, U+2028 and U+2029 included; LineIndex::new counts only \n, \r\n and \r. Lookups stay cheap on a minified file that's one long line.

Conformance

test262, the official ECMAScript suite, runs in CI on every pull request, and the counts are in each run's summary (Conformance). Every test262 file that should parse does, 48,408 of them, scripts and modules; of the 4,374 that shouldn't, 3,824 fail to parse, and the other 550 are early errors (a name declared twice, a regular expression's own grammar) that come with scope analysis in M11. For the lexer alone, all 49,655 files tokenize. Of the 4,676 files that shouldn't parse, the lexer catches the 267 whose fault is in the tokens; the rest need the parser.

Data from scripts

Plenty of pages ship their data inside a <script>: Nuxt's window.__NUXT__, Next.js's streamed payload, a Redux store dropped into a variable. Usually you'd start a browser to get at it, or write a regex and watch it break on the first nested brace. parsec_js::data reads it straight from the syntax tree instead. Nothing runs: no property is read, no function called, no name looked up.

Hand page_state the text of one script and it gives back every piece of state it recognizes:

use parsec_js::data::page_state;

let src = r#"window.__NUXT__=(function(a,b){return {layout:a,data:[{title:b}]}}("default","Home"));"#;
let found = page_state(src)?;
assert_eq!(found[0].name, "window.__NUXT__");
assert_eq!(
    found[0].value.as_ref().unwrap().to_json_string(),
    r#"{"layout":"default","data":[{"title":"Home"}]}"#
);

Each Found carries a name, the span of the value in your source, and a value that's either a Json or a Refused saying why it isn't data. A syntax error in the script comes back as the outer Err. If you've already parsed the script, page_state_in(&ast, src) skips the second parse.

The shapes it finds

Only statements at the top of the script count. Code inside a function or an if might never run, so it isn't state.

Shape name
window.X = …, self.X = …, globalThis.X = …, any depth, window["X"] too window.X, window.X.config
var X = …, let X = …, const X = … X
self.__next_f.push([…]), Next.js App Router self.__next_f, one per push

The value on the right can be a literal, or one of two shapes that wrap one:

  • JSON.parse("…") with a single string literal. The string is parsed as JSON. Because the string's escapes stand between the JSON text and your source, a refusal points at the string as a whole.
  • A function called on the spot, the way Nuxt 2 writes its state: (function(a,b,…){return {…}}(null,"x",…)). Each parameter takes the value of its argument, and the arguments have to be literals themselves. The function has to be plain, with plain parameters and a body that does nothing but return. Any parameter without an argument is undefined. Substitution may copy at most 16 bytes per byte of source, so a script can't name one large argument ten thousand times to make you build a gigabyte.

Next.js payloads

Next.js App Router streams its payload as a run of self.__next_f.push(…) calls, often one per <script>. Run page_state over each script in page order, collect what it finds, and next_flight joins the text:

use parsec_js::data::{next_flight, page_state};

let mut found = Vec::new();
for script in scripts {
    found.extend(page_state(script)?);
}
let flight = next_flight(&found);

A row of the payload can start in one push and end in the next, which is why only the joined text makes sense. What you get is React's Flight format: rows of id:value, each ending in a newline, most of whose values are JSON. Reading the rows is up to you.

JSON in a script

Some state is plain JSON in a script element of its own, like Next.js's <script id="__NEXT_DATA__" type="application/json">. Pass the element's text to json:

use parsec_js::data::json;

let data = json(next_data_text)?;

It's as strict as JSON.parse: no comments, no trailing commas, no single quotes, and nesting deeper than 256 levels is too-deep. Nuxt 3's __NUXT_DATA__ reads the same way, though what you get is devalue's flat array, where numbers point at other entries; json leaves it as that array.

Literals

literal(&ast, src, expr) is the piece underneath, for any expression you've found yourself. It accepts what JSON can say, written the ways JavaScript allows:

  • objects with plain keys (names, strings, numbers), arrays, strings, numbers in every notation, true, false, null, and templates without ${…};
  • - and + on a number, and ! on a number or a boolean, since minifiers write !0 for true and !1 for false;
  • undefined and void 0, which, as in JSON.stringify, leave a key out of an object and turn into null in an array. So does a hole, [1, , 3].

When a key turns up twice, it keeps its first place and its last value. Keys stay in source order; JavaScript itself would move keys that look like array indices to the front.

Anything else gets refused, along with the span that stopped it:

reason What stopped it
not-a-literal a name, a call, an operator, a function: anything that would have to run
substitution a template's ${…}
bigint a BigInt, which JSON can't write
regexp a regular expression
computed-key {[k]: v}
method a method, getter or setter
spread ...x
proto __proto__: v, which sets the prototype rather than a key
not-a-number -, + or ! on something else
undefined a value that's undefined as a whole
lone-surrogate half a surrogate pair, which a Rust String can't hold
parameters, function-body a called function that isn't the plain kind above
too-large substitution past its cap
json-syntax, too-deep JSON that JSON.parse would reject, or nesting past 256

Json is a plain enum: Null, Bool, Number(f64), String, Array and Object(Vec<(String, Json)>). to_json_string writes it out the way JSON.stringify does, so 1e400 becomes null there too.

What's next

  • M10: the rest of the syntax tree: modules, the depth and step limits with their tests. Scripts already parse, all 47,895 test262 scripts that should.
  • M11: scopes, bindings and early errors.

The Roadmap has the rest.

Clone this wiki locally