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 · 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.
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.
- M10: the rest of the syntax tree: modules, the depth and step limits with their tests, and a bench against oxc and swc. Scripts already parse, all 47,895 test262 scripts that should.
- M11: scopes, bindings and early errors.
-
M12: data from
<script>tags as JSON, without running anything.
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