Expand description
JavaScript for Parsec: a parser for ECMAScript 2025 scripts, with Annex B’s additions, and modules, and the lexer under it.
It’s a parser, not an engine: nothing here runs code. parse gives
an Ast, every node in one arena with a Span beside it and the
comments kept on the side, or the first syntax error as a
Diagnostic. Ast::to_estree writes the tree as ESTree JSON in
the shape acorn gives, so tools written for acorn or espree can read
it.
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""#));scope works out which declaration each name refers to: the
scopes, their bindings, every reference resolved or left free, and
the names declared twice where the spec forbids it.
regexp checks a regular expression’s pattern by its own grammar,
the error a RegExp built from it would throw.
early_errors gives the early errors the parser leaves for a later
pass: those two, and an export of a name a module never declares.
Every error is a Diagnostic with a stable code, listed with the
rule it breaks in diagnostics, and labels on the other places it
involves. parse_recovering goes on after an error to find the
rest, and Diagnostic::render prints one as a code frame.
Ast::reparse brings a tree up to date after an edit by parsing
only the function body or statement around it, which on a large file
is a small part of a parse; the tree is the one parse would give.
module has a module’s import and export records, the spec’s
ImportEntry and ExportEntry, for building a module graph.
data reads the state pages keep in scripts, window.__NUXT__ = …
and its kin, as JSON, without running anything.
Recursion is bounded by Limits::max_depth (DEFAULT_MAX_DEPTH
without one) and work by Limits::max_steps, so hostile input gets
an error, never a stack overflow.
The lexer works alone too. Every token carries its Span in the
source, and nothing is allocated per token; what a token says (a
string’s value, a number’s) is in its text, and text reads it.
/ means division after an expression and starts a regular expression
anywhere else, and } either closes a block or carries on a template.
The lexer doesn’t guess which: Lexer::next_token takes a Goal,
as the spec’s InputElementDiv and InputElementRegExp goals do, and the
parser, which knows, passes it.
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());Re-exports§
pub use ast::Ast;pub use ast::Comment;pub use ast::CommentKind;pub use ast::List;pub use ast::Node;pub use ast::NodeId;pub use early::early_errors;pub use early::early_errors_in;
Modules§
- ast
- The syntax tree: every node in one arena, addressed by
NodeId, with itsSpanbeside it and its children’s ids inside it. - data
- Data from scripts: the state a page writes into a
<script>as a literal, read as JSON without running anything. - diagnostics
- Every error and warning this crate reports, by its code.
- early
- The spec’s early errors: what makes a program a SyntaxError though its grammar is fine.
- module
- What a module imports and exports: the spec’s ImportEntry and ExportEntry records (ECMA-262 16.2.1.6), read from the tree.
- regexp
- Regular expression patterns, checked by their own grammar (ECMA-262
22.2.1) and its early errors, with Annex B’s additions (B.1.2) for
patterns without the
uorvflag. - scope
- Scopes and bindings: which declaration each name in a program refers to, worked out from the tree alone.
- text
- What a token’s text means: an identifier’s name with its escapes decoded, a string’s or template’s value in UTF-16 code units, a number’s value, and those values written out as JSON.
Structs§
- Diagnostic
- Something a parser has to say about its input: a stable
codeto match on (likeunterminated-string), where, and a sentence for people. With a'staticmessage and no labels, making one allocates nothing. - Edit
- A change to a source: the bytes in
rangereplaced bytext. - Estree
Options - What
Ast::to_estree_withwrites. - Flags
- What the lexer noticed about a token that its kind doesn’t say.
- Label
- A second place a
Diagnosticpoints at, with what it is. - Lexer
- Reads tokens from a source, one per
Lexer::next_token. - Limits
- The most a parse may cost.
Noneis no limit. - Line
Index - Where each line starts in a text, for turning byte offsets into lines and columns, in characters or in UTF-16 code units as editors and the language server protocol count them.
- Options
- What to parse and how much it may cost.
- Render
Options - How
Diagnostic::renderlays a code frame out. - Reparsed
- What
Ast::reparsedid. - Span
- A byte range in the input,
start..end. - Token
- One token: what it is, what the lexer noticed about it, and where it is. 12 bytes, with no allocation behind it.
Enums§
- Goal
- Which of the lexical grammar’s goal symbols to read the next token
with. The grammar is ambiguous without one:
/divides after an expression and starts a regular expression anywhere else, and}closes a block unless it ends a template substitution. The parser knows which; the lexer is told and never guesses. - Keyword
- The words a parser treats specially: every ReservedWord, the ones
strict code reserves, and the contextual ones (
async,of,getand the rest), which are identifiers wherever they aren’t keywords. Which a word is, where, is the parser’s to decide;Keyword::is_reservedsays which are ReservedWords. - Kind
- What kind of token it is.
- Offsets
- What the
startandendoffsets inAst::to_estree_with’s JSON count from the start of the source. - Punct
- A Punctuator, DivPunctuator or RightBracePunctuator.
- Severity
- How bad a
Diagnosticis. - Source
Type - Whether the source is a Script or a Module. Modules are strict, and Annex B’s HTML-like comments are a syntax error in them.
Constants§
- DEFAULT_
MAX_ DEPTH - How deep the parser recurses when
Limits::max_depthdoesn’t say. A level is a statement, a function or class, an operand of a prefix operator or**, or an expression or pattern nested in brackets. Real code stays far below it (typescript.js, 9 MB, needs 53), and at the limit the parser uses at most about 250 KB of stack in a release build and 700 KB in a debug one, so it fits a 1 MB thread. A higher limit needs a thread with more: about 1 KB a level in a release build, 3 KB in a debug one.
Functions§
- parse
- Parses
srcas a Script or a Module, asoptionssays. The first syntax error is theErr. - parse_
recovering - Parses
srcasparsedoes, but goes on after a syntax error to find the rest: every error, in the order found, is theErr. - parse_
script - Parses
srcas a Script.