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
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
//! Type inference engine using Algorithm W
use crate::frontend::ast::{BinaryOp, Expr, ExprKind, Literal, Param, Pattern, TypeKind, UnaryOp};
use crate::middleend::environment::TypeEnv;
use crate::middleend::types::{MonoType, TyVar, TyVarGenerator, TypeScheme};
use crate::middleend::unify::Unifier;
use anyhow::{bail, Result};
/// Type inference context with enhanced constraint solving
pub struct InferenceContext {
    /// Type variable generator
    gen: TyVarGenerator,
    /// Unification engine
    unifier: Unifier,
    /// Type environment
    env: TypeEnv,
    /// Deferred constraints for later resolution
    constraints: Vec<(TyVar, TyVar)>,
    /// Enhanced constraint queue for complex type relationships
    type_constraints: Vec<TypeConstraint>,
    /// Recursion depth tracker for safety
    recursion_depth: usize,
}
/// Enhanced constraint types for self-hosting compiler patterns
#[derive(Debug, Clone)]
pub enum TypeConstraint {
    /// Two types must unify
    Unify(MonoType, MonoType),
    /// Type must be a function with specific arity
    FunctionArity(MonoType, usize),
    /// Type must support method call
    MethodCall(MonoType, String, Vec<MonoType>),
    /// Type must be iterable
    Iterable(MonoType, MonoType),
}
impl InferenceContext {
    #[must_use]
    /// Create a new inference context
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::middleend::infer::InferenceContext;
    /// let ctx = InferenceContext::new();
    /// ```
    pub fn new() -> Self {
        InferenceContext {
            gen: TyVarGenerator::new(),
            unifier: Unifier::new(),
            env: TypeEnv::standard(),
            constraints: Vec::new(),
            type_constraints: Vec::new(),
            recursion_depth: 0,
        }
    }
    #[must_use]
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::middleend::infer::InferenceContext;
    /// use ruchy::middleend::environment::TypeEnv;
    ///
    /// let ctx = InferenceContext::with_env(TypeEnv::standard());
    /// ```
    pub fn with_env(env: TypeEnv) -> Self {
        InferenceContext {
            gen: TyVarGenerator::new(),
            unifier: Unifier::new(),
            env,
            constraints: Vec::new(),
            type_constraints: Vec::new(),
            recursion_depth: 0,
        }
    }
    /// Infer the type of an expression with enhanced constraint solving
    ///
    /// # Errors
    ///
    /// Returns an error if type inference fails (type error, undefined variable, etc.)
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::middleend::infer::InferenceContext;
    /// use ruchy::frontend::ast::Expr;
    ///
    /// let mut ctx = InferenceContext::new();
    /// // ctx.infer(&expr)?;
    /// ```
    pub fn infer(&mut self, expr: &Expr) -> Result<MonoType> {
        // Check recursion depth to prevent infinite loops
        if self.recursion_depth > 100 {
            bail!("Type inference recursion limit exceeded");
        }
        self.recursion_depth += 1;
        let result = self.infer_expr(expr);
        self.recursion_depth -= 1;
        let inferred_type = result?;
        // Solve all accumulated constraints
        self.solve_all_constraints()?;
        // Apply final substitutions
        Ok(self.unifier.apply(&inferred_type))
    }

    /// Instantiate a type scheme with fresh type variables
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::middleend::infer::InferenceContext;
    /// use ruchy::middleend::types::{TypeScheme, MonoType, TyVar};
    ///
    /// let mut ctx = InferenceContext::new();
    /// let var = TyVar(0);
    /// let scheme = TypeScheme {
    ///     vars: vec![var.clone()],
    ///     ty: MonoType::Var(var)
    /// };
    /// let instantiated = ctx.instantiate(&scheme);
    /// assert!(matches!(instantiated, MonoType::Var(_)));
    /// ```
    pub fn instantiate(&mut self, scheme: &TypeScheme) -> MonoType {
        scheme.instantiate(&mut self.gen)
    }

    /// Solve all accumulated constraints (enhanced for self-hosting)
    fn solve_all_constraints(&mut self) -> Result<()> {
        // First solve simple variable constraints
        self.solve_constraints();
        // Then solve complex type constraints
        while let Some(constraint) = self.type_constraints.pop() {
            self.solve_type_constraint(constraint)?;
        }
        Ok(())
    }
    /// Solve deferred constraints
    fn solve_constraints(&mut self) {
        while let Some((a, b)) = self.constraints.pop() {
            // Convert TyVar to MonoType for unification
            let ty_a = MonoType::Var(a);
            let ty_b = MonoType::Var(b);
            // Ignore failures for now - this is a simplified implementation
            let _ = self.unifier.unify(&ty_a, &ty_b);
        }
    }
    /// Solve complex type constraints for advanced patterns
    fn solve_type_constraint(&mut self, constraint: TypeConstraint) -> Result<()> {
        match constraint {
            TypeConstraint::Unify(t1, t2) => {
                self.unifier.unify(&t1, &t2)?;
            }
            TypeConstraint::FunctionArity(func_ty, expected_arity) => {
                // Verify function has correct number of parameters
                let mut current_ty = &func_ty;
                let mut arity = 0;
                while let MonoType::Function(_, ret) = current_ty {
                    arity += 1;
                    current_ty = ret;
                }
                if arity != expected_arity {
                    bail!("Function arity mismatch: expected {expected_arity}, found {arity}");
                }
            }
            TypeConstraint::MethodCall(receiver_ty, method_name, arg_types) => {
                // Verify receiver type supports the method call
                self.check_method_call_constraint(&receiver_ty, &method_name, &arg_types)?;
            }
            TypeConstraint::Iterable(collection_ty, element_ty) => {
                // Ensure collection_ty is a valid iterable containing element_ty
                match collection_ty {
                    MonoType::List(inner) => {
                        self.unifier.unify(&inner, &element_ty)?;
                    }
                    MonoType::String => {
                        // String iterates over characters
                        self.unifier.unify(&element_ty, &MonoType::Char)?;
                    }
                    _ => bail!("Type {collection_ty} is not iterable"),
                }
            }
        }
        Ok(())
    }
    /// Check method call constraints for compiler patterns
    fn check_method_call_constraint(
        &mut self,
        receiver_ty: &MonoType,
        method_name: &str,
        _arg_types: &[MonoType],
    ) -> Result<()> {
        match (method_name, receiver_ty) {
            // List methods
            ("map" | "filter" | "reduce", MonoType::List(_)) => Ok(()),
            ("len" | "length", MonoType::List(_) | MonoType::String) => Ok(()),
            ("push", MonoType::List(_)) => Ok(()),
            // DataFrame methods
            ("filter" | "groupby" | "agg" | "select" | "col", MonoType::DataFrame(_)) => Ok(()),
            ("filter" | "groupby" | "agg" | "select" | "col", MonoType::Named(name))
                if name == "DataFrame" =>
            {
                Ok(())
            }
            // Series methods
            ("mean" | "std" | "sum" | "count", MonoType::Series(_) | MonoType::DataFrame(_)) => {
                Ok(())
            }
            ("mean" | "std" | "sum" | "count", MonoType::Named(name))
                if name == "Series" || name == "DataFrame" =>
            {
                Ok(())
            }
            // HashMap methods (for compiler symbol tables)
            ("insert" | "get" | "contains_key", MonoType::Named(name))
                if name.starts_with("HashMap") =>
            {
                Ok(())
            }
            // String methods
            ("chars" | "trim" | "to_upper" | "to_lower", MonoType::String) => Ok(()),
            // For testing purposes, be more permissive with unknown methods
            _ => {
                // In a production implementation, this would be stricter
                // For self-hosting development, we allow more flexibility
                Ok(())
            }
        }
    }
    /// Core type inference dispatcher with complexity <10
    ///
    /// Delegates to specialized handlers for each expression category
    ///
    /// # Example Usage
    /// This method infers types for expressions by delegating to specialized handlers.
    /// For example, literals get their type directly, while function calls check argument types.
    fn infer_expr(&mut self, expr: &Expr) -> Result<MonoType> {
        match &expr.kind {
            // Literals and identifiers
            ExprKind::Literal(lit) => Ok(Self::infer_literal(lit)),
            ExprKind::Identifier(name) => self.infer_identifier(name),
            ExprKind::QualifiedName { module: _, name } => self.infer_identifier(name),
            // Control flow and pattern matching
            ExprKind::If {
                condition: _,
                then_branch: _,
                else_branch: _,
            } => self.infer_control_flow_expr(expr),
            ExprKind::For { .. } | ExprKind::While { .. } | ExprKind::Loop { .. } => {
                self.infer_control_flow_expr(expr)
            }
            ExprKind::Match { expr, arms } => self.infer_match(expr, arms),
            ExprKind::IfLet { .. } | ExprKind::WhileLet { .. } => {
                self.infer_control_flow_expr(expr)
            }
            // Functions and lambdas
            ExprKind::Function { .. } | ExprKind::Lambda { .. } => self.infer_function_expr(expr),
            // Collections and data structures
            ExprKind::List(..) | ExprKind::Tuple(..) | ExprKind::ListComprehension { .. } => {
                self.infer_collection_expr(expr)
            }
            // Operations and method calls
            ExprKind::Binary { .. }
            | ExprKind::Unary { .. }
            | ExprKind::Call { .. }
            | ExprKind::MethodCall { .. } => self.infer_operation_expr(expr),
            // All other expressions
            _ => self.infer_other_expr(expr),
        }
    }
    fn infer_literal(lit: &Literal) -> MonoType {
        match lit {
            Literal::Integer(_, _) => MonoType::Int,
            Literal::Float(_) => MonoType::Float,
            Literal::String(_) => MonoType::String,
            Literal::Bool(_) => MonoType::Bool,
            Literal::Char(_) => MonoType::Char,
            Literal::Byte(_) => MonoType::Int, // Treat byte as int for now
            Literal::Unit => MonoType::Unit,
            Literal::Null => MonoType::Unit, // Treat null as unit type for now
            Literal::Atom(_) => MonoType::String, // Atoms are typed as Strings for now
        }
    }
    fn infer_identifier(&mut self, name: &str) -> Result<MonoType> {
        match self.env.lookup(name) {
            Some(scheme) => Ok(self.env.instantiate(scheme, &mut self.gen)),
            None => bail!("Undefined variable: {name}"),
        }
    }
    fn infer_binary(&mut self, left: &Expr, op: BinaryOp, right: &Expr) -> Result<MonoType> {
        let left_ty = self.infer_expr(left)?;
        let right_ty = self.infer_expr(right)?;
        match op {
            // Addition (can be numeric or string concatenation)
            BinaryOp::Add => {
                // Check if both are strings (concatenation)
                if matches!((&left_ty, &right_ty), (MonoType::String, MonoType::String)) {
                    Ok(MonoType::String)
                } else {
                    // Numeric addition - both operands must be numeric and same type
                    self.unifier.unify(&left_ty, &right_ty)?;
                    // For now, assume Int (could be Float too)
                    self.unifier.unify(&left_ty, &MonoType::Int)?;
                    Ok(MonoType::Int)
                }
            }
            // Other arithmetic operators (numeric only)
            BinaryOp::Subtract | BinaryOp::Multiply | BinaryOp::Divide | BinaryOp::Modulo => {
                // Both operands must be numeric and same type
                self.unifier.unify(&left_ty, &right_ty)?;
                // For now, assume Int (could be Float too)
                self.unifier.unify(&left_ty, &MonoType::Int)?;
                Ok(MonoType::Int)
            }
            BinaryOp::Power => {
                self.unifier.unify(&left_ty, &MonoType::Int)?;
                self.unifier.unify(&right_ty, &MonoType::Int)?;
                Ok(MonoType::Int)
            }
            // Comparison operators
            BinaryOp::Equal
            | BinaryOp::NotEqual
            | BinaryOp::Less
            | BinaryOp::LessEqual
            | BinaryOp::Greater
            | BinaryOp::GreaterEqual
            | BinaryOp::Gt => {
                // Operands must have same type
                self.unifier.unify(&left_ty, &right_ty)?;
                Ok(MonoType::Bool)
            }
            // Boolean operators
            BinaryOp::And | BinaryOp::Or => {
                self.unifier.unify(&left_ty, &MonoType::Bool)?;
                self.unifier.unify(&right_ty, &MonoType::Bool)?;
                Ok(MonoType::Bool)
            }
            // Null coalescing operator: return type is union of operand types
            BinaryOp::NullCoalesce => {
                // Type is the union of left and right, but return the more specific non-null type
                Ok(right_ty) // For now, assume right type (could be improved with union types)
            }
            // Bitwise operators
            BinaryOp::BitwiseAnd
            | BinaryOp::BitwiseOr
            | BinaryOp::BitwiseXor
            | BinaryOp::LeftShift
            | BinaryOp::RightShift => {
                self.unifier.unify(&left_ty, &MonoType::Int)?;
                self.unifier.unify(&right_ty, &MonoType::Int)?;
                Ok(MonoType::Int)
            }
            // Actor message passing
            BinaryOp::Send => {
                // For now, return unit type for actor send
                Ok(MonoType::Unit)
            }
            // Containment check (Python-style 'in' operator)
            BinaryOp::In => {
                // 'in' returns a boolean (membership test)
                Ok(MonoType::Bool)
            }
        }
    }
    fn infer_unary(&mut self, op: UnaryOp, operand: &Expr) -> Result<MonoType> {
        let operand_ty = self.infer_expr(operand)?;
        match op {
            UnaryOp::Not => {
                self.unifier.unify(&operand_ty, &MonoType::Bool)?;
                Ok(MonoType::Bool)
            }
            UnaryOp::Negate => {
                // Can negate Int or Float
                self.unifier.unify(&operand_ty, &MonoType::Int)?;
                Ok(MonoType::Int)
            }
            UnaryOp::BitwiseNot => {
                self.unifier.unify(&operand_ty, &MonoType::Int)?;
                Ok(MonoType::Int)
            }
            UnaryOp::Reference | UnaryOp::MutableReference => {
                // Reference operators &x and &mut x: T -> &T
                // For type inference, &T and &mut T are the same
                // (PARSER-085: Issue #71)
                Ok(MonoType::Reference(Box::new(operand_ty)))
            }
            UnaryOp::Deref => {
                // Dereference operator *x: &T -> T
                match operand_ty {
                    MonoType::Reference(ref inner) => Ok((**inner).clone()),
                    _ => Err(anyhow::anyhow!("Cannot dereference non-reference type")),
                }
            }
        }
    }
    fn infer_throw(&mut self, expr: &Expr) -> Result<MonoType> {
        // Infer the type of the expression being thrown
        let _expr_ty = self.infer_expr(expr)?;
        // The expression must implement Error trait
        // For now, we'll just ensure it's a valid type
        // In a more complete implementation, we'd check Error trait bounds
        // The throw expression itself has the Never type (!)
        // But we'll represent it as a generic type for now
        Ok(MonoType::Var(self.gen.fresh()))
    }
    fn infer_await(&mut self, expr: &Expr) -> Result<MonoType> {
        // The expression must be a Future<Output = T>
        let expr_ty = self.infer_expr(expr)?;
        // For now, we'll just return the inner type
        // In a full implementation, we'd check for Future trait
        if let MonoType::Named(name) = &expr_ty {
            if name.starts_with("Future") {
                // Extract the output type
                return Ok(MonoType::Var(self.gen.fresh()));
            }
        }
        // For now, just return a fresh type variable
        Ok(MonoType::Var(self.gen.fresh()))
    }
    fn infer_if(
        &mut self,
        condition: &Expr,
        then_branch: &Expr,
        else_branch: Option<&Expr>,
    ) -> Result<MonoType> {
        // Condition must be Bool
        let cond_ty = self.infer_expr(condition)?;
        self.unifier.unify(&cond_ty, &MonoType::Bool)?;
        let then_ty = self.infer_expr(then_branch)?;
        if let Some(else_expr) = else_branch {
            let else_ty = self.infer_expr(else_expr)?;
            // Both branches must have same type
            self.unifier.unify(&then_ty, &else_ty)?;
            Ok(self.unifier.apply(&then_ty))
        } else {
            // No else branch means Unit type
            self.unifier.unify(&then_ty, &MonoType::Unit)?;
            Ok(MonoType::Unit)
        }
    }
    fn infer_let(
        &mut self,
        name: &str,
        value: &Expr,
        body: &Expr,
        _is_mutable: bool,
    ) -> Result<MonoType> {
        // Infer type of value
        let value_ty = self.infer_expr(value)?;
        // Generalize the value type
        let scheme = self.env.generalize(value_ty);
        // Extend environment and infer body
        let old_env = self.env.clone();
        self.env = self.env.extend(name, scheme);
        let body_ty = self.infer_expr(body)?;
        self.env = old_env;
        Ok(body_ty)
    }
    fn infer_function(
        &mut self,
        name: &str,
        params: &[Param],
        body: &Expr,
        _return_type: Option<&crate::frontend::ast::Type>,
        _is_async: bool,
    ) -> Result<MonoType> {
        // Create fresh type variables for parameters
        let mut param_types = Vec::new();
        let old_env = self.env.clone();
        for param in params {
            let param_ty =
                if param.ty.kind == crate::frontend::ast::TypeKind::Named("Any".to_string()) {
                    // Untyped parameter - create fresh type variable
                    MonoType::Var(self.gen.fresh())
                } else {
                    // Convert AST type to MonoType
                    Self::ast_type_to_mono_static(&param.ty)?
                };
            param_types.push(param_ty.clone());
            self.env = self.env.extend(param.name(), TypeScheme::mono(param_ty));
        }
        // Add function itself to environment for recursion
        let result_var = MonoType::Var(self.gen.fresh());
        let func_type = param_types
            .iter()
            .rev()
            .fold(result_var.clone(), |acc, param_ty| {
                MonoType::Function(Box::new(param_ty.clone()), Box::new(acc))
            });
        self.env = self.env.extend(name, TypeScheme::mono(func_type.clone()));
        // Infer body type
        let body_ty = self.infer_expr(body)?;
        self.unifier.unify(&result_var, &body_ty)?;
        self.env = old_env;
        let final_type = self.unifier.apply(&func_type);
        // Always return the function type for type inference
        // The distinction between statements and expressions should be handled at a higher level
        Ok(final_type)
    }
    fn infer_lambda(&mut self, params: &[Param], body: &Expr) -> Result<MonoType> {
        let old_env = self.env.clone();
        // Create type variables for parameters
        let mut param_types = Vec::new();
        for param in params {
            let param_ty = match &param.ty.kind {
                TypeKind::Named(name) if name == "Any" || name == "_" => {
                    // Untyped parameter - create fresh type variable
                    MonoType::Var(self.gen.fresh())
                }
                _ => {
                    // Convert AST type to MonoType
                    Self::ast_type_to_mono_static(&param.ty)?
                }
            };
            param_types.push(param_ty.clone());
            self.env = self.env.extend(param.name(), TypeScheme::mono(param_ty));
        }
        // Infer body type
        let body_ty = self.infer_expr(body)?;
        // Restore environment
        self.env = old_env;
        // Build function type from parameters and body
        let lambda_type = param_types.iter().rev().fold(body_ty, |acc, param_ty| {
            MonoType::Function(Box::new(param_ty.clone()), Box::new(acc))
        });
        Ok(self.unifier.apply(&lambda_type))
    }
    fn infer_call(&mut self, func: &Expr, args: &[Expr]) -> Result<MonoType> {
        let func_ty = self.infer_expr(func)?;
        // Create type for the function we expect
        let result_ty = MonoType::Var(self.gen.fresh());
        let mut expected_func_ty = result_ty.clone();
        for arg in args.iter().rev() {
            let arg_ty = self.infer_expr(arg)?;
            expected_func_ty = MonoType::Function(Box::new(arg_ty), Box::new(expected_func_ty));
        }
        // Unify with actual function type
        self.unifier.unify(&func_ty, &expected_func_ty)?;
        Ok(self.unifier.apply(&result_ty))
    }
    fn infer_macro(&mut self, name: &str, args: &[Expr]) -> Result<MonoType> {
        // Type check the arguments first
        for arg in args {
            self.infer_expr(arg)?;
        }
        // Determine the return type based on the macro name
        match name {
            "println" => Ok(MonoType::Unit), // println! returns unit
            "vec" => {
                // vec! returns a vector of the element type
                if args.is_empty() {
                    // Empty vec! needs type annotation or we use a generic type
                    Ok(MonoType::List(Box::new(MonoType::Var(self.gen.fresh()))))
                } else {
                    // Infer element type from first argument
                    let elem_ty = self.infer_expr(&args[0])?;
                    Ok(MonoType::List(Box::new(elem_ty)))
                }
            }
            "df" => {
                // df! macro creates a DataFrame with columns
                self.infer_dataframe_macro(args)
            }
            _ => bail!("Unknown macro: {name}"),
        }
    }

    fn infer_dataframe_macro(&mut self, args: &[Expr]) -> Result<MonoType> {
        let mut columns = Vec::new();

        for arg in args {
            // df! macro arguments are assignments like: age = [25, 30, 35]
            if let ExprKind::Assign { target, value } = &arg.kind {
                // Extract column name from the target (should be an identifier)
                let column_name = match &target.kind {
                    ExprKind::Identifier(name) => name.clone(),
                    _ => continue, // Skip non-identifier targets
                };

                // Infer the type of the column data
                let column_type = self.infer_expr(value)?;

                // Extract element type from list/array for column type
                let element_type = match column_type {
                    MonoType::List(elem_type) => *elem_type,
                    other_type => other_type, // Single values become single-element columns
                };

                columns.push((column_name, element_type));
            }
        }

        Ok(MonoType::DataFrame(columns))
    }

    fn infer_dataframe_from_assignments(&mut self, assignments: &[Expr]) -> Result<MonoType> {
        let mut columns = Vec::new();

        for assignment in assignments {
            // Each assignment should be: age = [25, 30, 35]
            if let ExprKind::Assign { target, value } = &assignment.kind {
                // Extract column name from the target (should be an identifier)
                let column_name = match &target.kind {
                    ExprKind::Identifier(name) => name.clone(),
                    _ => continue, // Skip non-identifier targets
                };

                // Infer the type of the column data
                let column_type = self.infer_expr(value)?;

                // Extract element type from list/array for column type
                let element_type = match column_type {
                    MonoType::List(elem_type) => *elem_type,
                    other_type => other_type, // Single values become single-element columns
                };

                columns.push((column_name, element_type));
            }
        }

        Ok(MonoType::DataFrame(columns))
    }
    /// REFACTORED FOR COMPLEXITY REDUCTION
    /// Original: 41 cyclomatic complexity, Target: <20
    /// Strategy: Extract method-category specific handlers
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::middleend::infer::infer_method_call;
    ///
    /// let result = infer_method_call("example");
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn infer_method_call(
        &mut self,
        receiver: &Expr,
        method: &str,
        args: &[Expr],
    ) -> Result<MonoType> {
        let receiver_ty = self.infer_expr(receiver)?;
        self.add_method_constraint(&receiver_ty, method, args)?;
        // Dispatch based on receiver type category (complexity: delegated)
        match &receiver_ty {
            MonoType::List(_) => self.infer_list_method(&receiver_ty, method, args),
            MonoType::String => self.infer_string_method(&receiver_ty, method, args),
            MonoType::DataFrame(_) | MonoType::Series(_) => {
                self.infer_dataframe_method(&receiver_ty, method, args)
            }
            MonoType::Named(name) if name == "DataFrame" || name == "Series" => {
                self.infer_dataframe_method(&receiver_ty, method, args)
            }
            _ => self.infer_generic_method(&receiver_ty, method, args),
        }
    }
    /// Extract method constraint addition (complexity ~3)
    fn add_method_constraint(
        &mut self,
        receiver_ty: &MonoType,
        method: &str,
        args: &[Expr],
    ) -> Result<()> {
        let arg_types: Result<Vec<_>> = args.iter().map(|arg| self.infer_expr(arg)).collect();
        let arg_types = arg_types?;
        self.type_constraints.push(TypeConstraint::MethodCall(
            receiver_ty.clone(),
            method.to_string(),
            arg_types,
        ));
        Ok(())
    }
    /// Extract list method handling (complexity ~10)
    fn infer_list_method(
        &mut self,
        receiver_ty: &MonoType,
        method: &str,
        args: &[Expr],
    ) -> Result<MonoType> {
        if let MonoType::List(elem_ty) = receiver_ty {
            match method {
                "len" | "length" => {
                    self.validate_no_args(method, args)?;
                    Ok(MonoType::Int)
                }
                "push" => {
                    self.validate_single_arg(method, args)?;
                    let arg_ty = self.infer_expr(&args[0])?;
                    self.unifier.unify(&arg_ty, elem_ty)?;
                    Ok(MonoType::Unit)
                }
                "pop" => {
                    self.validate_no_args(method, args)?;
                    Ok(MonoType::Optional(elem_ty.clone()))
                }
                "sorted" | "reversed" | "unique" => {
                    self.validate_no_args(method, args)?;
                    Ok(MonoType::List(elem_ty.clone()))
                }
                "sum" => {
                    self.validate_no_args(method, args)?;
                    Ok(*elem_ty.clone())
                }
                "min" | "max" => {
                    self.validate_no_args(method, args)?;
                    Ok(MonoType::Optional(elem_ty.clone()))
                }
                _ => self.infer_generic_method(receiver_ty, method, args),
            }
        } else {
            self.infer_generic_method(receiver_ty, method, args)
        }
    }
    /// Extract string method handling (complexity ~5)
    fn infer_string_method(
        &mut self,
        receiver_ty: &MonoType,
        method: &str,
        args: &[Expr],
    ) -> Result<MonoType> {
        match method {
            "len" | "length" => {
                self.validate_no_args(method, args)?;
                Ok(MonoType::Int)
            }
            "chars" => {
                self.validate_no_args(method, args)?;
                Ok(MonoType::List(Box::new(MonoType::String)))
            }
            _ => self.infer_generic_method(receiver_ty, method, args),
        }
    }
    /// Extract dataframe method handling (complexity ~8)
    fn infer_dataframe_method(
        &mut self,
        receiver_ty: &MonoType,
        method: &str,
        args: &[Expr],
    ) -> Result<MonoType> {
        match method {
            "filter" | "groupby" | "agg" | "select" => match receiver_ty {
                MonoType::DataFrame(columns) => Ok(MonoType::DataFrame(columns.clone())),
                MonoType::Named(name) if name == "DataFrame" => {
                    Ok(MonoType::Named("DataFrame".to_string()))
                }
                _ => Ok(MonoType::Named("DataFrame".to_string())),
            },
            "mean" | "std" | "sum" | "count" => Ok(MonoType::Float),
            "col" => self.infer_column_selection(receiver_ty, args),
            _ => self.infer_generic_method(receiver_ty, method, args),
        }
    }
    /// Extract column selection logic (complexity ~5)
    fn infer_column_selection(
        &mut self,
        receiver_ty: &MonoType,
        args: &[Expr],
    ) -> Result<MonoType> {
        if let MonoType::DataFrame(columns) = receiver_ty {
            if let Some(arg) = args.first() {
                if let ExprKind::Literal(Literal::String(col_name)) = &arg.kind {
                    if let Some((_, col_type)) = columns.iter().find(|(name, _)| name == col_name) {
                        return Ok(MonoType::Series(Box::new(col_type.clone())));
                    }
                }
            }
            Ok(MonoType::Series(Box::new(MonoType::Var(self.gen.fresh()))))
        } else {
            Ok(MonoType::Series(Box::new(MonoType::Var(self.gen.fresh()))))
        }
    }
    /// Extract generic method handling (complexity ~8)
    fn infer_generic_method(
        &mut self,
        receiver_ty: &MonoType,
        method: &str,
        args: &[Expr],
    ) -> Result<MonoType> {
        if let Some(scheme) = self.env.lookup(method) {
            let method_ty = self.env.instantiate(scheme, &mut self.gen);
            let result_ty = MonoType::Var(self.gen.fresh());
            let expected_func_ty =
                self.build_method_function_type(receiver_ty, args, result_ty.clone())?;
            self.unifier.unify(&method_ty, &expected_func_ty)?;
            Ok(self.unifier.apply(&result_ty))
        } else {
            Ok(MonoType::Var(self.gen.fresh()))
        }
    }
    /// Extract function type construction (complexity ~4)
    fn build_method_function_type(
        &mut self,
        receiver_ty: &MonoType,
        args: &[Expr],
        result_ty: MonoType,
    ) -> Result<MonoType> {
        let mut expected_func_ty = result_ty;
        for arg in args.iter().rev() {
            let arg_ty = self.infer_expr(arg)?;
            expected_func_ty = MonoType::Function(Box::new(arg_ty), Box::new(expected_func_ty));
        }
        // Add receiver as first argument
        expected_func_ty =
            MonoType::Function(Box::new(receiver_ty.clone()), Box::new(expected_func_ty));
        Ok(expected_func_ty)
    }
    /// Helper methods for argument validation (complexity ~3 each)
    fn validate_no_args(&self, method: &str, args: &[Expr]) -> Result<()> {
        if !args.is_empty() {
            bail!("Method {method} takes no arguments");
        }
        Ok(())
    }
    fn validate_single_arg(&self, method: &str, args: &[Expr]) -> Result<()> {
        if args.len() != 1 {
            bail!("Method {method} takes exactly one argument");
        }
        Ok(())
    }
    fn infer_block(&mut self, exprs: &[Expr]) -> Result<MonoType> {
        if exprs.is_empty() {
            return Ok(MonoType::Unit);
        }

        // Check for DataFrame macro pattern: df![...]
        // Parsed as Block([Identifier("df"), List([assignments...])])
        if exprs.len() == 2 {
            if let (ExprKind::Identifier(name), ExprKind::List(assignments)) =
                (&exprs[0].kind, &exprs[1].kind)
            {
                if name == "df" {
                    return self.infer_dataframe_from_assignments(assignments);
                }
            }
        }

        // Standard block inference: return type of last expression
        let mut last_ty = MonoType::Unit;
        for expr in exprs {
            last_ty = self.infer_expr(expr)?;
        }
        Ok(last_ty)
    }
    fn infer_list(&mut self, elements: &[Expr]) -> Result<MonoType> {
        if elements.is_empty() {
            // Empty list with fresh type variable
            let elem_ty = MonoType::Var(self.gen.fresh());
            return Ok(MonoType::List(Box::new(elem_ty)));
        }
        // All elements must have same type
        let first_ty = self.infer_expr(&elements[0])?;
        for elem in &elements[1..] {
            let elem_ty = self.infer_expr(elem)?;
            self.unifier.unify(&first_ty, &elem_ty)?;
        }
        Ok(MonoType::List(Box::new(self.unifier.apply(&first_ty))))
    }
    fn infer_list_comprehension(
        &mut self,
        element: &Expr,
        variable: &str,
        iterable: &Expr,
        condition: Option<&Expr>,
    ) -> Result<MonoType> {
        // Type check the iterable - must be a list
        let iterable_ty = self.infer_expr(iterable)?;
        let elem_ty = MonoType::Var(self.gen.fresh());
        self.unifier
            .unify(&iterable_ty, &MonoType::List(Box::new(elem_ty.clone())))?;
        // Save the old environment and add the loop variable
        let old_env = self.env.clone();
        self.env = self
            .env
            .extend(variable, TypeScheme::mono(self.unifier.apply(&elem_ty)));
        // Type check the optional condition (must be bool)
        if let Some(cond) = condition {
            let cond_ty = self.infer_expr(cond)?;
            self.unifier.unify(&cond_ty, &MonoType::Bool)?;
        }
        // Type check the element expression
        let result_elem_ty = self.infer_expr(element)?;
        // Restore the environment
        self.env = old_env;
        // Return List<T> where T is the type of the element expression
        Ok(MonoType::List(Box::new(
            self.unifier.apply(&result_elem_ty),
        )))
    }
    fn infer_match(
        &mut self,
        expr: &Expr,
        arms: &[crate::frontend::ast::MatchArm],
    ) -> Result<MonoType> {
        let expr_ty = self.infer_expr(expr)?;
        if arms.is_empty() {
            bail!("Match expression must have at least one arm");
        }
        // All arms must return same type
        let result_ty = MonoType::Var(self.gen.fresh());
        for arm in arms {
            // Infer pattern and bind variables
            let old_env = self.env.clone();
            self.infer_pattern(&arm.pattern, &expr_ty)?;
            // Guards have been removed from the grammar
            // Infer body type
            let body_ty = self.infer_expr(&arm.body)?;
            self.unifier.unify(&result_ty, &body_ty)?;
            self.env = old_env;
        }
        Ok(self.unifier.apply(&result_ty))
    }
    fn infer_pattern(&mut self, pattern: &Pattern, expected_ty: &MonoType) -> Result<()> {
        match pattern {
            Pattern::Wildcard => Ok(()),
            Pattern::Literal(lit) => {
                let lit_ty = Self::infer_literal(lit);
                self.unifier.unify(expected_ty, &lit_ty)
            }
            Pattern::Identifier(name) => {
                // Bind the identifier to the expected type
                self.env = self.env.extend(name, TypeScheme::mono(expected_ty.clone()));
                Ok(())
            }
            Pattern::QualifiedName(_path) => {
                // Qualified names in patterns should match against specific enum variants
                // For now, assume it's valid
                Ok(())
            }
            Pattern::List(patterns) => {
                let elem_ty = MonoType::Var(self.gen.fresh());
                self.unifier
                    .unify(expected_ty, &MonoType::List(Box::new(elem_ty.clone())))?;
                for pat in patterns {
                    self.infer_pattern(pat, &elem_ty)?;
                }
                Ok(())
            }
            Pattern::Ok(inner) => {
                // Expected type should be Result<T, E>, extract T for inner pattern
                if let MonoType::Result(ok_ty, _) = expected_ty {
                    self.infer_pattern(inner, ok_ty)
                } else {
                    // Create a fresh Result type
                    let error_ty = MonoType::Var(self.gen.fresh());
                    let inner_ty = MonoType::Var(self.gen.fresh());
                    let result_ty =
                        MonoType::Result(Box::new(inner_ty.clone()), Box::new(error_ty));
                    self.unifier.unify(expected_ty, &result_ty)?;
                    self.infer_pattern(inner, &inner_ty)
                }
            }
            Pattern::Err(inner) => {
                // Expected type should be Result<T, E>, extract E for inner pattern
                if let MonoType::Result(_, err_ty) = expected_ty {
                    self.infer_pattern(inner, err_ty)
                } else {
                    // Create a fresh Result type
                    let ok_ty = MonoType::Var(self.gen.fresh());
                    let inner_ty = MonoType::Var(self.gen.fresh());
                    let result_ty = MonoType::Result(Box::new(ok_ty), Box::new(inner_ty.clone()));
                    self.unifier.unify(expected_ty, &result_ty)?;
                    self.infer_pattern(inner, &inner_ty)
                }
            }
            Pattern::Some(inner) => {
                // Expected type should be Option<T>, extract T for inner pattern
                if let MonoType::Optional(inner_ty) = expected_ty {
                    self.infer_pattern(inner, inner_ty)
                } else {
                    // Create a fresh Option type
                    let inner_ty = MonoType::Var(self.gen.fresh());
                    let option_ty = MonoType::Optional(Box::new(inner_ty.clone()));
                    self.unifier.unify(expected_ty, &option_ty)?;
                    self.infer_pattern(inner, &inner_ty)
                }
            }
            Pattern::None => {
                // None pattern matches Option<T> where T can be any type
                let type_var = MonoType::Var(self.gen.fresh());
                let option_ty = MonoType::Optional(Box::new(type_var));
                self.unifier.unify(expected_ty, &option_ty)
            }
            Pattern::Tuple(patterns) => {
                // Create tuple type with each pattern's inferred type
                let mut elem_types = Vec::new();
                for pat in patterns {
                    let elem_ty = MonoType::Var(self.gen.fresh());
                    self.infer_pattern(pat, &elem_ty)?;
                    elem_types.push(elem_ty);
                }
                let tuple_ty = MonoType::Tuple(elem_types);
                self.unifier.unify(expected_ty, &tuple_ty)
            }
            Pattern::Struct {
                name,
                fields,
                has_rest: _,
            } => {
                // For now, treat struct patterns as a named type
                // In a more complete implementation, we'd look up the struct definition
                let struct_ty = MonoType::Named(name.clone());
                self.unifier.unify(expected_ty, &struct_ty)?;
                // Infer field patterns (simplified approach)
                for field in fields {
                    if let Some(pattern) = &field.pattern {
                        let field_ty = MonoType::Var(self.gen.fresh());
                        self.infer_pattern(pattern, &field_ty)?;
                    }
                }
                Ok(())
            }
            Pattern::Range { start, end, .. } => {
                // Range patterns should match numeric types
                let start_ty = MonoType::Var(self.gen.fresh());
                let end_ty = MonoType::Var(self.gen.fresh());
                self.infer_pattern(start, &start_ty)?;
                self.infer_pattern(end, &end_ty)?;
                // Unify start and end types, and with expected type
                self.unifier.unify(&start_ty, &end_ty)?;
                self.unifier.unify(expected_ty, &start_ty)
            }
            Pattern::Or(patterns) => {
                // All patterns in an OR must have the same type
                for pat in patterns {
                    self.infer_pattern(pat, expected_ty)?;
                }
                Ok(())
            }
            Pattern::Rest => {
                // Rest patterns don't bind to specific types
                Ok(())
            }
            Pattern::RestNamed(name) => {
                // Named rest patterns bind the remaining elements to the name
                // For arrays [first, ..rest], rest should be array type
                self.env = self.env.extend(name, TypeScheme::mono(expected_ty.clone()));
                Ok(())
            }
            Pattern::AtBinding { name, pattern } => {
                // @ bindings bind the name to the matched value and also match the pattern
                self.env = self.env.extend(name, TypeScheme::mono(expected_ty.clone()));
                self.infer_pattern(pattern, expected_ty)
            }
            Pattern::WithDefault { pattern, .. } => {
                // For default patterns, we check the inner pattern with the expected type
                // The default value will be used if the actual value doesn't match
                self.infer_pattern(pattern, expected_ty)
            }
            Pattern::TupleVariant { path: _, patterns } => {
                // For enum tuple variants, infer the type from the arguments
                // For now, treat like a tuple pattern
                for pat in patterns {
                    let elem_ty = MonoType::Var(self.gen.fresh());
                    self.infer_pattern(pat, &elem_ty)?;
                }
                Ok(())
            }
            Pattern::Mut(inner) => {
                // Mut patterns have the same type as their inner pattern
                // Mutability is a runtime concern, not a type concern
                self.infer_pattern(inner, expected_ty)
            }
        }
    }
    fn infer_for(&mut self, var: &str, iter: &Expr, body: &Expr) -> Result<MonoType> {
        let iter_ty = self.infer_expr(iter)?;
        // Iterator should be a list
        let elem_ty = MonoType::Var(self.gen.fresh());
        self.unifier
            .unify(&iter_ty, &MonoType::List(Box::new(elem_ty.clone())))?;
        // Bind loop variable and infer body
        let old_env = self.env.clone();
        self.env = self.env.extend(var, TypeScheme::mono(elem_ty));
        let _body_ty = self.infer_expr(body)?;
        self.env = old_env;
        // For loops always return Unit regardless of body type
        Ok(MonoType::Unit)
    }
    fn infer_while(&mut self, condition: &Expr, body: &Expr) -> Result<MonoType> {
        // Condition must be Bool
        let cond_ty = self.infer_expr(condition)?;
        self.unifier.unify(&cond_ty, &MonoType::Bool)?;
        // Type check body
        let body_ty = self.infer_expr(body)?;
        self.unifier.unify(&body_ty, &MonoType::Unit)?;
        // While loops return unit
        Ok(MonoType::Unit)
    }
    fn infer_loop(&mut self, body: &Expr) -> Result<MonoType> {
        // Type check body
        let body_ty = self.infer_expr(body)?;
        self.unifier.unify(&body_ty, &MonoType::Unit)?;
        // Loop expressions return unit
        Ok(MonoType::Unit)
    }
    fn infer_range(&mut self, start: &Expr, end: &Expr) -> Result<MonoType> {
        let start_ty = self.infer_expr(start)?;
        let end_ty = self.infer_expr(end)?;
        // Both must be integers
        self.unifier.unify(&start_ty, &MonoType::Int)?;
        self.unifier.unify(&end_ty, &MonoType::Int)?;
        // Range produces a list of integers
        Ok(MonoType::List(Box::new(MonoType::Int)))
    }
    fn infer_pipeline(
        &mut self,
        expr: &Expr,
        stages: &[crate::frontend::ast::PipelineStage],
    ) -> Result<MonoType> {
        let mut current_ty = self.infer_expr(expr)?;
        for stage in stages {
            // Each stage is a function applied to current value
            let stage_ty = self.infer_expr(&stage.op)?;
            // Create expected function type
            let result_ty = MonoType::Var(self.gen.fresh());
            let expected_func =
                MonoType::Function(Box::new(current_ty.clone()), Box::new(result_ty.clone()));
            self.unifier.unify(&stage_ty, &expected_func)?;
            current_ty = self.unifier.apply(&result_ty);
        }
        Ok(current_ty)
    }
    fn infer_assign(&mut self, target: &Expr, value: &Expr) -> Result<MonoType> {
        // Infer the type of the value being assigned
        let value_ty = self.infer_expr(value)?;
        // Infer the type of the target (lvalue)
        let target_ty = self.infer_expr(target)?;
        // Target and value must have compatible types
        self.unifier.unify(&target_ty, &value_ty)?;
        // Assignment expressions return Unit
        Ok(MonoType::Unit)
    }
    fn infer_compound_assign(
        &mut self,
        target: &Expr,
        op: BinaryOp,
        value: &Expr,
    ) -> Result<MonoType> {
        // Infer the types of target and value
        let target_ty = self.infer_expr(target)?;
        let value_ty = self.infer_expr(value)?;
        // For compound assignment, we need to ensure the operation is valid
        // This is equivalent to: target = target op value
        let result_ty = self.infer_binary_op_type(op, &target_ty, &value_ty)?;
        // The result type must be compatible with the target type
        self.unifier.unify(&target_ty, &result_ty)?;
        // Compound assignment expressions return Unit
        Ok(MonoType::Unit)
    }
    fn infer_binary_op_type(
        &mut self,
        op: BinaryOp,
        left_ty: &MonoType,
        right_ty: &MonoType,
    ) -> Result<MonoType> {
        match op {
            BinaryOp::Add
            | BinaryOp::Subtract
            | BinaryOp::Multiply
            | BinaryOp::Divide
            | BinaryOp::Modulo => {
                // Arithmetic operations: both operands should be numbers, result is same type
                // Try Int first, then Float
                if let Ok(()) = self.unifier.unify(left_ty, &MonoType::Int) {
                    if let Ok(()) = self.unifier.unify(right_ty, &MonoType::Int) {
                        return Ok(MonoType::Int);
                    }
                }
                // Fall back to Float
                self.unifier.unify(left_ty, &MonoType::Float)?;
                self.unifier.unify(right_ty, &MonoType::Float)?;
                Ok(MonoType::Float)
            }
            BinaryOp::Power => {
                // Power operation: base and exponent are numbers, result is same as base
                self.unifier.unify(left_ty, right_ty)?;
                if let Ok(()) = self.unifier.unify(left_ty, &MonoType::Int) {
                    Ok(MonoType::Int)
                } else {
                    self.unifier.unify(left_ty, &MonoType::Float)?;
                    Ok(MonoType::Float)
                }
            }
            BinaryOp::Equal
            | BinaryOp::NotEqual
            | BinaryOp::Less
            | BinaryOp::LessEqual
            | BinaryOp::Greater
            | BinaryOp::GreaterEqual
            | BinaryOp::Gt => {
                // Comparison operations: operands must be same type, result is Bool
                self.unifier.unify(left_ty, right_ty)?;
                Ok(MonoType::Bool)
            }
            BinaryOp::And | BinaryOp::Or => {
                // Logical operations: both operands must be Bool, result is Bool
                self.unifier.unify(left_ty, &MonoType::Bool)?;
                self.unifier.unify(right_ty, &MonoType::Bool)?;
                Ok(MonoType::Bool)
            }
            BinaryOp::NullCoalesce => {
                // Null coalescing: return type should be the non-null operand type
                // For now, return right_ty (could be improved with proper union types)
                Ok(right_ty.clone())
            }
            BinaryOp::BitwiseAnd
            | BinaryOp::BitwiseOr
            | BinaryOp::BitwiseXor
            | BinaryOp::LeftShift
            | BinaryOp::RightShift => {
                // Bitwise operations: both operands must be Int, result is Int
                self.unifier.unify(left_ty, &MonoType::Int)?;
                self.unifier.unify(right_ty, &MonoType::Int)?;
                Ok(MonoType::Int)
            }
            BinaryOp::Send => {
                // Actor message passing: return unit type
                Ok(MonoType::Unit)
            }
            BinaryOp::In => {
                // Containment check returns boolean
                Ok(MonoType::Bool)
            }
        }
    }
    fn infer_increment_decrement(&mut self, target: &Expr) -> Result<MonoType> {
        // Infer the type of the target
        let target_ty = self.infer_expr(target)?;
        // Target must be a numeric type (Int or Float)
        // Try Int first, then Float
        if let Ok(()) = self.unifier.unify(&target_ty, &MonoType::Int) {
            Ok(MonoType::Int)
        } else {
            self.unifier.unify(&target_ty, &MonoType::Float)?;
            Ok(MonoType::Float)
        }
    }
    fn ast_type_to_mono_static(ty: &crate::frontend::ast::Type) -> Result<MonoType> {
        use crate::frontend::ast::TypeKind;
        Ok(match &ty.kind {
            TypeKind::Named(name) => match name.as_str() {
                "i32" | "i64" => MonoType::Int,
                "f32" | "f64" => MonoType::Float,
                "bool" => MonoType::Bool,
                "String" | "str" => MonoType::String,
                "Any" => MonoType::Var(TyVarGenerator::new().fresh()),
                _ => MonoType::Named(name.clone()),
            },
            TypeKind::Generic { base, params } => {
                // For now, treat generic types as their base type
                // Full generic inference will be implemented later
                match base.as_str() {
                    "Vec" | "List" => {
                        if let Some(first_param) = params.first() {
                            MonoType::List(Box::new(Self::ast_type_to_mono_static(first_param)?))
                        } else {
                            MonoType::List(Box::new(MonoType::Var(TyVarGenerator::new().fresh())))
                        }
                    }
                    "Option" => {
                        if let Some(first_param) = params.first() {
                            MonoType::Optional(Box::new(Self::ast_type_to_mono_static(
                                first_param,
                            )?))
                        } else {
                            MonoType::Optional(Box::new(MonoType::Var(
                                TyVarGenerator::new().fresh(),
                            )))
                        }
                    }
                    _ => MonoType::Named(base.clone()),
                }
            }
            TypeKind::Optional(inner) => {
                MonoType::Optional(Box::new(Self::ast_type_to_mono_static(inner)?))
            }
            TypeKind::List(inner) => {
                MonoType::List(Box::new(Self::ast_type_to_mono_static(inner)?))
            }
            TypeKind::Array { elem_type, size: _ } => {
                // For now, treat arrays as lists in the type system
                // The size is tracked in the AST but not in the monomorphic type
                MonoType::List(Box::new(Self::ast_type_to_mono_static(elem_type)?))
            }
            TypeKind::Function { params, ret } => {
                let ret_ty = Self::ast_type_to_mono_static(ret)?;
                let result: Result<MonoType> =
                    params.iter().rev().try_fold(ret_ty, |acc, param| {
                        Ok(MonoType::Function(
                            Box::new(Self::ast_type_to_mono_static(param)?),
                            Box::new(acc),
                        ))
                    });
                result?
            }
            TypeKind::DataFrame { columns } => {
                let mut col_types = Vec::new();
                for (name, ty) in columns {
                    col_types.push((name.clone(), Self::ast_type_to_mono_static(ty)?));
                }
                MonoType::DataFrame(col_types)
            }
            TypeKind::Series { dtype } => {
                MonoType::Series(Box::new(Self::ast_type_to_mono_static(dtype)?))
            }
            TypeKind::Tuple(types) => {
                let mono_types: Result<Vec<_>> =
                    types.iter().map(Self::ast_type_to_mono_static).collect();
                MonoType::Tuple(mono_types?)
            }
            TypeKind::Reference { inner, .. } => {
                // For type inference, treat references the same as the inner type
                Self::ast_type_to_mono_static(inner)?
            }
            // SPEC-001-H: Refined types - extract base type, ignore constraint
            // Type inference operates on structural types, not refinements
            TypeKind::Refined { base, .. } => Self::ast_type_to_mono_static(base)?,
        })
    }
    /// Get the final inferred type for a type variable
    #[must_use]
    /// # Examples
    ///
    /// ```
    /// use ruchy::middleend::infer::solve;
    ///
    /// let result = solve(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn solve(&self, var: &crate::middleend::types::TyVar) -> MonoType {
        self.unifier.solve(var)
    }
    /// Apply current substitution to a type
    #[must_use]
    /// # Examples
    ///
    /// ```
    /// use ruchy::middleend::infer::apply;
    ///
    /// let result = apply(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn apply(&self, ty: &MonoType) -> MonoType {
        self.unifier.apply(ty)
    }
    /// Infer types for control flow expressions (if, match, loops)
    ///
    /// # Example Usage
    /// Handles type inference for control flow constructs.
    /// For if expressions, ensures both branches have compatible types.
    /// For match expressions, checks pattern compatibility and branch types.
    fn infer_control_flow_expr(&mut self, expr: &Expr) -> Result<MonoType> {
        match &expr.kind {
            ExprKind::If {
                condition,
                then_branch,
                else_branch,
            } => self.infer_if(condition, then_branch, else_branch.as_deref()),
            ExprKind::For {
                var, iter, body, ..
            } => self.infer_for(var, iter, body),
            ExprKind::While {
                condition, body, ..
            } => self.infer_while(condition, body),
            ExprKind::Loop { body, .. } => self.infer_loop(body),
            ExprKind::IfLet {
                pattern: _,
                expr,
                then_branch,
                else_branch,
            } => {
                let _expr_ty = self.infer_expr(expr)?;
                let then_ty = self.infer_expr(then_branch)?;
                let else_ty = if let Some(else_expr) = else_branch {
                    self.infer_expr(else_expr)?
                } else {
                    MonoType::Unit
                };
                self.unifier.unify(&then_ty, &else_ty)?;
                Ok(then_ty)
            }
            ExprKind::WhileLet {
                pattern: _,
                expr,
                body,
                ..
            } => {
                let _expr_ty = self.infer_expr(expr)?;
                let _body_ty = self.infer_expr(body)?;
                Ok(MonoType::Unit)
            }
            _ => bail!("Unexpected expression type in control flow handler"),
        }
    }
    /// Infer types for function and lambda expressions
    fn infer_function_expr(&mut self, expr: &Expr) -> Result<MonoType> {
        match &expr.kind {
            ExprKind::Function {
                name,
                params,
                body,
                return_type,
                is_async,
                ..
            } => self.infer_function(name, params, body, return_type.as_ref(), *is_async),
            ExprKind::Lambda { params, body } => self.infer_lambda(params, body),
            _ => bail!("Unexpected expression type in function handler"),
        }
    }
    /// Infer types for collection expressions (lists, tuples, comprehensions)
    fn infer_collection_expr(&mut self, expr: &Expr) -> Result<MonoType> {
        match &expr.kind {
            ExprKind::List(elements) => self.infer_list(elements),
            ExprKind::Tuple(elements) => {
                let element_types: Result<Vec<_>> =
                    elements.iter().map(|e| self.infer_expr(e)).collect();
                Ok(MonoType::Tuple(element_types?))
            }
            ExprKind::ListComprehension { element, clauses } => {
                // For now, use the first clause for type inference
                if let Some(first_clause) = clauses.first() {
                    self.infer_list_comprehension(
                        element,
                        &first_clause.variable,
                        &first_clause.iterable,
                        first_clause.condition.as_deref(),
                    )
                } else {
                    bail!("List comprehension must have at least one clause")
                }
            }
            _ => bail!("Unexpected expression type in collection handler"),
        }
    }
    /// Infer types for operations and method calls
    fn infer_operation_expr(&mut self, expr: &Expr) -> Result<MonoType> {
        match &expr.kind {
            ExprKind::Binary { left, op, right } => self.infer_binary(left, *op, right),
            ExprKind::Unary { op, operand } => self.infer_unary(*op, operand),
            ExprKind::Call { func, args } => self.infer_call(func, args),
            ExprKind::MethodCall {
                receiver,
                method,
                args,
            } => self.infer_method_call(receiver, method, args),
            _ => bail!("Unexpected expression type in operation handler"),
        }
    }
    /// REFACTORED FOR COMPLEXITY REDUCTION
    /// Original: 38 cyclomatic complexity, Target: <20
    /// Strategy: Group related expression types into category handlers
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::middleend::infer::infer_other_expr;
    ///
    /// let result = infer_other_expr(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn infer_other_expr(&mut self, expr: &Expr) -> Result<MonoType> {
        match &expr.kind {
            // Special cases that need specific handling
            ExprKind::StringInterpolation { parts } => self.infer_string_interpolation(parts),
            ExprKind::Throw { expr } => self.infer_throw(expr),
            ExprKind::Ok { value } => self.infer_result_ok(value),
            ExprKind::Err { error } => self.infer_result_err(error),
            // Control flow expressions (all return Unit)
            ExprKind::Break { .. } | ExprKind::Continue { .. } | ExprKind::Return { .. } => {
                self.infer_other_control_flow_expr(expr)
            }
            // Definition expressions (all return Unit)
            ExprKind::Struct { .. }
            | ExprKind::Enum { .. }
            | ExprKind::Trait { .. }
            | ExprKind::Impl { .. }
            | ExprKind::Extension { .. }
            | ExprKind::Actor { .. }
            | ExprKind::Import { .. }
            | ExprKind::Export { .. } => self.infer_other_definition_expr(expr),
            // Literal and access expressions
            ExprKind::StructLiteral { .. }
            | ExprKind::ObjectLiteral { .. }
            | ExprKind::FieldAccess { .. }
            | ExprKind::IndexAccess { .. }
            | ExprKind::Slice { .. } => self.infer_other_literal_access_expr(expr),
            // Option expressions
            ExprKind::Some { .. } | ExprKind::None => self.infer_other_option_expr(expr),
            // Async expressions
            ExprKind::Await { .. } | ExprKind::AsyncBlock { .. } | ExprKind::Try { .. } => {
                self.infer_other_async_expr(expr)
            }
            // Actor expressions
            ExprKind::Send { .. }
            | ExprKind::ActorSend { .. }
            | ExprKind::Ask { .. }
            | ExprKind::ActorQuery { .. } => self.infer_other_actor_expr(expr),
            // Assignment expressions
            ExprKind::Assign { .. }
            | ExprKind::CompoundAssign { .. }
            | ExprKind::PreIncrement { .. }
            | ExprKind::PostIncrement { .. }
            | ExprKind::PreDecrement { .. }
            | ExprKind::PostDecrement { .. } => self.infer_other_assignment_expr(expr),
            // Remaining expressions
            _ => self.infer_remaining_expr(expr),
        }
    }
    /// Extract control flow handling (complexity ~1)
    fn infer_other_control_flow_expr(&mut self, _expr: &Expr) -> Result<MonoType> {
        Ok(MonoType::Unit) // All control flow returns Unit
    }
    /// Extract definition handling (complexity ~1)  
    fn infer_other_definition_expr(&mut self, _expr: &Expr) -> Result<MonoType> {
        Ok(MonoType::Unit) // All definitions return Unit
    }
    /// Extract literal/access handling (complexity ~8)
    fn infer_other_literal_access_expr(&mut self, expr: &Expr) -> Result<MonoType> {
        match &expr.kind {
            ExprKind::StructLiteral { name, .. } => Ok(MonoType::Named(name.clone())),
            ExprKind::ObjectLiteral { fields } => self.infer_object_literal(fields),
            ExprKind::FieldAccess { object, .. } => self.infer_field_access(object),
            ExprKind::IndexAccess { object, index } => self.infer_index_access(object, index),
            ExprKind::Slice { object, .. } => self.infer_slice(object),
            _ => bail!("Unexpected literal/access expression"),
        }
    }
    /// Extract option handling (complexity ~5)
    fn infer_other_option_expr(&mut self, expr: &Expr) -> Result<MonoType> {
        match &expr.kind {
            ExprKind::Some { value } => {
                let inner_type = self.infer_expr(value)?;
                Ok(MonoType::Optional(Box::new(inner_type)))
            }
            ExprKind::None => {
                let type_var = MonoType::Var(self.gen.fresh());
                Ok(MonoType::Optional(Box::new(type_var)))
            }
            _ => bail!("Unexpected option expression"),
        }
    }
    /// Extract async handling (complexity ~5)
    fn infer_other_async_expr(&mut self, expr: &Expr) -> Result<MonoType> {
        match &expr.kind {
            ExprKind::Await { expr } => self.infer_await(expr),
            ExprKind::AsyncBlock { body } => self.infer_async_block(body),
            ExprKind::Try { expr } => {
                let expr_type = self.infer(expr)?;
                Ok(expr_type)
            }
            _ => bail!("Unexpected async expression"),
        }
    }
    /// Extract actor handling (complexity ~6)
    fn infer_other_actor_expr(&mut self, expr: &Expr) -> Result<MonoType> {
        match &expr.kind {
            ExprKind::Send { actor, message } | ExprKind::ActorSend { actor, message } => {
                self.infer_send(actor, message)
            }
            ExprKind::Ask {
                actor,
                message,
                timeout,
            } => self.infer_ask(actor, message, timeout.as_deref()),
            ExprKind::ActorQuery { actor, message } => self.infer_ask(actor, message, None),
            _ => bail!("Unexpected actor expression"),
        }
    }
    /// Extract assignment handling (complexity ~6)
    fn infer_other_assignment_expr(&mut self, expr: &Expr) -> Result<MonoType> {
        match &expr.kind {
            ExprKind::Assign { target, value } => self.infer_assign(target, value),
            ExprKind::CompoundAssign { target, op, value } => {
                self.infer_compound_assign(target, *op, value)
            }
            ExprKind::PreIncrement { target }
            | ExprKind::PostIncrement { target }
            | ExprKind::PreDecrement { target }
            | ExprKind::PostDecrement { target } => self.infer_increment_decrement(target),
            _ => bail!("Unexpected assignment expression"),
        }
    }
    /// Extract remaining expressions (complexity ~8)
    fn infer_remaining_expr(&mut self, expr: &Expr) -> Result<MonoType> {
        match &expr.kind {
            ExprKind::Let {
                name,
                value,
                body,
                is_mutable,
                ..
            } => self.infer_let(name, value, body, *is_mutable),
            ExprKind::Block(exprs) => self.infer_block(exprs),
            ExprKind::Range { start, end, .. } => self.infer_range(start, end),
            ExprKind::Pipeline { expr, stages } => self.infer_pipeline(expr, stages),
            ExprKind::Module { body, .. } => self.infer_expr(body),
            ExprKind::DataFrame { columns } => self.infer_dataframe(columns),
            ExprKind::Command { .. } => Ok(MonoType::String),
            ExprKind::Macro { name, args } => self.infer_macro(name, args),
            ExprKind::DataFrameOperation { source, operation } => {
                self.infer_dataframe_operation(source, operation)
            }
            _ => bail!("Unknown expression type in inference"),
        }
    }
    /// Helper methods for complex expression groups
    fn infer_string_interpolation(
        &mut self,
        parts: &[crate::frontend::ast::StringPart],
    ) -> Result<MonoType> {
        for part in parts {
            if let crate::frontend::ast::StringPart::Expr(expr) = part {
                let _ = self.infer_expr(expr)?;
            }
        }
        Ok(MonoType::Named("String".to_string()))
    }
    fn infer_result_ok(&mut self, value: &Expr) -> Result<MonoType> {
        let value_type = self.infer_expr(value)?;
        let error_type = MonoType::Var(self.gen.fresh());
        Ok(MonoType::Result(Box::new(value_type), Box::new(error_type)))
    }
    fn infer_result_err(&mut self, error: &Expr) -> Result<MonoType> {
        let error_type = self.infer_expr(error)?;
        let value_type = MonoType::Var(self.gen.fresh());
        Ok(MonoType::Result(Box::new(value_type), Box::new(error_type)))
    }
    fn infer_object_literal(
        &mut self,
        fields: &[crate::frontend::ast::ObjectField],
    ) -> Result<MonoType> {
        for field in fields {
            match field {
                crate::frontend::ast::ObjectField::KeyValue { value, .. } => {
                    let _ = self.infer_expr(value)?;
                }
                crate::frontend::ast::ObjectField::Spread { expr } => {
                    let _ = self.infer_expr(expr)?;
                }
            }
        }
        Ok(MonoType::Named("Object".to_string()))
    }
    fn infer_field_access(&mut self, object: &Expr) -> Result<MonoType> {
        let _object_ty = self.infer_expr(object)?;
        Ok(MonoType::Var(self.gen.fresh()))
    }
    fn infer_index_access(&mut self, object: &Expr, index: &Expr) -> Result<MonoType> {
        let object_ty = self.infer_expr(object)?;
        let index_ty = self.infer_expr(index)?;
        // Check if the index is a range (which results in slicing)
        if let MonoType::List(inner_ty) = &index_ty {
            if matches!(**inner_ty, MonoType::Int) {
                // This is a range (List of integers), so return the same collection type
                return Ok(object_ty);
            }
        }
        // Regular integer indexing - return the element type
        match object_ty {
            MonoType::List(element_ty) => {
                // Ensure index is an integer
                self.unifier.unify(&index_ty, &MonoType::Int)?;
                Ok(*element_ty)
            }
            MonoType::String => {
                // Ensure index is an integer
                self.unifier.unify(&index_ty, &MonoType::Int)?;
                Ok(MonoType::String)
            }
            _ => Ok(MonoType::Var(self.gen.fresh())),
        }
    }
    fn infer_slice(&mut self, object: &Expr) -> Result<MonoType> {
        let object_ty = self.infer_expr(object)?;
        // Slicing returns the same type as the original collection
        // (a slice of a list is still a list, a slice of a string is still a string)
        Ok(object_ty)
    }
    fn infer_send(&mut self, actor: &Expr, message: &Expr) -> Result<MonoType> {
        let _actor_ty = self.infer_expr(actor)?;
        let _message_ty = self.infer_expr(message)?;
        Ok(MonoType::Unit)
    }
    fn infer_ask(
        &mut self,
        actor: &Expr,
        message: &Expr,
        timeout: Option<&Expr>,
    ) -> Result<MonoType> {
        let _actor_ty = self.infer_expr(actor)?;
        let _message_ty = self.infer_expr(message)?;
        if let Some(t) = timeout {
            let timeout_ty = self.infer_expr(t)?;
            self.unifier.unify(&timeout_ty, &MonoType::Int)?;
        }
        Ok(MonoType::Var(self.gen.fresh()))
    }
    fn infer_dataframe(
        &mut self,
        columns: &[crate::frontend::ast::DataFrameColumn],
    ) -> Result<MonoType> {
        let mut column_types = Vec::new();
        for col in columns {
            // Infer the type of the first value to determine column type
            let col_type = if col.values.is_empty() {
                MonoType::Var(self.gen.fresh())
            } else {
                let first_ty = self.infer_expr(&col.values[0])?;
                // Verify all values in the column have the same type
                for value in &col.values[1..] {
                    let value_ty = self.infer_expr(value)?;
                    self.unifier.unify(&first_ty, &value_ty)?;
                }
                first_ty
            };
            column_types.push((col.name.clone(), col_type));
        }
        Ok(MonoType::DataFrame(column_types))
    }
    fn infer_dataframe_operation(
        &mut self,
        source: &Expr,
        operation: &crate::frontend::ast::DataFrameOp,
    ) -> Result<MonoType> {
        use crate::frontend::ast::DataFrameOp;
        let source_ty = self.infer_expr(source)?;
        // Ensure source is a DataFrame
        match &source_ty {
            MonoType::DataFrame(columns) => {
                match operation {
                    DataFrameOp::Filter(_) => {
                        // Filter preserves the DataFrame structure
                        Ok(source_ty.clone())
                    }
                    DataFrameOp::Select(selected_cols) => {
                        // Select creates a new DataFrame with only the selected columns
                        let mut new_columns = Vec::new();
                        for col_name in selected_cols {
                            if let Some((_, ty)) = columns.iter().find(|(name, _)| name == col_name)
                            {
                                new_columns.push((col_name.clone(), ty.clone()));
                            }
                        }
                        Ok(MonoType::DataFrame(new_columns))
                    }
                    DataFrameOp::GroupBy(_) => {
                        // GroupBy returns a grouped DataFrame (for now, same type)
                        Ok(source_ty.clone())
                    }
                    DataFrameOp::Aggregate(_) => {
                        // Aggregation returns a DataFrame with aggregated values
                        Ok(source_ty.clone())
                    }
                    DataFrameOp::Join { .. } => {
                        // Join returns a DataFrame (simplified for now)
                        Ok(source_ty.clone())
                    }
                    DataFrameOp::Sort { .. } => {
                        // Sort preserves the DataFrame structure
                        Ok(source_ty.clone())
                    }
                    DataFrameOp::Limit(_) | DataFrameOp::Head(_) | DataFrameOp::Tail(_) => {
                        // These operations preserve the DataFrame structure
                        Ok(source_ty.clone())
                    }
                }
            }
            MonoType::Named(name) if name == "DataFrame" => {
                // Fallback for untyped DataFrames
                Ok(MonoType::Named("DataFrame".to_string()))
            }
            _ => bail!("DataFrame operation on non-DataFrame type: {source_ty}"),
        }
    }
    fn infer_async_block(&mut self, body: &Expr) -> Result<MonoType> {
        // Infer the body type
        let body_ty = self.infer_expr(body)?;
        // Async blocks return Future<Output = body_type>
        Ok(MonoType::Named(format!("Future<{body_ty}>")))
    }
}
impl Default for InferenceContext {
    fn default() -> Self {
        Self::new()
    }
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[allow(clippy::panic)]
#[path = "infer_core_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "infer_prop_tests.rs"]
mod property_tests_infer;

#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[path = "infer_coverage_tests.rs"]
mod coverage_tests;