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
// Private fields, not-implemented, regression fixes, shadowing, method chaining

use super::common::*;

#[test]
fn test_p3_mixed_decl_expr_basic() {
    // Basic: var declaration followed by expression statements.
    // Should not produce unused variable warnings in Zig output.
    let js = r#"
export function mixDeclExpr(x, y) {
const z = x + y;
return z;
}
"#;
    let zig = transpile_and_check(js, "test_p3_mixed_decl_expr_basic");
    println!("=== Mix decl+expr (basic) ===\n{}", zig);
    // z should be used (returned), no suppression needed
    assert!(
        zig.contains("z = (x + y)"),
        "Expected 'z = (x + y)':\n{}",
        zig
    );
}

#[test]
fn test_p3_mixed_decl_expr_unused_var() {
    // Variable declared but never read → Zig correctly reports "unused local constant".
    // This is a feature, not a bug: Zig catches JS code quality issues.
    // We do NOT suppress this error — the transpiler faithfully translates JS to Zig,
    // and the Zig compiler helpfully flags dead code.
    // Known-expected: no ast-check (Zig will reject unused local consts).
    let js = r#"
export function mixUnusedVar(x) {
const z = x * 2;
return x + 1;
}
"#;
    let zig = transpile_and_assert(js, "test_p3_mixed_decl_expr_unused_var");
    println!("=== Mix decl+expr (unused var) ===\n{}", zig);
    // z is unused — Zig compiler will reject with "unused local constant".
    // This is intended: it forces JS authors to clean up dead code.
}

#[test]
fn test_p3_mixed_decl_expr_call() {
    // Expression statement with function call between declarations.
    let js = r#"
export function mixDeclCall(x) {
const a = x + 1;
const b = x + 2;
return a + b;
}
"#;
    let zig = transpile_and_check(js, "test_p3_mixed_decl_expr_call");
    println!("=== Mix decl+expr (call) ===\n{}", zig);
    // All variables are used, no suppression needed
    assert!(
        zig.contains("a = (x + 1)"),
        "Expected 'a = (x + 1)':\n{}",
        zig
    );
    assert!(
        zig.contains("b = (x + 2)"),
        "Expected 'b = (x + 2)':\n{}",
        zig
    );
}

#[test]
fn test_p3_mixed_decl_expr_return_unused() {
    // Expression result not consumed (standalone expression as statement).
    let js = r#"
export function mixStandaloneExpr(x) {
const z = x + 1;
return z;
}
"#;
    let zig = transpile_and_check(js, "test_p3_mixed_decl_expr_return_unused");
    println!("=== Mix decl+expr (standalone) ===\n{}", zig);
    // z is used, no suppression
}

#[test]
fn test_native_proto_private_field_basic() {
    // ES2022 private field #field with numeric default, access via this.#field
    let js = r#"
class Counter {
#count = 10;
increment() {
    return this.#count + 1;
}
getCount() {
    return this.#count;
}
}

export function testCounter() {
const c = new Counter();
return c.getCount();
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_private_field_basic");
    println!("=== Private field Zig code ===\n{}", zig);

    // Verify: Counter struct defined
    assert!(
        zig.contains("const Counter = struct {"),
        "Expected Counter struct"
    );
    // Verify: private field name is stripped of # prefix
    assert!(zig.contains("count:"), "Expected count field in struct");
    // Verify: default value from #count = 10 is preserved
    assert!(
        zig.contains(".count = 10") || zig.contains(".count=10"),
        "Expected default value 10. Got:\n{}",
        zig
    );
    // Verify: this.#count → self.count
    assert!(
        zig.contains("self.count"),
        "Expected self.count access. Got:\n{}",
        zig
    );
    // Verify: increment method exists
    assert!(zig.contains("increment"), "Expected increment method");
    // Verify: getCount method exists
    assert!(zig.contains("getCount"), "Expected getCount method");
}

#[test]
fn test_native_proto_private_field_no_default() {
    // Private field without explicit default → type is JsAny → zero is undefined
    let js = r#"
class Widget {
#id;
getId() {
    return this.#id;
}
}

export function testWidget() {
const w = new Widget();
return w.getId();
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_private_field_no_default");
    println!("=== Private field (no default) Zig code ===\n{}", zig);

    // Verify: Widget struct defined
    assert!(
        zig.contains("const Widget = struct {"),
        "Expected Widget struct"
    );
    // Verify: field exists (name without #)
    assert!(zig.contains("id:"), "Expected id field");
    // Verify: default init uses undefined (JsAny zero value, not 0)
    assert!(
        zig.contains(".id = undefined"),
        "Expected default=undefined. Got:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_private_field_string_default() {
    // Private field with string default
    let js = r#"
class Logger {
#name = "default";
getName() {
    return this.#name;
}
}

export function testLogger() {
const log = new Logger();
return log.getName();
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_private_field_string_default");
    println!("=== Private field (string) Zig code ===\n{}", zig);

    // Verify: string default preserved
    assert!(
        zig.contains(".name = \"default\""),
        "Expected string default. Got:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_private_field_multiple() {
    // Multiple private fields with mixed defaults
    let js = r#"
class Config {
#port = 8080;
#host = "localhost";
#secure = true;
getHost() {
    return this.#host;
}
}

export function testConfig() {
const cfg = new Config();
return cfg.getHost();
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_private_field_multiple");
    println!("=== Private fields (multiple) Zig code ===\n{}", zig);

    // Verify: all fields with correct defaults
    assert!(
        zig.contains(".port = 8080") || zig.contains(".port=8080"),
        "Expected port=8080. Got:\n{}",
        zig
    );
    assert!(
        zig.contains(".host = \"localhost\""),
        "Expected host default. Got:\n{}",
        zig
    );
    assert!(
        zig.contains(".secure = true") || zig.contains(".secure=true"),
        "Expected secure=true. Got:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_private_field_mixed_with_public() {
    // Class with both private and public fields
    let js = r#"
class Person {
name = "anonymous";
#age = 0;
constructor(nameVal, ageVal) {
    this.name = nameVal;
    this.#age = ageVal;
}
getAge() {
    return this.#age;
}
describe() {
    return this.name;
}
}

export function testPerson() {
const p = new Person("Alice", 30);
return p.describe();
}
"#;
    let zig = transpile_and_assert(js, "test_native_proto_private_field_mixed");
    println!("=== Private+public fields Zig code ===\n{}", zig);

    // Verify: Person struct defined
    assert!(
        zig.contains("const Person = struct {"),
        "Expected Person struct"
    );
    // Verify: both public and private fields present
    assert!(zig.contains("name:"), "Expected name field");
    assert!(zig.contains("age:"), "Expected age field (stripped #)");
    // Verify: init has both fields
    assert!(
        zig.contains("pub fn init("),
        "Expected init() constructor. Got:\n{}",
        zig
    );
    // Verify: new Person routes correctly
    assert!(zig.contains("Person.init("), "Expected Person.init routing");
    // Verify: this.#age → self.age
    assert!(zig.contains("self.age"), "Expected self.age. Got:\n{}", zig);
}

// ── 🔘 不实现特性检查 ─────────────────────────────────────────────
// 验证所有标记为 🔘 不实现的特性都能报编译错误
// 合格标准:result.errors 非空 或 zig_code 包含 @compileError

#[test]
fn test_bigint_add() {
    // ✅ BigInt 字面量: 2n + 3n (现已支持)
    let zig = transpile_and_assert(
        r#"
function test() {
return 2n + 3n;
}
"#,
        "test_bigint_add",
    );
    assert!(
        zig.contains("JsBigInt"),
        "BigInt expr should generate JsBigInt code"
    );
}

#[test]
fn test_not_implemented_tagged_template() {
    // 🔘 标签模板: tag`...`
    assert_not_implemented(
        r#"
function tag(parts, ...args) { return parts[0]; }
const result = tag`hello ${1}`;
"#,
        "Tagged template literal",
    );
}

#[test]
fn test_implemented_instanceof_runtime() {
    // ✅ instanceof 运算符 — fallback runtime dispatch for untyped params
    let js = r#"
function check(arr) {
return arr instanceof Array;
}
"#;
    let zig = transpile_and_assert(js, "test_implemented_instanceof_runtime");
    assert!(
        zig.contains("instanceOf"),
        "Expected instanceOf call in:\n{}",
        zig
    );
    assert!(
        zig.contains("\"Array\""),
        "Expected 'Array' string literal in:\n{}",
        zig
    );
}

#[test]
fn test_class_expression() {
    // ✅ Class expression: const X = class { constructor(val) { this.x = val; } }
    // The class struct is emitted as a module-level declaration, and the
    // variable is assigned a reference to it.
    let js = r#"
/**
 * @returns {i64}
 */
export function testClassExpr() {
const X = class { constructor(val) { this.x = val; } };
const obj = X.init(42);
return obj.x;
}
"#;
    let zig = transpile_and_check(js, "test_class_expression");
    assert!(
        zig.contains("_AnonClass_0 = struct") || zig.contains("= struct"),
        "Expected class struct in:\n{}",
        zig
    );
    assert!(
        zig.contains("init("),
        "Expected init constructor in:\n{}",
        zig
    );
}

#[test]
fn test_class_expression_named() {
    // ✅ Named class expression: const X = class Y { ... }
    let js = r#"
/**
 * @returns {i64}
 */
export function testNamedClassExpr() {
const X = class MyClass { constructor(val) { this.x = val; } };
const obj = X.init(99);
return obj.x;
}
"#;
    let zig = transpile_and_check(js, "test_class_expression_named");
    assert!(
        zig.contains("MyClass = struct"),
        "Expected named class struct in:\n{}",
        zig
    );
    assert!(
        zig.contains("const X = MyClass"),
        "Expected X assigned to MyClass in:\n{}",
        zig
    );
}

#[test]
fn test_class_extends_compile_error() {
    // BUG-14: `class extends` should produce @compileError, not silently
    // accept the extends keyword without inheritance.
    let js = r#"
class Animal {
    constructor(name) { this.name = name; }
    speak() { return this.name; }
}
class Dog extends Animal {
    constructor(name) { super(name); }
    bark() { return this.name; }
}
"#;
    let result = parse_and_transpile(js, None).unwrap();
    assert!(
        result
            .errors
            .iter()
            .any(|e| e.contains("class extends is not supported")),
        "Expected 'class extends is not supported' in errors: {:?}",
        result.errors
    );
    assert!(
        result
            .zig_code
            .contains("@compileError(\"class extends is not supported"),
        "Expected @compileError in zig code:\n{}",
        result.zig_code
    );
}

#[test]
fn test_class_extends_expression_compile_error() {
    // BUG-14: class expression with extends should also produce @compileError.
    let js = r#"
/** @returns {i64} */
export function fn() {
    const Base = class { constructor(v) { this.x = v; } };
    const Child = class extends Base { constructor(v) { super(v); } };
    return 0;
}
"#;
    let result = parse_and_transpile(js, None).unwrap();
    assert!(
        result
            .errors
            .iter()
            .any(|e| e.contains("class extends is not supported")),
        "Expected 'class extends is not supported' in errors: {:?}",
        result.errors
    );
    assert!(
        result
            .zig_code
            .contains("@compileError(\"class extends is not supported"),
        "Expected @compileError in zig code:\n{}",
        result.zig_code
    );
}

#[test]
fn test_not_implemented_generator_function() {
    // 🔘 function*: 生成器函数
    assert_not_implemented(
        r#"
function* gen() { yield 1; yield 2; }
"#,
        "Generator function (function*)",
    );
}

#[test]
fn test_not_implemented_yield_expression() {
    // 🔘 yield: 生成器 yield 表达式
    assert_not_implemented(
        r#"
function* gen() { yield 1; }
const g = gen();
const val = g.next().value;
"#,
        "Yield expression (inside generator)",
    );
}

#[test]
fn test_not_implemented_async_generator() {
    // 🔘 async function*: 异步生成器
    assert_not_implemented(
        r#"
async function* gen() { yield 1; }
"#,
        "Async generator (async function*)",
    );
}

#[test]
fn test_not_implemented_dynamic_import() {
    // 🔘 动态 import(): import("module")
    assert_not_implemented(
        r#"
const mod = import("some_module");
"#,
        "Dynamic import()",
    );
}

#[test]
fn test_not_implemented_new_target() {
    // 🔘 new.target: meta property
    assert_not_implemented(
        r#"
function Foo() {
if (new.target) { return 1; }
return 0;
}
"#,
        "new.target meta property",
    );
}

#[test]
fn test_not_implemented_for_await_of() {
    // 🔘 for await...of: 异步迭代
    assert_not_implemented(
        r#"
async function process(items) {
for await (const item of items) { }
}
"#,
        "for await...of (async iteration)",
    );
}

#[test]
fn test_import_meta_is_compile_error() {
    // 🔘 import.meta: 改为 @compileError(无法在 Zig 运行时中正确表示)
    let result = parse_and_transpile(
        r#"
function getMeta() {
return import.meta.url;
}
"#,
        None,
    )
    .unwrap();
    // import.meta 应产生 "not supported" 错误
    let has_not_supported = result.errors.iter().any(|e| e.contains("not supported"));
    assert!(
        has_not_supported,
        "import.meta should produce 'not supported' error, got: {:?}",
        result.errors
    );
    // 应生成 @compileError
    assert!(
        result.zig_code.contains("@compileError"),
        "import.meta should generate @compileError: {}",
        result.zig_code
    );
}

#[test]
fn test_not_implemented_with_statement() {
    // 🔘 with 语句: with (obj) {}
    assert_not_implemented(
        r#"
const obj = { x: 1 };
with (obj) { console.log(x); }
"#,
        "with statement",
    );
}

#[test]
fn test_not_implemented_debugger_statement() {
    // 🔘 debugger 语句
    assert_not_implemented(
        r#"
function buggy() {
debugger;
}
"#,
        "debugger statement",
    );
}

#[test]
fn test_arguments_object() {
    // ✅ arguments object: now supported
    let js = r#"
function sum(a, b) {
let total = 0;
for (let i = 0; i < arguments.length; i++) { total += arguments[i]; }
return total;
}
"#;
    let zig = transpile_and_check(js, "test_arguments_object");
    assert!(
        zig.contains("__arguments"),
        "Expected __arguments variable in:\n{}",
        zig
    );
}

#[test]
fn test_static_block_no_error() {
    // ✅ static {}: initialization block — no longer produces a compileError.
    // (Full support for static field mutation in static blocks requires
    // static-var emission which is not yet complete.)
    let js = r#"
class Foo {
static x = 1;
}
"#;
    let zig = transpile_and_check(js, "test_static_block");
    // Verify: no @compileError about "static {} blocks are not supported"
    assert!(
        !zig.contains("static {} blocks are not supported"),
        "static block should not produce error about unsupported, got:\n{}",
        zig
    );
    assert!(
        !zig.contains("@compileError"),
        "should not have compileError, got:\n{}",
        zig
    );
}

#[test]
fn test_static_field_read() {
    // ✅ Static field read: ClassName.field → __ClassName_field module-scope var
    let js = r#"
class Foo {
  static x = 1;
}
/**
 * @returns {number}
 */
export function readStatic() {
  return Foo.x;
}
"#;
    let zig = transpile_and_check(js, "test_static_field_read");
    assert!(
        zig.contains("__Foo_x"),
        "Expected __Foo_x in output:\n{}",
        zig
    );
}

#[test]
fn test_static_field_assign() {
    // ✅ Static field write: ClassName.field = value → __ClassName_field = value
    let js = r#"
class Foo {
  static x = 1;
}
/**
 * @param {number} v
 * @returns {number}
 */
export function writeStatic(v) {
  Foo.x = v;
  return Foo.x;
}
"#;
    let zig = transpile_and_check(js, "test_static_field_assign");
    assert!(
        zig.contains("__Foo_x = v"),
        "Expected '__Foo_x = v' in output:\n{}",
        zig
    );
    assert!(
        zig.contains("return __Foo_x"),
        "Expected 'return __Foo_x' in output:\n{}",
        zig
    );
}

#[test]
fn test_static_block_this_read() {
    // ✅ `this.field` inside static {} → reads static field like ClassName.field
    let js = r#"
class Foo {
  static x = 1;
  static {
    this.x = this.x + 1;
  }
}
"#;
    let zig = transpile_and_check(js, "test_static_block_this_read");
    assert!(
        !zig.contains("@compileError"),
        "Should not produce compileError, got:\n{}",
        zig
    );
    // this.x read should produce __Foo_x, and write should produce __Foo_x =
    assert!(
        zig.contains("__Foo_x"),
        "Expected __Foo_x for this.x access:\n{}",
        zig
    );
}

#[test]
fn test_static_block_this_write() {
    // ✅ `this.field = value` inside static {} → writes static field like ClassName.field = value
    let js = r#"
class Foo {
  static x = 1;
  static {
    this.x = 42;
  }
}
"#;
    let zig = transpile_and_check(js, "test_static_block_this_write");
    assert!(
        !zig.contains("@compileError"),
        "Should not produce compileError, got:\n{}",
        zig
    );
    assert!(
        zig.contains("__Foo_x = 42"),
        "Expected '__Foo_x = 42' for this.x = 42:\n{}",
        zig
    );
}

// ── ✅ ES2023 Array immutable methods (now implemented) ──────────

#[test]
fn test_array_with() {
    // ✅ Array.prototype.with(index, value) — ES2023 immutable method
    let js = r#"
/**
 * @returns {number}
 */
export function testWith() {
const arr = [1, 2, 3];
const arr2 = arr.with(1, 99);
return arr2[1];
}
"#;
    let zig = transpile_and_check(js, "test_array_with");
    assert!(
        zig.contains("__with"),
        "Expected __with variable in:\n{}",
        zig
    );
    assert!(
        zig.contains("appendSlice"),
        "Expected clone via appendSlice in:\n{}",
        zig
    );
}

#[test]
fn test_array_to_reversed() {
    // ✅ Array.prototype.toReversed() — ES2023 immutable method
    let js = r#"
/**
 * @returns {number}
 */
export function testToReversed() {
const arr = [1, 2, 3];
const arr2 = arr.toReversed();
return arr2[0];
}
"#;
    let zig = transpile_and_check(js, "test_array_to_reversed");
    assert!(
        zig.contains("__rev"),
        "Expected __rev variable in:\n{}",
        zig
    );
    assert!(
        zig.contains("append"),
        "Expected append in reversed loop in:\n{}",
        zig
    );
}

#[test]
fn test_not_implemented_string_raw() {
    // 🔘 String.raw: 标签模板静态方法
    assert_not_implemented(
        r#"
function test() {
return String.raw`hello\nworld`;
}
"#,
        "String.raw (tagged template static method)",
    );
}

#[test]
fn test_not_implemented_map_group_by() {
    // 🔘 Map.groupBy(): ES2024 静态方法
    assert_not_implemented(
        r#"
function groupByAge(people) {
return Map.groupBy(people, (p) => p.age > 18 ? "adult" : "child");
}
"#,
        "Map.groupBy() (ES2024)",
    );
}

#[test]
fn test_not_implemented_set_operations() {
    // 🔘 Set.prototype.difference() etc: ES2025 Set 操作
    assert_not_implemented(
        r#"
function test() {
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
return a.difference(b);
}
"#,
        "Set.prototype.difference() (ES2025 Set operation)",
    );
}

#[test]
fn test_not_implemented_set_union() {
    // 🔘 Set.prototype.union(): ES2025 Set 操作
    assert_not_implemented(
        r#"
function test() {
const a = new Set([1, 2]);
const b = new Set([2, 3]);
return a.union(b);
}
"#,
        "Set.prototype.union() (ES2025 Set operation)",
    );
}

#[test]
fn test_not_implemented_set_is_subset_of() {
    // 🔘 Set.prototype.isSubsetOf(): ES2025 Set 操作
    assert_not_implemented(
        r#"
function test() {
const a = new Set([1, 2]);
const b = new Set([1, 2, 3]);
return a.isSubsetOf(b);
}
"#,
        "Set.prototype.isSubsetOf() (ES2025 Set operation)",
    );
}

#[test]
fn test_not_implemented_object_get_own_property_symbols() {
    // 🔘 Object.getOwnPropertySymbols(): Symbol 属性
    assert_not_implemented(
        r#"
function test(obj) {
return Object.getOwnPropertySymbols(obj);
}
"#,
        "Object.getOwnPropertySymbols()",
    );
}

#[test]
fn test_object_group_by() {
    // ✅ Object.groupBy(): ES2024 static method now supported
    // Uses a simple callback with number comparison on array literal
    let js = r#"
/**
 * @returns {JsAny}
 */
export function test() {
const items = [1, 2, 3];
return Object.groupBy(items, (item) => item > 1 ? "big" : "small");
}
"#;
    let zig = transpile_and_check(js, "test_object_group_by");
    assert!(
        zig.contains("_grp_map"),
        "Expected _grp_map in groupBy emit:\n{}",
        zig
    );
}

#[test]
fn test_date_set_time() {
    // ✅ Date.prototype.setTime(): now supported
    let js = r#"
function test() {
const d = new Date();
return d.setTime(0);
}
"#;
    let zig = transpile_and_check(js, "test_date_set_time");
    assert!(zig.contains("setTime"), "Expected setTime in:\n{}", zig);
}

#[test]
fn test_date_to_utc_string() {
    // ✅ Date.prototype.toUTCString(): now supported
    let js = r#"
function test() {
const d = new Date();
return d.toUTCString();
}
"#;
    let zig = transpile_and_check(js, "test_date_to_utc_string");
    assert!(
        zig.contains("toUTCString"),
        "Expected toUTCString in:\n{}",
        zig
    );
}

#[test]
fn test_not_implemented_eval() {
    // 🔘 eval(): 安全风险,编译时无法动态执行
    assert_not_implemented(
        r#"
function test() {
return eval("1 + 2");
}
"#,
        "eval() (security risk)",
    );
}

#[test]
fn test_regexp_source() {
    // ✅ RegExp.prototype.source: now supported
    let js = r#"
function test() {
const re = /abc/g;
return re.source;
}
"#;
    let zig = transpile_and_check(js, "test_regexp_source");
    assert!(
        zig.contains("pattern"),
        "Expected pattern field access in:\n{}",
        zig
    );
}

#[test]
fn test_not_implemented_promise() {
    // 🔘 new Promise(): 建议用 async/await + Io 替代
    assert_not_implemented(
        r#"
function test() {
const p = new Promise((resolve, reject) => { resolve(1); });
return p;
}
"#,
        "new Promise() (use async/await instead)",
    );
}

#[test]
fn test_not_implemented_promise_static_methods() {
    // 🔘 Promise.all/race/resolve/reject: 静态方法也不支持
    assert_not_implemented(
        r#"
function test() {
return Promise.all([1, 2, 3]);
}
"#,
        "Promise.all() (use async/await + host functions instead)",
    );
}

#[test]
fn test_not_implemented_intl_static_methods() {
    // 🔘 Intl.NumberFormat/DateTimeFormat: 静态方法调用也不支持
    assert_not_implemented(
        r#"
function test() {
const fmt = Intl.NumberFormat("en-US");
return fmt;
}
"#,
        "Intl.NumberFormat() (use Zig/C library for internationalization)",
    );
}

#[test]
fn test_not_implemented_weakmap() {
    // 🔘 WeakMap: Zig 内存管理不同
    assert_not_implemented(
        r#"
function test() {
const wm = new WeakMap();
return wm;
}
"#,
        "WeakMap (Zig memory model different)",
    );
}

#[test]
fn test_not_implemented_weakset() {
    // 🔘 WeakSet: Zig 内存管理不同
    assert_not_implemented(
        r#"
function test() {
const ws = new WeakSet();
return ws;
}
"#,
        "WeakSet (Zig memory model different)",
    );
}

#[test]
fn test_not_implemented_reflect() {
    // 🔘 Reflect: 反射 API,Zig 不需要
    assert_not_implemented(
        r#"
function test(obj) {
return Reflect.has(obj, "x");
}
"#,
        "Reflect API (not needed in Zig)",
    );
}

#[test]
fn test_not_implemented_intl() {
    // 🔘 Intl: 国际化,可调用 Zig/C 库
    assert_not_implemented(
        r#"
function test() {
const fmt = new Intl.NumberFormat("en-US");
return fmt.format(1234.5);
}
"#,
        "Intl (use Zig/C library instead)",
    );
}

#[test]
fn test_bigint_constructor() {
    // ✅ BigInt(): 大整数构造函数 (现已支持)
    let zig = transpile_and_assert(
        r#"
function test() {
return BigInt(123);
}
"#,
        "test_bigint_constructor",
    );
    assert!(
        zig.contains("fromValue"),
        "BigInt(123) should generate fromValue code, got:\n{}",
        zig
    );
}

#[test]
fn test_not_implemented_atomics() {
    // 🔘 Atomics: 共享内存原子操作,niche 场景
    assert_not_implemented(
        r#"
function test(arr) {
return Atomics.load(arr, 0);
}
"#,
        "Atomics (niche scenario)",
    );
}

// ── for 循环初始值修复 ──────────────────────────────────────────
#[test]
fn test_for_loop_nonzero_init() {
    // Bug fix: `for (let i = 1; ...)` was erroneously emitting `var i: i64 = 0`
    // instead of `var i: i64 = 1`. Now the actual init expression is emitted.
    let js = r#"
/**
 * @returns {i64}
 */
export function sumFrom1() {
let sum = 0;
for (let i = 1; i <= 5; i = i + 1) {
    sum = sum + i;
}
return sum;
}
"#;
    let zig = transpile_and_assert(js, "test_for_loop_nonzero_init");
    assert!(
        zig.contains("var i: i64 = 1"),
        "Expected 'var i: i64 = 1' (not 0) in generated code:\n{}",
        zig
    );
    assert!(
        !zig.contains("var i: i64 = 0"),
        "Should not contain 'var i: i64 = 0' when init is 1:\n{}",
        zig
    );
}

// ── 补充:遗漏的 🔘 不实现特性 ──────────────────────────────────

#[test]
fn test_array_to_sorted() {
    // ✅ Array.prototype.toSorted() — ES2023 immutable method
    let js = r#"
/**
 * @returns {number}
 */
export function testToSorted() {
const arr = [3, 1, 2];
const arr2 = arr.toSorted();
return arr2[0];
}
"#;
    let zig = transpile_and_check(js, "test_array_to_sorted");
    assert!(
        zig.contains("__sorted"),
        "Expected __sorted variable in:\n{}",
        zig
    );
    assert!(zig.contains("sort"), "Expected sort call in:\n{}", zig);
}

#[test]
fn test_array_to_spliced() {
    // ✅ Array.prototype.toSpliced() — ES2023 immutable method
    let js = r#"
/**
 * @returns {number}
 */
export function testToSpliced() {
const arr = [1, 2, 3, 4];
const arr2 = arr.toSpliced(1, 2);
return arr2[1];
}
"#;
    let zig = transpile_and_check(js, "test_array_to_spliced");
    assert!(zig.contains("__sp"), "Expected __sp variable in:\n{}", zig);
    assert!(
        zig.contains("orderedRemove"),
        "Expected orderedRemove in:\n{}",
        zig
    );
}

#[test]
fn test_regexp_flags() {
    // ✅ RegExp.prototype.flags: now supported
    let js = r#"
function test() {
const re = /abc/gi;
return re.flags;
}
"#;
    let zig = transpile_and_check(js, "test_regexp_flags");
    assert!(
        zig.contains("flags"),
        "Expected flags field access in:\n{}",
        zig
    );
}

#[test]
fn test_regexp_global() {
    // ✅ RegExp.prototype.global: now supported
    let js = r#"
function test() {
const re = /abc/g;
return re.global;
}
"#;
    let zig = transpile_and_check(js, "test_regexp_global");
    assert!(
        zig.contains("global"),
        "Expected global field access in:\n{}",
        zig
    );
}

// ── 边缘情况:带类型标注的 🔘 特性 ──────────────────────────────
// 验证即使添加 @returns 类型标注,不实现特性仍然报错

#[test]
fn test_implemented_instanceof_with_annotation() {
    // ✅ instanceof with @returns annotation — no longer produces @compileError
    // Without JSDoc param type, arr is inferred from usage or defaults to anytype.
    // The key assertion is that instanceof is handled (no @compileError).
    let js = r#"
/**
 * @returns {bool}
 */
function check(arr) {
return arr instanceof Array;
}
"#;
    let zig = transpile_and_check(js, "test_implemented_instanceof_with_annotation");
    assert!(
        !zig.contains("@compileError"),
        "Should not contain @compileError:\n{}",
        zig
    );
    // Should produce either a runtime instanceOf call or a compile-time literal
    assert!(
        zig.contains("instanceOf") || zig.contains("true") || zig.contains("false"),
        "Expected instanceof resolution in:\n{}",
        zig
    );
}

#[test]
fn test_not_implemented_eval_with_annotation() {
    // 🔘 eval() 带返回类型标注 — 不应静默通过
    assert_not_implemented(
        r#"
/**
 * @returns {i64}
 */
function test() {
return eval("1 + 2");
}
"#,
        "eval() with @returns annotation",
    );
}

// ── #811: ternary + string concat with parenthesized expression ────

#[test]
fn test_native_proto_ternary_concat_parens() {
    // #811: ParenthesizedExpression wrapping ConditionalExpression in string concat
    // Fix: emit_string_concat / expr_is_string / infer_expr_type now unwrap ParenthesizedExpression
    let js = r#"
export function format(x) {
return "value: " + (x > 5 ? "big" : "small");
}
"#;
    let zig = transpile_and_assert(js, "test_ternary_concat_parens");
    println!("=== Ternary concat with parens ===\n{}", zig);

    // Should use {s} format specifier, not {}
    assert!(
        zig.contains("{s}"),
        "Expected {{s}} format specifier for string ternary, got:\n{}",
        zig
    );
    assert!(
        !zig.contains("{}"),
        "Should NOT use {{}} for string ternary, but got:\n{}",
        zig
    );
    assert!(
        zig.contains("std.fmt.allocPrint"),
        "Expected allocPrint for concat, got:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_ternary_concat_no_parens() {
    // Ternary in concat without explicit parens (sanity check: already worked)
    let js = r#"
export function format(x) {
return "value: " + x > 5 ? "big" : "small";
}
"#;
    let zig = transpile_and_assert(js, "test_ternary_concat_no_parens");
    println!("=== Ternary concat without parens ===\n{}", zig);

    // Even without parens, the operator precedence means + binds tighter,
    // so the ?? is "(value: " + x > 5) ? ...", which is a different semantic.
    // This test mainly ensures we don't crash; format specifier check is omitted.
    assert!(
        zig.contains("std.fmt.allocPrint"),
        "Expected allocPrint for concat, got:\n{}",
        zig
    );
}

// ── P2: Comparison operators always return Bool ─────────────────

#[test]
fn test_native_proto_comparison_strict_eq_bool() {
    // P2-1: When both operands are Indeterminate (e.g., function params),
    // === should still return Bool (not default to i64).
    let js = r#"
export function isEqual(a, b) {
return a === b;
}
"#;
    let zig = transpile_and_assert(js, "test_comparison_strict_eq_bool");
    println!("=== Comparison strict eq ===\n{}", zig);

    // Return type should be bool
    assert!(
        zig.contains("pub fn isEqual(") && zig.contains(") bool"),
        "Expected return type bool for === on indeterminate operands:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_comparison_neq_bool() {
    // !== should return Bool even with indeterminate operands.
    let js = r#"
export function isNotEqual(a, b) {
return a !== b;
}
"#;
    let zig = transpile_and_assert(js, "test_comparison_neq_bool");
    println!("=== Comparison neq ===\n{}", zig);
    assert!(
        zig.contains(") bool"),
        "Expected return type bool for !== on indeterminate operands:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_comparison_lt_bool() {
    // < should return Bool
    let js = r#"
export function isLess(a, b) {
return a < b;
}
"#;
    let zig = transpile_and_assert(js, "test_comparison_lt_bool");
    println!("=== Comparison less than ===\n{}", zig);
    assert!(
        zig.contains(") bool"),
        "Expected return type bool for < on indeterminate operands:\n{}",
        zig
    );
}

#[test]
fn test_native_proto_comparison_complex_bool() {
    // Complex case: comparison in ternary should still produce bool
    let js = r#"
export function valueIsNaN(x) {
return x !== x ? "NaN" : "ok";
}
"#;
    let zig = transpile_and_assert(js, "test_comparison_complex_bool");
    println!("=== Comparison complex ===\n{}", zig);

    // The comparison x !== x should produce bool (not i64)
    assert!(
        zig.contains("pub fn valueIsNaN("),
        "Expected valueIsNaN to transpile successfully:\n{}",
        zig
    );
}

// ── Gap 1: BigInt compound assignment in for-loop update ──────────

/// Gap 1 diagnostic: BigInt += in for-loop update should emit valid Zig.
/// Currently the continuation syntax `while (cond) : ({ bigVar += ... })` is
/// invalid because BigInt has no Zig `+=` and the expansion contains `catch`.
#[test]
fn test_bigint_for_loop_compound_assign() {
    let js = r#"
/**
 * @param {bigint} sum
 * @returns {bigint}
 */
export function test(sum) {
    for (var i = 0; i < 3; i++) {
        sum += BigInt(i);
    }
    return sum;
}
"#;
    let zig = transpile_and_assert(js, "test_bigint_for_loop_compound");
    println!("=== BigInt for-loop compound assign ===\n{}", zig);

    // The update should NOT use += for BigInt; it should use .add() method
    // and handle catch correctly (not in while continuation).
    assert!(
        !zig.contains("sum +="),
        "BigInt compound assignment should not use Zig +=:\n{}",
        zig
    );
}

// ── Cross-type comparison: String vs Number, Bool vs Number, etc. ────

/// Gap 3 fix: comparing a @type-annotated string with a number literal
/// must route through JsAny comparison instead of emitting invalid Zig `==`.
#[test]
fn test_cross_type_str_vs_number_strict_eq() {
    let js = r#"
/**
 * @param {string} s
 * @param {number} n
 */
export function strEqNum(s, n) {
    return s === n;
}
"#;
    let zig = transpile_and_assert(js, "test_cross_type_str_vs_num_strict_eq");
    println!("=== Cross-type str === num ===\n{}", zig);

    // Should use JsAny.from(...).strictEq(JsAny.from(...)) or .eq()
    assert!(
        zig.contains("JsAny.from("),
        "Expected JsAny.from() wrapping for cross-type comparison:\n{}",
        zig
    );
}

/// Gap 3 fix: comparing a boolean with a number uses JsAny comparison.
#[test]
fn test_cross_type_bool_vs_number_eq() {
    let js = r#"
/**
 * @param {boolean} b
 * @param {number} n
 */
export function boolEqNum(b, n) {
    return b == n;
}
"#;
    let zig = transpile_and_assert(js, "test_cross_type_bool_vs_num_eq");
    println!("=== Cross-type bool == num ===\n{}", zig);

    assert!(
        zig.contains("JsAny.from("),
        "Expected JsAny.from() wrapping for bool vs number comparison:\n{}",
        zig
    );
}