gofront 0.0.2 → 0.0.4

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.
@@ -0,0 +1,907 @@
1
+ // CodeGen expression methods and helpers — installed as a mixin on CodeGen.prototype.
2
+
3
+ const INT_TYPE_NAMES = new Set([
4
+ "int",
5
+ "uint",
6
+ "int8",
7
+ "int16",
8
+ "int32",
9
+ "int64",
10
+ "uint8",
11
+ "uint16",
12
+ "uint32",
13
+ "uint64",
14
+ "uintptr",
15
+ "byte",
16
+ "rune",
17
+ ]);
18
+
19
+ export const expressionGenMethods = {
20
+ genExpr(expr) {
21
+ switch (expr.kind) {
22
+ case "BasicLit":
23
+ if (expr.litKind === "STRING") return JSON.stringify(expr.value);
24
+ return expr.value; // int, float, bool, nil(null)
25
+
26
+ case "Ident":
27
+ return expr.name;
28
+
29
+ case "UnaryExpr": {
30
+ const op = expr.op === "^" ? "~" : expr.op; // bitwise NOT
31
+ // Dereference/address-of — transparent in JS
32
+ if (op === "*" || op === "&") return this.genExpr(expr.operand);
33
+ return `${op}${this.genExpr(expr.operand)}`;
34
+ }
35
+
36
+ case "BinaryExpr": {
37
+ const l = this.genExpr(expr.left);
38
+ const r = this.genExpr(expr.right);
39
+ // Integer division: only when both sides are int
40
+ if (
41
+ expr.op === "/" &&
42
+ this.isIntType(expr.left._type) &&
43
+ this.isIntType(expr.right._type)
44
+ ) {
45
+ return `Math.trunc(${l} / ${r})`;
46
+ }
47
+ // Go &^ (bit clear / AND NOT) → JS & ~
48
+ if (expr.op === "&^") {
49
+ return `${l} & ~${r}`;
50
+ }
51
+ // Struct/array equality: use __equal for value comparison
52
+ if (expr.op === "==" || expr.op === "!=") {
53
+ const lt = expr.left._type;
54
+ if (this._isStructOrArrayType(lt)) {
55
+ this._usesEqual = true;
56
+ const cmp = `__equal(${l}, ${r})`;
57
+ return expr.op === "==" ? cmp : `!${cmp}`;
58
+ }
59
+ }
60
+ // Go == and != are strict — map to JS === / !==
61
+ const op =
62
+ expr.op === "==" ? "===" : expr.op === "!=" ? "!==" : expr.op;
63
+ return `${l} ${op} ${r}`;
64
+ }
65
+
66
+ case "CallExpr":
67
+ return this.genCall(expr);
68
+
69
+ case "SelectorExpr": {
70
+ // Method expression: TypeName.MethodName → (recv, ...args) => recv.method(...args)
71
+ if (expr._isMethodExpr) {
72
+ const method = expr.field;
73
+ return `((recv, ...args) => recv.${method}(...args))`;
74
+ }
75
+ // math constants
76
+ if (expr.expr.kind === "Ident" && expr.expr.name === "math") {
77
+ switch (expr.field) {
78
+ case "Pi":
79
+ return "Math.PI";
80
+ case "E":
81
+ return "Math.E";
82
+ case "MaxFloat64":
83
+ return "Number.MAX_VALUE";
84
+ case "SmallestNonzeroFloat64":
85
+ return "Number.MIN_VALUE";
86
+ case "MaxInt":
87
+ return "Number.MAX_SAFE_INTEGER";
88
+ case "MinInt":
89
+ return "Number.MIN_SAFE_INTEGER";
90
+ }
91
+ }
92
+ // os constants/vars
93
+ if (expr.expr.kind === "Ident" && expr.expr.name === "os") {
94
+ switch (expr.field) {
95
+ case "Args":
96
+ return "process.argv";
97
+ }
98
+ }
99
+ // time constants (nanosecond durations)
100
+ if (expr.expr.kind === "Ident" && expr.expr.name === "time") {
101
+ switch (expr.field) {
102
+ case "Millisecond":
103
+ return "1000000";
104
+ case "Second":
105
+ return "1000000000";
106
+ case "Minute":
107
+ return "60000000000";
108
+ case "Hour":
109
+ return "3600000000000";
110
+ }
111
+ }
112
+ const base = this.genExpr(expr.expr);
113
+ // Bundled GoFront packages are inlined — drop the qualifier.
114
+ if (this.bundledPackages.has(base)) return expr.field;
115
+ // Pointer types are wrapped as { value: T }; route through .value
116
+ if (expr.expr._type?.kind === "pointer" && expr.field !== "value") {
117
+ const sel = `${base}.value.${expr.field}`;
118
+ if (expr._isMethodValue && !expr._callee)
119
+ return `${sel}.bind(${base}.value)`;
120
+ return sel;
121
+ }
122
+ const sel = `${base}.${expr.field}`;
123
+ // Method used as value (not called) — bind the receiver
124
+ if (expr._isMethodValue && !expr._callee) return `${sel}.bind(${base})`;
125
+ return sel;
126
+ }
127
+
128
+ case "IndexExpr": {
129
+ const base = this.genExpr(expr.expr);
130
+ const idx = this.genExpr(expr.index);
131
+ if (expr._mapValueType && !expr._lvalue) {
132
+ const zero = this.zeroValueForType(expr._mapValueType);
133
+ // Use an IIFE to avoid double-evaluating base/key when either
134
+ // could be a function call or other expression with side effects.
135
+ if (this._hasCallExpr(expr.expr) || this._hasCallExpr(expr.index)) {
136
+ return `((__m, __k) => __m[__k] ?? ${zero})(${base}, ${idx})`;
137
+ }
138
+ return `(${base}[${idx}] ?? ${zero})`;
139
+ }
140
+ // String indexing returns a byte (charCodeAt), not a JS character
141
+ const exprType = expr.expr._type;
142
+ const isStr =
143
+ (exprType?.kind === "basic" && exprType.name === "string") ||
144
+ (exprType?.kind === "untyped" && exprType.base === "string");
145
+ if (isStr && !expr._lvalue) {
146
+ return `${base}.charCodeAt(${idx})`;
147
+ }
148
+ return `${base}[${idx}]`;
149
+ }
150
+
151
+ case "SliceExpr": {
152
+ const base = this.genExpr(expr.expr);
153
+ const lo = expr.low ? this.genExpr(expr.low) : "";
154
+ const hi = expr.high ? this.genExpr(expr.high) : "";
155
+ if (!lo && !hi) return `${base}.slice()`;
156
+ if (!hi) return `${base}.slice(${lo})`;
157
+ return `${base}.slice(${lo}, ${hi})`;
158
+ }
159
+
160
+ case "CompositeLit":
161
+ return this.genCompositeLit(expr);
162
+
163
+ case "FuncLit": {
164
+ const params = expr.params.map((p) => p.name).join(", ");
165
+ const asyncPrefix = expr.async ? "async " : "";
166
+ const saved = this.out;
167
+ this.out = [];
168
+ this.indented(() => this._genBody(expr.body));
169
+ const body = this.out.join("\n");
170
+ this.out = saved;
171
+ return `${asyncPrefix}function(${params}) {\n${body}\n${" ".repeat(this.indent)}}`;
172
+ }
173
+
174
+ case "TypeConversion": {
175
+ const inner = this.genExpr(expr.expr);
176
+ const t = expr.targetType;
177
+
178
+ // Slice type conversions
179
+ if (t?.kind === "SliceType") {
180
+ const elem = t.elem?.name;
181
+ // []byte(s) → UTF-8 byte array
182
+ if (elem === "byte" || elem === "uint8") {
183
+ return `Array.from(new TextEncoder().encode(${inner}))`;
184
+ }
185
+ // []rune(s) → Unicode code point array (only when source is a string)
186
+ if (elem === "rune" || elem === "int32" || elem === "int") {
187
+ const srcType = expr.expr._type;
188
+ if (
189
+ (srcType?.kind === "basic" && srcType?.name === "string") ||
190
+ (srcType?.kind === "untyped" && srcType?.base === "string")
191
+ ) {
192
+ return `Array.from(${inner}, __c => __c.codePointAt(0))`;
193
+ }
194
+ return `Array.from(${inner})`;
195
+ }
196
+ return `Array.from(${inner})`;
197
+ }
198
+
199
+ const target = t?.name;
200
+ switch (target) {
201
+ case "string": {
202
+ // Go string(65) → "A" (Unicode code point), not "65"
203
+ const srcType = expr.expr._type;
204
+ if (srcType && this.isIntType(srcType)) {
205
+ return `String.fromCodePoint(${inner})`;
206
+ }
207
+ return `String(${inner})`;
208
+ }
209
+ case "int":
210
+ case "byte":
211
+ case "rune":
212
+ return `Math.trunc(Number(${inner}))`;
213
+ case "float64":
214
+ return `Number(${inner})`;
215
+ case "bool":
216
+ return `Boolean(${inner})`;
217
+ default:
218
+ return inner;
219
+ }
220
+ }
221
+
222
+ case "TypeAssertExpr": {
223
+ const val = this.genExpr(expr.expr);
224
+ const check = this._typeCheckExpr(expr.type, val);
225
+ if (!expr._commaOk) {
226
+ // plain assertion: panic if check fails (matches Go behavior)
227
+ if (check === "true") return val; // can't check at runtime — pass through
228
+ return `(${check} ? ${val} : (() => { throw new Error("interface conversion: type assertion failed"); })())`;
229
+ }
230
+ // comma-ok: emit [value-or-zero, runtimeTypeCheck]
231
+ const zero = this.zeroValueForTypeNode(expr.type);
232
+ return `(${check} ? [${val}, true] : [${zero}, false])`;
233
+ }
234
+
235
+ case "AwaitExpr":
236
+ return `await ${this.genExpr(expr.expr)}`;
237
+
238
+ case "RangeExpr":
239
+ return this.genExpr(expr.expr);
240
+
241
+ default:
242
+ throw new Error(`CodeGen: unhandled expression kind '${expr.kind}'`);
243
+ }
244
+ },
245
+
246
+ genCall(expr) {
247
+ // Handle built-ins that need special JS translation
248
+ if (expr.func.kind === "Ident") {
249
+ switch (expr.func.name) {
250
+ case "append":
251
+ return this.genAppend(expr);
252
+ case "len": {
253
+ const arg = expr.args[0];
254
+ const t = arg?._type;
255
+ const js = this.genExpr(arg);
256
+ if (t?.kind === "map") return `Object.keys(${js}).length`;
257
+ this._usesLen = true;
258
+ return `__len(${js})`;
259
+ }
260
+ case "cap":
261
+ return `${this.genExpr(expr.args[0])}.length`;
262
+ case "make":
263
+ return this.genMake(expr);
264
+ case "delete": {
265
+ const [m, k] = expr.args.map((a) => this.genExpr(a));
266
+ return `(delete ${m}[${k}])`;
267
+ }
268
+ case "copy": {
269
+ const [dst, src] = expr.args.map((a) => this.genExpr(a));
270
+ return `((__cd,__cs)=>{const n=Math.min(__cd.length,__cs.length);__cd.splice(0,n,...__cs.slice(0,n));return n;})(${dst},${src})`;
271
+ }
272
+ case "new": {
273
+ const zero = this.zeroValueForExpr(expr.args[0]);
274
+ return `{ value: ${zero} }`;
275
+ }
276
+ case "print":
277
+ case "println": {
278
+ const args = expr.args.map((a) => this.genExpr(a)).join(", ");
279
+ return `console.log(${args})`;
280
+ }
281
+ case "panic": {
282
+ const arg = this.genExpr(expr.args[0]);
283
+ return `(() => { throw new Error(${arg}); })()`;
284
+ }
285
+ case "recover":
286
+ return `(typeof __panic !== "undefined" && __panic !== null ? (() => { const __r = __panic.message ?? String(__panic); __panic = null; return __r; })() : null)`;
287
+ case "error": {
288
+ // errors are plain strings; nil (null) means no error
289
+ const arg = this.genExpr(expr.args[0]);
290
+ return arg;
291
+ }
292
+ case "min": {
293
+ const args = expr.args.map((a) => this.genExpr(a)).join(", ");
294
+ return `Math.min(${args})`;
295
+ }
296
+ case "max": {
297
+ const args = expr.args.map((a) => this.genExpr(a)).join(", ");
298
+ return `Math.max(${args})`;
299
+ }
300
+ case "clear": {
301
+ const arg = expr.args[0];
302
+ const t = arg?._type;
303
+ const js = this.genExpr(arg);
304
+ if (
305
+ t?.kind === "map" ||
306
+ (t?.kind === "named" && t.underlying?.kind === "map")
307
+ ) {
308
+ return `((__m) => { for (const __k in __m) delete __m[__k]; })(${js})`;
309
+ }
310
+ return `(${js}).length = 0`;
311
+ }
312
+ }
313
+ }
314
+
315
+ // error.Error() → the error string itself (errors are plain strings at runtime)
316
+ if (
317
+ expr.func.kind === "SelectorExpr" &&
318
+ expr.func.field === "Error" &&
319
+ expr.func.expr._type?.name === "error"
320
+ ) {
321
+ return this.genExpr(expr.func.expr);
322
+ }
323
+
324
+ // fmt.Sprintf / fmt.Printf / fmt.Println / fmt.Print / fmt.Errorf
325
+ if (
326
+ expr.func.kind === "SelectorExpr" &&
327
+ expr.func.expr.kind === "Ident" &&
328
+ expr.func.expr.name === "fmt"
329
+ ) {
330
+ const fmtArgs = expr.args.map((a) => this.genExpr(a)).join(", ");
331
+ switch (expr.func.field) {
332
+ case "Sprintf":
333
+ case "Errorf":
334
+ this._usesSprintf = true;
335
+ return `__sprintf(${fmtArgs})`;
336
+ case "Printf":
337
+ case "Print":
338
+ this._usesSprintf = true;
339
+ return `process?.stdout?.write(__sprintf(${fmtArgs}))`;
340
+ case "Println":
341
+ this._usesSprintf = true;
342
+ return `console.log(__sprintf(${fmtArgs}))`;
343
+ }
344
+ }
345
+
346
+ // strings.* — direct JS string method mappings
347
+ if (
348
+ expr.func.kind === "SelectorExpr" &&
349
+ expr.func.expr.kind === "Ident" &&
350
+ expr.func.expr.name === "strings"
351
+ ) {
352
+ const a = expr.args.map((e) => this.genExpr(e));
353
+ switch (expr.func.field) {
354
+ case "Contains":
355
+ return `${a[0]}.includes(${a[1]})`;
356
+ case "HasPrefix":
357
+ return `${a[0]}.startsWith(${a[1]})`;
358
+ case "HasSuffix":
359
+ return `${a[0]}.endsWith(${a[1]})`;
360
+ case "Index":
361
+ return `${a[0]}.indexOf(${a[1]})`;
362
+ case "LastIndex":
363
+ return `${a[0]}.lastIndexOf(${a[1]})`;
364
+ case "Count":
365
+ return `${a[0]}.split(${a[1]}).length - 1`;
366
+ case "Repeat":
367
+ return `${a[0]}.repeat(${a[1]})`;
368
+ case "Replace":
369
+ return `${a[0]}.replace(${a[1]}, ${a[2]})`;
370
+ case "ReplaceAll":
371
+ return `${a[0]}.replaceAll(${a[1]}, ${a[2]})`;
372
+ case "ToUpper":
373
+ return `${a[0]}.toUpperCase()`;
374
+ case "ToLower":
375
+ return `${a[0]}.toLowerCase()`;
376
+ case "TrimSpace":
377
+ return `${a[0]}.trim()`;
378
+ case "Trim":
379
+ return `${a[0]}.replace(new RegExp(\`^[\${${a[1]}}]+|[\${${a[1]}}]+$\`, "g"), "")`;
380
+ case "TrimPrefix":
381
+ return `(${a[0]}.startsWith(${a[1]}) ? ${a[0]}.slice(${a[1]}.length) : ${a[0]})`;
382
+ case "TrimSuffix":
383
+ return `(${a[0]}.endsWith(${a[1]}) ? ${a[0]}.slice(0, -${a[1]}.length) : ${a[0]})`;
384
+ case "TrimLeft":
385
+ return `${a[0]}.replace(new RegExp(\`^[\${${a[1]}}]+\`), "")`;
386
+ case "TrimRight":
387
+ return `${a[0]}.replace(new RegExp(\`[\${${a[1]}}]+$\`), "")`;
388
+ case "Split":
389
+ return `${a[0]}.split(${a[1]})`;
390
+ case "Join":
391
+ return `${a[0]}.join(${a[1]})`;
392
+ case "EqualFold":
393
+ return `${a[0]}.toLowerCase() === ${a[1]}.toLowerCase()`;
394
+ }
395
+ }
396
+
397
+ // strconv.* — number/string conversion
398
+ if (
399
+ expr.func.kind === "SelectorExpr" &&
400
+ expr.func.expr.kind === "Ident" &&
401
+ expr.func.expr.name === "strconv"
402
+ ) {
403
+ const a = expr.args.map((e) => this.genExpr(e));
404
+ switch (expr.func.field) {
405
+ case "Itoa":
406
+ return `String(${a[0]})`;
407
+ case "Atoi":
408
+ return `(Number.isNaN(Number(${a[0]})) ? [0, "invalid syntax"] : [Number(${a[0]}) | 0, null])`;
409
+ case "FormatBool":
410
+ return `String(${a[0]})`;
411
+ case "FormatInt":
412
+ return `(${a[0]}).toString(${a[1]})`;
413
+ case "FormatFloat":
414
+ return `String(${a[0]})`;
415
+ case "ParseFloat":
416
+ return `(Number.isNaN(Number(${a[0]})) ? [0, "invalid syntax"] : [Number(${a[0]}), null])`;
417
+ case "ParseInt":
418
+ return `(Number.isNaN(parseInt(${a[0]}, ${a[1]} || 10)) ? [0, "invalid syntax"] : [parseInt(${a[0]}, ${a[1]} || 10), null])`;
419
+ case "ParseBool":
420
+ return `(${a[0]} === "true" || ${a[0]} === "1" ? [true, null] : ${a[0]} === "false" || ${a[0]} === "0" ? [false, null] : [false, "invalid syntax"])`;
421
+ }
422
+ }
423
+
424
+ // sort.* — in-place sorting
425
+ if (
426
+ expr.func.kind === "SelectorExpr" &&
427
+ expr.func.expr.kind === "Ident" &&
428
+ expr.func.expr.name === "sort"
429
+ ) {
430
+ const a = expr.args.map((e) => this.genExpr(e));
431
+ switch (expr.func.field) {
432
+ case "Ints":
433
+ case "Float64s":
434
+ return `${a[0]}.sort((a, b) => a - b)`;
435
+ case "Strings":
436
+ return `${a[0]}.sort()`;
437
+ case "Slice":
438
+ return `${a[0]}.sort((a, b) => ${a[1]}(a, b) ? -1 : ${a[1]}(b, a) ? 1 : 0)`;
439
+ case "SliceStable":
440
+ return `${a[0]}.sort((a, b) => ${a[1]}(a, b) ? -1 : ${a[1]}(b, a) ? 1 : 0)`;
441
+ case "SliceIsSorted":
442
+ return `${a[0]}.every((v, i, a) => i === 0 || ${a[1]}(a[i - 1], v))`;
443
+ }
444
+ }
445
+
446
+ // math.* — math functions
447
+ if (
448
+ expr.func.kind === "SelectorExpr" &&
449
+ expr.func.expr.kind === "Ident" &&
450
+ expr.func.expr.name === "math"
451
+ ) {
452
+ const a = expr.args.map((e) => this.genExpr(e));
453
+ switch (expr.func.field) {
454
+ case "Abs":
455
+ return `Math.abs(${a[0]})`;
456
+ case "Floor":
457
+ return `Math.floor(${a[0]})`;
458
+ case "Ceil":
459
+ return `Math.ceil(${a[0]})`;
460
+ case "Round":
461
+ return `Math.round(${a[0]})`;
462
+ case "Sqrt":
463
+ return `Math.sqrt(${a[0]})`;
464
+ case "Cbrt":
465
+ return `Math.cbrt(${a[0]})`;
466
+ case "Pow":
467
+ return `Math.pow(${a[0]}, ${a[1]})`;
468
+ case "Log":
469
+ return `Math.log(${a[0]})`;
470
+ case "Log2":
471
+ return `Math.log2(${a[0]})`;
472
+ case "Log10":
473
+ return `Math.log10(${a[0]})`;
474
+ case "Sin":
475
+ return `Math.sin(${a[0]})`;
476
+ case "Cos":
477
+ return `Math.cos(${a[0]})`;
478
+ case "Tan":
479
+ return `Math.tan(${a[0]})`;
480
+ case "Min":
481
+ return `Math.min(${a[0]}, ${a[1]})`;
482
+ case "Max":
483
+ return `Math.max(${a[0]}, ${a[1]})`;
484
+ case "Mod":
485
+ return `${a[0]} % ${a[1]}`;
486
+ case "Inf":
487
+ return `(${a[0]} >= 0 ? Infinity : -Infinity)`;
488
+ case "IsNaN":
489
+ return `Number.isNaN(${a[0]})`;
490
+ case "IsInf":
491
+ return `(${a[1]} > 0 ? ${a[0]} === Infinity : ${a[1]} < 0 ? ${a[0]} === -Infinity : !Number.isFinite(${a[0]}))`;
492
+ case "NaN":
493
+ return "NaN";
494
+ }
495
+ }
496
+
497
+ // unicode.* — rune/character classification
498
+ if (
499
+ expr.func.kind === "SelectorExpr" &&
500
+ expr.func.expr.kind === "Ident" &&
501
+ expr.func.expr.name === "unicode"
502
+ ) {
503
+ const a = expr.args.map((e) => this.genExpr(e));
504
+ switch (expr.func.field) {
505
+ case "IsLetter":
506
+ return `/\\p{L}/u.test(String.fromCodePoint(${a[0]}))`;
507
+ case "IsDigit":
508
+ return `/\\p{Nd}/u.test(String.fromCodePoint(${a[0]}))`;
509
+ case "IsSpace":
510
+ return `/\\s/.test(String.fromCodePoint(${a[0]}))`;
511
+ case "IsUpper":
512
+ return `((__c) => __c === __c.toUpperCase() && /\\p{L}/u.test(__c))(String.fromCodePoint(${a[0]}))`;
513
+ case "IsLower":
514
+ return `((__c) => __c === __c.toLowerCase() && /\\p{L}/u.test(__c))(String.fromCodePoint(${a[0]}))`;
515
+ case "IsPunct":
516
+ return `/\\p{P}/u.test(String.fromCodePoint(${a[0]}))`;
517
+ case "IsControl":
518
+ return `/\\p{Cc}/u.test(String.fromCodePoint(${a[0]}))`;
519
+ case "IsPrint":
520
+ return `!/\\p{Cc}/u.test(String.fromCodePoint(${a[0]}))`;
521
+ case "IsGraphic":
522
+ return `!/\\p{Cc}/u.test(String.fromCodePoint(${a[0]}))`;
523
+ case "ToUpper":
524
+ return `String.fromCodePoint(${a[0]}).toUpperCase().codePointAt(0)`;
525
+ case "ToLower":
526
+ return `String.fromCodePoint(${a[0]}).toLowerCase().codePointAt(0)`;
527
+ }
528
+ }
529
+
530
+ // os.* — process/environment access
531
+ if (
532
+ expr.func.kind === "SelectorExpr" &&
533
+ expr.func.expr.kind === "Ident" &&
534
+ expr.func.expr.name === "os"
535
+ ) {
536
+ const a = expr.args.map((e) => this.genExpr(e));
537
+ switch (expr.func.field) {
538
+ case "Exit":
539
+ return `process.exit(${a[0]})`;
540
+ case "Getenv":
541
+ return `(process.env[${a[0]}] ?? "")`;
542
+ }
543
+ }
544
+
545
+ // errors.New — identity (errors are plain strings)
546
+ if (
547
+ expr.func.kind === "SelectorExpr" &&
548
+ expr.func.expr.kind === "Ident" &&
549
+ expr.func.expr.name === "errors"
550
+ ) {
551
+ const a = expr.args.map((e) => this.genExpr(e));
552
+ if (expr.func.field === "New") return a[0];
553
+ }
554
+
555
+ // time.* — partial JS-friendly time support
556
+ if (
557
+ expr.func.kind === "SelectorExpr" &&
558
+ expr.func.expr.kind === "Ident" &&
559
+ expr.func.expr.name === "time"
560
+ ) {
561
+ const a = expr.args.map((e) => this.genExpr(e));
562
+ switch (expr.func.field) {
563
+ case "Now":
564
+ return "Date.now()";
565
+ case "Since":
566
+ return `(Date.now() - ${a[0]})`;
567
+ case "Sleep":
568
+ return `await new Promise(r => setTimeout(r, ${a[0]} / 1000000))`;
569
+ }
570
+ }
571
+
572
+ // Mark the callee so SelectorExpr knows it's being called, not used as a value
573
+ expr.func._callee = true;
574
+ const rawFn = this.genExpr(expr.func);
575
+ // Wrap function literals in parens so `function(){}()` → `(function(){})()`
576
+ const fn = expr.func.kind === "FuncLit" ? `(${rawFn})` : rawFn;
577
+ // Multi-value forwarding: f(g()) where g() returns multiple values → f(...g())
578
+ if (expr._multiForward) {
579
+ return `${fn}(...${this.genExpr(expr.args[0])})`;
580
+ }
581
+ const args = expr.args
582
+ .map((a) => (a._spread ? `...${this.genExpr(a)}` : this.genExpr(a)))
583
+ .join(", ");
584
+ return `${fn}(${args})`;
585
+ },
586
+
587
+ genAppend(expr) {
588
+ const slice = this.genExpr(expr.args[0]);
589
+ const elems = expr.args
590
+ .slice(1)
591
+ .map((a) => (a._spread ? `...${this.genExpr(a)}` : this.genExpr(a)));
592
+ if (elems.length === 0) return slice;
593
+ this._usesAppend = true;
594
+ return `__append(${slice}, ${elems.join(", ")})`;
595
+ },
596
+
597
+ genMake(expr) {
598
+ // make([]T, n) or make([]T, n, cap) → new Array(n).fill(zero)
599
+ // make(map[K]V) → {}
600
+ const typeArg = expr.args[0];
601
+ const typeNode = typeArg.kind === "TypeExpr" ? typeArg.type : typeArg;
602
+ const resolvedKind = typeArg._type?.kind;
603
+ if (typeNode.kind === "SliceType" || resolvedKind === "slice") {
604
+ const n = expr.args[1] ? this.genExpr(expr.args[1]) : "0";
605
+ // Use the proper zero value for the element type (e.g. new Point() not 0)
606
+ const elemNode = typeNode.kind === "SliceType" ? typeNode.elem : null;
607
+ const elemResolved =
608
+ typeArg._type?.kind === "slice" ? typeArg._type.elem : null;
609
+ let zero = "null";
610
+ if (elemResolved) {
611
+ zero = this.zeroValueForType(elemResolved);
612
+ } else if (elemNode) {
613
+ zero = this.zeroValueForTypeNode(elemNode);
614
+ }
615
+ // If zero value is a constructor call, use a factory function so each element is distinct
616
+ if (zero.startsWith("new ")) {
617
+ return `Array.from({length: ${n}}, () => ${zero})`;
618
+ }
619
+ return `new Array(${n}).fill(${zero})`;
620
+ }
621
+ // map or fallback
622
+ return "{}";
623
+ },
624
+
625
+ // Render struct elements as a JS field list string.
626
+ // Handles positional (_positionalField), embedded-spread (_isEmbedInit), and keyed (KeyValueExpr).
627
+ _genStructFields(elems) {
628
+ return elems
629
+ .map((e) => {
630
+ if (e._positionalField) {
631
+ return `${e._positionalField}: ${this.genExpr(e)}`;
632
+ }
633
+ if (e.kind !== "KeyValueExpr") return null;
634
+ if (e._isEmbedInit) return `...${this.genExpr(e.value)}`;
635
+ return `${e.key.name ?? this.genExpr(e.key)}: ${this.genExpr(e.value)}`;
636
+ })
637
+ .filter((s) => s !== null)
638
+ .join(", ");
639
+ },
640
+
641
+ genCompositeLit(expr) {
642
+ const t = expr.typeExpr;
643
+
644
+ // Implicit composite literal: {X: 1} or {1, 2} inside a slice/map — type inferred from context
645
+ if (t === null) {
646
+ const typeName = expr._type?.name ?? expr._type?.underlying?.name;
647
+ const hasPositional = expr.elems.some((e) => e._positionalField);
648
+ const hasKeyed = expr.elems.some((e) => e.kind === "KeyValueExpr");
649
+ if (hasPositional || hasKeyed) {
650
+ if (typeName && this.structNames.has(typeName)) {
651
+ return `new ${typeName}({ ${this._genStructFields(expr.elems)} })`;
652
+ }
653
+ const fields = expr.elems
654
+ .map((e) => {
655
+ if (e._positionalField)
656
+ return `${e._positionalField}: ${this.genExpr(e)}`;
657
+ return `${e.key.name ?? this.genExpr(e.key)}: ${this.genExpr(e.value)}`;
658
+ })
659
+ .join(", ");
660
+ return `{ ${fields} }`;
661
+ }
662
+ return `[${expr.elems.map((e) => this.genExpr(e)).join(", ")}]`;
663
+ }
664
+
665
+ const typeName = this.getTypeName(t);
666
+
667
+ // Struct: new Foo({ X: 1, Y: 2 }) — keyed or positional
668
+ if (typeName && this.structNames.has(typeName)) {
669
+ return `new ${typeName}({ ${this._genStructFields(expr.elems)} })`;
670
+ }
671
+
672
+ // Fallback: named type that's not a struct but has positional elements → treat as struct
673
+ if (expr.elems.some((e) => e._positionalField)) {
674
+ if (typeName) {
675
+ return `new ${typeName}({ ${this._genStructFields(expr.elems)} })`;
676
+ }
677
+ }
678
+
679
+ // Slice/array: [1, 2, 3]
680
+ if (t?.kind === "SliceType" || t?.kind === "ArrayType") {
681
+ const elems = expr.elems
682
+ .map((e) =>
683
+ e.kind === "KeyValueExpr" ? this.genExpr(e.value) : this.genExpr(e),
684
+ )
685
+ .join(", ");
686
+ return `[${elems}]`;
687
+ }
688
+
689
+ // Map: { key: value }
690
+ if (t?.kind === "MapType") {
691
+ const entries = expr.elems
692
+ .map((e) => {
693
+ if (e.kind === "KeyValueExpr") {
694
+ const k =
695
+ e.key.litKind === "STRING"
696
+ ? JSON.stringify(e.key.value)
697
+ : `[${this.genExpr(e.key)}]`;
698
+ return `${k}: ${this.genExpr(e.value)}`;
699
+ }
700
+ return this.genExpr(e);
701
+ })
702
+ .join(", ");
703
+ return `{ ${entries} }`;
704
+ }
705
+
706
+ // Fallback: key-value pairs → plain object, positional → array
707
+ if (expr.elems.length > 0 && expr.elems[0]?.kind === "KeyValueExpr") {
708
+ const fields = expr.elems
709
+ .map(
710
+ (e) =>
711
+ `${e.key.name ?? this.genExpr(e.key)}: ${this.genExpr(e.value)}`,
712
+ )
713
+ .join(", ");
714
+ return `{ ${fields} }`;
715
+ }
716
+ return `[${expr.elems.map((e) => this.genExpr(e)).join(", ")}]`;
717
+ },
718
+
719
+ // ── Helpers ───────────────────────────────────────────────────
720
+
721
+ getTypeName(typeNode) {
722
+ if (!typeNode) return null;
723
+ if (typeNode.kind === "TypeName") return typeNode.name;
724
+ if (typeNode.kind === "Ident") return typeNode.name;
725
+ if (typeNode.kind === "SelectorExpr") return typeNode.field;
726
+ return null;
727
+ },
728
+
729
+ isIntType(t) {
730
+ if (!t) return false;
731
+ if (t.kind === "untyped") return t.base === "int";
732
+ const base = t.kind === "named" ? t.underlying : t;
733
+ return base?.kind === "basic" && INT_TYPE_NAMES.has(base.name);
734
+ },
735
+
736
+ // Returns true if the AST node contains a function call (side-effect risk).
737
+ _hasCallExpr(node) {
738
+ if (!node || typeof node !== "object") return false;
739
+ if (node.kind === "CallExpr") return true;
740
+ for (const v of Object.values(node)) {
741
+ if (v && typeof v === "object" && this._hasCallExpr(v)) return true;
742
+ }
743
+ return false;
744
+ },
745
+
746
+ // Returns the JS zero-value literal for a basic type name, or null if not a basic type.
747
+ _zeroForBasicName(name) {
748
+ switch (name) {
749
+ case "int":
750
+ case "uint":
751
+ case "int8":
752
+ case "int16":
753
+ case "int32":
754
+ case "int64":
755
+ case "uint8":
756
+ case "uint16":
757
+ case "uint32":
758
+ case "uint64":
759
+ case "uintptr":
760
+ case "float32":
761
+ case "float64":
762
+ case "byte":
763
+ case "rune":
764
+ return "0";
765
+ case "string":
766
+ return '""';
767
+ case "bool":
768
+ return "false";
769
+ default:
770
+ return null;
771
+ }
772
+ },
773
+
774
+ zeroValueForTypeNode(typeNode) {
775
+ if (!typeNode) return "null";
776
+ switch (typeNode.kind) {
777
+ case "TypeName": {
778
+ const basic = this._zeroForBasicName(typeNode.name);
779
+ if (basic !== null) return basic;
780
+ if (this.structNames.has(typeNode.name))
781
+ return `new ${typeNode.name}()`;
782
+ return "null";
783
+ }
784
+ case "SliceType":
785
+ return "null";
786
+ case "ArrayType":
787
+ return "[]";
788
+ case "MapType":
789
+ return "{}";
790
+ case "PointerType":
791
+ return "null";
792
+ case "StructType": {
793
+ const fields = typeNode.fields
794
+ .filter((f) => !f.embedded && f.names.length > 0)
795
+ .map(
796
+ (f) =>
797
+ `${f.names.map((n) => `${n}: ${this.zeroValueForTypeNode(f.type)}`).join(", ")}`,
798
+ )
799
+ .join(", ");
800
+ return `{ ${fields} }`;
801
+ }
802
+ default:
803
+ return "null";
804
+ }
805
+ },
806
+
807
+ // zeroValueForType operates on typechecker type objects (not AST type nodes).
808
+ zeroValueForType(t) {
809
+ if (!t) return "null";
810
+ switch (t.kind) {
811
+ case "basic":
812
+ return this._zeroForBasicName(t.name) ?? "null";
813
+ case "slice":
814
+ return "null";
815
+ case "map":
816
+ return "{}";
817
+ case "struct": {
818
+ const fields = [...t.fields.entries()]
819
+ .map(([name, ft]) => `${name}: ${this.zeroValueForType(ft)}`)
820
+ .join(", ");
821
+ return `{ ${fields} }`;
822
+ }
823
+ case "named":
824
+ if (this.structNames.has(t.name)) return `new ${t.name}()`;
825
+ return "null";
826
+ default:
827
+ return "null";
828
+ }
829
+ },
830
+
831
+ // Emit a JS boolean expression that checks whether `val` matches type node `t`.
832
+ _typeCheckExpr(typeNode, val) {
833
+ if (!typeNode) return "true";
834
+ if (typeNode.kind === "TypeName") {
835
+ switch (typeNode.name) {
836
+ case "int":
837
+ case "uint":
838
+ case "int8":
839
+ case "int16":
840
+ case "int32":
841
+ case "int64":
842
+ case "uint8":
843
+ case "uint16":
844
+ case "uint32":
845
+ case "uint64":
846
+ case "uintptr":
847
+ case "float32":
848
+ case "float64":
849
+ case "byte":
850
+ case "rune":
851
+ return `typeof ${val} === "number"`;
852
+ case "string":
853
+ return `typeof ${val} === "string"`;
854
+ case "bool":
855
+ return `typeof ${val} === "boolean"`;
856
+ case "nil":
857
+ return `${val} === null`;
858
+ case "error":
859
+ return `typeof ${val} === "string"`;
860
+ default:
861
+ if (this.structNames.has(typeNode.name))
862
+ return `${val} instanceof ${typeNode.name}`;
863
+ return "true"; // unknown type — can't check at runtime
864
+ }
865
+ }
866
+ return "true";
867
+ },
868
+
869
+ zeroValueForExpr(expr) {
870
+ // For new(T) calls
871
+ if (expr.kind === "Ident") {
872
+ switch (expr.name) {
873
+ case "int":
874
+ case "float64":
875
+ return "0";
876
+ case "string":
877
+ return '""';
878
+ case "bool":
879
+ return "false";
880
+ default:
881
+ if (this.structNames.has(expr.name)) return `new ${expr.name}()`;
882
+ }
883
+ }
884
+ return "null";
885
+ },
886
+
887
+ // Returns true if the type is a struct or array (uses value comparison with __equal).
888
+ _isStructOrArrayType(t) {
889
+ if (!t) return false;
890
+ const base = t.kind === "named" ? t.underlying : t;
891
+ return base?.kind === "struct" || base?.kind === "array";
892
+ },
893
+
894
+ typeComment(typeNode) {
895
+ if (!typeNode) return "unknown";
896
+ switch (typeNode.kind) {
897
+ case "TypeName":
898
+ return typeNode.name;
899
+ case "SliceType":
900
+ return `[]${this.typeComment(typeNode.elem)}`;
901
+ case "MapType":
902
+ return `map[${this.typeComment(typeNode.key)}]${this.typeComment(typeNode.value)}`;
903
+ default:
904
+ return typeNode.kind;
905
+ }
906
+ },
907
+ };