storm-lua-minify 0.3.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -41
- package/dist/aggregateSpecialization.js +406 -0
- package/dist/ast2lua.js +156 -68
- package/dist/astWalk.js +162 -0
- package/dist/callGraph.js +372 -0
- package/dist/cli.js +53 -58
- package/dist/cliOptions.js +36 -0
- package/dist/cliProgress.js +87 -0
- package/dist/config.js +73 -0
- package/dist/constantFold.js +798 -0
- package/dist/controlFlow.js +266 -0
- package/dist/functionRewrites.js +580 -0
- package/dist/generatedAst.js +108 -0
- package/dist/generatedNode.js +23 -0
- package/dist/interproceduralAnalysis.js +842 -0
- package/dist/interproceduralConstants.js +120 -0
- package/dist/luaString.js +157 -0
- package/dist/minifier.js +1178 -44
- package/dist/optimizerAnalysis.js +43 -0
- package/dist/optimizerDiagnostics.js +65 -0
- package/dist/optimizerFacts.js +529 -0
- package/dist/optimizerPass.js +96 -0
- package/dist/optimizerTransaction.js +56 -0
- package/dist/optimizerValueDomain.js +180 -0
- package/dist/options.js +233 -0
- package/dist/progress.js +2 -0
- package/dist/removeUnused.js +145 -0
- package/dist/renamer.js +223 -54
- package/dist/resolver.js +28 -11
- package/dist/runtimeEnvironment.js +105 -0
- package/dist/sourceMetadata.js +314 -0
- package/dist/statementDataflow.js +259 -0
- package/dist/statementScheduler.js +595 -0
- package/dist/symbolLiveness.js +92 -0
- package/dist/tableEffects.js +356 -0
- package/dist/transform.js +10 -371
- package/dist/valueFlow.js +409 -0
- package/dist/wholeProgramExports.js +646 -0
- package/dist/wholeProgramFieldRenames.js +583 -0
- package/dist/wholeProgramFields.js +672 -0
- package/dist/wholeProgramObjects.js +783 -0
- package/package.json +11 -2
- package/dist/index.js +0 -27
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.removeUnusedLocals = removeUnusedLocals;
|
|
4
|
+
function rangeOf(node) {
|
|
5
|
+
return node.range;
|
|
6
|
+
}
|
|
7
|
+
function nestedBodies(statement) {
|
|
8
|
+
switch (statement.type) {
|
|
9
|
+
case "DoStatement":
|
|
10
|
+
case "WhileStatement":
|
|
11
|
+
case "RepeatStatement":
|
|
12
|
+
case "FunctionDeclaration":
|
|
13
|
+
case "ForNumericStatement":
|
|
14
|
+
case "ForGenericStatement":
|
|
15
|
+
return [statement.body];
|
|
16
|
+
case "IfStatement":
|
|
17
|
+
return statement.clauses.map((clause) => clause.body);
|
|
18
|
+
default:
|
|
19
|
+
return [];
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function isStatementCall(expression) {
|
|
23
|
+
return (expression.type === "CallExpression" ||
|
|
24
|
+
expression.type === "TableCallExpression" ||
|
|
25
|
+
expression.type === "StringCallExpression");
|
|
26
|
+
}
|
|
27
|
+
function callStatement(expression) {
|
|
28
|
+
return {
|
|
29
|
+
type: "CallStatement",
|
|
30
|
+
expression,
|
|
31
|
+
loc: expression.loc,
|
|
32
|
+
range: rangeOf(expression),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function hasExternalReference(statement, references) {
|
|
36
|
+
const range = rangeOf(statement);
|
|
37
|
+
if (!range)
|
|
38
|
+
return references.length > 0;
|
|
39
|
+
return references.some((reference) => {
|
|
40
|
+
const position = rangeOf(reference)?.[0];
|
|
41
|
+
return (position === undefined || position < range[0] || position >= range[1]);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function removeFromBlock(body, resolved, metadata, facts, onRemoveLocalFunction, options = { removeLocals: true, removeFunctions: true }) {
|
|
45
|
+
let changed = false;
|
|
46
|
+
body.forEach((statement) => {
|
|
47
|
+
nestedBodies(statement).forEach((nested) => {
|
|
48
|
+
changed =
|
|
49
|
+
removeFromBlock(nested, resolved, metadata, facts, onRemoveLocalFunction, options) || changed;
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
const replacements = new Map();
|
|
53
|
+
body.forEach((statement) => {
|
|
54
|
+
if (metadata.annotationsOf(statement).keep)
|
|
55
|
+
return;
|
|
56
|
+
if (options.removeFunctions &&
|
|
57
|
+
statement.type === "FunctionDeclaration" &&
|
|
58
|
+
statement.isLocal &&
|
|
59
|
+
statement.identifier?.type === "Identifier") {
|
|
60
|
+
const symbol = resolved.symbolOf(statement.identifier);
|
|
61
|
+
if (symbol && !hasExternalReference(statement, symbol.references)) {
|
|
62
|
+
onRemoveLocalFunction?.(statement);
|
|
63
|
+
changed = true;
|
|
64
|
+
replacements.set(statement, []);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (!options.removeLocals || statement.type !== "LocalStatement")
|
|
69
|
+
return;
|
|
70
|
+
const unused = statement.variables.map((variable) => {
|
|
71
|
+
const symbol = resolved.symbolOf(variable);
|
|
72
|
+
return Boolean(symbol && symbol.references.length === 0);
|
|
73
|
+
});
|
|
74
|
+
if (!unused.some(Boolean))
|
|
75
|
+
return;
|
|
76
|
+
if (unused.every(Boolean)) {
|
|
77
|
+
if (statement.init.every((expression) => facts.discardabilityOf(expression).discardable ||
|
|
78
|
+
isStatementCall(expression))) {
|
|
79
|
+
const calls = statement.init.filter(isStatementCall).map(callStatement);
|
|
80
|
+
changed = true;
|
|
81
|
+
replacements.set(statement, calls);
|
|
82
|
+
}
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
let variables = [...statement.variables];
|
|
86
|
+
let init = [...statement.init];
|
|
87
|
+
let unusedAfterPairRemoval = [...unused];
|
|
88
|
+
// 初期値なしなら全変数の値はnilで固定され、位置対応を維持する必要がない。
|
|
89
|
+
if (init.length === 0) {
|
|
90
|
+
variables = variables.filter((_, index) => !unused[index]);
|
|
91
|
+
unusedAfterPairRemoval = unused.filter((value) => !value);
|
|
92
|
+
}
|
|
93
|
+
// 要素数が一致するときだけ、変数とRHSの対応を崩さず安全なペアを抜ける。
|
|
94
|
+
if (init.length > 0 && variables.length === init.length) {
|
|
95
|
+
const retainedIndexes = variables
|
|
96
|
+
.map((_, index) => index)
|
|
97
|
+
.filter((index) => !(unused[index] && facts.discardabilityOf(init[index]).discardable));
|
|
98
|
+
variables = retainedIndexes.map((index) => variables[index]);
|
|
99
|
+
init = retainedIndexes.map((index) => init[index]);
|
|
100
|
+
unusedAfterPairRemoval = retainedIndexes.map((index) => unused[index]);
|
|
101
|
+
}
|
|
102
|
+
// 末尾の未使用名は、対応RHSを余剰式として評価させたまま名前だけ除ける。
|
|
103
|
+
let retainedVariableCount = variables.length;
|
|
104
|
+
while (retainedVariableCount > 0 &&
|
|
105
|
+
unusedAfterPairRemoval[retainedVariableCount - 1]) {
|
|
106
|
+
retainedVariableCount--;
|
|
107
|
+
}
|
|
108
|
+
variables = variables.slice(0, retainedVariableCount);
|
|
109
|
+
if (variables.length === statement.variables.length)
|
|
110
|
+
return;
|
|
111
|
+
changed = true;
|
|
112
|
+
const replacement = {
|
|
113
|
+
...statement,
|
|
114
|
+
variables,
|
|
115
|
+
init,
|
|
116
|
+
};
|
|
117
|
+
replacements.set(statement, [replacement]);
|
|
118
|
+
});
|
|
119
|
+
if (replacements.size > 0) {
|
|
120
|
+
const nextBody = [];
|
|
121
|
+
body.forEach((statement, index) => {
|
|
122
|
+
const replacement = replacements.get(statement);
|
|
123
|
+
if (!replacement) {
|
|
124
|
+
nextBody.push(statement);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (replacement.length > 0) {
|
|
128
|
+
metadata.replaceStatement(statement, replacement);
|
|
129
|
+
nextBody.push(...replacement);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const next = body.slice(index + 1).find((candidate) => {
|
|
133
|
+
const candidateReplacement = replacements.get(candidate);
|
|
134
|
+
return !candidateReplacement || candidateReplacement.length > 0;
|
|
135
|
+
});
|
|
136
|
+
const nextReplacement = next ? replacements.get(next) : undefined;
|
|
137
|
+
metadata.removeStatement(statement, nextReplacement?.[0] ?? next);
|
|
138
|
+
});
|
|
139
|
+
body.splice(0, body.length, ...nextBody);
|
|
140
|
+
}
|
|
141
|
+
return changed;
|
|
142
|
+
}
|
|
143
|
+
function removeUnusedLocals(chunk, resolved, metadata, facts, onRemoveLocalFunction, options) {
|
|
144
|
+
return removeFromBlock(chunk.body, resolved, metadata, facts, onRemoveLocalFunction, options);
|
|
145
|
+
}
|
package/dist/renamer.js
CHANGED
|
@@ -3,7 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.isAvailable = isAvailable;
|
|
4
4
|
exports.generateCandidate = generateCandidate;
|
|
5
5
|
exports.assignRenames = assignRenames;
|
|
6
|
+
const resolver_1 = require("./resolver");
|
|
6
7
|
const ast2lua_1 = require("./ast2lua");
|
|
8
|
+
const controlFlow_1 = require("./controlFlow");
|
|
9
|
+
const optimizerFacts_1 = require("./optimizerFacts");
|
|
10
|
+
const symbolLiveness_1 = require("./symbolLiveness");
|
|
7
11
|
function isAvailable(id, reserved) {
|
|
8
12
|
return id !== "self" && !(0, ast2lua_1.isKeyword)(id) && !reserved.has(id);
|
|
9
13
|
}
|
|
@@ -21,62 +25,33 @@ function generateCandidate(counter) {
|
|
|
21
25
|
}
|
|
22
26
|
return id;
|
|
23
27
|
}
|
|
24
|
-
|
|
25
|
-
* スコープ木のDFSでシンボルごとにスロット番号を割り当てる。
|
|
26
|
-
* `active`は祖先スコープ(自分を含む)で既に使われているスロットの集合。
|
|
27
|
-
* 兄弟スコープには同じ`active`のコピーが渡されるため、互いの割当は影響しない。
|
|
28
|
-
*/
|
|
29
|
-
function assignSlots(scope, active) {
|
|
30
|
-
const slotOf = new Map();
|
|
31
|
-
const used = new Set(active);
|
|
32
|
-
scope.symbols.forEach((symbol) => {
|
|
33
|
-
let slot = 0;
|
|
34
|
-
while (used.has(slot)) {
|
|
35
|
-
slot++;
|
|
36
|
-
}
|
|
37
|
-
slotOf.set(symbol, slot);
|
|
38
|
-
used.add(slot);
|
|
39
|
-
});
|
|
40
|
-
scope.children.forEach((child) => {
|
|
41
|
-
assignSlots(child, used).forEach((slot, symbol) => {
|
|
42
|
-
slotOf.set(symbol, slot);
|
|
43
|
-
});
|
|
44
|
-
});
|
|
45
|
-
return slotOf;
|
|
46
|
-
}
|
|
47
|
-
function assignRenames(resolveResult, reserved,
|
|
28
|
+
function assignRenames(chunk, resolveResult, reserved,
|
|
48
29
|
// #8a: プログラム全体を横断して決定されたグローバル識別子の短縮名。
|
|
49
30
|
// 全モジュールに対して同じマップを渡すことで、モジュールをまたいで
|
|
50
31
|
// 共有される1つのランタイム束縛に一貫した短縮名を割り当てられる。
|
|
51
|
-
globalRenames) {
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
const
|
|
74
|
-
slotOf.forEach((slot, symbol) => {
|
|
75
|
-
const name = nameOfSlot.get(slot);
|
|
76
|
-
if (name !== undefined) {
|
|
77
|
-
nameOfSymbol.set(symbol, name);
|
|
78
|
-
}
|
|
79
|
-
});
|
|
32
|
+
globalRenames, keepNames = new Set(), options = {}) {
|
|
33
|
+
const unavailableNames = new Set(reserved);
|
|
34
|
+
keepNames.forEach((symbol) => unavailableNames.add(symbol.name));
|
|
35
|
+
const variables = options.renameLocals === false
|
|
36
|
+
? []
|
|
37
|
+
: resolveResult.symbols.filter((symbol) => symbol.kind !== "label" &&
|
|
38
|
+
!symbol.implicit &&
|
|
39
|
+
!keepNames.has(symbol));
|
|
40
|
+
const variableGraph = buildVariableInterference(chunk, resolveResult, variables, options.allowLocalNameReuse === true, options.analysis);
|
|
41
|
+
const variableColors = colorGraph(variableGraph);
|
|
42
|
+
const variableNames = assignColorNames(variableColors, unavailableNames);
|
|
43
|
+
// Labels have a separate Lua namespace. Color them independently so a label
|
|
44
|
+
// and a local may share a short spelling, while usedNames still reserves the
|
|
45
|
+
// spelling against labels from subsequently spliced modules.
|
|
46
|
+
const labels = options.renameLocals === false
|
|
47
|
+
? []
|
|
48
|
+
: resolveResult.symbols.filter((symbol) => symbol.kind === "label" &&
|
|
49
|
+
symbol.name !== "self" &&
|
|
50
|
+
!keepNames.has(symbol));
|
|
51
|
+
const labelNames = assignColorNames(colorGraph(buildLexicalGraph(labels, false)), unavailableNames);
|
|
52
|
+
const nameOfSymbol = new Map([...variableNames, ...labelNames]);
|
|
53
|
+
validateBindings(chunk, resolveResult, nameOfSymbol, globalRenames);
|
|
54
|
+
const usedNames = new Set(nameOfSymbol.values());
|
|
80
55
|
return {
|
|
81
56
|
nameOf: (identifier) => {
|
|
82
57
|
// メソッド定義の暗黙のselfパラメータは慣習的な名前のため常に維持する
|
|
@@ -96,6 +71,200 @@ globalRenames) {
|
|
|
96
71
|
}
|
|
97
72
|
return undefined;
|
|
98
73
|
},
|
|
99
|
-
usedNames
|
|
74
|
+
usedNames,
|
|
100
75
|
};
|
|
101
76
|
}
|
|
77
|
+
function buildVariableInterference(chunk, resolved, symbols, allowLocalNameReuse, analysis) {
|
|
78
|
+
const graph = mutableGraph(symbols);
|
|
79
|
+
const facts = analysis?.facts ?? (0, optimizerFacts_1.analyzeOptimizerFacts)(chunk, resolved);
|
|
80
|
+
const liveness = analysis?.liveness ??
|
|
81
|
+
(0, symbolLiveness_1.analyzeSymbolLiveness)((0, controlFlow_1.analyzeControlFlow)(chunk, resolved), facts);
|
|
82
|
+
if (facts.generation !== liveness.controlFlow.version)
|
|
83
|
+
throw new Error("Identifier coloring requires one AST generation");
|
|
84
|
+
liveness.controlFlow.nodes.forEach((node) => {
|
|
85
|
+
addClique(graph, liveness.liveIn(node));
|
|
86
|
+
addClique(graph, liveness.liveOut(node));
|
|
87
|
+
liveness.defs(node).forEach((definition) => {
|
|
88
|
+
liveness.liveOut(node).forEach((live) => {
|
|
89
|
+
addEdge(graph, definition, live);
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
// Parameters, generic-for variables, and multi-local declarations bind as a
|
|
94
|
+
// group. Giving two members one spelling would make only the last binding
|
|
95
|
+
// addressable after reparsing even if one member happens to be unused.
|
|
96
|
+
const declarationsByOwner = new Map();
|
|
97
|
+
symbols.forEach((symbol) => {
|
|
98
|
+
const declaration = facts
|
|
99
|
+
.operationsOfSymbol(symbol)
|
|
100
|
+
.find((operation) => operation.kind === "declare" &&
|
|
101
|
+
operation.origin === symbol.declaration);
|
|
102
|
+
if (!declaration)
|
|
103
|
+
return;
|
|
104
|
+
const group = declarationsByOwner.get(declaration.owner) ?? [];
|
|
105
|
+
group.push(symbol);
|
|
106
|
+
declarationsByOwner.set(declaration.owner, group);
|
|
107
|
+
});
|
|
108
|
+
declarationsByOwner.forEach((group) => {
|
|
109
|
+
addClique(graph, group);
|
|
110
|
+
});
|
|
111
|
+
// A captured binding can be shadowed inside the closure by any same-scope
|
|
112
|
+
// declaration whose emitted spelling matches it (notably `local function`).
|
|
113
|
+
// Extending this lexical interference across the whole declaring scope is
|
|
114
|
+
// conservative, deterministic, and leaves ordinary non-captured locals free
|
|
115
|
+
// to reuse names according to liveness.
|
|
116
|
+
symbols.forEach((symbol) => {
|
|
117
|
+
const captured = facts
|
|
118
|
+
.operationsOfSymbol(symbol)
|
|
119
|
+
.some((operation) => "location" in operation && operation.location.kind === "upvalue");
|
|
120
|
+
if (!captured)
|
|
121
|
+
return;
|
|
122
|
+
symbols.forEach((other) => {
|
|
123
|
+
if (other.scope === symbol.scope)
|
|
124
|
+
addEdge(graph, symbol, other);
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
addLexicalEdges(graph, symbols, allowLocalNameReuse);
|
|
128
|
+
return graph;
|
|
129
|
+
}
|
|
130
|
+
function buildLexicalGraph(symbols, allowSameScopeReuse) {
|
|
131
|
+
const graph = mutableGraph(symbols);
|
|
132
|
+
addLexicalEdges(graph, symbols, allowSameScopeReuse);
|
|
133
|
+
return graph;
|
|
134
|
+
}
|
|
135
|
+
function mutableGraph(symbols) {
|
|
136
|
+
return new Map(symbols.map((symbol) => [symbol, new Set()]));
|
|
137
|
+
}
|
|
138
|
+
function addLexicalEdges(graph, symbols, allowSameScopeReuse) {
|
|
139
|
+
for (let left = 0; left < symbols.length; left++) {
|
|
140
|
+
for (let right = left + 1; right < symbols.length; right++) {
|
|
141
|
+
const first = symbols[left];
|
|
142
|
+
const last = symbols[right];
|
|
143
|
+
if (isAncestor(first.scope, last.scope) ||
|
|
144
|
+
isAncestor(last.scope, first.scope) ||
|
|
145
|
+
(!allowSameScopeReuse && first.scope === last.scope))
|
|
146
|
+
addEdge(graph, first, last);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function isAncestor(ancestor, descendant) {
|
|
151
|
+
if (ancestor === descendant)
|
|
152
|
+
return false;
|
|
153
|
+
for (let current = descendant.parent; current; current = current.parent)
|
|
154
|
+
if (current === ancestor)
|
|
155
|
+
return true;
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
function addClique(graph, symbols) {
|
|
159
|
+
const present = [...symbols].filter((symbol) => graph.has(symbol));
|
|
160
|
+
for (let left = 0; left < present.length; left++)
|
|
161
|
+
for (let right = left + 1; right < present.length; right++)
|
|
162
|
+
addEdge(graph, present[left], present[right]);
|
|
163
|
+
}
|
|
164
|
+
function addEdge(graph, first, last) {
|
|
165
|
+
if (first === last || !graph.has(first) || !graph.has(last))
|
|
166
|
+
return;
|
|
167
|
+
graph.get(first)?.add(last);
|
|
168
|
+
graph.get(last)?.add(first);
|
|
169
|
+
}
|
|
170
|
+
/** Deterministic weighted DSATUR coloring. */
|
|
171
|
+
function colorGraph(graph) {
|
|
172
|
+
const colors = new Map();
|
|
173
|
+
while (colors.size < graph.size) {
|
|
174
|
+
const remaining = [...graph.keys()].filter((symbol) => !colors.has(symbol));
|
|
175
|
+
remaining.sort((left, right) => {
|
|
176
|
+
const saturationDifference = saturation(graph, colors, right) - saturation(graph, colors, left);
|
|
177
|
+
if (saturationDifference !== 0)
|
|
178
|
+
return saturationDifference;
|
|
179
|
+
const weightDifference = weightOf(right) - weightOf(left);
|
|
180
|
+
if (weightDifference !== 0)
|
|
181
|
+
return weightDifference;
|
|
182
|
+
const degreeDifference = (graph.get(right)?.size ?? 0) - (graph.get(left)?.size ?? 0);
|
|
183
|
+
return degreeDifference !== 0 ? degreeDifference : left.id - right.id;
|
|
184
|
+
});
|
|
185
|
+
const symbol = remaining[0];
|
|
186
|
+
const unavailable = new Set([...(graph.get(symbol) ?? [])].flatMap((neighbor) => {
|
|
187
|
+
const color = colors.get(neighbor);
|
|
188
|
+
return color === undefined ? [] : [color];
|
|
189
|
+
}));
|
|
190
|
+
let color = 0;
|
|
191
|
+
while (unavailable.has(color))
|
|
192
|
+
color++;
|
|
193
|
+
colors.set(symbol, color);
|
|
194
|
+
}
|
|
195
|
+
return colors;
|
|
196
|
+
}
|
|
197
|
+
function saturation(graph, colors, symbol) {
|
|
198
|
+
return new Set([...(graph.get(symbol) ?? [])].flatMap((neighbor) => {
|
|
199
|
+
const color = colors.get(neighbor);
|
|
200
|
+
return color === undefined ? [] : [color];
|
|
201
|
+
})).size;
|
|
202
|
+
}
|
|
203
|
+
function weightOf(symbol) {
|
|
204
|
+
return symbol.references.length + 1;
|
|
205
|
+
}
|
|
206
|
+
function assignColorNames(colors, reserved) {
|
|
207
|
+
const unavailable = new Set(reserved);
|
|
208
|
+
const weightByColor = new Map();
|
|
209
|
+
const firstSymbolByColor = new Map();
|
|
210
|
+
colors.forEach((color, symbol) => {
|
|
211
|
+
weightByColor.set(color, (weightByColor.get(color) ?? 0) + weightOf(symbol));
|
|
212
|
+
firstSymbolByColor.set(color, Math.min(firstSymbolByColor.get(color) ?? symbol.id, symbol.id));
|
|
213
|
+
});
|
|
214
|
+
const orderedColors = [...weightByColor.keys()].sort((left, right) => (weightByColor.get(right) ?? 0) - (weightByColor.get(left) ?? 0) ||
|
|
215
|
+
(firstSymbolByColor.get(left) ?? 0) -
|
|
216
|
+
(firstSymbolByColor.get(right) ?? 0));
|
|
217
|
+
const nameByColor = new Map();
|
|
218
|
+
let counter = 0;
|
|
219
|
+
orderedColors.forEach((color) => {
|
|
220
|
+
let candidate;
|
|
221
|
+
do
|
|
222
|
+
candidate = generateCandidate(counter++);
|
|
223
|
+
while (!isAvailable(candidate, unavailable));
|
|
224
|
+
unavailable.add(candidate);
|
|
225
|
+
nameByColor.set(color, candidate);
|
|
226
|
+
});
|
|
227
|
+
// Every candidate is an identifier token and keywords are excluded, so the
|
|
228
|
+
// separator cost around each occurrence is invariant across candidates.
|
|
229
|
+
// Occurrence count therefore gives the exact candidate-dependent byte cost.
|
|
230
|
+
const result = new Map();
|
|
231
|
+
colors.forEach((color, symbol) => {
|
|
232
|
+
const name = nameByColor.get(color);
|
|
233
|
+
if (name === undefined)
|
|
234
|
+
throw new Error("Colored symbol has no name");
|
|
235
|
+
result.set(symbol, name);
|
|
236
|
+
});
|
|
237
|
+
return result;
|
|
238
|
+
}
|
|
239
|
+
function validateBindings(chunk, original, names, globalRenames) {
|
|
240
|
+
const recolored = (0, resolver_1.resolveScopes)(chunk, {
|
|
241
|
+
identifierName: (identifier) => {
|
|
242
|
+
const symbol = original.symbolOf(identifier);
|
|
243
|
+
if (symbol)
|
|
244
|
+
return names.get(symbol) ?? identifier.name;
|
|
245
|
+
return original.isGlobalReference(identifier)
|
|
246
|
+
? (globalRenames?.get(identifier.name) ?? identifier.name)
|
|
247
|
+
: identifier.name;
|
|
248
|
+
},
|
|
249
|
+
});
|
|
250
|
+
original.symbols.forEach((symbol) => {
|
|
251
|
+
if (symbol.implicit) {
|
|
252
|
+
symbol.references.forEach((identifier) => {
|
|
253
|
+
const rebound = recolored.symbolOf(identifier);
|
|
254
|
+
if (!rebound?.implicit || rebound.name !== symbol.name)
|
|
255
|
+
throw new Error(`Identifier coloring changed implicit binding for symbol ${String(symbol.id)}`);
|
|
256
|
+
});
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
[symbol.declaration, ...symbol.references].forEach((identifier) => {
|
|
260
|
+
if (recolored.symbolOf(identifier)?.declaration !== symbol.declaration)
|
|
261
|
+
throw new Error(`Identifier coloring changed binding for symbol ${String(symbol.id)}`);
|
|
262
|
+
});
|
|
263
|
+
});
|
|
264
|
+
original.globals.forEach((binding) => {
|
|
265
|
+
binding.references.forEach((identifier) => {
|
|
266
|
+
if (!recolored.isGlobalReference(identifier))
|
|
267
|
+
throw new Error(`Identifier coloring captured global ${binding.name}`);
|
|
268
|
+
});
|
|
269
|
+
});
|
|
270
|
+
}
|
package/dist/resolver.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.resolveScopes = resolveScopes;
|
|
4
|
-
function resolveScopes(chunk) {
|
|
4
|
+
function resolveScopes(chunk, options = {}) {
|
|
5
5
|
let nextSymbolId = 0;
|
|
6
6
|
const allSymbols = [];
|
|
7
7
|
const globals = new Map();
|
|
8
8
|
const identifierSymbols = new WeakMap();
|
|
9
9
|
const globalReferenceNodes = new WeakSet();
|
|
10
|
+
const functionScopes = new WeakMap();
|
|
11
|
+
const identifierName = options.identifierName ??
|
|
12
|
+
((identifier) => identifier.name);
|
|
10
13
|
function createScope(kind, parent) {
|
|
11
14
|
const scope = {
|
|
12
15
|
kind,
|
|
@@ -19,33 +22,36 @@ function resolveScopes(chunk) {
|
|
|
19
22
|
parent?.children.push(scope);
|
|
20
23
|
return scope;
|
|
21
24
|
}
|
|
22
|
-
function declare(scope, node, kind) {
|
|
25
|
+
function declare(scope, node, kind, implicit = false) {
|
|
26
|
+
const name = identifierName(node);
|
|
23
27
|
const symbol = {
|
|
24
28
|
id: nextSymbolId++,
|
|
25
|
-
name
|
|
29
|
+
name,
|
|
26
30
|
kind,
|
|
27
31
|
scope,
|
|
28
32
|
declaration: node,
|
|
29
33
|
references: [],
|
|
34
|
+
...(implicit ? { implicit: true } : {}),
|
|
30
35
|
};
|
|
31
36
|
// 同名の再宣言はスコープ内の以後の参照から見た束縛を上書きする(Luaの通常のシャドーイング)
|
|
32
37
|
scope.symbols.push(symbol);
|
|
33
|
-
scope.bindings.set(
|
|
38
|
+
scope.bindings.set(name, symbol);
|
|
34
39
|
allSymbols.push(symbol);
|
|
35
40
|
identifierSymbols.set(node, symbol);
|
|
36
41
|
return symbol;
|
|
37
42
|
}
|
|
38
43
|
function declareLabel(scope, node) {
|
|
44
|
+
const name = identifierName(node);
|
|
39
45
|
const symbol = {
|
|
40
46
|
id: nextSymbolId++,
|
|
41
|
-
name
|
|
47
|
+
name,
|
|
42
48
|
kind: "label",
|
|
43
49
|
scope,
|
|
44
50
|
declaration: node,
|
|
45
51
|
references: [],
|
|
46
52
|
};
|
|
47
53
|
scope.symbols.push(symbol);
|
|
48
|
-
scope.labels.set(
|
|
54
|
+
scope.labels.set(name, symbol);
|
|
49
55
|
allSymbols.push(symbol);
|
|
50
56
|
identifierSymbols.set(node, symbol);
|
|
51
57
|
return symbol;
|
|
@@ -69,16 +75,17 @@ function resolveScopes(chunk) {
|
|
|
69
75
|
return undefined;
|
|
70
76
|
}
|
|
71
77
|
function reference(scope, node, isWrite = false) {
|
|
72
|
-
const
|
|
78
|
+
const name = identifierName(node);
|
|
79
|
+
const symbol = lookupBinding(scope, name);
|
|
73
80
|
if (symbol) {
|
|
74
81
|
symbol.references.push(node);
|
|
75
82
|
identifierSymbols.set(node, symbol);
|
|
76
83
|
return;
|
|
77
84
|
}
|
|
78
|
-
let binding = globals.get(
|
|
85
|
+
let binding = globals.get(name);
|
|
79
86
|
if (!binding) {
|
|
80
|
-
binding = { name
|
|
81
|
-
globals.set(
|
|
87
|
+
binding = { name, references: [], writes: [] };
|
|
88
|
+
globals.set(name, binding);
|
|
82
89
|
}
|
|
83
90
|
binding.references.push(node);
|
|
84
91
|
if (isWrite) {
|
|
@@ -188,7 +195,7 @@ function resolveScopes(chunk) {
|
|
|
188
195
|
// hoistLabelsで宣言済みのため、ここでは何もしない
|
|
189
196
|
return;
|
|
190
197
|
case "GotoStatement": {
|
|
191
|
-
const symbol = lookupLabel(scope, statement.label
|
|
198
|
+
const symbol = lookupLabel(scope, identifierName(statement.label));
|
|
192
199
|
if (symbol) {
|
|
193
200
|
symbol.references.push(statement.label);
|
|
194
201
|
identifierSymbols.set(statement.label, symbol);
|
|
@@ -218,6 +225,14 @@ function resolveScopes(chunk) {
|
|
|
218
225
|
}
|
|
219
226
|
}
|
|
220
227
|
const inner = createScope("function", scope);
|
|
228
|
+
functionScopes.set(fn, inner);
|
|
229
|
+
if (fn.identifier?.type === "MemberExpression" &&
|
|
230
|
+
fn.identifier.indexer === ":") {
|
|
231
|
+
// `function object:method(...)` declares an implicit first parameter. It has no
|
|
232
|
+
// declaration token in the AST, but it must still own every `self` reference so
|
|
233
|
+
// global analysis, aliases, summaries, and binding validation share Lua's binding.
|
|
234
|
+
declare(inner, { type: "Identifier", name: "self" }, "param", true);
|
|
235
|
+
}
|
|
221
236
|
fn.parameters.forEach((parameter) => {
|
|
222
237
|
if (parameter.type === "Identifier") {
|
|
223
238
|
declare(inner, parameter, "param");
|
|
@@ -268,6 +283,7 @@ function resolveScopes(chunk) {
|
|
|
268
283
|
return;
|
|
269
284
|
case "FunctionDeclaration": {
|
|
270
285
|
const inner = createScope("function", scope);
|
|
286
|
+
functionScopes.set(expr, inner);
|
|
271
287
|
expr.parameters.forEach((parameter) => {
|
|
272
288
|
if (parameter.type === "Identifier") {
|
|
273
289
|
declare(inner, parameter, "param");
|
|
@@ -305,5 +321,6 @@ function resolveScopes(chunk) {
|
|
|
305
321
|
globals,
|
|
306
322
|
symbolOf: (identifier) => identifierSymbols.get(identifier),
|
|
307
323
|
isGlobalReference: (identifier) => globalReferenceNodes.has(identifier),
|
|
324
|
+
scopeOfFunction: (fn) => functionScopes.get(fn),
|
|
308
325
|
};
|
|
309
326
|
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.runtimeEnvironmentOf = runtimeEnvironmentOf;
|
|
4
|
+
exports.checkParallelValueCount = checkParallelValueCount;
|
|
5
|
+
exports.checkParallelEvaluation = checkParallelEvaluation;
|
|
6
|
+
exports.analyzeLocalResourceUsage = analyzeLocalResourceUsage;
|
|
7
|
+
const COMMON_RESOURCES = {
|
|
8
|
+
maxActiveLocalsPerFunction: 200,
|
|
9
|
+
maxRegistersPerFunction: 255,
|
|
10
|
+
// compilerの一時register推定が未完成でも、local/register上限間に余裕を残す。
|
|
11
|
+
conservativeParallelValueLimit: 50,
|
|
12
|
+
};
|
|
13
|
+
function runtimeEnvironmentOf(profile) {
|
|
14
|
+
if (profile === "stormworks") {
|
|
15
|
+
return {
|
|
16
|
+
profile,
|
|
17
|
+
semantics: {
|
|
18
|
+
mutableMetatables: false,
|
|
19
|
+
debugLocalIntrospection: false,
|
|
20
|
+
},
|
|
21
|
+
resources: COMMON_RESOURCES,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
return {
|
|
25
|
+
profile,
|
|
26
|
+
semantics: {
|
|
27
|
+
mutableMetatables: true,
|
|
28
|
+
debugLocalIntrospection: true,
|
|
29
|
+
},
|
|
30
|
+
resources: COMMON_RESOURCES,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function checkParallelValueCount(environment, count) {
|
|
34
|
+
return checkParallelEvaluation(environment, {
|
|
35
|
+
activeLocalsBefore: 0,
|
|
36
|
+
parallelValueCount: count,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
function checkParallelEvaluation(environment, request) {
|
|
40
|
+
const limit = environment.resources.conservativeParallelValueLimit;
|
|
41
|
+
const localHeadroom = Math.max(0, environment.resources.maxActiveLocalsPerFunction -
|
|
42
|
+
request.activeLocalsBefore);
|
|
43
|
+
const registerHeadroom = Math.max(0, environment.resources.maxRegistersPerFunction - request.activeLocalsBefore);
|
|
44
|
+
const allowedCount = Math.min(limit, localHeadroom, registerHeadroom);
|
|
45
|
+
const estimatedPeakRegisters = request.activeLocalsBefore + request.parallelValueCount;
|
|
46
|
+
if (request.parallelValueCount <= allowedCount) {
|
|
47
|
+
return {
|
|
48
|
+
allowed: true,
|
|
49
|
+
confidence: "conservative-policy",
|
|
50
|
+
limit: allowedCount,
|
|
51
|
+
estimatedPeakRegisters,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
const reason = localHeadroom < request.parallelValueCount
|
|
55
|
+
? "local-limit"
|
|
56
|
+
: registerHeadroom < request.parallelValueCount
|
|
57
|
+
? "register-limit"
|
|
58
|
+
: "parallel-value-limit";
|
|
59
|
+
return {
|
|
60
|
+
allowed: false,
|
|
61
|
+
reason,
|
|
62
|
+
limit: allowedCount,
|
|
63
|
+
estimatedPeakRegisters,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** 各function/blockの字句的local生存数を、文の直前位置で数える。 */
|
|
67
|
+
function analyzeLocalResourceUsage(chunk) {
|
|
68
|
+
const activeBefore = new WeakMap();
|
|
69
|
+
const visitBlock = (body, entryActive) => {
|
|
70
|
+
let active = entryActive;
|
|
71
|
+
body.forEach((statement) => {
|
|
72
|
+
activeBefore.set(statement, active);
|
|
73
|
+
switch (statement.type) {
|
|
74
|
+
case "LocalStatement":
|
|
75
|
+
active += statement.variables.length;
|
|
76
|
+
break;
|
|
77
|
+
case "FunctionDeclaration":
|
|
78
|
+
visitBlock(statement.body, statement.parameters.length);
|
|
79
|
+
if (statement.isLocal)
|
|
80
|
+
active++;
|
|
81
|
+
break;
|
|
82
|
+
case "DoStatement":
|
|
83
|
+
case "WhileStatement":
|
|
84
|
+
visitBlock(statement.body, active);
|
|
85
|
+
break;
|
|
86
|
+
case "RepeatStatement":
|
|
87
|
+
visitBlock(statement.body, active);
|
|
88
|
+
break;
|
|
89
|
+
case "IfStatement":
|
|
90
|
+
statement.clauses.forEach((clause) => {
|
|
91
|
+
visitBlock(clause.body, active);
|
|
92
|
+
});
|
|
93
|
+
break;
|
|
94
|
+
case "ForNumericStatement":
|
|
95
|
+
visitBlock(statement.body, active + 1);
|
|
96
|
+
break;
|
|
97
|
+
case "ForGenericStatement":
|
|
98
|
+
visitBlock(statement.body, active + statement.variables.length);
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
};
|
|
103
|
+
visitBlock(chunk.body, 0);
|
|
104
|
+
return { activeLocalsBefore: (statement) => activeBefore.get(statement) };
|
|
105
|
+
}
|