ruchy 4.2.1

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
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
use super::*;

    // Test unary operator: BitwiseNot
    #[test]
    fn test_compile_unary_bitwise_not() {
        let mut compiler = Compiler::new("test".to_string());
        let operand = Expr::new(
            ExprKind::Literal(Literal::Integer(0b1010, None)),
            crate::frontend::ast::Span::default(),
        );
        let expr = Expr::new(
            ExprKind::Unary {
                op: UnaryOp::BitwiseNot,
                operand: Box::new(operand),
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler.compile_expr(&expr).expect("Compilation failed");
        let chunk = compiler.finalize();

        let bitnot_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::BitNot.to_u8());
        assert!(bitnot_found, "Should have BitNot instruction");
        assert!(result_reg < 10);
    }

    // Test unsupported unary operator: Reference
    #[test]
    fn test_compile_unary_reference_error() {
        let mut compiler = Compiler::new("test".to_string());
        let operand = Expr::new(
            ExprKind::Identifier("x".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let expr = Expr::new(
            ExprKind::Unary {
                op: UnaryOp::Reference,
                operand: Box::new(operand),
            },
            crate::frontend::ast::Span::default(),
        );

        let result = compiler.compile_expr(&expr);
        assert!(result.is_err(), "Reference operator should fail");
        assert!(result.unwrap_err().contains("Unsupported unary operator"));
    }

    // Test unsupported unary operator: MutableReference
    #[test]
    fn test_compile_unary_mutable_reference_error() {
        let mut compiler = Compiler::new("test".to_string());
        let operand = Expr::new(
            ExprKind::Identifier("x".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let expr = Expr::new(
            ExprKind::Unary {
                op: UnaryOp::MutableReference,
                operand: Box::new(operand),
            },
            crate::frontend::ast::Span::default(),
        );

        let result = compiler.compile_expr(&expr);
        assert!(result.is_err(), "MutableReference operator should fail");
        assert!(result.unwrap_err().contains("Unsupported unary operator"));
    }

    // Test unsupported unary operator: Deref
    #[test]
    fn test_compile_unary_deref_error() {
        let mut compiler = Compiler::new("test".to_string());
        let operand = Expr::new(
            ExprKind::Identifier("x".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let expr = Expr::new(
            ExprKind::Unary {
                op: UnaryOp::Deref,
                operand: Box::new(operand),
            },
            crate::frontend::ast::Span::default(),
        );

        let result = compiler.compile_expr(&expr);
        assert!(result.is_err(), "Deref operator should fail");
        assert!(result.unwrap_err().contains("Unsupported unary operator"));
    }

    // Test let binding compilation
    #[test]
    fn test_compile_let_binding() {
        let mut compiler = Compiler::new("test".to_string());

        // let x = 42 in x
        let value = Expr::new(
            ExprKind::Literal(Literal::Integer(42, None)),
            crate::frontend::ast::Span::default(),
        );
        let body = Expr::new(
            ExprKind::Identifier("x".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let let_expr = Expr::new(
            ExprKind::Let {
                name: "x".to_string(),
                type_annotation: None,
                value: Box::new(value),
                body: Box::new(body),
                is_mutable: false,
                else_block: None,
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&let_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        assert!(!chunk.local_names.is_empty(), "Should have local names");
        assert_eq!(chunk.local_names[0], "x");
        assert!(result_reg < 10);
    }

    // Test variable reference: local variable
    #[test]
    fn test_compile_variable_local() {
        let mut compiler = Compiler::new("test".to_string());

        // First, set up a local variable through let binding
        let value = Expr::new(
            ExprKind::Literal(Literal::Integer(42, None)),
            crate::frontend::ast::Span::default(),
        );
        let body = Expr::new(
            ExprKind::Identifier("x".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let let_expr = Expr::new(
            ExprKind::Let {
                name: "x".to_string(),
                type_annotation: None,
                value: Box::new(value),
                body: Box::new(body),
                is_mutable: false,
                else_block: None,
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&let_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have MOVE instruction for copying local variable
        let move_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::Move.to_u8());
        assert!(
            move_found,
            "Should have Move instruction for local variable access"
        );
        assert!(result_reg < 10);
    }

    // Test variable reference: global variable
    #[test]
    fn test_compile_variable_global() {
        let mut compiler = Compiler::new("test".to_string());

        // Reference a global variable (not defined locally)
        let expr = Expr::new(
            ExprKind::Identifier("global_var".to_string()),
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler.compile_expr(&expr).expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have LOAD_GLOBAL instruction
        let load_global_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::LoadGlobal.to_u8());
        assert!(load_global_found, "Should have LoadGlobal instruction");
        assert!(result_reg < 10);
    }

    // Test assignment to local variable
    #[test]
    fn test_compile_assignment() {
        let mut compiler = Compiler::new("test".to_string());

        // let mut x = 10 in { x = 20; x }
        let init_value = Expr::new(
            ExprKind::Literal(Literal::Integer(10, None)),
            crate::frontend::ast::Span::default(),
        );
        let target = Expr::new(
            ExprKind::Identifier("x".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let new_value = Expr::new(
            ExprKind::Literal(Literal::Integer(20, None)),
            crate::frontend::ast::Span::default(),
        );
        let assign_expr = Expr::new(
            ExprKind::Assign {
                target: Box::new(target.clone()),
                value: Box::new(new_value),
            },
            crate::frontend::ast::Span::default(),
        );
        let body = Expr::new(
            ExprKind::Block(vec![assign_expr, target]),
            crate::frontend::ast::Span::default(),
        );
        let let_expr = Expr::new(
            ExprKind::Let {
                name: "x".to_string(),
                type_annotation: None,
                value: Box::new(init_value),
                body: Box::new(body),
                is_mutable: true,
                else_block: None,
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&let_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have MOVE instructions for assignment
        let move_count = chunk
            .instructions
            .iter()
            .filter(|i| i.opcode() == OpCode::Move.to_u8())
            .count();
        assert!(
            move_count >= 1,
            "Should have Move instruction(s) for assignment"
        );
        assert!(result_reg < 10);
    }

    // Test assignment to undefined variable (error)
    #[test]
    fn test_compile_assignment_undefined_error() {
        let mut compiler = Compiler::new("test".to_string());

        let target = Expr::new(
            ExprKind::Identifier("undefined_var".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let value = Expr::new(
            ExprKind::Literal(Literal::Integer(42, None)),
            crate::frontend::ast::Span::default(),
        );
        let assign_expr = Expr::new(
            ExprKind::Assign {
                target: Box::new(target),
                value: Box::new(value),
            },
            crate::frontend::ast::Span::default(),
        );

        let result = compiler.compile_expr(&assign_expr);
        assert!(
            result.is_err(),
            "Assignment to undefined variable should fail"
        );
        assert!(result.unwrap_err().contains("Undefined variable"));
    }

    // Test function definition
    #[test]
    fn test_compile_function_definition() {
        let mut compiler = Compiler::new("test".to_string());

        // fun add(a, b) { a + b }
        let param_a = make_test_param("a");
        let param_b = make_test_param("b");

        let a = Expr::new(
            ExprKind::Identifier("a".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let b = Expr::new(
            ExprKind::Identifier("b".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let body = Expr::new(
            ExprKind::Binary {
                op: BinaryOp::Add,
                left: Box::new(a),
                right: Box::new(b),
            },
            crate::frontend::ast::Span::default(),
        );

        let func_expr = Expr::new(
            ExprKind::Function {
                name: "add".to_string(),
                type_params: vec![],
                params: vec![param_a, param_b],
                return_type: None,
                body: Box::new(body),
                is_async: false,
                is_pub: false,
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&func_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Function should be stored in locals
        assert!(
            chunk.local_names.contains(&"add".to_string()),
            "Function should be in local names"
        );
        // Should have a Closure constant
        let has_closure = chunk
            .constants
            .iter()
            .any(|c| matches!(c, Value::Closure { .. }));
        assert!(has_closure, "Should have Closure constant");
        assert!(result_reg < 10);
    }

    // Test for loop compilation
    #[test]
    fn test_compile_for_loop() {
        let mut compiler = Compiler::new("test".to_string());

        // for i in [1, 2, 3] { i }
        let iter_elements = vec![
            Expr::new(
                ExprKind::Literal(Literal::Integer(1, None)),
                crate::frontend::ast::Span::default(),
            ),
            Expr::new(
                ExprKind::Literal(Literal::Integer(2, None)),
                crate::frontend::ast::Span::default(),
            ),
            Expr::new(
                ExprKind::Literal(Literal::Integer(3, None)),
                crate::frontend::ast::Span::default(),
            ),
        ];
        let iter_expr = Expr::new(
            ExprKind::List(iter_elements),
            crate::frontend::ast::Span::default(),
        );
        let body = Expr::new(
            ExprKind::Identifier("i".to_string()),
            crate::frontend::ast::Span::default(),
        );

        let for_expr = Expr::new(
            ExprKind::For {
                label: None,
                var: "i".to_string(),
                pattern: None,
                iter: Box::new(iter_expr),
                body: Box::new(body),
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&for_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have For opcode
        let for_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::For.to_u8());
        assert!(for_found, "Should have For instruction");
        // Should have stored loop body
        assert!(
            !chunk.loop_bodies.is_empty(),
            "Should have stored loop body"
        );
        assert!(result_reg < 10);
    }

    // Test method call compilation
    #[test]
    fn test_compile_method_call() {
        let mut compiler = Compiler::new("test".to_string());

        // "hello".len()
        let receiver = Expr::new(
            ExprKind::Literal(Literal::String("hello".to_string())),
            crate::frontend::ast::Span::default(),
        );
        let method_call = Expr::new(
            ExprKind::MethodCall {
                receiver: Box::new(receiver),
                method: "len".to_string(),
                args: vec![],
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&method_call)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have MethodCall opcode
        let method_call_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::MethodCall.to_u8());
        assert!(method_call_found, "Should have MethodCall instruction");
        // Should have stored method call info
        assert!(
            !chunk.method_calls.is_empty(),
            "Should have stored method call info"
        );
        assert!(result_reg < 10);
    }

    // Test field access compilation
    #[test]
    fn test_compile_field_access() {
        let mut compiler = Compiler::new("test".to_string());

        // obj.field
        let object = Expr::new(
            ExprKind::Identifier("obj".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let field_access = Expr::new(
            ExprKind::FieldAccess {
                object: Box::new(object),
                field: "field".to_string(),
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&field_access)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have LoadField opcode
        let load_field_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::LoadField.to_u8());
        assert!(load_field_found, "Should have LoadField instruction");
        assert!(result_reg < 10);
    }

    // Test index access compilation
    #[test]
    fn test_compile_index_access() {
        let mut compiler = Compiler::new("test".to_string());

        // arr[0]
        let object = Expr::new(
            ExprKind::Identifier("arr".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let index = Expr::new(
            ExprKind::Literal(Literal::Integer(0, None)),
            crate::frontend::ast::Span::default(),
        );
        let index_access = Expr::new(
            ExprKind::IndexAccess {
                object: Box::new(object),
                index: Box::new(index),
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&index_access)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have LoadIndex opcode
        let load_index_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::LoadIndex.to_u8());
        assert!(load_index_found, "Should have LoadIndex instruction");
        assert!(result_reg < 10);
    }

    // Test tuple compilation with literals
    #[test]
    fn test_compile_tuple_literals() {
        let mut compiler = Compiler::new("test".to_string());

        // (1, 2, 3)
        let elements = vec![
            Expr::new(
                ExprKind::Literal(Literal::Integer(1, None)),
                crate::frontend::ast::Span::default(),
            ),
            Expr::new(
                ExprKind::Literal(Literal::Integer(2, None)),
                crate::frontend::ast::Span::default(),
            ),
            Expr::new(
                ExprKind::Literal(Literal::Integer(3, None)),
                crate::frontend::ast::Span::default(),
            ),
        ];
        let tuple_expr = Expr::new(
            ExprKind::Tuple(elements),
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&tuple_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Literal tuple should be in constant pool
        let has_tuple = chunk.constants.iter().any(|c| matches!(c, Value::Tuple(_)));
        assert!(has_tuple, "Should have Tuple constant");
        assert!(result_reg < 10);
    }

    // Test tuple compilation with non-literals
    #[test]
    fn test_compile_tuple_non_literals() {
        let mut compiler = Compiler::new("test".to_string());

        // (x, y)
        let elements = vec![
            Expr::new(
                ExprKind::Identifier("x".to_string()),
                crate::frontend::ast::Span::default(),
            ),
            Expr::new(
                ExprKind::Identifier("y".to_string()),
                crate::frontend::ast::Span::default(),
            ),
        ];
        let tuple_expr = Expr::new(
            ExprKind::Tuple(elements),
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&tuple_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have NewTuple instruction for non-literal elements
        let new_tuple_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::NewTuple.to_u8());
        assert!(new_tuple_found, "Should have NewTuple instruction");
        assert!(result_reg < 10);
    }

    // Test object literal with literals
    #[test]
    fn test_compile_object_literal_literals() {
        use crate::frontend::ast::ObjectField;

        let mut compiler = Compiler::new("test".to_string());

        // { x: 1, y: 2 }
        let fields = vec![
            ObjectField::KeyValue {
                key: "x".to_string(),
                value: Expr::new(
                    ExprKind::Literal(Literal::Integer(1, None)),
                    crate::frontend::ast::Span::default(),
                ),
            },
            ObjectField::KeyValue {
                key: "y".to_string(),
                value: Expr::new(
                    ExprKind::Literal(Literal::Integer(2, None)),
                    crate::frontend::ast::Span::default(),
                ),
            },
        ];
        let obj_expr = Expr::new(
            ExprKind::ObjectLiteral { fields },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&obj_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Literal object should be in constant pool
        let has_object = chunk
            .constants
            .iter()
            .any(|c| matches!(c, Value::Object(_)));
        assert!(has_object, "Should have Object constant");
        assert!(result_reg < 10);
    }

    // Test object literal with non-literals
    #[test]
    fn test_compile_object_literal_non_literals() {
        use crate::frontend::ast::ObjectField;

        let mut compiler = Compiler::new("test".to_string());

        // { x: a, y: b }
        let fields = vec![
            ObjectField::KeyValue {
                key: "x".to_string(),
                value: Expr::new(
                    ExprKind::Identifier("a".to_string()),
                    crate::frontend::ast::Span::default(),
                ),
            },
            ObjectField::KeyValue {
                key: "y".to_string(),
                value: Expr::new(
                    ExprKind::Identifier("b".to_string()),
                    crate::frontend::ast::Span::default(),
                ),
            },
        ];
        let obj_expr = Expr::new(
            ExprKind::ObjectLiteral { fields },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&obj_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have NewObject instruction for non-literal elements
        let new_object_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::NewObject.to_u8());
        assert!(new_object_found, "Should have NewObject instruction");
        assert!(result_reg < 10);
    }

    // Test object literal with spread (error)
    #[test]
    fn test_compile_object_literal_spread_error() {
        use crate::frontend::ast::ObjectField;

        let mut compiler = Compiler::new("test".to_string());

        // { ...other }
        let fields = vec![ObjectField::Spread {
            expr: Expr::new(
                ExprKind::Identifier("other".to_string()),
                crate::frontend::ast::Span::default(),
            ),
        }];
        let obj_expr = Expr::new(
            ExprKind::ObjectLiteral { fields },
            crate::frontend::ast::Span::default(),
        );

        let result = compiler.compile_expr(&obj_expr);
        assert!(result.is_err(), "Spread in object literal should fail");
        assert!(result.unwrap_err().contains("Spread operator"));
    }

    // Test match expression compilation
    #[test]
    fn test_compile_match_expression() {
        use crate::frontend::ast::{MatchArm, Pattern};

        let mut compiler = Compiler::new("test".to_string());

        // match x { 1 => "one", _ => "other" }
        let match_expr = Expr::new(
            ExprKind::Identifier("x".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let arms = vec![
            MatchArm {
                pattern: Pattern::Literal(Literal::Integer(1, None)),
                guard: None,
                body: Box::new(Expr::new(
                    ExprKind::Literal(Literal::String("one".to_string())),
                    crate::frontend::ast::Span::default(),
                )),
                span: crate::frontend::ast::Span::default(),
            },
            MatchArm {
                pattern: Pattern::Wildcard,
                guard: None,
                body: Box::new(Expr::new(
                    ExprKind::Literal(Literal::String("other".to_string())),
                    crate::frontend::ast::Span::default(),
                )),
                span: crate::frontend::ast::Span::default(),
            },
        ];
        let match_full = Expr::new(
            ExprKind::Match {
                expr: Box::new(match_expr),
                arms,
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&match_full)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have Match opcode
        let match_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::Match.to_u8());
        assert!(match_found, "Should have Match instruction");
        // Should have stored match expression
        assert!(
            !chunk.match_exprs.is_empty(),
            "Should have stored match expression"
        );
        assert!(result_reg < 10);
    }

    // Test closure compilation
    #[test]
    fn test_compile_closure() {
        let mut compiler = Compiler::new("test".to_string());

        // |x| x + 1
        let param = make_test_param("x");
        let x = Expr::new(
            ExprKind::Identifier("x".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let one = Expr::new(
            ExprKind::Literal(Literal::Integer(1, None)),
            crate::frontend::ast::Span::default(),
        );
        let body = Expr::new(
            ExprKind::Binary {
                op: BinaryOp::Add,
                left: Box::new(x),
                right: Box::new(one),
            },
            crate::frontend::ast::Span::default(),
        );

        let lambda = Expr::new(
            ExprKind::Lambda {
                params: vec![param],
                body: Box::new(body),
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler.compile_expr(&lambda).expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have NewClosure opcode
        let new_closure_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::NewClosure.to_u8());
        assert!(new_closure_found, "Should have NewClosure instruction");
        // Should have stored closure info
        assert!(
            !chunk.closures.is_empty(),
            "Should have stored closure info"
        );
        assert!(result_reg < 10);
    }

    // Test empty list compilation
    #[test]
    fn test_compile_empty_list() {
        let mut compiler = Compiler::new("test".to_string());

        // []
        let list_expr = Expr::new(
            ExprKind::List(vec![]),
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&list_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Empty list uses NewArray path (not constant pool optimization)
        let new_array_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::NewArray.to_u8());
        assert!(
            new_array_found,
            "Should have NewArray instruction for empty list"
        );
        assert!(result_reg < 10);
    }

    // Test empty tuple compilation
    #[test]
    fn test_compile_empty_tuple() {
        let mut compiler = Compiler::new("test".to_string());

        // ()
        let tuple_expr = Expr::new(
            ExprKind::Tuple(vec![]),
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&tuple_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Empty tuple uses NewTuple path
        let new_tuple_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::NewTuple.to_u8());
        assert!(
            new_tuple_found,
            "Should have NewTuple instruction for empty tuple"
        );
        assert!(result_reg < 10);
    }

    // Test empty object compilation
    #[test]
    fn test_compile_empty_object() {
        let mut compiler = Compiler::new("test".to_string());

        // {}
        let obj_expr = Expr::new(
            ExprKind::ObjectLiteral { fields: vec![] },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&obj_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Empty object uses NewObject path
        let new_object_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::NewObject.to_u8());
        assert!(
            new_object_found,
            "Should have NewObject instruction for empty object"
        );
        assert!(result_reg < 10);
    }

    // Test patch_jump functionality
    #[test]
    fn test_patch_jump() {
        let mut chunk = BytecodeChunk::new("test".to_string());

        // Emit a jump with placeholder offset
        let jump_idx = chunk.emit(Instruction::asbx(OpCode::Jump, 0, 0), 0);

        // Emit some instructions
        chunk.emit(Instruction::abc(OpCode::Add, 0, 1, 2), 0);
        chunk.emit(Instruction::abc(OpCode::Add, 0, 1, 2), 0);
        chunk.emit(Instruction::abc(OpCode::Add, 0, 1, 2), 0);

        // Patch the jump
        chunk.patch_jump(jump_idx);

        // Verify the jump offset was updated correctly
        let jump_instr = chunk.instructions[jump_idx];
        assert_eq!(jump_instr.opcode(), OpCode::Jump.to_u8());
        assert_eq!(
            jump_instr.get_sbx(),
            3,
            "Jump offset should be 3 (skip 3 instructions)"
        );
    }

    // Test finalize method
    #[test]
    fn test_finalize() {
        let mut compiler = Compiler::new("my_function".to_string());

        // Compile a simple expression
        let expr = Expr::new(
            ExprKind::Literal(Literal::Integer(42, None)),
            crate::frontend::ast::Span::default(),
        );
        let _ = compiler.compile_expr(&expr).expect("Compilation failed");

        let chunk = compiler.finalize();

        // Check finalize results
        assert_eq!(chunk.name, "my_function");
        assert!(chunk.register_count > 0, "Should have register count set");
        // Last instruction should be Return
        let last_instr = chunk.instructions.last().expect("Should have instructions");
        assert_eq!(last_instr.opcode(), OpCode::Return.to_u8());
    }

    // Test is_local_register helper
    #[test]
    fn test_is_local_register() {
        let mut compiler = Compiler::new("test".to_string());

        // Initially no locals
        assert!(!compiler.is_local_register(0));
        assert!(!compiler.is_local_register(1));

        // Add a local variable through let binding
        let value = Expr::new(
            ExprKind::Literal(Literal::Integer(42, None)),
            crate::frontend::ast::Span::default(),
        );
        let body = Expr::new(
            ExprKind::Literal(Literal::Integer(0, None)),
            crate::frontend::ast::Span::default(),
        );
        let let_expr = Expr::new(
            ExprKind::Let {
                name: "x".to_string(),
                type_annotation: None,
                value: Box::new(value),
                body: Box::new(body),
                is_mutable: false,
                else_block: None,
            },
            crate::frontend::ast::Span::default(),
        );
        let _ = compiler
            .compile_expr(&let_expr)
            .expect("Compilation failed");

        // Register 0 should now be a local
        assert!(compiler.is_local_register(0));
        // Other registers should not be locals
        assert!(!compiler.is_local_register(100));
    }

    // Test unsupported expression kind
    #[test]
    fn test_compile_unsupported_expression() {
        let mut compiler = Compiler::new("test".to_string());

        // Use an unsupported expression kind (e.g., Import)
        let expr = Expr::new(
            ExprKind::Import {
                module: "std".to_string(),
                items: None,
            },
            crate::frontend::ast::Span::default(),
        );

        let result = compiler.compile_expr(&expr);
        assert!(result.is_err(), "Unsupported expression should fail");
        assert!(result.unwrap_err().contains("Unsupported expression kind"));
    }

    // Test function call with no arguments
    #[test]
    fn test_compile_function_call_no_args() {
        let mut compiler = Compiler::new("test".to_string());

        // foo()
        let func = Expr::new(
            ExprKind::Identifier("foo".to_string()),
            crate::frontend::ast::Span::default(),
        );

        let call = Expr::new(
            ExprKind::Call {
                func: Box::new(func),
                args: vec![],
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler.compile_expr(&call).expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have Call instruction
        let call_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::Call.to_u8());
        assert!(call_found, "Should have Call instruction");
        assert!(result_reg < 10);
    }

    // Test method call with arguments
    #[test]
    fn test_compile_method_call_with_args() {
        let mut compiler = Compiler::new("test".to_string());

        // "hello".substring(0, 3)
        let receiver = Expr::new(
            ExprKind::Literal(Literal::String("hello".to_string())),
            crate::frontend::ast::Span::default(),
        );
        let method_call = Expr::new(
            ExprKind::MethodCall {
                receiver: Box::new(receiver),
                method: "substring".to_string(),
                args: vec![
                    Expr::new(
                        ExprKind::Literal(Literal::Integer(0, None)),
                        crate::frontend::ast::Span::default(),
                    ),
                    Expr::new(
                        ExprKind::Literal(Literal::Integer(3, None)),
                        crate::frontend::ast::Span::default(),
                    ),
                ],
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&method_call)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have stored method call with args
        assert!(!chunk.method_calls.is_empty());
        let (_, method_name, args) = &chunk.method_calls[0];
        assert_eq!(method_name, "substring");
        assert_eq!(args.len(), 2);
        assert!(result_reg < 10);
    }

    // Test nested if expression
    #[test]
    fn test_compile_nested_if() {
        let mut compiler = Compiler::new("test".to_string());

        // if true { if false { 1 } else { 2 } } else { 3 }
        let inner_condition = Expr::new(
            ExprKind::Literal(Literal::Bool(false)),
            crate::frontend::ast::Span::default(),
        );
        let inner_then = Expr::new(
            ExprKind::Literal(Literal::Integer(1, None)),
            crate::frontend::ast::Span::default(),
        );
        let inner_else = Expr::new(
            ExprKind::Literal(Literal::Integer(2, None)),
            crate::frontend::ast::Span::default(),
        );
        let inner_if = Expr::new(
            ExprKind::If {
                condition: Box::new(inner_condition),
                then_branch: Box::new(inner_then),
                else_branch: Some(Box::new(inner_else)),
            },
            crate::frontend::ast::Span::default(),
        );

        let outer_condition = Expr::new(
            ExprKind::Literal(Literal::Bool(true)),
            crate::frontend::ast::Span::default(),
        );
        let outer_else = Expr::new(
            ExprKind::Literal(Literal::Integer(3, None)),
            crate::frontend::ast::Span::default(),
        );
        let outer_if = Expr::new(
            ExprKind::If {
                condition: Box::new(outer_condition),
                then_branch: Box::new(inner_if),
                else_branch: Some(Box::new(outer_else)),
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&outer_if)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have multiple JumpIfFalse instructions
        let jump_count = chunk
            .instructions
            .iter()
            .filter(|i| i.opcode() == OpCode::JumpIfFalse.to_u8())
            .count();
        assert!(
            jump_count >= 2,
            "Should have at least 2 JumpIfFalse instructions for nested if"
        );
        assert!(result_reg < 10);
    }

    // Test block with local variable not freed
    #[test]
    fn test_compile_block_preserves_local_registers() {
        let mut compiler = Compiler::new("test".to_string());

        // { let x = 1; let y = 2; x + y }
        let let_x = Expr::new(
            ExprKind::Let {
                name: "x".to_string(),
                type_annotation: None,
                value: Box::new(Expr::new(
                    ExprKind::Literal(Literal::Integer(1, None)),
                    crate::frontend::ast::Span::default(),
                )),
                body: Box::new(Expr::new(
                    ExprKind::Let {
                        name: "y".to_string(),
                        type_annotation: None,
                        value: Box::new(Expr::new(
                            ExprKind::Literal(Literal::Integer(2, None)),
                            crate::frontend::ast::Span::default(),
                        )),
                        body: Box::new(Expr::new(
                            ExprKind::Binary {
                                op: BinaryOp::Add,
                                left: Box::new(Expr::new(
                                    ExprKind::Identifier("x".to_string()),
                                    crate::frontend::ast::Span::default(),
                                )),
                                right: Box::new(Expr::new(
                                    ExprKind::Identifier("y".to_string()),
                                    crate::frontend::ast::Span::default(),
                                )),
                            },
                            crate::frontend::ast::Span::default(),
                        )),
                        is_mutable: false,
                        else_block: None,
                    },
                    crate::frontend::ast::Span::default(),
                )),
                is_mutable: false,
                else_block: None,
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler.compile_expr(&let_x).expect("Compilation failed");
        let chunk = compiler.finalize();

        // Should have both local names
        assert!(chunk.local_names.contains(&"x".to_string()));
        assert!(chunk.local_names.contains(&"y".to_string()));
        assert!(result_reg < 10);
    }

    // Test locals_map is populated in finalize
    #[test]
    fn test_finalize_populates_locals_map() {
        let mut compiler = Compiler::new("test".to_string());

        // let x = 42 in x
        let value = Expr::new(
            ExprKind::Literal(Literal::Integer(42, None)),
            crate::frontend::ast::Span::default(),
        );
        let body = Expr::new(
            ExprKind::Identifier("x".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let let_expr = Expr::new(
            ExprKind::Let {
                name: "x".to_string(),
                type_annotation: None,
                value: Box::new(value),
                body: Box::new(body),
                is_mutable: false,
                else_block: None,
            },
            crate::frontend::ast::Span::default(),
        );

        let _ = compiler
            .compile_expr(&let_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // locals_map should contain x
        assert!(chunk.locals_map.contains_key("x"));
        assert_eq!(*chunk.locals_map.get("x").unwrap(), 0);
    }

    // Test Gt binary operator (alias for Greater)
    #[test]
    fn test_compile_binary_gt() {
        let mut compiler = Compiler::new("test".to_string());
        let left = Expr::new(
            ExprKind::Literal(Literal::Integer(10, None)),
            crate::frontend::ast::Span::default(),
        );
        let right = Expr::new(
            ExprKind::Literal(Literal::Integer(5, None)),
            crate::frontend::ast::Span::default(),
        );
        let expr = Expr::new(
            ExprKind::Binary {
                op: BinaryOp::Gt,
                left: Box::new(left),
                right: Box::new(right),
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler.compile_expr(&expr).expect("Compilation failed");
        let chunk = compiler.finalize();

        let gt_found = chunk
            .instructions
            .iter()
            .any(|i| i.opcode() == OpCode::Greater.to_u8());
        assert!(gt_found, "Should have Greater instruction for Gt operator");
        assert!(result_reg < 10);
    }

    // Test float constant deduplication
    #[test]
    fn test_float_constant_deduplication() {
        let mut chunk = BytecodeChunk::new("test".to_string());

        let idx1 = chunk.add_constant(Value::Float(3.14));
        let idx2 = chunk.add_constant(Value::Float(3.14));
        let idx3 = chunk.add_constant(Value::Float(2.71));

        assert_eq!(idx1, idx2, "Duplicate floats should return same index");
        assert_ne!(idx1, idx3, "Different floats should have different indices");
        assert_eq!(chunk.constants.len(), 2);
    }

    // Test bool constant deduplication
    #[test]
    fn test_bool_constant_deduplication() {
        let mut chunk = BytecodeChunk::new("test".to_string());

        let idx1 = chunk.add_constant(Value::Bool(true));
        let idx2 = chunk.add_constant(Value::Bool(true));
        let idx3 = chunk.add_constant(Value::Bool(false));
        let idx4 = chunk.add_constant(Value::Bool(false));

        assert_eq!(idx1, idx2, "Duplicate true should return same index");
        assert_eq!(idx3, idx4, "Duplicate false should return same index");
        assert_ne!(idx1, idx3, "true and false should have different indices");
        assert_eq!(chunk.constants.len(), 2);
    }

    // Test nil constant deduplication
    #[test]
    fn test_nil_constant_deduplication() {
        let mut chunk = BytecodeChunk::new("test".to_string());

        let idx1 = chunk.add_constant(Value::Nil);
        let idx2 = chunk.add_constant(Value::Nil);
        let idx3 = chunk.add_constant(Value::Nil);

        assert_eq!(idx1, idx2, "Duplicate Nil should return same index");
        assert_eq!(idx2, idx3, "All Nil should return same index");
        assert_eq!(chunk.constants.len(), 1);
    }

    // Test function with default parameters
    #[test]
    fn test_compile_function_with_defaults() {
        let mut compiler = Compiler::new("test".to_string());

        // fun greet(name, greeting = "Hello") { greeting + name }
        let param_name = make_test_param("name");
        let default_value = Expr::new(
            ExprKind::Literal(Literal::String("Hello".to_string())),
            crate::frontend::ast::Span::default(),
        );
        let param_greeting = make_test_param_with_default("greeting", default_value);

        let greeting_ident = Expr::new(
            ExprKind::Identifier("greeting".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let name_ident = Expr::new(
            ExprKind::Identifier("name".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let body = Expr::new(
            ExprKind::Binary {
                op: BinaryOp::Add,
                left: Box::new(greeting_ident),
                right: Box::new(name_ident),
            },
            crate::frontend::ast::Span::default(),
        );

        let func_expr = Expr::new(
            ExprKind::Function {
                name: "greet".to_string(),
                type_params: vec![],
                params: vec![param_name, param_greeting],
                return_type: None,
                body: Box::new(body),
                is_async: false,
                is_pub: false,
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler
            .compile_expr(&func_expr)
            .expect("Compilation failed");
        let chunk = compiler.finalize();

        // Function should have closure with default parameters
        let has_closure = chunk.constants.iter().any(|c| {
            if let Value::Closure { params, .. } = c {
                // Second param should have a default value
                params.len() == 2 && params[1].1.is_some()
            } else {
                false
            }
        });
        assert!(has_closure, "Should have Closure with default parameter");
        assert!(result_reg < 10);
    }

    // Test closure with default parameters
    #[test]
    fn test_compile_closure_with_defaults() {
        let mut compiler = Compiler::new("test".to_string());

        // |x, y = 10| x + y
        let param_x = make_test_param("x");
        let default_y = Expr::new(
            ExprKind::Literal(Literal::Integer(10, None)),
            crate::frontend::ast::Span::default(),
        );
        let param_y = make_test_param_with_default("y", default_y);

        let x = Expr::new(
            ExprKind::Identifier("x".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let y = Expr::new(
            ExprKind::Identifier("y".to_string()),
            crate::frontend::ast::Span::default(),
        );
        let body = Expr::new(
            ExprKind::Binary {
                op: BinaryOp::Add,
                left: Box::new(x),
                right: Box::new(y),
            },
            crate::frontend::ast::Span::default(),
        );

        let lambda = Expr::new(
            ExprKind::Lambda {
                params: vec![param_x, param_y],
                body: Box::new(body),
            },
            crate::frontend::ast::Span::default(),
        );

        let result_reg = compiler.compile_expr(&lambda).expect("Compilation failed");
        let chunk = compiler.finalize();

        // Closure info should include default parameters
        assert!(!chunk.closures.is_empty());
        let (params, _) = &chunk.closures[0];
        assert_eq!(params.len(), 2);
        assert!(
            params[1].1.is_some(),
            "Second param should have default value"
        );
        assert!(result_reg < 10);
    }

    // Test string values not deduplicated (by reference)
    #[test]
    fn test_string_constant_not_deduplicated() {
        let mut chunk = BytecodeChunk::new("test".to_string());

        let idx1 = chunk.add_constant(Value::from_string("hello".to_string()));
        let idx2 = chunk.add_constant(Value::from_string("hello".to_string()));

        // String comparison returns false in values_equal (by reference, not value)
        // So strings are not deduplicated
        assert_ne!(
            idx1, idx2,
            "Strings should not be deduplicated (by reference)"
        );
        assert_eq!(chunk.constants.len(), 2);
    }