swf2js 0.0.0-stage → 0.1.1

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,2560 @@
1
+ /**
2
+ * @fileoverview AVM2_Transpiler — converts AVM2/ABC bytecode to JavaScript ES2020.
3
+ *
4
+ * AVM2 is a typed, stack-based VM with a scope chain, multinames, and an explicit
5
+ * class system. We transpile each ABC method body to a JS function, and each ABC
6
+ * class to an ES6 class declaration.
7
+ *
8
+ * Uses CFG reachability traversal over method bytecode so control-flow obfuscation
9
+ * (unconditional jumps over dead junk bytes, opaque predicates) does not desync
10
+ * instruction decoding.
11
+ *
12
+ * The output is a string of ES2020 JS declarations suitable for inclusion in bundle.js.
13
+ */
14
+
15
+ import { AbcReader } from './abc-reader.js';
16
+ import { DiagnosticsCollector } from '../../util/diagnostics.js';
17
+ import { structureCfg } from '../cfg-structurer.js';
18
+
19
+ // Multiname kinds that pop runtime components from the operand stack
20
+ const MN_RTQNAME = 0x0F;
21
+ const MN_RTQNAME_A = 0x10;
22
+ const MN_RTQNAME_L = 0x11;
23
+ const MN_RTQNAME_LA = 0x12;
24
+ const MN_MULTINAME_L = 0x1B;
25
+ const MN_MULTINAME_LA = 0x1C;
26
+
27
+ const MAX_STACK_ARGS = 4096;
28
+
29
+ const JS_RESERVED = new Set([
30
+ 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default',
31
+ 'delete', 'do', 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for',
32
+ 'function', 'if', 'import', 'in', 'instanceof', 'new', 'null', 'return', 'super',
33
+ 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while',
34
+ 'with', 'yield', 'let', 'static', 'implements', 'interface', 'package', 'private',
35
+ 'protected', 'public', 'await', 'eval', 'arguments',
36
+ ]);
37
+
38
+ // AVM2 instruction opcodes (AVM2 Overview §4)
39
+ export const ABC = {
40
+ bkpt: 0x01,
41
+ nop: 0x02,
42
+ throw: 0x03,
43
+ getsuper: 0x04,
44
+ setsuper: 0x05,
45
+ dxns: 0x06,
46
+ dxnslate: 0x07,
47
+ kill: 0x08,
48
+ label: 0x09,
49
+
50
+ ifnlt: 0x0C,
51
+ ifnle: 0x0D,
52
+ ifngt: 0x0E,
53
+ ifnge: 0x0F,
54
+ jump: 0x10,
55
+ iftrue: 0x11,
56
+ iffalse: 0x12,
57
+ ifeq: 0x13,
58
+ ifne: 0x14,
59
+ iflt: 0x15,
60
+ ifle: 0x16,
61
+ ifgt: 0x17,
62
+ ifge: 0x18,
63
+ ifstricteq: 0x19,
64
+ ifstrictne: 0x1A,
65
+ lookupswitch: 0x1B,
66
+ pushwith: 0x1C,
67
+ popscope: 0x1D,
68
+ nextname: 0x1E,
69
+ hasnext: 0x1F,
70
+
71
+ pushnull: 0x20,
72
+ pushundefined: 0x21,
73
+ nextvalue: 0x23,
74
+ pushbyte: 0x24,
75
+ pushshort: 0x25,
76
+ pushtrue: 0x26,
77
+ pushfalse: 0x27,
78
+ pushnan: 0x28,
79
+ pop: 0x29,
80
+ dup: 0x2A,
81
+ swap: 0x2B,
82
+ pushstring: 0x2C,
83
+ pushint: 0x2D,
84
+ pushuint: 0x2E,
85
+ pushdouble: 0x2F,
86
+
87
+ pushscope: 0x30,
88
+ pushnamespace: 0x31,
89
+ hasnext2: 0x32,
90
+ li8: 0x35,
91
+ li16: 0x36,
92
+ li32: 0x37,
93
+ lf32: 0x38,
94
+ lf64: 0x39,
95
+ si8: 0x3A,
96
+ si16: 0x3B,
97
+ si32: 0x3C,
98
+ sf32: 0x3D,
99
+ sf64: 0x3E,
100
+
101
+ newfunction: 0x40,
102
+ call: 0x41,
103
+ construct: 0x42,
104
+ callmethod: 0x43,
105
+ callstatic: 0x44,
106
+ callsuper: 0x45,
107
+ callproperty: 0x46,
108
+ returnvoid: 0x47,
109
+ returnvalue: 0x48,
110
+ constructsuper: 0x49,
111
+ constructprop: 0x4A,
112
+ callsuperid: 0x4B,
113
+ callproplex: 0x4C,
114
+ callsupervoid: 0x4E,
115
+ callpropvoid: 0x4F,
116
+
117
+ sxi1: 0x50,
118
+ sxi8: 0x51,
119
+ sxi16: 0x52,
120
+ applytype: 0x53,
121
+ newobject: 0x55,
122
+ newarray: 0x56,
123
+ newactivation: 0x57,
124
+ newclass: 0x58,
125
+ getdescendants: 0x59,
126
+ newcatch: 0x5A,
127
+ findpropglobalstrict: 0x5B,
128
+ findpropglobal: 0x5C,
129
+ findpropstrict: 0x5D,
130
+ findproperty: 0x5E,
131
+ finddef: 0x5F,
132
+
133
+ getlex: 0x60,
134
+ setproperty: 0x61,
135
+ getlocal: 0x62,
136
+ setlocal: 0x63,
137
+ getglobalscope: 0x64,
138
+ getscopeobject: 0x65,
139
+ getproperty: 0x66,
140
+ getouterscope: 0x67,
141
+ initproperty: 0x68,
142
+ setpropertylate: 0x69,
143
+ deleteproperty: 0x6A,
144
+ deletepropertylate: 0x6B,
145
+ getslot: 0x6C,
146
+ setslot: 0x6D,
147
+ getglobalslot: 0x6E,
148
+ setglobalslot: 0x6F,
149
+
150
+ convert_s: 0x70,
151
+ esc_xelem: 0x71,
152
+ esc_xattr: 0x72,
153
+ convert_i: 0x73,
154
+ convert_u: 0x74,
155
+ convert_d: 0x75,
156
+ convert_b: 0x76,
157
+ convert_o: 0x77,
158
+ checkfilter: 0x78,
159
+
160
+ coerce: 0x80,
161
+ coerce_b: 0x81,
162
+ coerce_a: 0x82,
163
+ coerce_i: 0x83,
164
+ coerce_d: 0x84,
165
+ coerce_s: 0x85,
166
+ astype: 0x86,
167
+ astypelate: 0x87,
168
+ coerce_u: 0x88,
169
+ coerce_o: 0x89,
170
+
171
+ negate: 0x90,
172
+ increment: 0x91,
173
+ inclocal: 0x92,
174
+ decrement: 0x93,
175
+ declocal: 0x94,
176
+ typeof: 0x95,
177
+ not: 0x96,
178
+ bitnot: 0x97,
179
+
180
+ add: 0xA0,
181
+ subtract: 0xA1,
182
+ multiply: 0xA2,
183
+ divide: 0xA3,
184
+ modulo: 0xA4,
185
+ lshift: 0xA5,
186
+ rshift: 0xA6,
187
+ urshift: 0xA7,
188
+ bitand: 0xA8,
189
+ bitor: 0xA9,
190
+ bitxor: 0xAA,
191
+ equals: 0xAB,
192
+ strictequals: 0xAC,
193
+ lessthan: 0xAD,
194
+ lessequals: 0xAE,
195
+ greaterthan: 0xAF,
196
+ greaterequals: 0xB0,
197
+ instanceof: 0xB1,
198
+ istype: 0xB2,
199
+ istypelate: 0xB3,
200
+ in: 0xB4,
201
+
202
+ increment_i: 0xC0,
203
+ decrement_i: 0xC1,
204
+ inclocal_i: 0xC2,
205
+ declocal_i: 0xC3,
206
+ negate_i: 0xC4,
207
+ add_i: 0xC5,
208
+ subtract_i: 0xC6,
209
+ multiply_i: 0xC7,
210
+
211
+ getlocal0: 0xD0,
212
+ getlocal1: 0xD1,
213
+ getlocal2: 0xD2,
214
+ getlocal3: 0xD3,
215
+ setlocal0: 0xD4,
216
+ setlocal1: 0xD5,
217
+ setlocal2: 0xD6,
218
+ setlocal3: 0xD7,
219
+
220
+ debug: 0xEF,
221
+ debugline: 0xF0,
222
+ debugfile: 0xF1,
223
+ bkptline: 0xF2,
224
+ timestamp: 0xF3,
225
+ };
226
+
227
+ let _nextAvm2BlockId = 0;
228
+
229
+ /**
230
+ * Transpile a DoABC tag's abcData buffer to JavaScript.
231
+ * Returns a string of ES2020 class and function declarations.
232
+ *
233
+ * @param {Uint8Array} abcData
234
+ * @param {DiagnosticsCollector} diagnostics
235
+ * @param {object} [opts]
236
+ * @param {boolean} [opts.skeletonOnly=false] - emit class skeletons without method bodies
237
+ * @param {number} [opts.maxMethods=Infinity] - max method bodies to transpile
238
+ * @returns {string}
239
+ */
240
+ function avm2Reflection(abc, instance, cls, classTrait) {
241
+ const { strings, multinames } = abc.constantPool;
242
+ function typeName(index) {
243
+ const name = multinames[index];
244
+ if (!name) return '*';
245
+ if (name.typeBaseIndex !== undefined) {
246
+ return `${typeName(name.typeBaseIndex)}.<${name.typeParameterIndices.map(typeName).join(',')}>`;
247
+ }
248
+ return name.ns ? `${name.ns}::${name.localName}` : name.localName || '*';
249
+ }
250
+ function annotations(trait) {
251
+ return (trait?.metadataIndices || []).map(index => abc.metadata[index]).filter(Boolean)
252
+ .map(({ nameIndex, entries }) => [strings[nameIndex], entries.map(([key, value]) => [strings[key], strings[value]])]);
253
+ }
254
+ function parameters(method) {
255
+ const types = method?.paramTypes || [];
256
+ const required = types.length - (method?.optionalValues?.length || 0);
257
+ return types.map((type, index) => [typeName(type), index >= required]);
258
+ }
259
+ function members(traits) {
260
+ return traits.flatMap(trait => {
261
+ const name = multinames[trait.nameIndex];
262
+ if (!name || name.nsKind !== 0x16 || name.ns) return [];
263
+ const method = abc.methods[trait.methodIndex];
264
+ switch (trait.kind) {
265
+ case 0: case 6: return [[trait.kind, name.localName, typeName(trait.typeNameIndex), annotations(trait)]];
266
+ case 1: return [[1, name.localName, typeName(method?.returnType), annotations(trait), parameters(method)]];
267
+ case 2: return [[2, name.localName, typeName(method?.returnType), annotations(trait)]];
268
+ case 3: return [[3, name.localName, typeName(method?.paramTypes[0]), annotations(trait)]];
269
+ default: return [];
270
+ }
271
+ });
272
+ }
273
+ return [instance.flags, parameters(abc.methods[instance.iinit]), members(instance.traits), members(cls.traits), annotations(classTrait)];
274
+ }
275
+
276
+ export function transpileAvm2(abcData, diagnostics, opts = {}) {
277
+ let abc;
278
+ try {
279
+ abc = new AbcReader(abcData).read();
280
+ } catch (err) {
281
+ diagnostics.error(`ABC parse failed: ${err.message}`, 'transpile');
282
+ return `/* ABC parse failed: ${err.message} */`;
283
+ }
284
+
285
+ const cp = abc.constantPool;
286
+ abc.usesDefaultXmlNamespace = abc.methods.some(method => method.flags & 0x40); // SET_DXNS
287
+ const blockId = opts.blockId ?? _nextAvm2BlockId++;
288
+ const blockHash = _hashAbc(abcData);
289
+ const methodTableName = `_avm2MethodTable_${blockHash}_${blockId}`;
290
+ // ABC class indices are block-local. Keep their numeric table local to this
291
+ // ABC instead of sharing `_classes[index]` across unrelated DoABC blocks.
292
+ const classTableName = `_avm2ClassTable_${blockHash}_${blockId}`;
293
+ const namespaceKeys = new NamespaceKeyTable(`_ns${blockHash}_${blockId}`, cp, methodTableName);
294
+ const out = [];
295
+ const classInitializers = [];
296
+ const classScriptScopes = new Map();
297
+ const methodScriptScopes = new Map();
298
+ for (let scriptIndex = 0; scriptIndex < abc.scripts.length; scriptIndex++) {
299
+ for (const trait of abc.scripts[scriptIndex].traits) {
300
+ if ([1, 2, 3, 5].includes(trait.kind) && trait.methodIndex !== undefined) {
301
+ methodScriptScopes.set(trait.methodIndex, scriptIndex);
302
+ } else if (trait.kind === 4 && trait.classIndex !== undefined) {
303
+ classScriptScopes.set(trait.classIndex, scriptIndex);
304
+ }
305
+ }
306
+ }
307
+ for (let classIndex = 0; classIndex < abc.instances.length; classIndex++) {
308
+ const scriptIndex = classScriptScopes.get(classIndex);
309
+ if (scriptIndex === undefined) continue;
310
+ const instance = abc.instances[classIndex];
311
+ const cls = abc.classes[classIndex];
312
+ methodScriptScopes.set(instance.iinit, scriptIndex);
313
+ methodScriptScopes.set(cls.cinit, scriptIndex);
314
+ for (const trait of [...instance.traits, ...cls.traits]) {
315
+ if ([1, 2, 3, 5].includes(trait.kind) && trait.methodIndex !== undefined) {
316
+ methodScriptScopes.set(trait.methodIndex, scriptIndex);
317
+ }
318
+ }
319
+ }
320
+ // Function traits declared inside a method close over that method's script.
321
+ for (let methodIndex = 0; methodIndex < abc.methods.length; methodIndex++) {
322
+ const scriptIndex = methodScriptScopes.get(methodIndex);
323
+ if (scriptIndex === undefined) continue;
324
+ for (const trait of abc.methods[methodIndex].body?.traits || []) {
325
+ if (trait.kind === 5 && trait.methodIndex !== undefined) methodScriptScopes.set(trait.methodIndex, scriptIndex);
326
+ }
327
+ }
328
+ const skeletonOnly = Boolean(opts.skeletonOnly);
329
+ const maxMethods = opts.maxMethods ?? Infinity;
330
+ let transpiledMethodCount = 0;
331
+
332
+ // A script owns its global traits and global slot-number space. Preserve
333
+ // that scope separately even when multiple scripts reuse a slot ID.
334
+ const scriptScopeNames = abc.scripts.map((_, i) => `${methodTableName}_script_${i}`);
335
+ const scriptTraits = abc.scripts.map(script => script.traits.flatMap(trait => {
336
+ const multiname = cp.multinames[trait.nameIndex];
337
+ const name = _avm2PropertyName(multiname, `_trait${trait.nameIndex}`, methodTableName);
338
+ if (!name) return [];
339
+ const qualified = _avm2TypeTraitName(multiname, name, methodTableName);
340
+ if ((trait.kind === 0 || trait.kind === 6) && trait.valueIndex && _isNamespaceKind(trait.valueKind)) {
341
+ return [`[${JSON.stringify(name)}, ${trait.slotId || 0}, ${trait.kind}, ${JSON.stringify(qualified)}, ${_namespaceLiteral(cp, trait.valueIndex, methodTableName)}]`];
342
+ }
343
+ if (!trait.slotId || ![0, 4, 5, 6].includes(trait.kind)) return [JSON.stringify(name)];
344
+ const slot = [name, trait.slotId, trait.kind];
345
+ if (trait.kind === 4 && qualified !== name) slot.push(qualified);
346
+ return [JSON.stringify(slot)];
347
+ }));
348
+ if (scriptScopeNames.length) {
349
+ const scopes = scriptTraits.map(traits => `[${traits.join(',')}]`).join(',');
350
+ out.push(`var [${scriptScopeNames.join(', ')}] = _createAvm2ScriptScopes(${JSON.stringify(methodTableName)}, [${scopes}]);`);
351
+ }
352
+
353
+ // Disambiguate duplicate class names across packages in the same ABC block
354
+ const seenClasses = new Set();
355
+ const classNames = abc.instances.map((inst, i) => {
356
+ const name = cp.multinames[inst.nameIndex];
357
+ const rawName = name?.localName || `_Class${i}`;
358
+ let safe = _safeClass(rawName);
359
+ if (_avm2UsesNamespaceIdentity(name)) safe += `_abc_${blockHash}_${blockId}_${i}`;
360
+ if (seenClasses.has(safe)) {
361
+ const ns = cp.multinames[inst.nameIndex]?.ns;
362
+ const pkg = ns ? _safeIdent(ns) : '';
363
+ safe = pkg && !seenClasses.has(`${pkg}_${safe}`) ? `${pkg}_${safe}` : `${safe}_${i}`;
364
+ }
365
+ seenClasses.add(safe);
366
+ return safe;
367
+ });
368
+
369
+ const emitBody = (method, isCtor, hasSuper, scriptScopeId, isInitializer = false, lexicalClass, ownerClass, instanceMethod = false) => {
370
+ if (!method?.body) return '// native or abstract';
371
+ if (skeletonOnly || transpiledMethodCount >= maxMethods) {
372
+ return '/* body omitted */';
373
+ }
374
+ transpiledMethodCount++;
375
+ const methodIndex = abc.methods.indexOf(method);
376
+ const scopeId = scriptScopeId ?? methodScriptScopes.get(methodIndex) ?? 0;
377
+ return transpileMethodBody(method, abc, diagnostics, isCtor, hasSuper, methodTableName, classTableName, namespaceKeys, scopeId, isInitializer, lexicalClass, ownerClass, false, instanceMethod);
378
+ };
379
+
380
+ // Emit each class as an ES6 class declaration
381
+ for (let i = 0; i < abc.instances.length; i++) {
382
+ const inst = abc.instances[i];
383
+ const cls = abc.classes[i];
384
+
385
+ const className = classNames[i];
386
+ const superMn = inst.superNameIndex ? cp.multinames[inst.superNameIndex] : null;
387
+ const superRaw = superMn?.localName || null;
388
+ const superQualified = _avm2TypeTraitName(superMn, superRaw, methodTableName);
389
+ const hasSuper = Boolean(superQualified && superQualified !== 'Object');
390
+ // Resolve via _getlex so flash.utils.ByteArray / swflib builtins work even when
391
+ // the bare identifier is not a lexical binding (ReferenceError on `extends ByteArray`).
392
+ const nativeSuperNames = new Set(['Sprite', 'MovieClip', 'Shape', 'Bitmap', 'DisplayObject',
393
+ 'DisplayObjectContainer', 'EventDispatcher', 'ByteArray', 'Point', 'Rectangle', 'Matrix', 'TextField']);
394
+ const superFallback = _avm2UsesNamespaceIdentity(superMn) ? 'Object' : nativeSuperNames.has(superRaw) ? superRaw : `_getlex(${JSON.stringify(superRaw)}) || Object`;
395
+ const extendsClause = hasSuper
396
+ ? superQualified !== superRaw
397
+ ? ` extends (_getDefinition(${JSON.stringify(superQualified)}) || ${superFallback})`
398
+ : nativeSuperNames.has(superRaw) ? ` extends ${superRaw}` : ` extends (${superFallback})`
399
+ : '';
400
+
401
+ const classLines = [];
402
+ classLines.push(`class ${className}${extendsClause} {`);
403
+
404
+ const instanceValues = [];
405
+ const instanceSlotNames = Object.create(null);
406
+ const instanceConstSlots = Object.create(null);
407
+ const staticSlots = [];
408
+ const staticSlotNames = Object.create(null);
409
+ const staticConstSlots = Object.create(null);
410
+ const methodLines = [];
411
+ const methodBindings = [];
412
+ const dispatchBindings = [];
413
+ const lexicalStaticNames = cls.traits
414
+ .filter(trait => trait.kind <= 3 || trait.kind === 6)
415
+ .map(trait => _avm2PropertyName(cp.multinames[trait.nameIndex], `_trait${trait.nameIndex}`, methodTableName));
416
+ const emitInstanceBody = (method, isCtor, hasSuper) =>
417
+ emitBody(method, isCtor, hasSuper, undefined, false,
418
+ lexicalStaticNames.length ? className : undefined, className, true);
419
+
420
+ const emitStaticBody = (method) => emitBody(method, false, false, undefined, false, undefined, className);
421
+
422
+ // Instance traits
423
+ for (const trait of inst.traits) {
424
+ if (trait.kind === 0 || trait.kind === 6) {
425
+ const rawName = _avm2PropertyName(cp.multinames[trait.nameIndex], `_trait${trait.nameIndex}`, methodTableName);
426
+ instanceValues.push(`[${JSON.stringify(rawName)}, ${_slotDefaultLiteral(cp, trait, methodTableName)}]`);
427
+ if (trait.slotId) {
428
+ instanceSlotNames[trait.slotId] = rawName;
429
+ if (trait.kind === 6) instanceConstSlots[trait.slotId] = true;
430
+ }
431
+ } else {
432
+ emitTrait(trait, false, methodLines, abc, cp, emitInstanceBody, hasSuper, methodBindings, dispatchBindings, methodTableName, inst.protectedNsIndex);
433
+ }
434
+ }
435
+
436
+ // Static traits
437
+ for (const trait of cls.traits) {
438
+ if (trait.kind === 0 || trait.kind === 6) {
439
+ const rawName = _avm2PropertyName(cp.multinames[trait.nameIndex], `_trait${trait.nameIndex}`, methodTableName);
440
+ if (trait.slotId) {
441
+ staticSlotNames[trait.slotId] = rawName;
442
+ if (trait.kind === 6) staticConstSlots[trait.slotId] = true;
443
+ }
444
+ staticSlots.push(`[${JSON.stringify(rawName)}, ${_slotDefaultLiteral(cp, trait, methodTableName)}]`);
445
+ } else {
446
+ emitTrait(trait, true, methodLines, abc, cp, emitStaticBody, false, methodBindings, dispatchBindings, methodTableName);
447
+ }
448
+ }
449
+
450
+ // Constructor
451
+ const ctorMethod = abc.methods[inst.iinit];
452
+ const ctorParams = buildParamList(ctorMethod);
453
+ classLines.push(` constructor(${ctorParams}) {`);
454
+ const ctorBody = emitInstanceBody(ctorMethod, true, hasSuper);
455
+ classLines.push(indent(ctorBody, 2));
456
+ classLines.push(` }`);
457
+
458
+ classLines.push(...methodLines);
459
+ classLines.push(`}`);
460
+ const classMn = cp.multinames[inst.nameIndex];
461
+ const classRawName = classMn?.localName || className;
462
+ const classMetadata = [];
463
+ if (_avm2UsesNamespaceIdentity(classMn)) {
464
+ classMetadata.push(`definitionKey: ${JSON.stringify(_avm2TypeTraitName(classMn, classRawName, methodTableName))}`);
465
+ classMetadata.push(`propertyKey: ${JSON.stringify(_avm2PropertyName(classMn, classRawName, methodTableName))}`);
466
+ }
467
+ const classTrait = abc.scripts[classScriptScopes.get(i)]?.traits.find(trait => trait.kind === 4 && trait.classIndex === i);
468
+ classMetadata.push(`reflection: ${JSON.stringify(avm2Reflection(abc, inst, cls, classTrait))}`);
469
+ if (classMn?.ns) classMetadata.push(`namespace: ${JSON.stringify(classMn.ns)}`);
470
+ if (inst.flags & 0x01) classMetadata.push('sealed: true');
471
+ if (instanceValues.length) classMetadata.push(`instanceValues: [${instanceValues.join(', ')}]`);
472
+ if (staticSlots.length) classMetadata.push(`staticValues: [${staticSlots.join(', ')}]`);
473
+ if (lexicalStaticNames.length) classMetadata.push(`lexical: ${JSON.stringify(lexicalStaticNames)}`);
474
+ for (const [key, slots] of Object.entries({ instanceSlotNames, staticSlotNames, instanceConstSlots, staticConstSlots })) {
475
+ if (Object.keys(slots).length) classMetadata.push(`${key}: ${JSON.stringify(slots)}`);
476
+ }
477
+ if (superQualified === 'Object') classMetadata.push('objectDispatchBase: true');
478
+ if (dispatchBindings.length) classMetadata.push(`dispatch: ${JSON.stringify(dispatchBindings)}`);
479
+ const metadata = classMetadata.length ? `, { ${classMetadata.join(', ')} }` : '';
480
+ classLines.push(`_registerAvm2Class(${className}, ${classTableName}, ${i}, ${JSON.stringify(classRawName)}${metadata});`);
481
+ const protectedNamespace = cp.namespaces[inst.protectedNsIndex];
482
+ if (protectedNamespace?.kind === 0x18) {
483
+ const prefix = _avm2PropertyName({
484
+ nsKind: 0x18, nsIndex: inst.protectedNsIndex, ns: cp.strings[protectedNamespace.nameIndex],
485
+ }, '', methodTableName);
486
+ const protectedMembers = new Map();
487
+ const protectedSlots = [];
488
+ for (const trait of inst.traits) {
489
+ const name = cp.multinames[trait.nameIndex];
490
+ if (!name?.localName || name.nsKind !== 0x18 || !_avm2PropertyName(name, '', methodTableName).startsWith(prefix)) continue;
491
+ if (trait.kind === 0 || trait.kind === 6) protectedSlots.push(name.localName);
492
+ else if (trait.kind >= 1 && trait.kind <= 3) {
493
+ protectedMembers.set(name.localName, Boolean((trait.attrs & 0x02) || protectedMembers.get(name.localName)));
494
+ }
495
+ }
496
+ const slots = protectedSlots.length ? `, ${JSON.stringify(protectedSlots)}` : '';
497
+ classLines.push(`_registerAvm2ProtectedTraits(${className}, ${JSON.stringify(prefix)}, ${JSON.stringify([...protectedMembers])}${slots});`);
498
+ }
499
+ const isInterface = Boolean(inst.flags & 0x04);
500
+ if (isInterface || inst.interfaces.length) {
501
+ const interfaces = inst.interfaces.map(index => {
502
+ const name = cp.multinames[index];
503
+ return _avm2TypeTraitName(name, name?.localName || `_mn${index}`, methodTableName);
504
+ });
505
+ const traits = isInterface ? _avm2InterfaceTraits(inst.traits, cp, methodTableName) : null;
506
+ classLines.push(`_registerAvm2Interfaces(${className}, ${JSON.stringify(interfaces)}, ${JSON.stringify(traits)});`);
507
+ }
508
+ if (methodBindings.length) {
509
+ classLines.push(`_registerAvm2Methods(${className}, ${methodTableName}, ${JSON.stringify(methodBindings)});`);
510
+ }
511
+ out.push(classLines.join('\n'));
512
+ const classInitMethod = abc.methods[cls.cinit];
513
+ if (classInitMethod?.body) {
514
+ const body = emitBody(classInitMethod, false, false, undefined, true, undefined, className);
515
+ classInitializers.push(
516
+ `_queueAvm2ClassInitializer(/* ${className} cinit */ function() {\n${indent(body, 1)}\n}.bind(${className}));`
517
+ );
518
+ }
519
+ }
520
+
521
+ // Script Class traits shadow the registry during scope lookup. Populate
522
+ // them with their ABC class index before a cinit constructs other classes.
523
+ for (const [scriptIndex, script] of abc.scripts.entries()) {
524
+ for (const trait of script.traits) {
525
+ const className = trait.kind === 4 && classNames[trait.classIndex];
526
+ if (!className) continue;
527
+ const multiname = cp.multinames[trait.nameIndex];
528
+ const name = _avm2PropertyName(multiname, `_trait${trait.nameIndex}`, methodTableName);
529
+ if (!name) continue;
530
+ const qualified = _avm2TypeTraitName(multiname, name, methodTableName);
531
+ const scope = scriptScopeNames[scriptIndex];
532
+ out.push(`_seedScriptTrait(${scope}, ${JSON.stringify(name)}, ${className});`);
533
+ if (qualified !== name) out.push(`_seedScriptTrait(${scope}, ${JSON.stringify(qualified)}, ${className});`);
534
+ }
535
+ }
536
+
537
+ // Script method traits are installed by ABC linking, even when their
538
+ // initializer has no bytecode that assigns the method.
539
+ for (const [scriptIndex, script] of abc.scripts.entries()) {
540
+ for (const trait of script.traits) {
541
+ if (trait.kind !== 1) continue;
542
+ const method = abc.methods[trait.methodIndex];
543
+ if (!method?.body) continue;
544
+ const multiname = cp.multinames[trait.nameIndex];
545
+ const name = _avm2PropertyName(multiname, `_trait${trait.nameIndex}`, methodTableName);
546
+ const params = method.paramTypes.map((_, index) => `_l${index + 1}`).join(', ');
547
+ const body = emitBody(method, false, false, scriptIndex);
548
+ const scope = scriptScopeNames[scriptIndex];
549
+ const qualified = multiname?.nsKind === 0x16 && multiname.ns ? `, ${JSON.stringify(multiname.ns + '.' + name)}` : '';
550
+ out.push(`_registerAvm2ScriptMethod(${scope}, ${JSON.stringify(name)}, function(${params}) {\n${indent(body, 1)}\n}${qualified});`);
551
+ }
552
+ }
553
+
554
+ // Class declarations and script Class traits now exist before cinit runs.
555
+ out.push(...classInitializers);
556
+
557
+ // Script init functions — local0/`this` is the script/global scope in AVM2
558
+ for (let i = 0; i < abc.scripts.length; i++) {
559
+ const script = abc.scripts[i];
560
+ const initMethod = abc.methods[script.init];
561
+ if (initMethod?.body) {
562
+ const body = emitBody(initMethod, false, false, i);
563
+ out.push(
564
+ `_queueAvm2ScriptInitializer(/* script ${i} init */ function() {\n${indent(body, 1)}\n}.bind(${scriptScopeNames[i]}));`
565
+ );
566
+ }
567
+ }
568
+
569
+ return [
570
+ `var ${methodTableName} = Object.create(null);`,
571
+ `var ${classTableName} = Object.create(null);`,
572
+ ...namespaceKeys.declarations(),
573
+ ...out,
574
+ ].join('\n\n');
575
+ }
576
+
577
+ // Multiple multinames can share an ordered namespace set, and each may be used
578
+ // at many call sites. Store its key prefixes and member name once per ABC.
579
+ class NamespaceKeyTable {
580
+ constructor(name, cp, methodTableName) {
581
+ this.name = name;
582
+ this.cp = cp;
583
+ this.methodTableName = methodTableName;
584
+ this.references = new Map();
585
+ this.callReferences = new Map();
586
+ this.lexicalReferences = new Map();
587
+ this.typeReferences = new Map();
588
+ this.sets = new Map();
589
+ this.entries = new Map();
590
+ }
591
+
592
+ lookup(index) {
593
+ if (!this.references.has(index)) this.references.set(index, this.buildReference(index));
594
+ return this.references.get(index);
595
+ }
596
+
597
+ lexical(index) {
598
+ if (!this.lexicalReferences.has(index)) this.lexicalReferences.set(index, this.buildReference(index, true));
599
+ return this.lexicalReferences.get(index);
600
+ }
601
+
602
+ exactType(index) {
603
+ if (this.typeReferences.has(index)) return this.typeReferences.get(index);
604
+ const multiname = this.cp.multinames[index];
605
+ const name = multiname?.localName;
606
+ const namespaces = multiname?.nsSet?.filter(ns => ns.kind)
607
+ .map(ns => ({ ...ns, nsKind: ns.kind, localName: name }));
608
+ const exact = namespaces?.some(_avm2UsesNamespaceIdentity) ? namespaces
609
+ : _avm2UsesNamespaceIdentity(multiname) ? [multiname] : null;
610
+ const reference = name && exact
611
+ ? this.reference(name, [...new Set(exact.map(ns => _avm2TypeTraitName(ns, name, this.methodTableName)))])
612
+ : null;
613
+ this.typeReferences.set(index, reference);
614
+ return reference;
615
+ }
616
+
617
+ buildReference(index, lexical = false) {
618
+ const multiname = this.cp.multinames[index];
619
+ const name = multiname?.localName;
620
+ if (!name) return null;
621
+ const builtinNamespace = 'http://adobe.com/AS3/2006/builtin';
622
+ if (!multiname.nsSet) {
623
+ if (multiname.nsKind !== 0x08 || multiname.ns !== builtinNamespace) return null;
624
+ return this.reference(name, [_avm2PropertyName(multiname, name, this.methodTableName), name]);
625
+ }
626
+ const keys = new Set();
627
+ for (const ns of multiname.nsSet) {
628
+ if (ns.kind === 0) continue;
629
+ if (lexical && ns.kind === 0x16 && ns.ns) keys.add(`${ns.ns}.${name}`);
630
+ keys.add(_avm2PropertyName({ ...ns, nsKind: ns.kind, localName: name }, name, this.methodTableName));
631
+ if (ns.kind === 0x08 && ns.ns === builtinNamespace) keys.add(name);
632
+ }
633
+ return this.reference(name, [...keys]);
634
+ }
635
+
636
+ call(index) {
637
+ const multiname = this.cp.multinames[index];
638
+ if (multiname?.nsKind !== 0x16 || !multiname.ns || !multiname.localName) return this.lookup(index);
639
+ if (!this.callReferences.has(index)) {
640
+ const name = multiname.localName;
641
+ this.callReferences.set(index, this.reference(name, [`${multiname.ns}.${name}`, name]));
642
+ }
643
+ return this.callReferences.get(index);
644
+ }
645
+
646
+ reference(name, keys) {
647
+ if (!keys.length) return null;
648
+ const set = this.prefixSet(keys.map(key => key.slice(0, key.length - name.length)));
649
+ const entry = JSON.stringify([set, name]);
650
+ if (!this.entries.has(entry)) this.entries.set(entry, this.entries.size);
651
+ return `${this.name}(${this.entries.get(entry)})`;
652
+ }
653
+
654
+ prefixSet(prefixes) {
655
+ const serialized = JSON.stringify(prefixes);
656
+ if (!this.sets.has(serialized)) this.sets.set(serialized, this.sets.size);
657
+ return this.sets.get(serialized);
658
+ }
659
+
660
+ lateSet(multiname) {
661
+ const prefixes = new Set();
662
+ for (const namespace of multiname.nsSet || []) {
663
+ if (!namespace.kind) continue;
664
+ prefixes.add(_avm2PropertyName({ ...namespace, nsKind: namespace.kind }, '', this.methodTableName));
665
+ if (namespace.kind === 0x08 && namespace.ns === 'http://adobe.com/AS3/2006/builtin') prefixes.add('');
666
+ }
667
+ return `${this.name}.prefixes(${this.prefixSet([...prefixes])})`;
668
+ }
669
+
670
+ declarations() {
671
+ if (!this.sets.size) return [];
672
+ return [`var ${this.name} = _createAvm2NamespaceKeys(
673
+ [${[...this.sets.keys()].join(',\n ')}],
674
+ [${[...this.entries.keys()].join(',\n ')}]
675
+ );`];
676
+ }
677
+ }
678
+
679
+ function _hashAbc(data) {
680
+ let hash = 0x811c9dc5;
681
+ for (const byte of data) hash = Math.imul(hash ^ byte, 0x01000193);
682
+ return (hash >>> 0).toString(16);
683
+ }
684
+
685
+ /**
686
+ * Transpile a single ABC method body to JS source.
687
+ * @param {import('./abc-reader.js').AbcMethod|undefined} method
688
+ * @param {import('./abc-reader.js').AbcFile} abc
689
+ * @param {DiagnosticsCollector} diagnostics
690
+ * @param {boolean} isCtor
691
+ * @param {boolean} hasSuper
692
+ * @returns {string}
693
+ */
694
+ function transpileMethodBody(method, abc, diagnostics, isCtor, hasSuper, methodTableName, classTableName, namespaceKeys, scriptScopeId = 0, isInitializer = false, lexicalClass, ownerClass, capturesOuterScope = false, instanceMethod = false) {
695
+ if (!method?.body) return '// native or abstract';
696
+ try {
697
+ return new Avm2Context(method, abc, diagnostics, isCtor, hasSuper, methodTableName, classTableName, namespaceKeys, scriptScopeId, isInitializer, lexicalClass, ownerClass, capturesOuterScope, instanceMethod).transpile();
698
+ } catch (err) {
699
+ diagnostics.warn(`Method body transpilation failed: ${err.message}`, 'transpile');
700
+ return `// transpilation error: ${err.message}`;
701
+ }
702
+ }
703
+
704
+ /**
705
+ * Emit a single trait (method, getter, setter, slot) into classLines.
706
+ */
707
+ function emitTrait(trait, isStatic, classLines, abc, cp, emitBody, hasSuper, methodBindings, dispatchBindings, methodTableName, protectedNsIndex = 0) {
708
+ const mn = cp.multinames[trait.nameIndex];
709
+ if (mn?.ns) {
710
+ // Package/custom namespace noted for debugging; localName used as JS property
711
+ }
712
+ const rawName = _avm2PropertyName(mn, `_trait${trait.nameIndex}`, methodTableName);
713
+ const staticPrefix = isStatic ? 'static ' : '';
714
+
715
+ if (trait.kind === 1 || trait.kind === 2 || trait.kind === 3) {
716
+ const method = abc.methods[trait.methodIndex];
717
+ const kindPrefix = trait.kind === 2 ? 'get ' : trait.kind === 3 ? 'set ' : '';
718
+ const params = trait.kind === 2 ? '' : buildParamList(method, trait.kind === 3 ? 1 : undefined);
719
+ const body = emitBody(method, false, hasSuper);
720
+ const propKey = _safeMethodName(rawName, isStatic);
721
+ classLines.push(` ${staticPrefix}${kindPrefix}${propKey}(${params}) {`);
722
+ classLines.push(indent(body, 2));
723
+ classLines.push(` }`);
724
+ const key = propKey.startsWith('[') ? rawName : propKey;
725
+ if (trait.kind === 1) {
726
+ methodBindings.push(isStatic ? [trait.methodIndex, key, true] : [trait.methodIndex, key]);
727
+ }
728
+ if (!isStatic) {
729
+ const protectedUri = cp.strings[cp.namespaces[protectedNsIndex]?.nameIndex];
730
+ const protectedMethod = protectedNsIndex && mn?.nsKind === 0x18 &&
731
+ (mn.nsIndex === protectedNsIndex || (mn.ns && mn.ns === protectedUri));
732
+ const overrides = Boolean(trait.attrs & 0x02);
733
+ const binding = [trait.dispId, key, _avm2TypeTraitName(mn, rawName, methodTableName)];
734
+ if (protectedMethod || trait.kind !== 1 || (!trait.dispId && !overrides)) {
735
+ binding.push(protectedMethod ? mn.localName : null, overrides);
736
+ }
737
+ if (trait.kind !== 1) binding.push(trait.kind);
738
+ dispatchBindings.push(binding);
739
+ }
740
+ } else if (trait.kind === 0 || trait.kind === 6) {
741
+ const propKey = _safeMethodName(rawName, isStatic);
742
+ classLines.push(` ${staticPrefix}${propKey} = undefined;`);
743
+ }
744
+ }
745
+
746
+ /**
747
+ * Build parameter list mapped to `_l1, _l2, ...` matching AVM2 local registers.
748
+ * @param {import('./abc-reader.js').AbcMethod|undefined} method
749
+ * @param {number} [exactCount]
750
+ * @returns {string}
751
+ */
752
+ function buildParamList(method, exactCount) {
753
+ const count = exactCount !== undefined ? exactCount : (method?.paramTypes?.length ?? 0);
754
+ if (count <= 0) return '';
755
+ return Array.from({ length: count }, (_, i) => `_l${i + 1}`).join(', ');
756
+ }
757
+
758
+ function _isNamespaceKind(kind) {
759
+ return kind === 0x05 || kind === 0x08 || (kind >= 0x16 && kind <= 0x1A);
760
+ }
761
+
762
+ function _namespaceLiteral(cp, index, abcId) {
763
+ const namespace = cp.namespaces[index];
764
+ const uri = cp.strings[namespace?.nameIndex ?? 0] || '';
765
+ const kind = namespace?.kind ?? 0;
766
+ const key = (kind === 0x08 || kind === 0x16) && !uri ? ''
767
+ : kind === 0x16 ? uri + '.' : _avm2PropertyName({ ns: uri, nsKind: kind, nsIndex: index }, '', abcId);
768
+ const prefixes = uri === 'http://adobe.com/AS3/2006/builtin' && kind === 0x08 ? [key, ''] : [key];
769
+ return `_avm2NamespaceConstant(${JSON.stringify(uri)}, ${JSON.stringify(prefixes)}, ${kind})`;
770
+ }
771
+
772
+ function _optionalDefaultLiteral(cp, optional, abcId) {
773
+ const idx = optional.valueIndex;
774
+ switch (optional.kind) {
775
+ case 0x00: return 'undefined';
776
+ case 0x01: return JSON.stringify(cp.strings[idx] ?? '');
777
+ case 0x03: return String(cp.ints[idx] ?? 0);
778
+ case 0x04: return String(cp.uints[idx] ?? 0);
779
+ case 0x05: case 0x08: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A:
780
+ return _namespaceLiteral(cp, idx, abcId);
781
+ case 0x06: {
782
+ const value = cp.doubles[idx];
783
+ if (Number.isNaN(value)) return 'NaN';
784
+ if (value === Infinity) return 'Infinity';
785
+ if (value === -Infinity) return '-Infinity';
786
+ return String(value);
787
+ }
788
+ case 0x0A: return 'false';
789
+ case 0x0B: return 'true';
790
+ case 0x0C: return 'null';
791
+ default: return 'undefined';
792
+ }
793
+ }
794
+
795
+ function _slotDefaultLiteral(cp, trait, abcId) {
796
+ if (trait.valueIndex) {
797
+ return _optionalDefaultLiteral(cp, { valueIndex: trait.valueIndex, kind: trait.valueKind }, abcId);
798
+ }
799
+ const typeName = cp.multinames[trait.typeNameIndex]?.localName;
800
+ if (typeName === 'int' || typeName === 'uint') return '0';
801
+ if (typeName === 'Number') return 'NaN';
802
+ if (typeName === 'Boolean') return 'false';
803
+ if (!typeName || typeName === '*') return 'undefined';
804
+ if (typeName === 'String' || typeName === 'Object') return 'null';
805
+ return 'null';
806
+ }
807
+
808
+ class Avm2Context {
809
+ constructor(method, abc, diagnostics, isCtor, hasSuper, methodTableName, classTableName, namespaceKeys, scriptScopeId, isInitializer, lexicalClass, ownerClass, capturesOuterScope, instanceMethod) {
810
+ this.method = method;
811
+ this.abc = abc;
812
+ this.cp = abc.constantPool;
813
+ this.diag = diagnostics;
814
+ this.isCtor = isCtor;
815
+ this.isInitializer = isInitializer;
816
+ this.hasSuper = hasSuper;
817
+ this.methodTableName = methodTableName;
818
+ this.classTableName = classTableName;
819
+ this.namespaceKeys = namespaceKeys;
820
+ this.scriptScopeId = scriptScopeId;
821
+ this.lexicalClass = lexicalClass;
822
+ this.ownerClass = ownerClass;
823
+ this.capturesOuterScope = capturesOuterScope;
824
+ this.instanceMethod = instanceMethod;
825
+ this.outerDepth = Math.min(method.body?.initScopeDepth || 0, MAX_STACK_ARGS);
826
+ this.usesOuterScopes = false;
827
+ this.code = method.body?.code ?? new Uint8Array(0);
828
+ /** @type {string[]} */
829
+ this.stack = [];
830
+ /** @type {string[]} */
831
+ this.lines = [];
832
+ /** @type {string[]} - scope object stack */
833
+ this.scopes = [];
834
+ this._tmp = 0;
835
+ this._dynamicStack = false;
836
+ this._stackDepthConflict = false;
837
+ this._locals = method.body?.localCount ?? 4;
838
+ this._paramCount = method.paramTypes?.length ?? 0;
839
+ this._emittedSuper = false;
840
+ /** @type {boolean} Buffer pre-constructsuper `this` on `_pre` (AS3 vs ES6). */
841
+ this._usePreSuper = false;
842
+ }
843
+
844
+ /** Receiver for getlocal0: `_pre` until constructsuper runs in extending ctors. */
845
+ _thisRef() {
846
+ if (this._usePreSuper && this._runtimeScopes) return '(_avm2SuperReady ? this : _pre)';
847
+ return this._usePreSuper && !this._emittedSuper ? '_pre' : 'this';
848
+ }
849
+
850
+ _classScopeArg(namespaceKeys, globalOnly = false, nameIndex) {
851
+ const name = this.cp.multinames[nameIndex];
852
+ const protectedStatic = name?.nsKind === 0x1A || name?.nsSet?.some(ns => ns.kind === 0x1A);
853
+ const lexicalClass = !globalOnly && (this.lexicalClass || (protectedStatic && this.ownerClass));
854
+ const scriptScope = !globalOnly && !this.capturesOuterScope && this.abc.scripts.length > 1
855
+ ? this._scriptScopeName() : null;
856
+ if (scriptScope) return `, ${lexicalClass || 'undefined'}, ${namespaceKeys || 'undefined'}, ${scriptScope}`;
857
+ if (namespaceKeys) return `, ${lexicalClass || 'undefined'}, ${namespaceKeys}`;
858
+ return lexicalClass ? `, ${lexicalClass}` : '';
859
+ }
860
+
861
+ _getlexExpression(name, namespaceKeys, nameIndex, receiver = this._lookupReceiver(), scopes = this._scopeExpression()) {
862
+ const multiname = this.cp.multinames[nameIndex];
863
+ if (_avm2UsesNamespaceIdentity(multiname)) {
864
+ const exact = _avm2TypeTraitName(multiname, name, this.methodTableName);
865
+ const lexicalClass = this.lexicalClass || (multiname.nsKind === 0x1A && this.ownerClass) || 'undefined';
866
+ return `_getlexScoped(${JSON.stringify(name)}, ${receiver}, ${scopes}, ${lexicalClass}, ${namespaceKeys || 'undefined'}, ${this._scriptScopeExpression()}, false, ${JSON.stringify(exact)})`;
867
+ }
868
+ return `_getlexScoped(${JSON.stringify(name)}, ${receiver}, ${scopes}${this._classScopeArg(namespaceKeys, false, nameIndex)})`;
869
+ }
870
+
871
+ _lookupReceiver() {
872
+ return this.capturesOuterScope ? 'null' : this._thisRef();
873
+ }
874
+
875
+ _outerScopesExpression() {
876
+ if (!this.capturesOuterScope && !this.outerDepth) return null;
877
+ this.usesOuterScopes = true;
878
+ return '_avm2OuterScopes';
879
+ }
880
+
881
+ _scopeExpression() {
882
+ const outer = this._outerScopesExpression();
883
+ if (this._runtimeScopes) return outer ? `${outer}.concat(_avm2Scopes)` : '_avm2Scopes.slice()';
884
+ const local = `[${this.scopes.join(', ')}]`;
885
+ return outer ? (this.scopes.length ? `${outer}.concat(${local})` : outer) : local;
886
+ }
887
+
888
+ _scriptScopeName() {
889
+ return `${this.methodTableName}_script_${this.scriptScopeId}`;
890
+ }
891
+
892
+ _scriptScopeExpression() {
893
+ return this.abc.scripts.length ? this._scriptScopeName() : 'globalThis';
894
+ }
895
+
896
+ _superCall(args) {
897
+ const owner = this.ownerClass;
898
+ return [
899
+ 'var _superFrame;',
900
+ `try { super(...(_superFrame = _beginAvm2Super(${owner}, new.target, _pre, [${args.join(', ')}])).args); }`,
901
+ 'finally { _endAvm2Super(_superFrame); }',
902
+ ...(this._runtimeScopes && this._usePreSuper ? ['_avm2SuperReady = true;'] : []),
903
+ `_applyAvm2Super(this, ${owner}, new.target, _superFrame);`,
904
+ ];
905
+ }
906
+
907
+ transpile() {
908
+ const headerLines = [];
909
+ let firstLocal = this._paramCount + 1;
910
+ if (this.method.flags & 0x04) { // NEED_REST
911
+ headerLines.push(`var _l${firstLocal} = [...arguments].slice(${this._paramCount});`);
912
+ firstLocal++;
913
+ }
914
+ const localDecls = [];
915
+ for (let r = firstLocal; r < this._locals; r++) {
916
+ localDecls.push(`_l${r}`);
917
+ }
918
+ if (localDecls.length > 0) {
919
+ headerLines.push(`var ${localDecls.join(', ')};`);
920
+ }
921
+
922
+ const optionalValues = this.method.optionalValues || [];
923
+ const firstOptionalParam = this._paramCount - optionalValues.length + 1;
924
+ for (let i = 0; i < optionalValues.length; i++) {
925
+ const paramIndex = firstOptionalParam + i;
926
+ if (paramIndex < 1) continue;
927
+ const value = _optionalDefaultLiteral(this.cp, optionalValues[i], this.methodTableName);
928
+ headerLines.push(`if (arguments.length < ${paramIndex}) _l${paramIndex} = ${value};`);
929
+ }
930
+ // Incoming integer arguments are converted before bytecode reads the local registers.
931
+ for (let i = 0; i < this._paramCount; i++) {
932
+ const type = this.cp.multinames[this.method.paramTypes[i]];
933
+ if (type?.nsKind !== 0x16 || type.ns || (type.localName !== 'int' && type.localName !== 'uint')) continue;
934
+ const local = `_l${i + 1}`;
935
+ const conversion = type.localName === 'int' ? '| 0' : '>>> 0';
936
+ headerLines.push(`${local} = ${local} ${conversion};`);
937
+ }
938
+
939
+ const bytes = this.code;
940
+ const exceptions = (this.method.body?.exceptions ?? []).filter(({ from, to, target }) =>
941
+ from < to && to <= bytes.length && target < bytes.length);
942
+ this._runtimeScopes = exceptions.length > 0;
943
+ this._dynamicStack = this._runtimeScopes;
944
+ const { instructions, blockStarts } = this._collectReachable(bytes, exceptions);
945
+
946
+ this.usesDefaultXmlNamespace = this.abc.usesDefaultXmlNamespace ||
947
+ instructions.some(({ op }) => op === ABC.dxns || op === ABC.dxnslate);
948
+ if (this.usesDefaultXmlNamespace) {
949
+ const initial = this.capturesOuterScope ? '(typeof _avm2CapturedDxns === "undefined" ? undefined : _avm2CapturedDxns)'
950
+ : this.ownerClass ? `_avm2ClassDefaultXmlNamespace(${this.ownerClass})` : 'undefined';
951
+ headerLines.push(`var _avm2Dxns = ${initial};`);
952
+ }
953
+
954
+ if (this.isCtor && this.hasSuper) {
955
+ const hasConstructSuper = instructions.some(insn => insn.op === ABC.constructsuper);
956
+ // AS3 allows reading/writing slots before constructsuper; ES6 does not.
957
+ headerLines.push(`var _pre = _createAvm2PreSuper(${this.ownerClass}, new.target);`);
958
+ if (!hasConstructSuper) {
959
+ headerLines.push(...this._superCall([]));
960
+ this._emittedSuper = true;
961
+ headerLines.push('_bindAvm2Symbol(this);');
962
+ } else {
963
+ this._usePreSuper = true;
964
+ if (this._runtimeScopes) headerLines.push('var _avm2SuperReady = false;');
965
+ }
966
+ } else if (this.isCtor && !this.hasSuper) {
967
+ headerLines.push(`_initializeAvm2Instance(this, ${this.ownerClass}, new.target);`);
968
+ }
969
+
970
+ if (instructions.length === 0) {
971
+ return headerLines.join('\n');
972
+ }
973
+
974
+ // Split instructions into basic blocks
975
+ const rawBlocks = this._splitBasicBlocks(instructions, blockStarts);
976
+ let { blocks, maxSpill } = this._simulateBlocks(rawBlocks, exceptions);
977
+
978
+ // Malformed or obfuscated ABC can reach a block with different operand
979
+ // stack heights. Static slot names then bind the block to the first path.
980
+ // Re-emit in a runtime stack dispatcher when the CFG proves such a join.
981
+ if (!this._dynamicStack && this._stackDepthConflict) {
982
+ this._dynamicStack = true;
983
+ this._stackDepthConflict = false;
984
+ this._tmp = 0;
985
+ this._emittedSuper = false;
986
+ this.scopes = [];
987
+ ({ blocks, maxSpill } = this._simulateBlocks(rawBlocks));
988
+ }
989
+
990
+ if (maxSpill > 0) {
991
+ const stackVars = Array.from({ length: maxSpill }, (_, k) => `_s${k}`);
992
+ headerLines.push(`var ${stackVars.join(', ')};`);
993
+ }
994
+ if (this._dynamicStack) headerLines.push('var _avm2Stack = [];');
995
+ if (this._runtimeScopes) headerLines.push('var _avm2Scopes = [];');
996
+
997
+ // A synchronous AVM2 handler cannot yield to the browser while running.
998
+ // Bound basic-block visits so malformed or non-terminating loops return
999
+ // control instead of locking the tab indefinitely.
1000
+ headerLines.push('var _avm2CheckBudget = _createAvm2ExecutionBudget();');
1001
+ if (!exceptions.length) {
1002
+ for (const block of blocks) block.stmts.unshift('_avm2CheckBudget();');
1003
+ }
1004
+
1005
+ const entryId = blocks[0]?.id;
1006
+ const emitDispatcher = () => this._emitRuntimeStackDispatcher(blocks, entryId, exceptions);
1007
+ const structuredLines = this._dynamicStack ? emitDispatcher()
1008
+ : structureCfg(blocks, entryId, undefined, emitDispatcher);
1009
+ if (this.usesOuterScopes && !this.capturesOuterScope) {
1010
+ headerLines.unshift(`var _avm2OuterScopes = _getAvm2OuterScopes(${this.ownerClass || 'null'}, ${this._scriptScopeExpression()}, ${this.outerDepth}, ${this.instanceMethod});`);
1011
+ }
1012
+ return [...headerLines, ...structuredLines].join('\n');
1013
+ }
1014
+
1015
+ _emitRuntimeStackDispatcher(blocks, entryId, exceptions) {
1016
+ if (!blocks.length) return [];
1017
+ const byId = new Map(blocks.map(block => [block.id, block]));
1018
+ const dispatch = [`var _avm2Pc = ${entryId};`, '_avm2Dispatch: while (_avm2Pc !== -1) {'];
1019
+ const lines = [' switch (_avm2Pc) {'];
1020
+ for (const block of blocks) {
1021
+ lines.push(` case ${block.id}: {`);
1022
+ for (const stmt of block.stmts) lines.push(` ${stmt}`);
1023
+ if (block.term === 'jump' || block.term === 'fallthrough') {
1024
+ const next = block.next != null && byId.has(block.next) ? block.next : -1;
1025
+ lines.push(` _avm2Pc = ${next}; break;`);
1026
+ } else if (block.term === 'branch') {
1027
+ const t = block.trueTarget != null && byId.has(block.trueTarget) ? block.trueTarget : -1;
1028
+ const f = block.falseTarget != null && byId.has(block.falseTarget) ? block.falseTarget : -1;
1029
+ lines.push(` _avm2Pc = (${block.cond || 'false'}) ? ${t} : ${f}; break;`);
1030
+ } else if (block.term === 'switch') {
1031
+ lines.push(` switch (${block.switchExpr || '0'}) {`);
1032
+ for (const entry of block.switchCases || []) {
1033
+ const target = entry.target != null && byId.has(entry.target) ? entry.target : -1;
1034
+ for (const value of entry.values) lines.push(` case ${value}:`);
1035
+ lines.push(` _avm2Pc = ${target}; break;`);
1036
+ }
1037
+ const def = block.switchDefault != null && byId.has(block.switchDefault) ? block.switchDefault : -1;
1038
+ lines.push(` default: _avm2Pc = ${def}; break;`, ' }', ' break;');
1039
+ } else {
1040
+ if (block.term !== 'return' && block.term !== 'throw') lines.push(' _avm2Pc = -1;');
1041
+ lines.push(' break;');
1042
+ }
1043
+ lines.push(' }');
1044
+ }
1045
+ lines.push(' default: _avm2Pc = -1; break;', ' }');
1046
+ if (!exceptions.length) return [...dispatch, ...lines, '}'];
1047
+ dispatch.push(' _avm2CheckBudget();', ' try {', ...lines.map(line => ` ${line}`),
1048
+ ' } catch (_avm2Caught) {', ' _avm2Scopes.length = 0;');
1049
+ for (const { from, to, target, excType } of exceptions) {
1050
+ if (!byId.has(target)) continue;
1051
+ const typed = excType ? ` && _isType(_avm2Caught, ${this._typeOperand(excType, undefined, true).expression})` : '';
1052
+ dispatch.push(
1053
+ ` if (_avm2Pc >= ${from} && _avm2Pc < ${to}${typed}) {`,
1054
+ ' _avm2Stack.length = 0;',
1055
+ ' _avm2Stack.push(_avm2Caught);',
1056
+ ` _avm2Pc = ${target};`,
1057
+ ' continue _avm2Dispatch;',
1058
+ ' }',
1059
+ );
1060
+ }
1061
+ dispatch.push(' throw _avm2Caught;', ' }', '}');
1062
+ return dispatch;
1063
+ }
1064
+
1065
+ /**
1066
+ * Collect reachable instructions via BFS from PC 0 and exception handlers.
1067
+ * Skips dead obfuscation bytes behind unconditional jumps and opaque predicates.
1068
+ */
1069
+ _collectReachable(bytes, exceptions) {
1070
+ const visited = new Set();
1071
+ const branchTargets = new Set();
1072
+ const blockStarts = new Set([0]);
1073
+ /** @type {Map<number, object>} */
1074
+ const insnMap = new Map();
1075
+ const queue = [0];
1076
+
1077
+ for (const exc of exceptions) {
1078
+ blockStarts.add(exc.from);
1079
+ blockStarts.add(exc.to);
1080
+ if (exc.target >= 0 && exc.target < bytes.length) {
1081
+ queue.push(exc.target);
1082
+ branchTargets.add(exc.target);
1083
+ blockStarts.add(exc.target);
1084
+ }
1085
+ }
1086
+
1087
+ while (queue.length > 0) {
1088
+ let pc = queue.pop();
1089
+ let prevConstBool = null;
1090
+
1091
+ while (pc >= 0 && pc < bytes.length && !visited.has(pc)) {
1092
+ visited.add(pc);
1093
+ const insn = this._decodeInstruction(bytes, pc);
1094
+ insnMap.set(pc, insn);
1095
+
1096
+ const effectiveBool = branchTargets.has(pc) ? null : prevConstBool;
1097
+
1098
+ if (insn.op === ABC.pushtrue) {
1099
+ prevConstBool = true;
1100
+ } else if (insn.op === ABC.pushfalse) {
1101
+ prevConstBool = false;
1102
+ } else {
1103
+ prevConstBool = null;
1104
+ }
1105
+
1106
+ if (insn.op === ABC.returnvoid || insn.op === ABC.returnvalue || insn.op === ABC.throw) {
1107
+ break;
1108
+ }
1109
+
1110
+ if (insn.op === ABC.jump) {
1111
+ const target = insn.nextPc + insn.offset;
1112
+ if (target >= 0 && target < bytes.length) {
1113
+ branchTargets.add(target);
1114
+ blockStarts.add(target);
1115
+ if (!visited.has(target)) queue.push(target);
1116
+ }
1117
+ break;
1118
+ }
1119
+
1120
+ if (insn.op === ABC.lookupswitch) {
1121
+ for (const target of insn.targets) {
1122
+ if (target >= 0 && target < bytes.length) {
1123
+ branchTargets.add(target);
1124
+ blockStarts.add(target);
1125
+ if (!visited.has(target)) queue.push(target);
1126
+ }
1127
+ }
1128
+ break;
1129
+ }
1130
+
1131
+ if (insn.isBranch) {
1132
+ const target = insn.nextPc + insn.offset;
1133
+ const alwaysTrue =
1134
+ (effectiveBool === true && insn.op === ABC.iftrue) ||
1135
+ (effectiveBool === false && insn.op === ABC.iffalse);
1136
+ const alwaysFalse =
1137
+ (effectiveBool === true && insn.op === ABC.iffalse) ||
1138
+ (effectiveBool === false && insn.op === ABC.iftrue);
1139
+
1140
+ if (alwaysTrue) {
1141
+ insn.opaque = 'taken';
1142
+ if (target >= 0 && target < bytes.length) {
1143
+ branchTargets.add(target);
1144
+ blockStarts.add(target);
1145
+ if (!visited.has(target)) queue.push(target);
1146
+ }
1147
+ break;
1148
+ }
1149
+
1150
+ blockStarts.add(insn.nextPc);
1151
+ if (!alwaysFalse && target >= 0 && target < bytes.length) {
1152
+ branchTargets.add(target);
1153
+ blockStarts.add(target);
1154
+ if (!visited.has(target)) queue.push(target);
1155
+ } else if (alwaysFalse) {
1156
+ insn.opaque = 'not-taken';
1157
+ }
1158
+ }
1159
+
1160
+ pc = insn.nextPc;
1161
+ }
1162
+ }
1163
+
1164
+ const instructions = Array.from(insnMap.values()).sort((a, b) => a.pc - b.pc);
1165
+ return { instructions, blockStarts };
1166
+ }
1167
+
1168
+ _splitBasicBlocks(instructions, blockStarts) {
1169
+ const rawBlocks = [];
1170
+ let current = null;
1171
+
1172
+ for (let idx = 0; idx < instructions.length; idx++) {
1173
+ const insn = instructions[idx];
1174
+ if (!current || blockStarts.has(insn.pc)) {
1175
+ current = { id: insn.pc, insns: [], fallthroughId: null };
1176
+ rawBlocks.push(current);
1177
+ }
1178
+ current.insns.push(insn);
1179
+ const endsBlock =
1180
+ insn.op === ABC.jump ||
1181
+ insn.op === ABC.lookupswitch ||
1182
+ insn.op === ABC.returnvoid ||
1183
+ insn.op === ABC.returnvalue ||
1184
+ insn.op === ABC.throw ||
1185
+ insn.isBranch;
1186
+ if (endsBlock) {
1187
+ const nextInsn = instructions[idx + 1];
1188
+ if (!insn.isBranch || insn.opaque === 'not-taken') {
1189
+ current.fallthroughId = nextInsn ? nextInsn.pc : null;
1190
+ } else {
1191
+ current.fallthroughId = nextInsn && nextInsn.pc === insn.nextPc ? nextInsn.pc : (nextInsn ? nextInsn.pc : null);
1192
+ }
1193
+ current = null;
1194
+ } else {
1195
+ const nextInsn = instructions[idx + 1];
1196
+ if (nextInsn && blockStarts.has(nextInsn.pc)) {
1197
+ current.fallthroughId = nextInsn.pc;
1198
+ }
1199
+ }
1200
+ }
1201
+ return rawBlocks;
1202
+ }
1203
+
1204
+ _simulateBlocks(rawBlocks, exceptions = []) {
1205
+ const rawMap = new Map();
1206
+ for (let i = 0; i < rawBlocks.length; i++) {
1207
+ const b = rawBlocks[i];
1208
+ if (b.fallthroughId === null && i + 1 < rawBlocks.length) {
1209
+ const last = b.insns[b.insns.length - 1];
1210
+ if (last.op !== ABC.jump && last.op !== ABC.lookupswitch && last.op !== ABC.returnvoid && last.op !== ABC.returnvalue && last.op !== ABC.throw) {
1211
+ b.fallthroughId = rawBlocks[i + 1].id;
1212
+ }
1213
+ }
1214
+ rawMap.set(b.id, b);
1215
+ }
1216
+
1217
+ const entryDepth = new Map([[rawBlocks[0].id, 0]]);
1218
+ const simulated = new Map();
1219
+ const queue = [rawBlocks[0].id];
1220
+ for (const { target } of exceptions) {
1221
+ if (rawMap.has(target) && !entryDepth.has(target)) {
1222
+ entryDepth.set(target, 1);
1223
+ queue.push(target);
1224
+ }
1225
+ }
1226
+ let maxSpill = 0;
1227
+ const visitTarget = (target, outDepth) => {
1228
+ if (target == null || !rawMap.has(target)) return;
1229
+ if (!entryDepth.has(target)) {
1230
+ entryDepth.set(target, outDepth);
1231
+ queue.push(target);
1232
+ } else if (entryDepth.get(target) !== outDepth) {
1233
+ this._stackDepthConflict = true;
1234
+ }
1235
+ };
1236
+
1237
+ while (queue.length > 0) {
1238
+ const bid = queue.shift();
1239
+ if (simulated.has(bid)) continue;
1240
+ const raw = rawMap.get(bid);
1241
+ if (!raw) continue;
1242
+
1243
+ const d = entryDepth.get(bid) ?? 0;
1244
+ this.stack = this._dynamicStack ? this._createRuntimeStack() : Array.from({ length: d }, (_, k) => `_s${k}`);
1245
+ this.lines = [];
1246
+
1247
+ const lastIdx = raw.insns.length - 1;
1248
+ for (let k = 0; k < lastIdx; k++) {
1249
+ this._emitInstruction(raw.insns[k]);
1250
+ }
1251
+
1252
+ const last = raw.insns[lastIdx];
1253
+ /** @type {import('../cfg-structurer.js').BasicBlock} */
1254
+ let bb;
1255
+
1256
+ if (last.op === ABC.returnvoid || last.op === ABC.returnvalue || last.op === ABC.throw) {
1257
+ this._emitInstruction(last);
1258
+ bb = {
1259
+ id: bid,
1260
+ stmts: this.lines,
1261
+ term: last.op === ABC.throw ? 'throw' : 'return',
1262
+ };
1263
+ } else if (last.op === ABC.jump) {
1264
+ const outDepth = this._spillStack();
1265
+ if (outDepth > maxSpill) maxSpill = outDepth;
1266
+ const target = last.nextPc + last.offset;
1267
+ bb = { id: bid, stmts: this.lines, term: 'jump', next: rawMap.has(target) ? target : null };
1268
+ visitTarget(bb.next, outDepth);
1269
+ } else if (last.op === ABC.lookupswitch) {
1270
+ const switchExpr = this._pop();
1271
+ const outDepth = this._spillStack();
1272
+ if (outDepth > maxSpill) maxSpill = outDepth;
1273
+ const defTarget = rawMap.has(last.targets[0]) ? last.targets[0] : null;
1274
+ const byTarget = new Map();
1275
+ for (let c = 1; c < last.targets.length; c++) {
1276
+ const t = last.targets[c];
1277
+ if (!rawMap.has(t) || t === defTarget) continue;
1278
+ if (!byTarget.has(t)) byTarget.set(t, []);
1279
+ byTarget.get(t).push(c - 1);
1280
+ }
1281
+ const switchCases = Array.from(byTarget.entries()).map(([target, values]) => ({ values, target }));
1282
+ bb = { id: bid, stmts: this.lines, term: 'switch', switchExpr, switchDefault: defTarget, switchCases };
1283
+ for (const t of [defTarget, ...switchCases.map(c => c.target)]) visitTarget(t, outDepth);
1284
+ } else if (last.isBranch) {
1285
+ const target = last.nextPc + last.offset;
1286
+ const fall = raw.fallthroughId;
1287
+ if (last.opaque === 'taken') {
1288
+ this._pop();
1289
+ const outDepth = this._spillStack();
1290
+ if (outDepth > maxSpill) maxSpill = outDepth;
1291
+ bb = { id: bid, stmts: this.lines, term: 'jump', next: rawMap.has(target) ? target : null };
1292
+ visitTarget(bb.next, outDepth);
1293
+ } else if (last.opaque === 'not-taken') {
1294
+ this._pop();
1295
+ const outDepth = this._spillStack();
1296
+ if (outDepth > maxSpill) maxSpill = outDepth;
1297
+ bb = { id: bid, stmts: this.lines, term: 'fallthrough', next: fall };
1298
+ visitTarget(fall, outDepth);
1299
+ } else {
1300
+ const cond = this._branchCond(last);
1301
+ const outDepth = this._spillStack();
1302
+ if (outDepth > maxSpill) maxSpill = outDepth;
1303
+ const tTarget = rawMap.has(target) ? target : null;
1304
+ const fTarget = fall !== null && rawMap.has(fall) ? fall : null;
1305
+ bb = { id: bid, stmts: this.lines, term: 'branch', cond, trueTarget: tTarget, falseTarget: fTarget };
1306
+ for (const t of [fTarget, tTarget]) visitTarget(t, outDepth);
1307
+ }
1308
+ } else {
1309
+ this._emitInstruction(last);
1310
+ const outDepth = this._spillStack();
1311
+ if (outDepth > maxSpill) maxSpill = outDepth;
1312
+ const nxt = raw.fallthroughId !== null && rawMap.has(raw.fallthroughId) ? raw.fallthroughId : null;
1313
+ bb = { id: bid, stmts: this.lines, term: 'fallthrough', next: nxt };
1314
+ visitTarget(nxt, outDepth);
1315
+ }
1316
+
1317
+ simulated.set(bid, bb);
1318
+ }
1319
+
1320
+ const blocks = rawBlocks.map(r => simulated.get(r.id)).filter(Boolean);
1321
+ return { blocks, maxSpill };
1322
+ }
1323
+
1324
+ _spillStack() {
1325
+ if (this._dynamicStack) return 0;
1326
+ const d = this.stack.length;
1327
+ for (let k = 0; k < d; k++) {
1328
+ if (this.stack[k] !== `_s${k}`) {
1329
+ this.lines.push(`_s${k} = ${this.stack[k]};`);
1330
+ }
1331
+ }
1332
+ return d;
1333
+ }
1334
+
1335
+ _branchCond(insn) {
1336
+ switch (insn.op) {
1337
+ case ABC.iftrue: return _simplifyCond(this._pop());
1338
+ case ABC.iffalse: return _negateCond(this._pop());
1339
+ case ABC.ifeq: { const b = this._pop(); const a = this._pop(); return `_avm2Equals(${a}, ${b})`; }
1340
+ case ABC.ifne: { const b = this._pop(); const a = this._pop(); return `!_avm2Equals(${a}, ${b})`; }
1341
+ case ABC.iflt: { const b = this._pop(); const a = this._pop(); return `(${a} < ${b})`; }
1342
+ case ABC.ifle: { const b = this._pop(); const a = this._pop(); return `(${a} <= ${b})`; }
1343
+ case ABC.ifgt: { const b = this._pop(); const a = this._pop(); return `(${a} > ${b})`; }
1344
+ case ABC.ifge: { const b = this._pop(); const a = this._pop(); return `(${a} >= ${b})`; }
1345
+ case ABC.ifnlt: { const b = this._pop(); const a = this._pop(); return `!(${a} < ${b})`; }
1346
+ case ABC.ifnle: { const b = this._pop(); const a = this._pop(); return `!(${a} <= ${b})`; }
1347
+ case ABC.ifngt: { const b = this._pop(); const a = this._pop(); return `!(${a} > ${b})`; }
1348
+ case ABC.ifnge: { const b = this._pop(); const a = this._pop(); return `!(${a} >= ${b})`; }
1349
+ case ABC.ifstricteq: { const b = this._pop(); const a = this._pop(); return `(${a} === ${b})`; }
1350
+ case ABC.ifstrictne: { const b = this._pop(); const a = this._pop(); return `(${a} !== ${b})`; }
1351
+ default: return 'true';
1352
+ }
1353
+ }
1354
+
1355
+ /** Decode a single instruction's operands without executing stack effects. */
1356
+ _decodeInstruction(bytes, pc) {
1357
+ const op = bytes[pc];
1358
+ let i = pc + 1;
1359
+ const insn = { pc, op, nextPc: i, isBranch: false };
1360
+
1361
+ switch (op) {
1362
+ // 0 operands
1363
+ case ABC.bkpt: case ABC.nop: case ABC.throw: case ABC.dxnslate: case ABC.label:
1364
+ case ABC.pushwith: case ABC.popscope: case ABC.nextname: case ABC.hasnext:
1365
+ case ABC.pushnull: case ABC.pushundefined: case ABC.nextvalue:
1366
+ case ABC.pushtrue: case ABC.pushfalse: case ABC.pushnan:
1367
+ case ABC.pop: case ABC.dup: case ABC.swap: case ABC.pushscope:
1368
+ case ABC.li8: case ABC.li16: case ABC.li32: case ABC.lf32: case ABC.lf64:
1369
+ case ABC.si8: case ABC.si16: case ABC.si32: case ABC.sf32: case ABC.sf64:
1370
+ case ABC.returnvoid: case ABC.returnvalue:
1371
+ case ABC.sxi1: case ABC.sxi8: case ABC.sxi16:
1372
+ case ABC.newactivation: case ABC.getglobalscope:
1373
+ case ABC.setpropertylate: case ABC.deletepropertylate:
1374
+ case ABC.convert_s: case ABC.esc_xelem: case ABC.esc_xattr:
1375
+ case ABC.convert_i: case ABC.convert_u: case ABC.convert_d:
1376
+ case ABC.convert_b: case ABC.convert_o: case ABC.checkfilter:
1377
+ case ABC.coerce_b: case ABC.coerce_a: case ABC.coerce_i:
1378
+ case ABC.coerce_d: case ABC.coerce_s: case ABC.astypelate:
1379
+ case ABC.coerce_u: case ABC.coerce_o:
1380
+ case ABC.negate: case ABC.increment: case ABC.decrement:
1381
+ case ABC.typeof: case ABC.not: case ABC.bitnot:
1382
+ case ABC.add: case ABC.subtract: case ABC.multiply: case ABC.divide: case ABC.modulo:
1383
+ case ABC.lshift: case ABC.rshift: case ABC.urshift:
1384
+ case ABC.bitand: case ABC.bitor: case ABC.bitxor:
1385
+ case ABC.equals: case ABC.strictequals: case ABC.lessthan: case ABC.lessequals:
1386
+ case ABC.greaterthan: case ABC.greaterequals:
1387
+ case ABC.instanceof: case ABC.istypelate: case ABC.in:
1388
+ case ABC.increment_i: case ABC.decrement_i: case ABC.negate_i:
1389
+ case ABC.add_i: case ABC.subtract_i: case ABC.multiply_i:
1390
+ case ABC.getlocal0: case ABC.getlocal1: case ABC.getlocal2: case ABC.getlocal3:
1391
+ case ABC.setlocal0: case ABC.setlocal1: case ABC.setlocal2: case ABC.setlocal3:
1392
+ case ABC.timestamp:
1393
+ break;
1394
+
1395
+ // u8 operand
1396
+ case ABC.pushbyte: {
1397
+ insn.a = i < bytes.length ? ((bytes[i++] << 24) >> 24) : 0;
1398
+ break;
1399
+ }
1400
+
1401
+ // s24 branch/jump operands
1402
+ case ABC.ifnlt: case ABC.ifnle: case ABC.ifngt: case ABC.ifnge:
1403
+ case ABC.jump:
1404
+ case ABC.iftrue: case ABC.iffalse:
1405
+ case ABC.ifeq: case ABC.ifne:
1406
+ case ABC.iflt: case ABC.ifle:
1407
+ case ABC.ifgt: case ABC.ifge:
1408
+ case ABC.ifstricteq: case ABC.ifstrictne: {
1409
+ insn.offset = i + 3 <= bytes.length ? this._readS24(bytes, i) : 0;
1410
+ i = Math.min(i + 3, bytes.length);
1411
+ insn.isBranch = op !== ABC.jump;
1412
+ break;
1413
+ }
1414
+
1415
+ // lookupswitch: s24 default, u30 caseCount, (caseCount + 1) * s24
1416
+ case ABC.lookupswitch: {
1417
+ const defOff = i + 3 <= bytes.length ? this._readS24(bytes, i) : 0;
1418
+ i = Math.min(i + 3, bytes.length);
1419
+ const cntR = this._readU30(bytes, i);
1420
+ i = cntR.next;
1421
+ const caseCount = Math.min(cntR.val, 4096);
1422
+ const targets = [pc + defOff];
1423
+ for (let c = 0; c <= caseCount && i + 3 <= bytes.length; c++) {
1424
+ const cOff = this._readS24(bytes, i);
1425
+ i += 3;
1426
+ targets.push(pc + cOff);
1427
+ }
1428
+ insn.targets = targets;
1429
+ break;
1430
+ }
1431
+
1432
+ // single u30 operand
1433
+ case ABC.getsuper: case ABC.setsuper: case ABC.dxns: case ABC.kill:
1434
+ case ABC.pushshort: case ABC.pushstring: case ABC.pushint: case ABC.pushuint:
1435
+ case ABC.pushdouble: case ABC.pushnamespace:
1436
+ case ABC.newfunction: case ABC.call: case ABC.construct: case ABC.constructsuper:
1437
+ case ABC.applytype: case ABC.newobject: case ABC.newarray: case ABC.newclass:
1438
+ case ABC.getdescendants: case ABC.newcatch:
1439
+ case ABC.findpropglobalstrict: case ABC.findpropglobal:
1440
+ case ABC.findpropstrict: case ABC.findproperty: case ABC.finddef:
1441
+ case ABC.getlex: case ABC.setproperty: case ABC.getlocal: case ABC.setlocal:
1442
+ case ABC.getscopeobject: case ABC.getproperty: case ABC.getouterscope:
1443
+ case ABC.initproperty: case ABC.deleteproperty:
1444
+ case ABC.getslot: case ABC.setslot: case ABC.getglobalslot: case ABC.setglobalslot:
1445
+ case ABC.coerce: case ABC.astype: case ABC.istype:
1446
+ case ABC.inclocal: case ABC.declocal: case ABC.inclocal_i: case ABC.declocal_i:
1447
+ case ABC.debugline: case ABC.debugfile: case ABC.bkptline: {
1448
+ const r = this._readU30(bytes, i);
1449
+ insn.a = r.val;
1450
+ i = r.next;
1451
+ break;
1452
+ }
1453
+
1454
+ // two u30 operands
1455
+ case ABC.hasnext2:
1456
+ case ABC.callmethod: case ABC.callstatic:
1457
+ case ABC.callsuper: case ABC.callproperty:
1458
+ case ABC.constructprop: case ABC.callsuperid:
1459
+ case ABC.callproplex: case ABC.callsupervoid: case ABC.callpropvoid: {
1460
+ const r1 = this._readU30(bytes, i);
1461
+ const r2 = this._readU30(bytes, r1.next);
1462
+ insn.a = r1.val;
1463
+ insn.b = r2.val;
1464
+ i = r2.next;
1465
+ break;
1466
+ }
1467
+
1468
+ // debug: u8 debugType, u30 index, u8 reg, u30 extra
1469
+ case ABC.debug: {
1470
+ if (i < bytes.length) insn.a = bytes[i++];
1471
+ const r1 = this._readU30(bytes, i);
1472
+ i = r1.next;
1473
+ if (i < bytes.length) i++;
1474
+ const r2 = this._readU30(bytes, i);
1475
+ i = r2.next;
1476
+ break;
1477
+ }
1478
+
1479
+ default:
1480
+ break;
1481
+ }
1482
+
1483
+ insn.nextPc = i;
1484
+ return insn;
1485
+ }
1486
+
1487
+ /** Emit JS for a single decoded instruction. Returns true if control flow unconditionally leaves. */
1488
+ _emitInstruction(insn) {
1489
+ const op = insn.op;
1490
+
1491
+ switch (op) {
1492
+ // --- Push constants ---
1493
+ case ABC.pushbyte:
1494
+ this.stack.push(String(insn.a));
1495
+ return false;
1496
+ case ABC.pushshort: {
1497
+ // u30 sign-extended from 16-bit
1498
+ const raw = insn.a & 0xFFFF;
1499
+ const val = raw >= 0x8000 ? raw - 0x10000 : raw;
1500
+ this.stack.push(String(val));
1501
+ return false;
1502
+ }
1503
+ case ABC.pushint:
1504
+ this.stack.push(String(this.cp.ints[insn.a] ?? 0));
1505
+ return false;
1506
+ case ABC.pushuint:
1507
+ this.stack.push(String(this.cp.uints[insn.a] ?? 0));
1508
+ return false;
1509
+ case ABC.pushdouble:
1510
+ this.stack.push(String(this.cp.doubles[insn.a] ?? 0));
1511
+ return false;
1512
+ case ABC.pushstring:
1513
+ this.stack.push(JSON.stringify(this.cp.strings[insn.a] ?? ''));
1514
+ return false;
1515
+ case ABC.pushnamespace:
1516
+ this.stack.push(_namespaceLiteral(this.cp, insn.a, this.methodTableName));
1517
+ return false;
1518
+ case ABC.pushtrue:
1519
+ this.stack.push('true');
1520
+ return false;
1521
+ case ABC.pushfalse:
1522
+ this.stack.push('false');
1523
+ return false;
1524
+ case ABC.pushnull:
1525
+ this.stack.push('null');
1526
+ return false;
1527
+ case ABC.pushundefined:
1528
+ this.stack.push('undefined');
1529
+ return false;
1530
+ case ABC.pushnan:
1531
+ this.stack.push('NaN');
1532
+ return false;
1533
+
1534
+ // --- Stack ---
1535
+ case ABC.pop: {
1536
+ const v = this._pop();
1537
+ if (v !== 'undefined') this.lines.push(`${v};`);
1538
+ return false;
1539
+ }
1540
+ case ABC.dup: {
1541
+ const v = this._peek();
1542
+ if (this._dynamicStack) {
1543
+ const value = this._pop();
1544
+ this.stack.push(value, value);
1545
+ return false;
1546
+ }
1547
+ // dup copies a value, so a deferred read must only run once even
1548
+ // when a following instruction updates its source before either use.
1549
+ if (!/^(?:_[lst]\d+|this|_pre|undefined|null|true|false|NaN|[-\d.]+)$/.test(v)) {
1550
+ const tmp = this._tmpVar();
1551
+ this.stack.pop();
1552
+ this.lines.push(`var ${tmp} = ${v};`);
1553
+ this.stack.push(tmp, tmp);
1554
+ } else {
1555
+ this.stack.push(v);
1556
+ }
1557
+ return false;
1558
+ }
1559
+ case ABC.swap: {
1560
+ const a = this._pop();
1561
+ const b = this._pop();
1562
+ this.stack.push(a, b);
1563
+ return false;
1564
+ }
1565
+
1566
+ // --- Locals ---
1567
+ case ABC.getlocal0: this.stack.push(this._thisRef()); return false;
1568
+ case ABC.getlocal1: this.stack.push('_l1'); return false;
1569
+ case ABC.getlocal2: this.stack.push('_l2'); return false;
1570
+ case ABC.getlocal3: this.stack.push('_l3'); return false;
1571
+ case ABC.getlocal: this.stack.push(insn.a === 0 ? this._thisRef() : `_l${insn.a}`); return false;
1572
+
1573
+ case ABC.setlocal0: { this._pop(); return false; } // cannot assign to `this` in JS
1574
+ case ABC.setlocal1: case ABC.setlocal2: case ABC.setlocal3:
1575
+ case ABC.setlocal: {
1576
+ const local = op === ABC.setlocal ? insn.a : op - ABC.setlocal0;
1577
+ const value = this._pop();
1578
+ if (local !== 0) {
1579
+ this._preserveStackBeforeLocalWrite(local);
1580
+ this.lines.push(`_l${local} = ${value};`);
1581
+ }
1582
+ return false;
1583
+ }
1584
+ case ABC.kill:
1585
+ if (insn.a !== 0) {
1586
+ this._preserveStackBeforeLocalWrite(insn.a);
1587
+ this.lines.push(`_l${insn.a} = undefined;`);
1588
+ }
1589
+ return false;
1590
+
1591
+ // --- Arithmetic ---
1592
+ case ABC.add: case ABC.add_i: this._binop('+'); return false;
1593
+ case ABC.subtract: case ABC.subtract_i: this._binop('-'); return false;
1594
+ case ABC.multiply: case ABC.multiply_i: this._binop('*'); return false;
1595
+ case ABC.divide: this._binop('/'); return false;
1596
+ case ABC.modulo: this._binop('%'); return false;
1597
+ case ABC.negate: { const v = this._pop(); this.stack.push(`(-(${v}))`); return false; }
1598
+ case ABC.negate_i: { const v = this._pop(); this.stack.push(`(-(${v}|0))`); return false; }
1599
+ case ABC.increment: { const v = this._pop(); this.stack.push(`((${v}) + 1)`); return false; }
1600
+ case ABC.decrement: { const v = this._pop(); this.stack.push(`((${v}) - 1)`); return false; }
1601
+ case ABC.increment_i:{ const v = this._pop(); this.stack.push(`((${v}|0) + 1)`); return false; }
1602
+ case ABC.decrement_i:{ const v = this._pop(); this.stack.push(`((${v}|0) - 1)`); return false; }
1603
+ case ABC.inclocal:
1604
+ if (insn.a !== 0) {
1605
+ this._preserveStackBeforeLocalWrite(insn.a);
1606
+ this.lines.push(`_l${insn.a}++;`);
1607
+ }
1608
+ return false;
1609
+ case ABC.declocal:
1610
+ if (insn.a !== 0) {
1611
+ this._preserveStackBeforeLocalWrite(insn.a);
1612
+ this.lines.push(`_l${insn.a}--;`);
1613
+ }
1614
+ return false;
1615
+ case ABC.inclocal_i:
1616
+ if (insn.a !== 0) {
1617
+ this._preserveStackBeforeLocalWrite(insn.a);
1618
+ this.lines.push(`_l${insn.a} = (_l${insn.a}|0) + 1;`);
1619
+ }
1620
+ return false;
1621
+ case ABC.declocal_i:
1622
+ if (insn.a !== 0) {
1623
+ this._preserveStackBeforeLocalWrite(insn.a);
1624
+ this.lines.push(`_l${insn.a} = (_l${insn.a}|0) - 1;`);
1625
+ }
1626
+ return false;
1627
+
1628
+ // --- Comparison ---
1629
+ case ABC.equals: {
1630
+ const right = this._pop(), left = this._pop();
1631
+ this.stack.push(`_avm2Equals(${left}, ${right})`);
1632
+ return false;
1633
+ }
1634
+ case ABC.strictequals: this._binop('==='); return false;
1635
+ case ABC.lessthan: this._binop('<'); return false;
1636
+ case ABC.lessequals: this._binop('<='); return false;
1637
+ case ABC.greaterthan: this._binop('>'); return false;
1638
+ case ABC.greaterequals: this._binop('>='); return false;
1639
+ case ABC.in: {
1640
+ const object = this._pop();
1641
+ const key = this._pop();
1642
+ this.stack.push(`_avm2In(${key}, ${object})`);
1643
+ return false;
1644
+ }
1645
+
1646
+ // --- Logic / bitwise ---
1647
+ case ABC.not: { const v = this._pop(); this.stack.push(`(!(${v}))`); return false; }
1648
+ case ABC.bitnot: { const v = this._pop(); this.stack.push(`(~(${v}))`); return false; }
1649
+ case ABC.bitand: this._binop('&'); return false;
1650
+ case ABC.bitor: this._binop('|'); return false;
1651
+ case ABC.bitxor: this._binop('^'); return false;
1652
+ case ABC.lshift: this._binop('<<'); return false;
1653
+ case ABC.rshift: this._binop('>>'); return false;
1654
+ case ABC.urshift: this._binop('>>>'); return false;
1655
+
1656
+ // --- Scope ---
1657
+ case ABC.pushscope:
1658
+ case ABC.pushwith: {
1659
+ const value = this._pop();
1660
+ if (this._runtimeScopes) {
1661
+ this.lines.push(`_avm2Scopes.push(_convertObject(${value}));`);
1662
+ return false;
1663
+ }
1664
+ const scope = this._tmpVar();
1665
+ this.lines.push(`var ${scope} = ${value};`);
1666
+ this.scopes.push(scope);
1667
+ return false;
1668
+ }
1669
+ case ABC.popscope:
1670
+ if (this._runtimeScopes) this.lines.push('_avm2Scopes.pop();');
1671
+ else this.scopes.pop();
1672
+ return false;
1673
+ case ABC.getscopeobject:
1674
+ this.stack.push(this._runtimeScopes ? `_avm2Scopes[${insn.a}]` : this.scopes[insn.a] ?? 'globalThis');
1675
+ return false;
1676
+ case ABC.getouterscope: {
1677
+ const outer = this._outerScopesExpression();
1678
+ this.stack.push(outer ? `${outer}[${insn.a}]` : 'undefined');
1679
+ return false;
1680
+ }
1681
+ case ABC.getglobalscope: {
1682
+ const outer = this._outerScopesExpression();
1683
+ const fallback = this._runtimeScopes ? `(_avm2Scopes[0] ?? ${this._scriptScopeExpression()})`
1684
+ : this.scopes[0] || this._scriptScopeExpression();
1685
+ this.stack.push(outer ? `(${outer}[0] ?? ${fallback})` : fallback);
1686
+ return false;
1687
+ }
1688
+
1689
+ // --- Property access ---
1690
+ case ABC.getproperty: {
1691
+ const xml = this._popXmlSelector(insn.a);
1692
+ if (xml) {
1693
+ this.stack.push(`_avm2E4XProperty(${this._pop()}, "get", ${xml}${this._xmlNamespaceArg(true)})`);
1694
+ return false;
1695
+ }
1696
+ const late = this._popRuntimeName(insn.a);
1697
+ const key = late ? '""' : this._popMultinameAccess(insn.a, true);
1698
+ const obj = this._pop();
1699
+ const candidates = this.namespaceKeys.lookup(insn.a);
1700
+ if (late) {
1701
+ this.stack.push(`_avm2GetLateProperty(${obj}, [${late}], ${this._xmlUris(insn.a)}${this._xmlNamespaceArg()})`);
1702
+ return false;
1703
+ }
1704
+ const name = candidates ? JSON.stringify(this.cp.multinames[insn.a]?.localName || '') : key;
1705
+ this.stack.push(this.usesDefaultXmlNamespace
1706
+ ? `_avm2NamedXmlProperty(${obj}, "get", ${name}, ${candidates || 'null'}, ${JSON.stringify(this.cp.multinames[insn.a]?.localName || '')}, ${this._xmlUris(insn.a)}, _avm2Dxns)`
1707
+ : `_avm2GetProperty(${obj}, ${name}${candidates ? `, ${candidates}` : ''})`);
1708
+ return false;
1709
+ }
1710
+ case ABC.setproperty:
1711
+ case ABC.initproperty: {
1712
+ const val = this._pop();
1713
+ const xml = this._popXmlSelector(insn.a);
1714
+ if (xml) {
1715
+ this.lines.push(`_avm2E4XProperty(${this._pop()}, "set", ${xml}, ${val}${this._xmlNamespaceArg()});`);
1716
+ return false;
1717
+ }
1718
+ const late = this._popRuntimeName(insn.a);
1719
+ const prop = late ? '' : this._popMultinameAccess(insn.a);
1720
+ const obj = this._pop();
1721
+ // Pre-super ctor body writes go to `_pre`.
1722
+ const candidates = this.namespaceKeys.lookup(insn.a);
1723
+ if (late) {
1724
+ const extra = this.usesDefaultXmlNamespace ? `, ${this._xmlUris(insn.a)}, _avm2Dxns` : '';
1725
+ this.lines.push(`_avm2SetLateProperty(${obj}, [${late}], ${val}${extra});`);
1726
+ } else if (this.usesDefaultXmlNamespace) {
1727
+ const name = this.cp.multinames[insn.a]?.localName || '';
1728
+ const key = candidates ? JSON.stringify(name) : this._popMultinameAccess(insn.a, true);
1729
+ this.lines.push(`_avm2NamedXmlProperty(${obj === 'this' ? '(this || globalThis)' : obj}, "set", ${key}, ${candidates || 'null'}, ${JSON.stringify(name)}, ${this._xmlUris(insn.a)}, _avm2Dxns, ${val});`);
1730
+ } else if (candidates) {
1731
+ this.lines.push(`_avm2SetProperty(${obj}, ${JSON.stringify(this.cp.multinames[insn.a]?.localName || '')}, ${val}, ${candidates});`);
1732
+ } else if (obj === '_pre') {
1733
+ this.lines.push(`_pre${prop} = ${val};`);
1734
+ } else if (obj === 'this') {
1735
+ this.lines.push(`(this || globalThis)${prop} = ${val};`);
1736
+ } else {
1737
+ this.lines.push(`(${obj})${prop} = ${val};`);
1738
+ }
1739
+ return false;
1740
+ }
1741
+ case ABC.setpropertylate: {
1742
+ const val = this._pop();
1743
+ const key = this._pop();
1744
+ const obj = this._pop();
1745
+ this.lines.push(`(${obj})[${key}] = ${val};`);
1746
+ return false;
1747
+ }
1748
+ case ABC.deleteproperty: {
1749
+ const xml = this._popXmlSelector(insn.a);
1750
+ if (xml) {
1751
+ this.stack.push(`_avm2E4XProperty(${this._pop()}, "delete", ${xml}${this._xmlNamespaceArg(true)})`);
1752
+ return false;
1753
+ }
1754
+ const late = this._popRuntimeName(insn.a);
1755
+ const prop = late ? '' : this._popMultinameAccess(insn.a);
1756
+ const obj = this._pop();
1757
+ const candidates = this.namespaceKeys.lookup(insn.a);
1758
+ if (late) {
1759
+ this.stack.push(`_avm2DeleteLateProperty(${obj}, [${late}], ${this._xmlUris(insn.a)}${this._xmlNamespaceArg()})`);
1760
+ return false;
1761
+ }
1762
+ if (this.usesDefaultXmlNamespace) {
1763
+ const name = this.cp.multinames[insn.a]?.localName || '';
1764
+ const key = candidates ? JSON.stringify(name) : this._popMultinameAccess(insn.a, true);
1765
+ this.stack.push(`_avm2NamedXmlProperty(${obj}, "delete", ${key}, ${candidates || 'null'}, ${JSON.stringify(name)}, ${this._xmlUris(insn.a)}, _avm2Dxns)`);
1766
+ return false;
1767
+ }
1768
+ this.stack.push(candidates
1769
+ ? `_avm2DeleteProperty(${obj}, ${JSON.stringify(this.cp.multinames[insn.a]?.localName || '')}, ${candidates})`
1770
+ : `delete (${obj})${prop}`);
1771
+ return false;
1772
+ }
1773
+ case ABC.deletepropertylate: {
1774
+ const key = this._pop();
1775
+ const obj = this._pop();
1776
+ this.stack.push(`delete (${obj})[${key}]`);
1777
+ return false;
1778
+ }
1779
+ case ABC.getsuper: {
1780
+ const key = this._popSuperAccess(insn.a, true);
1781
+ const obj = this._pop();
1782
+ this.stack.push(this.hasSuper
1783
+ ? `_avm2BindMethod(${obj}, super[${key}])`
1784
+ : `_avm2GetProperty(${obj}, ${key})`);
1785
+ return false;
1786
+ }
1787
+ case ABC.setsuper: {
1788
+ const val = this._pop();
1789
+ const prop = this._popSuperAccess(insn.a);
1790
+ const obj = this._pop();
1791
+ this.lines.push(this.hasSuper ? `super${prop} = ${val};` : `(${obj})${prop} = ${val};`);
1792
+ return false;
1793
+ }
1794
+ case ABC.getdescendants: {
1795
+ const selector = this._popXmlSelector(insn.a, true);
1796
+ this.stack.push(`_avm2E4XProperty(${this._pop()}, "descendants", ${selector}${this._xmlNamespaceArg(true)})`);
1797
+ return false;
1798
+ }
1799
+ case ABC.getslot: {
1800
+ const obj = this._pop();
1801
+ this.stack.push(`_getSlot(${obj}, ${insn.a})`);
1802
+ return false;
1803
+ }
1804
+ case ABC.setslot: {
1805
+ const val = this._pop();
1806
+ const obj = this._pop();
1807
+ this.lines.push(`_setSlot(${obj}, ${insn.a}, ${val}, ${(this.isCtor || this.isInitializer) ? 'true' : 'false'});`);
1808
+ return false;
1809
+ }
1810
+ case ABC.getglobalslot:
1811
+ this.stack.push(`_getGlobalSlot(${JSON.stringify(this.methodTableName)}, ${this.scriptScopeId}, ${insn.a})`);
1812
+ return false;
1813
+ case ABC.setglobalslot: {
1814
+ const val = this._pop();
1815
+ this.lines.push(`_setGlobalSlot(${JSON.stringify(this.methodTableName)}, ${this.scriptScopeId}, ${insn.a}, ${val});`);
1816
+ return false;
1817
+ }
1818
+
1819
+ // --- Find property ---
1820
+ case ABC.findpropstrict:
1821
+ case ABC.findpropglobalstrict: {
1822
+ const late = this._popRuntimeName(insn.a);
1823
+ const name = late ? '""' : JSON.stringify(this._multinameLookupName(insn.a));
1824
+ const candidates = late ? `_avm2RuntimeKeys(${late})` : this.namespaceKeys.lexical(insn.a);
1825
+ const globalOnly = op === ABC.findpropglobalstrict;
1826
+ const scopes = globalOnly ? '[]' : this._scopeExpression();
1827
+ const receiver = globalOnly ? 'globalThis' : this._lookupReceiver();
1828
+ this.stack.push(`_findProp(${name}, ${receiver}, ${scopes}, true, ${globalOnly}${this._classScopeArg(candidates, globalOnly, insn.a)})`);
1829
+ return false;
1830
+ }
1831
+ case ABC.findproperty:
1832
+ case ABC.findpropglobal:
1833
+ case ABC.finddef: {
1834
+ const late = this._popRuntimeName(insn.a);
1835
+ const name = late ? '""' : JSON.stringify(this._multinameLookupName(insn.a));
1836
+ const candidates = late ? `_avm2RuntimeKeys(${late})` : this.namespaceKeys.lexical(insn.a);
1837
+ const globalOnly = op === ABC.findpropglobal || op === ABC.finddef;
1838
+ const strict = op === ABC.finddef;
1839
+ const scopes = globalOnly ? '[]' : this._scopeExpression();
1840
+ const receiver = globalOnly ? 'globalThis' : this._lookupReceiver();
1841
+ this.stack.push(`_findProp(${name}, ${receiver}, ${scopes}, ${strict}, ${globalOnly}${this._classScopeArg(candidates, globalOnly, insn.a)})`);
1842
+ return false;
1843
+ }
1844
+ case ABC.getlex: {
1845
+ const kind = this.cp.multinames[insn.a]?.kind;
1846
+ if (kind === 0x0D || kind === 0x0E) {
1847
+ const selector = this._popXmlSelector(insn.a);
1848
+ this.stack.push(`_avm2GetLexicalXmlAttribute(${this._scopeExpression()}, ${selector})`);
1849
+ return false;
1850
+ }
1851
+ if (this.cp.multinames[insn.a]?.kind === 0x1D) {
1852
+ this.stack.push(this._typeOperand(insn.a).expression);
1853
+ return false;
1854
+ }
1855
+ const late = this._popRuntimeName(insn.a);
1856
+ const name = late ? '' : this._multiname(insn.a);
1857
+ this.stack.push(this._getlexExpression(name, late ? `_avm2RuntimeKeys(${late})` : this.namespaceKeys.lexical(insn.a), insn.a));
1858
+ return false;
1859
+ }
1860
+
1861
+ // --- Object/array/function creation ---
1862
+ case ABC.newobject: {
1863
+ const count = Math.min(insn.a, MAX_STACK_ARGS);
1864
+ const pairs = new Array(count);
1865
+ for (let n = count - 1; n >= 0; n--) {
1866
+ const val = this._pop();
1867
+ const key = this._pop();
1868
+ pairs[n] = `[${key}]: ${val}`;
1869
+ }
1870
+ this.stack.push(`({${pairs.join(', ')}})`);
1871
+ return false;
1872
+ }
1873
+ case ABC.newarray: {
1874
+ const items = this._popN(insn.a);
1875
+ this.stack.push(`[${items.join(', ')}]`);
1876
+ return false;
1877
+ }
1878
+ case ABC.newactivation: {
1879
+ const tmp = this._tmpVar();
1880
+ const traits = (this.method.body?.traits || []).filter(trait => trait.kind === 0 || trait.kind === 6);
1881
+ const explicitIds = new Set(traits.map(trait => trait.slotId).filter(Boolean));
1882
+ let nextId = 1;
1883
+ const slots = traits.map(trait => {
1884
+ const rawName = _avm2PropertyName(this.cp.multinames[trait.nameIndex], `_trait${trait.nameIndex}`, this.methodTableName);
1885
+ while (explicitIds.has(nextId)) nextId++;
1886
+ const slotId = trait.slotId || nextId++;
1887
+ return `[${slotId}, ${JSON.stringify(rawName)}, ${_slotDefaultLiteral(this.cp, trait, this.methodTableName)}]`;
1888
+ });
1889
+ this.lines.push(`var ${tmp} = _createAvm2Activation([${slots.join(', ')}]);`);
1890
+ this.stack.push(tmp);
1891
+ return false;
1892
+ }
1893
+ case ABC.newcatch: {
1894
+ const entry = this.method.body?.exceptions[insn.a];
1895
+ const key = entry?.varName ? _avm2PropertyName(this.cp.multinames[entry.varName], `_catch${entry.varName}`, this.methodTableName) : null;
1896
+ const slots = key === null ? '' : `[1, ${JSON.stringify(key)}, ${_slotDefaultLiteral(this.cp, { typeNameIndex: entry.excType }, this.methodTableName)}]`;
1897
+ this.stack.push(`_createAvm2Activation([${slots}])`);
1898
+ return false;
1899
+ }
1900
+ case ABC.newclass: {
1901
+ this._pop(); // emitted classes already resolve their base at registration
1902
+ const tmp = this._tmpVar();
1903
+ this.lines.push(`var ${tmp} = _captureAvm2ClassScopes(${this.classTableName}[${insn.a}], ${this._scopeExpression()}${this._xmlNamespaceArg()});`);
1904
+ this.stack.push(tmp);
1905
+ return false;
1906
+ }
1907
+ case ABC.newfunction: {
1908
+ const m = this.abc.methods[insn.a];
1909
+ const params = buildParamList(m);
1910
+ const body = m?.body
1911
+ ? transpileMethodBody(m, this.abc, this.diag, false, false, this.methodTableName, this.classTableName, this.namespaceKeys,
1912
+ this.scriptScopeId, false, this.lexicalClass, this.ownerClass, true)
1913
+ : '// empty';
1914
+ const tmp = this._tmpVar();
1915
+ const dxnsParameter = this.usesDefaultXmlNamespace ? ', _avm2CapturedDxns' : '';
1916
+ this.lines.push(`var ${tmp} = (function(_avm2OuterScopes${dxnsParameter}) { return function(${params}) {\n${indent(body, 1)}\n}; })(${this._scopeExpression()}${this._xmlNamespaceArg()});`);
1917
+ this.stack.push(tmp);
1918
+ return false;
1919
+ }
1920
+
1921
+ // --- Construct / Call ---
1922
+ case ABC.construct: {
1923
+ const args = this._popN(insn.a);
1924
+ const ctor = this._pop();
1925
+ this.stack.push(this._constructExpression(ctor, args));
1926
+ return false;
1927
+ }
1928
+ case ABC.constructsuper: {
1929
+ const args = this._popN(insn.a);
1930
+ this._pop(); // receiver
1931
+ if (this.hasSuper && (this._runtimeScopes || !this._emittedSuper)) {
1932
+ this.lines.push(...this._superCall(args));
1933
+ this._emittedSuper = true;
1934
+ if (this._usePreSuper) {
1935
+ if (this._runtimeScopes) this.lines.push('_avm2Scopes = _avm2Scopes.map(scope => scope === _pre ? this : scope);');
1936
+ else for (const scope of this.scopes) this.lines.push(`if (${scope} === _pre) ${scope} = this;`);
1937
+ }
1938
+ // Flash attaches a linked symbol's frame children before its AS3
1939
+ // constructor body accesses them. The callback maps this class name
1940
+ // back to its SymbolClass character and binds those child instances.
1941
+ this.lines.push('_bindAvm2Symbol(this);');
1942
+ }
1943
+ return false;
1944
+ }
1945
+ case ABC.constructprop: {
1946
+ const args = this._popN(insn.b);
1947
+ const late = this._popRuntimeName(insn.a);
1948
+ const prop = late ? '' : this._popMultinameAccess(insn.a);
1949
+ const obj = this._pop();
1950
+ const multiname = this.cp.multinames[insn.a];
1951
+ if (late) {
1952
+ this.stack.push(`_avm2ConstructLateProperty(${obj}, [${late}], [${args.join(', ')}]${this._xmlNamespaceArg()})`);
1953
+ } else if (_avm2UsesNamespaceIdentity(multiname)) {
1954
+ const key = this._popMultinameAccess(insn.a, true);
1955
+ const exact = this._multinameTypeName(insn.a);
1956
+ this.stack.push(this._constructExpression(`_avm2NamespacedConstructor(${obj}, ${key}, ${JSON.stringify(exact)})`, args));
1957
+ } else if (multiname?.nsKind === 0x16 && multiname.ns) {
1958
+ const name = this._multinameTypeName(insn.a);
1959
+ const receiver = this._lookupReceiver();
1960
+ const scopes = this._scopeExpression();
1961
+ const ctor = `_findProp(${JSON.stringify(name)}, ${receiver}, ${scopes}, true, false${this._classScopeArg()})[${JSON.stringify(name)}] || ${this._getlexExpression(name)}`;
1962
+ this.stack.push(this._constructExpression(ctor, args));
1963
+ } else {
1964
+ const candidates = this.namespaceKeys.lookup(insn.a);
1965
+ const ctor = candidates
1966
+ ? `_avm2GetProperty(${obj}, ${JSON.stringify(multiname?.localName || '')}, ${candidates})`
1967
+ : `((${obj})${prop})`;
1968
+ this.stack.push(this._constructExpression(ctor, args));
1969
+ }
1970
+ return false;
1971
+ }
1972
+ case ABC.callproperty:
1973
+ case ABC.callproplex:
1974
+ case ABC.callpropvoid: {
1975
+ const args = this._popN(insn.b);
1976
+ const late = this._popRuntimeName(insn.a);
1977
+ const key = late ? '""' : this._popMultinameAccess(insn.a, true);
1978
+ const obj = this._pop();
1979
+ const candidates = this.namespaceKeys.call(insn.a);
1980
+ const extra = this.usesDefaultXmlNamespace
1981
+ ? `, ${candidates ?? 'null'}, ${op === ABC.callproplex}, _avm2Dxns`
1982
+ : op === ABC.callproplex ? `, ${candidates ?? 'null'}, true` : candidates ? `, ${candidates}` : '';
1983
+ const call = late
1984
+ ? `_avm2CallLateProperty(${obj}, [${late}], [${args.join(', ')}], ${op === ABC.callproplex}${this._xmlNamespaceArg()})`
1985
+ : `_avm2CallProperty(${obj}, ${key}, [${args.join(', ')}]${extra})`;
1986
+ if (op === ABC.callpropvoid) {
1987
+ this.lines.push(`${call};`);
1988
+ } else {
1989
+ const tmp = this._tmpVar();
1990
+ this.lines.push(`var ${tmp} = ${call};`);
1991
+ this.stack.push(tmp);
1992
+ }
1993
+ return false;
1994
+ }
1995
+ case ABC.callsuper: {
1996
+ const args = this._popN(insn.b);
1997
+ const prop = this._popSuperAccess(insn.a);
1998
+ const obj = this._pop();
1999
+ const tmp = this._tmpVar();
2000
+ const target = this.hasSuper ? `super${prop}` : `(${obj})${prop}`;
2001
+ this.lines.push(`var ${tmp} = ${target}(${args.join(', ')});`);
2002
+ this.stack.push(tmp);
2003
+ return false;
2004
+ }
2005
+ case ABC.callsupervoid: {
2006
+ const args = this._popN(insn.b);
2007
+ const prop = this._popSuperAccess(insn.a);
2008
+ const obj = this._pop();
2009
+ const target = this.hasSuper ? `super${prop}` : `(${obj})${prop}`;
2010
+ this.lines.push(`${target}(${args.join(', ')});`);
2011
+ return false;
2012
+ }
2013
+ case ABC.callmethod: {
2014
+ const args = this._popN(insn.b);
2015
+ const obj = this._pop();
2016
+ const tmp = this._tmpVar();
2017
+ this.lines.push(`var ${tmp} = _callMethodById(${obj}, ${insn.a}, [${args.join(', ')}]);`);
2018
+ this.stack.push(tmp);
2019
+ return false;
2020
+ }
2021
+ case ABC.callsuperid: {
2022
+ const args = this._popN(insn.b);
2023
+ const obj = this._pop();
2024
+ const tmp = this._tmpVar();
2025
+ const owner = this.hasSuper && this.ownerClass ? `, ${this.ownerClass}` : '';
2026
+ this.lines.push(`var ${tmp} = _callSuperById(${obj}, ${insn.a}, [${args.join(', ')}]${owner});`);
2027
+ this.stack.push(tmp);
2028
+ return false;
2029
+ }
2030
+ case ABC.callstatic: {
2031
+ const args = this._popN(insn.b);
2032
+ const recv = this._pop();
2033
+ const tmp = this._tmpVar();
2034
+ this.lines.push(`var ${tmp} = _callStatic(${this.methodTableName}, ${insn.a}, ${recv}, [${args.join(', ')}]);`);
2035
+ this.stack.push(tmp);
2036
+ return false;
2037
+ }
2038
+ case ABC.call: {
2039
+ const args = this._popN(insn.a);
2040
+ const receiver = this._pop();
2041
+ const fn = this._pop();
2042
+ const tmp = this._tmpVar();
2043
+ this.lines.push(`var ${tmp} = _avm2Call(${fn}, ${receiver}, [${args.join(', ')}]${this._xmlNamespaceArg()});`);
2044
+ this.stack.push(tmp);
2045
+ return false;
2046
+ }
2047
+
2048
+ // --- Return / Throw ---
2049
+ case ABC.returnvalue: {
2050
+ const v = this._pop();
2051
+ this.lines.push(`return ${v};`);
2052
+ return true;
2053
+ }
2054
+ case ABC.returnvoid:
2055
+ this.lines.push(`return;`);
2056
+ return true;
2057
+ case ABC.throw: {
2058
+ const v = this._pop();
2059
+ this.lines.push(`throw ${v};`);
2060
+ return true;
2061
+ }
2062
+
2063
+ // --- Control flow ---
2064
+ case ABC.jump:
2065
+ this.lines.push(`/* jump ${insn.offset >= 0 ? '+' : ''}${insn.offset} */`);
2066
+ return true;
2067
+ case ABC.lookupswitch: {
2068
+ const idx = this._pop();
2069
+ this.lines.push(`/* lookupswitch(${idx}) */`);
2070
+ return true;
2071
+ }
2072
+ case ABC.iftrue: {
2073
+ const v = this._pop();
2074
+ if (insn.opaque === 'taken') {
2075
+ this.lines.push(`/* opaque iftrue (${v}) → +${insn.offset} */`);
2076
+ return true;
2077
+ }
2078
+ if (insn.opaque !== 'not-taken') {
2079
+ this.lines.push(`if (${v}) { /* branch +${insn.offset} */ }`);
2080
+ }
2081
+ return false;
2082
+ }
2083
+ case ABC.iffalse: {
2084
+ const v = this._pop();
2085
+ if (insn.opaque === 'taken') {
2086
+ this.lines.push(`/* opaque iffalse (${v}) → +${insn.offset} */`);
2087
+ return true;
2088
+ }
2089
+ if (insn.opaque !== 'not-taken') {
2090
+ this.lines.push(`if (!(${v})) { /* branch +${insn.offset} */ }`);
2091
+ }
2092
+ return false;
2093
+ }
2094
+ case ABC.ifeq: { const b = this._pop(); const a = this._pop(); this.lines.push(`if (_avm2Equals(${a}, ${b})) { /* ifeq */ }`); return false; }
2095
+ case ABC.ifne: { const b = this._pop(); const a = this._pop(); this.lines.push(`if (!_avm2Equals(${a}, ${b})) { /* ifne */ }`); return false; }
2096
+ case ABC.iflt: { const b = this._pop(); const a = this._pop(); this.lines.push(`if (${a} < ${b}) { /* iflt */ }`); return false; }
2097
+ case ABC.ifle: { const b = this._pop(); const a = this._pop(); this.lines.push(`if (${a} <= ${b}) { /* ifle */ }`); return false; }
2098
+ case ABC.ifgt: { const b = this._pop(); const a = this._pop(); this.lines.push(`if (${a} > ${b}) { /* ifgt */ }`); return false; }
2099
+ case ABC.ifge: { const b = this._pop(); const a = this._pop(); this.lines.push(`if (${a} >= ${b}) { /* ifge */ }`); return false; }
2100
+ case ABC.ifnlt: { const b = this._pop(); const a = this._pop(); this.lines.push(`if (!(${a} < ${b})) { /* ifnlt */ }`); return false; }
2101
+ case ABC.ifnle: { const b = this._pop(); const a = this._pop(); this.lines.push(`if (!(${a} <= ${b})) { /* ifnle */ }`); return false; }
2102
+ case ABC.ifngt: { const b = this._pop(); const a = this._pop(); this.lines.push(`if (!(${a} > ${b})) { /* ifngt */ }`); return false; }
2103
+ case ABC.ifnge: { const b = this._pop(); const a = this._pop(); this.lines.push(`if (!(${a} >= ${b})) { /* ifnge */ }`); return false; }
2104
+ case ABC.ifstricteq: { const b = this._pop(); const a = this._pop(); this.lines.push(`if (${a} === ${b}) { /* ifstricteq */ }`); return false; }
2105
+ case ABC.ifstrictne: { const b = this._pop(); const a = this._pop(); this.lines.push(`if (${a} !== ${b}) { /* ifstrictne */ }`); return false; }
2106
+
2107
+ // --- Type coercions ---
2108
+ case ABC.coerce_a:
2109
+ case ABC.checkfilter:
2110
+ return false;
2111
+ case ABC.convert_o: {
2112
+ const v = this._pop();
2113
+ this.stack.push(`_convertObject(${v})`);
2114
+ return false;
2115
+ }
2116
+ case ABC.coerce: {
2117
+ const v = this._pop();
2118
+ const { name, expression } = this._typeOperand(insn.a);
2119
+ this.stack.push(`_coerceType(${v}, ${expression}, ${JSON.stringify(name)})`);
2120
+ return false;
2121
+ }
2122
+ case ABC.coerce_o: {
2123
+ const v = this._pop();
2124
+ this.stack.push(`((${v}) ?? null)`);
2125
+ return false;
2126
+ }
2127
+ case ABC.coerce_s: { const v = this._pop(); this.stack.push(`_coerceString(${v})`); return false; }
2128
+ case ABC.coerce_b:
2129
+ case ABC.convert_b: { const v = this._pop(); this.stack.push(`Boolean(${v})`); return false; }
2130
+ case ABC.coerce_i:
2131
+ case ABC.convert_i: { const v = this._pop(); this.stack.push(`(${v}|0)`); return false; }
2132
+ case ABC.coerce_u:
2133
+ case ABC.convert_u: { const v = this._pop(); this.stack.push(`(${v}>>>0)`); return false; }
2134
+ case ABC.coerce_d:
2135
+ case ABC.convert_d: { const v = this._pop(); this.stack.push(`Number(${v})`); return false; }
2136
+ case ABC.convert_s:
2137
+ case ABC.esc_xelem:
2138
+ case ABC.esc_xattr: { const v = this._pop(); this.stack.push(`String(${v})`); return false; }
2139
+ case ABC.astype: {
2140
+ const v = this._pop();
2141
+ const { expression: type } = this._typeOperand(insn.a);
2142
+ this.stack.push(`_asType(${v}, ${type})`);
2143
+ return false;
2144
+ }
2145
+ case ABC.astypelate: { const t = this._pop(); const v = this._pop(); this.stack.push(`_asType(${v}, _requireAvm2Class(${t}))`); return false; }
2146
+ case ABC.instanceof: { const t = this._pop(); const v = this._pop(); this.stack.push(`((${v}) instanceof (${t}))`); return false; }
2147
+ case ABC.istype: { const v = this._pop(); this.stack.push(`_isType(${v}, ${this._typeOperand(insn.a).expression})`); return false; }
2148
+ case ABC.istypelate: { const t = this._pop(); const v = this._pop(); this.stack.push(`_isType(${v}, _requireAvm2Class(${t}))`); return false; }
2149
+ case ABC.typeof: { const v = this._pop(); this.stack.push(`_avm2TypeOf(${v})`); return false; }
2150
+
2151
+ // --- Iteration ---
2152
+ // hasnext2 updates the index register to the next live entry, or zero at exhaustion.
2153
+ case ABC.hasnext2: {
2154
+ this._preserveStackBeforeLocalWrite(insn.b);
2155
+ const tmp = this._tmpVar();
2156
+ this.lines.push(`var ${tmp} = (_l${insn.b} = _avm2HasNext(_l${insn.b}, _l${insn.a})) !== 0;`);
2157
+ this.stack.push(tmp);
2158
+ return false;
2159
+ }
2160
+ case ABC.hasnext: {
2161
+ const idx = this._pop();
2162
+ const obj = this._pop();
2163
+ this.stack.push(`_avm2HasNext(${idx}, ${obj})`);
2164
+ return false;
2165
+ }
2166
+ case ABC.nextname: {
2167
+ const idx = this._pop();
2168
+ const obj = this._pop();
2169
+ this.stack.push(`_avm2NextName(${obj}, ${idx})`);
2170
+ return false;
2171
+ }
2172
+ case ABC.nextvalue: {
2173
+ const idx = this._pop();
2174
+ const obj = this._pop();
2175
+ this.stack.push(`_avm2NextValue(${obj}, ${idx})`);
2176
+ return false;
2177
+ }
2178
+
2179
+ // --- Domain memory & sign extension ---
2180
+ case ABC.li8: case ABC.li16: case ABC.li32: case ABC.lf32: case ABC.lf64: {
2181
+ const addr = this._pop();
2182
+ this.stack.push(`_memRead(${op}, ${addr})`);
2183
+ return false;
2184
+ }
2185
+ case ABC.si8: case ABC.si16: case ABC.si32: case ABC.sf32: case ABC.sf64: {
2186
+ const addr = this._pop();
2187
+ const val = this._pop();
2188
+ this.lines.push(`_memWrite(${op}, ${addr}, ${val});`);
2189
+ return false;
2190
+ }
2191
+ case ABC.sxi1: case ABC.sxi8: case ABC.sxi16: {
2192
+ const v = this._pop();
2193
+ const bits = op === ABC.sxi1 ? 1 : op === ABC.sxi8 ? 8 : 16;
2194
+ this.stack.push(`_signExtend(${v}, ${bits})`);
2195
+ return false;
2196
+ }
2197
+
2198
+ // --- XML / NOP / Debug ---
2199
+ case ABC.nop: case ABC.bkpt: case ABC.label:
2200
+ case ABC.debug: case ABC.debugline: case ABC.debugfile:
2201
+ case ABC.bkptline: case ABC.timestamp:
2202
+ return false;
2203
+ case ABC.dxns:
2204
+ case ABC.dxnslate: {
2205
+ const uri = op === ABC.dxns ? JSON.stringify(this.cp.strings[insn.a] ?? '') : `String(${this._pop()})`;
2206
+ if (!this._dynamicStack) {
2207
+ this.stack = this.stack.map(value => {
2208
+ if (!value.includes('_avm2Dxns')) return value;
2209
+ const tmp = this._tmpVar();
2210
+ this.lines.push(`var ${tmp} = ${value};`);
2211
+ return tmp;
2212
+ });
2213
+ }
2214
+ this.lines.push(`_avm2Dxns = ${uri};`);
2215
+ return false;
2216
+ }
2217
+
2218
+ // --- Generics ---
2219
+ case ABC.applytype: {
2220
+ const typeArgs = this._popN(insn.a);
2221
+ const type = this._pop();
2222
+ this.stack.push(`_applyType(${type}, [${typeArgs.join(', ')}])`);
2223
+ return false;
2224
+ }
2225
+
2226
+ default: {
2227
+ const hex = op.toString(16).padStart(2, '0');
2228
+ this.diag.warn(`Unsupported AVM2 instruction 0x${hex}`, 'transpile', { opcode: op });
2229
+ this.lines.push(`throw new Error("Unsupported AVM2 instruction 0x${hex}");`);
2230
+ return false;
2231
+ }
2232
+ }
2233
+ }
2234
+
2235
+ // ---- Helpers ----
2236
+
2237
+ _preserveStackBeforeLocalWrite(local) {
2238
+ if (this._dynamicStack) return;
2239
+ const reference = new RegExp(`\\b_l${local}\\b`);
2240
+ const last = this.stack.findLastIndex(value => reference.test(value));
2241
+ // Locals are read when pushed in AVM2. Save deferred expressions that
2242
+ // would otherwise see the new value, keeping earlier operands in order.
2243
+ for (let index = 0; index <= last; index++) {
2244
+ const value = this.stack[index];
2245
+ if (/^_(?:s|t)\d+$/.test(value)) continue;
2246
+ const saved = this._tmpVar();
2247
+ this.lines.push(`var ${saved} = ${value};`);
2248
+ this.stack[index] = saved;
2249
+ }
2250
+ }
2251
+
2252
+ _pop() {
2253
+ if (this._dynamicStack) {
2254
+ const tmp = this._tmpVar();
2255
+ this.lines.push(`var ${tmp} = _avm2Stack.pop();`);
2256
+ if (this.stack.values.length) this.stack.values.pop();
2257
+ return tmp;
2258
+ }
2259
+ return this.stack.length > 0 ? this.stack.pop() : 'undefined';
2260
+ }
2261
+ _peek() {
2262
+ if (this._dynamicStack) return '_avm2Stack[_avm2Stack.length - 1]';
2263
+ return this.stack.length > 0 ? this.stack[this.stack.length - 1] : 'undefined';
2264
+ }
2265
+
2266
+ _createRuntimeStack() {
2267
+ const context = this;
2268
+ return {
2269
+ values: [],
2270
+ get length() { return this.values.length; },
2271
+ push(...values) {
2272
+ for (const value of values) {
2273
+ context.lines.push(`_avm2Stack.push(${value});`);
2274
+ this.values.push(value);
2275
+ }
2276
+ return this.values.length;
2277
+ },
2278
+ };
2279
+ }
2280
+
2281
+ _popN(n) {
2282
+ const count = Math.min(Math.max(0, n | 0), MAX_STACK_ARGS);
2283
+ const args = new Array(count);
2284
+ for (let i = count - 1; i >= 0; i--) {
2285
+ args[i] = this._pop();
2286
+ }
2287
+ return args;
2288
+ }
2289
+
2290
+ _binop(op) {
2291
+ const r = this._pop();
2292
+ const l = this._pop();
2293
+ this.stack.push(`(${l} ${op} ${r})`);
2294
+ }
2295
+
2296
+ _tmpVar() {
2297
+ return `_t${this._tmp++}`;
2298
+ }
2299
+
2300
+ _popSuperAccess(idx, keyOnly = false) {
2301
+ const name = this.cp.multinames[idx];
2302
+ const late = this._popRuntimeName(idx);
2303
+ if (late) {
2304
+ const candidates = `_avm2RuntimeKeys(${late})`;
2305
+ const key = this.hasSuper && this.ownerClass ? `_avm2SuperKey(${this.ownerClass}, "", ${candidates})` : `${candidates}[0]`;
2306
+ return keyOnly ? key : `[${key}]`;
2307
+ }
2308
+ if (!this.hasSuper || !this.ownerClass || (name?.nsKind !== 0x18 && !name?.nsSet?.some(ns => ns.kind === 0x18))) {
2309
+ return this._popMultinameAccess(idx, keyOnly);
2310
+ }
2311
+ const nameKey = this._popMultinameAccess(idx, true);
2312
+ const candidates = this.namespaceKeys.lookup(idx);
2313
+ const key = `_avm2SuperKey(${this.ownerClass}, ${nameKey}${candidates ? `, ${candidates}` : ''})`;
2314
+ return keyOnly ? key : `[${key}]`;
2315
+ }
2316
+
2317
+ /** @param {number} idx @returns {string} */
2318
+ _multiname(idx) {
2319
+ return this._multinameLookupName(idx);
2320
+ }
2321
+
2322
+ _multinameLookupName(idx) {
2323
+ const mn = this.cp.multinames[idx];
2324
+ if (mn?.nsKind === 0x16 && mn.ns) {
2325
+ return `${mn.ns}.${mn.localName}`;
2326
+ }
2327
+ return _avm2PropertyName(mn, `_mn${idx}`, this.methodTableName);
2328
+ }
2329
+
2330
+ _typeOperand(index, seen, catchType = false) {
2331
+ if (!index) return { name: '*', expression: 'null' };
2332
+ if (seen?.has(index)) throw new RangeError('Cyclic AVM2 parameterized type');
2333
+ const multiname = this.cp.multinames[index];
2334
+ if (multiname?.kind === 0x1D) {
2335
+ const path = new Set(seen).add(index);
2336
+ const base = this._typeOperand(multiname.typeBaseIndex, path, catchType);
2337
+ const args = multiname.typeParameterIndices.map(parameter => this._typeOperand(parameter, path, catchType));
2338
+ return {
2339
+ name: `${base.name}.<${args.map(arg => arg.name).join(', ')}>`,
2340
+ expression: `_applyType(${base.expression}, [${args.map(arg => arg.expression).join(', ')}])`,
2341
+ };
2342
+ }
2343
+ const name = this._multinameTypeName(index);
2344
+ const keys = this.namespaceKeys.exactType(index);
2345
+ const receiver = catchType ? 'null' : this._lookupReceiver();
2346
+ const scopes = catchType ? this._outerScopesExpression() || '[]' : this._scopeExpression();
2347
+ const expression = keys
2348
+ ? `_getlexScoped(${JSON.stringify(name)}, ${receiver}, ${scopes}, ${this.lexicalClass || 'undefined'}, ${keys}, ${this._scriptScopeExpression()}, true)`
2349
+ : this._getlexExpression(name, this.namespaceKeys.lexical(index), index, receiver, scopes);
2350
+ return { name, expression };
2351
+ }
2352
+
2353
+ _multinameTypeName(idx) {
2354
+ const mn = this.cp.multinames[idx];
2355
+ return _avm2TypeTraitName(mn, mn?.localName || `_mn${idx}`, this.methodTableName);
2356
+ }
2357
+
2358
+ _xmlNamespaceArg(skipValue = false) {
2359
+ return this.usesDefaultXmlNamespace ? (skipValue ? ', undefined, _avm2Dxns' : ', _avm2Dxns') : '';
2360
+ }
2361
+
2362
+ _constructExpression(ctor, args) {
2363
+ return this.usesDefaultXmlNamespace ? `_avm2Construct(${ctor}, [${args.join(', ')}], _avm2Dxns)`
2364
+ : `new (${ctor})(${args.join(', ')})`;
2365
+ }
2366
+
2367
+ _xmlUris(index) {
2368
+ const multiname = this.cp.multinames[index];
2369
+ if (!multiname) return '[""]';
2370
+ if (multiname.nsSet) {
2371
+ return JSON.stringify([...new Set(multiname.nsSet.map(ns => ns.kind ? ns.ns || '' : null))]);
2372
+ }
2373
+ if (multiname.nsIndex !== undefined) return JSON.stringify([multiname.nsKind ? multiname.ns || '' : null]);
2374
+ return 'null'; // Runtime QName supplies the namespace.
2375
+ }
2376
+
2377
+ _popXmlSelector(index, descendants = false) {
2378
+ const multiname = this.cp.multinames[index];
2379
+ const kind = multiname?.kind;
2380
+ const attribute = kind === 0x0D || kind === 0x0E || kind === MN_RTQNAME_A ||
2381
+ kind === MN_RTQNAME_LA || kind === MN_MULTINAME_LA;
2382
+ const lateName = kind === MN_RTQNAME_L || kind === MN_RTQNAME_LA ||
2383
+ kind === MN_MULTINAME_L || kind === MN_MULTINAME_LA;
2384
+ const runtimeNamespace = kind === MN_RTQNAME || kind === MN_RTQNAME_A ||
2385
+ kind === MN_RTQNAME_L || kind === MN_RTQNAME_LA;
2386
+ const wildcard = multiname?.nsIndex === 0 || !lateName && (!multiname?.localName || multiname.localName === '*');
2387
+ if (!descendants && !attribute && !wildcard) return null;
2388
+ if (!multiname && !descendants) return null;
2389
+ const name = lateName ? this._pop() : JSON.stringify(multiname?.localName || '*');
2390
+ const namespace = runtimeNamespace ? this._pop() : 'null';
2391
+ return `${attribute}, ${namespace}, ${name}, ${this._xmlUris(index)}`;
2392
+ }
2393
+
2394
+ _popRuntimeName(idx) {
2395
+ const multiname = this.cp.multinames[idx];
2396
+ switch (multiname?.kind) {
2397
+ case MN_MULTINAME_L:
2398
+ case MN_MULTINAME_LA:
2399
+ return `null, ${this._pop()}, ${this.namespaceKeys.lateSet(multiname)}`;
2400
+ case MN_RTQNAME_L:
2401
+ case MN_RTQNAME_LA: {
2402
+ const name = this._pop();
2403
+ return `${this._pop()}, ${name}`;
2404
+ }
2405
+ case MN_RTQNAME:
2406
+ case MN_RTQNAME_A:
2407
+ return `${this._pop()}, ${JSON.stringify(multiname.localName)}`;
2408
+ default:
2409
+ return null;
2410
+ }
2411
+ }
2412
+
2413
+ _popMultinameAccess(idx, keyOnly = false) {
2414
+ const key = _avm2PropertyName(this.cp.multinames[idx], `_mn${idx}`, this.methodTableName);
2415
+ return keyOnly ? JSON.stringify(key) : _propAccess(key);
2416
+ }
2417
+
2418
+ _readU30(bytes, i) {
2419
+ let val = 0, shift = 0, next = i;
2420
+ while (shift < 35 && next < bytes.length) {
2421
+ const b = bytes[next++];
2422
+ val |= (b & 0x7F) << shift;
2423
+ if (!(b & 0x80)) break;
2424
+ shift += 7;
2425
+ }
2426
+ return { val: val >>> 0, next };
2427
+ }
2428
+
2429
+ _readS24(bytes, i) {
2430
+ const v = bytes[i] | (bytes[i + 1] << 8) | (bytes[i + 2] << 16);
2431
+ return v >= 0x800000 ? v - 0x1000000 : v;
2432
+ }
2433
+ }
2434
+
2435
+ export { AVM2_RUNTIME_STUB, AVM2_RUNTIME_BOOTSTRAP } from '../../runtime/avm2-runtime.js';
2436
+
2437
+ // ---- Utilities ----
2438
+ function _safeIdent(name) {
2439
+ if (!name) return '_';
2440
+ let s = name.replace(/[^a-zA-Z0-9_$]/g, '_').replace(/^(\d)/, '_$1');
2441
+ if (JS_RESERVED.has(s)) s = '_' + s;
2442
+ return s || '_';
2443
+ }
2444
+
2445
+ function _safeClass(name) {
2446
+ if (!name) return '_Class';
2447
+ let s = name.replace(/[^a-zA-Z0-9_$]/g, '_').replace(/^(\d)/, '_$1');
2448
+ if (JS_RESERVED.has(s)) s = '_' + s;
2449
+ return s || '_Class';
2450
+ }
2451
+
2452
+ function _safeMethodName(name, isStatic) {
2453
+ if (!name) return '_';
2454
+ if (name === 'constructor' || (isStatic && name === 'prototype')) {
2455
+ return `_${name}`;
2456
+ }
2457
+ if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) return name;
2458
+ return `[${JSON.stringify(name)}]`;
2459
+ }
2460
+
2461
+ function _avm2PropertyName(multiname, fallback, abcId) {
2462
+ const name = multiname?.localName || fallback;
2463
+ if (!multiname || typeof multiname.nsKind !== 'number' || multiname.nsKind === 0 || multiname.nsKind === 0x16 || (multiname.nsKind === 0x08 && !multiname.ns)) return name;
2464
+ const nsKind = multiname.nsKind;
2465
+ let identity;
2466
+ if (nsKind === 0x18 || nsKind === 0x1A) {
2467
+ // A declaring class keeps its namespace identity across ABC blocks.
2468
+ // Protected overrides are linked separately using the class hierarchy.
2469
+ identity = multiname.ns
2470
+ ? `uri_${_hashAvm2Namespace(multiname.ns)}`
2471
+ : `abc_${String(abcId || 'local').replace(/^_avm2MethodTable_/, '')}_ns_${multiname.nsIndex ?? 0}`;
2472
+ } else if (nsKind === 0x05) {
2473
+ // Private namespace-pool indices are identities. Namespace indices can
2474
+ // repeat in a separate ABC, so include that ABC's unique block ID.
2475
+ const abcKey = String(abcId || 'local').replace(/^_avm2MethodTable_/, '');
2476
+ identity = `abc_${abcKey}_ns_${multiname.nsIndex ?? 0}`;
2477
+ } else {
2478
+ // Named custom/package-internal namespaces with the same kind and URI
2479
+ // represent the same namespace even when their pool indices differ.
2480
+ identity = `uri_${_hashAvm2Namespace(multiname.ns || '')}`;
2481
+ }
2482
+ return `__avm2ns_${nsKind}_${identity}_${name}`;
2483
+ }
2484
+
2485
+ function _hashAvm2Namespace(value) {
2486
+ let hash = 0x811c9dc5;
2487
+ for (let i = 0; i < value.length; i++) hash = Math.imul(hash ^ value.charCodeAt(i), 0x01000193);
2488
+ return (hash >>> 0).toString(16);
2489
+ }
2490
+
2491
+ function _avm2UsesNamespaceIdentity(multiname) {
2492
+ const kind = multiname?.nsKind;
2493
+ return Boolean(kind && kind !== 0x16 && (kind !== 0x08 || multiname.ns));
2494
+ }
2495
+
2496
+ function _avm2TypeTraitName(multiname, fallback, abcId) {
2497
+ if (_avm2UsesNamespaceIdentity(multiname)) {
2498
+ const kind = multiname.nsKind;
2499
+ const uri = multiname.ns || '';
2500
+ // Keep the full URI in definition keys so colliding property-key hashes
2501
+ // cannot make two types interchangeable. Anonymous protected and private
2502
+ // namespaces are identified by their ABC pool entries instead.
2503
+ const identity = kind === 0x05 || (!uri && (kind === 0x18 || kind === 0x1A))
2504
+ ? `abc:${abcId}:${multiname.nsIndex ?? 0}` : `uri:${uri.length}:${uri}`;
2505
+ return `__avm2type_${kind}_${identity}_${multiname.localName || fallback}`;
2506
+ }
2507
+ return multiname?.nsKind === 0x16 && multiname.ns ? `${multiname.ns}.${multiname.localName}` : fallback;
2508
+ }
2509
+
2510
+ function _avm2InterfaceTraits(traits, cp, abcId) {
2511
+ const members = new Map();
2512
+ for (const trait of traits) {
2513
+ if (trait.kind < 1 || trait.kind > 3) continue;
2514
+ const name = cp.multinames[trait.nameIndex];
2515
+ if (!name?.localName) continue;
2516
+ const key = _avm2PropertyName(name, name.localName, abcId);
2517
+ const publicKey = name.localName === 'constructor' ? '_constructor' : name.localName;
2518
+ const member = members.get(key) || [key, publicKey, 0];
2519
+ member[2] |= trait.kind === 3 ? 2 : 1;
2520
+ members.set(key, member);
2521
+ }
2522
+ return [...members.values()];
2523
+ }
2524
+
2525
+ /** Returns `.propName` for safe identifiers, `["propName"]` for others */
2526
+ function _propAccess(name) {
2527
+ if (!name) return '._';
2528
+ if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) return `.${name}`;
2529
+ return `[${JSON.stringify(name)}]`;
2530
+ }
2531
+
2532
+ function _simplifyCond(expr) {
2533
+ let s = expr.trim();
2534
+ while (s.startsWith('(') && s.endsWith(')')) {
2535
+ // Only strip outer parens if they match each other
2536
+ let depth = 0;
2537
+ let matches = true;
2538
+ for (let k = 0; k < s.length - 1; k++) {
2539
+ if (s[k] === '(') depth++;
2540
+ else if (s[k] === ')') depth--;
2541
+ if (depth === 0) { matches = false; break; }
2542
+ }
2543
+ if (matches) s = s.slice(1, -1).trim();
2544
+ else break;
2545
+ }
2546
+ return s;
2547
+ }
2548
+
2549
+ function _negateCond(expr) {
2550
+ const s = _simplifyCond(expr);
2551
+ if (s.startsWith('!')) {
2552
+ return _simplifyCond(s.slice(1));
2553
+ }
2554
+ return `!(${s})`;
2555
+ }
2556
+
2557
+ function indent(src, levels = 1) {
2558
+ const pad = ' '.repeat(levels);
2559
+ return src.split('\n').map(l => pad + l).join('\n');
2560
+ }