GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — perf(javascript): parse every program through parseProgram, ESTree on request by alexander-akait · Pull Request #23073 · webpack/webpack

perf(javascript): parse every program through parseProgram, ESTree on request #23073

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
alexander-akait merged 15 commits into main from perf/javascript-flat-estree
Nov 2, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

perf(javascript): parse every program through parseProgram, ESTree on request #23073

Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
7dcb6a4
perf(javascript): write a SyntaxTree's nodes children first
alexander-akait Oct 28, 2026
3fd8794
perf(javascript): regenerate types for the post-order SyntaxTree writer
alexander-akait Oct 28, 2026
cde0f18
perf(javascript): build a whole SyntaxTree's ESTree in one pass
alexander-akait Oct 28, 2026
ed5f763
perf(javascript): make lazy parsing flat by default, ESTree on request
alexander-akait Oct 29, 2026
d4d8f5c
perf(javascript): parse every program through parseProgram
alexander-akait Oct 29, 2026
8c092bc
refactor(javascript): type parseProgram with overloads, no casts to any
alexander-akait Oct 29, 2026
2ae76fa
refactor(javascript): validate the printer's regexps without a parse
alexander-akait Oct 29, 2026
a6a167a
fix(javascript): refuse an unterminated literal before validating a r…
alexander-akait Oct 29, 2026
921ff2b
docs(javascript): describe parseProgram as the one entry, parsedTree …
alexander-akait Nov 2, 2026
781c0a2
refactor(javascript): type addEstree's root as the node it reads, wit…
alexander-akait Nov 2, 2026
5056ed8
docs(changeset): keep the folded JavaScript entry to one short sentence
alexander-akait Nov 2, 2026
b137712
fix(javascript): guard and invalidate the tree on every parseProgram …
alexander-akait Nov 2, 2026
208adba
fix(javascript): write a node acorn shares between two fields once pe…
alexander-akait Nov 2, 2026
76936cb
fix(javascript): build a tree in id order only when every child comes…
alexander-akait Nov 2, 2026
f9ffe0c
fix(javascript): read words as a script once auto falls back to one
alexander-akait Nov 2, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

2 changes: 1 addition & 1 deletion 2 .changeset/040-javascript-source-processor.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
"webpack": minor
---

Add a JavaScript `SourceProcessor` that minifies faster; drop `printer.load()`.
Add a faster JavaScript `SourceProcessor` and drop `printer.load()`.
6 changes: 3 additions & 3 deletions 6 docs/syntax.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ One visitor serves several node types through an array, resolved once in `use()`
Conventions every language keeps, and a new member follows:

- **A node is an integer id**, valid until the next parse; `0` is no node, and an HTML attribute's id is negative. The path is one object rebound before each callback; read it during the callback, never keep it.
- **A parse entry point returns ids too**, read through the exported path `A` until the next parse (`parseHtml`, CSS's `parseA*`, JavaScript's `parseProgram`), and takes a `parseError(input, code, start, end, severity)` option reporting each parse error of the tokenizer and of the parser or tree construction: `"error"` where end of input cuts a token or rule short, or where a JavaScript one stops the parse, and `"warning"` otherwise; without the option, a `"warning"` goes unreported and `parseProgram` returns `undefined` for an `"error"`. No spec names them all, so HTML's tree-construction errors take html5lib-python's names, JavaScript's take Babel's `reasonCode` kebab-cased (read off probes by `tooling/generate-js-data.js`), and CSS's are webpack's own.
- **A parse entry point returns ids too**, read through the exported path `A` until the next parse (`parseHtml`, CSS's `parseA*`, JavaScript's `parseProgram`), and takes a `parseError(input, code, start, end, severity)` option reporting each parse error of the tokenizer and of the parser or tree construction: `"error"` where end of input cuts a token or rule short, or where a JavaScript one stops the parse, and `"warning"` otherwise; without the option, HTML and CSS leave a `"warning"` unreported, and `parseProgram` throws its first error, recoverable or not, as acorn does (with the option it returns `undefined` for an `"error"`). No spec names them all, so HTML's tree-construction errors take html5lib-python's names, JavaScript's take Babel's `reasonCode` kebab-cased (read off probes by `tooling/generate-js-data.js`), and CSS's are webpack's own.
- **The node is the last argument and optional**, defaulting to the current one: `path.range()`, `path.range(other)`, `path.child(0)`.
- **A node has at most one `name` and one `value`; every other part is a `Field`, a `Flag` or a `Part`** (its position, and its text when it has more than the name and value), so the generic members cover any grammar instead of one method per part.
- **`name` and `value` are what the language's spec defines**, decoded as ESTree's `Identifier.name` and `Literal.value` are: escapes and character references resolved, a number as a number, a comment's text without its delimiters. **`source` is exactly the input**, so the spelling as written is `source(path.startOf(Part.name), path.endOf(Part.name))`. A node without a name or value answers `""`, a missing part `null`.
Expand Down Expand Up @@ -126,8 +126,8 @@ Conventions every language keeps, and a new member follows:

## JavaScript

- `syntax.js` reaches `parser` and `printer` through getters: parsing never loads the printer, and the printer loads the parser to read an asset into a `SyntaxTree`. It is the only parser: a source it refuses is refused, and terser's parse options for what is not a program (`parse.expression`, `parse.strict`, `parse.experimental_typescript`) are refused too. `toEstreeObject(tree, node, fields?)` builds a `SyntaxTree` node's ESTree object, each call returning the same object: every field, or only those listed and the rest on a later call. It bridges hooks and plugins while the parser moves to that struct-of-arrays tree. The tree already reads as [the node path](#the-node-path) does, a node passed last: `type`, `start`, `end`, `range`, `name`, `value`, `field`, `fieldCount`, `flag` and `textOf` with the `NodeType`, `Field`, `Flag` and `Part` that `syntax.parser` exports. `SourceProcessor` walks the tree a parse writes as the CSS and HTML ones walk theirs, each visitor handed that path and the children taken in source order (a template's quasis and expressions in turn). Asked for `mode: "minify"`, the same walk prints: `syntax-printer.js`'s `printer` returns each node's text from its children's, as `minify` prints a source it neither compresses nor mangles, comments left out and terser's format options read from `format`. A minify walks the tree its own parse wrote (`walkSyntaxTree`) with the comments it keeps, a name printed inside its parent's text where none of its own is read: each is taken as terser's printer reaches it, by the node holding its token, and printed once the text before it is, which a text opening with it leaves to the node printing that text. What terser's stream reads off the text before a node — `has_parens` before a function or object starting a statement, `!--`, `</script` — it reads off the tree instead, through two members only the JavaScript path has: `tree`, the `SyntaxTree` walked, and `ancestor(level)`, a node enclosing the current one; and each child's text is read once (`PrintContext#consume`), so a long one is made flat and its pieces let go as it is printed.
- `syntax-parser.js` — tokenizer, acorn-derived core and every production in one file (any parse reaches the productions). Given a `syntaxTree`, the lazy path writes each node into it as it finishes, an id in the tree's columns rather than an object; the few the parser reads back by name (a key, a module name, an exported declaration, a function before its body ends) stay objects until their parent is written, and an expression read as a pattern after all is retyped in place. Only the latest edition without parser plugins takes a tree, since acorn's own productions read their nodes back. `regexp.js` (pattern validator) is the one on-demand piece, reached only for a pattern the host engine rejected — never `require` it from a build path.
- `syntax.js` reaches `parser` and `printer` through getters: parsing never loads the printer, and the printer loads the parser to read an asset into a `SyntaxTree`. It is the only parser: a source it refuses is refused, and terser's parse options for what is not a program (`parse.expression`, `parse.strict`, `parse.experimental_typescript`) are refused too. `toEstreeObject(node, fields?)` builds the ESTree object of a node of the last parse (`SyntaxTree#estree` of any tree), each call returning the same object: every field, or only those listed and the rest on a later call; a whole program asked for first is built in one pass in id order. It bridges hooks and plugins while the parser moves to that struct-of-arrays tree. The tree already reads as [the node path](#the-node-path) does, a node passed last: `type`, `start`, `end`, `range`, `name`, `value`, `field`, `fieldCount`, `flag` and `textOf` with the `NodeType`, `Field`, `Flag` and `Part` that `syntax.parser` exports. `SourceProcessor` walks the tree a parse writes as the CSS and HTML ones walk theirs, each visitor handed that path and the children taken in source order (a template's quasis and expressions in turn). Asked for `mode: "minify"`, the same walk prints: `syntax-printer.js`'s `printer` returns each node's text from its children's, as `minify` prints a source it neither compresses nor mangles, comments left out and terser's format options read from `format`. A minify walks the tree its own parse wrote (`walkSyntaxTree`) with the comments it keeps, a name printed inside its parent's text where none of its own is read: each is taken as terser's printer reaches it, by the node holding its token, and printed once the text before it is, which a text opening with it leaves to the node printing that text. What terser's stream reads off the text before a node — `has_parens` before a function or object starting a statement, `!--`, `</script` — it reads off the tree instead, the one `parsedTree()` returns while the walk runs, and through the one member only the JavaScript path has, `ancestor(level)`, a node enclosing the current one; and each child's text is read once (`PrintContext#consume`), so a long one is made flat and its pieces let go as it is printed.
- `syntax-parser.js` — tokenizer, acorn-derived core and every production in one file (any parse reaches the productions). `parseProgram(input, pos, options)` is the one entry, a build's included: it writes a new `SyntaxTree`, read through `A`, and returns the program's node, unless `estree: true` asks for ESTree objects, the program returned, as `JavascriptParser` and `WebManifestParser` do (rebuilding a whole program with `toEstreeObject` costs 30–55% more). Beside `sourceType` (and `auto`, a module turning into a script at a top-level `return`) and `parseError`, it takes `allowReturnOutsideFunction`, `comments` (an array to collect into) and `importPhases`. The class path, building ESTree objects, stays only for `JavascriptParser.extend`'s plugins, a custom `parse` and tracked locations. The tree path writes each node into the tree, or the one a caller passes as `syntaxTree`, as it finishes, children before their parent, an id in the tree's columns rather than an object; the few the parser reads back by name (a key, a module name, an exported declaration, a function before its body ends) stay objects until their parent is written, and an expression read as a pattern after all is retyped in place. Only the latest edition without parser plugins takes a tree, since acorn's own productions read their nodes back. `regexp.js` (pattern validator) is the one on-demand piece, reached only for a pattern the host engine rejected — never `require` it from a build path.
- **`sourceType` names which production a source is**, for `parseProgram`, `process` and the printer's `minify` alike: `"module"` (the default), `"script"`, or a `FunctionBody` read as acorn's `commonjs` goal reads one (`return` and `new.target` at its top, no `import`, `export` or `import.meta`): `"commonjs"`, a CommonJS module in the function Node wraps it in, or `"event-handler"`, an event handler attribute's value in the one HTML compiles it into, which a `#!` line cannot open. HTML offers only `"event-handler"` for an attribute, never `"module"`. `minify` compresses a function's body inside a function built around its tree, so every rule a function's body reads by applies and a name it reads undeclared stays global (for a handler, the element's, form's or document's); it prints the body without that function, mapped where it was read, its `#!` line and comments kept, and a handler without the last semicolon the closing brace would leave off. `parseProgram` and `process` read import phases (`import defer`, `import source`) too.
- `syntax-printer.js` — webpack's JavaScript minifier, printing, mangling and compressing in one pass; `jsMinify.js` is the `minify` the default minimizer dispatches JS to under `experiments.futureDefaults`, and goes through it alone; without that flag the minimizer dispatches to `terserMinify` as `minimizer-webpack-plugin` publishes it, running the user's own terser since webpack lists it only as a devDependency. Neither needs an option to say which, and the printer itself never loads terser. `createModules` builds what the one pass reads: the parser's tables (`createParseTables`), the mangler's names (`createFrequency`), the output stream (`MinifiedOutput`, which the node printer's stream extends), the parse into a `SyntaxTree` (`parse.parseTree`), its mangling (`mangleTree`, `mangleTreeProperties`, `mangleManglingScopes`) and the `improvements` switches the node printer reads. `prepareMinify` reads and mangles the one source a `SourceProcessor` run minifies, and `createNodePrinter`'s printer compresses it as it prints. `test/specCases/minify-corpora.spectest.js` minifies each source of each corpus in its `CORPORA` list (add a new one there) under the option sets in `OPTION_SETS` with the one `SourceProcessor` pass `jsMinify` runs and with terser, and runs each output whose test states what its input prints (terser's `expect_stdout`, swc's `expected.stdout` and `exec.rs`) in terser's sandbox: it must print that, unless `INHERITED` lists it as misprinting by an option's own contract. webpack must refuse a source where terser does and only there: where the reference refuses a source the spec allows, the parse error it answers with is listed in `REFUSED_BY_REFERENCE` with what makes the source legal, and where webpack refuses a source the reference reads, the source is listed in `REFUSED_BY_WEBPACK` with the rule it breaks (a test262 test expecting a parse error needs no entry). Summed over each corpus, webpack's outputs must gzip no bigger than terser's. An entry that stops matching fails until retired. Each output is also sized against swc's recorded one, a fixture's `output.js` or, for one of terser's cases, what swc's port of it records (gzip decides, raw breaks a tie): one bigger fails unless `test/helpers/swcSmaller.js` lists it under what swc does that webpack does not yet, and a listed one no longer bigger fails until retired. Under the default minimizer's options each source of every corpus but test262 is also minified by `oxc-minify`, held the same way to `test/helpers/oxcSmaller.js`; an oxc output that misprints is no lead. `JS_MINIFY_REPORT=<file>` tallies where webpack's is worse, the same and better. terser's corpus submodule is pinned to the `terser` devDependency — bump both together, and regenerate `data.js`.
- `yarn test:minify-corpora` — webpack's one-pass JS minifier vs the published one it replaces over every JS corpus: terser's own `test/compress` and `test/input`, test262, swc's minifier tests and oxc's; where a test states what its input prints, the output is run and must print it, webpack must refuse a source where terser does, and each corpus's outputs must gzip no bigger than terser's in total, or than its `TERSER_TOTAL_BUDGET` ratio to terser's while it still is. Each output must also be no bigger than swc's recorded one unless `SWC_SMALLER` lists why, and every output outside test262 no bigger than `oxc-minify`'s unless `OXC_SMALLER` does; `JS_MINIFY_REPORT=<file>` tallies worse, the same and better.
7 changes: 3 additions & 4 deletions 7 lib/asset/WebManifestParser.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"use strict";

const HtmlSourceDependency = require("../dependencies/html/HtmlSourceDependency");
const { parse } = require("../javascript/syntax-parser");
const { parseProgram } = require("../javascript/syntax-parser");
const Parser = require("../module/Parser");

/** @import { Expression, ObjectExpression, Program, Property } from "estree" */
Expand Down Expand Up @@ -70,10 +70,9 @@ class WebManifestParser extends Parser {
let ast;
try {
// Wrap in parens so the top-level object is an expression, not a block.
ast = parse(`(${source})`, {
ecmaVersion: "latest",
ast = parseProgram(`(${source})`, 0, {
sourceType: "script",
lazyNodes: true
estree: true
});
} catch (_err) {
// Not valid JSON — leave the file untouched (still emitted as-is).
Expand Down
37 changes: 36 additions & 1 deletion 37 lib/javascript/JavascriptParser.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,12 @@ const {
hasOctalEscape,
isIdentifierChar,
overflowFrom,
parseProgram,
positionAt
} = require("./syntax-parser");

/** @import { BuiltJavascriptModule } from "./JavascriptModule" */
/** @import { EcmaVersion, ParserOptions, ParserPlugin } from "./syntax-parser" */
/** @import { CollectedComment, EcmaVersion, ParserOptions, ParserPlugin } from "./syntax-parser" */
/** @import { SideEffectsContext } from "./side-effects" */
/**
* @import {
Expand Down Expand Up @@ -7557,6 +7558,40 @@ class JavascriptParser extends Parser {
*/
static _parse(code, options, customParse) {
const type = options ? options.sourceType : "module";
if (
typeof customParse !== "function" &&
parser === WebpackParser &&
options.ranges === true &&
options.locations !== true
) {
/**
* @param {"module" | "script" | "auto"} sourceType what to read it as
* @returns {ParseResult} the program and its comments
*/
const parseAs = (sourceType) => {
/** @type {CollectedComment[]} */
const comments = [];
const ast = parseProgram(code, 0, {
sourceType,
allowReturnOutsideFunction: sourceType === "script",
comments: options.comments ? comments : undefined,
importPhases: options.importPhases === true,
estree: true
});
return { ast, comments: /** @type {Comment[]} */ (comments) };
};
if (type !== "auto") return parseAs(type);
try {
return parseAs("auto");
} catch (error) {
try {
return parseAs("script");
} catch (_err) {
// the module parse's error is the one to report
throw error;
}
}
}
/** @type {ParseOptions} */
let parserOptions;
if (typeof customParse === "function") {
Expand Down
39 changes: 39 additions & 0 deletions 39 lib/javascript/regexp.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -1792,6 +1792,45 @@ const install = (target) => {
}
};

/**
* Validates a regular expression literal's pattern and flags against the spec
* at an edition, without parsing a program around it.
* @param {string} pattern the pattern, as a literal writes it between its slashes
* @param {string} flags the flags
* @param {import("./syntax-parser").EcmaVersion} ecmaVersion the edition to hold it to
* @returns {void} throws a `SyntaxError` where the literal is invalid
*/
const validateRegExpLiteral = (pattern, flags, ecmaVersion) => {
const validator = new RegExpValidator({ ecmaVersion }, "");
// What a parse's scan refuses before validating, as the validator expects a
// literal it ended: a line break, a `/` ending it early, an open class or escape.
let escaped = false;
let inClass = false;
for (let i = 0; i < pattern.length; i++) {
const code = pattern.charCodeAt(i);
if (code === 10 || code === 13 || code === 0x2028 || code === 0x2029) {
validator.raise(0, "Unterminated regular expression");
}
if (escaped) {
escaped = false;
} else if (code === 92) {
escaped = true;
} else if (code === 91) {
inClass = true;
} else if (code === 93) {
inClass = false;
} else if (code === 47 && !inClass) {
validator.raise(0, "Unterminated regular expression");
}
}
if (escaped || inClass) validator.raise(0, "Unterminated regular expression");
const state = new RegExpValidationState(validator);
state.reset(0, pattern, flags);
validator.validateRegExpFlags(state);
validator.validateRegExpPattern(state);
};

module.exports.RegExpValidationState = RegExpValidationState;
module.exports.RegExpValidator = RegExpValidator;
module.exports.install = install;
module.exports.validateRegExpLiteral = validateRegExpLiteral;
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402860 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.