gofront 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +174 -403
  2. package/package.json +16 -19
  3. package/src/{codegen → backend/js}/expressions.js +265 -77
  4. package/src/{codegen → backend/js}/index.js +120 -89
  5. package/src/{codegen → backend/js}/runtime.js +102 -0
  6. package/src/{codegen → backend/js}/source-map.js +32 -0
  7. package/src/{codegen → backend/js}/statements.js +139 -64
  8. package/src/backend/js/stdlib/bits.js +32 -0
  9. package/src/{codegen → backend/js}/stdlib/errors.js +2 -2
  10. package/src/{codegen → backend/js}/stdlib/fmt.js +26 -8
  11. package/src/{codegen → backend/js}/stdlib/index.js +6 -0
  12. package/src/{codegen → backend/js}/stdlib/maps.js +1 -1
  13. package/src/{codegen → backend/js}/stdlib/path.js +2 -2
  14. package/src/backend/js/stdlib/shared.js +17 -0
  15. package/src/{codegen → backend/js}/stdlib/slices.js +1 -1
  16. package/src/{codegen → backend/js}/stdlib/sort.js +1 -1
  17. package/src/backend/js/stdlib/strconv.js +58 -0
  18. package/src/{codegen → backend/js}/stdlib/strings.js +4 -1
  19. package/src/{codegen → backend/js}/stdlib/testing.js +2 -2
  20. package/src/{codegen → backend/js}/stdlib/time.js +3 -3
  21. package/src/{codegen → backend/js}/templ.js +3 -3
  22. package/src/backend/wasm/boundary.js +1798 -0
  23. package/src/backend/wasm/emit-builtins.js +1103 -0
  24. package/src/backend/wasm/emit-exprs.js +1908 -0
  25. package/src/backend/wasm/emit-maps.js +1863 -0
  26. package/src/backend/wasm/emit-shared.js +519 -0
  27. package/src/backend/wasm/emit-stdlib.js +3006 -0
  28. package/src/backend/wasm/emit-stmts.js +2472 -0
  29. package/src/backend/wasm/emit.js +1376 -0
  30. package/src/backend/wasm/encode.js +937 -0
  31. package/src/backend/wasm/glue.js +144 -0
  32. package/src/backend/wasm/index.js +2790 -0
  33. package/src/backend/wasm/monomorph.js +711 -0
  34. package/src/backend/wasm/optimize.js +227 -0
  35. package/src/backend/wasm/types.js +544 -0
  36. package/src/backend/wasm/wat.js +302 -0
  37. package/src/cli-core.js +323 -75
  38. package/src/compiler.js +447 -14
  39. package/src/dev-server.js +56 -15
  40. package/src/index.js +99 -120
  41. package/src/lexer.js +18 -0
  42. package/src/lower/boxing.js +35 -0
  43. package/src/lower/captures.js +172 -0
  44. package/src/lower/embedding.js +30 -0
  45. package/src/lower/escape.js +164 -0
  46. package/src/lower/functions.js +302 -0
  47. package/src/lower/globals.js +316 -0
  48. package/src/lower/index.js +118 -0
  49. package/src/lower/ownership.js +137 -0
  50. package/src/lower/range.js +67 -0
  51. package/src/lower/walk.js +25 -0
  52. package/src/minifier.js +2 -0
  53. package/src/parser/index.js +8 -3
  54. package/src/resolver.js +3 -1
  55. package/src/test-runner.js +94 -20
  56. package/src/typechecker/assignability.js +42 -1
  57. package/src/typechecker/expressions.js +182 -3
  58. package/src/typechecker/index.js +261 -5
  59. package/src/typechecker/resolve.js +35 -6
  60. package/src/typechecker/stdlib/core.js +34 -19
  61. package/src/typechecker/stdlib/extended.js +18 -3
  62. package/src/typechecker/stdlib/shared.js +53 -0
  63. package/src/typechecker/stdlib.js +2 -0
  64. package/src/typechecker/types.js +259 -6
  65. package/src/vendor.js +2 -2
  66. package/src/codegen/stdlib/strconv.js +0 -33
  67. /package/src/{codegen → backend/js}/stdlib/builder.js +0 -0
  68. /package/src/{codegen → backend/js}/stdlib/bytes.js +0 -0
  69. /package/src/{codegen → backend/js}/stdlib/gom.js +0 -0
  70. /package/src/{codegen → backend/js}/stdlib/html.js +0 -0
  71. /package/src/{codegen → backend/js}/stdlib/io.js +0 -0
  72. /package/src/{codegen → backend/js}/stdlib/math.js +0 -0
  73. /package/src/{codegen → backend/js}/stdlib/os.js +0 -0
  74. /package/src/{codegen → backend/js}/stdlib/rand.js +0 -0
  75. /package/src/{codegen → backend/js}/stdlib/regexp.js +0 -0
  76. /package/src/{codegen → backend/js}/stdlib/unicode.js +0 -0
  77. /package/src/{codegen → backend/js}/stdlib/utf8.js +0 -0
@@ -0,0 +1,2472 @@
1
+ // src/backend/wasm/emit-stmts.js
2
+ // FunctionEmitter mixin: statement emission (decls, assignment, control flow, return).
3
+
4
+ import { isIntRangeType, isRangeFor } from "../../lower/range.js";
5
+ import {
6
+ getMapKeyValTypes,
7
+ isArrayType,
8
+ isFuncType,
9
+ isInterfaceType,
10
+ isMapType,
11
+ isNonEmptyInterface,
12
+ isPointerToStruct,
13
+ isSliceType,
14
+ isStringType,
15
+ isStructType,
16
+ } from "./types.js";
17
+
18
+ export class StmtsEmitter {
19
+ emitVarDecl(stmt) {
20
+ const decls = stmt.decls ?? stmt.specs ?? [stmt];
21
+ for (const spec of decls) {
22
+ const names = spec.names ?? (spec.name ? [spec.name] : []);
23
+ const values = spec.value ?? (spec.init ? [spec.init] : []);
24
+
25
+ for (let i = 0; i < names.length; i++) {
26
+ const name = names[i];
27
+ const rawType = spec.type ?? values[i]?._type;
28
+ const wType = this.toWasmType(rawType);
29
+ const localIdx = this.allocLocal(name, wType, rawType);
30
+ const localInfo = this.locals.get(name);
31
+ if (values?.[i]) {
32
+ const r = values[i];
33
+ this.emitExpr(r, wType);
34
+ this._emitCopyIfValueStruct(r, rawType, wType);
35
+ if (localInfo?.isBoxed) {
36
+ this.pushInstruction({
37
+ op: "struct.new",
38
+ typeIndex: localInfo.boxInfo.typeIndex,
39
+ });
40
+ }
41
+ this.pushInstruction({ op: "local.set", index: localIdx });
42
+ } else {
43
+ this.emitZeroValue(rawType, wType);
44
+ if (localInfo?.isBoxed) {
45
+ this.pushInstruction({
46
+ op: "struct.new",
47
+ typeIndex: localInfo.boxInfo.typeIndex,
48
+ });
49
+ }
50
+ this.pushInstruction({ op: "local.set", index: localIdx });
51
+ }
52
+ }
53
+ }
54
+ }
55
+
56
+ emitDefineStmt(stmt) {
57
+ const lhsNodes = Array.isArray(stmt.lhs) ? stmt.lhs : [stmt.lhs];
58
+ const rhsNodes = Array.isArray(stmt.rhs) ? stmt.rhs : [stmt.rhs];
59
+
60
+ if (
61
+ rhsNodes.length === 1 &&
62
+ lhsNodes.length === 2 &&
63
+ rhsNodes[0].kind === "TypeAssertExpr"
64
+ ) {
65
+ this._emitCommaOkTypeAssert(lhsNodes[0], lhsNodes[1], rhsNodes[0], true);
66
+ return;
67
+ }
68
+
69
+ if (
70
+ rhsNodes.length === 1 &&
71
+ lhsNodes.length === 2 &&
72
+ rhsNodes[0].kind === "IndexExpr" &&
73
+ isMapType(
74
+ rhsNodes[0].expr._type ?? this._resolveExprGoType(rhsNodes[0].expr),
75
+ this.mod.checker,
76
+ )
77
+ ) {
78
+ this._emitCommaOkMapIndex(lhsNodes[0], lhsNodes[1], rhsNodes[0], true);
79
+ return;
80
+ }
81
+
82
+ if (
83
+ rhsNodes.length === 1 &&
84
+ lhsNodes.length > 1 &&
85
+ rhsNodes[0]._type?.kind === "tuple"
86
+ ) {
87
+ this._emitTupleDefine(lhsNodes, rhsNodes[0]);
88
+ return;
89
+ }
90
+
91
+ for (let i = 0; i < lhsNodes.length; i++) {
92
+ this._emitDefineSingle(lhsNodes[i], rhsNodes[i]);
93
+ }
94
+ }
95
+
96
+ _emitDefineSingle(l, r) {
97
+ if (!r || l.kind !== "Ident") return;
98
+ if (l.name === "_") {
99
+ this.emitExpr(r);
100
+ this.pushInstruction("drop");
101
+ return;
102
+ }
103
+ const wType = this.toWasmType(r._type);
104
+ const idx = this.allocLocal(l.name, wType, r._type);
105
+ const localInfo = this.locals.get(l.name);
106
+ this.emitExpr(r, wType);
107
+ this._emitCopyIfValueStruct(r, r._type, wType);
108
+ if (localInfo?.isBoxed) {
109
+ this.pushInstruction({
110
+ op: "struct.new",
111
+ typeIndex: localInfo.boxInfo.typeIndex,
112
+ });
113
+ }
114
+ this.pushInstruction({ op: "local.set", index: idx });
115
+ }
116
+
117
+ _emitTupleDefine(lhsNodes, rhsNode) {
118
+ const tupleTypes = rhsNode._type.types;
119
+ const localIndices = [];
120
+ for (let i = 0; i < lhsNodes.length; i++) {
121
+ const l = lhsNodes[i];
122
+ const wType = this.toWasmType(tupleTypes[i]);
123
+ const idx =
124
+ l.kind === "Ident" && l.name !== "_"
125
+ ? this.allocLocal(l.name, wType, tupleTypes[i])
126
+ : null;
127
+ localIndices.push(idx);
128
+ }
129
+
130
+ this.emitExpr(rhsNode);
131
+
132
+ for (let i = lhsNodes.length - 1; i >= 0; i--) {
133
+ const idx = localIndices[i];
134
+ if (idx !== null) {
135
+ const localInfo = this.locals.get(lhsNodes[i].name);
136
+ if (localInfo?.isBoxed) {
137
+ this.pushInstruction({
138
+ op: "struct.new",
139
+ typeIndex: localInfo.boxInfo.typeIndex,
140
+ });
141
+ }
142
+ this.pushInstruction({ op: "local.set", index: idx });
143
+ } else {
144
+ this.pushInstruction("drop");
145
+ }
146
+ }
147
+ }
148
+
149
+ emitAssignStmt(stmt) {
150
+ const { lhs, rhs, op } = stmt;
151
+ if (op === ":=" || op === "=") {
152
+ this._emitAssign(lhs, rhs, op);
153
+ } else {
154
+ this._emitCompoundAssign(lhs, rhs, op);
155
+ }
156
+ }
157
+
158
+ _emitAssign(lhs, rhs, op) {
159
+ const lhsNodes = Array.isArray(lhs) ? lhs : [lhs];
160
+ const rhsNodes = Array.isArray(rhs) ? rhs : [rhs];
161
+
162
+ if (
163
+ rhsNodes.length === 1 &&
164
+ lhsNodes.length === 2 &&
165
+ rhsNodes[0].kind === "TypeAssertExpr"
166
+ ) {
167
+ this._emitCommaOkTypeAssert(
168
+ lhsNodes[0],
169
+ lhsNodes[1],
170
+ rhsNodes[0],
171
+ op === ":=",
172
+ );
173
+ return;
174
+ }
175
+
176
+ if (
177
+ rhsNodes.length === 1 &&
178
+ lhsNodes.length === 2 &&
179
+ rhsNodes[0].kind === "IndexExpr" &&
180
+ isMapType(
181
+ rhsNodes[0].expr._type ?? this._resolveExprGoType(rhsNodes[0].expr),
182
+ this.mod.checker,
183
+ )
184
+ ) {
185
+ this._emitCommaOkMapIndex(
186
+ lhsNodes[0],
187
+ lhsNodes[1],
188
+ rhsNodes[0],
189
+ op === ":=",
190
+ );
191
+ return;
192
+ }
193
+
194
+ if (
195
+ rhsNodes.length === 1 &&
196
+ lhsNodes.length > 1 &&
197
+ rhsNodes[0]._type?.kind === "tuple"
198
+ ) {
199
+ this._emitTupleAssign(lhsNodes, rhsNodes[0], op);
200
+ return;
201
+ }
202
+
203
+ for (let i = 0; i < lhsNodes.length; i++) {
204
+ this._emitAssignSingle(lhsNodes[i], rhsNodes[i], op);
205
+ }
206
+ }
207
+
208
+ _emitAssignSingle(l, r, op) {
209
+ if (!r) return;
210
+ if (l.kind === "Ident") {
211
+ if (l.name === "_") {
212
+ this.emitExpr(r);
213
+ this.pushInstruction("drop");
214
+ return;
215
+ }
216
+ let localInfo = this.resolveLocal(l.name);
217
+ if (!localInfo && op === ":=") {
218
+ const wType = this.toWasmType(r._type);
219
+ this.allocLocal(l.name, wType, r._type);
220
+ localInfo = this.locals.get(l.name);
221
+ }
222
+ if (localInfo) {
223
+ if (localInfo.isBoxed) {
224
+ this.pushInstruction({ op: "local.get", index: localInfo.index });
225
+ this.emitExpr(r, localInfo.boxInfo.wType);
226
+ this.pushInstruction({
227
+ op: "struct.set",
228
+ typeIndex: localInfo.boxInfo.typeIndex,
229
+ fieldIndex: 0,
230
+ });
231
+ return;
232
+ }
233
+ this.emitExpr(r, localInfo.type);
234
+ this._emitCopyIfValueStruct(r, localInfo.goType, localInfo.type);
235
+ this.pushInstruction({ op: "local.set", index: localInfo.index });
236
+ } else {
237
+ const globalInfo = this.mod.resolveGlobal(l.name);
238
+ if (globalInfo) {
239
+ this.emitExpr(r, globalInfo.type);
240
+ this._emitCopyIfValueStruct(r, globalInfo.goType, globalInfo.type);
241
+ this.pushInstruction({
242
+ op: "global.set",
243
+ index: globalInfo.index,
244
+ });
245
+ }
246
+ }
247
+ return;
248
+ }
249
+
250
+ if (l.kind === "SelectorExpr") {
251
+ const structInfo = this._resolveStructInfo(l.expr);
252
+ if (!structInfo) {
253
+ throw new Error(
254
+ `Cannot resolve struct for selector assignment: ${l.field}`,
255
+ );
256
+ }
257
+ const path = this._resolveFieldPath(structInfo, l.field);
258
+ if (!path) {
259
+ throw new Error(
260
+ `Unknown field '${l.field}' on struct '${structInfo.name}'`,
261
+ );
262
+ }
263
+ const lastStep = path[path.length - 1];
264
+ const baseWType = this.toWasmType(l.expr._type);
265
+
266
+ this.emitExpr(l.expr, baseWType);
267
+ for (let i = 0; i < path.length - 1; i++) {
268
+ const step = path[i];
269
+ this.pushInstruction({
270
+ op: "struct.get",
271
+ typeIndex: step.structInfo.typeIndex,
272
+ fieldIndex: step.fieldIndex,
273
+ });
274
+ }
275
+ this.emitExpr(r, lastStep.field.wType);
276
+ this._emitCopyIfValueStruct(
277
+ r,
278
+ lastStep.field.goType,
279
+ lastStep.field.wType,
280
+ );
281
+ this.pushInstruction({
282
+ op: "struct.set",
283
+ typeIndex: lastStep.structInfo.typeIndex,
284
+ fieldIndex: lastStep.fieldIndex,
285
+ });
286
+ return;
287
+ }
288
+
289
+ if (l.kind === "UnaryExpr" && l.op === "*") {
290
+ const structInfo = this._resolveStructInfo(l.operand);
291
+ if (structInfo) {
292
+ const baseWType = this.toWasmType(l.operand._type);
293
+ const tmpL = this.acquireTemp(baseWType);
294
+ const tmpR = this.acquireTemp(baseWType);
295
+ this.emitExpr(l.operand, baseWType);
296
+ this.pushInstruction({ op: "local.set", index: tmpL });
297
+ this.emitExpr(r, baseWType);
298
+ this.pushInstruction({ op: "local.set", index: tmpR });
299
+ for (let i = 0; i < structInfo.fields.length; i++) {
300
+ this.pushInstruction({ op: "local.get", index: tmpL });
301
+ this.pushInstruction({ op: "local.get", index: tmpR });
302
+ this.pushInstruction({
303
+ op: "struct.get",
304
+ typeIndex: structInfo.typeIndex,
305
+ fieldIndex: i,
306
+ });
307
+ this.pushInstruction({
308
+ op: "struct.set",
309
+ typeIndex: structInfo.typeIndex,
310
+ fieldIndex: i,
311
+ });
312
+ }
313
+ this.releaseTemp(tmpR, baseWType);
314
+ this.releaseTemp(tmpL, baseWType);
315
+ return;
316
+ }
317
+ const box = this.mod.getBoxType(l.operand._type?.base ?? l.operand._type);
318
+ const baseWType = {
319
+ kind: "ref",
320
+ nullable: true,
321
+ typeIndex: box.typeIndex,
322
+ };
323
+ const boxTmp = this.acquireTemp(baseWType);
324
+ this.emitExpr(l.operand, baseWType);
325
+ this.pushInstruction({ op: "local.set", index: boxTmp });
326
+ this.pushInstruction({ op: "local.get", index: boxTmp });
327
+ this.emitExpr(r, box.wType);
328
+ this.pushInstruction({
329
+ op: "struct.set",
330
+ typeIndex: box.typeIndex,
331
+ fieldIndex: 0,
332
+ });
333
+ this.releaseTemp(boxTmp, baseWType);
334
+ return;
335
+ }
336
+
337
+ if (l.kind === "IndexExpr") {
338
+ const baseNode = l.expr;
339
+ const baseType = baseNode._type ?? this._resolveExprGoType(baseNode);
340
+ if (isMapType(baseType, this.mod.checker)) {
341
+ const { keyType, valType } = getMapKeyValTypes(
342
+ baseType,
343
+ this.mod.checker,
344
+ );
345
+ const mapInfo = this.mod.getMapType(keyType, valType);
346
+ this.emitExpr(baseNode, mapInfo.wType);
347
+ this.emitExpr(l.index, mapInfo.keyWType);
348
+ this.emitExpr(r, mapInfo.valWType);
349
+ this._emitCopyIfValueStruct(r, valType, mapInfo.valWType);
350
+ this.pushInstruction({
351
+ op: "call",
352
+ funcIndex: this.mod.resolveFuncIndex(mapInfo.setFuncName),
353
+ });
354
+ return;
355
+ }
356
+
357
+ const sharedInfo = this._sharedInfo(baseType);
358
+ if (sharedInfo) {
359
+ this.emitSharedIndexAssign(l, r, sharedInfo);
360
+ return;
361
+ }
362
+
363
+ const isSlice = isSliceType(baseType, this.mod.checker);
364
+ const isPtrToArr =
365
+ baseType?.kind === "pointer" &&
366
+ isArrayType(baseType.base, this.mod.checker);
367
+
368
+ const elemGoType = isSlice
369
+ ? baseType.elem
370
+ : isPtrToArr
371
+ ? baseType.base.elem
372
+ : baseType.elem;
373
+ const arrInfo = this.mod.getArrayType(elemGoType);
374
+ const sliceInfo = isSlice ? this.mod.getSliceType(elemGoType) : null;
375
+
376
+ this._emitElemAddr(baseNode, l.index, sliceInfo, arrInfo);
377
+
378
+ this.emitExpr(r, arrInfo.elemWType);
379
+ this._emitCopyIfValueStruct(r, elemGoType, arrInfo.elemWType);
380
+
381
+ this.pushInstruction({
382
+ op: "array.set",
383
+ typeIndex: arrInfo.typeIndex,
384
+ });
385
+ return;
386
+ }
387
+ }
388
+
389
+ _emitTupleAssign(lhsNodes, rhsNode, op) {
390
+ const tupleTypes = rhsNode._type.types;
391
+ const dests = [];
392
+ for (let i = 0; i < lhsNodes.length; i++) {
393
+ const l = lhsNodes[i];
394
+ if (l.kind === "Ident" && l.name !== "_") {
395
+ let localInfo = this.resolveLocal(l.name);
396
+ if (!localInfo && op === ":=") {
397
+ const wType = this.toWasmType(tupleTypes[i]);
398
+ this.allocLocal(l.name, wType, tupleTypes[i]);
399
+ localInfo = this.locals.get(l.name);
400
+ }
401
+ dests.push(localInfo ?? this.mod.resolveGlobal(l.name) ?? null);
402
+ } else {
403
+ dests.push(null);
404
+ }
405
+ }
406
+
407
+ this.emitExpr(rhsNode);
408
+
409
+ for (let i = lhsNodes.length - 1; i >= 0; i--) {
410
+ const dest = dests[i];
411
+ if (dest && typeof dest.index === "number") {
412
+ if (dest.isBoxed) {
413
+ const valTmp = this.acquireTemp(dest.boxInfo.wType);
414
+ this.pushInstruction({ op: "local.set", index: valTmp });
415
+ this.pushInstruction({ op: "local.get", index: dest.index });
416
+ this.pushInstruction({ op: "local.get", index: valTmp });
417
+ this.pushInstruction({
418
+ op: "struct.set",
419
+ typeIndex: dest.boxInfo.typeIndex,
420
+ fieldIndex: 0,
421
+ });
422
+ this.releaseTemp(valTmp, dest.boxInfo.wType);
423
+ } else if (this.resolveLocal(lhsNodes[i].name)) {
424
+ this.pushInstruction({ op: "local.set", index: dest.index });
425
+ } else {
426
+ this.pushInstruction({ op: "global.set", index: dest.index });
427
+ }
428
+ } else {
429
+ this.pushInstruction("drop");
430
+ }
431
+ }
432
+ }
433
+
434
+ _emitCommaOkTypeAssert(valLhs, okLhs, assertExpr, isDefine) {
435
+ const targetGoType = assertExpr._type ?? assertExpr.type;
436
+ const targetWType = this.toWasmType(targetGoType);
437
+ const anyTmp = this.acquireTemp("anyref");
438
+ this.emitExpr(assertExpr.expr, "anyref");
439
+ this.pushInstruction({ op: "local.set", index: anyTmp });
440
+
441
+ const okTmp = this.acquireTemp("i32");
442
+ this.pushInstruction({ op: "local.get", index: anyTmp });
443
+ this._emitTypeTest(targetGoType);
444
+ this.pushInstruction({ op: "local.set", index: okTmp });
445
+
446
+ const valTmp = this.acquireTemp(targetWType);
447
+ this.pushInstruction({ op: "local.get", index: okTmp });
448
+ this.pushInstruction({ op: "if", blockType: targetWType });
449
+ this.pushInstruction({ op: "local.get", index: anyTmp });
450
+ this._emitTypeCast(targetGoType, targetWType);
451
+ this.pushInstruction("else");
452
+ this.emitZeroValue(targetGoType, targetWType);
453
+ this.pushInstruction("end");
454
+ this.pushInstruction({ op: "local.set", index: valTmp });
455
+
456
+ this.releaseTemp(anyTmp, "anyref");
457
+
458
+ // Assign val to valLhs
459
+ if (isDefine && valLhs.kind === "Ident" && valLhs.name !== "_") {
460
+ const idx = this.allocLocal(valLhs.name, targetWType, targetGoType);
461
+ this.pushInstruction({ op: "local.get", index: valTmp });
462
+ this.pushInstruction({ op: "local.set", index: idx });
463
+ } else if (valLhs.kind === "Ident" && valLhs.name !== "_") {
464
+ const local = this.resolveLocal(valLhs.name);
465
+ this.pushInstruction({ op: "local.get", index: valTmp });
466
+ if (local) {
467
+ this.pushInstruction({ op: "local.set", index: local.index });
468
+ } else {
469
+ const global = this.mod.resolveGlobal(valLhs.name);
470
+ this.pushInstruction({ op: "global.set", index: global.index });
471
+ }
472
+ }
473
+
474
+ // Assign ok to okLhs
475
+ if (isDefine && okLhs.kind === "Ident" && okLhs.name !== "_") {
476
+ const idx = this.allocLocal(okLhs.name, "i32", {
477
+ kind: "basic",
478
+ name: "bool",
479
+ });
480
+ this.pushInstruction({ op: "local.get", index: okTmp });
481
+ this.pushInstruction({ op: "local.set", index: idx });
482
+ } else if (okLhs.kind === "Ident" && okLhs.name !== "_") {
483
+ const local = this.resolveLocal(okLhs.name);
484
+ this.pushInstruction({ op: "local.get", index: okTmp });
485
+ if (local) {
486
+ this.pushInstruction({ op: "local.set", index: local.index });
487
+ } else {
488
+ const global = this.mod.resolveGlobal(okLhs.name);
489
+ this.pushInstruction({ op: "global.set", index: global.index });
490
+ }
491
+ }
492
+
493
+ this.releaseTemp(valTmp, targetWType);
494
+ this.releaseTemp(okTmp, "i32");
495
+ }
496
+
497
+ _emitCommaOkMapIndex(valLhs, okLhs, indexExpr, isDefine) {
498
+ const baseNode = indexExpr.expr;
499
+ const baseType = baseNode._type ?? this._resolveExprGoType(baseNode);
500
+ const { keyType, valType } = getMapKeyValTypes(baseType, this.mod.checker);
501
+ const mapInfo = this.mod.getMapType(keyType, valType);
502
+
503
+ this.emitExpr(baseNode, mapInfo.wType);
504
+ this.emitExpr(indexExpr.index, mapInfo.keyWType);
505
+ this.pushInstruction({
506
+ op: "call",
507
+ funcIndex: this.mod.resolveFuncIndex(mapInfo.getOkFuncName),
508
+ });
509
+
510
+ const okTmp = this.acquireTemp("i32");
511
+ const valTmp = this.acquireTemp(mapInfo.valWType);
512
+ this.pushInstruction({ op: "local.set", index: okTmp });
513
+ this.pushInstruction({ op: "local.set", index: valTmp });
514
+
515
+ // Assign val to valLhs
516
+ if (isDefine && valLhs.kind === "Ident" && valLhs.name !== "_") {
517
+ const idx = this.allocLocal(valLhs.name, mapInfo.valWType, valType);
518
+ const local = this.locals.get(valLhs.name);
519
+ if (local?.isBoxed) {
520
+ this.pushInstruction({ op: "local.get", index: valTmp });
521
+ this.pushInstruction({
522
+ op: "struct.new",
523
+ typeIndex: local.boxInfo.typeIndex,
524
+ });
525
+ this.pushInstruction({ op: "local.set", index: idx });
526
+ } else {
527
+ this.pushInstruction({ op: "local.get", index: valTmp });
528
+ this.pushInstruction({ op: "local.set", index: idx });
529
+ }
530
+ } else if (valLhs.kind === "Ident" && valLhs.name !== "_") {
531
+ const local = this.resolveLocal(valLhs.name);
532
+ if (local) {
533
+ if (local.isBoxed) {
534
+ this.pushInstruction({ op: "local.get", index: local.index });
535
+ this.pushInstruction({ op: "local.get", index: valTmp });
536
+ this.pushInstruction({
537
+ op: "struct.set",
538
+ typeIndex: local.boxInfo.typeIndex,
539
+ fieldIndex: 0,
540
+ });
541
+ } else {
542
+ this.pushInstruction({ op: "local.get", index: valTmp });
543
+ this.pushInstruction({ op: "local.set", index: local.index });
544
+ }
545
+ } else {
546
+ const global = this.mod.resolveGlobal(valLhs.name);
547
+ this.pushInstruction({ op: "local.get", index: valTmp });
548
+ this.pushInstruction({ op: "global.set", index: global.index });
549
+ }
550
+ }
551
+
552
+ // Assign ok to okLhs
553
+ if (isDefine && okLhs.kind === "Ident" && okLhs.name !== "_") {
554
+ const idx = this.allocLocal(okLhs.name, "i32", {
555
+ kind: "basic",
556
+ name: "bool",
557
+ });
558
+ const local = this.locals.get(okLhs.name);
559
+ if (local?.isBoxed) {
560
+ this.pushInstruction({ op: "local.get", index: okTmp });
561
+ this.pushInstruction({
562
+ op: "struct.new",
563
+ typeIndex: local.boxInfo.typeIndex,
564
+ });
565
+ this.pushInstruction({ op: "local.set", index: idx });
566
+ } else {
567
+ this.pushInstruction({ op: "local.get", index: okTmp });
568
+ this.pushInstruction({ op: "local.set", index: idx });
569
+ }
570
+ } else if (okLhs.kind === "Ident" && okLhs.name !== "_") {
571
+ const local = this.resolveLocal(okLhs.name);
572
+ if (local) {
573
+ if (local.isBoxed) {
574
+ this.pushInstruction({ op: "local.get", index: local.index });
575
+ this.pushInstruction({ op: "local.get", index: okTmp });
576
+ this.pushInstruction({
577
+ op: "struct.set",
578
+ typeIndex: local.boxInfo.typeIndex,
579
+ fieldIndex: 0,
580
+ });
581
+ } else {
582
+ this.pushInstruction({ op: "local.get", index: okTmp });
583
+ this.pushInstruction({ op: "local.set", index: local.index });
584
+ }
585
+ } else {
586
+ const global = this.mod.resolveGlobal(okLhs.name);
587
+ this.pushInstruction({ op: "local.get", index: okTmp });
588
+ this.pushInstruction({ op: "global.set", index: global.index });
589
+ }
590
+ }
591
+
592
+ this.releaseTemp(valTmp, mapInfo.valWType);
593
+ this.releaseTemp(okTmp, "i32");
594
+ }
595
+
596
+ _structNameOf(goType) {
597
+ if (!goType) return null;
598
+ if (goType.kind === "PointerType" || goType.kind === "pointer")
599
+ return this._structNameOf(goType.base);
600
+ if (goType.kind === "StarExpr")
601
+ return this._structNameOf(goType.expr ?? goType.operand);
602
+ return goType.name ?? null;
603
+ }
604
+
605
+ _emitTypeTest(targetGoType) {
606
+ if (!targetGoType) {
607
+ this.pushInstruction("drop");
608
+ this.pushInstruction({ op: "i32.const", value: 1 });
609
+ return;
610
+ }
611
+
612
+ if (targetGoType.name === "nil" || targetGoType.kind === "nil") {
613
+ this.pushInstruction("ref.is_null");
614
+ return;
615
+ }
616
+
617
+ if (targetGoType.name === "any" || targetGoType.name === "interface{}") {
618
+ this.pushInstruction("ref.is_null");
619
+ this.pushInstruction("i32.eqz");
620
+ return;
621
+ }
622
+
623
+ if (isNonEmptyInterface(targetGoType, this.mod.checker)) {
624
+ const candidates = this.mod.getTypesImplementingInterface(targetGoType);
625
+ if (candidates.length === 0) {
626
+ this.pushInstruction("drop");
627
+ this.pushInstruction({ op: "i32.const", value: 0 });
628
+ return;
629
+ }
630
+ const anyTmp = this.acquireTemp("anyref");
631
+ this.pushInstruction({ op: "local.set", index: anyTmp });
632
+
633
+ this.pushInstruction({ op: "local.get", index: anyTmp });
634
+ this.pushInstruction("ref.is_null");
635
+ this.pushInstruction("i32.eqz");
636
+
637
+ for (let i = 0; i < candidates.length; i++) {
638
+ this.pushInstruction({ op: "local.get", index: anyTmp });
639
+ this.pushInstruction({
640
+ op: "ref.test",
641
+ typeIndex: candidates[i].typeIndex,
642
+ });
643
+ if (i > 0) {
644
+ this.pushInstruction("i32.or");
645
+ }
646
+ }
647
+ this.pushInstruction("i32.and");
648
+ this.releaseTemp(anyTmp, "anyref");
649
+ return;
650
+ }
651
+
652
+ if (isStringType(targetGoType, this.mod.checker)) {
653
+ const isStrIdx = this.mod.getIsStringImportIndex();
654
+ this.pushInstruction({ op: "call", funcIndex: isStrIdx });
655
+ return;
656
+ }
657
+
658
+ if (isFuncType(targetGoType, this.mod.checker)) {
659
+ const closureInfo = this.mod.getClosureType(targetGoType);
660
+ this.pushInstruction({
661
+ op: "ref.test",
662
+ typeIndex: closureInfo.typeIndex,
663
+ });
664
+ return;
665
+ }
666
+
667
+ // `*T` lives in `any` as the bare struct ref; a `T` value as a boxed
668
+ // clone (see emitExpr). Fall through to the scalar box for values.
669
+ if (isPointerToStruct(targetGoType, this.mod.checker, this.mod)) {
670
+ const sInfo = this.mod.getStructType(this._structNameOf(targetGoType));
671
+ if (sInfo) {
672
+ this.pushInstruction({ op: "ref.test", typeIndex: sInfo.typeIndex });
673
+ return;
674
+ }
675
+ }
676
+
677
+ if (isSliceType(targetGoType, this.mod.checker)) {
678
+ const elem = this._getSliceElemType(targetGoType);
679
+ const sInfo = this.mod.getSliceType(elem);
680
+ if (sInfo) {
681
+ this.pushInstruction({ op: "ref.test", typeIndex: sInfo.typeIndex });
682
+ return;
683
+ }
684
+ }
685
+
686
+ if (isArrayType(targetGoType, this.mod.checker)) {
687
+ const elem = this._getArrayElemType(targetGoType);
688
+ const aInfo = this.mod.getArrayType(elem);
689
+ if (aInfo) {
690
+ this.pushInstruction({ op: "ref.test", typeIndex: aInfo.typeIndex });
691
+ return;
692
+ }
693
+ }
694
+
695
+ // Scalar types
696
+ const box = this.mod.getBoxType(targetGoType);
697
+ if (box) {
698
+ this.pushInstruction({ op: "ref.test", typeIndex: box.typeIndex });
699
+ return;
700
+ }
701
+
702
+ this.pushInstruction("drop");
703
+ this.pushInstruction({ op: "i32.const", value: 1 });
704
+ }
705
+
706
+ _emitTypeCast(targetGoType, targetWType) {
707
+ if (isInterfaceType(targetGoType, this.mod.checker)) {
708
+ return;
709
+ }
710
+
711
+ if (isStringType(targetGoType, this.mod.checker)) {
712
+ this.pushInstruction("extern.convert_any");
713
+ return;
714
+ }
715
+
716
+ if (isFuncType(targetGoType, this.mod.checker)) {
717
+ const closureInfo = this.mod.getClosureType(targetGoType);
718
+ this.pushInstruction({
719
+ op: "ref.cast_null",
720
+ typeIndex: closureInfo.typeIndex,
721
+ });
722
+ return;
723
+ }
724
+
725
+ if (isPointerToStruct(targetGoType, this.mod.checker, this.mod)) {
726
+ const sInfo = this.mod.getStructType(this._structNameOf(targetGoType));
727
+ if (sInfo) {
728
+ this.pushInstruction({
729
+ op: "ref.cast_null",
730
+ typeIndex: sInfo.typeIndex,
731
+ });
732
+ return;
733
+ }
734
+ }
735
+ if (isStructType(targetGoType, this.mod.checker, this.mod)) {
736
+ const sInfo = this.mod.getStructType(this._structNameOf(targetGoType));
737
+ const box = this.mod.getBoxType(targetGoType);
738
+ if (sInfo && box) {
739
+ this.pushInstruction({
740
+ op: "ref.cast_null",
741
+ typeIndex: box.typeIndex,
742
+ });
743
+ this.pushInstruction({
744
+ op: "struct.get",
745
+ typeIndex: box.typeIndex,
746
+ fieldIndex: 0,
747
+ });
748
+ this.emitCloneStruct(sInfo, targetWType);
749
+ return;
750
+ }
751
+ }
752
+
753
+ if (isSliceType(targetGoType, this.mod.checker)) {
754
+ const elem = this._getSliceElemType(targetGoType);
755
+ const sInfo = this.mod.getSliceType(elem);
756
+ if (sInfo) {
757
+ this.pushInstruction({
758
+ op: "ref.cast_null",
759
+ typeIndex: sInfo.typeIndex,
760
+ });
761
+ return;
762
+ }
763
+ }
764
+
765
+ if (isArrayType(targetGoType, this.mod.checker)) {
766
+ const elem = this._getArrayElemType(targetGoType);
767
+ const aInfo = this.mod.getArrayType(elem);
768
+ if (aInfo) {
769
+ this.pushInstruction({
770
+ op: "ref.cast_null",
771
+ typeIndex: aInfo.typeIndex,
772
+ });
773
+ return;
774
+ }
775
+ }
776
+
777
+ // Scalar types
778
+ const box = this.mod.getBoxType(targetGoType);
779
+ if (box) {
780
+ this.pushInstruction({
781
+ op: "ref.cast_null",
782
+ typeIndex: box.typeIndex,
783
+ });
784
+ this.pushInstruction({
785
+ op: "struct.get",
786
+ typeIndex: box.typeIndex,
787
+ fieldIndex: 0,
788
+ });
789
+ return;
790
+ }
791
+ }
792
+
793
+ _emitCompoundAssign(lhs, rhs, op) {
794
+ const baseOp = op.slice(0, -1);
795
+ const l = Array.isArray(lhs) ? lhs[0] : lhs;
796
+ const r = Array.isArray(rhs) ? rhs[0] : rhs;
797
+
798
+ if (l.kind === "SelectorExpr") {
799
+ const structInfo = this._resolveStructInfo(l.expr);
800
+ if (!structInfo) {
801
+ throw new Error(
802
+ `Cannot resolve struct for compound selector: ${l.field}`,
803
+ );
804
+ }
805
+ const path = this._resolveFieldPath(structInfo, l.field);
806
+ if (!path) {
807
+ throw new Error(
808
+ `Unknown field '${l.field}' on struct '${structInfo.name}'`,
809
+ );
810
+ }
811
+ const lastStep = path[path.length - 1];
812
+ const targetType = lastStep.field.wType;
813
+ const baseWType = this.toWasmType(l.expr._type);
814
+
815
+ const baseTmp = this.acquireTemp(baseWType);
816
+ this.emitExpr(l.expr, baseWType);
817
+ for (let i = 0; i < path.length - 1; i++) {
818
+ const step = path[i];
819
+ this.pushInstruction({
820
+ op: "struct.get",
821
+ typeIndex: step.structInfo.typeIndex,
822
+ fieldIndex: step.fieldIndex,
823
+ });
824
+ }
825
+ this.pushInstruction({ op: "local.set", index: baseTmp });
826
+
827
+ this.pushInstruction({ op: "local.get", index: baseTmp });
828
+
829
+ this.pushInstruction({ op: "local.get", index: baseTmp });
830
+ this.pushInstruction({
831
+ op: "struct.get",
832
+ typeIndex: lastStep.structInfo.typeIndex,
833
+ fieldIndex: lastStep.fieldIndex,
834
+ });
835
+ this.emitExpr(r, targetType);
836
+ this.emitBinaryOp(baseOp, targetType, l._type);
837
+
838
+ this.pushInstruction({
839
+ op: "struct.set",
840
+ typeIndex: lastStep.structInfo.typeIndex,
841
+ fieldIndex: lastStep.fieldIndex,
842
+ });
843
+ this.releaseTemp(baseTmp, baseWType);
844
+ return;
845
+ }
846
+
847
+ if (l.kind === "IndexExpr") {
848
+ const baseNode = l.expr;
849
+ const baseType = baseNode._type ?? this._resolveExprGoType(baseNode);
850
+ if (isMapType(baseType, this.mod.checker)) {
851
+ const { keyType, valType } = getMapKeyValTypes(
852
+ baseType,
853
+ this.mod.checker,
854
+ );
855
+ const mapInfo = this.mod.getMapType(keyType, valType);
856
+ const mTmp = this.acquireTemp(mapInfo.wType);
857
+ const kTmp = this.acquireTemp(mapInfo.keyWType);
858
+ this.emitExpr(baseNode, mapInfo.wType);
859
+ this.pushInstruction({ op: "local.set", index: mTmp });
860
+ this.emitExpr(l.index, mapInfo.keyWType);
861
+ this.pushInstruction({ op: "local.set", index: kTmp });
862
+
863
+ this.pushInstruction({ op: "local.get", index: mTmp });
864
+ this.pushInstruction({ op: "local.get", index: kTmp });
865
+
866
+ this.pushInstruction({ op: "local.get", index: mTmp });
867
+ this.pushInstruction({ op: "local.get", index: kTmp });
868
+ this.pushInstruction({
869
+ op: "call",
870
+ funcIndex: this.mod.resolveFuncIndex(mapInfo.getFuncName),
871
+ });
872
+
873
+ this.emitExpr(r, mapInfo.valWType);
874
+ this.emitBinaryOp(baseOp, mapInfo.valWType, valType);
875
+
876
+ this.pushInstruction({
877
+ op: "call",
878
+ funcIndex: this.mod.resolveFuncIndex(mapInfo.setFuncName),
879
+ });
880
+
881
+ this.releaseTemp(kTmp, mapInfo.keyWType);
882
+ this.releaseTemp(mTmp, mapInfo.wType);
883
+ return;
884
+ }
885
+
886
+ const sharedInfo = this._sharedInfo(baseType);
887
+ if (sharedInfo) {
888
+ this.emitSharedIndexUpdate(l, sharedInfo, (elemW, elemGoType) => {
889
+ this.emitExpr(r, elemW);
890
+ this.emitBinaryOp(baseOp, elemW, elemGoType);
891
+ });
892
+ return;
893
+ }
894
+
895
+ const isSlice = isSliceType(baseType, this.mod.checker);
896
+ const isPtrToArr =
897
+ baseType?.kind === "pointer" &&
898
+ isArrayType(baseType.base, this.mod.checker);
899
+
900
+ const elemGoType = isSlice
901
+ ? baseType.elem
902
+ : isPtrToArr
903
+ ? baseType.base.elem
904
+ : baseType.elem;
905
+ const arrInfo = this.mod.getArrayType(elemGoType);
906
+ const sliceInfo = isSlice ? this.mod.getSliceType(elemGoType) : null;
907
+ const targetType = arrInfo.elemWType;
908
+ const arrWType = {
909
+ kind: "ref",
910
+ nullable: true,
911
+ typeIndex: arrInfo.typeIndex,
912
+ };
913
+
914
+ this._emitElemAddr(baseNode, l.index, sliceInfo, arrInfo);
915
+ const arrTmp = this.acquireTemp(arrWType);
916
+ const targetIdxTmp = this.acquireTemp("i32");
917
+ this.pushInstruction({ op: "local.set", index: targetIdxTmp });
918
+ this.pushInstruction({ op: "local.tee", index: arrTmp });
919
+ this.pushInstruction({ op: "local.get", index: targetIdxTmp });
920
+
921
+ this.pushInstruction({ op: "local.get", index: arrTmp });
922
+ this.pushInstruction({ op: "local.get", index: targetIdxTmp });
923
+ this.pushInstruction({
924
+ op: "array.get",
925
+ typeIndex: arrInfo.typeIndex,
926
+ });
927
+
928
+ this.emitExpr(r, targetType);
929
+ this.emitBinaryOp(baseOp, targetType, elemGoType);
930
+
931
+ this.pushInstruction({
932
+ op: "array.set",
933
+ typeIndex: arrInfo.typeIndex,
934
+ });
935
+
936
+ this.releaseTemp(targetIdxTmp, "i32");
937
+ this.releaseTemp(arrTmp, arrWType);
938
+ return;
939
+ }
940
+
941
+ if (l.kind !== "Ident") return;
942
+
943
+ const localInfo = this.resolveLocal(l.name);
944
+ const globalInfo = !localInfo ? this.mod.resolveGlobal(l.name) : null;
945
+ if (!localInfo && !globalInfo) return;
946
+
947
+ if (localInfo?.isBoxed) {
948
+ const boxInfo = localInfo.boxInfo;
949
+ const targetType = boxInfo.wType;
950
+ if (baseOp === "/" || baseOp === "%") {
951
+ const resTmp = this.acquireTemp(targetType);
952
+ this.emitDivRem(baseOp, l, r, targetType);
953
+ this.pushInstruction({ op: "local.set", index: resTmp });
954
+ this.pushInstruction({ op: "local.get", index: localInfo.index });
955
+ this.pushInstruction({ op: "local.get", index: resTmp });
956
+ this.pushInstruction({
957
+ op: "struct.set",
958
+ typeIndex: boxInfo.typeIndex,
959
+ fieldIndex: 0,
960
+ });
961
+ this.releaseTemp(resTmp, targetType);
962
+ } else if (baseOp === "<<" || baseOp === ">>") {
963
+ const resTmp = this.acquireTemp(targetType);
964
+ this.emitShift(baseOp, l, r, targetType);
965
+ this.pushInstruction({ op: "local.set", index: resTmp });
966
+ this.pushInstruction({ op: "local.get", index: localInfo.index });
967
+ this.pushInstruction({ op: "local.get", index: resTmp });
968
+ this.pushInstruction({
969
+ op: "struct.set",
970
+ typeIndex: boxInfo.typeIndex,
971
+ fieldIndex: 0,
972
+ });
973
+ this.releaseTemp(resTmp, targetType);
974
+ } else {
975
+ this.pushInstruction({ op: "local.get", index: localInfo.index });
976
+ this.pushInstruction({ op: "local.get", index: localInfo.index });
977
+ this.pushInstruction({
978
+ op: "struct.get",
979
+ typeIndex: boxInfo.typeIndex,
980
+ fieldIndex: 0,
981
+ });
982
+ this.emitExpr(r, targetType);
983
+ this.emitBinaryOp(baseOp, targetType, l._type);
984
+ this.pushInstruction({
985
+ op: "struct.set",
986
+ typeIndex: boxInfo.typeIndex,
987
+ fieldIndex: 0,
988
+ });
989
+ }
990
+ return;
991
+ }
992
+
993
+ const targetType = localInfo ? localInfo.type : globalInfo.type;
994
+
995
+ if (baseOp === "/" || baseOp === "%") {
996
+ this.emitDivRem(baseOp, l, r, targetType);
997
+ } else if (baseOp === "<<" || baseOp === ">>") {
998
+ this.emitShift(baseOp, l, r, targetType);
999
+ } else {
1000
+ if (localInfo) {
1001
+ this.pushInstruction({ op: "local.get", index: localInfo.index });
1002
+ } else {
1003
+ this.pushInstruction({ op: "global.get", index: globalInfo.index });
1004
+ }
1005
+ this.emitExpr(r, targetType);
1006
+ this.emitBinaryOp(baseOp, targetType, l._type);
1007
+ }
1008
+
1009
+ if (localInfo) {
1010
+ this.pushInstruction({ op: "local.set", index: localInfo.index });
1011
+ } else {
1012
+ this.pushInstruction({ op: "global.set", index: globalInfo.index });
1013
+ }
1014
+ }
1015
+
1016
+ emitIncDecStmt(stmt) {
1017
+ const { expr, op } = stmt;
1018
+
1019
+ if (expr.kind === "SelectorExpr") {
1020
+ const structInfo = this._resolveStructInfo(expr.expr);
1021
+ if (!structInfo) return;
1022
+ const path = this._resolveFieldPath(structInfo, expr.field);
1023
+ if (!path) return;
1024
+ const lastStep = path[path.length - 1];
1025
+ const targetType = lastStep.field.wType;
1026
+ const baseWType = this.toWasmType(expr.expr._type);
1027
+
1028
+ const baseTmp = this.acquireTemp(baseWType);
1029
+ this.emitExpr(expr.expr, baseWType);
1030
+ for (let i = 0; i < path.length - 1; i++) {
1031
+ const step = path[i];
1032
+ this.pushInstruction({
1033
+ op: "struct.get",
1034
+ typeIndex: step.structInfo.typeIndex,
1035
+ fieldIndex: step.fieldIndex,
1036
+ });
1037
+ }
1038
+ this.pushInstruction({ op: "local.set", index: baseTmp });
1039
+
1040
+ this.pushInstruction({ op: "local.get", index: baseTmp });
1041
+
1042
+ this.pushInstruction({ op: "local.get", index: baseTmp });
1043
+ this.pushInstruction({
1044
+ op: "struct.get",
1045
+ typeIndex: lastStep.structInfo.typeIndex,
1046
+ fieldIndex: lastStep.fieldIndex,
1047
+ });
1048
+
1049
+ if (targetType === "i64") {
1050
+ this.pushInstruction({ op: "i64.const", value: 1n });
1051
+ this.pushInstruction(op === "++" ? "i64.add" : "i64.sub");
1052
+ } else if (targetType === "f32") {
1053
+ this.pushInstruction({ op: "f32.const", value: 1.0 });
1054
+ this.pushInstruction(op === "++" ? "f32.add" : "f32.sub");
1055
+ } else if (targetType === "f64") {
1056
+ this.pushInstruction({ op: "f64.const", value: 1.0 });
1057
+ this.pushInstruction(op === "++" ? "f64.add" : "f64.sub");
1058
+ } else {
1059
+ this.pushInstruction({ op: "i32.const", value: 1 });
1060
+ this.pushInstruction(op === "++" ? "i32.add" : "i32.sub");
1061
+ this.emitNarrowIntWrap(expr._type);
1062
+ }
1063
+
1064
+ this.pushInstruction({
1065
+ op: "struct.set",
1066
+ typeIndex: lastStep.structInfo.typeIndex,
1067
+ fieldIndex: lastStep.fieldIndex,
1068
+ });
1069
+ this.releaseTemp(baseTmp, baseWType);
1070
+ return;
1071
+ }
1072
+
1073
+ if (expr.kind === "IndexExpr") {
1074
+ const baseNode = expr.expr;
1075
+ const baseType = baseNode._type ?? this._resolveExprGoType(baseNode);
1076
+ if (isMapType(baseType, this.mod.checker)) {
1077
+ const { keyType, valType } = getMapKeyValTypes(
1078
+ baseType,
1079
+ this.mod.checker,
1080
+ );
1081
+ const mapInfo = this.mod.getMapType(keyType, valType);
1082
+ const mTmp = this.acquireTemp(mapInfo.wType);
1083
+ const kTmp = this.acquireTemp(mapInfo.keyWType);
1084
+ this.emitExpr(baseNode, mapInfo.wType);
1085
+ this.pushInstruction({ op: "local.set", index: mTmp });
1086
+ this.emitExpr(expr.index, mapInfo.keyWType);
1087
+ this.pushInstruction({ op: "local.set", index: kTmp });
1088
+
1089
+ this.pushInstruction({ op: "local.get", index: mTmp });
1090
+ this.pushInstruction({ op: "local.get", index: kTmp });
1091
+
1092
+ this.pushInstruction({ op: "local.get", index: mTmp });
1093
+ this.pushInstruction({ op: "local.get", index: kTmp });
1094
+ this.pushInstruction({
1095
+ op: "call",
1096
+ funcIndex: this.mod.resolveFuncIndex(mapInfo.getFuncName),
1097
+ });
1098
+
1099
+ if (mapInfo.valWType === "i64") {
1100
+ this.pushInstruction({ op: "i64.const", value: 1n });
1101
+ this.pushInstruction(op === "++" ? "i64.add" : "i64.sub");
1102
+ } else if (mapInfo.valWType === "f32") {
1103
+ this.pushInstruction({ op: "f32.const", value: 1.0 });
1104
+ this.pushInstruction(op === "++" ? "f32.add" : "f32.sub");
1105
+ } else if (mapInfo.valWType === "f64") {
1106
+ this.pushInstruction({ op: "f64.const", value: 1.0 });
1107
+ this.pushInstruction(op === "++" ? "f64.add" : "f64.sub");
1108
+ } else {
1109
+ this.pushInstruction({ op: "i32.const", value: 1 });
1110
+ this.pushInstruction(op === "++" ? "i32.add" : "i32.sub");
1111
+ this.emitNarrowIntWrap(valType);
1112
+ }
1113
+
1114
+ this.pushInstruction({
1115
+ op: "call",
1116
+ funcIndex: this.mod.resolveFuncIndex(mapInfo.setFuncName),
1117
+ });
1118
+
1119
+ this.releaseTemp(kTmp, mapInfo.keyWType);
1120
+ this.releaseTemp(mTmp, mapInfo.wType);
1121
+ return;
1122
+ }
1123
+
1124
+ const sharedInfo = this._sharedInfo(baseType);
1125
+ if (sharedInfo) {
1126
+ this.emitSharedIndexUpdate(expr, sharedInfo, (elemW) => {
1127
+ if (elemW === "f32" || elemW === "f64") {
1128
+ this.pushInstruction({ op: `${elemW}.const`, value: 1.0 });
1129
+ } else {
1130
+ this.pushInstruction({ op: "i32.const", value: 1 });
1131
+ }
1132
+ this.pushInstruction(`${elemW}.${op === "++" ? "add" : "sub"}`);
1133
+ });
1134
+ return;
1135
+ }
1136
+
1137
+ const isSlice = isSliceType(baseType, this.mod.checker);
1138
+ const isPtrToArr =
1139
+ baseType?.kind === "pointer" &&
1140
+ isArrayType(baseType.base, this.mod.checker);
1141
+
1142
+ const elemGoType = isSlice
1143
+ ? baseType.elem
1144
+ : isPtrToArr
1145
+ ? baseType.base.elem
1146
+ : baseType.elem;
1147
+ const arrInfo = this.mod.getArrayType(elemGoType);
1148
+ const sliceInfo = isSlice ? this.mod.getSliceType(elemGoType) : null;
1149
+ const targetType = arrInfo.elemWType;
1150
+ const arrWType = {
1151
+ kind: "ref",
1152
+ nullable: true,
1153
+ typeIndex: arrInfo.typeIndex,
1154
+ };
1155
+
1156
+ this._emitElemAddr(baseNode, expr.index, sliceInfo, arrInfo);
1157
+ const arrTmp = this.acquireTemp(arrWType);
1158
+ const targetIdxTmp = this.acquireTemp("i32");
1159
+ this.pushInstruction({ op: "local.set", index: targetIdxTmp });
1160
+ this.pushInstruction({ op: "local.tee", index: arrTmp });
1161
+ this.pushInstruction({ op: "local.get", index: targetIdxTmp });
1162
+
1163
+ this.pushInstruction({ op: "local.get", index: arrTmp });
1164
+ this.pushInstruction({ op: "local.get", index: targetIdxTmp });
1165
+ this.pushInstruction({
1166
+ op: "array.get",
1167
+ typeIndex: arrInfo.typeIndex,
1168
+ });
1169
+
1170
+ if (targetType === "i64") {
1171
+ this.pushInstruction({ op: "i64.const", value: 1n });
1172
+ this.pushInstruction(op === "++" ? "i64.add" : "i64.sub");
1173
+ } else if (targetType === "f32") {
1174
+ this.pushInstruction({ op: "f32.const", value: 1.0 });
1175
+ this.pushInstruction(op === "++" ? "f32.add" : "f32.sub");
1176
+ } else if (targetType === "f64") {
1177
+ this.pushInstruction({ op: "f64.const", value: 1.0 });
1178
+ this.pushInstruction(op === "++" ? "f64.add" : "f64.sub");
1179
+ } else {
1180
+ this.pushInstruction({ op: "i32.const", value: 1 });
1181
+ this.pushInstruction(op === "++" ? "i32.add" : "i32.sub");
1182
+ this.emitNarrowIntWrap(elemGoType);
1183
+ }
1184
+
1185
+ this.pushInstruction({
1186
+ op: "array.set",
1187
+ typeIndex: arrInfo.typeIndex,
1188
+ });
1189
+
1190
+ this.releaseTemp(targetIdxTmp, "i32");
1191
+ this.releaseTemp(arrTmp, arrWType);
1192
+ return;
1193
+ }
1194
+
1195
+ if (expr.kind === "Ident") {
1196
+ const localInfo = this.resolveLocal(expr.name);
1197
+ const globalInfo = !localInfo ? this.mod.resolveGlobal(expr.name) : null;
1198
+ if (!localInfo && !globalInfo) return;
1199
+
1200
+ if (localInfo?.isBoxed) {
1201
+ const boxInfo = localInfo.boxInfo;
1202
+ const innerWType = boxInfo.wType;
1203
+ this.pushInstruction({ op: "local.get", index: localInfo.index });
1204
+ this.pushInstruction({ op: "local.get", index: localInfo.index });
1205
+ this.pushInstruction({
1206
+ op: "struct.get",
1207
+ typeIndex: boxInfo.typeIndex,
1208
+ fieldIndex: 0,
1209
+ });
1210
+ if (innerWType === "i64") {
1211
+ this.pushInstruction({ op: "i64.const", value: 1n });
1212
+ this.pushInstruction(op === "++" ? "i64.add" : "i64.sub");
1213
+ } else if (innerWType === "f32") {
1214
+ this.pushInstruction({ op: "f32.const", value: 1.0 });
1215
+ this.pushInstruction(op === "++" ? "f32.add" : "f32.sub");
1216
+ } else if (innerWType === "f64") {
1217
+ this.pushInstruction({ op: "f64.const", value: 1.0 });
1218
+ this.pushInstruction(op === "++" ? "f64.add" : "f64.sub");
1219
+ } else {
1220
+ this.pushInstruction({ op: "i32.const", value: 1 });
1221
+ this.pushInstruction(op === "++" ? "i32.add" : "i32.sub");
1222
+ this.emitNarrowIntWrap(localInfo.goType);
1223
+ }
1224
+ this.pushInstruction({
1225
+ op: "struct.set",
1226
+ typeIndex: boxInfo.typeIndex,
1227
+ fieldIndex: 0,
1228
+ });
1229
+ return;
1230
+ }
1231
+
1232
+ const targetType = localInfo ? localInfo.type : globalInfo.type;
1233
+
1234
+ if (localInfo) {
1235
+ this.pushInstruction({ op: "local.get", index: localInfo.index });
1236
+ } else {
1237
+ this.pushInstruction({ op: "global.get", index: globalInfo.index });
1238
+ }
1239
+
1240
+ if (targetType === "i64") {
1241
+ this.pushInstruction({ op: "i64.const", value: 1n });
1242
+ this.pushInstruction(op === "++" ? "i64.add" : "i64.sub");
1243
+ } else if (targetType === "f32") {
1244
+ this.pushInstruction({ op: "f32.const", value: 1.0 });
1245
+ this.pushInstruction(op === "++" ? "f32.add" : "f32.sub");
1246
+ } else if (targetType === "f64") {
1247
+ this.pushInstruction({ op: "f64.const", value: 1.0 });
1248
+ this.pushInstruction(op === "++" ? "f64.add" : "f64.sub");
1249
+ } else {
1250
+ this.pushInstruction({ op: "i32.const", value: 1 });
1251
+ this.pushInstruction(op === "++" ? "i32.add" : "i32.sub");
1252
+ this.emitNarrowIntWrap(expr._type);
1253
+ }
1254
+
1255
+ if (localInfo) {
1256
+ this.pushInstruction({ op: "local.set", index: localInfo.index });
1257
+ } else {
1258
+ this.pushInstruction({ op: "global.set", index: globalInfo.index });
1259
+ }
1260
+ }
1261
+ }
1262
+
1263
+ emitIfStmt(stmt) {
1264
+ if (stmt.init) this.emitStmt(stmt.init);
1265
+
1266
+ this.emitExpr(stmt.cond, "i32");
1267
+ this.pushInstruction({ op: "if", blockType: "void" });
1268
+ this.pushControl("if");
1269
+
1270
+ const thenBlock = stmt.body ?? stmt.then;
1271
+ if (thenBlock) this.emitBlock(thenBlock);
1272
+ const elseBlock = stmt.elseBody ?? stmt.else;
1273
+ if (elseBlock) {
1274
+ this.pushInstruction("else");
1275
+ if (elseBlock.kind === "Block") {
1276
+ this.emitBlock(elseBlock);
1277
+ } else {
1278
+ this.emitStmt(elseBlock);
1279
+ }
1280
+ }
1281
+ this.pushInstruction("end");
1282
+ }
1283
+
1284
+ emitRangeForStmt(stmt) {
1285
+ const rangeExpr =
1286
+ stmt.cond?.kind === "RangeExpr" ? stmt.cond : stmt.init.rhs[0];
1287
+ const isAssign = stmt.init?.kind === "AssignStmt";
1288
+ const lhs = stmt.init?.lhs ?? [];
1289
+ const iterExpr = rangeExpr.expr;
1290
+ const iterType = iterExpr._type;
1291
+
1292
+ // `for i := range` shadows any outer `i`; restore the outer binding afterwards.
1293
+ const shadowed = isAssign
1294
+ ? []
1295
+ : lhs
1296
+ .filter((l) => l && l.name !== "_")
1297
+ .map((l) => [l.name, this.locals.get(l.name)]);
1298
+ const restoreShadowed = () => {
1299
+ for (const [name, prev] of shadowed) {
1300
+ if (prev) this.locals.set(name, prev);
1301
+ else this.locals.delete(name);
1302
+ }
1303
+ };
1304
+
1305
+ if (isIntRangeType(iterType)) {
1306
+ const limitTmp = this.acquireTemp("i32");
1307
+ this._emitIndexExprToI32(iterExpr, limitTmp);
1308
+
1309
+ const idxTmp = this.acquireTemp("i32");
1310
+ this.pushInstruction({ op: "i32.const", value: 0 });
1311
+ this.pushInstruction({ op: "local.set", index: idxTmp });
1312
+
1313
+ let idxLocalInfo = null;
1314
+ if (lhs[0] && lhs[0].name !== "_") {
1315
+ if (!isAssign) {
1316
+ const bodyBlock = stmt.body ?? stmt.block;
1317
+ const isNonEscaping =
1318
+ !this.mutatedCaptures?.has(lhs[0].name) &&
1319
+ !this.capturedNames?.includes(lhs[0].name) &&
1320
+ !this._varMutatesOrEscapes(bodyBlock, lhs[0].name);
1321
+ const wType = isNonEscaping ? "i32" : "i64";
1322
+ const lIdx = this.allocLocal(lhs[0].name, wType, {
1323
+ kind: "basic",
1324
+ name: "int",
1325
+ });
1326
+ idxLocalInfo = { index: lIdx, type: wType };
1327
+ } else {
1328
+ idxLocalInfo =
1329
+ this.resolveLocal(lhs[0].name) ??
1330
+ this.mod.resolveGlobal(lhs[0].name);
1331
+ }
1332
+ }
1333
+
1334
+ // Outer block for break
1335
+ this.pushInstruction({ op: "block", blockType: "void" });
1336
+ this.pushControl("break", stmt.label);
1337
+
1338
+ // Middle loop
1339
+ this.pushInstruction({ op: "loop", blockType: "void" });
1340
+ this.pushControl("loop", stmt.label);
1341
+
1342
+ // Condition: idx >= limit -> break
1343
+ this.pushInstruction({ op: "local.get", index: idxTmp });
1344
+ this.pushInstruction({ op: "local.get", index: limitTmp });
1345
+ this.pushInstruction("i32.ge_s");
1346
+ const breakDepth = this.resolveBranchDepth(stmt.label, false);
1347
+ this.pushInstruction({ op: "br_if", depth: breakDepth });
1348
+
1349
+ // Inner block for continue
1350
+ this.pushInstruction({ op: "block", blockType: "void" });
1351
+ this.pushControl("continue", stmt.label);
1352
+
1353
+ // Assign loop var if present
1354
+ if (idxLocalInfo) {
1355
+ this.pushInstruction({ op: "local.get", index: idxTmp });
1356
+ if (idxLocalInfo.type === "i64") {
1357
+ this.pushInstruction("i64.extend_i32_s");
1358
+ }
1359
+ if (this.resolveLocal(lhs[0].name)) {
1360
+ this.pushInstruction({
1361
+ op: "local.set",
1362
+ index: idxLocalInfo.index,
1363
+ });
1364
+ } else {
1365
+ this.pushInstruction({
1366
+ op: "global.set",
1367
+ index: idxLocalInfo.index,
1368
+ });
1369
+ }
1370
+ }
1371
+
1372
+ // Emit body
1373
+ const bodyBlock = stmt.body ?? stmt.block;
1374
+ if (bodyBlock) {
1375
+ this.emitBlock(bodyBlock);
1376
+ }
1377
+
1378
+ // End continue
1379
+ this.pushInstruction("end");
1380
+
1381
+ // Post: idx++
1382
+ this.pushInstruction({ op: "local.get", index: idxTmp });
1383
+ this.pushInstruction({ op: "i32.const", value: 1 });
1384
+ this.pushInstruction("i32.add");
1385
+ this.pushInstruction({ op: "local.set", index: idxTmp });
1386
+
1387
+ // Loop back
1388
+ this.pushInstruction({ op: "br", depth: 0 });
1389
+
1390
+ // End loop
1391
+ this.pushInstruction("end");
1392
+
1393
+ // End break
1394
+ this.pushInstruction("end");
1395
+
1396
+ this.releaseTemp(idxTmp, "i32");
1397
+ this.releaseTemp(limitTmp, "i32");
1398
+ restoreShadowed();
1399
+ return;
1400
+ }
1401
+
1402
+ if (isStringType(iterType, this.mod.checker)) {
1403
+ const strTmp = this.acquireTemp("externref");
1404
+ this.emitExpr(iterExpr, "externref");
1405
+ this.pushInstruction({ op: "local.set", index: strTmp });
1406
+
1407
+ const lenTmp = this.acquireTemp("i32");
1408
+ this.pushInstruction({ op: "local.get", index: strTmp });
1409
+ this.pushInstruction({
1410
+ op: "call",
1411
+ funcIndex: this.mod.getStringLenImportIndex(),
1412
+ });
1413
+ this.pushInstruction({ op: "local.set", index: lenTmp });
1414
+
1415
+ const idxTmp = this.acquireTemp("i32");
1416
+ this.pushInstruction({ op: "i32.const", value: 0 });
1417
+ this.pushInstruction({ op: "local.set", index: idxTmp });
1418
+
1419
+ let idxLocalInfo = null;
1420
+ if (lhs[0] && lhs[0].name !== "_") {
1421
+ if (!isAssign) {
1422
+ const lIdx = this.allocLocal(lhs[0].name, "i64", {
1423
+ kind: "basic",
1424
+ name: "int",
1425
+ });
1426
+ idxLocalInfo = { index: lIdx, type: "i64" };
1427
+ } else {
1428
+ idxLocalInfo =
1429
+ this.resolveLocal(lhs[0].name) ??
1430
+ this.mod.resolveGlobal(lhs[0].name);
1431
+ }
1432
+ }
1433
+
1434
+ let valLocalInfo = null;
1435
+ if (lhs[1] && lhs[1].name !== "_") {
1436
+ if (!isAssign) {
1437
+ const lIdx = this.allocLocal(lhs[1].name, "i32", {
1438
+ kind: "basic",
1439
+ name: "rune",
1440
+ });
1441
+ valLocalInfo = { index: lIdx, type: "i32" };
1442
+ } else {
1443
+ valLocalInfo =
1444
+ this.resolveLocal(lhs[1].name) ??
1445
+ this.mod.resolveGlobal(lhs[1].name);
1446
+ }
1447
+ }
1448
+
1449
+ // Outer block for break
1450
+ this.pushInstruction({ op: "block", blockType: "void" });
1451
+ this.pushControl("break", stmt.label);
1452
+
1453
+ // Middle loop
1454
+ this.pushInstruction({ op: "loop", blockType: "void" });
1455
+ this.pushControl("loop", stmt.label);
1456
+
1457
+ // Condition: idx >= len -> break
1458
+ this.pushInstruction({ op: "local.get", index: idxTmp });
1459
+ this.pushInstruction({ op: "local.get", index: lenTmp });
1460
+ this.pushInstruction("i32.ge_s");
1461
+ const breakDepth = this.resolveBranchDepth(stmt.label, false);
1462
+ this.pushInstruction({ op: "br_if", depth: breakDepth });
1463
+
1464
+ // Inner block for continue
1465
+ this.pushInstruction({ op: "block", blockType: "void" });
1466
+ this.pushControl("continue", stmt.label);
1467
+
1468
+ const runeTmp = this.acquireTemp("i32");
1469
+ this.pushInstruction({ op: "local.get", index: strTmp });
1470
+ this.pushInstruction({ op: "local.get", index: idxTmp });
1471
+ this.pushInstruction({
1472
+ op: "call",
1473
+ funcIndex: this.mod.getStringCodePointAtImportIndex(),
1474
+ });
1475
+ this.pushInstruction({ op: "local.set", index: runeTmp });
1476
+
1477
+ // Assign index variable
1478
+ if (idxLocalInfo) {
1479
+ this.pushInstruction({ op: "local.get", index: idxTmp });
1480
+ this.pushInstruction("i64.extend_i32_s");
1481
+ if (this.resolveLocal(lhs[0].name)) {
1482
+ this.pushInstruction({
1483
+ op: "local.set",
1484
+ index: idxLocalInfo.index,
1485
+ });
1486
+ } else {
1487
+ this.pushInstruction({
1488
+ op: "global.set",
1489
+ index: idxLocalInfo.index,
1490
+ });
1491
+ }
1492
+ }
1493
+
1494
+ // Assign rune variable
1495
+ if (valLocalInfo) {
1496
+ this.pushInstruction({ op: "local.get", index: runeTmp });
1497
+ if (valLocalInfo.type === "i64") {
1498
+ this.pushInstruction("i64.extend_i32_u");
1499
+ }
1500
+ if (this.resolveLocal(lhs[1].name)) {
1501
+ this.pushInstruction({
1502
+ op: "local.set",
1503
+ index: valLocalInfo.index,
1504
+ });
1505
+ } else {
1506
+ this.pushInstruction({
1507
+ op: "global.set",
1508
+ index: valLocalInfo.index,
1509
+ });
1510
+ }
1511
+ }
1512
+
1513
+ // Body
1514
+ const bodyBlock = stmt.body ?? stmt.block;
1515
+ if (bodyBlock) {
1516
+ this.emitBlock(bodyBlock);
1517
+ }
1518
+
1519
+ // End continue block
1520
+ this.pushInstruction("end");
1521
+
1522
+ // Advance idxTmp: idx += (rune > 0xffff ? 2 : 1)
1523
+ this.pushInstruction({ op: "local.get", index: idxTmp });
1524
+ this.pushInstruction({ op: "local.get", index: runeTmp });
1525
+ this.pushInstruction({ op: "i32.const", value: 65535 });
1526
+ this.pushInstruction("i32.gt_u");
1527
+ this.pushInstruction({ op: "if", blockType: "i32" });
1528
+ this.pushInstruction({ op: "i32.const", value: 2 });
1529
+ this.pushInstruction("else");
1530
+ this.pushInstruction({ op: "i32.const", value: 1 });
1531
+ this.pushInstruction("end");
1532
+ this.pushInstruction("i32.add");
1533
+ this.pushInstruction({ op: "local.set", index: idxTmp });
1534
+
1535
+ // Repeat loop
1536
+ this.pushInstruction({ op: "br", depth: 0 });
1537
+
1538
+ // End loop
1539
+ this.pushInstruction("end");
1540
+
1541
+ // End break block
1542
+ this.pushInstruction("end");
1543
+
1544
+ this.releaseTemp(runeTmp, "i32");
1545
+ this.releaseTemp(idxTmp, "i32");
1546
+ this.releaseTemp(lenTmp, "i32");
1547
+ this.releaseTemp(strTmp, "externref");
1548
+ restoreShadowed();
1549
+ return;
1550
+ }
1551
+
1552
+ if (isMapType(iterType, this.mod.checker)) {
1553
+ const { keyType, valType } = getMapKeyValTypes(
1554
+ iterType,
1555
+ this.mod.checker,
1556
+ );
1557
+ const mapInfo = this.mod.getMapType(keyType, valType);
1558
+
1559
+ const mapTmp = this.acquireTemp(mapInfo.wType);
1560
+ this.emitExpr(iterExpr, mapInfo.wType);
1561
+ this.pushInstruction({ op: "local.set", index: mapTmp });
1562
+
1563
+ // Outer block for break
1564
+ this.pushInstruction({ op: "block", blockType: "void" });
1565
+ this.pushControl("break", stmt.label);
1566
+
1567
+ // If map is nil: break immediately
1568
+ this.pushInstruction({ op: "local.get", index: mapTmp });
1569
+ this.pushInstruction("ref.is_null");
1570
+ const earlyBreakDepth = this.resolveBranchDepth(stmt.label, false);
1571
+ this.pushInstruction({ op: "br_if", depth: earlyBreakDepth });
1572
+
1573
+ const currIdxTmp = this.acquireTemp("i32");
1574
+ const nextIdxTmp = this.acquireTemp("i32");
1575
+ const entryTmp = this.acquireTemp({
1576
+ kind: "ref",
1577
+ nullable: true,
1578
+ typeIndex: mapInfo.entryTypeIndex,
1579
+ });
1580
+
1581
+ // currIdx = map.head (field 5)
1582
+ this.pushInstruction({ op: "local.get", index: mapTmp });
1583
+ this.pushInstruction({
1584
+ op: "struct.get",
1585
+ typeIndex: mapInfo.typeIndex,
1586
+ fieldIndex: 5,
1587
+ });
1588
+ this.pushInstruction({ op: "local.set", index: currIdxTmp });
1589
+
1590
+ let keyLocalInfo = null;
1591
+ if (lhs[0] && lhs[0].name !== "_") {
1592
+ if (!isAssign) {
1593
+ const lIdx = this.allocLocal(lhs[0].name, mapInfo.keyWType, keyType);
1594
+ keyLocalInfo = { index: lIdx, type: mapInfo.keyWType };
1595
+ } else {
1596
+ keyLocalInfo =
1597
+ this.resolveLocal(lhs[0].name) ??
1598
+ this.mod.resolveGlobal(lhs[0].name);
1599
+ }
1600
+ }
1601
+
1602
+ let valLocalInfo = null;
1603
+ if (lhs[1] && lhs[1].name !== "_") {
1604
+ if (!isAssign) {
1605
+ const lIdx = this.allocLocal(lhs[1].name, mapInfo.valWType, valType);
1606
+ valLocalInfo = { index: lIdx, type: mapInfo.valWType };
1607
+ } else {
1608
+ valLocalInfo =
1609
+ this.resolveLocal(lhs[1].name) ??
1610
+ this.mod.resolveGlobal(lhs[1].name);
1611
+ }
1612
+ }
1613
+
1614
+ // Loop block
1615
+ this.pushInstruction({ op: "loop", blockType: "void" });
1616
+ this.pushControl("loop", stmt.label);
1617
+
1618
+ // Condition: currIdx == -1 -> break
1619
+ this.pushInstruction({ op: "local.get", index: currIdxTmp });
1620
+ this.pushInstruction({ op: "i32.const", value: -1 });
1621
+ this.pushInstruction("i32.eq");
1622
+ const breakDepth = this.resolveBranchDepth(stmt.label, false);
1623
+ this.pushInstruction({ op: "br_if", depth: breakDepth });
1624
+
1625
+ // entry = map.entries[currIdx]
1626
+ this.pushInstruction({ op: "local.get", index: mapTmp });
1627
+ this.pushInstruction({
1628
+ op: "struct.get",
1629
+ typeIndex: mapInfo.typeIndex,
1630
+ fieldIndex: 1,
1631
+ });
1632
+ this.pushInstruction({ op: "local.get", index: currIdxTmp });
1633
+ this.pushInstruction({
1634
+ op: "array.get",
1635
+ typeIndex: mapInfo.entriesTypeIndex,
1636
+ });
1637
+ this.pushInstruction({ op: "local.set", index: entryTmp });
1638
+
1639
+ // nextIdx = entry.order_next (field 4)
1640
+ this.pushInstruction({ op: "local.get", index: entryTmp });
1641
+ this.pushInstruction({
1642
+ op: "struct.get",
1643
+ typeIndex: mapInfo.entryTypeIndex,
1644
+ fieldIndex: 4,
1645
+ });
1646
+ this.pushInstruction({ op: "local.set", index: nextIdxTmp });
1647
+
1648
+ // If entry.active == 0 (field 5): currIdx = nextIdx; br 0 (continue next iteration)
1649
+ this.pushInstruction({ op: "local.get", index: entryTmp });
1650
+ this.pushInstruction({
1651
+ op: "struct.get",
1652
+ typeIndex: mapInfo.entryTypeIndex,
1653
+ fieldIndex: 5,
1654
+ });
1655
+ this.pushInstruction({ op: "i32.const", value: 0 });
1656
+ this.pushInstruction("i32.eq");
1657
+ this.pushInstruction({ op: "if", blockType: "void" });
1658
+ this.pushInstruction({ op: "local.get", index: nextIdxTmp });
1659
+ this.pushInstruction({ op: "local.set", index: currIdxTmp });
1660
+ this.pushInstruction({ op: "br", depth: 1 });
1661
+ this.pushInstruction("end");
1662
+
1663
+ // Inner block for continue
1664
+ this.pushInstruction({ op: "block", blockType: "void" });
1665
+ this.pushControl("continue", stmt.label);
1666
+
1667
+ // Assign key variable
1668
+ if (keyLocalInfo) {
1669
+ this.pushInstruction({ op: "local.get", index: entryTmp });
1670
+ this.pushInstruction({
1671
+ op: "struct.get",
1672
+ typeIndex: mapInfo.entryTypeIndex,
1673
+ fieldIndex: 0,
1674
+ });
1675
+ if (this.resolveLocal(lhs[0].name)) {
1676
+ this.pushInstruction({
1677
+ op: "local.set",
1678
+ index: keyLocalInfo.index,
1679
+ });
1680
+ } else {
1681
+ this.pushInstruction({
1682
+ op: "global.set",
1683
+ index: keyLocalInfo.index,
1684
+ });
1685
+ }
1686
+ }
1687
+
1688
+ // Assign val variable
1689
+ if (valLocalInfo) {
1690
+ this.pushInstruction({ op: "local.get", index: entryTmp });
1691
+ this.pushInstruction({
1692
+ op: "struct.get",
1693
+ typeIndex: mapInfo.entryTypeIndex,
1694
+ fieldIndex: 1,
1695
+ });
1696
+ const isValStruct =
1697
+ isStructType(valType, this.mod.checker, this.mod) &&
1698
+ !isPointerToStruct(valType, this.mod.checker, this.mod);
1699
+ if (isValStruct) {
1700
+ const sInfo = this._resolveStructInfo({ _type: valType });
1701
+ if (sInfo) {
1702
+ this.emitCloneStruct(sInfo, mapInfo.valWType);
1703
+ }
1704
+ }
1705
+ if (this.resolveLocal(lhs[1].name)) {
1706
+ this.pushInstruction({
1707
+ op: "local.set",
1708
+ index: valLocalInfo.index,
1709
+ });
1710
+ } else {
1711
+ this.pushInstruction({
1712
+ op: "global.set",
1713
+ index: valLocalInfo.index,
1714
+ });
1715
+ }
1716
+ }
1717
+
1718
+ // Body
1719
+ const bodyBlock = stmt.body ?? stmt.block;
1720
+ if (bodyBlock) {
1721
+ this.emitBlock(bodyBlock);
1722
+ }
1723
+
1724
+ // End continue block
1725
+ this.pushInstruction("end");
1726
+
1727
+ // Advance: currIdx = nextIdx
1728
+ this.pushInstruction({ op: "local.get", index: nextIdxTmp });
1729
+ this.pushInstruction({ op: "local.set", index: currIdxTmp });
1730
+
1731
+ // Loop back
1732
+ this.pushInstruction({ op: "br", depth: 0 });
1733
+
1734
+ // End loop
1735
+ this.pushInstruction("end");
1736
+
1737
+ // End break
1738
+ this.pushInstruction("end");
1739
+
1740
+ this.releaseTemp(entryTmp, {
1741
+ kind: "ref",
1742
+ nullable: true,
1743
+ typeIndex: mapInfo.entryTypeIndex,
1744
+ });
1745
+ this.releaseTemp(nextIdxTmp, "i32");
1746
+ this.releaseTemp(currIdxTmp, "i32");
1747
+ this.releaseTemp(mapTmp, mapInfo.wType);
1748
+ restoreShadowed();
1749
+ return;
1750
+ }
1751
+
1752
+ const sharedInfo = this._sharedInfo(iterType);
1753
+ if (sharedInfo) {
1754
+ this._emitSharedRange(stmt, iterExpr, sharedInfo, lhs, isAssign);
1755
+ restoreShadowed();
1756
+ return;
1757
+ }
1758
+
1759
+ // Slice or Array range
1760
+ const isSlice = isSliceType(iterType, this.mod.checker);
1761
+ const isPtrToArr =
1762
+ iterType?.kind === "pointer" &&
1763
+ isArrayType(iterType.base, this.mod.checker);
1764
+
1765
+ const elemGoType = isSlice
1766
+ ? iterType.elem
1767
+ : isPtrToArr
1768
+ ? iterType.base.elem
1769
+ : iterType.elem;
1770
+ const arrInfo = this.mod.getArrayType(elemGoType);
1771
+ const sliceInfo = isSlice ? this.mod.getSliceType(elemGoType) : null;
1772
+
1773
+ const arrWType = {
1774
+ kind: "ref",
1775
+ nullable: true,
1776
+ typeIndex: arrInfo.typeIndex,
1777
+ };
1778
+ const arrTmp = this.acquireTemp(arrWType);
1779
+ const offTmp = this.acquireTemp("i32");
1780
+ const lenTmp = this.acquireTemp("i32");
1781
+
1782
+ if (isSlice) {
1783
+ const sliceWType = {
1784
+ kind: "ref",
1785
+ nullable: true,
1786
+ typeIndex: sliceInfo.typeIndex,
1787
+ };
1788
+ const sliceTmp = this.acquireTemp(sliceWType);
1789
+ this.emitExpr(iterExpr, sliceWType);
1790
+ this.pushInstruction({ op: "local.set", index: sliceTmp });
1791
+
1792
+ this._emitSliceUnpack(sliceTmp, sliceInfo, {
1793
+ arr: arrTmp,
1794
+ off: offTmp,
1795
+ len: lenTmp,
1796
+ });
1797
+ this.releaseTemp(sliceTmp, sliceWType);
1798
+ } else {
1799
+ this.emitExpr(iterExpr, arrWType);
1800
+ this.pushInstruction({ op: "local.set", index: arrTmp });
1801
+ this.pushInstruction({ op: "i32.const", value: 0 });
1802
+ this.pushInstruction({ op: "local.set", index: offTmp });
1803
+ this.pushInstruction({ op: "local.get", index: arrTmp });
1804
+ this.pushInstruction("array.len");
1805
+ this.pushInstruction({ op: "local.set", index: lenTmp });
1806
+ }
1807
+
1808
+ const idxTmp = this.acquireTemp("i32");
1809
+ this.pushInstruction({ op: "i32.const", value: 0 });
1810
+ this.pushInstruction({ op: "local.set", index: idxTmp });
1811
+
1812
+ let idxLocalInfo = null;
1813
+ if (lhs[0] && lhs[0].name !== "_") {
1814
+ if (!isAssign) {
1815
+ const bodyBlock = stmt.body ?? stmt.block;
1816
+ const isNonEscaping =
1817
+ !this.mutatedCaptures?.has(lhs[0].name) &&
1818
+ !this.capturedNames?.includes(lhs[0].name) &&
1819
+ !this._varMutatesOrEscapes(bodyBlock, lhs[0].name);
1820
+ const wType = isNonEscaping ? "i32" : "i64";
1821
+ const lIdx = this.allocLocal(lhs[0].name, wType, {
1822
+ kind: "basic",
1823
+ name: "int",
1824
+ });
1825
+ idxLocalInfo = { index: lIdx, type: wType };
1826
+ } else {
1827
+ idxLocalInfo =
1828
+ this.resolveLocal(lhs[0].name) ?? this.mod.resolveGlobal(lhs[0].name);
1829
+ }
1830
+ }
1831
+
1832
+ let valLocalInfo = null;
1833
+ if (lhs[1] && lhs[1].name !== "_") {
1834
+ if (!isAssign) {
1835
+ const lIdx = this.allocLocal(
1836
+ lhs[1].name,
1837
+ arrInfo.elemWType,
1838
+ elemGoType,
1839
+ );
1840
+ valLocalInfo = { index: lIdx, type: arrInfo.elemWType };
1841
+ } else {
1842
+ valLocalInfo =
1843
+ this.resolveLocal(lhs[1].name) ?? this.mod.resolveGlobal(lhs[1].name);
1844
+ }
1845
+ }
1846
+
1847
+ // Outer block for break
1848
+ this.pushInstruction({ op: "block", blockType: "void" });
1849
+ this.pushControl("break", stmt.label);
1850
+
1851
+ // Middle loop
1852
+ this.pushInstruction({ op: "loop", blockType: "void" });
1853
+ this.pushControl("loop", stmt.label);
1854
+
1855
+ // Condition: idx >= len -> break
1856
+ this.pushInstruction({ op: "local.get", index: idxTmp });
1857
+ this.pushInstruction({ op: "local.get", index: lenTmp });
1858
+ this.pushInstruction("i32.ge_s");
1859
+ const breakDepth = this.resolveBranchDepth(stmt.label, false);
1860
+ this.pushInstruction({ op: "br_if", depth: breakDepth });
1861
+
1862
+ // Inner block for continue
1863
+ this.pushInstruction({ op: "block", blockType: "void" });
1864
+ this.pushControl("continue", stmt.label);
1865
+
1866
+ // Assign idx
1867
+ if (idxLocalInfo) {
1868
+ this.pushInstruction({ op: "local.get", index: idxTmp });
1869
+ if (idxLocalInfo.type === "i64") {
1870
+ this.pushInstruction("i64.extend_i32_s");
1871
+ }
1872
+ if (this.resolveLocal(lhs[0].name)) {
1873
+ this.pushInstruction({ op: "local.set", index: idxLocalInfo.index });
1874
+ } else {
1875
+ this.pushInstruction({
1876
+ op: "global.set",
1877
+ index: idxLocalInfo.index,
1878
+ });
1879
+ }
1880
+ }
1881
+
1882
+ // Assign val
1883
+ if (valLocalInfo) {
1884
+ this.pushInstruction({ op: "local.get", index: arrTmp });
1885
+ this.pushInstruction({ op: "local.get", index: offTmp });
1886
+ this.pushInstruction({ op: "local.get", index: idxTmp });
1887
+ this.pushInstruction("i32.add");
1888
+ this.pushInstruction({
1889
+ op: "array.get",
1890
+ typeIndex: arrInfo.typeIndex,
1891
+ });
1892
+ if (
1893
+ isStructType(elemGoType, this.mod.checker, this.mod) &&
1894
+ !isPointerToStruct(elemGoType, this.mod.checker, this.mod)
1895
+ ) {
1896
+ const sInfo = this._resolveStructInfo({ _type: elemGoType });
1897
+ if (sInfo) {
1898
+ this.emitCloneStruct(sInfo, arrInfo.elemWType);
1899
+ }
1900
+ }
1901
+ if (this.resolveLocal(lhs[1].name)) {
1902
+ this.pushInstruction({ op: "local.set", index: valLocalInfo.index });
1903
+ } else {
1904
+ this.pushInstruction({
1905
+ op: "global.set",
1906
+ index: valLocalInfo.index,
1907
+ });
1908
+ }
1909
+ }
1910
+
1911
+ // Body
1912
+ const bodyBlock = stmt.body ?? stmt.block;
1913
+ if (bodyBlock) {
1914
+ this.emitBlock(bodyBlock);
1915
+ }
1916
+
1917
+ // End continue
1918
+ this.pushInstruction("end");
1919
+
1920
+ // Post: idx++
1921
+ this.pushInstruction({ op: "local.get", index: idxTmp });
1922
+ this.pushInstruction({ op: "i32.const", value: 1 });
1923
+ this.pushInstruction("i32.add");
1924
+ this.pushInstruction({ op: "local.set", index: idxTmp });
1925
+
1926
+ // Loop back
1927
+ this.pushInstruction({ op: "br", depth: 0 });
1928
+
1929
+ // End loop
1930
+ this.pushInstruction("end");
1931
+
1932
+ // End break
1933
+ this.pushInstruction("end");
1934
+
1935
+ this.releaseTemp(idxTmp, "i32");
1936
+ this.releaseTemp(lenTmp, "i32");
1937
+ this.releaseTemp(offTmp, "i32");
1938
+ this.releaseTemp(arrTmp, arrWType);
1939
+
1940
+ restoreShadowed();
1941
+ }
1942
+
1943
+ emitForStmt(stmt) {
1944
+ if (isRangeFor(stmt) || stmt.cond?.kind === "RangeExpr") {
1945
+ this.emitRangeForStmt(stmt);
1946
+ return;
1947
+ }
1948
+
1949
+ const iv = this._detectInductionVar(stmt);
1950
+ let prevLocal = null;
1951
+ let ivLocalInfo = null;
1952
+
1953
+ if (iv) {
1954
+ prevLocal = this.locals.get(iv.name);
1955
+ const lIdx = this.allocLocal(
1956
+ iv.name,
1957
+ "i32",
1958
+ { kind: "basic", name: "int" },
1959
+ false,
1960
+ );
1961
+ ivLocalInfo = this.locals.get(iv.name);
1962
+ ivLocalInfo.isInductionVar = true;
1963
+ this.emitExpr(iv.initExpr, "i32");
1964
+ this.pushInstruction({ op: "local.set", index: lIdx });
1965
+ } else if (stmt.init) {
1966
+ this.emitStmt(stmt.init);
1967
+ }
1968
+
1969
+ // Outer block for break
1970
+ this.pushInstruction({ op: "block", blockType: "void" });
1971
+ this.pushControl("break", stmt.label);
1972
+
1973
+ // Middle loop for repeating iterations
1974
+ this.pushInstruction({ op: "loop", blockType: "void" });
1975
+ this.pushControl("loop", stmt.label);
1976
+
1977
+ if (stmt.cond) {
1978
+ this.emitExpr(stmt.cond, "i32");
1979
+ this.pushInstruction("i32.eqz");
1980
+ const breakDepth = this.resolveBranchDepth(stmt.label, false);
1981
+ this.pushInstruction({ op: "br_if", depth: breakDepth });
1982
+ }
1983
+
1984
+ // Inner block for continue
1985
+ this.pushInstruction({ op: "block", blockType: "void" });
1986
+ this.pushControl("continue", stmt.label);
1987
+
1988
+ const bodyBlock = stmt.body ?? stmt.block;
1989
+ if (bodyBlock) {
1990
+ this.emitBlock(bodyBlock);
1991
+ }
1992
+
1993
+ // End inner continue block
1994
+ this.pushInstruction("end");
1995
+
1996
+ if (iv) {
1997
+ this.pushInstruction({ op: "local.get", index: ivLocalInfo.index });
1998
+ this.pushInstruction({ op: "i32.const", value: iv.step });
1999
+ this.pushInstruction("i32.add");
2000
+ this.pushInstruction({ op: "local.set", index: ivLocalInfo.index });
2001
+ } else if (stmt.post) {
2002
+ this.emitStmt(stmt.post);
2003
+ }
2004
+
2005
+ // Repeat loop: branch back to loop block
2006
+ this.pushInstruction({ op: "br", depth: 0 });
2007
+
2008
+ // End loop
2009
+ this.pushInstruction("end");
2010
+
2011
+ // End outer break block
2012
+ this.pushInstruction("end");
2013
+
2014
+ if (iv) {
2015
+ if (prevLocal) {
2016
+ this.locals.set(iv.name, prevLocal);
2017
+ } else {
2018
+ this.locals.delete(iv.name);
2019
+ }
2020
+ }
2021
+ }
2022
+
2023
+ _detectInductionVar(stmt) {
2024
+ if (stmt.init?.kind !== "DefineStmt") return null;
2025
+ const lhs = stmt.init.lhs ?? [];
2026
+ if (lhs.length !== 1 || lhs[0].kind !== "Ident") return null;
2027
+ const varName = lhs[0].name;
2028
+ if (!varName || varName === "_") return null;
2029
+
2030
+ const rhs = stmt.init.rhs ?? [];
2031
+ if (rhs.length !== 1) return null;
2032
+ const initRhs = rhs[0];
2033
+
2034
+ // Initial value must be a non-negative integer literal < 2^31 or i32 expr
2035
+ let initOk = false;
2036
+ if (initRhs.kind === "BasicLit" && initRhs.litKind === "INT") {
2037
+ const val = BigInt(initRhs.value);
2038
+ if (val >= 0n && val < 2147483648n) initOk = true;
2039
+ } else if (this.toWasmType(initRhs._type) === "i32") {
2040
+ initOk = true;
2041
+ }
2042
+ if (!initOk) return null;
2043
+
2044
+ // Post statement must increment varName by a constant > 0
2045
+ let step = null;
2046
+ if (stmt.post) {
2047
+ if (
2048
+ stmt.post.kind === "IncDecStmt" &&
2049
+ stmt.post.expr?.kind === "Ident" &&
2050
+ stmt.post.expr.name === varName &&
2051
+ stmt.post.op === "++"
2052
+ ) {
2053
+ step = 1;
2054
+ } else if (
2055
+ stmt.post.kind === "CompoundAssignStmt" &&
2056
+ stmt.post.lhs?.length === 1 &&
2057
+ stmt.post.lhs[0].kind === "Ident" &&
2058
+ stmt.post.lhs[0].name === varName &&
2059
+ stmt.post.op === "+=" &&
2060
+ stmt.post.rhs?.length === 1 &&
2061
+ stmt.post.rhs[0].kind === "BasicLit" &&
2062
+ stmt.post.rhs[0].litKind === "INT"
2063
+ ) {
2064
+ const sVal = BigInt(stmt.post.rhs[0].value);
2065
+ if (sVal > 0n && sVal < 2147483648n) step = Number(sVal);
2066
+ }
2067
+ }
2068
+ if (step === null) return null;
2069
+
2070
+ // Condition must bound varName (< bound or <= bound) where bound < 2^31
2071
+ const boundNode = this._findInductionBound(stmt.cond, varName);
2072
+ if (!boundNode) return null;
2073
+ // The last `i += step` must not wrap i32: i can reach bound + step - 1.
2074
+ if (
2075
+ boundNode.kind === "BasicLit" &&
2076
+ BigInt(boundNode.value) + BigInt(step) > 2147483647n
2077
+ ) {
2078
+ return null;
2079
+ }
2080
+
2081
+ // Check escaping and mutation in body
2082
+ if (this.mutatedCaptures?.has(varName)) return null;
2083
+ if (this.capturedNames?.includes(varName)) return null;
2084
+
2085
+ const bodyBlock = stmt.body ?? stmt.block;
2086
+ if (bodyBlock && this._varMutatesOrEscapes(bodyBlock, varName)) {
2087
+ return null;
2088
+ }
2089
+
2090
+ return { name: varName, initExpr: initRhs, step };
2091
+ }
2092
+
2093
+ _findInductionBound(cond, varName) {
2094
+ if (!cond) return null;
2095
+ if (cond.kind === "BinaryExpr") {
2096
+ if (
2097
+ (cond.op === "<" || cond.op === "<=") &&
2098
+ cond.left?.kind === "Ident" &&
2099
+ cond.left.name === varName
2100
+ ) {
2101
+ const right = cond.right;
2102
+ if (
2103
+ right?.kind === "CallExpr" &&
2104
+ right.func?.kind === "Ident" &&
2105
+ (right.func.name === "len" || right.func.name === "cap")
2106
+ ) {
2107
+ return right;
2108
+ }
2109
+ if (right?.kind === "BasicLit" && right.litKind === "INT") {
2110
+ const val = BigInt(right.value);
2111
+ if (val >= 0n && val < 2147483648n) return right;
2112
+ return null;
2113
+ }
2114
+ if (this.toWasmType(right?._type) === "i32") {
2115
+ return right;
2116
+ }
2117
+ return null;
2118
+ }
2119
+ if (cond.op === "&&") {
2120
+ return (
2121
+ this._findInductionBound(cond.left, varName) ??
2122
+ this._findInductionBound(cond.right, varName)
2123
+ );
2124
+ }
2125
+ }
2126
+ return null;
2127
+ }
2128
+
2129
+ _varMutatesOrEscapes(node, varName) {
2130
+ if (!node || typeof node !== "object") return false;
2131
+ if (Array.isArray(node)) {
2132
+ return node.some((item) => this._varMutatesOrEscapes(item, varName));
2133
+ }
2134
+ if (
2135
+ node.kind === "UnaryExpr" &&
2136
+ node.op === "&" &&
2137
+ node.operand?.kind === "Ident" &&
2138
+ node.operand.name === varName
2139
+ ) {
2140
+ return true;
2141
+ }
2142
+ if (node.kind === "FuncLit") {
2143
+ if (this._findIdentInAST(node, varName)) return true;
2144
+ }
2145
+ if (node.kind === "AssignStmt" || node.kind === "CompoundAssignStmt") {
2146
+ const lhs = node.lhs ?? [];
2147
+ for (const l of lhs) {
2148
+ if (l.kind === "Ident" && l.name === varName) return true;
2149
+ }
2150
+ }
2151
+ if (node.kind === "IncDecStmt") {
2152
+ if (node.expr?.kind === "Ident" && node.expr.name === varName)
2153
+ return true;
2154
+ }
2155
+ if (node.kind === "DefineStmt") {
2156
+ const lhs = node.lhs ?? [];
2157
+ for (const l of lhs) {
2158
+ if (l.kind === "Ident" && l.name === varName) return true;
2159
+ }
2160
+ }
2161
+ for (const key of Object.keys(node)) {
2162
+ if (key.startsWith("_")) continue;
2163
+ if (this._varMutatesOrEscapes(node[key], varName)) return true;
2164
+ }
2165
+ return false;
2166
+ }
2167
+
2168
+ _findIdentInAST(node, name) {
2169
+ if (!node || typeof node !== "object") return false;
2170
+ if (Array.isArray(node)) {
2171
+ return node.some((item) => this._findIdentInAST(item, name));
2172
+ }
2173
+ if (node.kind === "Ident" && node.name === name) return true;
2174
+ for (const key of Object.keys(node)) {
2175
+ if (key.startsWith("_")) continue;
2176
+ if (this._findIdentInAST(node[key], name)) return true;
2177
+ }
2178
+ return false;
2179
+ }
2180
+
2181
+ emitSwitchStmt(stmt) {
2182
+ this.pushInstruction({ op: "block", blockType: "void" });
2183
+ this.pushControl("break", stmt.label);
2184
+
2185
+ if (stmt.init) this.emitStmt(stmt.init);
2186
+
2187
+ const getCaseVals = (c) => c.list ?? c.values ?? [];
2188
+
2189
+ if (stmt.tag) {
2190
+ const tagGoType = stmt.tag._type ?? this._resolveExprGoType(stmt.tag);
2191
+ const tagWType = this.toWasmType(tagGoType);
2192
+ const tagTmp = this.acquireTemp(tagWType);
2193
+ this.emitExpr(stmt.tag, tagWType);
2194
+ this.pushInstruction({ op: "local.set", index: tagTmp });
2195
+
2196
+ const nonDefaultCases = (stmt.cases ?? []).filter(
2197
+ (c) => getCaseVals(c).length > 0,
2198
+ );
2199
+ const defaultCase = (stmt.cases ?? []).find(
2200
+ (c) => getCaseVals(c).length === 0,
2201
+ );
2202
+
2203
+ let ifCount = 0;
2204
+ for (const c of nonDefaultCases) {
2205
+ const vals = getCaseVals(c);
2206
+ for (let i = 0; i < vals.length; i++) {
2207
+ this.pushInstruction({ op: "local.get", index: tagTmp });
2208
+ this.emitExpr(vals[i], tagWType);
2209
+ this.emitBinaryOp("==", tagWType, tagGoType);
2210
+ if (i > 0) this.pushInstruction("i32.or");
2211
+ }
2212
+ this.pushInstruction({ op: "if", blockType: "void" });
2213
+ ifCount++;
2214
+
2215
+ for (const s of c.stmts ?? []) this.emitStmt(s);
2216
+ this.pushInstruction("else");
2217
+ }
2218
+
2219
+ if (defaultCase) {
2220
+ for (const s of defaultCase.stmts ?? []) this.emitStmt(s);
2221
+ }
2222
+
2223
+ for (let i = 0; i < ifCount; i++) {
2224
+ this.pushInstruction("end");
2225
+ }
2226
+ this.releaseTemp(tagTmp, tagWType);
2227
+ } else {
2228
+ const nonDefaultCases = (stmt.cases ?? []).filter(
2229
+ (c) => getCaseVals(c).length > 0,
2230
+ );
2231
+ const defaultCase = (stmt.cases ?? []).find(
2232
+ (c) => getCaseVals(c).length === 0,
2233
+ );
2234
+
2235
+ let ifCount = 0;
2236
+ for (const c of nonDefaultCases) {
2237
+ const vals = getCaseVals(c);
2238
+ for (let i = 0; i < vals.length; i++) {
2239
+ this.emitExpr(vals[i], "i32");
2240
+ if (i > 0) this.pushInstruction("i32.or");
2241
+ }
2242
+ this.pushInstruction({ op: "if", blockType: "void" });
2243
+ ifCount++;
2244
+
2245
+ for (const s of c.stmts ?? []) this.emitStmt(s);
2246
+ this.pushInstruction("else");
2247
+ }
2248
+
2249
+ if (defaultCase) {
2250
+ for (const s of defaultCase.stmts ?? []) this.emitStmt(s);
2251
+ }
2252
+
2253
+ for (let i = 0; i < ifCount; i++) {
2254
+ this.pushInstruction("end");
2255
+ }
2256
+ }
2257
+
2258
+ this.pushInstruction("end");
2259
+ }
2260
+
2261
+ emitTypeSwitchStmt(stmt) {
2262
+ this.pushInstruction({ op: "block", blockType: "void" });
2263
+ this.pushControl("break", stmt.label);
2264
+
2265
+ const prevAssignLocal = stmt.assign ? this.locals.get(stmt.assign) : null;
2266
+
2267
+ const tswTmp = this.acquireTemp("anyref");
2268
+ this.emitExpr(stmt.expr, "anyref");
2269
+ this.pushInstruction({ op: "local.set", index: tswTmp });
2270
+
2271
+ const getCaseTypes = (c) => c.types ?? c.list ?? [];
2272
+
2273
+ const nonDefaultCases = (stmt.cases ?? []).filter(
2274
+ (c) => getCaseTypes(c).length > 0,
2275
+ );
2276
+ const defaultCase = (stmt.cases ?? []).find(
2277
+ (c) => getCaseTypes(c).length === 0,
2278
+ );
2279
+
2280
+ let ifCount = 0;
2281
+ for (const c of nonDefaultCases) {
2282
+ const types = getCaseTypes(c);
2283
+ for (let i = 0; i < types.length; i++) {
2284
+ this.pushInstruction({ op: "local.get", index: tswTmp });
2285
+ this._emitTypeTest(types[i]._type ?? types[i]);
2286
+ if (i > 0) {
2287
+ this.pushInstruction("i32.or");
2288
+ }
2289
+ }
2290
+ this.pushInstruction({ op: "if", blockType: "void" });
2291
+ ifCount++;
2292
+
2293
+ if (stmt.assign) {
2294
+ const targetGoType =
2295
+ types.length === 1
2296
+ ? (types[0]._type ?? types[0])
2297
+ : { kind: "basic", name: "any" };
2298
+ const targetWType = this.toWasmType(targetGoType);
2299
+ const assignLocal = this.allocLocal(
2300
+ stmt.assign,
2301
+ targetWType,
2302
+ targetGoType,
2303
+ );
2304
+ if (types.length === 1) {
2305
+ this.pushInstruction({ op: "local.get", index: tswTmp });
2306
+ this._emitTypeCast(targetGoType, targetWType);
2307
+ } else {
2308
+ this.pushInstruction({ op: "local.get", index: tswTmp });
2309
+ }
2310
+ this.pushInstruction({ op: "local.set", index: assignLocal });
2311
+ }
2312
+
2313
+ for (const s of c.stmts ?? []) {
2314
+ this.emitStmt(s);
2315
+ }
2316
+
2317
+ this.pushInstruction("else");
2318
+ }
2319
+
2320
+ if (defaultCase) {
2321
+ if (stmt.assign) {
2322
+ const assignLocal = this.allocLocal(stmt.assign, "anyref", {
2323
+ kind: "basic",
2324
+ name: "any",
2325
+ });
2326
+ this.pushInstruction({ op: "local.get", index: tswTmp });
2327
+ this.pushInstruction({ op: "local.set", index: assignLocal });
2328
+ }
2329
+ for (const s of defaultCase.stmts ?? []) {
2330
+ this.emitStmt(s);
2331
+ }
2332
+ }
2333
+
2334
+ for (let i = 0; i < ifCount; i++) {
2335
+ this.pushInstruction("end");
2336
+ }
2337
+
2338
+ this.releaseTemp(tswTmp, "anyref");
2339
+
2340
+ if (prevAssignLocal) {
2341
+ this.locals.set(stmt.assign, prevAssignLocal);
2342
+ } else if (stmt.assign) {
2343
+ this.locals.delete(stmt.assign);
2344
+ }
2345
+
2346
+ this.pushInstruction("end");
2347
+ }
2348
+
2349
+ emitBranchStmt(stmt) {
2350
+ const isContinue = stmt.keyword === "continue";
2351
+ const depth = this.resolveBranchDepth(stmt.label, isContinue);
2352
+ this.pushInstruction({ op: "br", depth });
2353
+ }
2354
+
2355
+ emitReturnStmt(stmt) {
2356
+ const values = stmt.values ?? [];
2357
+ if (this.hasDefer) {
2358
+ if (this.namedReturnVars?.length > 0) {
2359
+ if (values.length === 0) {
2360
+ // Naked return: named return vars already hold their values
2361
+ } else if (values.length === 1 && this.namedReturnVars.length > 1) {
2362
+ // Multi-value call: leaves results on stack
2363
+ this.emitExpr(values[0]);
2364
+ for (let i = this.namedReturnVars.length - 1; i >= 0; i--) {
2365
+ this._assignToNamedReturnVar(this.namedReturnVars[i]);
2366
+ }
2367
+ } else {
2368
+ // Evaluate all values into temporary locals first
2369
+ const temps = [];
2370
+ for (let i = 0; i < values.length; i++) {
2371
+ const val = values[i];
2372
+ const targetWType = this.returnTypes[i] ?? null;
2373
+ this.emitExpr(val, targetWType);
2374
+ this._emitCopyIfValueStruct(val, val._type, targetWType);
2375
+ const tmp = this.acquireTemp(targetWType);
2376
+ this.pushInstruction({ op: "local.set", index: tmp });
2377
+ temps.push({ tmp, type: targetWType });
2378
+ }
2379
+ for (let i = 0; i < temps.length; i++) {
2380
+ this.pushInstruction({ op: "local.get", index: temps[i].tmp });
2381
+ this._assignToNamedReturnVar(this.namedReturnVars[i]);
2382
+ this.releaseTemp(temps[i].tmp, temps[i].type);
2383
+ }
2384
+ }
2385
+ } else if (this.returnTempLocals?.length > 0) {
2386
+ if (values.length === 1 && this.returnTempLocals.length > 1) {
2387
+ this.emitExpr(values[0]);
2388
+ for (let i = this.returnTempLocals.length - 1; i >= 0; i--) {
2389
+ this.pushInstruction({
2390
+ op: "local.set",
2391
+ index: this.returnTempLocals[i],
2392
+ });
2393
+ }
2394
+ } else {
2395
+ for (let i = 0; i < values.length; i++) {
2396
+ const val = values[i];
2397
+ const targetWType = this.returnTypes[i] ?? null;
2398
+ this.emitExpr(val, targetWType);
2399
+ this._emitCopyIfValueStruct(val, val._type, targetWType);
2400
+ this.pushInstruction({
2401
+ op: "local.set",
2402
+ index: this.returnTempLocals[i],
2403
+ });
2404
+ }
2405
+ }
2406
+ }
2407
+ const depth = this.resolveBranchDepthToRole("runDefers");
2408
+ this.pushInstruction({ op: "br", depth });
2409
+ return;
2410
+ }
2411
+
2412
+ if (values.length === 0 && this.namedReturnVars?.length > 0) {
2413
+ for (const nr of this.namedReturnVars) {
2414
+ const loc = this.locals.get(nr.name);
2415
+ if (loc.isBoxed) {
2416
+ this.pushInstruction({ op: "local.get", index: loc.index });
2417
+ this.pushInstruction({
2418
+ op: "struct.get",
2419
+ typeIndex: loc.boxInfo.typeIndex,
2420
+ fieldIndex: 0,
2421
+ });
2422
+ } else {
2423
+ this.pushInstruction({ op: "local.get", index: loc.index });
2424
+ }
2425
+ }
2426
+ this.pushInstruction("return");
2427
+ return;
2428
+ }
2429
+
2430
+ for (let i = 0; i < values.length; i++) {
2431
+ const val = values[i];
2432
+ const targetWType = this.returnTypes[i] ?? null;
2433
+ this.emitExpr(val, targetWType);
2434
+ this._emitCopyIfValueStruct(val, val._type, targetWType);
2435
+ }
2436
+ this.pushInstruction("return");
2437
+ }
2438
+
2439
+ _assignToNamedReturnVar(nr) {
2440
+ const loc = this.locals.get(nr.name);
2441
+ if (loc.isBoxed) {
2442
+ const valTmp = this.acquireTemp(loc.boxInfo.wType);
2443
+ this.pushInstruction({ op: "local.set", index: valTmp });
2444
+ this.pushInstruction({ op: "local.get", index: loc.index });
2445
+ this.pushInstruction({ op: "local.get", index: valTmp });
2446
+ this.pushInstruction({
2447
+ op: "struct.set",
2448
+ typeIndex: loc.boxInfo.typeIndex,
2449
+ fieldIndex: 0,
2450
+ });
2451
+ this.releaseTemp(valTmp, loc.boxInfo.wType);
2452
+ } else {
2453
+ this.pushInstruction({ op: "local.set", index: loc.index });
2454
+ }
2455
+ }
2456
+
2457
+ emitExprStmt(stmt) {
2458
+ this.emitExpr(stmt.expr);
2459
+ const goType = stmt.expr._type;
2460
+ if (!goType || goType.name === "void") return;
2461
+ if (goType.kind === "tuple" || goType.kind === "TupleType") {
2462
+ for (const _ of goType.types ?? []) {
2463
+ this.pushInstruction("drop");
2464
+ }
2465
+ return;
2466
+ }
2467
+ const wType = this.toWasmType(goType);
2468
+ if (wType) {
2469
+ this.pushInstruction("drop");
2470
+ }
2471
+ }
2472
+ }