Skip to content

Commit ee4b859

Browse files
fix(javascript): read a directive's spelling from an AST that states none
An AST webpack did not parse — a preparsed one, or whatever a custom `module.parser.javascript.parse` returns — may report a directive as a plain expression statement, so requiring the optional `directive` field stopped the prologue scan there and left the module non-strict. Recover the spelling from the literal itself for those trees: a range that does not start where the statement does is a parenthesized expression, and the raw text keeps an escape unexpanded.
1 parent fc21b55 commit ee4b859

10 files changed

Lines changed: 189 additions & 21 deletions

File tree

‎lib/UseStrictPlugin.js‎

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ const {
1212
} = require("./ModuleTypeConstants");
1313
const ConstDependency = require("./dependencies/ConstDependency");
1414

15-
/** @import { Directive } from "estree" */
1615
/** @import { JavascriptParserOptions } from "../declarations/WebpackOptions" */
1716
/** @import Compiler from "./Compiler" */
1817
/** @import { BuildInfo } from "./Module" */
@@ -38,17 +37,9 @@ class UseStrictPlugin {
3837
const handler = (parser, parserOptions) => {
3938
parser.hooks.program.tap(PLUGIN_NAME, (ast) => {
4039
for (const statement of ast.body) {
41-
if (
42-
statement.type !== "ExpressionStatement" ||
43-
/** @type {Directive} */ (statement).directive === undefined
44-
) {
45-
break;
46-
}
47-
if (
48-
/** @type {Directive} */ (statement).directive !== "use strict"
49-
) {
50-
continue;
51-
}
40+
const directive = parser.getDirective(statement);
41+
if (directive === undefined) break;
42+
if (directive !== "use strict") continue;
5243
// Remove "use strict" expression. It will be added later by the renderer again.
5344
// This is necessary in order to not break the strict mode when webpack prepends code.
5445
// @see https://github.com/webpack/webpack/issues/1970

‎lib/javascript/JavascriptParser.js‎

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5887,6 +5887,37 @@ class JavascriptParser extends Parser {
58875887
return oldScope;
58885888
}
58895889

5890+
/**
5891+
* The directive a statement spells, or `undefined` when it is not one. An
5892+
* AST webpack did not parse may leave the metadata off a directive, so the
5893+
* spelling is recovered from the literal itself there.
5894+
* @param {Directive | Statement | ModuleDeclaration} statement statement
5895+
* @returns {string | undefined} the spelling between the quotes
5896+
*/
5897+
getDirective(statement) {
5898+
if (statement.type !== "ExpressionStatement") return undefined;
5899+
const directive = /** @type {Directive} */ (statement).directive;
5900+
if (directive !== undefined || this._hasParserRecord) return directive;
5901+
const expression = statement.expression;
5902+
if (expression.type !== "Literal" || typeof expression.value !== "string") {
5903+
return undefined;
5904+
}
5905+
// a parenthesized string is an expression rather than a directive, and
5906+
// only the statement says so — the literal starts inside the parentheses
5907+
if (
5908+
statement.range !== undefined &&
5909+
expression.range !== undefined &&
5910+
statement.range[0] !== expression.range[0]
5911+
) {
5912+
return undefined;
5913+
}
5914+
// the raw text keeps an escape unexpanded, which is what separates a
5915+
// directive from a string that merely reads like one
5916+
return expression.raw === undefined
5917+
? expression.value
5918+
: expression.raw.slice(1, -1);
5919+
}
5920+
58905921
/**
58915922
* Processes the provided statement.
58925923
* @param {(Directive | Statement | ModuleDeclaration)[]} statements statements
@@ -5905,15 +5936,9 @@ class JavascriptParser extends Parser {
59055936
this.scope.isAsmJs = true;
59065937
}
59075938
for (const directiveStatement of statements) {
5908-
if (
5909-
directiveStatement.type !== "ExpressionStatement" ||
5910-
/** @type {Directive} */ (directiveStatement).directive === undefined
5911-
) {
5912-
break;
5913-
}
5914-
if (
5915-
/** @type {Directive} */ (directiveStatement).directive === "use strict"
5916-
) {
5939+
const directive = this.getDirective(directiveStatement);
5940+
if (directive === undefined) break;
5941+
if (directive === "use strict") {
59175942
this.scope.isStrict = true;
59185943
break;
59195944
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
"use\x20strict";
2+
module.exports = [provided, (function () { return this === undefined; })()];
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
it("should detect a strict directive an AST does not mark as one", () => {
2+
expect(require("./strict")).toEqual([42, true]);
3+
});
4+
5+
it("should keep rejecting strings that only read like a directive", () => {
6+
expect(require("./escaped")).toEqual([42, false]);
7+
expect(require("./parenthesized")).toEqual([42, false]);
8+
});
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
("use strict");
2+
module.exports = [provided, (function () { return this === undefined; })()];
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const value = 42;
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
"use strict";
2+
module.exports = [provided, (function () { return this === undefined; })()];
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
"use strict";
2+
3+
const acorn = require("acorn");
4+
const webpack = require("../../../../");
5+
6+
/**
7+
* @import {
8+
* ParseOptions,
9+
* ParseResult
10+
* } from "../../../../lib/javascript/JavascriptParser"
11+
*/
12+
13+
/**
14+
* Drops the optional directive metadata, as a parser that reports a directive
15+
* as a plain expression statement does.
16+
* @param {EXPECTED_ANY} node node to strip
17+
* @returns {void}
18+
*/
19+
const stripDirectives = (node) => {
20+
if (Array.isArray(node)) {
21+
for (const item of node) stripDirectives(item);
22+
return;
23+
}
24+
if (node === null || typeof node !== "object") return;
25+
if (node.type === "ExpressionStatement") node.directive = undefined;
26+
for (const key of Object.keys(node)) stripDirectives(node[key]);
27+
};
28+
29+
/** @type {import("../../../../").Configuration} */
30+
module.exports = {
31+
plugins: [
32+
new webpack.ProvidePlugin({
33+
provided: [require.resolve("./provided"), "value"]
34+
})
35+
],
36+
module: {
37+
parser: {
38+
javascript: {
39+
/**
40+
* A parser whose AST states no directive, so webpack reads the
41+
* spelling out of the literal itself.
42+
* @param {string} code source code
43+
* @param {ParseOptions} options parse options
44+
* @returns {ParseResult} parse result
45+
*/
46+
parse: (code, options) => {
47+
/** @type {ParseResult["comments"]} */
48+
const comments = [];
49+
const ast = acorn.parse(code, {
50+
sourceType: options.sourceType,
51+
ecmaVersion: "latest",
52+
locations: false,
53+
ranges: true,
54+
allowHashBang: true,
55+
allowReturnOutsideFunction: options.allowReturnOutsideFunction,
56+
onComment: /** @type {EXPECTED_ANY} */ (comments)
57+
});
58+
stripDirectives(ast);
59+
return {
60+
ast: /** @type {ParseResult["ast"]} */ (ast),
61+
comments
62+
};
63+
}
64+
}
65+
}
66+
},
67+
optimization: {
68+
minimize: false
69+
}
70+
};

‎test/unitCases/JavascriptParser.unittest.js‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,37 @@ describe("JavascriptParser", () => {
4444
expect(modes).toEqual([expected]);
4545
}
4646
});
47+
48+
it.each([
49+
['"use strict";', true],
50+
['"custom";', false]
51+
])("reads %s from an AST that states no directive", (directive, expected) => {
52+
const source = `${directive} probe();`;
53+
const parser = new JavascriptParser("script");
54+
const state =
55+
/** @type {import("../../lib/Parser").ParserState} */
56+
(/** @type {unknown} */ ({ source }));
57+
/** @type {EXPECTED_ANY} */
58+
let ast;
59+
parser.hooks.program.tap("test", (program) => {
60+
ast = program;
61+
});
62+
parser.parse(source, state);
63+
// a parser of the caller's own may report a directive as a plain
64+
// expression statement, and may carry no raw text either
65+
for (const statement of ast.body) {
66+
statement.directive = undefined;
67+
if (statement.expression) statement.expression.raw = undefined;
68+
}
69+
ast.comments = [];
70+
/** @type {boolean[]} */
71+
const modes = [];
72+
parser.hooks.call.for("probe").tap("test", () => {
73+
modes.push(parser.scope.isStrict);
74+
});
75+
parser.parse(ast, state);
76+
expect(modes).toEqual([expected]);
77+
});
4778
});
4879

4980
/* eslint-disable no-unused-vars */

‎types.d.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14373,6 +14373,42 @@ declare class JavascriptParser extends ParserClass {
1437314373
*/
1437414374
inBlockScope(fn: () => void, inExecutedPath?: boolean): void;
1437514375

14376+
/**
14377+
* The directive a statement spells, or `undefined` when it is not one. An
14378+
* AST webpack did not parse may leave the metadata off a directive, so the
14379+
* spelling is recovered from the literal itself there.
14380+
*/
14381+
getDirective(
14382+
statement:
14383+
| ImportDeclaration
14384+
| ExportNamedDeclaration
14385+
| ExportAllDeclaration
14386+
| FunctionDeclaration
14387+
| VariableDeclaration
14388+
| ClassDeclaration
14389+
| ExpressionStatement
14390+
| BlockStatement
14391+
| StaticBlock
14392+
| EmptyStatement
14393+
| DebuggerStatement
14394+
| WithStatement
14395+
| ReturnStatement
14396+
| LabeledStatement
14397+
| BreakStatement
14398+
| ContinueStatement
14399+
| IfStatement
14400+
| SwitchStatement
14401+
| ThrowStatement
14402+
| TryStatement
14403+
| WhileStatement
14404+
| DoWhileStatement
14405+
| ForStatement
14406+
| ForInStatement
14407+
| ForOfStatement
14408+
| ExportDefaultDeclaration
14409+
| Directive
14410+
): undefined | string;
14411+
1437614412
/**
1437714413
* Processes the provided statement.
1437814414
*/

0 commit comments

Comments
 (0)