Repository navigation
JavaScript
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 · Scopes and early errors · Modules · 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" }.
cargo add parsec-jsIt depends on parsec-base and nothing else. You don't compile the HTML parser to use it (Architecture says why).
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 byNodeId.ast.node(id)reads one,ast.span(id)gives its byte range in the source, andast.get(list)turns aList(a statement body, arguments, properties) into a slice of ids. Comments are kept on the side, inast.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
importandexportform,import.meta, dynamicimport(), top-levelawaitand 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.
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.
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.
/ 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);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, andKind::Invalidfor 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, sotoken.newline_before()is a method. -
ESCAPED: the token has a backslash escape, so its value isn't its text. An escaped keyword (var) isKind::Identwith this flag, neverKind::Keyword. -
LEGACY_OCTAL:017,08or"\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.
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.
A code is for matching on: unexpected-token, duplicate-label, with-in-strict. It won't be renamed, and it won't come to mean something else. The message beside it is for people and may be reworded. Every code parsec-js gives is in the parsec_js::diagnostics table, with what's wrong and the ECMAScript 2025 section the rule is in, and a test fails if one is missing.
When an error involves a second place, a label points at it: the ( that's still open when the parser finds { instead of ), the first of two declarations, labels, defaults or constructors, the "use strict" that makes a legacy octal escape before it an error.
let err = parse_script("if (ready { go() }").unwrap_err();
assert_eq!(err.labels[0].message, "this `(` is still open");Diagnostic::render prints a diagnostic the way a compiler does:
use parsec_js::{LineIndex, RenderOptions, parse_script};
let src = "outer: outer: total++;\n";
let err = parse_script(src).unwrap_err();
let frame = err.render(src, &LineIndex::ecmascript(src), &RenderOptions::default());
print!("{frame}");error[duplicate-label]: the label `outer` is already in use here
--> 1:8
|
1 | outer: outer: total++;
| ----- ^^^^^
| |
| the label is defined here
Columns are what a terminal shows: tabs expand to tab_width, Chinese, Japanese and Korean characters and most emoji take two columns, combining accents none. A minified bundle's one long line is cut to max_width columns around the error, with … where it's cut. Control and bidirectional characters print as �, so a frame of hostile input can't move your cursor or reorder the line. Set path to show a file name. The renderer is in parsec-base, so the CSS and XML parsers will print the same frames.
parse stops at the first error. parse_recovering keeps going: when a statement fails, it skips to the next ;, to the } that closes the block, or to a statement keyword at the start of a line, and parses on from there.
use parsec_js::{Options, parse_recovering};
let src = "let a = ;\nlet b = 2;\nif (b { go() }\n";
for d in parse_recovering(src, &Options::default()).unwrap_err() {
println!("{d}");
}
// error[unexpected-token] at 8..9: `;` can't go here
// error[unexpected-token] at 27..28: `{` can't go hereThe first error is always the one parse gives. Later ones can follow from it now and then, as with any compiler. A program with no errors gives the same tree either way, and parse itself doesn't slow down: the only cost is a flag it checks once a statement. The depth and step limits still stop the parse.
An editor reparses on every keystroke. Ast::reparse takes the edit, the bytes in range replaced by text, and parses only the smallest function body or statement around it again. The rest of the tree is kept, with its spans moved.
use parsec_js::{Edit, Options, Span, parse_script};
let src = "function f() {\n return 1;\n}\nf();\n";
let mut ast = parse_script(src)?;
let done = ast.reparse(src, &Edit { range: Span::new(24, 25), text: "42" }, &Options::default())?;
// done.source is the new source, and done.reparsed is the
// `return 42;` it parsed againThe tree you get is the one parse would give for the new source, node for node. A test makes random edits to test262's files and the benchmark bundles and checks every one against a full parse, and a fuzz target does the same.
To get that, reparse parses the whole source when it can't be sure a piece would come out the same:
- the edit opens or closes something that reaches outside the piece, like a
/*, a string, a template or a}; - it's in a directive prologue, where
"use strict"changes what follows, or a parameter list; - the statement starts with
importorexport, which the module as a whole checks; -
max_stepsis set, since the step budget counts the whole source.
An edit inside a comment that stays one comment, like fixing a typo in a doc comment, changes no token, and only moves the spans after it.
On typescript.js, 9 MB, a single-character edit takes 2.2 ms against 33 ms for a parse (bench js-reparse, the median of 400 edits on an Apple M-series laptop). The piece parsed again is a median 152 bytes; most of the 2.2 ms is moving the spans and node ids after it.
A syntax error in the new source is the Err, and the tree stays as it was.
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.
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 countLineIndex::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.
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.
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.
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 butreturn. Any parameter without an argument isundefined. 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 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.
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.
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!0fortrueand!1forfalse; -
undefinedandvoid 0, which, as inJSON.stringify, leave a key out of an object and turn intonullin 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.
A syntax tree tells you what the code says. It doesn't tell you what a name means: whether the x on line 40 is the parameter, the let in the block around it, or a global some other script set. parsec_js::scope works that out, from the tree alone.
use parsec_js::parse_script;
use parsec_js::scope::{BindingKind, Scopes};
let src = "let total = 0; for (const x of items) total += x; console.log(total);";
let ast = parse_script(src)?;
let scopes = Scopes::analyze(&ast, src);
assert_eq!(scopes.free_names(), ["items", "console"]);
for r in scopes.references() {
match r.binding {
Some(b) => println!("{} -> {:?}", r.name(&ast, src), scopes.binding(b).kind),
None => println!("{} is free", r.name(&ast, src)),
}
}analyze is a separate pass, and only runs if you call it, so parsing costs the same whether you want scopes or not. It's one walk over the tree with its own stack, so a deep tree can't overflow yours.
-
Scopes, each with its
kind, itsparent, thenodethat made it, and whether it'sstrict. The kinds follow the spec's environments:GlobalorModuleat the top,Function,Block(a block, aswitch's cases, aforwithletorconstin its head),Catch,With,Class,ClassField(the implicit function each field initializer runs in),StaticBlock, andFunctionBodyfor a function whose parameters have a default or a computed key, since what the body declares can't be seen from them. -
Bindings, each with its
name,kind(Var,Let,Const,Function,Class,Param,CatchParam,Import, a function expression's or class's own name,Arguments), the scope it lives in, and the identifier that declares it. -
References, one per IdentifierReference, each resolved to its binding or left free, with its
access(Read,Write,ReadWrite) and atdzflag. -
Lookups by node:
scope_of(node)for the scope a node makes,reference(node)anddeclaration(node)for an identifier, andlookup(scope, name)for what a name would mean anywhere.
-
varand function declarations hoist to their function. In sloppy code, a function declared in a block is also avarin its function (Annex B), unless avarof that name would be an error there or it's a parameter's name. Inside the block, references go to the block's binding; outside, to thevar. -
let,constandclasslive in their block. A reference that comes before its declaration in the same function getstdz: true:let x = x;,class C extends C {},for (let x of x). One in a nested function doesn't, since that function may run later. -
argumentsis a binding in every function that isn't an arrow, made only when something refers to it. - A direct
eval(…)marks its scope and every scope around itdynamic, since the eval'd code can read and add names there. Awithbody gets aWithscope of its own, also dynamic.eval?.(…)and(0, eval)(…)aren't direct, and don't count.
Some programs are SyntaxErrors though every token is where the grammar allows it. The spec calls these early errors. The parser checks most of them as it goes: a break with nothing to break, with in strict code, a duplicate __proto__, super outside a method. Three kinds need the whole program or a grammar of their own, and early_errors checks them on a tree the parser accepted:
use parsec_js::{early_errors, parse_script};
let src = "let total = 0;\nvar total;\nconst digits = /[9-0]/;";
let ast = parse_script(src)?;
for d in early_errors(&ast, src) {
println!("{}: {}", d.code, d.message);
}
// lexical-var-conflict: `total` is declared both with `var` and as a lexical name in this scope
// regexp-range-order: this range's start is after its end| Code | What's wrong |
|---|---|
duplicate-declaration |
a lexical name declared twice in one scope, or as a parameter too |
lexical-var-conflict |
a var and a let, const, class or block function of the same name |
export-undeclared |
export { a } in a module that never declares a
|
regexp-… |
a regular expression pattern that wouldn't compile |
Every diagnostic has a span in your source, and a duplicate has a label on the first declaration. If you've already called Scopes::analyze, pass its result to early_errors_in and the analysis isn't run twice. The parsec_js::early docs list every early error in the spec, its code, and whether the parser or early_errors checks it.
The lexer only finds where a regular expression literal ends. What's between the slashes is a language of its own, and parsec_js::regexp::validate(pattern, flags) reads it the way a RegExp would be built, without building one. It knows all three modes: no flag, with Annex B's looser rules (/\8/, /a{/ and /[\d-z]/ are fine there); u; and v, with nested classes, &&, --, \q{…} and properties of strings. It checks named groups (one name may repeat only in separate alternatives), modifiers like (?i:…), backreferences, and every \p{…} name and value in Unicode 17.0. Each error has its own code, like regexp-property or regexp-duplicate-group-name.
With early_errors, all 4,374 of test262's parse negatives fail and all 48,408 files that should parse still do. The harness doesn't skip any negative for the kind of error it has; the only files it leaves out are the module fixtures, which aren't tests, and those using syntax past ES2025.
parsec_js::module::ModuleRecord is what a module imports and exports, as the spec's ParseModule records it. It's what you need for a module graph, and nothing gets resolved or loaded:
use parsec_js::module::ModuleRecord;
use parsec_js::{Options, SourceType, parse};
let options = Options { source_type: SourceType::Module, ..Options::default() };
let ast = parse(src, &options)?;
let record = ModuleRecord::new(&ast, src);
for m in &record.requested_modules {
println!("{} {:?}", m.specifier, m.attributes);
}-
requested_modules: each module asked for, once, with its import attributes sorted by key. Two requests are one only when their specifiers and attributes have the same UTF-16 value, so two different lone surrogates stay two even though both print as U+FFFD. -
import_entries: what each import binds, and from which request. -
local_export_entries,indirect_export_entries,star_export_entries: the exports, sorted as the spec sorts them.import { a } from "m"; export { a }lands in the indirect list as a re-export ofm'sa;export default 42is a local export of*default*.
- M16: JavaScript from Python, WebAssembly and C.
The Roadmap has the rest.
Parsec is the parsing foundation for the web, in Rust. It's Apache-2.0, 0.3.0 is out, and these pages describe main. Found something wrong here? Open an issue or ask in Discussions.
Repository · Issues · Discussions · Roadmap · Security policy · Licence