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 · 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::{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.
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). For the lexer, every file that should parse must tokenize without an error: all 49,655 do. 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