-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalls.ts
More file actions
1323 lines (1150 loc) · 49.8 KB
/
calls.ts
File metadata and controls
1323 lines (1150 loc) · 49.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// NOTE: This file uses raw ctx.emit() extensively. Prefer structured IR builders
// (emitStore, emitLoad, emitCall, etc.) when modifying — see .claude/rules.md.
import {
CallNode,
FunctionNode,
VariableNode,
FunctionParameter,
ClassNode,
} from "../../ast/types.js";
import { IGeneratorContext } from "../infrastructure/generator-context.js";
import {
stripNullable,
mapParamTypeToLLVM,
mapReturnTypeToLLVM,
} from "../infrastructure/type-system.js";
/**
* CallExpressionGenerator
*
* Handles function call expressions:
* - Built-in functions (httpServe, fetch, parseInt)
* - C library functions (malloc, free, socket, close, htons)
* - User-defined functions with type checking
*/
export class CallExpressionGenerator {
constructor(private ctx: IGeneratorContext) {}
private getFunctionFromAST(name: string): FunctionNode | null {
const ast = this.ctx.getAst();
if (!ast || !ast.functions) return null;
const resolvedName = this.ctx.resolveImportAlias(name);
for (let i = 0; i < ast.functions.length; i++) {
const fn = ast.functions[i] as FunctionNode;
if (fn.name === resolvedName) {
return fn;
}
}
return null;
}
/**
* Generate function call expression
* @param expr - Call expression node
* @param params - Function parameter names
*/
generate(expr: CallNode, params: string[]): string {
// Handle super() constructor call
if (expr.name === "super") {
return this.generateSuperCall(expr, params);
}
if (expr.name === "callHandler") {
const fnPtr = this.ctx.generateExpression(expr.args[0], params);
const typedFn = this.ctx.nextTemp();
const numCallArgs = expr.args.length - 1;
const argTypeList: string[] = [];
for (let ti = 0; ti < numCallArgs; ti++) {
argTypeList.push("i8*");
}
this.ctx.emit(`${typedFn} = bitcast i8* ${fnPtr} to double (${argTypeList.join(", ")})*`);
const callArgsList: string[] = [];
for (let ai = 1; ai < expr.args.length; ai++) {
const argVal = this.ctx.generateExpression(expr.args[ai], params);
callArgsList.push(`i8* ${argVal}`);
}
const callResult = this.ctx.nextTemp();
this.ctx.emit(`${callResult} = call double ${typedFn}(${callArgsList.join(", ")})`);
return fnPtr;
}
if (expr.name === "__gc_disable") {
this.ctx.emitCallVoid("@GC_disable", "");
return "0.0";
}
if (expr.name === "__gc_enable") {
this.ctx.emitCallVoid("@GC_enable", "");
return "0.0";
}
// cs_exec_passthrough(command) — run command with inherited stdio (for chad run)
if (expr.name === "cs_exec_passthrough") {
const arg0 = this.ctx.generateExpression(expr.args[0], params);
this.ctx.emitCallVoid("@cs_exec_passthrough", `i8* ${arg0}`);
return "0.0";
}
// cs_watch_loop(chad_binary, source_file, output_binary) — file watcher FFI
if (expr.name === "cs_watch_loop") {
if (expr.args.length >= 3) {
const arg0 = this.ctx.generateExpression(expr.args[0], params);
const arg1 = this.ctx.generateExpression(expr.args[1], params);
const arg2 = this.ctx.generateExpression(expr.args[2], params);
this.ctx.emitCallVoid("@cs_watch_loop", `i8* ${arg0}, i8* ${arg1}, i8* ${arg2}`);
}
return "0.0";
}
if (expr.name === "execSync") {
return this.generateExecSync(expr, params);
}
// Handle httpServe() special built-in function
if (expr.name === "httpServe") {
return this.ctx.generateHttpServe(expr, params);
}
// Handle wsBroadcast() - broadcast message to all WebSocket clients
if (expr.name === "wsBroadcast") {
return this.ctx.generateWsBroadcast(expr, params);
}
// Handle wsSend(connId, msg) - send message to a specific WebSocket connection
if (expr.name === "wsSend") {
return this.ctx.generateWsSend(expr, params);
}
if (expr.name === "parseMultipart") {
return this.ctx.generateParseMultipart(expr, params);
}
if (expr.name === "bytesResponse") {
return this.generateBytesResponse(expr, params);
}
// Handle setTimeout() - libuv timer (one-shot)
if (expr.name === "setTimeout") {
return this.generateSetTimeout(expr, params);
}
// Handle setInterval() - libuv timer (repeating)
if (expr.name === "setInterval") {
return this.generateSetInterval(expr, params);
}
// Handle test() - built-in test runner (only when called with string + arrow/function callback)
if (expr.name === "test" && expr.args.length >= 2) {
if (expr.args[1].type === "arrow_function" || expr.args[1].type === "variable") {
return this.generateTest(expr, params);
}
}
if (expr.name === "describe" && expr.args.length >= 2) {
if (expr.args[1].type === "arrow_function" || expr.args[1].type === "variable") {
return this.generateDescribe(expr, params);
}
}
// Handle clearTimeout() / clearInterval() - stop timer
if (expr.name === "clearTimeout" || expr.name === "clearInterval") {
return this.generateClearTimer(expr, params);
}
// Handle runEventLoop() - run libuv event loop
if (expr.name === "runEventLoop") {
return this.generateRunEventLoop();
}
// Handle fetch() special built-in function
// Returns a Promise that resolves to a Response object
if (expr.name === "fetch") {
if (expr.args.length < 1) {
return this.ctx.emitError("fetch() requires at least 1 argument (URL)", expr.loc);
}
const urlValue = this.ctx.generateExpression(expr.args[0], params);
this.ctx.setUsesPromises(true);
this.ctx.setUsesCurl(true);
this.ctx.setUsesJson(true);
const temp = this.ctx.emitCall("%Promise*", "@fetch_async", `i8* ${urlValue}`);
return temp;
}
// Handle parseInt(str, radix?) global function
if (expr.name === "parseInt") {
return this.generateParseInt(expr, params);
}
// Handle parseFloat(str) global function
if (expr.name === "parseFloat") {
return this.generateParseFloat(expr, params);
}
// Handle Number(value) global function
if (expr.name === "Number") {
return this.generateNumber(expr, params);
}
// Handle String(value) global function
if (expr.name === "String") {
return this.generateString(expr, params);
}
// Handle isNaN(value) global function
if (expr.name === "isNaN") {
return this.generateIsNaN(expr, params);
}
if (expr.name === "btoa") {
if (expr.args.length !== 1) {
return this.ctx.emitError("btoa() requires exactly 1 argument", expr.loc);
}
const arg = this.ctx.generateExpression(expr.args[0], params);
const result = this.ctx.emitCall("i8*", "@cs_btoa", `i8* ${arg}`);
this.ctx.setVariableType(result, "i8*");
return result;
}
if (expr.name === "atob") {
if (expr.args.length !== 1) {
return this.ctx.emitError("atob() requires exactly 1 argument", expr.loc);
}
const arg = this.ctx.generateExpression(expr.args[0], params);
const result = this.ctx.emitCall("i8*", "@cs_atob", `i8* ${arg}`);
this.ctx.setVariableType(result, "i8*");
return result;
}
if (expr.name === "encodeURIComponent") {
if (expr.args.length !== 1) {
return this.ctx.emitError("encodeURIComponent() requires exactly 1 argument", expr.loc);
}
const arg = this.ctx.generateExpression(expr.args[0], params);
const result = this.ctx.emitCall("i8*", "@cs_encode_uri_component", `i8* ${arg}`);
this.ctx.setVariableType(result, "i8*");
return result;
}
if (expr.name === "decodeURIComponent") {
if (expr.args.length !== 1) {
return this.ctx.emitError("decodeURIComponent() requires exactly 1 argument", expr.loc);
}
const arg = this.ctx.generateExpression(expr.args[0], params);
const result = this.ctx.emitCall("i8*", "@cs_decode_uri_component", `i8* ${arg}`);
this.ctx.setVariableType(result, "i8*");
return result;
}
// Handle C built-in functions with proper signatures
if (expr.name === "malloc") {
return this.generateMalloc(expr, params);
}
if (expr.name === "free") {
return this.generateFree(expr, params);
}
if (expr.name === "socket") {
return this.generateSocket(expr, params);
}
if (expr.name === "close") {
return this.generateClose(expr, params);
}
if (expr.name === "htons") {
return this.generateHtons(expr, params);
}
if (expr.name === "bind") {
return this.generateBind(expr, params);
}
if (expr.name === "listen") {
return this.generateListen(expr, params);
}
if (expr.name === "accept") {
return this.generateAccept(expr, params);
}
if (expr.name === "__ts_parse_source") {
this.ctx.setUsesTreeSitter(true);
return this.generateTsParseSource(expr, params);
}
if (expr.name === "__ts_get_root_node") {
return this.generateTsGetRootNode(expr, params);
}
if (expr.name === "__ts_node_type") {
return this.generateTsNodeType(expr, params);
}
if (expr.name === "__ts_node_child_count") {
return this.generateTsNodeChildCount(expr, params);
}
if (expr.name === "__ts_node_named_child_count") {
return this.generateTsNodeNamedChildCount(expr, params);
}
if (expr.name === "__ts_node_child") {
return this.generateTsNodeChild(expr, params);
}
if (expr.name === "__ts_node_named_child") {
return this.generateTsNodeNamedChild(expr, params);
}
if (expr.name === "__ts_node_text") {
return this.generateTsNodeText(expr, params);
}
if (expr.name === "__ts_node_is_null") {
return this.generateTsNodeIsNull(expr, params);
}
if (expr.name === "__ts_node_is_named") {
return this.generateTsNodeIsNamed(expr, params);
}
if (expr.name === "__ts_node_start_byte") {
return this.generateTsNodeStartByte(expr, params);
}
if (expr.name === "__ts_node_end_byte") {
return this.generateTsNodeEndByte(expr, params);
}
if (expr.name === "__ts_node_child_by_field_name") {
return this.generateTsNodeChildByFieldName(expr, params);
}
// Generic function call with type checking
return this.generateGenericCall(expr, params);
}
private generateParseInt(expr: CallNode, params: string[]): string {
if (expr.args.length < 1 || expr.args.length > 2) {
return this.ctx.emitError("parseInt() requires 1 or 2 arguments (string, radix?)", expr.loc);
}
// Get the string argument
const strValue = this.ctx.generateExpression(expr.args[0], params);
// Get the radix argument (default to 10 if not provided)
let radixValue: string;
if (expr.args.length === 2) {
const radixDouble = this.ctx.generateExpression(expr.args[1], params);
const dblRadix = this.ctx.ensureDouble(radixDouble);
radixValue = this.ctx.nextTemp();
this.ctx.emit(`${radixValue} = fptosi double ${dblRadix} to i32`);
} else {
// Default radix is 10
radixValue = "10";
}
// Call strtol(str, null, radix)
// strtol returns i64, we'll truncate to i32 and then convert to double
const nullPtr = this.ctx.nextTemp();
this.ctx.emit(`${nullPtr} = inttoptr i32 0 to i8**`);
const resultI64 = this.ctx.emitCall(
"i64",
"@strtol",
`i8* ${strValue}, i8** ${nullPtr}, i32 ${radixValue}`,
);
// Convert i64 to double for compatibility with ChadScript's numeric type
const resultDouble = this.ctx.nextTemp();
this.ctx.emit(`${resultDouble} = sitofp i64 ${resultI64} to double`);
return resultDouble;
}
private generateParseFloat(expr: CallNode, params: string[]): string {
if (expr.args.length !== 1) {
return this.ctx.emitError("parseFloat() requires exactly 1 argument (string)", expr.loc);
}
const strValue = this.ctx.generateExpression(expr.args[0], params);
const nullPtr = this.ctx.nextTemp();
this.ctx.emit(`${nullPtr} = inttoptr i32 0 to i8**`);
const result = this.ctx.emitCall("double", "@strtod", `i8* ${strValue}, i8** ${nullPtr}`);
return result;
}
private generateNumber(expr: CallNode, params: string[]): string {
if (expr.args.length !== 1) {
return this.ctx.emitError("Number() requires exactly 1 argument", expr.loc);
}
const arg = expr.args[0];
if (this.ctx.isStringExpression(arg)) {
const strValue = this.ctx.generateExpression(arg, params);
const nullPtr = this.ctx.nextTemp();
this.ctx.emit(`${nullPtr} = inttoptr i32 0 to i8**`);
const resultDouble = this.ctx.emitCall(
"double",
"@strtod",
`i8* ${strValue}, i8** ${nullPtr}`,
);
return resultDouble;
}
return this.ctx.generateExpression(arg, params);
}
private generateString(expr: CallNode, params: string[]): string {
if (expr.args.length !== 1) {
return this.ctx.emitError("String() requires exactly 1 argument", expr.loc);
}
const arg = expr.args[0];
if (this.ctx.isStringExpression(arg)) {
return this.ctx.generateExpression(arg, params);
}
const numValue = this.ctx.generateExpression(arg, params);
return this.ctx.stringGen.doConvertNumberToString(numValue);
}
private generateIsNaN(expr: CallNode, params: string[]): string {
if (expr.args.length !== 1) {
return this.ctx.emitError("isNaN() requires exactly 1 argument", expr.loc);
}
const arg = expr.args[0];
let doubleValue: string;
if (this.ctx.isStringExpression(arg)) {
const strValue = this.ctx.generateExpression(arg, params);
const nullPtr = this.ctx.nextTemp();
this.ctx.emit(`${nullPtr} = inttoptr i32 0 to i8**`);
doubleValue = this.ctx.emitCall("double", "@strtod", `i8* ${strValue}, i8** ${nullPtr}`);
} else {
doubleValue = this.ctx.generateExpression(arg, params);
doubleValue = this.ctx.ensureDouble(doubleValue);
}
const cmpResult = this.ctx.nextTemp();
this.ctx.emit(`${cmpResult} = fcmp uno double ${doubleValue}, ${doubleValue}`);
const resultI32 = this.ctx.nextTemp();
this.ctx.emit(`${resultI32} = zext i1 ${cmpResult} to i32`);
const resultDouble = this.ctx.nextTemp();
this.ctx.emit(`${resultDouble} = sitofp i32 ${resultI32} to double`);
return resultDouble;
}
// Bare execSync() delegates to ChildProcessGenerator via the C bridge
private generateExecSync(expr: CallNode, params: string[]): string {
return this.ctx.childProcessGen.generateBareExecSync(expr, params);
}
private generateMalloc(expr: CallNode, params: string[]): string {
const sizeDouble = this.ctx.generateExpression(expr.args[0], params);
const dblSize = this.ctx.ensureDouble(sizeDouble);
const sizeI64 = this.ctx.nextTemp();
this.ctx.emit(`${sizeI64} = fptosi double ${dblSize} to i64`);
const result = this.ctx.emitCall("i8*", "@malloc", `i64 ${sizeI64}`);
const resultI64 = this.ctx.nextTemp();
this.ctx.emit(`${resultI64} = ptrtoint i8* ${result} to i64`);
const resultDouble = this.ctx.nextTemp();
this.ctx.emit(`${resultDouble} = sitofp i64 ${resultI64} to double`);
return resultDouble;
}
private generateFree(expr: CallNode, params: string[]): string {
const ptrDouble = this.ctx.generateExpression(expr.args[0], params);
const dblPtr = this.ctx.ensureDouble(ptrDouble);
const ptrI64 = this.ctx.nextTemp();
this.ctx.emit(`${ptrI64} = fptosi double ${dblPtr} to i64`);
const ptr = this.ctx.nextTemp();
this.ctx.emit(`${ptr} = inttoptr i64 ${ptrI64} to i8*`);
this.ctx.emitCallVoid("@free", `i8* ${ptr}`);
return "0.0";
}
private generateSocket(expr: CallNode, params: string[]): string {
// socket(domain: number, type: number, protocol: number) -> i32
const domainDouble = this.ctx.generateExpression(expr.args[0], params);
const typeDouble = this.ctx.generateExpression(expr.args[1], params);
const protocolDouble = this.ctx.generateExpression(expr.args[2], params);
const dblDomain = this.ctx.ensureDouble(domainDouble);
const domain = this.ctx.nextTemp();
this.ctx.emit(`${domain} = fptosi double ${dblDomain} to i32`);
const dblType = this.ctx.ensureDouble(typeDouble);
const type = this.ctx.nextTemp();
this.ctx.emit(`${type} = fptosi double ${dblType} to i32`);
const dblProtocol = this.ctx.ensureDouble(protocolDouble);
const protocol = this.ctx.nextTemp();
this.ctx.emit(`${protocol} = fptosi double ${dblProtocol} to i32`);
const resultI32 = this.ctx.emitCall(
"i32",
"@socket",
`i32 ${domain}, i32 ${type}, i32 ${protocol}`,
);
const resultDouble = this.ctx.nextTemp();
this.ctx.emit(`${resultDouble} = sitofp i32 ${resultI32} to double`);
return resultDouble;
}
private generateClose(expr: CallNode, params: string[]): string {
// close(fd: number) -> i32
const fdDouble = this.ctx.generateExpression(expr.args[0], params);
const dblFd = this.ctx.ensureDouble(fdDouble);
const fd = this.ctx.nextTemp();
this.ctx.emit(`${fd} = fptosi double ${dblFd} to i32`);
const resultI32 = this.ctx.emitCall("i32", "@close", `i32 ${fd}`);
const resultDouble = this.ctx.nextTemp();
this.ctx.emit(`${resultDouble} = sitofp i32 ${resultI32} to double`);
return resultDouble;
}
private generateHtons(expr: CallNode, params: string[]): string {
const hostshortDouble = this.ctx.generateExpression(expr.args[0], params);
const dblHostshort = this.ctx.ensureDouble(hostshortDouble);
const hostshort = this.ctx.nextTemp();
this.ctx.emit(`${hostshort} = fptosi double ${dblHostshort} to i16`);
const hi = this.ctx.nextTemp();
this.ctx.emit(`${hi} = lshr i16 ${hostshort}, 8`);
const lo = this.ctx.nextTemp();
this.ctx.emit(`${lo} = shl i16 ${hostshort}, 8`);
const resultI16 = this.ctx.nextTemp();
this.ctx.emit(`${resultI16} = or i16 ${hi}, ${lo}`);
const resultI32 = this.ctx.nextTemp();
this.ctx.emit(`${resultI32} = zext i16 ${resultI16} to i32`);
const resultDouble = this.ctx.nextTemp();
this.ctx.emit(`${resultDouble} = sitofp i32 ${resultI32} to double`);
return resultDouble;
}
private generateBind(expr: CallNode, params: string[]): string {
const fdDouble = this.ctx.generateExpression(expr.args[0], params);
const addrDouble = this.ctx.generateExpression(expr.args[1], params);
const addrlenDouble = this.ctx.generateExpression(expr.args[2], params);
const dblFd2 = this.ctx.ensureDouble(fdDouble);
const fd = this.ctx.nextTemp();
this.ctx.emit(`${fd} = fptosi double ${dblFd2} to i32`);
const dblAddr = this.ctx.ensureDouble(addrDouble);
const addrI64 = this.ctx.nextTemp();
this.ctx.emit(`${addrI64} = fptosi double ${dblAddr} to i64`);
const addr = this.ctx.nextTemp();
this.ctx.emit(`${addr} = inttoptr i64 ${addrI64} to i8*`);
const dblAddrlen = this.ctx.ensureDouble(addrlenDouble);
const addrlen = this.ctx.nextTemp();
this.ctx.emit(`${addrlen} = fptosi double ${dblAddrlen} to i32`);
const resultI32 = this.ctx.emitCall("i32", "@bind", `i32 ${fd}, i8* ${addr}, i32 ${addrlen}`);
const resultDouble = this.ctx.nextTemp();
this.ctx.emit(`${resultDouble} = sitofp i32 ${resultI32} to double`);
return resultDouble;
}
private generateListen(expr: CallNode, params: string[]): string {
const fdDouble = this.ctx.generateExpression(expr.args[0], params);
const backlogDouble = this.ctx.generateExpression(expr.args[1], params);
const dblFd3 = this.ctx.ensureDouble(fdDouble);
const fd = this.ctx.nextTemp();
this.ctx.emit(`${fd} = fptosi double ${dblFd3} to i32`);
const dblBacklog = this.ctx.ensureDouble(backlogDouble);
const backlog = this.ctx.nextTemp();
this.ctx.emit(`${backlog} = fptosi double ${dblBacklog} to i32`);
const resultI32 = this.ctx.emitCall("i32", "@listen", `i32 ${fd}, i32 ${backlog}`);
const resultDouble = this.ctx.nextTemp();
this.ctx.emit(`${resultDouble} = sitofp i32 ${resultI32} to double`);
return resultDouble;
}
private generateAccept(expr: CallNode, params: string[]): string {
const fdDouble = this.ctx.generateExpression(expr.args[0], params);
const addrDouble = this.ctx.generateExpression(expr.args[1], params);
const addrlenDouble = this.ctx.generateExpression(expr.args[2], params);
const dblFd4 = this.ctx.ensureDouble(fdDouble);
const fd = this.ctx.nextTemp();
this.ctx.emit(`${fd} = fptosi double ${dblFd4} to i32`);
const dblAddr2 = this.ctx.ensureDouble(addrDouble);
const addrI64 = this.ctx.nextTemp();
this.ctx.emit(`${addrI64} = fptosi double ${dblAddr2} to i64`);
const addr = this.ctx.nextTemp();
this.ctx.emit(`${addr} = inttoptr i64 ${addrI64} to i8*`);
const dblAddrlen2 = this.ctx.ensureDouble(addrlenDouble);
const addrlenI64 = this.ctx.nextTemp();
this.ctx.emit(`${addrlenI64} = fptosi double ${dblAddrlen2} to i64`);
const addrlen = this.ctx.nextTemp();
this.ctx.emit(`${addrlen} = inttoptr i64 ${addrlenI64} to i32*`);
const resultI32 = this.ctx.emitCall(
"i32",
"@accept",
`i32 ${fd}, i8* ${addr}, i32* ${addrlen}`,
);
const resultDouble = this.ctx.nextTemp();
this.ctx.emit(`${resultDouble} = sitofp i32 ${resultI32} to double`);
return resultDouble;
}
private generateGenericCall(expr: CallNode, params: string[]): string {
if (this.ctx.symbolTable.isClosure(expr.name)) {
return this.generateClosureCall(expr, params);
}
const resolvedFuncName = this.ctx.resolveImportAlias(expr.name);
let returnType = "double";
let paramTypes: string[] = [];
const funcResult = this.getFunctionFromAST(expr.name);
const func = funcResult as FunctionNode;
let hasOptionalParams = false;
if (funcResult && func.parameters) {
for (let i = 0; i < func.parameters.length; i++) {
const p = func.parameters[i];
const pTyped = p as FunctionParameter;
if (pTyped.optional || pTyped.defaultValue) {
hasOptionalParams = true;
break;
}
}
}
if (funcResult && func.async) {
returnType = "%Promise*";
this.ctx.setUsesPromises(true);
} else if (funcResult && func.paramTypes && func.paramTypes.length > 0) {
const normalizedReturnType = func.returnType ? stripNullable(func.returnType) : "";
if (normalizedReturnType) {
returnType = mapReturnTypeToLLVM(
normalizedReturnType,
this.ctx.isEnumType(normalizedReturnType),
);
}
for (let i = 0; i < func.paramTypes.length; i++) {
const p = func.paramTypes[i] as string;
const paramName = func.params[i] || "";
paramTypes.push(
mapParamTypeToLLVM(
p,
paramName,
this.ctx.isEnumType(stripNullable(p)),
this.ctx.interfaceStructGenHasInterface(stripNullable(p)),
),
);
}
} else {
const funcNode = this.getFunctionFromAST(expr.name);
if (funcNode) {
const normalizedRetType = funcNode.returnType ? stripNullable(funcNode.returnType) : "";
if (normalizedRetType) {
returnType = mapReturnTypeToLLVM(
normalizedRetType,
this.ctx.isEnumType(normalizedRetType),
);
}
if (funcNode.parameters) {
for (let i = 0; i < funcNode.parameters.length; i++) {
const p = funcNode.parameters[i] as FunctionParameter;
const pType = p.type || "number";
paramTypes.push(
mapParamTypeToLLVM(
pType,
p.name || "",
this.ctx.isEnumType(stripNullable(pType)),
false,
),
);
}
} else if (funcNode.paramTypes) {
for (let i = 0; i < funcNode.paramTypes.length; i++) {
const t = funcNode.paramTypes[i];
const paramName = funcNode.params[i] || "";
paramTypes.push(
mapParamTypeToLLVM(t, paramName, this.ctx.isEnumType(stripNullable(t)), false),
);
}
}
}
}
const argsList: string[] = [];
if (hasOptionalParams) {
argsList.push(`i32 ${expr.args.length}`);
}
const loopLimit =
func !== null && func.params !== null && func.params.length > 0
? func.params.length
: expr.args.length;
for (let i = 0; i < loopLimit; i++) {
if (i < expr.args.length) {
const paramType = paramTypes[i] || "double";
const result = this.ctx.generateExpression(expr.args[i], params);
const resultType = this.ctx.getVariableType(result);
if (paramType === "double" && resultType === "i8*") {
argsList.push(`double 0.0`);
} else if (paramType === "i8*" && resultType === "double") {
const coerced = this.ctx.nextTemp();
this.ctx.emit(`${coerced} = bitcast double ${result} to i64`);
const coerced2 = this.ctx.nextTemp();
this.ctx.emit(`${coerced2} = inttoptr i64 ${coerced} to i8*`);
argsList.push(`i8* ${coerced2}`);
} else if (paramType === "double" && resultType === "i64") {
const coerced = this.ctx.ensureDouble(result);
argsList.push(`double ${coerced}`);
} else if (paramType === "i32" && (resultType === "double" || !resultType)) {
// FFI: double → i32 (e.g., number literal passed to C int32_t param)
const coerced = this.ctx.nextTemp();
this.ctx.emit(`${coerced} = fptosi double ${result} to i32`);
argsList.push(`i32 ${coerced}`);
} else if (paramType === "i32" && resultType === "i64") {
const coerced = this.ctx.nextTemp();
this.ctx.emit(`${coerced} = trunc i64 ${result} to i32`);
argsList.push(`i32 ${coerced}`);
} else if (paramType === "i64" && (resultType === "double" || !resultType)) {
const coerced = this.ctx.nextTemp();
this.ctx.emit(`${coerced} = fptosi double ${result} to i64`);
argsList.push(`i64 ${coerced}`);
} else if (paramType === "float" && (resultType === "double" || !resultType)) {
// FFI: double → float (e.g., number literal passed to C float param)
const coerced = this.ctx.nextTemp();
this.ctx.emit(`${coerced} = fptrunc double ${result} to float`);
argsList.push(`float ${coerced}`);
} else {
argsList.push(`${paramType} ${result}`);
}
} else {
const paramType = paramTypes[i] || "double";
let defaultVal = "null";
if (paramType === "double") defaultVal = "0.0";
else if (paramType === "float") defaultVal = "0.0";
else if (
paramType === "i32" ||
paramType === "i64" ||
paramType === "i16" ||
paramType === "i8"
)
defaultVal = "0";
argsList.push(`${paramType} ${defaultVal}`);
}
}
// Declared functions (TS `declare function`) are external C symbols —
// use their real name without the _cs_ prefix
const mangledName =
func && func.declare ? resolvedFuncName : this.ctx.mangleUserName(resolvedFuncName);
if (returnType === "void") {
this.ctx.emitCallVoid(`@${mangledName}`, argsList.join(", "));
return "0";
}
const temp = this.ctx.emitCall(returnType, `@${mangledName}`, argsList.join(", "));
// FFI return type coercion: convert non-standard LLVM types back to
// ChadScript's type system (double for numbers, i8* for pointers)
if (returnType === "i32" || returnType === "i16" || returnType === "i8") {
const coerced = this.ctx.nextTemp();
this.ctx.emit(`${coerced} = sitofp ${returnType} ${temp} to double`);
return coerced;
}
if (returnType === "i64") {
const coerced = this.ctx.nextTemp();
this.ctx.emit(`${coerced} = sitofp i64 ${temp} to double`);
return coerced;
}
if (returnType === "float") {
const coerced = this.ctx.nextTemp();
this.ctx.emit(`${coerced} = fpext float ${temp} to double`);
return coerced;
}
return temp;
}
private generateClosureCall(expr: CallNode, params: string[]): string {
const closureMetadata = this.ctx.symbolTable.getClosureMetadata(expr.name);
if (!closureMetadata) {
return this.ctx.emitError(`Closure metadata not found for: ${expr.name}`, expr.loc);
}
const lambdaName = closureMetadata.lambdaName;
const envPtrRegister = closureMetadata.envPtrRegister;
const captures = closureMetadata.captures;
const returnType = "double";
const argsList: string[] = [];
if (captures && captures.length > 0) {
argsList.push(`i8* ${envPtrRegister}`);
} else {
argsList.push("i8* null");
}
for (let _cai = 0; _cai < expr.args.length; _cai++) {
const arg = expr.args[_cai];
const result = this.ctx.generateExpression(arg, params);
const coerced = this.ctx.ensureDouble(result);
argsList.push(`double ${coerced}`);
}
const temp = this.ctx.emitCall(returnType, `@${lambdaName}`, argsList.join(", "));
return temp;
}
private generateSetTimeout(expr: CallNode, params: string[]): string {
if (expr.args.length < 2) {
return this.ctx.emitError("setTimeout() requires 2 arguments (callback, delay_ms)", expr.loc);
}
this.ctx.setUsesTimers(true);
const callbackArg = expr.args[0];
if (callbackArg.type !== "variable") {
return this.ctx.emitError("setTimeout() callback must be a function reference", expr.loc);
}
const callbackName = (callbackArg as VariableNode).name;
const delayValue = this.ctx.generateExpression(expr.args[1], params);
const dblDelay = this.ctx.ensureDouble(delayValue);
const callbackPtr = this.ctx.emitBitcast(
`@${this.ctx.mangleUserName(callbackName)}`,
"void ()*",
"void ()*",
);
const result = this.ctx.emitCall(
"i8*",
"@__setTimeout",
`void ()* ${callbackPtr}, double ${dblDelay}`,
);
return result;
}
private generateSetInterval(expr: CallNode, params: string[]): string {
if (expr.args.length < 2) {
return this.ctx.emitError(
"setInterval() requires 2 arguments (callback, interval_ms)",
expr.loc,
);
}
this.ctx.setUsesTimers(true);
const callbackArg = expr.args[0];
if (callbackArg.type !== "variable") {
return this.ctx.emitError("setInterval() callback must be a function reference", expr.loc);
}
const callbackName = (callbackArg as VariableNode).name;
const intervalValue = this.ctx.generateExpression(expr.args[1], params);
const dblInterval = this.ctx.ensureDouble(intervalValue);
const callbackPtr = this.ctx.emitBitcast(
`@${this.ctx.mangleUserName(callbackName)}`,
"void ()*",
"void ()*",
);
const result = this.ctx.emitCall(
"i8*",
"@__setInterval",
`void ()* ${callbackPtr}, double ${dblInterval}`,
);
return result;
}
private emitIndentPrintf(prefix: string): void {
const depth = this.ctx.emitLoad("i32", "@__describe_depth");
const hasDepth = this.ctx.emitIcmp("sgt", "i32", depth, "0");
const preLabel = this.ctx.nextLabel(`${prefix}_pre`);
const loopLabel = this.ctx.nextLabel(`${prefix}_loop`);
const bodyLabel = this.ctx.nextLabel(`${prefix}_body`);
const doneLabel = this.ctx.nextLabel(`${prefix}_done`);
this.ctx.emitBrCond(hasDepth, preLabel, doneLabel);
this.ctx.emitLabel(preLabel);
this.ctx.setCurrentLabel(preLabel);
this.ctx.emitBr(loopLabel);
this.ctx.emitLabel(loopLabel);
this.ctx.setCurrentLabel(loopLabel);
const idx = `%__indent_idx_${loopLabel}`;
const nextIdx = `%__indent_next_${loopLabel}`;
this.ctx.emit(`${idx} = phi i32 [ 0, %${preLabel} ], [ ${nextIdx}, %${bodyLabel} ]`);
const cmp = this.ctx.emitIcmp("slt", "i32", idx, depth);
this.ctx.emitBrCond(cmp, bodyLabel, doneLabel);
this.ctx.emitLabel(bodyLabel);
this.ctx.setCurrentLabel(bodyLabel);
const fmt = this.ctx.nextTemp();
this.ctx.emit(`${fmt} = getelementptr [3 x i8], [3 x i8]* @.str.indent_unit, i32 0, i32 0`);
const printResult = this.ctx.nextTemp();
this.ctx.emit(`${printResult} = call i32 (i8*, ...) @printf(i8* ${fmt})`);
this.ctx.emit(`${nextIdx} = add i32 ${idx}, 1`);
this.ctx.emitBr(loopLabel);
this.ctx.emitLabel(doneLabel);
this.ctx.setCurrentLabel(doneLabel);
}
private generateTest(expr: CallNode, params: string[]): string {
this.ctx.setUsesTestRunner(true);
const nameValue = this.ctx.generateExpression(expr.args[0], params);
this.ctx.emitStore("i1", "0", "@__test_current_failed");
const totalPtr = this.ctx.emitLoad("i32", "@__test_total");
const totalInc = this.ctx.nextTemp();
this.ctx.emit(`${totalInc} = add i32 ${totalPtr}, 1`);
this.ctx.emitStore("i32", totalInc, "@__test_total");
const callbackArg = expr.args[1];
let callbackFn: string;
if (callbackArg.type === "variable") {
callbackFn = this.ctx.mangleUserName((callbackArg as VariableNode).name);
} else if (callbackArg.type === "arrow_function") {
callbackFn = this.ctx.generateExpression(callbackArg, params);
} else {
return this.ctx.emitError(
"test() callback must be a function reference or arrow function",
expr.loc,
);
}
const callResult = this.ctx.emitCall("double", `@${callbackFn}`, "");
const failed = this.ctx.emitLoad("i1", "@__test_current_failed");
const passLabel = this.ctx.nextLabel("test_pass");
const failLabel = this.ctx.nextLabel("test_fail");
const mergeLabel = this.ctx.nextLabel("test_merge");
this.ctx.emitBrCond(failed, failLabel, passLabel);
this.ctx.emitLabel(passLabel);
this.ctx.setCurrentLabel(passLabel);
const passedPtr = this.ctx.emitLoad("i32", "@__test_passed");
const passedInc = this.ctx.nextTemp();
this.ctx.emit(`${passedInc} = add i32 ${passedPtr}, 1`);
this.ctx.emitStore("i32", passedInc, "@__test_passed");
this.emitIndentPrintf("test_pass_indent");
const printPass = this.ctx.nextTemp();
this.ctx.emit(
`${printPass} = call i32 (i8*, ...) @printf(i8* getelementptr([12 x i8], [12 x i8]* @.str.test_pass, i32 0, i32 0), i8* ${nameValue})`,
);
this.ctx.emitBr(mergeLabel);
this.ctx.emitLabel(failLabel);
this.ctx.setCurrentLabel(failLabel);
const failedPtr = this.ctx.emitLoad("i32", "@__test_failed");
const failedInc = this.ctx.nextTemp();
this.ctx.emit(`${failedInc} = add i32 ${failedPtr}, 1`);
this.ctx.emitStore("i32", failedInc, "@__test_failed");
this.emitIndentPrintf("test_fail_indent");
const printFail = this.ctx.nextTemp();
this.ctx.emit(
`${printFail} = call i32 (i8*, ...) @printf(i8* getelementptr([12 x i8], [12 x i8]* @.str.test_fail, i32 0, i32 0), i8* ${nameValue})`,
);
this.ctx.emitBr(mergeLabel);
this.ctx.emitLabel(mergeLabel);
this.ctx.setCurrentLabel(mergeLabel);
return "0";
}
private generateDescribe(expr: CallNode, params: string[]): string {
this.ctx.setUsesTestRunner(true);
const nameValue = this.ctx.generateExpression(expr.args[0], params);
this.emitIndentPrintf("describe_indent");
const headerFmt = this.ctx.nextTemp();
this.ctx.emit(
`${headerFmt} = getelementptr [4 x i8], [4 x i8]* @.str.describe_header, i32 0, i32 0`,
);
const headerPrint = this.ctx.nextTemp();
this.ctx.emit(
`${headerPrint} = call i32 (i8*, ...) @printf(i8* ${headerFmt}, i8* ${nameValue})`,
);
const oldDepth = this.ctx.emitLoad("i32", "@__describe_depth");
const newDepth = this.ctx.nextTemp();
this.ctx.emit(`${newDepth} = add i32 ${oldDepth}, 1`);
this.ctx.emitStore("i32", newDepth, "@__describe_depth");
const callbackArg = expr.args[1];
let callbackFn: string;
if (callbackArg.type === "variable") {
callbackFn = this.ctx.mangleUserName((callbackArg as VariableNode).name);
} else if (callbackArg.type === "arrow_function") {
callbackFn = this.ctx.generateExpression(callbackArg, params);
} else {
return this.ctx.emitError(
"describe() callback must be a function reference or arrow function",
expr.loc,
);
}
const callResult = this.ctx.emitCall("double", `@${callbackFn}`, "");
const restoredDepth = this.ctx.emitLoad("i32", "@__describe_depth");
const decDepth = this.ctx.nextTemp();
this.ctx.emit(`${decDepth} = sub i32 ${restoredDepth}, 1`);
this.ctx.emitStore("i32", decDepth, "@__describe_depth");
return "0";