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
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
// Destructuring, class, String methods, Array higher-order, misc

use super::common::*;

#[test]
fn test_p2_destructure_object_basic() {
    // const {a, b} = obj → const a = obj.get("a"); const b = obj.get("b");
    let js = r#"
function basic(obj) {
const { a, b } = obj;
return a + b;
}
"#;
    let zig = transpile_and_assert(js, "test_p2_destructure_object_basic");
    assert!(
        zig.contains("const _js_dest_"),
        "Expected temp variable in:\n{}",
        zig
    );
    assert!(
        zig.contains(".get(\"a\")"),
        "Expected .get(\"a\") access in:\n{}",
        zig
    );
    assert!(
        zig.contains(".get(\"b\")"),
        "Expected .get(\"b\") access in:\n{}",
        zig
    );
}

#[test]
fn test_p2_destructure_object_with_defaults() {
    // const {a = 1, b = 2} = obj (HashMap) →
    //   const a = if (_js_dest_0.get("a")) |v| v.asI64() else 1;
    let js = r#"
function withDefaults(obj) {
const { a = 1, b = 2 } = obj;
return a + b;
}
"#;
    let zig = transpile_and_check(js, "test_p2_destructure_object_with_defaults");
    assert!(
        zig.contains(".asI64() else 1"),
        "Expected '.asI64() else 1' in:\n{}",
        zig
    );
    assert!(
        zig.contains(".asI64() else 2"),
        "Expected '.asI64() else 2' in:\n{}",
        zig
    );
    assert!(
        zig.contains(".get(\"a\")"),
        "Expected .get(\"a\") in:\n{}",
        zig
    );
    assert!(
        zig.contains(".get(\"b\")"),
        "Expected .get(\"b\") in:\n{}",
        zig
    );
}

#[test]
fn test_p2_destructure_object_rename() {
    // const {a: x} = obj → const x = obj.get("a");
    let js = r#"
function rename(obj) {
const { a: x } = obj;
return x;
}
"#;
    let zig = transpile_and_assert(js, "test_p2_destructure_object_rename");
    assert!(
        zig.contains("const x = "),
        "Expected 'const x =' in:\n{}",
        zig
    );
    assert!(
        zig.contains(".get(\"a\")"),
        "Expected .get(\"a\") access in:\n{}",
        zig
    );
}

#[test]
fn test_p2_destructure_object_mixed() {
    // const {a, b: c = 10} = obj (HashMap)
    // a → .get("a"), c → if (.get("b")) |v| v.asI64() else 10 (renamed + default)
    let js = r#"
function mixed(obj) {
const { a, b: c = 10 } = obj;
return a + c;
}
"#;
    let zig = transpile_and_check(js, "test_p2_destructure_object_mixed");
    assert!(
        zig.contains("const a = "),
        "Expected 'const a' in:\n{}",
        zig
    );
    assert!(
        zig.contains("const c = "),
        "Expected 'const c' in:\n{}",
        zig
    );
    assert!(
        zig.contains(".asI64() else 10"),
        "Expected '.asI64() else 10' in:\n{}",
        zig
    );
}

#[test]
fn test_p2_destructure_array_basic() {
    // const [a, b] = arr → const a = arr[0]; const b = arr[1];
    let js = r#"
function arrayBasic(arr) {
const [a, b] = arr;
return a + b;
}
"#;
    let zig = transpile_and_assert(js, "test_p2_destructure_array_basic");
    assert!(zig.contains("[0]"), "Expected '[0]' in:\n{}", zig);
    assert!(zig.contains("[1]"), "Expected '[1]' in:\n{}", zig);
}

#[test]
fn test_p2_destructure_array_with_defaults() {
    // const [a = 1, b = 2] = arr → const a = arr[0] orelse 1; const b = arr[1] orelse 2;
    let js = r#"
function arrayDefaults(arr) {
const [a = 1, b = 2] = arr;
return a + b;
}
"#;
    let zig = transpile_and_check(js, "test_p2_destructure_array_with_defaults");
    assert!(
        zig.contains("[0] orelse 1"),
        "Expected '[0] orelse 1' in:\n{}",
        zig
    );
    assert!(
        zig.contains("[1] orelse 2"),
        "Expected '[1] orelse 2' in:\n{}",
        zig
    );
}

#[test]
fn test_p2_destructure_array_hole() {
    // const [a, , b] = arr → skip hole
    let js = r#"
function arrayHole(arr) {
const [a, , b] = arr;
return a + b;
}
"#;
    let zig = transpile_and_assert(js, "test_p2_destructure_array_hole");
    assert!(zig.contains("[0]"), "Expected '[0]' in:\n{}", zig);
    assert!(zig.contains("[2]"), "Expected '[2]' in:\n{}", zig);
    // Should NOT contain [1]
    assert!(
        !zig.contains("[1]"),
        "Should not contain '[1]' in:\n{}",
        zig
    );
}

#[test]
fn test_p2_destructure_function_call_init() {
    // Destructuring from a function call → temp variable
    let js = r#"
function callInit() {
const obj = { x: 1, y: 2 };
const { x, y } = obj;
return x + y;
}
"#;
    let zig = transpile_and_assert(js, "test_p2_destructure_function_call_init");
    assert!(
        zig.contains("const x = "),
        "Expected 'const x' in:\n{}",
        zig
    );
    assert!(
        zig.contains("const y = "),
        "Expected 'const y' in:\n{}",
        zig
    );
}

#[test]
fn test_p2_nested_function_basic() {
    // Nested function declaration without captures:
    // function outer() { function inner(x) { return x + 1; } return inner(5); }
    // → inner is hoisted as `const inner = struct { pub fn call(...) ... };`
    //   and `inner(5)` is rewritten to `inner.call(5)`
    let js = r#"
function outer() {
function inner(x) {
    return x + 1;
}
return inner(5);
}
"#;
    let zig = transpile_and_assert(js, "test_p2_nested_function_basic");
    assert!(
        zig.contains("const inner = struct {"),
        "Expected inline struct declaration in:\n{}",
        zig
    );
    assert!(
        zig.contains("inner.call(5)"),
        "Expected 'inner.call(5)' in:\n{}",
        zig
    );
    assert!(
        zig.contains("pub fn call("),
        "Expected 'pub fn call(' in:\n{}",
        zig
    );
}

#[test]
fn test_p2_nested_function_capture_error() {
    // Nested function that captures outer variable → now supported!
    let js = r#"
function outer(x) {
function inner(y) {
    return x + y;
}
return inner(10);
}
"#;
    let zig = transpile_and_assert(js, "test_p2_nested_function_capture_error");
    println!("=== Nested function capture Zig code ===\n{}", zig);

    // Verify: inner is defined via named type with capture field (Zig 0.16 syntax)
    assert!(
        zig.contains("_inner_type = struct {"),
        "Expected _inner_type struct declaration"
    );
    assert!(zig.contains("x:"), "Expected capture field x");

    // Verify: inner is instantiated from named type
    assert!(
        zig.contains("inner = _inner_type"),
        "Expected inner = _inner_type instantiation"
    );

    // Verify: call is rewritten to inner.call(args)
    assert!(zig.contains("inner.call("), "Expected call to be rewritten");

    // Verify: struct has call method with self parameter
    assert!(
        zig.contains("pub fn call(self:"),
        "Expected call method with self parameter"
    );
}

#[test]
fn test_p2_nested_function_anytype_return() {
    // Rule 8: Nested function with anytype parameters whose return
    // depends on those parameters should use @TypeOf() via AnytypeReturn.
    // The nested function correctly gets @TypeOf(...) for its return type.
    // The outer function defaults to i64 with a Rule 8 warning because
    // AnytypeReturn cannot be propagated through call boundaries
    // (the nested function is not visible at the return-type position).
    let js = r#"
function outer() {
function add(a, b) {
    return a + b;
}
return add(1, 2);
}
"#;
    let result = parse_and_transpile(js, None).unwrap();
    let zig = result.zig_code;
    println!("=== Nested function (AnytypeReturn) Zig code ===\n{}", zig);

    // Verify: add's return type uses @TypeOf(return expression)
    assert!(
        zig.contains("@TypeOf("),
        "Expected @TypeOf() for AnytypeReturn in:\n{}",
        zig
    );

    // Verify: add is properly lifted as a struct
    assert!(
        zig.contains("const add = struct {"),
        "Expected 'const add = struct {{' in:\n{}",
        zig
    );
    assert!(
        zig.contains("add.call("),
        "Expected call rewriting to add.call() in:\n{}",
        zig
    );

    // The outer function gets a Rule 8 warning because it can't propagate
    // AnytypeReturn through the function call boundary. This is acceptable:
    // Zig's @TypeOf can't reference variables defined inside the function body.
    let rule8_errors: Vec<_> = result
        .errors
        .iter()
        .filter(|e| e.contains("Rule 8"))
        .collect();
    assert_eq!(
        rule8_errors.len(),
        1,
        "Expected exactly one Rule 8 error for 'outer', got: {:?}",
        rule8_errors
    );
    assert!(
        rule8_errors[0].contains("outer"),
        "Rule 8 error should mention 'outer': {:?}",
        rule8_errors
    );
}

// ── Class transpilation tests ────────────────────────────

#[test]
fn test_native_proto_class_basic() {
    // Simple class with i64 fields and area() method
    let js = r#"
class Rectangle {
width = 0;
height = 0;
constructor(w, h) {
    this.width = w;
    this.height = h;
}
area() {
    return this.width * this.height;
}
}

export function testRect() {
const rect = new Rectangle(3, 4);
return rect.area();
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_class_basic");
    println!("=== Class transpilation Zig code ===\n{}", zig);

    // Verify: Rectangle struct is defined
    assert!(
        zig.contains("const Rectangle = struct {"),
        "Expected Rectangle struct definition"
    );

    // Verify: init() maps constructor (may have extra whitespace after param list)
    assert!(
        zig.contains("pub fn init(w: anytype, h: anytype"),
        "Expected init(w, h) constructor. Got:\n{}",
        zig
    );

    // Verify: new Rectangle routes to Rectangle.init
    assert!(
        zig.contains("Rectangle.init("),
        "Expected new Rect→Rectangle.init routing"
    );

    // Verify: area() method exists
    assert!(
        zig.contains("pub fn area(self:"),
        "Expected area method. Got:\n{}",
        zig
    );

    // Verify: export function compiles
    assert!(
        zig.contains("pub fn testRect"),
        "Expected testRect export. Got:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_class_mixed_fields() {
    // Class with i64 + string fields
    let js = r#"
class User {
id = 0;
name = "";
constructor(idVal, nameVal) {
    this.id = idVal;
    this.name = nameVal;
}
getId() {
    return this.id;
}
getName() {
    return this.name;
}
}

export function testUser() {
const u = new User(42, "Alice");
return u.getId();
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_class_mixed_fields");
    println!("=== Class mixed fields Zig code ===\n{}", zig);

    // Verify: User struct defined
    assert!(
        zig.contains("const User = struct {"),
        "Expected User struct"
    );

    // Verify: init with two params
    assert!(zig.contains("pub fn init("), "Expected init method");

    // Verify: new User routes correctly
    assert!(zig.contains("User.init("), "Expected User.init routing");

    // Verify: getId and getName methods exist
    assert!(zig.contains("getId"), "Expected getId method");
    assert!(zig.contains("getName"), "Expected getName method");
}

#[test]
fn test_native_proto_class_implicit_fields() {
    // Class WITHOUT PropertyDefinition — all fields declared via this.x = expr in constructor
    let js = r#"
class Point {
constructor(xVal, yVal) {
    this.x = xVal;
    this.y = yVal;
}
sum() {
    return this.x + this.y;
}
}

export function testPoint() {
const p = new Point(10, 20);
return p.sum();
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_class_implicit_fields");
    println!("=== Class implicit fields Zig code ===\n{}", zig);

    // Verify: Point struct defined
    assert!(
        zig.contains("const Point = struct {"),
        "Expected Point struct definition. Got:\n{}",
        zig
    );

    // Verify: x and y fields are present (inferred from constructor this.x = expr)
    assert!(zig.contains("x:"), "Expected field 'x' in struct");
    assert!(zig.contains("y:"), "Expected field 'y' in struct");

    // Verify: init() maps constructor
    assert!(zig.contains("pub fn init("), "Expected init() constructor");

    // Verify: new Point routes correctly
    assert!(
        zig.contains("Point.init("),
        "Expected new Point→Point.init routing"
    );

    // Verify: sum() method exists
    assert!(zig.contains("pub fn sum(self:"), "Expected sum method");

    // Verify: export function compiles
    assert!(
        zig.contains("pub fn testPoint"),
        "Expected testPoint export"
    );
}

#[test]
fn test_native_proto_array_flat() {
    let js = r#"
export function testFlat() {
const arr = [1, 2, 3];
return arr.flat();
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_array_flat");
    println!("=== Array.flat Zig code ===\n{}", zig);

    // flat() without callback falls through to runtime js_array.flat()
    assert!(zig.contains("testFlat"), "Expected testFlat function");
    assert!(zig.contains("js_array.flat"), "Expected js_array.flat call");
}

#[test]
fn test_native_proto_array_flat_map() {
    let js = r#"
export function testFlatMap() {
const arr = [1, 2, 3];
return arr.flatMap((x) => x * 2);
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_array_flat_map");
    println!("=== Array.flatMap Zig code ===\n{}", zig);

    // flatMap with callback should be inlined (ArrayCallbackKind::FlatMap)
    assert!(zig.contains("testFlatMap"), "Expected testFlatMap function");
    assert!(zig.contains("__fmap"), "Expected __fmap inline expansion");
}

#[test]
fn test_native_proto_string_pad_start() {
    let js = r#"
export function testPadStart() {
const s = "42";
return s.padStart(5, "0");
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_string_pad_start");
    println!("=== String.padStart Zig code ===\n{}", zig);

    // Verify: padStart runtime call generated
    assert!(
        zig.contains("js_string.padStart"),
        "Expected js_string.padStart"
    );
}

#[test]
fn test_native_proto_string_pad_end() {
    let js = r#"
export function testPadEnd() {
const s = "hello";
return s.padEnd(10, ".");
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_string_pad_end");
    println!("=== String.padEnd Zig code ===\n{}", zig);

    // Verify: padEnd runtime call generated
    assert!(
        zig.contains("js_string.padEnd"),
        "Expected js_string.padEnd"
    );
}

// ── Test: String.substring() ─────────────

#[test]
fn test_native_proto_string_substring() {
    let js = r#"
export function testSubstring() {
const s = "hello world";
return s.substring(0, 5);
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_string_substring");
    assert!(
        zig.contains("js_string.substring"),
        "Expected js_string.substring call, got:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_string_substring_swap() {
    // substring(5, 0) should swap to (0, 5) — JS semantics
    let js = r#"
export function testSubstringSwap() {
const s = "hello world";
return s.substring(5, 0);
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_string_substring_swap");
    assert!(
        zig.contains("js_string.substring"),
        "Expected js_string.substring call, got:\n{}",
        zig
    );
}

// ── Test: String.at() (Task #627) ────────────
#[test]
fn test_native_proto_string_at() {
    let js = r#"
export function testAt() {
const s = "hello";
return s.at(1);
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_string_at");
    println!("=== String.at() Zig code ===\n{}", zig);

    // Verify: at() runtime call generated
    assert!(
        zig.contains("js_string.at"),
        "Expected js_string.at call, got:\n{}",
        zig
    );

    // Verify: handles negative index
    let js_neg = r#"
export function testAtNeg() {
const s = "hello";
return s.at(-1);
}
"#;
    let zig_neg = transpile_and_assert(js_neg, "test_native_proto_string_at_neg");
    println!("=== String.at(-1) Zig code ===\n{}", zig_neg);

    assert!(
        zig_neg.contains("js_string.at"),
        "Expected js_string.at call for negative index, got:\n{}",
        zig_neg
    );
}

// ── Test: String.codePointAt() (Task #630) ────────────
#[test]
fn test_native_proto_string_code_point_at() {
    let js = r#"
export function testCodePointAt() {
const s = "hello";
return s.codePointAt(1);
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_string_code_point_at");
    println!("=== String.codePointAt() Zig code ===\n{}", zig);

    // Verify: codePointAt() runtime call generated
    assert!(
        zig.contains("js_string.codePointAt"),
        "Expected js_string.codePointAt call, got:\n{}",
        zig
    );
}

// ── Test: Object.hasOwn() with struct ─────────────

#[test]
fn test_native_proto_object_has_own_struct() {
    let js = r#"
export function testHasOwn() {
const obj = { name: "Alice", age: 30 };
return Object.hasOwn(obj, "name");
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_object_has_own_struct");
    assert!(
        zig.contains("@hasField"),
        "Expected @hasField for struct type, got:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_object_has_own_missing() {
    let js = r#"
export function testHasOwnMissing() {
const obj = { name: "Alice", age: 30 };
return Object.hasOwn(obj, "email");
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_object_has_own_missing");
    assert!(
        zig.contains("@hasField"),
        "Expected @hasField for struct type, got:\n{}",
        zig
    );
}

// ── Test: JSON.parse() without JSDoc (Phase 1) ─────────────

#[test]
fn test_native_proto_json_parse_no_jsdoc() {
    // JSON.parse() without JSDoc should return JsAny type
    let js = r#"
const json = JSON.parse('{"name":"Alice","age":30}');

export function getName() {
return json.name;
}
"#;
    let result = parse_and_transpile(js, None);
    match &result {
        Ok(r) => println!("=== JSON.parse() without JSDoc ===\n{}", r.zig_code),
        Err(e) => println!("=== JSON.parse() without JSDoc ERROR ===\n{:?}", e),
    }
    let zig = result.unwrap().zig_code;

    // Should NOT generate std.json.parse() (that's for JSDoc @type case)
    assert!(
        !zig.contains("std.json.parse("),
        "Should not generate std.json.parse() without JSDoc, got:\n{}",
        zig
    );

    // Should generate js_json.parse() which returns JsAny
    assert!(
        zig.contains("js_json.parse("),
        "Expected js_json.parse(), got:\n{}",
        zig
    );

    // json variable should be declared (Zig infers type as JsAny)
    assert!(
        zig.contains("const json"),
        "Expected 'const json' declaration, got:\n{}",
        zig
    );
}

// ── Test: Array.filter() with concise arrow predicate ─────────────

#[test]
fn test_native_proto_array_filter() {
    // JS source: arr.filter(x => x > 3) — returns filtered ArrayList
    let js = r#"
/**
 * @returns {number}
 */
export function filterCount() {
const arr = [1, 2, 3, 4, 5, 6];
const filtered = arr.filter(x => x > 3);
return filtered.length;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_filter");

    // Verify inline for-loop with ArrayList result
    assert!(zig.contains("blk_"), "Expected labeled block in:\n{}", zig);
    assert!(
        zig.contains("__filter: std.ArrayList("),
        "Expected __filter ArrayList var in:\n{}",
        zig
    );
    assert!(zig.contains("for ("), "Expected for loop in:\n{}", zig);
    assert!(
        zig.contains(".append(js_allocator.allocator()"),
        "Expected append in:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_") && zig.contains("__filter"),
        "Expected break :blk_ __filter in:\n{}",
        zig
    );
    // Should contain the predicate condition: x > 3
    assert!(zig.contains("> 3"), "Expected '> 3' predicate in:\n{}", zig);
}

// ── Test: Array.some() with concise arrow predicate ─────────────

#[test]
fn test_native_proto_array_some() {
    let js = r#"
/**
 * @returns {number}
 */
export function hasMatch() {
const arr = [1, 2, 3, 4, 5];
if (arr.some(x => x > 3)) {
    return 1;
}
return 0;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_some");
    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.every() with concise arrow predicate ─────────────

#[test]
fn test_native_proto_array_every() {
    let js = r#"
/**
 * @returns {number}
 */
export function allPositive() {
const arr = [1, 2, 3, 4, 5];
if (arr.every(x => x > 0)) {
    return 1;
}
return 0;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_every");
    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.some() with block body arrow ─────────────

#[test]
fn test_native_proto_array_some_block_body() {
    let js = r#"
/**
 * @returns {number}
 */
export function someBlockBody() {
const arr = [1, 2, 3, 4, 5];
if (arr.some(x => { return x > 3; })) {
    return 1;
}
return 0;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_some_block_body");
    assert!(
        zig.contains("break :blk_") && zig.contains(" true"),
        "Expected break :blk_ with true, got:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_") && zig.contains(" false"),
        "Expected break :blk_ with false, got:\n{}",
        zig
    );
}

// ── Test: Array.every() with block body arrow ─────────────

#[test]
fn test_native_proto_array_every_block_body() {
    let js = r#"
/**
 * @returns {number}
 */
export function everyBlockBody() {
const arr = [1, 2, 3, 4, 5];
if (arr.every(x => { return x > 0; })) {
    return 1;
}
return 0;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_every_block_body");
    assert!(
        zig.contains("break :blk_") && zig.contains(" true"),
        "Expected break :blk_ with true, got:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_") && zig.contains(" false"),
        "Expected break :blk_ with false, got:\n{}",
        zig
    );
}

// ── Test: Array.concat() ─────────────

#[test]
fn test_native_proto_array_concat() {
    let js = r#"
/**
 * @returns {number}
 */
export function concatLength() {
const a = [1, 2, 3];
const b = [4, 5];
const c = a.concat(b);
return c.length;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_concat");
    assert!(zig.contains("blk_"), "Expected labeled block in:\n{}", zig);
    assert!(
        zig.contains("__concat:"),
        "Expected __concat var in:\n{}",
        zig
    );
    assert!(
        zig.contains("appendSlice"),
        "Expected appendSlice in:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_") && zig.contains("__concat"),
        "Expected break :blk_ __concat in:\n{}",
        zig
    );
}

// ── Test: Array.find() ─────────────

#[test]
fn test_native_proto_array_find() {
    let js = r#"
/**
 * @returns {number}
 */
export function findFirstEven() {
const arr = [1, 2, 3, 4, 5];
const found = arr.find(x => x % 2 === 0);
return found;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_find");
    assert!(
        zig.contains("break :blk_"),
        "Expected break :blk_ with value in:\n{}",
        zig
    );
    // find returns the element (x), not true/false
    assert!(
        zig.contains("break :blk_") && zig.contains(" x"),
        "Expected break :blk_ x in:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_") && zig.contains(" undefined"),
        "Expected break :blk_ undefined fallback in:\n{}",
        zig
    );
}

// ── Test: Array.find() with block body ─────────────

#[test]
fn test_native_proto_array_find_block_body() {
    let js = r#"
/**
 * @returns {number}
 */
export function findBlockBody() {
const arr = [1, 2, 3, 4, 5];
const found = arr.find(x => { return x > 3; });
return found;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_find_block_body");
    assert!(
        zig.contains("break :blk_") && zig.contains(" x"),
        "Expected break :blk_ x in:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_") && zig.contains(" undefined"),
        "Expected break :blk_ undefined fallback in:\n{}",
        zig
    );
}

// ── Test: Array.findIndex() ─────────────

#[test]
fn test_native_proto_array_find_index() {
    let js = r#"
/**
 * @returns {number}
 */
export function findIndexFirstEven() {
const arr = [1, 2, 3, 4, 5];
const idx = arr.findIndex(x => x % 2 === 0);
return idx;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_find_index");
    assert!(zig.contains("for ("), "Expected for loop in:\n{}", zig);
    assert!(
        zig.contains("0..)"),
        "Expected range (0..) for index iteration in:\n{}",
        zig
    );
    assert!(
        zig.contains("@intCast"),
        "Expected @intCast for index in:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_") && zig.contains(" -1"),
        "Expected break :blk_ -1 fallback in:\n{}",
        zig
    );
}

// ── Test: Array.findIndex() with block body ─────────────

#[test]
fn test_native_proto_array_find_index_block_body() {
    let js = r#"
/**
 * @returns {number}
 */
export function findIndexBlockBody() {
const arr = [10, 20, 30, 40];
const idx = arr.findIndex(x => { return x > 25; });
return idx;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_find_index_block_body");
    assert!(
        zig.contains("@intCast"),
        "Expected @intCast for index in:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_") && zig.contains(" -1"),
        "Expected break :blk_ -1 fallback in:\n{}",
        zig
    );
}

// ── Test: Array.findLast() ─────────────

#[test]
fn test_native_proto_array_find_last() {
    let js = r#"
/**
 * @returns {number}
 */
export function findLastEven() {
const arr = [1, 2, 3, 4, 5];
const found = arr.findLast(x => x % 2 === 0);
return found;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_find_last");
    assert!(
        zig.contains("var __i: usize = "),
        "Expected reverse loop in:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_"),
        "Expected break :blk_ with value in:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_") && zig.contains(" undefined"),
        "Expected break :blk_ undefined fallback in:\n{}",
        zig
    );
}

// ── Test: Array.findLastIndex() ─────────────

#[test]
fn test_native_proto_array_find_last_index() {
    let js = r#"
/**
 * @returns {number}
 */
export function findLastIndexEven() {
const arr = [10, 20, 30, 40];
const idx = arr.findLastIndex(x => x % 20 === 0);
return idx;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_find_last_index");
    assert!(
        zig.contains("var __i: usize = "),
        "Expected reverse loop in:\n{}",
        zig
    );
    assert!(
        zig.contains("@intCast"),
        "Expected @intCast for index in:\n{}",
        zig
    );
    assert!(
        zig.contains("break :blk_") && zig.contains(" -1"),
        "Expected break :blk_ -1 fallback in:\n{}",
        zig
    );
}

// ── Test: Array.fill() ─────────────

#[test]
fn test_native_proto_array_fill() {
    let js = r#"
/**
 * @returns {number}
 */
export function fillAll() {
const arr = [1, 2, 3, 4, 5];
arr.fill(0);
return arr[0] + arr[1] + arr[2] + arr[3] + arr[4];
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_fill");
    assert!(zig.contains("for ("), "Expected for loop in:\n{}", zig);
    assert!(
        zig.contains("|*elem|"),
        "Expected pointer iteration |*elem| in:\n{}",
        zig
    );
    assert!(
        zig.contains("elem."),
        "Expected elem.* assignment in:\n{}",
        zig
    );
}

// ── Test: Array.fill() with start/end ─────────────

#[test]
fn test_native_proto_array_fill_range() {
    let js = r#"
/**
 * @returns {number}
 */
export function fillRange() {
const arr = [1, 2, 3, 4, 5];
arr.fill(9, 1, 4);
return arr[1] + arr[2] + arr[3];
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_fill_range");
    assert!(
        zig.contains("@intCast"),
        "Expected @intCast for index conversion in:\n{}",
        zig
    );
    assert!(
        zig.contains("|*elem|"),
        "Expected pointer iteration |*elem| in:\n{}",
        zig
    );
}

// ═══════════════════════════════════════════════════════════════
// Phase 2 P2 builtin method tests
// ═══════════════════════════════════════════════════════════════

// ── Test: Array.at() ─────────────────────────────

#[test]
fn test_native_proto_array_at() {
    // JS source: arr.at(index) — positive and negative indices
    let js = r#"
/**
 * @param {number} idx
 * @returns {number}
 */
export function atIndex(idx) {
const arr = [10, 20, 30, 40, 50];
return arr.at(idx);
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_at");

    // Verify labeled block with clamped index
    assert!(zig.contains("blk_"), "Expected labeled block in:\n{}", zig);
    assert!(
        zig.contains("__at_idx"),
        "Expected __at_idx variable in:\n{}",
        zig
    );
    assert!(
        zig.contains("@intCast(@as(isize, @intCast("),
        "Expected negative index casting in:\n{}",
        zig
    );
    assert!(
        zig.contains(".items[__at_idx]"),
        "Expected .items[__at_idx] access in:\n{}",
        zig
    );
}

// ── Test: Array.lastIndexOf() ─────────────────────

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

    // Verify backward while loop
    assert!(zig.contains("blk_"), "Expected labeled block in:\n{}", zig);
    assert!(
        zig.contains("while (__i >= 0)"),
        "Expected backward while loop in:\n{}",
        zig
    );
    assert!(zig.contains("__i -= 1"), "Expected decrement in:\n{}", zig);
    assert!(
        zig.contains("@as(i64, -1)"),
        "Expected @as(i64, -1) fallback in:\n{}",
        zig
    );
}

// ── Test: Array.copyWithin() ──────────────────────

#[test]
fn test_native_proto_array_copywithin() {
    // JS source: arr.copyWithin(target, start)
    let js = r#"
/**
 * @returns {number}
 */
export function copyArray() {
const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 2);
return arr[0] + arr[1] + arr[2];
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_array_copywithin");

    // Verify inline copy block
    assert!(zig.contains("blk_"), "Expected labeled block in:\n{}", zig);
    assert!(
        zig.contains("__cpw_target"),
        "Expected __cpw_target in:\n{}",
        zig
    );
    assert!(
        zig.contains("__cpw_start"),
        "Expected __cpw_start in:\n{}",
        zig
    );
    assert!(zig.contains("__cpw_cnt"), "Expected __cpw_cnt in:\n{}", zig);
    assert!(
        zig.contains("break :blk_") && zig.contains("&arr"),
        "Expected break :blk_ & in:\n{}",
        zig
    );
}

// ── Test: String.trimStart() ──────────────────────

#[test]
fn test_native_proto_string_trimstart() {
    let js = r#"
export function trimLeft(str) {
return str.trimStart();
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_string_trimstart");

    assert!(
        zig.contains("js_string.trimStart("),
        "Expected js_string.trimStart( in:\n{}",
        zig
    );
}

// ── Test: String.trimEnd() ────────────────────────

#[test]
fn test_native_proto_string_trimend() {
    let js = r#"
export function trimRight(str) {
return str.trimEnd();
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_string_trimend");

    assert!(
        zig.contains("js_string.trimEnd("),
        "Expected js_string.trimEnd( in:\n{}",
        zig
    );
}

// ── Test: String.lastIndexOf() ────────────────────

#[test]
fn test_native_proto_string_lastindexof() {
    // Note: is_string detection requires a string literal, not a variable
    let js = r#"
export function findLastChar() {
return "hello world".lastIndexOf("o");
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_string_lastindexof");

    assert!(
        zig.contains("js_string.lastIndexOf("),
        "Expected js_string.lastIndexOf( in:\n{}",
        zig
    );
    // R8-P1-19: missing fromIndex defaults to std.math.maxInt(i64) so the
    // search starts from the end of the string.
    assert!(
        zig.contains("std.math.maxInt(i64)"),
        "Expected default fromIndex 'std.math.maxInt(i64)' as the third arg in:\n{}",
        zig
    );
}

// ── Test: String.lastIndexOf() with explicit fromIndex (R8-P1-19) ──

#[test]
fn test_native_proto_string_lastindexof_from_index() {
    let js = r#"
export function findLastCharFrom() {
return "hello world".lastIndexOf("o", 5);
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_string_lastindexof_from_index");

    assert!(
        zig.contains("js_string.lastIndexOf("),
        "Expected js_string.lastIndexOf( in:\n{}",
        zig
    );
    // The explicit fromIndex argument should appear as the third parameter.
    assert!(
        zig.contains(", 5)"),
        "Expected explicit fromIndex '5' as the third arg in:\n{}",
        zig
    );
    // When the caller supplies fromIndex explicitly, the default sentinel
    // must NOT be appended.
    assert!(
        !zig.contains("std.math.maxInt(i64)"),
        "Should NOT append default sentinel after explicit fromIndex in:\n{}",
        zig
    );
}

// ── Test: String.match() ──────────────────────────

#[test]
fn test_native_proto_string_match_stub() {
    let js = r#"
export function matchRegex(str) {
return str.match(/hello/);
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_string_match_stub");

    assert!(
        zig.contains("js_string_regex.matchString(js_allocator.allocator(),"),
        "Expected js_string_regex.matchString(js_allocator.allocator(), for String.match() in:\n{}",
        zig
    );
    assert!(
        zig.contains("\"hello\""),
        "Expected pattern '\"hello\"' for String.match() in:\n{}",
        zig
    );
}

// ── Test: String.search() stub ────────────────────

#[test]
fn test_native_proto_string_search_stub() {
    let js = r#"
export function searchRegex(str) {
return str.search(/world/);
}
"#;
    let result = parse_and_transpile(js, None).unwrap();
    let zig = result.zig_code;

    assert!(
        zig.contains("host_regex.regex_search"),
        "Expected 'host_regex.regex_search' for String.search() in:\n{}",
        zig
    );
}

// ── Test: Object.is() ─────────────────────────────

#[test]
fn test_native_proto_object_is() {
    let js = r#"
export function sameValue(a, b) {
return Object.is(a, b);
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_object_is");

    // P0-2: Object.is now dispatches by type. For untyped params (JsAny),
    // it uses JsAny.sameValue() which implements ECMA-262 §7.2.10
    // (NaN===NaN→true, +0 vs -0→false) internally.
    assert!(zig.contains("sameValue"), "Expected sameValue in:\n{}", zig);
    assert!(
        zig.contains("Object.is") || zig.contains("sameValue"),
        "Expected Object.is or sameValue in:\n{}",
        zig
    );
}

// ── Test: Object.getOwnPropertyNames() ───────

#[test]
fn test_native_proto_object_getownpropertynames() {
    let js = r#"
export function getPropNames(obj) {
return Object.getOwnPropertyNames(obj);
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_object_getownpropertynames");
    println!("=== Object.getOwnPropertyNames Zig code ===\n{}", zig);

    // Should now emit actual runtime call, not @compileError
    assert!(
        zig.contains("getOwnPropertyNames"),
        "Expected getOwnPropertyNames in:\n{}",
        zig
    );
    assert!(
        !zig.contains("@compileError"),
        "Should not have @compileError for getOwnPropertyNames in:\n{}",
        zig
    );
}

// ═══════════════════════════════════════════════════════════════
// Anonymous object type annotation tests
// ═══════════════════════════════════════════════════════════════

// ── Test: @returns {{name: string, age: number}} on export fn ──

#[test]
fn test_native_proto_anon_obj_type_returns() {
    // JS source: @returns {{name: string, age: number}} on export fn
    let js = r#"
/**
 * @returns {{name: string, age: number}}
 */
export function makeUser() {
const user = { name: "Bob", age: 25 };
return user;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_anon_obj_type_returns");
    println!("=== Anonymous object @returns Zig code ===\n{}", zig);

    // Verify struct fields are present in the generated Zig
    assert!(
        zig.contains("name") && zig.contains("age"),
        "Expected name and age fields, got:\n{}",
        zig
    );
    // The return type uses Zig anonymous struct literal syntax
    assert!(
        zig.contains("pub fn makeUser"),
        "Expected pub fn makeUser in:\n{}",
        zig
    );
}

// ── Test: @type {{name: string, age: number}} on non-JSON.parse var ──

#[test]
fn test_native_proto_anon_obj_type_variable_access() {
    // Test that @type {{name: string, age: number}} correctly infers
    // struct fields, and property access returns correct types
    let js = r#"
/**
 * @returns {string}
 */
export function getName() {
/**
 * @type {{name: string, age: number}}
 */
const user = { name: "Alice", age: 30 };
return user.name;
}

/**
 * @returns {number}
 */
export function getAge() {
/**
 * @type {{name: string, age: number}}
 */
const user = { name: "Alice", age: 30 };
return user.age;
}
"#;
    let zig = transpile_and_check(js, "test_native_proto_anon_obj_type_variable_access");
    println!("=== Anonymous object @type variable Zig code ===\n{}", zig);

    // Verify .name and .age property access is generated
    assert!(
        zig.contains(".name"),
        "Expected .name property access in:\n{}",
        zig
    );
    assert!(
        zig.contains(".age"),
        "Expected .age property access in:\n{}",
        zig
    );
}

// ── Test: Number.* static constants ──────────────────────