swf2js 0.0.0-stage → 0.1.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.
Files changed (38) hide show
  1. package/LICENSE-GPL +680 -0
  2. package/README.md +208 -2
  3. package/package.json +24 -4
  4. package/src/cli.js +272 -0
  5. package/src/decoder/button-decoder.js +136 -0
  6. package/src/decoder/shape-decoder.js +786 -0
  7. package/src/decoder/symbol-table.js +36 -0
  8. package/src/decoder/tag-decoder.js +1190 -0
  9. package/src/decoder/tag-types.js +258 -0
  10. package/src/emitter/asset-encoder.js +708 -0
  11. package/src/emitter/bundle-emitter.js +596 -0
  12. package/src/emitter/embedded-swf.js +246 -0
  13. package/src/emitter/font-encoder.js +365 -0
  14. package/src/emitter/timeline-data-codec.js +58 -0
  15. package/src/model/swf-document.js +59 -0
  16. package/src/model/transpile-result.js +32 -0
  17. package/src/parser/bit-reader.js +237 -0
  18. package/src/parser/decompressor.js +91 -0
  19. package/src/parser/swf-parser.js +164 -0
  20. package/src/pretty-printer/pretty-printer.js +137 -0
  21. package/src/runtime/avm1-runtime.js +4907 -0
  22. package/src/runtime/avm2-runtime.js +1591 -0
  23. package/src/runtime/embedded-movie-runtime.js +208 -0
  24. package/src/runtime/index.js +17 -0
  25. package/src/runtime/movie-runtime.js +306 -0
  26. package/src/runtime/swflib.js +14050 -0
  27. package/src/transpiler/actionscript.js +390 -0
  28. package/src/transpiler/avm1/avm1-ir.js +205 -0
  29. package/src/transpiler/avm1/avm1-opcodes.js +149 -0
  30. package/src/transpiler/avm1/avm1-rewrite.js +291 -0
  31. package/src/transpiler/avm1/avm1-transpiler.js +2082 -0
  32. package/src/transpiler/avm2/abc-reader.js +416 -0
  33. package/src/transpiler/avm2/avm2-transpiler.js +2560 -0
  34. package/src/transpiler/cfg-structurer.js +876 -0
  35. package/src/transpiler/timeline/display-list.js +643 -0
  36. package/src/transpiler/timeline/timeline-codegen.js +6354 -0
  37. package/src/util/diagnostics.js +50 -0
  38. package/src/util/logger.js +40 -0
@@ -0,0 +1,876 @@
1
+ /**
2
+ * @fileoverview Structured control-flow reconstruction (CFG → if/else, while, do-while, switch).
3
+ *
4
+ * Shared by AVM1 and AVM2 transpilers. Takes a map/array of basic blocks with
5
+ * statement lines and branch terminators and reconstructs clean ES2020 control flow,
6
+ * falling back to a `switch (_pc)` dispatcher only for irreducible subgraphs.
7
+ */
8
+
9
+ /**
10
+ * @typedef {Object} BasicBlock
11
+ * @property {number} id - Start byte offset (PC)
12
+ * @property {string[]} stmts - Emitted JS statements inside this block
13
+ * @property {"fallthrough"|"jump"|"branch"|"switch"|"return"|"throw"} term
14
+ * @property {number|null} [next] - Target PC for fallthrough or jump
15
+ * @property {string} [cond] - Condition JS expression for branch
16
+ * @property {number|null} [trueTarget] - PC when cond is truthy
17
+ * @property {number|null} [falseTarget] - PC when cond is falsy
18
+ * @property {string} [switchExpr] - Switch discriminant expression
19
+ * @property {number|null} [switchDefault] - Default target PC
20
+ * @property {Array<{ values: number[], target: number }>} [switchCases]
21
+ */
22
+
23
+ /**
24
+ * Reconstruct structured ES2020 JS lines from a list of BasicBlocks (ordered by PC).
25
+ * Block 0 (or `entryId`) is the entry point.
26
+ *
27
+ * @param {BasicBlock[]} blocks - Ordered by ascending `id`
28
+ * @param {number} [entryId]
29
+ * @param {string} [implicitExit] - Statement that leaves the bytecode region
30
+ * @param {() => string[]} [emitDispatcher] - Fallback when branches cannot be emitted without dropping a transfer
31
+ * @returns {string[]}
32
+ */
33
+ export function structureCfg(blocks, entryId, implicitExit, emitDispatcher) {
34
+ if (blocks.length === 0) return [];
35
+ if (implicitExit) blocks = connectImplicitExits(blocks, implicitExit);
36
+
37
+ const startId = entryId ?? blocks[0].id;
38
+ /** @type {Map<number, BasicBlock>} */
39
+ const blockMap = new Map();
40
+ /** @type {Map<number, number>} */
41
+ const orderIndex = new Map();
42
+ for (let i = 0; i < blocks.length; i++) {
43
+ blockMap.set(blocks[i].id, blocks[i]);
44
+ orderIndex.set(blocks[i].id, i);
45
+ }
46
+
47
+ if (!blockMap.has(startId)) return [];
48
+
49
+ // Compute successors & predecessors over reachable blocks
50
+ const { reachable, preds, succs } = computeGraph(startId, blockMap);
51
+ const rBlocks = blocks.filter(b => reachable.has(b.id));
52
+ if (rBlocks.length === 0) return [];
53
+
54
+ // For very large/complex CFGs, cap dominator cost; iterative doms on <=2000 blocks is ~1ms
55
+ const doms = computeDominators(startId, rBlocks, preds);
56
+ const naturalLoops = findNaturalLoops(rBlocks, succs, preds, doms, orderIndex);
57
+ if (emitDispatcher) {
58
+ // The structured loop emitter picks one follow block. With multiple exits
59
+ // inside nested loops it can inline an exit in the wrong loop and re-run a latch.
60
+ for (const [outerHeader, outer] of naturalLoops) {
61
+ for (const [innerHeader, inner] of naturalLoops) {
62
+ if (outer.body.has(innerHeader) && !inner.body.has(outerHeader) &&
63
+ (outer.exits.size > 1 || inner.exits.size > 1)) return emitDispatcher();
64
+ }
65
+ }
66
+ }
67
+ const postDoms = computePostDominators(rBlocks, succs, preds, orderIndex);
68
+ const fwdReach = computeForwardReachable(rBlocks, succs, orderIndex);
69
+
70
+ const out = [];
71
+ const emitted = new Set();
72
+ const loopRegions = [];
73
+ let nextJoinLabel = 0;
74
+ let unresolvedTransfer = false;
75
+
76
+ function emitRegion(id, stopId, loopHeader, loopExit, scopeVisited, depth) {
77
+ if (loopHeader === null || stopId === null) {
78
+ emitRegionBody(id, stopId, loopHeader, loopExit, scopeVisited, depth);
79
+ return;
80
+ }
81
+ const region = { stopId, loopHeader, label: null };
82
+ const start = out.length;
83
+ loopRegions.push(region);
84
+ emitRegionBody(id, stopId, loopHeader, loopExit, scopeVisited, depth);
85
+ loopRegions.pop();
86
+ if (region.label) {
87
+ for (let index = start; index < out.length; index++) out[index] = ' ' + out[index];
88
+ out.splice(start, 0, `${region.label}: {`);
89
+ out.push('}');
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Emit structured code starting at `id`, stopping before `stopId` (merge point).
95
+ * @param {number|null|undefined} id
96
+ * @param {number|null} stopId
97
+ * @param {number|null} loopHeader
98
+ * @param {number|null} loopExit
99
+ * @param {Set<number>} scopeVisited
100
+ * @param {number} depth
101
+ */
102
+ function emitRegionBody(id, stopId, loopHeader, loopExit, scopeVisited, depth) {
103
+ let cur = id;
104
+ while (cur !== null && cur !== undefined && cur !== stopId) {
105
+ if (depth > 80) {
106
+ emitFallbackDispatcher(cur, stopId, loopHeader, loopExit);
107
+ return;
108
+ }
109
+
110
+ // Handle loop control transfers when jumping to enclosing loop boundaries
111
+ if (loopExit !== null && cur === loopExit) {
112
+ out.push('break;');
113
+ return;
114
+ }
115
+ if (loopHeader !== null && cur === loopHeader && scopeVisited.has(cur)) {
116
+ out.push('continue;');
117
+ return;
118
+ }
119
+
120
+ // An inner arm can skip its join and go straight to an enclosing join,
121
+ // such as the increment shared by hits and misses in a collision loop.
122
+ const join = loopHeader === null ? null
123
+ : loopRegions.find(region => region.loopHeader === loopHeader && region.stopId === cur);
124
+ if (join) {
125
+ join.label ??= `_cfgJoin${nextJoinLabel++}`;
126
+ out.push(`break ${join.label};`);
127
+ return;
128
+ }
129
+
130
+ if (scopeVisited.has(cur) || emitted.has(cur)) {
131
+ const shared = blockMap.get(cur);
132
+ if (shared && (shared.term === 'return' || shared.term === 'throw') && shared.stmts.length <= 4) {
133
+ for (const s of shared.stmts) out.push(s);
134
+ return;
135
+ }
136
+ // A transfer to code already placed in a different arm requires the original graph.
137
+ unresolvedTransfer = true;
138
+ return;
139
+ }
140
+
141
+ const block = blockMap.get(cur);
142
+ if (!block) return;
143
+
144
+ // Check if `cur` is a natural loop header (not already the active loopHeader)
145
+ const loop = naturalLoops.get(cur);
146
+ if (loop && cur !== loopHeader) {
147
+ scopeVisited.add(cur);
148
+ const nextAfterLoop = emitLoop(cur, loop, stopId, scopeVisited, depth);
149
+ cur = nextAfterLoop;
150
+ continue;
151
+ }
152
+
153
+ scopeVisited.add(cur);
154
+ emitted.add(cur);
155
+
156
+ // Emit block's non-terminator statements
157
+ for (const s of block.stmts) {
158
+ out.push(s);
159
+ }
160
+
161
+ if (block.term === 'return' || block.term === 'throw') {
162
+ return;
163
+ }
164
+
165
+ if (block.term === 'fallthrough' || block.term === 'jump') {
166
+ cur = block.next ?? null;
167
+ continue;
168
+ }
169
+
170
+ if (block.term === 'branch') {
171
+ const tId = block.trueTarget ?? null;
172
+ const fId = block.falseTarget ?? null;
173
+ const cond = block.cond || 'true';
174
+
175
+ // Direct loop-control shortcuts when inside a loop
176
+ if (loopExit !== null && tId === loopExit && fId !== loopExit) {
177
+ out.push(`if (${cond}) break;`);
178
+ cur = fId;
179
+ continue;
180
+ }
181
+ if (loopExit !== null && fId === loopExit && tId !== loopExit) {
182
+ out.push(`if (${negateExpr(cond)}) break;`);
183
+ cur = tId;
184
+ continue;
185
+ }
186
+ if (loopHeader !== null && tId === loopHeader && fId !== loopHeader) {
187
+ out.push(`if (${cond}) continue;`);
188
+ cur = fId;
189
+ continue;
190
+ }
191
+ if (loopHeader !== null && fId === loopHeader && tId !== loopHeader) {
192
+ out.push(`if (${negateExpr(cond)}) continue;`);
193
+ cur = tId;
194
+ continue;
195
+ }
196
+
197
+ // A missing successor ends this activation. It is a possible exit,
198
+ // so the other successor cannot be a post-dominator of this branch.
199
+ if (tId === null || fId === null) {
200
+ if (tId === fId) {
201
+ out.push(`if (${cond}) return;`);
202
+ out.push('return;');
203
+ return;
204
+ }
205
+ out.push(`if (${tId === null ? cond : negateExpr(cond)}) return;`);
206
+ cur = tId === null ? fId : tId;
207
+ continue;
208
+ }
209
+
210
+ if (tId === fId) {
211
+ out.push(`void (${cond});`);
212
+ cur = tId;
213
+ continue;
214
+ }
215
+
216
+ // Find merge point (immediate post-dominator or earliest common forward node, bounded by stopId)
217
+ const mergeId = findBranchMerge(cur, tId, fId, stopId, loopHeader);
218
+
219
+ // Pattern: if (cond) { then } -> merge
220
+ if (fId === mergeId && tId !== null) {
221
+ out.push(`if (${cond}) {`);
222
+ emitIndented(tId, mergeId, loopHeader, loopExit, new Set(scopeVisited), depth + 1);
223
+ out.push(`}`);
224
+ cur = mergeId;
225
+ continue;
226
+ }
227
+
228
+ // Pattern: if (!(cond)) { else } -> merge
229
+ if (tId === mergeId && fId !== null) {
230
+ out.push(`if (${negateExpr(cond)}) {`);
231
+ emitIndented(fId, mergeId, loopHeader, loopExit, new Set(scopeVisited), depth + 1);
232
+ out.push(`}`);
233
+ cur = mergeId;
234
+ continue;
235
+ }
236
+
237
+ // Pattern: early return/throw on true branch -> no `else` wrapper needed
238
+ const tBlock = tId !== null ? blockMap.get(tId) : null;
239
+ if (tBlock && (tBlock.term === 'return' || tBlock.term === 'throw') && mergeId === null) {
240
+ out.push(`if (${cond}) {`);
241
+ emitIndented(tId, stopId, loopHeader, loopExit, new Set(scopeVisited), depth + 1);
242
+ out.push(`}`);
243
+ cur = fId;
244
+ continue;
245
+ }
246
+
247
+ // Pattern: early return/throw on false branch
248
+ const fBlock = fId !== null ? blockMap.get(fId) : null;
249
+ if (fBlock && (fBlock.term === 'return' || fBlock.term === 'throw') && mergeId === null) {
250
+ out.push(`if (${negateExpr(cond)}) {`);
251
+ emitIndented(fId, stopId, loopHeader, loopExit, new Set(scopeVisited), depth + 1);
252
+ out.push(`}`);
253
+ cur = tId;
254
+ continue;
255
+ }
256
+
257
+ // Full if / else
258
+ out.push(`if (${cond}) {`);
259
+ if (tId !== null) {
260
+ emitIndented(tId, mergeId ?? stopId, loopHeader, loopExit, new Set(scopeVisited), depth + 1);
261
+ }
262
+ out.push(`} else {`);
263
+ if (fId !== null) {
264
+ emitIndented(fId, mergeId ?? stopId, loopHeader, loopExit, new Set(scopeVisited), depth + 1);
265
+ }
266
+ out.push(`}`);
267
+ cur = mergeId;
268
+ continue;
269
+ }
270
+
271
+ if (block.term === 'switch') {
272
+ const cases = block.switchCases ?? [];
273
+ const defId = block.switchDefault ?? null;
274
+ const mergeId = findSwitchMerge(cur, cases, defId, stopId, postDoms, orderIndex);
275
+ const beforeSwitch = new Set(emitted);
276
+ const armBlocks = new Set();
277
+ const emitArm = target => {
278
+ // One dispatch may run through another arm's entry before reaching
279
+ // the common continuation. Each arm needs its own copy of that code.
280
+ out.push(' {');
281
+ const bodyStart = out.length;
282
+ emitRegion(target, mergeId ?? stopId, loopHeader, loopExit, new Set(scopeVisited), depth + 1);
283
+ for (let k = bodyStart; k < out.length; k++) out[k] = ' ' + out[k];
284
+ const term = blockMap.get(target)?.term;
285
+ if (term !== 'return' && term !== 'throw') out.push(' break;');
286
+ out.push(' }');
287
+ for (const id of emitted) {
288
+ if (beforeSwitch.has(id)) continue;
289
+ armBlocks.add(id);
290
+ emitted.delete(id);
291
+ }
292
+ };
293
+
294
+ out.push(`switch (${block.switchExpr ?? '0'}) {`);
295
+ for (const c of cases) {
296
+ for (const v of c.values) {
297
+ out.push(` case ${v}:`);
298
+ }
299
+ emitArm(c.target);
300
+ }
301
+ if (defId !== null && defId !== mergeId) {
302
+ out.push(` default:`);
303
+ emitArm(defId);
304
+ }
305
+ out.push(`}`);
306
+ for (const id of armBlocks) emitted.add(id);
307
+ cur = mergeId;
308
+ continue;
309
+ }
310
+
311
+ break;
312
+ }
313
+ }
314
+
315
+ function emitIndented(id, stopId, loopHeader, loopExit, scopeVisited, depth) {
316
+ const startIdx = out.length;
317
+ emitRegion(id, stopId, loopHeader, loopExit, scopeVisited, depth);
318
+ for (let k = startIdx; k < out.length; k++) {
319
+ out[k] = ' ' + out[k];
320
+ }
321
+ }
322
+
323
+ function findBranchMerge(id, trueTarget, falseTarget, stopId, loopHeader) {
324
+ const merge = findMergeNode(id, trueTarget, falseTarget, stopId, postDoms, fwdReach, blockMap, orderIndex, loopHeader);
325
+ const loop = naturalLoops.get(loopHeader);
326
+ if (merge !== stopId) return merge;
327
+
328
+ // A lookupswitch can dispatch to case bodies earlier in the bytecode.
329
+ // The forward graph misses such paths to a shared tail. Only hoist a
330
+ // direct branch target when every path through the other arm reaches it.
331
+ const stopOrder = stopId === loopHeader ? Infinity : orderIndex.get(stopId) ?? Infinity;
332
+ for (const [target, alternate] of [[trueTarget, falseTarget], [falseTarget, trueTarget]]) {
333
+ const targetOrder = orderIndex.get(target);
334
+ if ((loop && !loop.body.has(target)) || target === loopHeader ||
335
+ targetOrder <= orderIndex.get(id) || targetOrder > stopOrder) continue;
336
+ const path = new Set();
337
+ const confirmed = new Set([target]);
338
+ const reachesTarget = blockId => {
339
+ if (confirmed.has(blockId)) return true;
340
+ if (blockId === stopId || blockId === loopHeader || (loop && !loop.body.has(blockId)) ||
341
+ path.has(blockId) || path.size > 80) return false;
342
+ const block = blockMap.get(blockId);
343
+ const edges = succs.get(blockId);
344
+ if (!edges?.length || (block.term === 'branch' &&
345
+ (!blockMap.has(block.trueTarget) || !blockMap.has(block.falseTarget))) ||
346
+ (block.term === 'switch' && !blockMap.has(block.switchDefault))) return false;
347
+ path.add(blockId);
348
+ if (!edges.every(reachesTarget)) return false;
349
+ path.delete(blockId);
350
+ confirmed.add(blockId);
351
+ return true;
352
+ };
353
+ if (reachesTarget(alternate)) return target;
354
+ }
355
+ return merge;
356
+ }
357
+
358
+ /**
359
+ * Emit a natural loop headed at `headerId`.
360
+ * Recognizes while, mxmlc-style jump-to-test while, do-while, and while(true).
361
+ * Returns the follow/exit block ID after the loop.
362
+ */
363
+ function emitLoop(headerId, loop, outerStopId, scopeVisited, depth) {
364
+ const header = blockMap.get(headerId);
365
+ const { body, exits, backSources } = loop;
366
+
367
+ // Choose primary exit node (first exit outside loop, ideally matching outerStopId or lowest PC)
368
+ let exitId = null;
369
+ if (exits.size > 0) {
370
+ const sortedExits = Array.from(exits).sort((a, b) => (orderIndex.get(a) ?? 0) - (orderIndex.get(b) ?? 0));
371
+ exitId = sortedExits[0];
372
+ }
373
+ if (exitId === null) exitId = outerStopId;
374
+
375
+ // 1. Standard while-loop at header: `header` is a branch with one arm in loop and one arm = exit
376
+ const headerContainsOnlyBudgetChecks = header.stmts.every((stmt) => /^_avm[12]CheckBudget\(\d*\);$/.test(stmt));
377
+ if (header.term === 'branch' && headerContainsOnlyBudgetChecks) {
378
+ const tIn = header.trueTarget !== null && body.has(header.trueTarget);
379
+ const fIn = header.falseTarget !== null && body.has(header.falseTarget);
380
+ if (tIn && !fIn) {
381
+ emitted.add(headerId);
382
+ if (header.stmts.length === 0) {
383
+ out.push(`while (${header.cond}) {`);
384
+ } else {
385
+ out.push(`while (true) {`);
386
+ for (const s of header.stmts) out.push(' ' + s);
387
+ out.push(` if (${negateExpr(header.cond)}) break;`);
388
+ }
389
+ emitIndented(header.trueTarget, headerId, headerId, header.falseTarget, new Set(scopeVisited), depth + 1);
390
+ out.push(`}`);
391
+ return header.falseTarget;
392
+ }
393
+ if (fIn && !tIn) {
394
+ emitted.add(headerId);
395
+ if (header.stmts.length === 0) {
396
+ out.push(`while (${negateExpr(header.cond)}) {`);
397
+ } else {
398
+ out.push(`while (true) {`);
399
+ for (const s of header.stmts) out.push(' ' + s);
400
+ out.push(` if (${header.cond}) break;`);
401
+ }
402
+ emitIndented(header.falseTarget, headerId, headerId, header.trueTarget, new Set(scopeVisited), depth + 1);
403
+ out.push(`}`);
404
+ return header.trueTarget;
405
+ }
406
+ }
407
+
408
+ // 2. mxmlc / ASC style loop: `header` unconditionally jumps to test block `C` at bottom of loop,
409
+ // and `C` branches back to `headerNext` (or `bodyEntry`) and exits to `exitId`.
410
+ if (header.term === 'jump' && header.stmts.length === 0 && header.next !== null && body.has(header.next)) {
411
+ const testBlock = blockMap.get(header.next);
412
+ if (testBlock && testBlock.term === 'branch') {
413
+ const tIn = testBlock.trueTarget !== null && body.has(testBlock.trueTarget) && testBlock.trueTarget !== headerId;
414
+ const fIn = testBlock.falseTarget !== null && body.has(testBlock.falseTarget) && testBlock.falseTarget !== headerId;
415
+ if ((tIn && !fIn) || (fIn && !tIn)) {
416
+ const bodyEntry = tIn ? testBlock.trueTarget : testBlock.falseTarget;
417
+ const loopExitTarget = tIn ? testBlock.falseTarget : testBlock.trueTarget;
418
+ const condExpr = tIn ? testBlock.cond : negateExpr(testBlock.cond);
419
+
420
+ emitted.add(headerId);
421
+ emitted.add(testBlock.id);
422
+ if (testBlock.stmts.length === 0) {
423
+ out.push(`while (${condExpr}) {`);
424
+ emitIndented(bodyEntry, testBlock.id, header.next, loopExitTarget, new Set(scopeVisited), depth + 1);
425
+ out.push(`}`);
426
+ } else {
427
+ out.push(`while (true) {`);
428
+ for (const s of testBlock.stmts) out.push(' ' + s);
429
+ out.push(` if (${negateExpr(condExpr)}) break;`);
430
+ emitIndented(bodyEntry, testBlock.id, header.next, loopExitTarget, new Set(scopeVisited), depth + 1);
431
+ out.push(`}`);
432
+ }
433
+ return loopExitTarget;
434
+ }
435
+ }
436
+ }
437
+
438
+ // 3. do { ... } while (cond): single back-edge source `T` is a conditional branch to `headerId`
439
+ if (backSources.length === 1) {
440
+ const tailId = backSources[0];
441
+ const tail = blockMap.get(tailId);
442
+ if (tail && tail.term === 'branch' && tailId !== headerId) {
443
+ if (tail.trueTarget === headerId && !body.has(tail.falseTarget)) {
444
+ emitted.add(headerId);
445
+ emitted.add(tailId);
446
+ out.push(`do {`);
447
+ for (const s of header.stmts) out.push(' ' + s);
448
+ if (header.term === 'fallthrough' || header.term === 'jump') {
449
+ emitIndented(header.next, tailId, headerId, tail.falseTarget, new Set(scopeVisited), depth + 1);
450
+ } else if (header.term === 'branch') {
451
+ // Re-emit header without loop-header guard by emitting its branch inside do-while
452
+ emitHeaderBranchInsideLoop(header, tailId, headerId, tail.falseTarget, scopeVisited, depth + 1);
453
+ }
454
+ for (const s of tail.stmts) out.push(' ' + s);
455
+ out.push(`} while (${tail.cond});`);
456
+ return tail.falseTarget;
457
+ }
458
+ if (tail.falseTarget === headerId && !body.has(tail.trueTarget)) {
459
+ emitted.add(headerId);
460
+ emitted.add(tailId);
461
+ out.push(`do {`);
462
+ for (const s of header.stmts) out.push(' ' + s);
463
+ if (header.term === 'fallthrough' || header.term === 'jump') {
464
+ emitIndented(header.next, tailId, headerId, tail.trueTarget, new Set(scopeVisited), depth + 1);
465
+ } else if (header.term === 'branch') {
466
+ emitHeaderBranchInsideLoop(header, tailId, headerId, tail.trueTarget, scopeVisited, depth + 1);
467
+ }
468
+ for (const s of tail.stmts) out.push(' ' + s);
469
+ out.push(`} while (${negateExpr(tail.cond)});`);
470
+ return tail.trueTarget;
471
+ }
472
+ }
473
+ }
474
+
475
+ // 4. Generic while (true) loop
476
+ emitted.add(headerId);
477
+ out.push(`while (true) {`);
478
+ for (const s of header.stmts) out.push(' ' + s);
479
+ if (header.term === 'fallthrough' || header.term === 'jump') {
480
+ if (header.next === headerId) {
481
+ out.push(` continue;`);
482
+ } else {
483
+ emitIndented(header.next, exitId, headerId, exitId, new Set(scopeVisited), depth + 1);
484
+ }
485
+ } else if (header.term === 'branch') {
486
+ emitHeaderBranchInsideLoop(header, exitId, headerId, exitId, scopeVisited, depth + 1);
487
+ } else if (header.term === 'return' || header.term === 'throw') {
488
+ // returns/throws already inside header.stmts
489
+ }
490
+ out.push(`}`);
491
+ return exitId;
492
+ }
493
+
494
+ function emitHeaderBranchInsideLoop(header, stopId, loopHeader, loopExit, scopeVisited, depth) {
495
+ const tId = header.trueTarget;
496
+ const fId = header.falseTarget;
497
+ const cond = header.cond;
498
+ if (tId === loopExit) {
499
+ out.push(` if (${cond}) break;`);
500
+ emitIndented(fId, stopId, loopHeader, loopExit, new Set(scopeVisited), depth);
501
+ } else if (fId === loopExit) {
502
+ out.push(` if (${negateExpr(cond)}) break;`);
503
+ emitIndented(tId, stopId, loopHeader, loopExit, new Set(scopeVisited), depth);
504
+ } else {
505
+ const mergeId = findBranchMerge(header.id, tId, fId, stopId, loopHeader);
506
+ out.push(` if (${cond}) {`);
507
+ const s1 = out.length;
508
+ emitRegion(tId, mergeId ?? stopId, loopHeader, loopExit, new Set(scopeVisited), depth + 1);
509
+ for (let k = s1; k < out.length; k++) out[k] = ' ' + out[k];
510
+ if (fId !== mergeId) {
511
+ out.push(` } else {`);
512
+ const s2 = out.length;
513
+ emitRegion(fId, mergeId ?? stopId, loopHeader, loopExit, new Set(scopeVisited), depth + 1);
514
+ for (let k = s2; k < out.length; k++) out[k] = ' ' + out[k];
515
+ }
516
+ out.push(` }`);
517
+ if (mergeId !== null && mergeId !== stopId) {
518
+ emitIndented(mergeId, stopId, loopHeader, loopExit, new Set(scopeVisited), depth);
519
+ }
520
+ }
521
+ }
522
+
523
+ /** Fallback dispatcher when recursion depth or irreducible CFG prevents inline folding. */
524
+ function emitFallbackDispatcher(startBlockId, stopId, loopHeader, loopExit) {
525
+ const subBlocks = [];
526
+ const seen = new Set();
527
+ const q = [startBlockId];
528
+ while (q.length > 0) {
529
+ const bid = q.pop();
530
+ if (bid === null || bid === undefined || bid === stopId || bid === loopExit || seen.has(bid) || emitted.has(bid)) continue;
531
+ const b = blockMap.get(bid);
532
+ if (!b) continue;
533
+ seen.add(bid);
534
+ emitted.add(bid);
535
+ subBlocks.push(b);
536
+ for (const s of succs.get(bid) ?? []) q.push(s);
537
+ }
538
+ if (subBlocks.length === 0) return;
539
+ subBlocks.sort((a, b) => a.id - b.id);
540
+
541
+ out.push(`var _pc = ${startBlockId};`);
542
+ out.push(`_cfg: while (_pc !== -1) {`);
543
+ out.push(` switch (_pc) {`);
544
+ for (const b of subBlocks) {
545
+ out.push(` case ${b.id}: {`);
546
+ for (const s of b.stmts) out.push(` ${s}`);
547
+ if (b.term === 'return' || b.term === 'throw') {
548
+ out.push(` _pc = -1; break;`);
549
+ } else if (b.term === 'fallthrough' || b.term === 'jump') {
550
+ const nxt = b.next;
551
+ if (nxt === null || nxt === stopId) out.push(` _pc = -1; break;`);
552
+ else if (nxt === loopExit) out.push(` break _cfg;`);
553
+ else out.push(` _pc = ${nxt}; break;`);
554
+ } else if (b.term === 'branch') {
555
+ const t = b.trueTarget === null || b.trueTarget === stopId ? -1 : b.trueTarget;
556
+ const f = b.falseTarget === null || b.falseTarget === stopId ? -1 : b.falseTarget;
557
+ out.push(` _pc = (${b.cond}) ? ${t} : ${f}; break;`);
558
+ } else {
559
+ out.push(` _pc = -1; break;`);
560
+ }
561
+ out.push(` }`);
562
+ }
563
+ out.push(` default: _pc = -1; break;`);
564
+ out.push(` }`);
565
+ out.push(`}`);
566
+ }
567
+
568
+ emitRegion(startId, null, null, null, new Set(), 0);
569
+ return unresolvedTransfer && emitDispatcher ? emitDispatcher() : out;
570
+ }
571
+
572
+ // ---- Graph analysis helpers ----
573
+
574
+ function connectImplicitExits(blocks, statement) {
575
+ // A terminal transfer must be a graph edge. Otherwise an exit reached by a
576
+ // jump in a loop can look like an empty arm that falls through to its latch.
577
+ const exitId = blocks[blocks.length - 1].id + 1;
578
+ let used = false;
579
+ const connected = blocks.map(block => {
580
+ if ((block.term === 'jump' || block.term === 'fallthrough') && block.next == null) {
581
+ used = true;
582
+ return { ...block, next: exitId };
583
+ }
584
+ if (block.term === 'branch' && (block.trueTarget == null || block.falseTarget == null)) {
585
+ used = true;
586
+ return { ...block, trueTarget: block.trueTarget ?? exitId, falseTarget: block.falseTarget ?? exitId };
587
+ }
588
+ return block;
589
+ });
590
+ if (used) connected.push({ id: exitId, stmts: [statement], term: 'return' });
591
+ return connected;
592
+ }
593
+
594
+ function computeGraph(startId, blockMap) {
595
+ const reachable = new Set();
596
+ const succs = new Map();
597
+ const preds = new Map();
598
+ const stack = [startId];
599
+
600
+ while (stack.length > 0) {
601
+ const id = stack.pop();
602
+ if (reachable.has(id)) continue;
603
+ const b = blockMap.get(id);
604
+ if (!b) continue;
605
+ reachable.add(id);
606
+
607
+ const s = [];
608
+ if ((b.term === 'fallthrough' || b.term === 'jump') && b.next != null && blockMap.has(b.next)) {
609
+ s.push(b.next);
610
+ } else if (b.term === 'branch') {
611
+ if (b.trueTarget != null && blockMap.has(b.trueTarget)) s.push(b.trueTarget);
612
+ if (b.falseTarget != null && blockMap.has(b.falseTarget) && b.falseTarget !== b.trueTarget) s.push(b.falseTarget);
613
+ } else if (b.term === 'switch') {
614
+ for (const c of b.switchCases ?? []) {
615
+ if (blockMap.has(c.target) && !s.includes(c.target)) s.push(c.target);
616
+ }
617
+ if (b.switchDefault != null && blockMap.has(b.switchDefault) && !s.includes(b.switchDefault)) {
618
+ s.push(b.switchDefault);
619
+ }
620
+ }
621
+ succs.set(id, s);
622
+ for (const target of s) {
623
+ if (!preds.has(target)) preds.set(target, []);
624
+ preds.get(target).push(id);
625
+ if (!reachable.has(target)) stack.push(target);
626
+ }
627
+ }
628
+ if (!preds.has(startId)) preds.set(startId, []);
629
+ return { reachable, preds, succs };
630
+ }
631
+
632
+ function computeDominators(startId, rBlocks, preds) {
633
+ // Bitwise/Set iterative dominator algorithm (Cooper-Harvey-Kennedy style using index sets)
634
+ const doms = new Map();
635
+ const allIds = new Set(rBlocks.map(b => b.id));
636
+ doms.set(startId, new Set([startId]));
637
+ for (const b of rBlocks) {
638
+ if (b.id !== startId) doms.set(b.id, new Set(allIds));
639
+ }
640
+
641
+ let changed = true;
642
+ let iters = 0;
643
+ while (changed && iters++ < 100) {
644
+ changed = false;
645
+ for (const b of rBlocks) {
646
+ if (b.id === startId) continue;
647
+ const ps = (preds.get(b.id) ?? []).filter(p => doms.has(p));
648
+ if (ps.length === 0) continue;
649
+ const newDom = new Set(doms.get(ps[0]));
650
+ for (let i = 1; i < ps.length; i++) {
651
+ const pd = doms.get(ps[i]);
652
+ for (const d of newDom) {
653
+ if (!pd.has(d)) newDom.delete(d);
654
+ }
655
+ }
656
+ newDom.add(b.id);
657
+ const oldDom = doms.get(b.id);
658
+ if (newDom.size !== oldDom.size) {
659
+ doms.set(b.id, newDom);
660
+ changed = true;
661
+ }
662
+ }
663
+ }
664
+ return doms;
665
+ }
666
+
667
+ function findNaturalLoops(rBlocks, succs, preds, doms, orderIndex) {
668
+ /** @type {Map<number, { body: Set<number>, exits: Set<number>, backSources: number[] }>} */
669
+ const loops = new Map();
670
+
671
+ for (const u of rBlocks) {
672
+ const uDoms = doms.get(u.id);
673
+ if (!uDoms) continue;
674
+ for (const h of succs.get(u.id) ?? []) {
675
+ if (uDoms.has(h)) {
676
+ // u -> h is a back-edge
677
+ if (!loops.has(h)) {
678
+ loops.set(h, { body: new Set([h]), exits: new Set(), backSources: [] });
679
+ }
680
+ const loop = loops.get(h);
681
+ loop.backSources.push(u.id);
682
+ const work = [u.id];
683
+ while (work.length > 0) {
684
+ const n = work.pop();
685
+ if (!loop.body.has(n)) {
686
+ loop.body.add(n);
687
+ for (const p of preds.get(n) ?? []) {
688
+ if (!loop.body.has(p)) work.push(p);
689
+ }
690
+ }
691
+ }
692
+ }
693
+ }
694
+ }
695
+
696
+ for (const [, loop] of loops) {
697
+ for (const n of loop.body) {
698
+ for (const s of succs.get(n) ?? []) {
699
+ if (!loop.body.has(s)) loop.exits.add(s);
700
+ }
701
+ }
702
+ }
703
+ return loops;
704
+ }
705
+
706
+ function computePostDominators(rBlocks, succs, preds, orderIndex) {
707
+ // Compute post-dominators on forward edges (ignoring back-edges where target <= source)
708
+ const postDoms = new Map();
709
+ const exitNodes = rBlocks.filter(b => {
710
+ const fwdSuccs = (succs.get(b.id) ?? []).filter(s => (orderIndex.get(s) ?? 0) > (orderIndex.get(b.id) ?? 0));
711
+ return fwdSuccs.length === 0;
712
+ });
713
+
714
+ const allIds = new Set(rBlocks.map(b => b.id));
715
+ for (const b of rBlocks) {
716
+ postDoms.set(b.id, exitNodes.some(e => e.id === b.id) ? new Set([b.id]) : new Set(allIds));
717
+ }
718
+
719
+ let changed = true;
720
+ let iters = 0;
721
+ while (changed && iters++ < 100) {
722
+ changed = false;
723
+ for (let i = rBlocks.length - 1; i >= 0; i--) {
724
+ const b = rBlocks[i];
725
+ const fwdSuccs = (succs.get(b.id) ?? []).filter(s => (orderIndex.get(s) ?? 0) > (orderIndex.get(b.id) ?? 0));
726
+ if (fwdSuccs.length === 0) continue;
727
+ const newPd = new Set(postDoms.get(fwdSuccs[0]));
728
+ for (let j = 1; j < fwdSuccs.length; j++) {
729
+ const sd = postDoms.get(fwdSuccs[j]);
730
+ for (const d of newPd) {
731
+ if (!sd.has(d)) newPd.delete(d);
732
+ }
733
+ }
734
+ newPd.add(b.id);
735
+ const oldPd = postDoms.get(b.id);
736
+ if (newPd.size !== oldPd.size) {
737
+ postDoms.set(b.id, newPd);
738
+ changed = true;
739
+ }
740
+ }
741
+ }
742
+ return postDoms;
743
+ }
744
+
745
+ function computeForwardReachable(rBlocks, succs, orderIndex) {
746
+ const reach = new Map();
747
+ for (let i = rBlocks.length - 1; i >= 0; i--) {
748
+ const id = rBlocks[i].id;
749
+ const ord = orderIndex.get(id) ?? 0;
750
+ const set = new Set([id]);
751
+ for (const s of succs.get(id) ?? []) {
752
+ if ((orderIndex.get(s) ?? 0) > ord) {
753
+ const sr = reach.get(s);
754
+ if (sr) {
755
+ for (const x of sr) set.add(x);
756
+ } else {
757
+ set.add(s);
758
+ }
759
+ }
760
+ }
761
+ reach.set(id, set);
762
+ }
763
+ return reach;
764
+ }
765
+
766
+ function findMergeNode(branchId, tId, fId, stopId, postDoms, fwdReach, blockMap, orderIndex, loopHeader = null) {
767
+ const bOrd = orderIndex.get(branchId) ?? 0;
768
+ const boundaryOrd = orderIndex.get(stopId) ?? Infinity;
769
+ // A loop header behind the branch ends an iteration on a back edge.
770
+ // Forward shared tails (including the latch) are still inside this region.
771
+ const stopOrd = stopId === loopHeader && boundaryOrd <= bOrd ? Infinity : boundaryOrd;
772
+
773
+ const pds = postDoms.get(branchId);
774
+ if (pds) {
775
+ const candidates = Array.from(pds)
776
+ .filter(id => id !== branchId && (orderIndex.get(id) ?? 0) > bOrd)
777
+ .sort((a, b) => (orderIndex.get(a) ?? 0) - (orderIndex.get(b) ?? 0));
778
+ if (candidates.length > 0) {
779
+ const first = candidates[0];
780
+ if ((orderIndex.get(first) ?? Infinity) <= stopOrd) return first;
781
+ return stopId;
782
+ }
783
+ }
784
+
785
+ // Fallback: earliest common forward-reachable node from both tId and fId
786
+ if (tId !== null && fId !== null) {
787
+ const tr = fwdReach.get(tId);
788
+ const fr = fwdReach.get(fId);
789
+ if (tr && fr) {
790
+ let bestId = null;
791
+ let bestOrd = Infinity;
792
+ for (const id of tr) {
793
+ if (!fr.has(id)) continue;
794
+ const ord = orderIndex.get(id) ?? Infinity;
795
+ if (ord > bOrd && ord <= stopOrd && ord < bestOrd) {
796
+ bestOrd = ord;
797
+ bestId = id;
798
+ }
799
+ }
800
+ if (bestId !== null) return bestId;
801
+ }
802
+ const tb = blockMap.get(tId);
803
+ const fb = blockMap.get(fId);
804
+ if (tb && (tb.term === 'fallthrough' || tb.term === 'jump') && tb.next === fId) return fId;
805
+ if (fb && (fb.term === 'fallthrough' || fb.term === 'jump') && fb.next === tId) return tId;
806
+ }
807
+ return stopId;
808
+ }
809
+
810
+ function findSwitchMerge(switchId, cases, defId, stopId, postDoms, orderIndex) {
811
+ const targets = [defId, ...cases.map(entry => entry.target)];
812
+ // AVM2 compilers can place the dispatch after its arms. The forward graph
813
+ // drops those backward edges, but each arm still has its own post-dominators.
814
+ const candidates = Array.from(postDoms.get(defId) ?? [])
815
+ .filter(id => id !== switchId && (stopId === null || orderIndex.get(id) <= orderIndex.get(stopId)) &&
816
+ targets.every(target => postDoms.get(target)?.has(id)))
817
+ .sort((a, b) => orderIndex.get(a) - orderIndex.get(b));
818
+ return candidates.length > 0 ? candidates[0] : stopId;
819
+ }
820
+
821
+ /** Simplify negation of a boolean condition expression without changing semantics. */
822
+ function negateExpr(expr) {
823
+ let s = expr.trim();
824
+ // Strip outer redundant parens
825
+ while (s.startsWith('(') && s.endsWith(')')) {
826
+ let depth = 0, wraps = true;
827
+ for (let k = 0; k < s.length - 1; k++) {
828
+ if (s[k] === '(') depth++;
829
+ else if (s[k] === ')') depth--;
830
+ if (depth === 0) { wraps = false; break; }
831
+ }
832
+ if (wraps) s = s.slice(1, -1).trim();
833
+ else break;
834
+ }
835
+ if (s.startsWith('!')) {
836
+ let inner = s.slice(1).trim();
837
+ while (inner.startsWith('(') && inner.endsWith(')')) {
838
+ let depth = 0, wraps = true;
839
+ for (let k = 0; k < inner.length - 1; k++) {
840
+ if (inner[k] === '(') depth++;
841
+ else if (inner[k] === ')') depth--;
842
+ if (depth === 0) { wraps = false; break; }
843
+ }
844
+ if (wraps) inner = inner.slice(1, -1).trim();
845
+ else break;
846
+ }
847
+ return inner;
848
+ }
849
+ // Flip top-level equality comparisons safely
850
+ const eqFlip = flipTopLevelOp(s);
851
+ if (eqFlip) return eqFlip;
852
+ return `!(${s})`;
853
+ }
854
+
855
+ function flipTopLevelOp(s) {
856
+ let depth = 0, inStr = null, esc = false;
857
+ for (let i = 0; i < s.length; i++) {
858
+ const ch = s[i];
859
+ if (esc) { esc = false; continue; }
860
+ if (inStr) {
861
+ if (ch === '\\') esc = true;
862
+ else if (ch === inStr) inStr = null;
863
+ continue;
864
+ }
865
+ if (ch === '"' || ch === "'") { inStr = ch; continue; }
866
+ if (ch === '(' || ch === '[' || ch === '{') { depth++; continue; }
867
+ if (ch === ')' || ch === ']' || ch === '}') { depth--; continue; }
868
+ if (depth === 0) {
869
+ if (s.startsWith('===', i)) return `${s.slice(0, i)}!==${s.slice(i + 3)}`;
870
+ if (s.startsWith('!==', i)) return `${s.slice(0, i)}===${s.slice(i + 3)}`;
871
+ if (s.startsWith('==', i) && s[i + 2] !== '=') return `${s.slice(0, i)}!=${s.slice(i + 2)}`;
872
+ if (s.startsWith('!=', i) && s[i + 2] !== '=') return `${s.slice(0, i)}==${s.slice(i + 2)}`;
873
+ }
874
+ }
875
+ return null;
876
+ }