Skip to content

Commit 44d89f2

Browse files
fix(javascript): read and write ESTree trees the minifier threw on or changed
Given as ESTree, an arrow kept its `"use strict"` as a statement, so its body ran sloppy, and an anonymous `export default` function or class threw; given back as ESTree, a template inlined into another threw. Claude-Session: https://claude.ai/code/session_011CuRTB8fAv8PE7di49qDL4
1 parent fa5846c commit 44d89f2

2 files changed

Lines changed: 125 additions & 12 deletions

File tree

‎lib/javascript/syntax-printer.js‎

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12253,10 +12253,11 @@ const installEstree = (modules) => {
1225312253
FunctionExpression: (estree) => lambdaFromEstree(estree, false),
1225412254
ArrowFunctionExpression: (estree) => {
1225512255
// terser's conversion leaves an arrow's directive a statement, where its
12256-
// parser reads one; only a tree we parsed ourselves is ours to fix.
12256+
// parser reads one, so the body turns sloppy: corrections read it too.
1225712257
const body =
1225812258
estree.body.type === "BlockStatement"
12259-
? tokenAt === null
12259+
? tokenAt === null &&
12260+
!(modules.corrections !== undefined && modules.corrections.enabled)
1226012261
? fromEstree(estree.body)
1226112262
: blockFromEstree(estree.body)
1226212263
: BlockStatementNode({
@@ -12645,8 +12646,9 @@ const installEstree = (modules) => {
1264512646
// WHY: terser's conversion exports every declaration as a value, where
1264612647
// its parser exports a named one as a declaration and an anonymous class
1264712648
// or function as the expression it is; `drop_unused` then reads a name
12648-
// the value has not got. Only a tree we parsed ourselves is ours to fix.
12649-
if (tokenAt === null || (!isClass && !isFunction)) {
12649+
// the value has not got. Only a tree we parsed ourselves is ours to fix,
12650+
// but an anonymous one, which terser's conversion cannot read at all.
12651+
if ((tokenAt === null && declaration.id) || (!isClass && !isFunction)) {
1265012652
return makeNode(ExportNode, undefined, {
1265112653
startToken: start,
1265212654
endToken: end,
@@ -13335,20 +13337,30 @@ const installEstree = (modules) => {
1333513337
const quasis = [];
1333613338
/** @type {EXPECTED_ANY[]} */
1333713339
const expressions = [];
13338-
for (let i = 0; i < node.segments.length; i++) {
13339-
if (i % 2 !== 0) {
13340-
expressions.push(toEstree(node.segments[i]));
13340+
// Inlining a template into another leaves two text segments in a row,
13341+
// which ESTree holds as one.
13342+
let afterText = false;
13343+
for (const segment of node.segments) {
13344+
if (segment.type !== "TemplateElement") {
13345+
expressions.push(toEstree(segment));
13346+
afterText = false;
13347+
} else if (afterText) {
13348+
const { value } = quasis[quasis.length - 1];
13349+
value.raw += segment.raw;
13350+
value.cooked =
13351+
value.cooked === null || segment.value === null
13352+
? null
13353+
: value.cooked + segment.value;
1334113354
} else {
1334213355
quasis.push({
1334313356
type: "TemplateElement",
13344-
value: {
13345-
raw: node.segments[i].raw,
13346-
cooked: node.segments[i].value
13347-
},
13348-
tail: i === node.segments.length - 1
13357+
value: { raw: segment.raw, cooked: segment.value },
13358+
tail: false
1334913359
});
13360+
afterText = true;
1335013361
}
1335113362
}
13363+
quasis[quasis.length - 1].tail = true;
1335213364
return { type: "TemplateLiteral", quasis, expressions };
1335313365
});
1335413366
defineToEstree("Defun", (node) => ({

‎test/unitCases/syntax-printer.unittest.js‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6195,6 +6195,107 @@ describe("syntax-printer", () => {
61956195
expect(ast.createWalker().webpackSkipsSqueezed).toBe(false);
61966196
});
61976197

6198+
describe("a tree given or given back as ESTree", () => {
6199+
/**
6200+
* @param {string} code a module
6201+
* @returns {EXPECTED_ANY} acorn's tree for it
6202+
*/
6203+
const estree = (code) =>
6204+
acorn.parse(code, { ecmaVersion: "latest", sourceType: "module" });
6205+
6206+
it("should keep an arrow's directive, as terser does only with corrections off", async () => {
6207+
const { minify } = await load();
6208+
const code = '(() => { "use strict"; x = 1; })();';
6209+
/** @type {EXPECTED_ANY} */
6210+
const options = { parse: { spidermonkey: true } };
6211+
expect((await minify(estree(code), options)).code).toBe(
6212+
'(()=>{"use strict";x=1})();'
6213+
);
6214+
const reference = await terserReference().minify(estree(code), options);
6215+
expect(reference.code).toBe("x=1;");
6216+
expect(
6217+
(await uncorrected(() => minify(estree(code), options))).code
6218+
).toBe(reference.code);
6219+
});
6220+
6221+
it("should give back a template inlined into another, which terser throws on", async () => {
6222+
const { minify } = await load();
6223+
const code = "console.log(`x${`y${a}`}z`, `p${`q`}r${b}`);";
6224+
/** @type {EXPECTED_ANY} */
6225+
const options = { format: { spidermonkey: true, code: true } };
6226+
const { code: printed, ast } = /** @type {EXPECTED_ANY} */ (
6227+
await minify(code, options)
6228+
);
6229+
expect(printed).toBe("console.log(`xy${a}z`,`pqr${b}`);");
6230+
const [first, second] = ast.body[0].expression.arguments;
6231+
expect(
6232+
[first, second].map((/** @type {EXPECTED_ANY} */ template) => [
6233+
template.quasis.map((/** @type {EXPECTED_ANY} */ quasi) => [
6234+
quasi.value.cooked,
6235+
quasi.tail
6236+
]),
6237+
template.expressions.length
6238+
])
6239+
).toEqual([
6240+
[
6241+
[
6242+
["xy", false],
6243+
["z", true]
6244+
],
6245+
1
6246+
],
6247+
[
6248+
[
6249+
["pqr", false],
6250+
["", true]
6251+
],
6252+
1
6253+
]
6254+
]);
6255+
const back = await minify(ast, {
6256+
compress: false,
6257+
mangle: false,
6258+
parse: { spidermonkey: true }
6259+
});
6260+
expect(back.code).toBe(printed);
6261+
await expect(terserReference().minify(code, options)).rejects.toThrow(
6262+
"to_mozilla_ast"
6263+
);
6264+
});
6265+
6266+
it("should read an anonymous default export, which terser throws on", async () => {
6267+
const { minify } = await load();
6268+
for (const code of [
6269+
"export default function (a) { return a; } console.log(1);",
6270+
"export default class { m() {} }",
6271+
"export default function* () {}",
6272+
"export default async function () {}"
6273+
]) {
6274+
for (const options of [
6275+
{ module: true },
6276+
{ module: true, compress: false, mangle: false },
6277+
{ module: true, toplevel: true, compress: { passes: 2 } }
6278+
]) {
6279+
const fromSource = await minify(code, options);
6280+
const fromTree = await minify(estree(code), {
6281+
...options,
6282+
parse: { spidermonkey: true }
6283+
});
6284+
expect(fromTree.code).toBe(fromSource.code);
6285+
}
6286+
await expect(
6287+
terserReference().minify(
6288+
estree(code),
6289+
/** @type {EXPECTED_ANY} */ ({
6290+
module: true,
6291+
parse: { spidermonkey: true }
6292+
})
6293+
)
6294+
).rejects.toThrow("definition");
6295+
}
6296+
});
6297+
});
6298+
61986299
describe("fields named as ESTree names them", () => {
61996300
// Each field the node classes take ESTree's name for, read and written
62006301
// by every phase: a loop, branch, call, generator, class, template, try.

0 commit comments

Comments
 (0)