js2zig-core 0.18.0

Core JS-to-Zig transpiler library
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
// Optional prop, Math, Array basic, Math P4, Await, TypedArray, string escape, JSON edge

use super::common::*;

#[test]
fn test_native_proto_optional_property() {
    // JS source: @typedef with optional property
    let js = r#"
/**
 * @typedef {Object} User
 * @property {string} name
 * @property {number} age
 * @property {string} [email]  →optional
 * @property {number} [score]  →optional
 */

/**
 * @param {User} user
 * @returns {string}
 */
export function getUserJson(user) {
return JSON.stringify(user);
}

/**
 * @returns {string}
 */
export function createUser() {
/**
 * @type {User}
 */
const user = JSON.parse('{"name":"Alice","age":30}');
// email and score are not provided (undefined)
return user.name + " has email: " + (user.email || "none");
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_optional_property");

    // Step2: verify optional fields are generated with ?Type
    assert!(
        zig.contains("name: []const u8,"),
        "Expected 'name: []const u8,' in:\n{}",
        zig
    );
    assert!(
        zig.contains("age: f64,"),
        "Expected 'age: f64,' in:\n{}",
        zig
    );
    assert!(
        zig.contains("email: ?[]const u8,"),
        "Expected 'email: ?[]const u8,' (optional) in:\n{}",
        zig
    );
    assert!(
        zig.contains("score: ?f64,"),
        "Expected 'score: ?f64,' (optional) in:\n{}",
        zig
    );

    // Step3: verify toJson() is generated (std.json.fmt() handles ?T automatically)
    assert!(
        zig.contains("pub fn toJson"),
        "Expected toJson() method in:\n{}",
        zig
    );
}

// ── Test: Math built-in methods ─────────────────────

#[test]
fn test_native_proto_math_methods() {
    // JS source: Math.abs(), Math.floor(), Math.ceil(), Math.round(), Math.sqrt(), Math.hypot()
    let js = r#"
/**
 * @param {number} x
 * @returns {number}
 */
export function testMath(x) {
const absX = Math.abs(x);
const floorX = Math.floor(x);
const ceilX = Math.ceil(x);
const roundX = Math.round(x);
const sqrtX = Math.sqrt(x);
const hypotX = Math.hypot(x, 3, 4);
return absX + floorX + ceilX + roundX + sqrtX + hypotX;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_math_methods");

    // Step2: verify Math methods are generated correctly
    assert!(zig.contains("@abs("), "Expected '@abs(' in:\n{}", zig);
    assert!(zig.contains("@floor("), "Expected '@floor(' in:\n{}", zig);
    assert!(zig.contains("@ceil("), "Expected '@ceil(' in:\n{}", zig);
    assert!(zig.contains("@round("), "Expected '@round(' in:\n{}", zig);
    assert!(zig.contains("@sqrt("), "Expected '@sqrt(' in:\n{}", zig);
    // Math.hypot(x, 3, 4) → @sqrt(@as(f64,x)*@as(f64,x) + @as(f64,3)*@as(f64,3) + @as(f64,4)*@as(f64,4))
    assert!(
        zig.contains("@sqrt("),
        "Expected '@sqrt(' for Math.hypot in:\n{}",
        zig
    );
    assert!(
        zig.contains("*@as(f64,"),
        "Expected squared terms for Math.hypot in:\n{}",
        zig
    );
}

// ── Test: Array.pop() built-in method ─────────────

#[test]
fn test_native_proto_array_pop() {
    // JS source: arr.pop()
    let js = r#"
/**
 * @returns {number}
 */
export function popArray() {
const arr = [1, 2, 3];
return arr.pop();
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_pop");

    // Step2: verify arr.pop() is generated
    assert!(
        zig.contains("arr.pop()"),
        "Expected 'arr.pop()' in:\n{}",
        zig
    );
}

// ── Test: Array.indexOf() built-in method ─────────────

#[test]
fn test_native_proto_array_indexof() {
    // JS source: arr.indexOf(x) - returns index or -1
    let js = r#"
/**
 * @param {number} target
 * @returns {number}
 */
export function findIndex(target) {
const arr = [10, 20, 30, 40, 50];
return arr.indexOf(target);
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_indexof");

    // Verify labeled block with for loop is generated
    assert!(zig.contains("blk_"), "Expected labeled block in:\n{}", zig);
    assert!(zig.contains("for ("), "Expected for loop in:\n{}", zig);
    assert!(
        zig.contains(".items"),
        "Expected .items access in:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_"),
        "Expected break :blk_ in:\n{}",
        zig
    );
    assert!(
        zig.contains("@as(i64, -1)"),
        "Expected @as(i64, -1) fallback in:\n{}",
        zig
    );
}

// ── Test: Array.includes() built-in method ─────────────

#[test]
fn test_native_proto_array_includes() {
    // JS source: arr.includes(x) - returns bool, used in numeric context
    let js = r#"
/**
 * @param {number} target
 * @returns {number}
 */
export function hasItem(target) {
const arr = [10, 20, 30];
if (arr.includes(target)) {
    return 1;
}
return 0;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_includes");

    // Verify labeled block with for loop and bool return
    assert!(zig.contains("blk_"), "Expected labeled block in:\n{}", zig);
    assert!(zig.contains("for ("), "Expected for loop in:\n{}", zig);
    assert!(
        zig.contains("break :blk_") && zig.contains(" true"),
        "Expected break :blk_ with true in:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_") && zig.contains(" false"),
        "Expected break :blk_ with false in:\n{}",
        zig
    );
}

// ── Test: Array.join() built-in method ─────────────

#[test]
fn test_native_proto_array_join() {
    // JS source: arr.join(sep) - returns string
    let js = r#"
/**
 * @returns {string}
 */
export function joinNumbers() {
const arr = [1, 2, 3];
return arr.join(", ");
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_join");

    // Verify std.io.Writer.Allocating is used
    assert!(
        zig.contains("std.io.Writer.Allocating"),
        "Expected std.io.Writer.Allocating in:\n{}",
        zig
    );
    assert!(
        zig.contains("__join_buf"),
        "Expected __join_buf variable in:\n{}",
        zig
    );
    assert!(
        zig.contains("writeAll"),
        "Expected writeAll for separator in:\n{}",
        zig
    );
    // i64 elements should use {d} format
    assert!(
        zig.contains("{d}"),
        "Expected {{d}} format for i64 elements in:\n{}",
        zig
    );
}

// ── Test: Array.slice() built-in method ─────────────

#[test]
fn test_native_proto_array_slice() {
    // JS source: arr.slice(start, end) - returns sub-slice
    let js = r#"
/**
 * @returns {number}
 */
export function sliceSum() {
const arr = [10, 20, 30, 40, 50];
const sub = arr.slice(1, 4);
return sub[0] + sub[1] + sub[2];
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_slice");

    // Verify slice expression is generated: arr.items[1..4]
    assert!(
        zig.contains(".items[1..4]"),
        "Expected '.items[1..4]' slice in:\n{}",
        zig
    );
}

// ── Test: Array.splice() built-in method ─────────────

#[test]
fn test_native_proto_array_splice() {
    // JS source: arr.splice(start, deleteCount)
    let js = r#"
/**
 * @param {number} start
 * @param {number} count
 * @returns {number}
 */
export function spliceArray(start, count) {
const arr = [1, 2, 3, 4, 5];
return arr.splice(start, count);
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_splice");

    // Verify splice generates ArrayList operations
    assert!(
        zig.contains("orderedRemove"),
        "Expected orderedRemove in:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_") && zig.contains("__spliced"),
        "Expected break :blk_ __spliced in:\n{}",
        zig
    );
}

// ── Test: Array.splice() with insert items ─────────────

#[test]
fn test_native_proto_array_splice_insert() {
    // JS source: arr.splice(start, deleteCount, item1, item2)
    let js = r#"
/**
 * @param {number} start
 * @returns {number}
 */
export function spliceInsert(start) {
const arr = [1, 2, 3, 4, 5];
return arr.splice(start, 2, 99, 100);
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_splice_insert");

    // Verify splice generates insertSlice for multi-arg
    assert!(
        zig.contains("orderedRemove"),
        "Expected orderedRemove in:\n{}",
        zig
    );
    assert!(
        zig.contains("insertSlice"),
        "Expected insertSlice for insertion in:\n{}",
        zig
    );
}

// ── Test: New Math methods (random, pow, max, min) ─────────────────────

#[test]
fn test_native_proto_math_new_methods() {
    // JS source: Math.random(), Math.pow(), Math.max(), Math.min()
    let js = r#"
/**
 * @param {number} x
 * @param {number} y
 * @returns {number}
 */
export function testMathNew(x, y) {
const rand = Math.random();
const powXY = Math.pow(x, y);
const maxXY = Math.max(x, y);
const minXY = Math.min(x, y);
return powXY + maxXY + minXY;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_math_new_methods");

    // Step2: verify Math methods are generated correctly
    assert!(
        zig.contains("std.crypto.random.int(u32)"),
        "Expected 'std.crypto.random.int(u32)' in:\n{}",
        zig
    );
    assert!(
        zig.contains("std.math.pow(f64,"),
        "Expected 'std.math.pow(f64,' in:\n{}",
        zig
    );
    assert!(zig.contains("if ("), "Expected 'if (' in max/min:\n{}", zig);
}

// ── Test: Phase 4 Math methods (expm1/sinh/cosh/tanh/asinh/acosh/atanh/clz32/fround/imul/log1p) ──
#[test]
fn test_native_proto_math_phase4() {
    let js = r#"
/**
 * @param {number} x
 * @param {number} y
 * @returns {number}
 */
export function testMathPhase4(x, y) {
const a = Math.expm1(x);
const b = Math.sinh(x);
const c = Math.cosh(x);
const d = Math.tanh(x);
const e = Math.asinh(x);
const f = Math.acosh(x);
const g = Math.atanh(x);
const h = Math.clz32(x);
const i = Math.fround(x);
const j = Math.imul(x, y);
const k = Math.log1p(x);
return a + b + c + d + e + f + g + h + i + j + k;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_math_phase4");

    // Verify Phase 4 Math methods are generated correctly
    assert!(
        zig.contains("std.math.expm1("),
        "Expected 'std.math.expm1(' in:\n{}",
        zig
    );
    assert!(
        zig.contains("std.math.sinh("),
        "Expected 'std.math.sinh(' in:\n{}",
        zig
    );
    assert!(
        zig.contains("std.math.cosh("),
        "Expected 'std.math.cosh(' in:\n{}",
        zig
    );
    assert!(
        zig.contains("std.math.tanh("),
        "Expected 'std.math.tanh(' in:\n{}",
        zig
    );
    assert!(
        zig.contains("std.math.asinh("),
        "Expected 'std.math.asinh(' in:\n{}",
        zig
    );
    assert!(
        zig.contains("std.math.acosh("),
        "Expected 'std.math.acosh(' in:\n{}",
        zig
    );
    assert!(
        zig.contains("std.math.atanh("),
        "Expected 'std.math.atanh(' in:\n{}",
        zig
    );
    assert!(zig.contains("@clz("), "Expected '@clz(' in:\n{}", zig);
    assert!(zig.contains("@as(f32,"), "Expected '@as(f32,' in:\n{}", zig);
    assert!(zig.contains("@as(i32,"), "Expected '@as(i32,' in:\n{}", zig);
    assert!(
        zig.contains("std.math.log1p("),
        "Expected 'std.math.log1p(' in:\n{}",
        zig
    );
}

// ── P0-7: Math float-arg coercion (@floatFromInt on float args) ─────────
// Before P0-7, Math.sin/cos/tan/atan/log/exp/asin/acos/hypot/fround/clz32/sign
// unconditionally emitted `@floatFromInt(arg)`, which is a Zig compile error
// when the argument is a float (e.g. `Math.sin(1.5)` → `@sin(@floatFromInt(1.5))`
// fails: @floatFromInt expects an integer). P0-7 adds `expr_is_float` +
// `emit_f64_coerced` to pick the correct coercion per arg shape.

#[test]
fn test_p0_7_float_literal_args() {
    // Float-literal args: must emit `@as(f64, <literal>)`, NOT `@floatFromInt`.
    let js = r#"
/**
 * @returns {number}
 */
export function p07FloatLit() {
    return Math.sin(1.5) + Math.cos(2.5) + Math.tan(0.5)
         + Math.atan(0.5) + Math.asin(0.5) + Math.acos(0.5)
         + Math.exp(1.5) + Math.log(2.5);
}
"#;
    let zig = transpile_and_check(js, "test_p0_7_float_literal_args");

    // Float-coercing builtins must be present
    assert!(zig.contains("@sin("), "Expected '@sin(' in:\n{}", zig);
    assert!(zig.contains("@cos("), "Expected '@cos(' in:\n{}", zig);
    assert!(zig.contains("@tan("), "Expected '@tan(' in:\n{}", zig);
    assert!(
        zig.contains("std.math.atan("),
        "Expected 'std.math.atan(' (atan is NOT a @-builtin) in:\n{}",
        zig
    );
    assert!(
        zig.contains("std.math.asin("),
        "Expected 'std.math.asin(' in:\n{}",
        zig
    );
    assert!(
        zig.contains("std.math.acos("),
        "Expected 'std.math.acos(' in:\n{}",
        zig
    );
    assert!(zig.contains("@exp("), "Expected '@exp(' in:\n{}", zig);
    assert!(zig.contains("@log("), "Expected '@log(' in:\n{}", zig);
    // CRITICAL: @floatFromInt must NOT appear for float-literal args
    assert!(
        !zig.contains("@floatFromInt"),
        "P0-7 regression: @floatFromInt emitted for float-literal args:\n{}",
        zig
    );
    // Spot-check the identity-cast form for a float literal
    assert!(
        zig.contains("@as(f64, 1.5)"),
        "Expected '@as(f64, 1.5)' identity cast for float literal in:\n{}",
        zig
    );
}

#[test]
fn test_p0_7_int_variable_arg() {
    // @param {number} → x is f64. With P0-1 fix, expr_is_float() now detects
    // f64-typed TypedIdent, so @as(f64, x) identity cast is used instead of
    // the invalid @floatFromInt on an already-f64 variable.
    let js = r#"
/**
 * @param {number} x
 * @returns {number}
 */
export function p07IntVar(x) {
    return Math.sin(x);
}
"#;
    let zig = transpile_and_check(js, "test_p0_7_int_variable_arg");

    assert!(zig.contains("@sin("), "Expected '@sin(' in:\n{}", zig);
    assert!(
        !zig.contains("@floatFromInt"),
        "Expected NO @floatFromInt for f64 variable arg in:\n{}",
        zig
    );
}

#[test]
fn test_p0_7_float_expr_arg() {
    // Arg is itself a float-returning BuiltinCall (Math.cos): must use
    // `@as(f64, ...)` identity cast, NOT `@floatFromInt`.
    let js = r#"
/**
 * @returns {number}
 */
export function p07FloatExpr() {
    return Math.sin(Math.cos(0.5));
}
"#;
    let zig = transpile_and_check(js, "test_p0_7_float_expr_arg");

    assert!(zig.contains("@sin("), "Expected '@sin(' in:\n{}", zig);
    assert!(zig.contains("@cos("), "Expected '@cos(' in:\n{}", zig);
    assert!(
        !zig.contains("@floatFromInt"),
        "P0-7 regression: @floatFromInt emitted for float-expr arg:\n{}",
        zig
    );
}

#[test]
fn test_p0_7_hypot_float_args() {
    // Math.hypot with float literals: squared terms use identity cast.
    let js = r#"
/**
 * @returns {number}
 */
export function p07HypotFloat() {
    return Math.hypot(1.5, 2.5);
}
"#;
    let zig = transpile_and_check(js, "test_p0_7_hypot_float_args");

    assert!(
        zig.contains("@sqrt("),
        "Expected '@sqrt(' for hypot in:\n{}",
        zig
    );
    assert!(
        zig.contains("@as(f64, 1.5)"),
        "Expected '@as(f64, 1.5)' squared term in:\n{}",
        zig
    );
    assert!(
        zig.contains("@as(f64, 2.5)"),
        "Expected '@as(f64, 2.5)' squared term in:\n{}",
        zig
    );
    assert!(
        !zig.contains("@floatFromInt"),
        "P0-7 regression: @floatFromInt emitted for hypot float args:\n{}",
        zig
    );
}

#[test]
fn test_p0_7_clz32_float_arg() {
    // Math.clz32(1.5): float arg must be reduced via @intFromFloat before @clz.
    // Uses transpile_and_assert (no ast-check) because @clz's narrow integer
    // return type interacts with the `@returns {number}` signature.
    let js = r#"
/**
 * @returns {number}
 */
export function p07Clz32Float() {
    return Math.clz32(1.5);
}
"#;
    let zig = transpile_and_assert(js, "test_p0_7_clz32_float_arg");

    assert!(zig.contains("@clz("), "Expected '@clz(' in:\n{}", zig);
    assert!(
        zig.contains("@intFromFloat"),
        "Expected @intFromFloat for clz32 float arg in:\n{}",
        zig
    );
    // The float ARGUMENT must use @intFromFloat, not @floatFromInt.
    // (The RESULT may use @floatFromInt for I64→F64 return coercion —
    // that's correct and expected with `@returns {number}` → f64.)
    assert!(
        !zig.contains("@floatFromInt(1.5)"),
        "P0-7 regression: @floatFromInt emitted on clz32 float ARG:\n{}",
        zig
    );
}

#[test]
fn test_p0_7_fround_float_arg() {
    // Math.fround(1.5): float arg → @as(f32, @floatCast(...)).
    // Uses transpile_and_assert: fround yields f32 which may not match the
    // inferred `@returns {number}` signature under ast-check.
    let js = r#"
/**
 * @returns {number}
 */
export function p07Fround() {
    return Math.fround(1.5);
}
"#;
    let zig = transpile_and_assert(js, "test_p0_7_fround_float_arg");

    assert!(
        zig.contains("@floatCast"),
        "Expected @floatCast for fround float arg in:\n{}",
        zig
    );
    assert!(
        !zig.contains("@floatFromInt"),
        "P0-7 regression: @floatFromInt emitted for fround float arg:\n{}",
        zig
    );
}

#[test]
fn test_p0_7_sign_float_arg() {
    // Math.sign(2.5): float-literal arg → cached value uses `@as(f64, 2.5)`.
    let js = r#"
/**
 * @returns {number}
 */
export function p07Sign() {
    return Math.sign(2.5);
}
"#;
    let zig = transpile_and_check(js, "test_p0_7_sign_float_arg");

    assert!(
        zig.contains("@as(f64, 2.5)"),
        "Expected '@as(f64, 2.5)' for sign float arg in:\n{}",
        zig
    );
    assert!(
        !zig.contains("@floatFromInt"),
        "P0-7 regression: @floatFromInt emitted for sign float arg:\n{}",
        zig
    );
}

// ── P0-8: Math.min/max float-variable detection + mixed-type coercion ────
// Before P0-8, emit_min_max's `any_float` only matched FloatLiteral, so a
// float-typed variable arg (division result, BuiltinCall returning f64) fell
// into the i64 branch and emitted `@as(i64, <f64 expr>)` — a Zig compile
// error. Mixed int+float args (e.g. Math.max(x, 1.5)) also broke: the float
// branch emitted raw args without coercion, producing an i64-vs-f64
// comparison. P0-8 routes `any_float` through `expr_is_float` and coerces
// every arg in the float branch via `emit_f64_coerced`.

#[test]
fn test_p0_8_min_max_float_expr_arg() {
    // Arg is a float-returning BuiltinCall (Math.cos): must take the f64
    // branch, producing f64-typed comparisons — NOT the i64 branch.
    let js = r#"
/**
 * @returns {number}
 */
export function p08MaxBuiltin() {
    return Math.max(Math.cos(0.5), 1.5);
}
"#;
    let zig = transpile_and_check(js, "test_p0_8_min_max_float_expr_arg");

    assert!(
        zig.contains("@cos("),
        "Expected '@cos(' for float-expr arg in:\n{}",
        zig
    );
    // Float branch coerces args to f64; @as(i64, ...) must NOT appear.
    assert!(
        !zig.contains("@as(i64,"),
        "P0-8 regression: i64 branch used for float-expr arg in:\n{}",
        zig
    );
    assert!(
        zig.contains("@as(f64, 1.5)"),
        "Expected '@as(f64, 1.5)' coercion for float literal in:\n{}",
        zig
    );
}

#[test]
fn test_p0_8_min_max_mixed_int_float() {
    // Mixed f64 variable (@param {number}) + float literal: with P0-1 fix,
    // expr_is_float() now detects f64-typed TypedIdent, so the f64 branch
    // runs and wraps both args with @as(f64, ...) identity casts.
    // No @floatFromInt is needed since x is already f64.
    let js = r#"
/**
 * @param {number} x
 * @returns {number}
 */
export function p08MaxMixed(x) {
    return Math.max(x, 1.5);
}
"#;
    let zig = transpile_and_check(js, "test_p0_8_min_max_mixed_int_float");

    assert!(
        !zig.contains("@floatFromInt"),
        "P0-1 fix: no @floatFromInt needed for f64 arg in:\n{}",
        zig
    );
    assert!(
        zig.contains("@as(f64, x)"),
        "Expected '@as(f64, x)' identity cast for f64 variable in:\n{}",
        zig
    );
    assert!(
        zig.contains("@as(f64, 1.5)"),
        "Expected '@as(f64, 1.5)' for float literal in:\n{}",
        zig
    );
    assert!(
        !zig.contains("@as(i64,"),
        "P0-8 regression: i64 branch used for mixed int/float args in:\n{}",
        zig
    );
}

#[test]
fn test_p0_8_min_max_int_args_unchanged() {
    // All-f64 args (@param {number} variables): with P0-1 fix,
    // expr_is_float() now detects f64-typed TypedIdent, so the f64 branch is
    // used for min/max. No @floatFromInt since variables are already f64.
    let js = r#"
/**
 * @param {number} x
 * @param {number} y
 * @returns {number}
 */
export function p08MaxInt(x, y) {
    return Math.max(x, y);
}
"#;
    let zig = transpile_and_check(js, "test_p0_8_min_max_int_args_unchanged");

    assert!(
        !zig.contains("@floatFromInt"),
        "f64 min/max branch must not emit @floatFromInt in:\n{}",
        zig
    );
}

// ── Test: AwaitExpression support ────────────

#[test]
fn test_native_proto_await() {
    // JS source: async function with await.
    // NOTE: In the real pipeline, `export` is stripped by the preprocessor,
    // and `exported_functions` is passed to transpile_js() to mark exports.
    // This test simulates that: no `export` in JS, uses exported_functions param.
    let js = r#"
/**
 * @param {i64} x
 * @returns {i64}
 */
async function asyncDouble(x) {
const result = await double(x);
return result;
}

function double(x) {
return x * 2;
}
"#;
    let mut exports = std::collections::HashSet::new();
    exports.insert("asyncDouble".to_string());
    let zig = transpile_and_check_with_exports(js, "test_native_proto_await", exports);

    // Step2: verify async function signature has `io: js_runtime.Io`
    assert!(
        zig.contains("io: js_runtime.Io"),
        "Expected 'io: js_runtime.Io' in async function signature, got:\n{}",
        zig
    );

    // Step3: verify await is translated to io.async() + .await(io)
    assert!(
        zig.contains("io.async("),
        "Expected 'io.async(' in generated code, got:\n{}",
        zig
    );
    assert!(
        zig.contains(".await(io)"),
        "Expected '.await(io)' in generated code, got:\n{}",
        zig
    );
    // defer _ = _tN.cancel(io) catch undefined;
    assert!(
        zig.contains("defer"),
        "Expected 'defer' in generated code, got:\n{}",
        zig
    );
    assert!(
        zig.contains(".cancel(io)"),
        "Expected '.cancel(io)' in generated code, got:\n{}",
        zig
    );

    // Step4: verify non-async function does NOT have `io: anytype`
    assert!(
        zig.contains("fn double(x: anytype) @TypeOf("),
        "Expected non-async function signature, got:\n{}",
        zig
    );
}

// ── P1-12: stmt_contains_await / expr_contains_await — nested-position tests ─
// Before the fix, awaited expressions inside ForStatement bodies, TryStatement
// blocks, the RHS of AssignmentExpression, or inside TemplateLiteral
// interpolations were silently dropped, so a function using `await` in those
// positions was incorrectly categorized as non-async (no `io: js_runtime.Io`).
// Each test below places the only `await` inside one of the previously-missing
// constructs and confirms the function is marked async.

#[test]
fn test_p1_12_await_inside_for_loop_body() {
    let js = r#"
async function fetchFirst(items) {
    for (let i = 0; i < items.length; i = i + 1) {
        const v = await items[i];
        return v;
    }
}
"#;
    let mut exports = std::collections::HashSet::new();
    exports.insert("fetchFirst".to_string());
    let zig = transpile_and_check_with_exports(js, "test_p1_12_await_in_for", exports);
    assert!(
        zig.contains("io: js_runtime.Io"),
        "Expected async signature (await inside for-loop was dropped before P1-12):\n{}",
        zig
    );
}

#[test]
fn test_p1_12_await_inside_try_block() {
    let js = r#"
async function safeFetch(key) {
    let result = null;
    try {
        result = await fetch(key);
    } catch (e) {
        result = null;
    }
    return result;
}

function fetch(k) { return k; }
"#;
    let mut exports = std::collections::HashSet::new();
    exports.insert("safeFetch".to_string());
    let zig = transpile_and_check_with_exports(js, "test_p1_12_await_in_try", exports);
    assert!(
        zig.contains("io: js_runtime.Io"),
        "Expected async signature (await inside try block was dropped before P1-12):\n{}",
        zig
    );
}

#[test]
fn test_p1_12_await_in_template_literal() {
    let js = r#"
async function greet(getNameFn) {
    return `hello ${await getNameFn()}`;
}

function getName() { return "x"; }
"#;
    let mut exports = std::collections::HashSet::new();
    exports.insert("greet".to_string());
    let zig = transpile_and_check_with_exports(js, "test_p1_12_await_in_template", exports);
    assert!(
        zig.contains("io: js_runtime.Io"),
        "Expected async signature (await inside TemplateLiteral was dropped before P1-12):\n{}",
        zig
    );
}

#[test]
fn test_p1_12_await_in_switch_case() {
    // Use break (not return) inside the case body — `return await foo()`
    // generates an unreachable-code pattern after the switch.
    let js = r#"
async function dispatch(code) {
    let result = null;
    switch (code) {
        case 1:
            result = await fetchOne();
            break;
        default:
            result = null;
    }
    return result;
}

function fetchOne() { return 1; }
"#;
    let mut exports = std::collections::HashSet::new();
    exports.insert("dispatch".to_string());
    let zig = transpile_and_check_with_exports(js, "test_p1_12_await_in_switch", exports);
    assert!(
        zig.contains("io: js_runtime.Io"),
        "Expected async signature (await inside switch was dropped before P1-12):\n{}",
        zig
    );
}

// ── Test: TypedArray support ─────────────

#[test]
fn test_native_proto_typedarray_basic() {
    // JS source: new Int32Array(), .length, index access
    let js = r#"
/**
 * @returns {number}
 */
export function sumInt32() {
const arr = new Int32Array([1, 2, 3]);
const len = arr.length;
return len;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_typedarray_basic");
    println!("=== TypedArray basic ===\n{}", zig);
    // Verify fromI64AsI32 is generated
    assert!(
        zig.contains("fromI64AsI32"),
        "Expected 'fromI64AsI32' in generated code:\n{}",
        zig
    );
    // Verify .length is generated as .len
    assert!(
        zig.contains(".len"),
        "Expected '.len' for TypedArray length:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_string_escape_backslash() {
    // Verify that backslashes in string literals are properly escaped for Zig output.
    // Without escaping, a string like "hello\nworld" would produce an invalid Zig string.
    let js = r#"function hasNewline() { return "hello\\nworld"; }"#;
    let zig = transpile_and_assert(js, "test_native_proto_string_escape_backslash");
    println!("=== String escape ===\n{}", zig);
    // The JS string "hello\\nworld" has the actual value: hello\nworld (backslash-n)
    // In Zig, this should be emitted as "hello\\nworld"
    assert!(
        zig.contains("hello\\\\nworld"),
        "Expected escaped backslash in:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_string_escape_quote() {
    // Verify that double quotes in string literals are properly escaped for Zig output.
    let js = r#"function hasQuote() { return 'he said "hello"'; }"#;
    let zig = transpile_and_assert(js, "test_native_proto_string_escape_quote");
    println!("=== String escape quote ===\n{}", zig);
    // The JS string 'he said "hello"' has actual double quotes
    // In Zig, this should be emitted as \"he said \\\"hello\\\"\"
    assert!(
        zig.contains(r#"\"hello\""#),
        "Expected escaped double quote in:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_typedarray_uint8() {
    // JS source: new Uint8Array()
    let js = r#"
function makeBytes() {
const bytes = new Uint8Array([1, 2, 3]);
return bytes.length;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_typedarray_uint8");
    println!("=== TypedArray Uint8 ===\n{}", zig);
    assert!(
        zig.contains("fromI64AsU8"),
        "Expected 'fromI64AsU8' in generated code:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_typedarray_length_in_expr() {
    // .length used in arithmetic expression (not just return)
    let js = r#"
/**
 * @returns {number}
 */
export function totalLength() {
const arr1 = new Int32Array([1, 2]);
const arr2 = new Int32Array([3, 4, 5]);
return arr1.length + arr2.length;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_typedarray_length_in_expr");
    println!("=== TypedArray length in expr ===\n{}", zig);
    // Verify .len is generated for both arrays
    assert!(
        zig.matches("arr1.len").count() >= 1,
        "Expected arr1.len in:\n{}",
        zig
    );
    assert!(
        zig.matches("arr2.len").count() >= 1,
        "Expected arr2.len in:\n{}",
        zig
    );
    // Verify the addition is present
    assert!(
        zig.contains(" + "),
        "Expected addition for length sum:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_typedarray_length_as_param() {
    // .length passed as function argument
    let js = r#"
/**
 * @param {number} x
 * @returns {number}
 */
function identity(x) { return x; }

/**
 * @returns {number}
 */
export function getLength() {
const arr = new Int32Array([10, 20, 30, 40]);
return identity(arr.length);
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_typedarray_length_as_param");
    println!("=== TypedArray length as param ===\n{}", zig);
    // Verify arr.len is generated
    assert!(zig.contains("arr.len"), "Expected arr.len in:\n{}", zig);
    assert!(
        zig.contains("identity"),
        "Expected identity call in:\n{}",
        zig
    );
}

// ── TypedArray: set/get/slice/subarray/copyWithin/fill ──

#[test]
fn test_native_proto_typedarray_set() {
    let js = r#"
/**
 * @param {number} idx
 * @param {number} val
 * @returns {number}
 */
export function setAndGet(idx, val) {
const arr = new Int32Array([10, 20, 30]);
arr.set(idx, val);
return arr.get(idx);
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_typedarray_set");
    println!("=== TypedArray set ===\n{}", zig);
    assert!(zig.contains("setI32"), "Expected setI32 in:\n{}", zig);
    assert!(zig.contains("getI32"), "Expected getI32 in:\n{}", zig);
}

#[test]
fn test_native_proto_typedarray_slice() {
    let js = r#"
/**
 * @returns {number}
 */
export function sliceArray() {
const arr = new Int32Array([10, 20, 30, 40, 50]);
const sub = arr.slice(1, 4);
return sub.length;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_typedarray_slice");
    println!("=== TypedArray slice ===\n{}", zig);
    assert!(zig.contains("sliceI32"), "Expected sliceI32 in:\n{}", zig);
}

#[test]
fn test_native_proto_typedarray_subarray() {
    let js = r#"
/**
 * @returns {number}
 */
export function subArray() {
const arr = new Int32Array([1, 2, 3, 4, 5]);
const sub = arr.subarray(1, 3);
return sub.length;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_typedarray_subarray");
    println!("=== TypedArray subarray ===\n{}", zig);
    assert!(
        zig.contains("subarrayI32"),
        "Expected subarrayI32 in:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_typedarray_copywithin() {
    let js = r#"
export function copyIn() {
const arr = new Int32Array([1, 2, 3, 4, 5]);
arr.copyWithin(0, 3, 5);
return arr.get(1);
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_typedarray_copywithin");
    println!("=== TypedArray copyWithin ===\n{}", zig);
    assert!(
        zig.contains("copyWithinI32"),
        "Expected copyWithinI32 in:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_typedarray_fill() {
    let js = r#"
export function fillArr() {
const arr = new Int32Array([1, 2, 3, 4, 5]);
arr.fill(0, 1, 4);
return arr.get(0);
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_typedarray_fill");
    println!("=== TypedArray fill ===\n{}", zig);
    assert!(zig.contains("fillI32"), "Expected fillI32 in:\n{}", zig);
}

// ── TypedArray: buffer / byteLength / byteOffset ──

#[test]
fn test_native_proto_typedarray_buffer() {
    let js = r#"
/**
 * @returns {number}
 */
export function getBufferLength() {
const arr = new Int32Array([1, 2, 3]);
const buf = arr.buffer;
return buf.length;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_typedarray_buffer");
    println!("=== TypedArray buffer ===\n{}", zig);
    assert!(zig.contains("bufferI32"), "Expected bufferI32 in:\n{}", zig);
}

#[test]
fn test_native_proto_typedarray_bytelength() {
    let js = r#"
/**
 * @returns {number}
 */
export function getByteLength() {
const arr = new Int32Array([1, 2, 3]);
return arr.byteLength;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_typedarray_bytelength");
    println!("=== TypedArray byteLength ===\n{}", zig);
    assert!(
        zig.contains("byteLengthI32"),
        "Expected byteLengthI32 in:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_typedarray_byteoffset() {
    let js = r#"
/**
 * @returns {number}
 */
export function getByteOffset() {
const arr = new Int32Array([1, 2, 3]);
return arr.byteOffset;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_typedarray_byteoffset");
    println!("=== TypedArray byteOffset ===\n{}", zig);
    assert!(
        zig.contains("byteOffset"),
        "Expected byteOffset in:\n{}",
        zig
    );
}

// ── TypedArray: Float64Array ──

#[test]
fn test_native_proto_float64array() {
    let js = r#"
/**
 * @returns {number}
 */
export function floatTest() {
const arr = new Float64Array([1.5, 2.5, 3.5]);
return arr.length;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_float64array");
    println!("=== Float64Array ===\n{}", zig);
    assert!(zig.contains("fromF64"), "Expected fromF64 in:\n{}", zig);
}

// ── String escaping edge cases ────────────────────────

#[test]
fn test_native_proto_string_escape_newline() {
    // Verify that newline characters in JS string literals are escaped as \\n in Zig output.
    // JS "line1\nline2" → actual newline (0x0A) in JS → must emit Zig "line1\\nline2"
    // where \\n is the two-byte escape sequence (backslash + n), NOT a raw newline.
    let js = "function hasNewline() { return \"line1\\nline2\"; }";
    let zig = transpile_and_assert(js, "test_native_proto_string_escape_newline");
    println!("=== String escape newline ===\n{}", zig);
    // The Zig output has literal '\' followed by 'n' (NOT the newline character).
    // In Rust, "\\n" matches the two-byte sequence 0x5C 0x6E.
    assert!(
        zig.contains("line1\\nline2"),
        "Expected \\n escape sequence (NOT raw newline) in:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_string_escape_tab() {
    // Verify that tab characters in JS string literals are escaped as \\t in Zig output.
    let js = "function hasTab() { return \"col1\\tcol2\"; }";
    let zig = transpile_and_assert(js, "test_native_proto_string_escape_tab");
    println!("=== String escape tab ===\n{}", zig);
    assert!(
        zig.contains("col1\\tcol2"),
        "Expected \\t escape sequence (NOT raw tab) in:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_json_parse_escaped_quotes() {
    // JSON.parse with a string that contains escaped double quotes.
    let js = r#"
/**
 * @typedef {Object} Msg
 * @property {string} text
 */

/**
 * @returns {string}
 */
export function parseEscapedJson() {
/**
 * @type {Msg}
 */
const msg = JSON.parse('{"text":"he said \\"hello\\""}');
return msg.text;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_json_parse_escaped_quotes");
    println!("=== JSON parse escaped quotes ===\n{}", zig);
    // Verify the JSON string is properly escaped in Zig
    assert!(
        zig.contains("std.json.parse(Msg,"),
        "Expected std.json.parse(Msg, ...), got:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_json_parse_unicode() {
    // JSON.parse with unicode escape sequences.
    let js = r#"
/**
 * @typedef {Object} Item
 * @property {string} name
 */

/**
 * @returns {string}
 */
export function parseUnicodeJson() {
/**
 * @type {Item}
 */
const item = JSON.parse('{"name":"\\u0048\\u0065\\u006c\\u006c\\u006f"}');
return item.name;
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_json_parse_unicode");
    println!("=== JSON parse unicode ===\n{}", zig);
    // Verify std.json.parse is generated
    assert!(
        zig.contains("std.json.parse(Item,"),
        "Expected std.json.parse(Item, ...), got:\n{}",
        zig
    );
    // Unicode escapes should pass through (Zig's std.json.parse handles them)
    assert!(
        zig.contains("\\\\u0048"),
        "Expected unicode escape in:\n{}",
        zig
    );
}

// ── Try-catch tests ──────────────────────────────────