-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethod-calls.ts
More file actions
1613 lines (1510 loc) · 62.3 KB
/
method-calls.ts
File metadata and controls
1613 lines (1510 loc) · 62.3 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
/**
* Method Call Expression Generator
*
* Handles method call expressions: object.method(args)
*
* Delegates to specialized generators based on the method type:
* - ConsoleGenerator: console.log, console.error
* - ProcessGenerator: process.exit
* - FilesystemGenerator: fs.readFileSync, fs.writeFileSync, etc.
* - PathGenerator: path.resolve, path.dirname
* - JsonGenerator: JSON.parse, JSON.stringify
* - MathGenerator: Math.*, etc.
* - StringGenerator: string methods (substr, split, concat, etc.)
* - ArrayGenerator: array methods (push, map, filter, etc.)
* - MapGenerator: Map methods (set, get, has)
* - SetGenerator: Set methods (add, has, delete)
* - ClassGenerator: class instance methods
* - RegexGenerator: regex.test
*
* This class acts as a dispatcher/orchestrator for method call routing.
*/
import {
Expression,
MethodCallNode,
VariableNode,
AST,
ClassNode,
FunctionNode,
MemberAccessNode,
InterfaceDeclaration,
SourceLocation,
} from "../../ast/types.js";
import type { SymbolTable } from "../infrastructure/symbol-table.js";
import type {
IStringGenerator,
IFsGenerator,
IPathGenerator,
IJsonGenerator,
IMathGenerator,
IDateGenerator,
ICryptoGenerator,
ISqliteGenerator,
IResponseGenerator,
IRegexGenerator,
IArrowFunctionGenerator,
IStringMapGenerator,
IMapGenerator,
ISetGenerator,
IStringSetGenerator,
IPointerMapGenerator,
IArrayGenerator,
IChildProcessGenerator,
IEmbedGenerator,
} from "../infrastructure/generator-context.js";
import { parseMapTypeString, parseSetTypeString } from "../infrastructure/type-system.js";
import {
generateConsoleCallInline,
generateConsoleTime,
generateConsoleTimeEnd,
} from "./method-calls/console.js";
import {
handleAssertStrictEqual,
handleAssertNotStrictEqual,
handleAssertOk,
handleAssertDeepEqual,
handleAssertFail,
} from "./method-calls/assert.js";
import {
generateProcessExitInline,
generateProcessCwdInline,
handleProcessChdir,
handleProcessKill,
handleProcessUptime,
handleProcessSyscallI32,
isProcessStdoutOrStderr,
handleProcessWrite,
} from "./method-calls/process.js";
import {
handleOsHostname,
handleOsHomedir,
handleOsTmpdir,
handleOsCpus,
handleOsTotalmem,
handleOsFreemem,
handleOsUptime,
} from "./method-calls/os.js";
import {
handleSubstr,
handleSubstring,
handleConcat,
handleRepeat,
handlePadStart,
handlePadEnd,
handleSplit,
handleStartsWith,
handleEndsWith,
handleTrim,
handleTrimStart,
handleTrimEnd,
handleIndexOf,
handleLastIndexOf,
handleStringArrayIndexOf,
handleStringArrayIncludes,
handleStringIncludes,
handleSlice,
handleReplace,
handleReplaceAll,
handleNumberIsFinite,
handleNumberIsNaN,
handleNumberIsInteger,
handleNumberToString,
handleNumberToFixed,
handleCharAt,
handleCharCodeAt,
handleToUpperCase,
handleToLowerCase,
handleMatch,
} from "./method-calls/string-methods.js";
import {
generateObjectKeys,
generateObjectValues,
generateObjectEntries,
} from "./method-calls/object-static.js";
import {
handlePromiseStaticMethods,
handlePromiseThen,
handlePromiseFinally,
} from "./method-calls/promise-handlers.js";
import {
handleClassMethods,
handleObjectMethods,
getInterfaceFromAST,
} from "./method-calls/class-dispatch.js";
interface ExprBase {
type: string;
}
interface InterfaceDefInfo {
properties: { name: string; type: string }[];
}
export interface MethodCallGeneratorContext {
nextTemp(): string;
nextLabel(prefix: string): string;
emit(instruction: string): void;
getCurrentLabel(): string;
setCurrentLabel(label: string): void;
emitStore(type: string, value: string, ptr: string): void;
emitLoad(type: string, ptr: string): string;
emitCall(retType: string, func: string, args: string): string;
emitCallVoid(func: string, args: string): void;
emitBitcast(value: string, fromType: string, toType: string): string;
emitIcmp(pred: string, type: string, lhs: string, rhs: string): string;
emitBr(label: string): void;
emitBrCond(cond: string, thenLabel: string, elseLabel: string): void;
emitLabel(name: string): void;
emitGep(baseType: string, ptr: string, indices: string): string;
generateExpression(expr: Expression, params: string[]): string;
isStringExpression(expr: Expression): boolean;
isArrayExpression(expr: Expression): boolean;
isStringArrayExpression(expr: Expression): boolean;
isObjectArrayExpression(expr: Expression): boolean;
isRegexExpression(expr: Expression): boolean;
isPromiseExpression(expr: Expression): boolean;
emitError(message: string, loc?: SourceLocation, suggestion?: string): never;
emitWarning(message: string, loc?: SourceLocation, suggestion?: string): void;
mangleUserName(name: string): string;
symbolTable: SymbolTable;
variableTypes: Map<string, string>;
getVariableType(name: string): string | undefined;
setVariableType(name: string, type: string): void;
thisPointer: string | null;
getThisPointer(): string | null;
currentClassName: string | null;
getCurrentClassName(): string | null;
currentFunction?: string | null;
getCurrentFunction(): string | null;
ast: AST;
getAst(): AST | undefined;
getAstInterfacesLength(): number;
getAstInterfaceNameAt(index: number): string | null;
getAstInterfaceAt(index: number): InterfaceDeclaration | null;
getAstClassesLength(): number;
getAstClassNameAt(index: number): string | null;
getAstClassAt(index: number): ClassNode | null;
getAstFunctionsLength(): number;
getAstFunctionAt(index: number): FunctionNode | null;
getAstFunctionNameAt(index: number): string | null;
setUsesPromises(value: boolean): void;
setUsesSqlite(value: boolean): void;
setUsesCurl(value: boolean): void;
setUsesUvHrtime(value: boolean): void;
setUsesConsoleTime(value: boolean): void;
setUsesCrypto(value: boolean): void;
setUsesJson(value: boolean): void;
setUsesHttpServer(value: boolean): void;
setUsesMultipart(value: boolean): void;
setUsesTestRunner(value: boolean): void;
classGenGetFieldInfo(
className: string | null,
fieldName: string | null,
): { index: number; type: string; tsType?: string } | null;
classGenGenerateMethodCall(
instancePtr: string,
className: string,
method: string,
args: Expression[],
params: string[],
): string;
classGenGenerateStaticMethodCall(
className: string,
method: string,
args: Expression[],
params: string[],
): string;
classGenIsStaticMethod(className: string, methodName: string): boolean;
typeResolverGetThisFieldMapKeyType(expr: Expression): string | null;
typeResolverGetThisFieldSetValueType(expr: Expression): string | null;
readonly arrowFunctionGen: IArrowFunctionGenerator;
getActualClassType(name: string): string | undefined;
findClassImplementingInterface(interfaceName: string): string | null;
readonly stringGen: IStringGenerator;
readonly fsGen: IFsGenerator;
readonly pathGen: IPathGenerator;
readonly jsonGen: IJsonGenerator;
readonly mathGen: IMathGenerator;
readonly dateGen: IDateGenerator;
readonly cryptoGen: ICryptoGenerator;
readonly sqliteGen: ISqliteGenerator;
readonly responseGen: IResponseGenerator;
readonly regexGen: IRegexGenerator;
readonly stringMapGen: IStringMapGenerator;
readonly mapGen: IMapGenerator;
readonly setGen: ISetGenerator;
readonly stringSetGen: IStringSetGenerator;
readonly pointerMapGen: IPointerMapGenerator;
readonly arrayGen: IArrayGenerator;
readonly childProcessGen: IChildProcessGenerator;
readonly embedGen: IEmbedGenerator;
readonly typeResolver?: {
getThisFieldMapKeyType(expr: Expression): string | null;
getThisFieldSetValueType(expr: Expression): string | null;
};
ensureDouble(value: string): string;
ensureI64(value: string): string;
getWantsBinaryReturn(): boolean;
isUint8ArrayExpression(expr: Expression): boolean;
}
export class MethodCallGenerator {
constructor(private ctx: MethodCallGeneratorContext) {}
// Optional method call: obj?.method() — null-check obj, skip call if null
private generateOptionalMethodCall(expr: MethodCallNode, params: string[]): string {
const objValue = this.ctx.generateExpression(expr.object, params);
const objType = this.ctx.getVariableType(objValue) || "i8*";
// Non-pointer types can't be null, just call normally
if (objType === "double" || objType === "i32" || objType === "i64" || objType === "i1") {
const nonOptExpr: MethodCallNode = {
type: "method_call",
object: expr.object,
method: expr.method,
args: expr.args,
loc: expr.loc,
};
return this.generate(nonOptExpr, params);
}
const checkType = objType.startsWith("%{") ? "i8*" : objType;
const isNull = this.ctx.nextTemp();
this.ctx.emit(`${isNull} = icmp eq ${checkType} ${objValue}, null`);
const callLabel = this.ctx.nextLabel("optcall");
const nullLabel = this.ctx.nextLabel("optcall_null");
const endLabel = this.ctx.nextLabel("optcall_end");
this.ctx.emit(`br i1 ${isNull}, label %${nullLabel}, label %${callLabel}`);
this.ctx.emit(`${callLabel}:`);
this.ctx.setCurrentLabel(callLabel);
// Call with optional stripped so we don't recurse
const nonOptExpr: MethodCallNode = {
type: "method_call",
object: expr.object,
method: expr.method,
args: expr.args,
loc: expr.loc,
};
const callResult = this.generate(nonOptExpr, params);
const resultType = this.ctx.getVariableType(callResult) || "double";
const callEndLabel = this.ctx.getCurrentLabel();
this.ctx.emit(`br label %${endLabel}`);
this.ctx.emit(`${nullLabel}:`);
this.ctx.setCurrentLabel(nullLabel);
let nullValue: string;
if (resultType === "double") nullValue = "0.0";
else if (resultType === "i1") nullValue = "false";
else if (resultType === "i32") nullValue = "0";
else nullValue = "null";
this.ctx.emit(`br label %${endLabel}`);
this.ctx.emit(`${endLabel}:`);
this.ctx.setCurrentLabel(endLabel);
const result = this.ctx.nextTemp();
this.ctx.emit(
`${result} = phi ${resultType} [ ${callResult}, %${callEndLabel} ], [ ${nullValue}, %${nullLabel} ]`,
);
this.ctx.setVariableType(result, resultType);
return result;
}
private isClassInstanceExpression(expr: Expression): boolean {
const e = expr as ExprBase;
if (e.type !== "variable") return false;
const varName = (expr as VariableNode).name;
return this.ctx.symbolTable.isClass(varName);
}
private isVariableWithName(expr: Expression, name: string): boolean {
if (!expr) {
return false;
}
const e = expr as ExprBase;
const eType = e.type;
if (eType !== "variable") {
return false;
}
const varExpr = expr as VariableNode;
const varName = varExpr.name;
return varName === name;
}
private getVariableName(expr: Expression): string | null {
const e = expr as ExprBase;
if (e.type === "variable") {
return (expr as VariableNode).name;
}
return null;
}
private getParameterMapKeyType(varName: string): string | null {
const currentFunc = this.ctx.getCurrentFunction();
if (!currentFunc) return null;
let funcParams: { name: string; type?: string }[] | null = null;
const funcLen = this.ctx.getAstFunctionsLength();
for (let i = 0; i < funcLen; i++) {
const fName = this.ctx.getAstFunctionNameAt(i);
if (fName === currentFunc) {
const f = this.ctx.getAstFunctionAt(i);
if (f && f.parameters) {
funcParams = f.parameters as { name: string; type?: string }[];
}
break;
}
}
if (!funcParams && this.ctx.getCurrentClassName()) {
const classLen = this.ctx.getAstClassesLength();
for (let i = 0; i < classLen; i++) {
const cName = this.ctx.getAstClassNameAt(i);
if (cName === this.ctx.getCurrentClassName()) {
const c = this.ctx.getAstClassAt(i);
if (!c) break;
for (let j = 0; j < c.methods.length; j++) {
const m = c.methods[j];
if (m.name === currentFunc && m.params) {
funcParams = [];
for (let k = 0; k < m.params.length; k++) {
const paramType = m.paramTypes ? m.paramTypes[k] : undefined;
funcParams.push({ name: m.params[k], type: paramType });
}
break;
}
}
break;
}
}
}
if (!funcParams) return null;
for (let i = 0; i < funcParams.length; i++) {
const p = funcParams[i] as { name: string; type?: string };
if (p.name === varName && p.type) {
const mapParsed = parseMapTypeString(p.type);
if (mapParsed) {
return mapParsed.keyType;
}
}
}
return null;
}
private getThisFieldMapKeyType(expr: Expression): string | null {
const result = this.ctx.typeResolver?.getThisFieldMapKeyType(expr);
if (result) {
return result;
}
const e2 = expr as ExprBase;
if (e2.type !== "member_access") return null;
const memberExpr = expr as MemberAccessNode;
const objBase = memberExpr.object as ExprBase;
if (objBase.type === "this") {
const classNameForLookup = this.ctx.getCurrentClassName();
if (!classNameForLookup) return null;
const fieldInfoResult = this.ctx.classGenGetFieldInfo(
classNameForLookup,
memberExpr.property,
);
const fieldInfo = fieldInfoResult as { index: number; type: string; tsType: string };
if (!fieldInfoResult || !fieldInfo.tsType) return null;
const mapParsed = parseMapTypeString(fieldInfo.tsType);
if (!mapParsed) return null;
return mapParsed.keyType;
}
return null;
}
private getThisFieldSetValueType(expr: Expression): string | null {
const result = this.ctx.typeResolver?.getThisFieldSetValueType(expr);
if (result) {
return result;
}
const e = expr as ExprBase;
if (e.type !== "member_access") return null;
const memberExpr = expr as MemberAccessNode;
const objBase = memberExpr.object as ExprBase;
if (objBase.type !== "this") return null;
const classNameForSet = this.ctx.getCurrentClassName();
if (!classNameForSet) return null;
const fieldInfoResult = this.ctx.classGenGetFieldInfo(classNameForSet, memberExpr.property);
const fieldInfo = fieldInfoResult as { index: number; type: string; tsType: string };
if (!fieldInfoResult || !fieldInfo.tsType) return null;
const setParsed = parseSetTypeString(fieldInfo.tsType);
if (!setParsed) return null;
return setParsed.valueType;
}
// Helper methods delegate to context
private nextTemp(): string {
return this.ctx.nextTemp();
}
private emit(instruction: string): void {
this.ctx.emit(instruction);
}
/**
* Generate code for method call expression
*
* @example
* Input: { type: 'method_call', object: str, method: 'substr', args: [0, 5] }
* Output: result register with method call result
*/
generate(expr: MethodCallNode, params: string[]): string {
// Optional method call: obj?.method() — null-check the object first
if (expr.optional) {
return this.generateOptionalMethodCall(expr, params);
}
const method = expr.method;
// Handle Promise static methods (Promise.resolve, Promise.reject, Promise.all)
if (this.isVariableWithName(expr.object, "Promise")) {
return handlePromiseStaticMethods(this.ctx, expr, params);
}
// Handle ChadScript.embedFile/embedDir/getEmbeddedFile/getEmbeddedFileAsUint8Array
if (this.isVariableWithName(expr.object, "ChadScript")) {
if (method === "embedFile") {
return this.ctx.embedGen.generateEmbedFile(expr, params);
} else if (method === "embedDir") {
return this.ctx.embedGen.generateEmbedDir(expr, params);
} else if (method === "getEmbeddedFile") {
return this.ctx.embedGen.generateGetEmbeddedFile(expr, params);
} else if (method === "getEmbeddedFileAsUint8Array") {
return this.ctx.embedGen.generateGetEmbeddedFileAsUint8Array(expr, params);
} else if (method === "serveEmbedded") {
return this.ctx.embedGen.generateServeEmbedded(expr, params);
}
return this.ctx.emitError(`ChadScript.${method}() is not a supported method`, expr.loc);
}
// Uint8Array.fromRawBytes(dataPtr: string, len: number) → %Uint8Array*
// Wraps a raw i8* + byte length into a Uint8Array without copying.
// Used by RouterRequest.bodyBytes() to expose binary HTTP bodies.
if (this.isVariableWithName(expr.object, "Uint8Array") && method === "fromRawBytes") {
return this.handleUint8ArrayFromRawBytes(expr, params);
}
// Handle Array.from() - returns the argument as-is since our iterators already produce arrays
if (this.isVariableWithName(expr.object, "Array") && method === "from") {
if (expr.args.length === 0) {
return this.ctx.emitError("Array.from() requires at least 1 argument", expr.loc);
}
return this.ctx.generateExpression(expr.args[0], params);
}
if (this.isVariableWithName(expr.object, "Array") && method === "isArray") {
if (expr.args.length === 0) {
return this.ctx.emitError("Array.isArray() requires at least 1 argument", expr.loc);
}
const arg = expr.args[0];
const isArray =
this.ctx.isArrayExpression(arg) ||
this.ctx.isStringArrayExpression(arg) ||
this.ctx.isObjectArrayExpression(arg);
return isArray ? "1.0" : "0.0";
}
// Buffer.from(str, 'base64') → %Uint8Array* via cs_base64_decode C bridge
if (this.isVariableWithName(expr.object, "Buffer") && method === "from") {
return this.handleBufferFrom(expr, params);
}
// String.fromCharCode(n) — convert a number to a 1-char string
if (this.isVariableWithName(expr.object, "String") && method === "fromCharCode") {
if (expr.args.length === 0) {
return this.ctx.emitError("String.fromCharCode() requires 1 argument", expr.loc);
}
const codeVal = this.ctx.generateExpression(expr.args[0], params);
const dblVal = this.ctx.ensureDouble(codeVal);
const intVal = this.ctx.nextTemp();
this.ctx.emit(`${intVal} = fptosi double ${dblVal} to i32`);
const byteVal = this.ctx.nextTemp();
this.ctx.emit(`${byteVal} = trunc i32 ${intVal} to i8`);
// Allocate 2 bytes: the char + null terminator
const buf = this.ctx.emitCall("i8*", "@GC_malloc_atomic", "i64 2");
this.ctx.emitStore("i8", byteVal, buf);
const nullPtr = this.ctx.emitGep("i8", buf, "i64 1");
this.ctx.emitStore("i8", "0", nullPtr);
this.ctx.setVariableType(buf, "i8*");
return buf;
}
if (this.isVariableWithName(expr.object, "Object") && method === "keys") {
return generateObjectKeys(this.ctx, expr, params);
}
if (this.isVariableWithName(expr.object, "Object") && method === "values") {
return generateObjectValues(this.ctx, expr, params);
}
if (this.isVariableWithName(expr.object, "Object") && method === "entries") {
return generateObjectEntries(this.ctx, expr, params);
}
if (this.isVariableWithName(expr.object, "Number") && method === "isFinite") {
if (expr.args.length === 0) {
return this.ctx.emitError("Number.isFinite() requires at least 1 argument", expr.loc);
}
return handleNumberIsFinite(this.ctx, expr, params);
}
if (this.isVariableWithName(expr.object, "Number") && method === "isNaN") {
if (expr.args.length === 0) {
return this.ctx.emitError("Number.isNaN() requires at least 1 argument", expr.loc);
}
return handleNumberIsNaN(this.ctx, expr, params);
}
if (this.isVariableWithName(expr.object, "Number") && method === "isInteger") {
if (expr.args.length === 0) {
return this.ctx.emitError("Number.isInteger() requires at least 1 argument", expr.loc);
}
return handleNumberIsInteger(this.ctx, expr, params);
}
// Handle Promise instance methods (.then, .catch, .finally)
if (method === "then" || method === "catch") {
const isPromise = this.ctx.isPromiseExpression(expr.object);
if (isPromise) {
return handlePromiseThen(this.ctx, expr, params, method === "catch");
}
}
if (method === "finally") {
const isPromise = this.ctx.isPromiseExpression(expr.object);
if (isPromise) {
return handlePromiseFinally(this.ctx, expr, params);
}
}
// Handle console.log and console.error - inline check to avoid cross-class property access
const objBase2 = expr.object as ExprBase;
if (objBase2.type === "variable") {
const varNode = expr.object as VariableNode;
if (varNode.name === "console") {
const method2 = expr.method;
if (method2 === "log" || method2 === "error" || method2 === "warn" || method2 === "debug") {
return generateConsoleCallInline(this.ctx, expr, params);
}
if (method2 === "time") {
return generateConsoleTime(this.ctx, expr, params);
}
if (method2 === "timeEnd") {
return generateConsoleTimeEnd(this.ctx, expr, params);
}
}
if (varNode.name === "assert") {
this.ctx.setUsesTestRunner(true);
if (expr.method === "strictEqual") return handleAssertStrictEqual(this.ctx, expr, params);
if (expr.method === "notStrictEqual")
return handleAssertNotStrictEqual(this.ctx, expr, params);
if (expr.method === "ok") return handleAssertOk(this.ctx, expr, params);
if (expr.method === "deepEqual") return handleAssertDeepEqual(this.ctx, expr, params);
if (expr.method === "fail") return handleAssertFail(this.ctx, expr, params);
}
}
// Handle process.exit() - inline check
if (objBase2.type === "variable") {
const varNode = expr.object as VariableNode;
if (varNode.name === "process" && expr.method === "exit") {
return generateProcessExitInline(this.ctx, expr, params);
}
if (varNode.name === "process" && expr.method === "cwd") {
return generateProcessCwdInline(this.ctx);
}
if (varNode.name === "process" && expr.method === "chdir") {
return handleProcessChdir(this.ctx, expr, params);
}
if (varNode.name === "process" && expr.method === "abort") {
this.ctx.emit(`call void @abort()`);
return "0";
}
if (varNode.name === "process" && expr.method === "kill") {
return handleProcessKill(this.ctx, expr, params);
}
if (varNode.name === "process" && expr.method === "uptime") {
return handleProcessUptime(this.ctx);
}
if (varNode.name === "process" && expr.method === "getuid") {
return handleProcessSyscallI32(this.ctx, "@getuid");
}
if (varNode.name === "process" && expr.method === "getgid") {
return handleProcessSyscallI32(this.ctx, "@getgid");
}
if (varNode.name === "process" && expr.method === "geteuid") {
return handleProcessSyscallI32(this.ctx, "@geteuid");
}
if (varNode.name === "process" && expr.method === "getegid") {
return handleProcessSyscallI32(this.ctx, "@getegid");
}
if (varNode.name === "tty" && expr.method === "isatty") {
if (expr.args.length === 0) {
return this.ctx.emitError("tty.isatty() requires 1 argument (fd)", expr.loc);
}
const fdValue = this.ctx.generateExpression(expr.args[0], params);
const dblFd = this.ctx.ensureDouble(fdValue);
const fdInt = this.nextTemp();
this.ctx.emit(`${fdInt} = fptosi double ${dblFd} to i32`);
const rawResult = this.nextTemp();
this.ctx.emit(`${rawResult} = call i32 @isatty(i32 ${fdInt})`);
const boolResult = this.nextTemp();
this.ctx.emit(`${boolResult} = icmp ne i32 ${rawResult}, 0`);
const doubleResult = this.nextTemp();
this.ctx.emit(`${doubleResult} = uitofp i1 ${boolResult} to double`);
return doubleResult;
}
// os.* methods — POSIX wrappers for system info
if (varNode.name === "os") {
if (method === "hostname") return handleOsHostname(this.ctx);
if (method === "homedir") return handleOsHomedir(this.ctx);
if (method === "tmpdir") return handleOsTmpdir(this.ctx);
if (method === "cpus") return handleOsCpus(this.ctx);
if (method === "totalmem") return handleOsTotalmem(this.ctx);
if (method === "freemem") return handleOsFreemem(this.ctx);
if (method === "uptime") return handleOsUptime(this.ctx);
}
}
// Handle fs.* methods - inline check to avoid interface dispatch issues
if (objBase2.type === "variable" && (expr.object as VariableNode).name === "fs") {
if (method === "readFileSync") {
// Return Uint8Array when the call site expects binary data
if (this.ctx.getWantsBinaryReturn()) {
return this.ctx.fsGen.generateReadFileSyncBinary(expr, params);
}
return this.ctx.fsGen.generateReadFileSync(expr, params);
} else if (method === "writeFileSync") {
// Use binary-safe write when second arg is a Uint8Array
if (expr.args.length >= 2 && this.ctx.isUint8ArrayExpression(expr.args[1])) {
return this.ctx.fsGen.generateWriteFileSyncBinary(expr, params);
}
return this.ctx.fsGen.generateWriteFileSync(expr, params);
} else if (method === "appendFileSync") {
return this.ctx.fsGen.generateAppendFileSync(expr, params);
} else if (method === "existsSync") {
return this.ctx.fsGen.generateExistsSync(expr, params);
} else if (method === "unlinkSync") {
return this.ctx.fsGen.generateUnlinkSync(expr, params);
} else if (method === "readdirSync") {
return this.ctx.fsGen.generateReaddirSync(expr, params);
} else if (method === "statSync") {
return this.ctx.fsGen.generateStatSync(expr, params);
} else if (method === "mkdirSync") {
return this.ctx.fsGen.generateMkdirSync(expr, params);
} else if (method === "renameSync") {
return this.ctx.fsGen.generateRenameSync(expr, params);
} else if (method === "copyFileSync") {
return this.ctx.fsGen.generateCopyFileSync(expr, params);
} else if (method === "readFile") {
return this.ctx.fsGen.generateReadFile(expr, params);
} else if (method === "writeFile") {
return this.ctx.fsGen.generateWriteFile(expr, params);
} else if (method === "appendFile") {
return this.ctx.fsGen.generateAppendFile(expr, params);
} else if (method === "readdir") {
return this.ctx.fsGen.generateReaddir(expr, params);
} else if (method === "stat") {
return this.ctx.fsGen.generateStat(expr, params);
} else if (method === "unlink") {
return this.ctx.fsGen.generateUnlink(expr, params);
} else if (method === "mkdir") {
return this.ctx.fsGen.generateMkdir(expr, params);
} else if (method === "rename") {
return this.ctx.fsGen.generateRename(expr, params);
} else if (method === "copyFile") {
return this.ctx.fsGen.generateCopyFile(expr, params);
}
}
// Handle path.resolve() and path.dirname() (delegated to PathGenerator)
if (method === "resolve" && this.isVariableWithName(expr.object, "path")) {
return this.ctx.pathGen.generateResolve(expr, params);
}
if (method === "dirname" && this.isVariableWithName(expr.object, "path")) {
return this.ctx.pathGen.generateDirname(expr, params);
}
if (method === "basename" && this.isVariableWithName(expr.object, "path")) {
return this.ctx.pathGen.generateBasename(expr, params);
}
if (method === "join" && this.isVariableWithName(expr.object, "path")) {
return this.ctx.pathGen.generateJoin(expr, params);
}
if (method === "extname" && this.isVariableWithName(expr.object, "path")) {
return this.ctx.pathGen.generateExtname(expr, params);
}
if (method === "isAbsolute" && this.isVariableWithName(expr.object, "path")) {
return this.ctx.pathGen.generateIsAbsolute(expr, params);
}
if (method === "normalize" && this.isVariableWithName(expr.object, "path")) {
return this.ctx.pathGen.generateNormalize(expr, params);
}
if (method === "relative" && this.isVariableWithName(expr.object, "path")) {
return this.ctx.pathGen.generateRelative(expr, params);
}
if (method === "parse" && this.isVariableWithName(expr.object, "path")) {
return this.ctx.pathGen.generateParse(expr, params);
}
// child_process.execSync / spawnSync / exec / spawn → ChildProcessGenerator
if (
method === "execSync" ||
method === "spawnSync" ||
method === "exec" ||
method === "spawn"
) {
const objName = this.getVariableName(expr.object);
if (objName === "child_process" || objName === "cp") {
if (method === "execSync") return this.ctx.childProcessGen.generateExecSync(expr, params);
if (method === "exec") return this.ctx.childProcessGen.generateExec(expr, params);
if (method === "spawn") return this.ctx.childProcessGen.generateSpawn(expr, params);
return this.ctx.childProcessGen.generateSpawnSync(expr, params);
}
}
if (method === "write" && isProcessStdoutOrStderr(expr)) {
return handleProcessWrite(this.ctx, expr, params);
}
// Handle JSON.parse() and JSON.stringify() - inline check
if (objBase2.type === "variable" && (expr.object as VariableNode).name === "JSON") {
if (method === "parse") {
this.ctx.setUsesJson(true);
return this.ctx.jsonGen.generateParse(expr, params, expr.typeParameter);
} else if (method === "stringify") {
return this.ctx.jsonGen.generateStringify(expr, params);
}
}
// Handle Math.* methods (delegated to MathGenerator)
if (this.ctx.mathGen.canHandle(expr)) {
return this.ctx.mathGen.generateMathMethod(expr, params);
}
// Handle Date.now()
if (this.ctx.dateGen.canHandle(expr)) {
return this.ctx.dateGen.generateNow();
}
// Date instance methods: d.getTime(), d.getFullYear(), etc.
if (
method === "getTime" ||
method === "getFullYear" ||
method === "getMonth" ||
method === "getDate" ||
method === "getHours" ||
method === "getMinutes" ||
method === "getSeconds" ||
method === "toISOString"
) {
const varName = this.getVariableName(expr.object);
if (varName) {
const varType = this.ctx.getVariableType(varName);
if (varType === "%Date*") {
const datePtr = this.ctx.generateExpression(expr.object, params);
return this.ctx.dateGen.generateDateMethod(datePtr, method);
}
}
if (objBase2.type === "new") {
const datePtr = this.ctx.generateExpression(expr.object, params);
const objType = this.ctx.getVariableType(datePtr);
if (objType === "%Date*") {
return this.ctx.dateGen.generateDateMethod(datePtr, method);
}
}
}
// Handle crypto.* methods
if (objBase2.type === "variable" && (expr.object as VariableNode).name === "crypto") {
this.ctx.setUsesCrypto(true);
if (method === "sha256") {
return this.ctx.cryptoGen.generateSha256(expr, params);
} else if (method === "md5") {
return this.ctx.cryptoGen.generateMd5(expr, params);
} else if (method === "sha512") {
return this.ctx.cryptoGen.generateSha512(expr, params);
} else if (method === "randomBytes") {
return this.ctx.cryptoGen.generateRandomBytes(expr, params);
} else if (method === "randomUUID") {
return this.ctx.cryptoGen.generateRandomUUID(expr, params);
} else if (method === "hmacSha256") {
return this.ctx.cryptoGen.generateHmacSha256(expr, params);
} else if (method === "pbkdf2") {
return this.ctx.cryptoGen.generatePbkdf2(expr, params);
}
}
// Handle sqlite.* methods
if (objBase2.type === "variable" && (expr.object as VariableNode).name === "sqlite") {
this.ctx.setUsesSqlite(true);
if (method === "open") {
return this.ctx.sqliteGen.generateOpen(expr, params);
} else if (method === "exec") {
return this.ctx.sqliteGen.generateExec(expr, params);
} else if (method === "get") {
return this.ctx.sqliteGen.generateGet(expr, params);
} else if (method === "getRow") {
return this.ctx.sqliteGen.generateGetRow(expr, params);
} else if (method === "all") {
return this.ctx.sqliteGen.generateAll(expr, params);
} else if (method === "query") {
return this.ctx.sqliteGen.generateQuery(expr, params);
} else if (method === "close") {
return this.ctx.sqliteGen.generateClose(expr, params);
}
}
// Handle JSON.stringify() (legacy implementation)
if (method === "stringify" && this.isVariableWithName(expr.object, "JSON")) {
return this.handleJsonStringify(expr, params);
}
// Handle regex methods
if (method === "test") {
const isRegex = this.ctx.isRegexExpression(expr.object);
if (isRegex) {
return this.handleRegexTest(expr, params);
}
}
if (method === "exec") {
const isRegex = this.ctx.isRegexExpression(expr.object);
if (isRegex) {
return this.handleRegexExec(expr, params);
}
}
if (method === "isFile" || method === "isDirectory") {
let statI8Ptr: string | null = null;
if (objBase2.type === "variable") {
const varName = (expr.object as VariableNode).name;
const varType = this.ctx.getVariableType(varName);
if (varType === "%StatResult*") {
const varPtr = this.ctx.symbolTable.getAlloca(varName);
if (varPtr) {
const raw = this.nextTemp();
this.emit(`${raw} = load i8*, i8** ${varPtr}`);
statI8Ptr = raw;
}
}
} else {
const objVal = this.ctx.generateExpression(expr.object, params);
const objType = this.ctx.getVariableType(objVal);
if (objType === "%StatResult*") {
statI8Ptr = objVal;
}
}
if (statI8Ptr) {
const statPtr = this.nextTemp();
this.emit(`${statPtr} = bitcast i8* ${statI8Ptr} to double*`);
const fieldIdx = method === "isFile" ? 1 : 2;
const fieldPtr = this.nextTemp();
this.emit(
`${fieldPtr} = getelementptr inbounds double, double* ${statPtr}, i64 ${fieldIdx}`,
);
const result = this.nextTemp();
this.emit(`${result} = load double, double* ${fieldPtr}`);
this.ctx.setVariableType(result, "double");
return result;
}
}
// Handle Response methods (from fetch())
if (method === "text" || method === "json") {
const isLikelyResponse = this.isLikelyResponseExpression(expr);
if (isLikelyResponse) {
try {
let responsePtr = this.ctx.generateExpression(expr.object, params);
const objType = this.ctx.getVariableType(responsePtr);
if (objType === "i8*") {
const castPtr = this.ctx.nextTemp();
this.ctx.emit(`${castPtr} = bitcast i8* ${responsePtr} to %__FetchResponse*`);
responsePtr = castPtr;
}
if (method === "text") {
return this.ctx.responseGen.generateText(responsePtr);
} else if (method === "json") {
this.ctx.setUsesJson(true);
if (expr.typeParameter) {
const typeName = expr.typeParameter;
const interfaceDefResult = getInterfaceFromAST(this.ctx, typeName);
if (interfaceDefResult) {
const interfaceDef = interfaceDefResult as InterfaceDefInfo;
return this.ctx.responseGen.generateTypedJson(responsePtr, typeName, interfaceDef);
}
}
return this.ctx.responseGen.generateJson(responsePtr);
}
} catch (e) {
throw e;
}
}
}
// Handle string methods
if (method === "substr") {
return handleSubstr(this.ctx, expr, params);
}
if (method === "substring") {
return handleSubstring(this.ctx, expr, params);
}
if (
method === "concat" &&
!this.ctx.isArrayExpression(expr.object) &&
!this.ctx.isStringArrayExpression(expr.object) &&
!this.ctx.isObjectArrayExpression(expr.object)
) {
return handleConcat(this.ctx, expr, params);
}
if (method === "repeat") {
return handleRepeat(this.ctx, expr, params);
}
if (method === "padStart") {
return handlePadStart(this.ctx, expr, params);
}
if (method === "padEnd") {
return handlePadEnd(this.ctx, expr, params);
}
if (method === "split") {
return handleSplit(this.ctx, expr, params);
}
if (method === "startsWith") {
return handleStartsWith(this.ctx, expr, params);
}
if (method === "endsWith") {
return handleEndsWith(this.ctx, expr, params);
}
if (method === "trim") {
return handleTrim(this.ctx, expr, params);
}
if (method === "trimStart") {
return handleTrimStart(this.ctx, expr, params);
}
if (method === "trimEnd") {
return handleTrimEnd(this.ctx, expr, params);