js-confuser-vm 0.1.0 → 0.1.2

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.
Files changed (63) hide show
  1. package/README.md +281 -147
  2. package/dist/build-runtime.js +41 -15
  3. package/dist/compiler.js +714 -265
  4. package/dist/disassembler.js +367 -0
  5. package/dist/index.js +7 -2
  6. package/dist/runtime.js +160 -119
  7. package/dist/template.js +163 -42
  8. package/dist/transforms/bytecode/aliasedOpcodes.js +4 -1
  9. package/dist/transforms/bytecode/concealConstants.js +2 -2
  10. package/dist/transforms/bytecode/controlFlowFlattening.js +569 -0
  11. package/dist/transforms/bytecode/dispatcher.js +15 -111
  12. package/dist/transforms/bytecode/macroOpcodes.js +2 -2
  13. package/{src/transforms/bytecode/resolveContants.ts → dist/transforms/bytecode/resolveConstants.js} +30 -56
  14. package/dist/transforms/bytecode/resolveRegisters.js +23 -4
  15. package/dist/transforms/bytecode/selfModifying.js +88 -21
  16. package/dist/transforms/bytecode/semanticOpcodes.js +162 -0
  17. package/dist/transforms/bytecode/specializedOpcodes.js +23 -12
  18. package/dist/transforms/bytecode/stringConcealing.js +288 -0
  19. package/dist/transforms/runtime/classObfuscation.js +43 -0
  20. package/dist/transforms/runtime/handlerTable.js +91 -0
  21. package/dist/transforms/runtime/semanticOpcodes.js +35 -0
  22. package/dist/transforms/runtime/specializedOpcodes.js +11 -5
  23. package/dist/types.js +1 -1
  24. package/dist/utils/ast-utils.js +75 -0
  25. package/dist/utils/op-utils.js +1 -2
  26. package/dist/utils/pass-utils.js +100 -0
  27. package/dist/utils/profile-utils.js +3 -0
  28. package/package.json +8 -1
  29. package/.gitmodules +0 -4
  30. package/.prettierignore +0 -1
  31. package/CHANGELOG.md +0 -335
  32. package/babel-plugin-inline-runtime.cjs +0 -34
  33. package/babel.config.json +0 -23
  34. package/index.ts +0 -38
  35. package/jest-strip-types.js +0 -10
  36. package/jest.config.js +0 -52
  37. package/src/build-runtime.ts +0 -78
  38. package/src/compiler.ts +0 -2593
  39. package/src/index.ts +0 -14
  40. package/src/minify.ts +0 -21
  41. package/src/options.ts +0 -18
  42. package/src/runtime.ts +0 -923
  43. package/src/template.ts +0 -141
  44. package/src/transforms/bytecode/aliasedOpcodes.ts +0 -148
  45. package/src/transforms/bytecode/concealConstants.ts +0 -52
  46. package/src/transforms/bytecode/dispatcher.ts +0 -398
  47. package/src/transforms/bytecode/macroOpcodes.ts +0 -193
  48. package/src/transforms/bytecode/microOpcodes.ts +0 -291
  49. package/src/transforms/bytecode/resolveLabels.ts +0 -112
  50. package/src/transforms/bytecode/resolveRegisters.ts +0 -221
  51. package/src/transforms/bytecode/selfModifying.ts +0 -121
  52. package/src/transforms/bytecode/specializedOpcodes.ts +0 -153
  53. package/src/transforms/runtime/aliasedOpcodes.ts +0 -191
  54. package/src/transforms/runtime/internalVariables.ts +0 -270
  55. package/src/transforms/runtime/macroOpcodes.ts +0 -138
  56. package/src/transforms/runtime/microOpcodes.ts +0 -93
  57. package/src/transforms/runtime/minify.ts +0 -1
  58. package/src/transforms/runtime/shuffleOpcodes.ts +0 -24
  59. package/src/transforms/runtime/specializedOpcodes.ts +0 -156
  60. package/src/types.ts +0 -93
  61. package/src/utils/op-utils.ts +0 -48
  62. package/src/utils/random-utils.ts +0 -31
  63. package/tsconfig.json +0 -12
@@ -1,270 +0,0 @@
1
- // Goes through the switch case for defined identifiers on the statement level
2
- // Example:
3
- // case OP.LOAD_CONST: {
4
- // var dst = this._operand();
5
- // frame.regs[dst] = this._constant();
6
- // break;
7
- // }
8
- // You find "dst" is defined in this scope.
9
- // You first check the compiler to see if it's already assigned an index in compiler._internals mapping varName=>index
10
- // If not found, use compiler._internals.globally.size as the new index (when options.randomizeOpcodes is off, when on, choose random between 0 and 65535), and add varName=>index to compiler._internals
11
- // Then replace the VariableDeclaration to an AssignmentExpression setting left this._internals[index] = init;
12
- // Then replace all identifiers of "dst" to this._internals[index] as well (Updates references)
13
- // Final output:
14
- // case OP.LOAD_CONST: {
15
- // this._internals[index] = this._operand();
16
- // frame.regs[this._internals[index]] = this._constant();
17
- // break;
18
- // }
19
-
20
- import { Compiler } from "../../compiler.ts";
21
- import * as t from "@babel/types";
22
- import traverseImport from "@babel/traverse";
23
- import { ok } from "assert";
24
- import { getRandomInt } from "../../utils/random-utils.ts";
25
- import { U16_MAX } from "../../utils/op-utils.ts";
26
-
27
- const traverse = (traverseImport.default ||
28
- traverseImport) as typeof traverseImport.default;
29
-
30
- export function makeInternalsAccess(index: number): t.MemberExpression {
31
- return t.memberExpression(
32
- t.memberExpression(t.thisExpression(), t.identifier("_internals")),
33
- t.numericLiteral(index),
34
- true, // computed
35
- );
36
- }
37
-
38
- function collectUsedIndices(compiler: Compiler): Set<number> {
39
- const used = new Set<number>();
40
- for (const v of compiler._internals.globally.values()) used.add(v);
41
- for (const opMap of compiler._internals.opcodes.values()) {
42
- for (const v of opMap.values()) used.add(v);
43
- }
44
- return used;
45
- }
46
-
47
- // Assign or look up the _internals slot index for a variable name within a
48
- // specific opcode handler.
49
- //
50
- // _internals.opcodes[currentOpcode] is the source of truth for this opcode.
51
- // _internals.globally holds the shared pool written on first sight.
52
- //
53
- // randomizeOpcodes OFF → always reuse / create in globally, mirror to opcodes.
54
- // randomizeOpcodes ON → first time a name is seen: create global slot.
55
- // subsequent opcodes: 50% reuse global, 50% create an
56
- // opcode-specific random slot (NOT written to globally).
57
- function assignInternalsIndex(
58
- name: string,
59
- compiler: Compiler,
60
- currentOpcode: number,
61
- ): number {
62
- // Ensure per-opcode map exists
63
- let opcodeMap = compiler._internals.opcodes.get(currentOpcode);
64
- if (!opcodeMap) {
65
- opcodeMap = new Map();
66
- compiler._internals.opcodes.set(currentOpcode, opcodeMap);
67
- }
68
-
69
- // Already registered for this opcode — return immediately
70
- const existing = opcodeMap.get(name);
71
- if (existing !== undefined) return existing;
72
-
73
- const globalIndex = compiler._internals.globally.get(name);
74
- let index: number;
75
-
76
- if (!compiler.options.randomizeOpcodes) {
77
- // Non-random: always share the global sequential slot
78
- if (globalIndex === undefined) {
79
- index = compiler._internals.globally.size;
80
- compiler._internals.globally.set(name, index);
81
- } else {
82
- index = globalIndex;
83
- }
84
- } else if (globalIndex === undefined) {
85
- // First opcode to declare this variable — establish the global slot
86
- const used = collectUsedIndices(compiler);
87
- let candidate: number;
88
- do {
89
- candidate = getRandomInt(0, U16_MAX);
90
- } while (used.has(candidate));
91
- index = candidate;
92
- compiler._internals.globally.set(name, index);
93
- } else {
94
- // Already in global: 50% chance to reuse, 50% opcode-specific new slot
95
- if (Math.random() < 0.5) {
96
- index = globalIndex;
97
- } else {
98
- const used = collectUsedIndices(compiler);
99
- let candidate: number;
100
- do {
101
- candidate = getRandomInt(0, U16_MAX);
102
- } while (used.has(candidate));
103
- index = candidate;
104
- // Intentionally NOT written to globally — this slot is opcode-specific
105
- }
106
- }
107
-
108
- opcodeMap.set(name, index);
109
- return index;
110
- }
111
-
112
- export function applyInternalVariablesToSwitchCase(
113
- node: t.SwitchCase,
114
- compiler: Compiler,
115
- currentOpcode: number,
116
- ) {
117
- // Work with the actual body array (block body or flat consequent)
118
- let bodyArr: t.Statement[];
119
- if (node.consequent.length === 1 && t.isBlockStatement(node.consequent[0])) {
120
- bodyArr = (node.consequent[0] as t.BlockStatement).body;
121
- } else {
122
- bodyArr = node.consequent as t.Statement[];
123
- }
124
-
125
- // Single traversal: declarations and references handled in one pass.
126
- //
127
- // Declaration (Identifier is VariableDeclarator.id):
128
- // → register/look-up slot, replace entire VariableDeclaration with
129
- // AssignmentExpression (bare for ForStatement.init, else ExpressionStatement).
130
- //
131
- // Reference (any other Identifier):
132
- // → look up opcodes[currentOpcode] (source of truth) and replace if found.
133
- // This handles cross-statement refs produced by micro-opcode splitting.
134
- const syntheticFile = t.file(t.program(bodyArr as t.Statement[]));
135
- const illegalNames = new Set<string>(); // Nested closure names are skipped
136
-
137
- traverse(syntheticFile, {
138
- Identifier(path) {
139
- const name = path.node.name;
140
- if (illegalNames.has(name)) return;
141
-
142
- // Skip non-computed property names: obj.name
143
- if (
144
- t.isMemberExpression(path.parent) &&
145
- !path.parent.computed &&
146
- path.parent.property === path.node
147
- ) {
148
- return;
149
- }
150
-
151
- // Skip non-computed object-property keys: { name: value }
152
- if (
153
- t.isObjectProperty(path.parent) &&
154
- !path.parent.computed &&
155
- path.parent.key === path.node
156
- ) {
157
- return;
158
- }
159
-
160
- // Don't descend into nested function scopes
161
- if (
162
- path.find(
163
- (p) =>
164
- p.isFunctionDeclaration() ||
165
- p.isFunctionExpression() ||
166
- p.isArrowFunctionExpression(),
167
- )
168
- ) {
169
- return;
170
- }
171
-
172
- // ── Declaration binding ──────────────────────────────────────────────
173
- if (t.isVariableDeclarator(path.parent) && path.parent.id === path.node) {
174
- // Verify it's not referenced in nested closure (illegal)
175
- const binding = path.scope.getBinding(name);
176
- if (
177
- binding?.referencePaths.some((rp) =>
178
- rp.findParent(
179
- (p) =>
180
- p.isFunctionDeclaration() ||
181
- p.isFunctionExpression() ||
182
- p.isArrowFunctionExpression(),
183
- ),
184
- )
185
- ) {
186
- illegalNames.add(name);
187
- return;
188
- }
189
-
190
- const index = assignInternalsIndex(name, compiler, currentOpcode);
191
- const init = (path.parent as t.VariableDeclarator).init;
192
-
193
- const assignment = t.assignmentExpression(
194
- "=",
195
- makeInternalsAccess(index),
196
- init ?? t.identifier("undefined"),
197
- );
198
-
199
- // Two levels up: VariableDeclarator → VariableDeclaration
200
- const varDeclPath = path.parentPath!.parentPath!;
201
-
202
- if (
203
- t.isForStatement(varDeclPath.parent) &&
204
- varDeclPath.parent.init === varDeclPath.node
205
- ) {
206
- // ForStatement.init accepts an Expression directly
207
- varDeclPath.replaceWith(assignment);
208
- } else {
209
- varDeclPath.replaceWith(t.expressionStatement(assignment));
210
- }
211
- return;
212
- }
213
-
214
- // ── Reference ───────────────────────────────────────────────────────
215
- // Source of truth for this opcode is its own per-opcode map
216
- const opcodeMap = compiler._internals.opcodes.get(currentOpcode);
217
- const index = opcodeMap?.get(name);
218
- if (index !== undefined) {
219
- path.replaceWith(makeInternalsAccess(index));
220
- path.skip();
221
- }
222
- },
223
- });
224
- }
225
-
226
- // This takes the AST and finds the runtime switch statement via the leading
227
- // comment "@SWITCH" then applies the above transformation to each switch case.
228
- export function applyInteralVariablesToRuntime(
229
- ast: t.File,
230
- compiler: Compiler,
231
- ) {
232
- let switchStatement: t.SwitchStatement | null = null;
233
- traverse(ast, {
234
- SwitchStatement(path) {
235
- if (path.node.leadingComments?.some((c) => c.value.includes("@SWITCH"))) {
236
- switchStatement = path.node;
237
- path.stop();
238
- }
239
- },
240
- });
241
-
242
- ok(
243
- switchStatement,
244
- "Could not find @SWITCH statement for internal variables",
245
- );
246
-
247
- for (const sc of (switchStatement as t.SwitchStatement).cases) {
248
- const test = sc.test;
249
- let currentOpcode: number | null = null;
250
-
251
- if (
252
- test &&
253
- t.isMemberExpression(test) &&
254
- t.isIdentifier(test.object, { name: "OP" }) &&
255
- t.isIdentifier(test.property)
256
- ) {
257
- // case OP.LOAD_CONST: → resolve via compiler.OP
258
- const opName = (test.property as t.Identifier).name;
259
- const val = compiler.OP[opName as keyof typeof compiler.OP];
260
- if (val !== undefined) currentOpcode = val as number;
261
- } else if (test && t.isNumericLiteral(test)) {
262
- // Already a numeric literal (e.g. generated micro-opcode cases)
263
- currentOpcode = test.value;
264
- }
265
-
266
- if (currentOpcode === null) continue;
267
-
268
- applyInternalVariablesToSwitchCase(sc, compiler, currentOpcode);
269
- }
270
- }
@@ -1,138 +0,0 @@
1
- import * as t from "@babel/types";
2
- import traverseImport from "@babel/traverse";
3
- import { ok } from "assert";
4
- import { Compiler } from "../../compiler.ts";
5
- import generate from "@babel/generator";
6
- const traverse = (traverseImport.default ||
7
- traverseImport) as typeof traverseImport.default;
8
-
9
- // Extract the real statement list from a SwitchCase consequent, normalising
10
- // the two forms that appear in the runtime:
11
- // • A single wrapping BlockStatement → use its .body
12
- // • Statements listed directly → use as-is
13
- // In both cases trailing BreakStatement / EmptyStatement are filtered out.
14
- function extractCaseBody(switchCase: t.SwitchCase): t.Statement[] {
15
- let stmts: t.Statement[];
16
- if (
17
- switchCase.consequent.length === 1 &&
18
- t.isBlockStatement(switchCase.consequent[0])
19
- ) {
20
- stmts = (switchCase.consequent[0] as t.BlockStatement).body;
21
- } else {
22
- stmts = switchCase.consequent as t.Statement[];
23
- }
24
- return stmts.filter((s) => !t.isBreakStatement(s) && !t.isEmptyStatement(s));
25
- }
26
-
27
- export function getOpcodeToCaseMap(
28
- switchStatement: t.SwitchStatement,
29
- compiler: Compiler,
30
- ): Map<number, t.SwitchCase> {
31
- // Build a map opName → SwitchCase from the existing OP.xxx case tests.
32
- const opcodeToCaseMap = new Map<number, t.SwitchCase>();
33
- for (const sc of (switchStatement as t.SwitchStatement).cases) {
34
- const test = sc.test;
35
- if (!test) continue;
36
-
37
- let opcode;
38
- let opName;
39
- if (
40
- t.isMemberExpression(test) &&
41
- t.isIdentifier(test.object, { name: "OP" }) &&
42
- t.isIdentifier(test.property)
43
- ) {
44
- opName = test.property.name;
45
- opcode = +Object.keys(compiler.OP_NAME).find(
46
- (key) => compiler.OP_NAME[key] == opName,
47
- );
48
- } else if (t.isNumericLiteral(test)) {
49
- opcode = test.value;
50
- }
51
-
52
- ok(
53
- typeof opcode === "number" && !Number.isNaN(opcode),
54
- `Failed to parse ${opcode} from ${opName}`,
55
- );
56
- if (opcode !== undefined) {
57
- opcodeToCaseMap.set(opcode, sc);
58
- }
59
- }
60
-
61
- return opcodeToCaseMap;
62
- }
63
-
64
- // Append a generated switch case for every entry in compiler.MACRO_OPS.
65
- // Each case inlines the constituent case bodies directly — no operand stack,
66
- // no substitution needed. Because every opcode handler now reads its own
67
- // operands via this._operand(), those calls naturally consume the inline
68
- // operands that macroOpcodes.ts embedded on the macro instruction.
69
- // Must be called BEFORE applyShuffleOpcodes so the new cases get shuffled.
70
- export function applyMacroOpcodes(ast: t.File, compiler: Compiler): void {
71
- let switchStatement: t.SwitchStatement | null = null;
72
- traverse(ast, {
73
- SwitchStatement(path) {
74
- if (path.node.leadingComments?.some((c) => c.value.includes("@SWITCH"))) {
75
- switchStatement = path.node;
76
- path.stop();
77
- }
78
- },
79
- });
80
-
81
- ok(switchStatement, "Could not find @SWITCH statement for macro opcodes");
82
-
83
- const opcodeToCaseMap = getOpcodeToCaseMap(switchStatement, compiler);
84
-
85
- for (const [macroOpStr, constituentOps] of Object.entries(
86
- compiler.MACRO_OPS,
87
- )) {
88
- const macroOpCode = Number(macroOpStr);
89
- const N = constituentOps.length;
90
-
91
- // Resolve each constituent op value → case node via OP_NAME lookup.
92
- const constituentCases: t.SwitchCase[] = [];
93
- let allFound = true;
94
- for (const opVal of constituentOps) {
95
- const found = opcodeToCaseMap.get(opVal);
96
- if (!found) {
97
- allFound = false;
98
- break;
99
- }
100
- constituentCases.push(found);
101
- }
102
- if (!allFound) {
103
- throw new Error(
104
- `Could not find all constituent ops for macro op ${macroOpCode}`,
105
- );
106
- }
107
-
108
- const opNames = constituentOps.map((v) => compiler.OP_NAME[v] ?? `OP_${v}`);
109
- let newName = opNames.join(",");
110
- compiler.OP_NAME[macroOpCode] = newName;
111
-
112
- // ── Build the macro case body ──────────────────────────────────────────
113
- // Clone and inline each sub-instruction's case body directly.
114
- // No operand substitution needed: each body already calls this._operand()
115
- // to read its own operands, which will consume the inline operands that
116
- // macroOpcodes.ts embedded on the macro instruction in order.
117
- const bodyStmts: t.Statement[] = [];
118
-
119
- for (let i = 0; i < N; i++) {
120
- const subStmts = extractCaseBody(constituentCases[i]).map(
121
- (s) => t.cloneNode(s, true) as t.Statement,
122
- );
123
-
124
- if (subStmts.length > 0) {
125
- t.addComment(subStmts[0], "leading", ` ${opNames[i]}`, true);
126
- bodyStmts.push(...subStmts);
127
- }
128
- }
129
-
130
- bodyStmts.push(t.breakStatement());
131
-
132
- (switchStatement as t.SwitchStatement).cases.push(
133
- t.switchCase(t.numericLiteral(macroOpCode), [
134
- t.blockStatement(bodyStmts),
135
- ]),
136
- );
137
- }
138
- }
@@ -1,93 +0,0 @@
1
- import * as t from "@babel/types";
2
- import traverseImport from "@babel/traverse";
3
- import { ok } from "assert";
4
- import { Compiler } from "../../compiler.ts";
5
- import { applyInternalVariablesToSwitchCase } from "./internalVariables.ts";
6
-
7
- const traverse = (traverseImport.default ||
8
- traverseImport) as typeof traverseImport.default;
9
-
10
- // Extract the real statement list from a SwitchCase consequent.
11
- function extractCaseBody(switchCase: t.SwitchCase): t.Statement[] {
12
- let stmts: t.Statement[];
13
- if (
14
- switchCase.consequent.length === 1 &&
15
- t.isBlockStatement(switchCase.consequent[0])
16
- ) {
17
- stmts = (switchCase.consequent[0] as t.BlockStatement).body;
18
- } else {
19
- stmts = switchCase.consequent as t.Statement[];
20
- }
21
- return stmts.filter((s) => !t.isBreakStatement(s) && !t.isEmptyStatement(s));
22
- }
23
-
24
- // Append a generated switch case for every entry in compiler.MICRO_OPS.
25
- // applyInteralVariablesToRuntime must run before this so that the source
26
- // case bodies are already using this._internals[index] instead of local vars.
27
- // Must be called BEFORE applyShuffleOpcodes so the new cases get shuffled.
28
- export function applyMicroOpcodes(ast: t.File, compiler: Compiler): void {
29
- if (!compiler.MICRO_OPS || Object.keys(compiler.MICRO_OPS).length === 0) {
30
- return;
31
- }
32
-
33
- let switchStatement: t.SwitchStatement | null = null;
34
- traverse(ast, {
35
- SwitchStatement(path) {
36
- if (path.node.leadingComments?.some((c) => c.value.includes("@SWITCH"))) {
37
- switchStatement = path.node;
38
- path.stop();
39
- }
40
- },
41
- });
42
-
43
- ok(switchStatement, "Could not find @SWITCH statement for micro opcodes");
44
-
45
- // Build opName → SwitchCase from existing cases.
46
- const nameToCaseMap = new Map<string, t.SwitchCase>();
47
- for (const sc of (switchStatement as t.SwitchStatement).cases) {
48
- const test = sc.test;
49
- if (
50
- test &&
51
- t.isMemberExpression(test) &&
52
- t.isIdentifier(test.object, { name: "OP" }) &&
53
- t.isIdentifier(test.property)
54
- ) {
55
- nameToCaseMap.set((test.property as t.Identifier).name, sc);
56
- }
57
- }
58
-
59
- for (const [microOpStr, info] of Object.entries(compiler.MICRO_OPS)) {
60
- const microOpCode = Number(microOpStr);
61
- const { originalOp, stmtIndex } = info;
62
-
63
- const originalName = compiler.OP_NAME[originalOp];
64
- if (!originalName) continue;
65
-
66
- const originalCase = nameToCaseMap.get(originalName);
67
- if (!originalCase) continue;
68
-
69
- // Extract and clone all non-break statements from the original case body.
70
- const allStmts = extractCaseBody(originalCase);
71
- if (stmtIndex >= allStmts.length) continue;
72
-
73
- const rawStmt = t.cloneNode(allStmts[stmtIndex], true) as t.Statement;
74
-
75
- const newCase = t.switchCase(t.numericLiteral(microOpCode), [
76
- t.blockStatement([rawStmt, t.breakStatement()]),
77
- ]);
78
-
79
- // Apply internal-variable substitution — this may replace rawStmt in the
80
- // block body (var decl → assignment), so add the comment afterwards on
81
- // whatever the first statement of the block actually is.
82
- applyInternalVariablesToSwitchCase(newCase, compiler, microOpCode);
83
-
84
- const blockBody = (newCase.consequent[0] as t.BlockStatement).body;
85
- const firstStmt = blockBody[0];
86
- if (firstStmt) {
87
- const microName = compiler.OP_NAME[microOpCode] ?? `MICRO_${microOpCode}`;
88
- t.addComment(firstStmt, "leading", ` ${microName}`, true);
89
- }
90
-
91
- (switchStatement as t.SwitchStatement).cases.push(newCase);
92
- }
93
- }
@@ -1 +0,0 @@
1
- export { minify as applyMinify } from "../../minify.ts";
@@ -1,24 +0,0 @@
1
- import * as t from "@babel/types";
2
- import traverseImport from "@babel/traverse";
3
- import { ok } from "assert";
4
- import { shuffle } from "../../utils/random-utils.ts";
5
- const traverse = (traverseImport.default ||
6
- traverseImport) as typeof traverseImport.default;
7
-
8
- // Randomly reorder the switch cases inside the @SWITCH statement so the
9
- // opcode handler order varies per build.
10
- export function applyShuffleOpcodes(ast: t.File): void {
11
- let switchStatement: t.SwitchStatement | null = null;
12
- traverse(ast, {
13
- SwitchStatement(path) {
14
- if (path.node.leadingComments?.some((c) => c.value.includes("@SWITCH"))) {
15
- switchStatement = path.node;
16
- path.stop();
17
- }
18
- },
19
- });
20
-
21
- ok(switchStatement, "Could not find opcode handlers switch statement");
22
-
23
- switchStatement.cases = shuffle(switchStatement.cases);
24
- }
@@ -1,156 +0,0 @@
1
- import * as t from "@babel/types";
2
- import traverseImport from "@babel/traverse";
3
- import { ok } from "assert";
4
- import { Compiler } from "../../compiler.ts";
5
- import { getOpcodeToCaseMap } from "./macroOpcodes.ts";
6
-
7
- const traverse = (traverseImport.default ||
8
- traverseImport) as typeof traverseImport.default;
9
-
10
- // Extract the real statement list from a SwitchCase consequent (identical to the
11
- // helper used by applyMacroOpcodes so the two files stay in sync).
12
- function extractCaseBody(switchCase: t.SwitchCase): t.Statement[] {
13
- let stmts: t.Statement[];
14
- if (
15
- switchCase.consequent.length === 1 &&
16
- t.isBlockStatement(switchCase.consequent[0])
17
- ) {
18
- stmts = (switchCase.consequent[0] as t.BlockStatement).body;
19
- } else {
20
- stmts = switchCase.consequent as t.Statement[];
21
- }
22
- return stmts.filter((s) => !t.isBreakStatement(s) && !t.isEmptyStatement(s));
23
- }
24
-
25
- // Inline a fixed numeric operand in place of every `this._operand()` call.
26
- // Because specialized opcodes are only created for instructions that have
27
- // *exactly one* numeric operand, every `_operand()` call inside the original
28
- // handler is replaced by the constant value that was baked into the opcode.
29
- function inlineFixedOperands(
30
- bodyStmts: t.Statement[],
31
- resolvedValues: number[],
32
- ): void {
33
- // Wrap the statements in a temporary BlockStatement so traverse has a root.
34
- // The replacement mutates the original statement objects in place.
35
- var replaced = 0;
36
- function consumeOperand() {
37
- const resolvedValue = resolvedValues[replaced++];
38
- ok(
39
- typeof resolvedValue === "number",
40
- `Expected a numeric operand value, got ${resolvedValue}`,
41
- );
42
- return t.numericLiteral(resolvedValue);
43
- }
44
-
45
- traverse(t.blockStatement(bodyStmts), {
46
- noScope: true,
47
- CallExpression(path) {
48
- const callee = path.node.callee;
49
-
50
- const isMethodCall = (methodName) => {
51
- return (
52
- t.isMemberExpression(callee) &&
53
- t.isThisExpression(callee.object) &&
54
- t.isIdentifier(callee.property, { name: methodName }) &&
55
- path.node.arguments.length === 0
56
- );
57
- };
58
-
59
- if (isMethodCall("_operand")) {
60
- path.replaceWith(consumeOperand());
61
- }
62
-
63
- if (isMethodCall("_constant")) {
64
- path.node.arguments = [consumeOperand(), consumeOperand()];
65
- }
66
- },
67
- });
68
-
69
- ok(
70
- replaced === resolvedValues.length,
71
- `Expected to replace ${resolvedValues.length} operands, but replaced ${replaced}`,
72
- );
73
- }
74
-
75
- // Append a generated switch case for every entry in compiler.SPECIALIZED_OPS.
76
- // Each case is a clone of the original opcode’s handler with `this._operand()`
77
- // replaced by the constant integer that was captured at compile time.
78
- // Must be called AFTER applyMacroOpcodes (so the original cases exist) but
79
- // BEFORE applyShuffleOpcodes so the new specialized cases also get shuffled.
80
- export function applySpecializedOpcodes(ast: t.File, compiler: Compiler): void {
81
- let switchStatement: t.SwitchStatement | null = null;
82
- traverse(ast, {
83
- SwitchStatement(path) {
84
- if (path.node.leadingComments?.some((c) => c.value.includes("@SWITCH"))) {
85
- switchStatement = path.node;
86
- path.stop();
87
- }
88
- },
89
- });
90
-
91
- ok(
92
- switchStatement,
93
- "Could not find @SWITCH statement for specialized opcodes",
94
- );
95
-
96
- // Build a map opName → SwitchCase from the existing OP.xxx case tests.
97
- const opcodeToCaseMap = getOpcodeToCaseMap(switchStatement, compiler);
98
-
99
- if (!compiler.SPECIALIZED_OPS) return;
100
-
101
- for (const [specialOpStr, info] of Object.entries(compiler.SPECIALIZED_OPS)) {
102
- const specialOpCode = Number(specialOpStr);
103
- const { originalOp, operands } = info;
104
-
105
- let newName = compiler.OP_NAME[specialOpCode];
106
- const originalName = compiler.OP_NAME[originalOp];
107
- const originalCase = opcodeToCaseMap.get(originalOp);
108
-
109
- ok(
110
- originalCase,
111
- `Could not find original case for opcode ${originalName} (${originalOp})`,
112
- );
113
-
114
- // Clone the original handler body
115
- const bodyStmts: t.Statement[] = extractCaseBody(originalCase).map(
116
- (s) => t.cloneNode(s, true) as t.Statement,
117
- );
118
-
119
- const placedOperands = info.operands;
120
- ok(placedOperands, `Could not find operand for original opcode ${newName}`);
121
-
122
- const resolvedValues = placedOperands.map((placedOperand) => {
123
- return (placedOperand as any)?.resolvedValue ?? placedOperand;
124
- });
125
-
126
- if (resolvedValues.find((v) => typeof v !== "number")) {
127
- console.error(info);
128
- throw new Error("Expected all resolved operand values to be numbers");
129
- }
130
-
131
- newName = `${originalName}_${resolvedValues.join("_")}`;
132
- compiler.OP_NAME[specialOpCode] = newName;
133
-
134
- // Replace this._operand() with the baked-in constant
135
- inlineFixedOperands(bodyStmts, resolvedValues);
136
-
137
- // Add a leading comment so the generated source stays readable
138
- if (bodyStmts.length > 0) {
139
- t.addComment(
140
- bodyStmts[0],
141
- "leading",
142
- ` ${compiler.OP_NAME[specialOpCode]} (specialized)`,
143
- true,
144
- );
145
- }
146
-
147
- bodyStmts.push(t.breakStatement());
148
-
149
- // Insert the new specialized case into the big switch
150
- (switchStatement as t.SwitchStatement).cases.push(
151
- t.switchCase(t.numericLiteral(specialOpCode), [
152
- t.blockStatement(bodyStmts),
153
- ]),
154
- );
155
- }
156
- }