ruchy 4.2.0

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
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
//! Pattern matching and destructuring parsing
//!
//! Handles parsing of all pattern constructs in Ruchy:
//! - Identifier patterns: `x`, `_`
//! - Tuple patterns: `(a, b, c)`
//! - List patterns: `[first, ...rest]`
//! - Struct patterns: `Point { x, y }`
//! - Variant patterns: `Some(x)`, `Ok(val)`, `Err(e)`
//! - Or patterns: `Some(x) | None`
//! - Literal patterns: `42`, `"hello"`, `true`
//! - Range patterns: `1..10`, `1..=100`
//!
//! # Examples
//! ```ruchy
//! // Tuple destructuring
//! let (x, y, z) = (1, 2, 3)
//!
//! // List destructuring with rest
//! let [first, ...rest] = [1, 2, 3, 4]
//!
//! // Struct destructuring
//! let Point { x, y } = point
//!
//! // Variant patterns in match
//! match result {
//!     Ok(value) => handle(value),
//!     Err(e) => log(e)
//! }
//!
//! // Or patterns
//! match value {
//!     Some(x) | None => process(x)
//! }
//! ```
//!
//! This is the largest extraction from expressions.rs (1,130+ lines),
//! representing Phase 17 of the modularization effort.

use crate::frontend::ast::{Expr, ExprKind, Literal, MatchArm, Pattern, Span, Type};
use crate::frontend::lexer::Token;
use crate::frontend::parser::{bail, parse_expr_recursive, utils, ParserState, Result};

fn parse_variant_pattern_with_name(
    state: &mut ParserState,
    variant_name: String,
) -> Result<Pattern> {
    // At this point, we've consumed the variant name and peeked '('
    state.tokens.expect(&Token::LeftParen)?;

    // Parse patterns (could be single or multiple comma-separated)
    let mut patterns = vec![];

    // Parse first pattern
    if !matches!(state.tokens.peek(), Some((Token::RightParen, _))) {
        patterns.push(parse_single_pattern(state)?);

        // Parse additional patterns separated by commas
        while matches!(state.tokens.peek(), Some((Token::Comma, _))) {
            state.tokens.advance(); // consume comma

            // Check for trailing comma
            if matches!(state.tokens.peek(), Some((Token::RightParen, _))) {
                break;
            }

            patterns.push(parse_single_pattern(state)?);
        }
    }

    state.tokens.expect(&Token::RightParen)?;

    // Try to create special pattern for common variants
    create_pattern_for_variant(variant_name, patterns)
}

/// Create pattern for variant (special cases for Some/Ok/Err, otherwise `TupleVariant`)
fn create_pattern_for_variant(variant_name: String, patterns: Vec<Pattern>) -> Result<Pattern> {
    // Special case for common Option/Result variants (single element)
    if patterns.len() == 1 {
        match variant_name.as_str() {
            "Some" => {
                return Ok(Pattern::Some(Box::new(
                    patterns
                        .into_iter()
                        .next()
                        .expect("patterns.len() == 1 so next() must return Some"),
                )))
            }
            "Ok" => {
                return Ok(Pattern::Ok(Box::new(
                    patterns
                        .into_iter()
                        .next()
                        .expect("patterns.len() == 1 so next() must return Some"),
                )))
            }
            "Err" => {
                return Ok(Pattern::Err(Box::new(
                    patterns
                        .into_iter()
                        .next()
                        .expect("patterns.len() == 1 so next() must return Some"),
                )))
            }
            _ => {}
        }
    }

    // For other variants or multiple elements, use TupleVariant
    Ok(Pattern::TupleVariant {
        path: vec![variant_name],
        patterns,
    })
}

/// Parse pattern for let statement (identifier or destructuring)
/// Extracted from `parse_let_statement` to reduce complexity
pub(in crate::frontend::parser) fn parse_let_pattern(
    state: &mut ParserState,
    is_mutable: bool,
) -> Result<Pattern> {
    match state.tokens.peek() {
        // Handle Option::Some pattern
        Some((Token::Some, _)) => {
            state.tokens.advance();
            if matches!(state.tokens.peek(), Some((Token::LeftParen, _))) {
                parse_variant_pattern_with_name(state, "Some".to_string())
            } else {
                bail!("Some must be followed by parentheses in patterns: Some(value)")
            }
        }
        // Handle Result::Ok pattern
        Some((Token::Ok, _)) => {
            state.tokens.advance();
            if matches!(state.tokens.peek(), Some((Token::LeftParen, _))) {
                parse_variant_pattern_with_name(state, "Ok".to_string())
            } else {
                bail!("Ok must be followed by parentheses in patterns: Ok(value)")
            }
        }
        // Handle Result::Err pattern
        Some((Token::Err, _)) => {
            state.tokens.advance();
            if matches!(state.tokens.peek(), Some((Token::LeftParen, _))) {
                parse_variant_pattern_with_name(state, "Err".to_string())
            } else {
                bail!("Err must be followed by parentheses in patterns: Err(value)")
            }
        }
        // Handle Option::None pattern
        Some((Token::None, _)) => {
            state.tokens.advance();
            Ok(Pattern::None)
        }
        Some((Token::Identifier(name), _)) => {
            let name = name.clone();
            state.tokens.advance();

            // Check if this is a variant pattern with custom variants
            if matches!(state.tokens.peek(), Some((Token::LeftParen, _))) {
                // Parse enum variant pattern with tuple destructuring
                parse_variant_pattern_with_name(state, name)
            }
            // Check if this is a struct pattern: Name { ... }
            else if matches!(state.tokens.peek(), Some((Token::LeftBrace, _))) {
                parse_struct_pattern_with_name(state, name)
            } else {
                Ok(Pattern::Identifier(name))
            }
        }
        Some((Token::DataFrame, _)) => {
            // Allow 'df' as a variable name (common in data science)
            state.tokens.advance();
            Ok(Pattern::Identifier("df".to_string()))
        }
        Some((Token::Default, _)) => {
            // Allow 'default' as a variable name (common in configurations)
            state.tokens.advance();
            Ok(Pattern::Identifier("default".to_string()))
        }
        Some((Token::Final, _)) => {
            // Allow 'final' as a variable name (Rust keyword, needs r# prefix in transpiler)
            state.tokens.advance();
            Ok(Pattern::Identifier("final".to_string()))
        }
        Some((Token::Underscore, _)) => {
            // Allow wildcard pattern
            state.tokens.advance();
            Ok(Pattern::Identifier("_".to_string()))
        }
        Some((Token::LeftParen, _)) => {
            // Parse tuple destructuring: (x, y) = (1, 2)
            parse_tuple_pattern(state)
        }
        Some((Token::LeftBracket, _)) => {
            // Parse list destructuring: [a, b] = [1, 2]
            parse_list_pattern(state)
        }
        Some((Token::LeftBrace, _)) => {
            // Parse struct destructuring: {name, age} = obj
            parse_struct_pattern(state)
        }
        _ => bail!(
            "Expected identifier or pattern after 'let{}'",
            if is_mutable { " mut" } else { "" }
        ),
    }
}
/// Parse optional type annotation for let statement
/// Extracted from `parse_let_statement` to reduce complexity
fn parse_let_type_annotation(state: &mut ParserState) -> Result<Option<Type>> {
    if matches!(state.tokens.peek(), Some((Token::Colon, _))) {
        state.tokens.advance(); // consume ':'
        Ok(Some(utils::parse_type(state)?))
    } else {
        Ok(None)
    }
}
/// Parse optional 'else' clause for let-else patterns
/// Extracted to reduce complexity
fn parse_let_else_clause(state: &mut ParserState) -> Result<Option<Box<Expr>>> {
    if matches!(state.tokens.peek(), Some((Token::Else, _))) {
        state.tokens.advance(); // consume 'else'
                                // Must be followed by a block (diverging expression)
        if !matches!(state.tokens.peek(), Some((Token::LeftBrace, _))) {
            bail!("let-else requires a block after 'else'");
        }
        let block = parse_expr_recursive(state)?;
        Ok(Some(Box::new(block)))
    } else {
        Ok(None)
    }
}

/// Parse optional 'in' clause for let expressions
/// Extracted from `parse_let_statement` to reduce complexity
fn parse_let_in_clause(state: &mut ParserState, value_span: Span) -> Result<Box<Expr>> {
    if matches!(state.tokens.peek(), Some((Token::In, _))) {
        state.tokens.advance(); // consume 'in'
        Ok(Box::new(parse_expr_recursive(state)?))
    } else {
        // For let statements (no 'in'), body is unit
        Ok(Box::new(Expr::new(
            ExprKind::Literal(Literal::Unit),
            value_span,
        )))
    }
}
/// Create the appropriate let expression based on pattern type
/// Extracted from `parse_let_statement` to reduce complexity
fn create_let_expression(
    pattern: Pattern,
    type_annotation: Option<Type>,
    value: Box<Expr>,
    body: Box<Expr>,
    is_mutable: bool,
    else_block: Option<Box<Expr>>,
    start_span: Span,
) -> Result<Expr> {
    let end_span = body.span;
    match &pattern {
        Pattern::Identifier(name) => Ok(Expr::new(
            ExprKind::Let {
                name: name.clone(),
                type_annotation,
                value,
                body,
                is_mutable,
                else_block,
            },
            start_span.merge(end_span),
        )),
        Pattern::Tuple(_) | Pattern::List(_) => {
            // For destructuring patterns, use LetPattern variant
            Ok(Expr::new(
                ExprKind::LetPattern {
                    pattern,
                    type_annotation,
                    value,
                    body,
                    is_mutable,
                    else_block,
                },
                start_span.merge(end_span),
            ))
        }
        Pattern::Wildcard
        | Pattern::Literal(_)
        | Pattern::QualifiedName(_)
        | Pattern::Struct { .. }
        | Pattern::TupleVariant { .. }
        | Pattern::Range { .. }
        | Pattern::Or(_)
        | Pattern::Rest
        | Pattern::RestNamed(_)
        | Pattern::AtBinding { .. }
        | Pattern::WithDefault { .. }
        | Pattern::Ok(_)
        | Pattern::Err(_)
        | Pattern::Some(_)
        | Pattern::None
        | Pattern::Mut(_) => {
            // For other pattern types, use LetPattern variant
            Ok(Expr::new(
                ExprKind::LetPattern {
                    pattern,
                    type_annotation,
                    value,
                    body,
                    is_mutable,
                    else_block,
                },
                start_span.merge(end_span),
            ))
        }
    }
}
// Var statement parsing moved to expressions_helpers/variable_declarations.rs module
pub(in crate::frontend::parser) fn parse_var_statement(state: &mut ParserState) -> Result<Expr> {
    super::variable_declarations::parse_var_statement(state)
}

/// Extract method: Parse variable pattern - complexity: 6
pub(in crate::frontend::parser) fn parse_var_pattern(state: &mut ParserState) -> Result<Pattern> {
    match state.tokens.peek() {
        Some((Token::Identifier(name), _)) => {
            let name = name.clone();
            state.tokens.advance();
            Ok(Pattern::Identifier(name))
        }
        Some((Token::DataFrame, _)) => {
            // Allow 'df' as a variable name (common in data science)
            state.tokens.advance();
            Ok(Pattern::Identifier("df".to_string()))
        }
        Some((Token::Underscore, _)) => {
            // Allow wildcard pattern in var statements too
            state.tokens.advance();
            Ok(Pattern::Identifier("_".to_string()))
        }
        Some((Token::LeftParen, _)) => parse_tuple_pattern(state),
        Some((Token::LeftBracket, _)) => parse_list_pattern(state),
        _ => bail!("Expected identifier or pattern after 'var'"),
    }
}

/// Extract method: Parse optional type annotation - complexity: 4
fn parse_optional_type_annotation(
    state: &mut ParserState,
) -> Result<Option<crate::frontend::ast::Type>> {
    if matches!(state.tokens.peek(), Some((Token::Colon, _))) {
        state.tokens.advance();
        Ok(Some(utils::parse_type(state)?))
    } else {
        Ok(None)
    }
}

/// Extract method: Create variable expression - complexity: 6
fn create_var_expression(
    pattern: Pattern,
    type_annotation: Option<crate::frontend::ast::Type>,
    value: Box<Expr>,
    start_span: Span,
) -> Result<Expr> {
    let body = Box::new(Expr::new(ExprKind::Literal(Literal::Unit), value.span));
    let end_span = value.span;
    let is_mutable = true;

    match &pattern {
        Pattern::Identifier(name) => Ok(Expr::new(
            ExprKind::Let {
                name: name.clone(),
                type_annotation,
                value,
                body,
                is_mutable,
                else_block: None, // var doesn't support let-else
            },
            start_span.merge(end_span),
        )),
        _ => Ok(Expr::new(
            ExprKind::LetPattern {
                pattern,
                type_annotation,
                value,
                body,
                is_mutable,
                else_block: None, // var doesn't support let-else
            },
            start_span.merge(end_span),
        )),
    }
}
pub(in crate::frontend::parser) fn parse_tuple_pattern(state: &mut ParserState) -> Result<Pattern> {
    state.tokens.expect(&Token::LeftParen)?;
    let mut patterns = Vec::new();
    while !matches!(state.tokens.peek(), Some((Token::RightParen, _))) {
        let pattern = parse_single_tuple_pattern_element(state)?;
        patterns.push(pattern);
        // Use shared separator handler
        if !handle_pattern_separator(state, Token::RightParen)? {
            break;
        }
    }
    state.tokens.expect(&Token::RightParen)?;
    Ok(Pattern::Tuple(patterns))
}
/// Parse a single element in a tuple pattern
/// Extracted to reduce complexity of `parse_tuple_pattern`
/// Complexity: 7 (within Toyota Way limits)
fn parse_single_tuple_pattern_element(state: &mut ParserState) -> Result<Pattern> {
    // Check for 'mut' modifier
    let is_mut = if matches!(state.tokens.peek(), Some((Token::Mut, _))) {
        state.tokens.advance(); // consume 'mut'
        true
    } else {
        false
    };

    // Parse the pattern element
    let pattern = match state.tokens.peek() {
        Some((Token::Identifier(name), _)) => {
            let name = name.clone();
            state.tokens.advance();
            Ok(Pattern::Identifier(name))
        }
        Some((Token::LeftParen, _)) => parse_tuple_pattern(state),
        Some((Token::LeftBracket, _)) => parse_list_pattern(state),
        Some((Token::LeftBrace, _)) => parse_struct_pattern(state),
        Some((Token::Underscore, _)) => {
            state.tokens.advance();
            Ok(Pattern::Wildcard)
        }
        _ => bail!("Expected identifier, tuple, list, struct, or wildcard in tuple pattern"),
    }?;

    // Wrap in Mut pattern if mut modifier was present
    if is_mut {
        Ok(Pattern::Mut(Box::new(pattern)))
    } else {
        Ok(pattern)
    }
}
pub(in crate::frontend::parser) fn parse_struct_pattern(
    state: &mut ParserState,
) -> Result<Pattern> {
    state.tokens.advance(); // consume '{'
    parse_struct_pattern_fields(state, String::new())
}

/// Parse struct pattern with a specific name: Point { x, y }
pub(in crate::frontend::parser) fn parse_struct_pattern_with_name(
    state: &mut ParserState,
    name: String,
) -> Result<Pattern> {
    state.tokens.advance(); // consume '{'
    parse_struct_pattern_fields(state, name)
}

/// Parse struct pattern fields (shared logic for both named and anonymous patterns)
fn parse_struct_pattern_fields(state: &mut ParserState, name: String) -> Result<Pattern> {
    let mut fields = Vec::new();
    let mut has_rest = false;

    while !matches!(state.tokens.peek(), Some((Token::RightBrace, _))) {
        if matches!(state.tokens.peek(), Some((Token::DotDot, _))) {
            has_rest = parse_struct_rest_pattern(state)?;
            break;
        }

        fields.push(parse_struct_field_pattern(state)?);

        if !handle_struct_field_separator(state)? {
            break;
        }
    }

    state.tokens.expect(&Token::RightBrace)?;

    Ok(Pattern::Struct {
        name,
        fields,
        has_rest,
    })
}

fn parse_struct_rest_pattern(state: &mut ParserState) -> Result<bool> {
    state.tokens.advance(); // consume '..'

    if matches!(state.tokens.peek(), Some((Token::Comma, _))) {
        state.tokens.advance();
    }

    if !matches!(state.tokens.peek(), Some((Token::RightBrace, _))) {
        bail!("Rest pattern (..) must be the last field in struct pattern");
    }

    Ok(true)
}

fn parse_struct_field_pattern(
    state: &mut ParserState,
) -> Result<crate::frontend::ast::StructPatternField> {
    // PARSER-XXX: Keywords can be used as field names in struct patterns
    let field_name = match state.tokens.peek() {
        Some((Token::Identifier(name), _)) => name.clone(),
        Some((Token::Type, _)) => "type".to_string(),
        Some((Token::Use, _)) => "use".to_string(),
        Some((Token::Mod, _)) => "mod".to_string(),
        Some((Token::Async, _)) => "async".to_string(),
        Some((Token::Await, _)) => "await".to_string(),
        Some((Token::Self_, _)) => "self".to_string(),
        Some((Token::Super, _)) => "super".to_string(),
        Some((Token::Crate, _)) => "crate".to_string(),
        _ => bail!("Expected identifier or '..' in struct pattern"),
    };
    state.tokens.advance();

    let pattern = if matches!(state.tokens.peek(), Some((Token::Colon, _))) {
        state.tokens.advance();
        Some(parse_match_pattern(state)?)
    } else {
        None
    };

    Ok(crate::frontend::ast::StructPatternField {
        name: field_name,
        pattern,
    })
}

fn handle_struct_field_separator(state: &mut ParserState) -> Result<bool> {
    if matches!(state.tokens.peek(), Some((Token::Comma, _))) {
        state.tokens.advance();
        // Trailing comma before closing brace is ok
        Ok(!matches!(state.tokens.peek(), Some((Token::RightBrace, _))))
    } else if matches!(state.tokens.peek(), Some((Token::RightBrace, _))) {
        Ok(false)
    } else {
        bail!("Expected comma or closing brace after struct pattern field")
    }
}
pub(in crate::frontend::parser) fn parse_list_pattern(state: &mut ParserState) -> Result<Pattern> {
    state.tokens.expect(&Token::LeftBracket)?;
    let mut patterns = Vec::new();
    while !matches!(state.tokens.peek(), Some((Token::RightBracket, _))) {
        let pattern = parse_single_list_pattern_element(state)?;
        patterns.push(pattern);
        // Handle comma separator
        if !handle_pattern_separator(state, Token::RightBracket)? {
            break;
        }
    }
    state.tokens.expect(&Token::RightBracket)?;
    Ok(Pattern::List(patterns))
}
/// Parse a single element in a list pattern
/// Extracted to reduce complexity of `parse_list_pattern`
/// PARSER-XXX: Support both ..rest (two dots) and ...rest (three dots) syntax
fn parse_single_list_pattern_element(state: &mut ParserState) -> Result<Pattern> {
    match state.tokens.peek() {
        Some((Token::Identifier(name), _)) => {
            let name = name.clone();
            parse_identifier_pattern_with_default(state, name)
        }
        Some((Token::DotDot, _)) => parse_list_rest_pattern(state),
        Some((Token::DotDotDot, _)) => parse_rest_pattern(state),
        Some((Token::LeftParen, _)) => parse_tuple_pattern(state),
        Some((Token::LeftBracket, _)) => parse_list_pattern(state),
        Some((Token::Underscore, _)) => {
            state.tokens.advance();
            Ok(Pattern::Wildcard)
        }
        _ => bail!("Expected identifier, tuple, list, wildcard, or rest pattern in list pattern"),
    }
}
/// Parse identifier pattern with optional default value
/// Extracted to reduce complexity
fn parse_identifier_pattern_with_default(state: &mut ParserState, name: String) -> Result<Pattern> {
    state.tokens.advance();
    // Check for default value: identifier = expr
    if matches!(state.tokens.peek(), Some((Token::Equal, _))) {
        state.tokens.advance(); // consume '='
        let default_expr = parse_expr_recursive(state)?;
        Ok(Pattern::WithDefault {
            pattern: Box::new(Pattern::Identifier(name)),
            default: Box::new(default_expr),
        })
    } else {
        Ok(Pattern::Identifier(name))
    }
}
/// Parse rest pattern (...rest or ...)
/// Extracted to reduce complexity
fn parse_rest_pattern(state: &mut ParserState) -> Result<Pattern> {
    state.tokens.advance(); // consume ...
                            // Check if named rest pattern
    if let Some((Token::Identifier(name), _)) = state.tokens.peek() {
        let name = name.clone();
        state.tokens.advance();
        Ok(Pattern::RestNamed(name))
    } else {
        Ok(Pattern::Rest)
    }
}
/// Handle pattern separator (comma) and check for trailing comma
/// Returns true if should continue parsing, false if should stop
/// Extracted to reduce complexity and share with tuple pattern
fn handle_pattern_separator(state: &mut ParserState, end_token: Token) -> Result<bool> {
    if matches!(state.tokens.peek(), Some((Token::Comma, _))) {
        state.tokens.advance();
        // Check for trailing comma
        if let Some((token, _)) = state.tokens.peek() {
            if *token == end_token {
                return Ok(false);
            }
        }
        Ok(true)
    } else if let Some((token, _)) = state.tokens.peek() {
        if *token != end_token {
            let expected = match end_token {
                Token::RightBracket => "',' or ']'",
                Token::RightParen => "',' or ')'",
                _ => "',' or closing delimiter",
            };
            bail!("Expected {expected} in pattern");
        }
        Ok(false)
    } else {
        bail!("Unexpected end of input in pattern")
    }
}
/// Parse if expression: if condition { `then_branch` } [else { `else_branch` }]
/// Also handles if-let: if let pattern = expr { `then_branch` } [else { `else_branch` }]
/// Complexity: <10 (split into helper functions)
pub(in crate::frontend::parser) fn parse_if_expression(state: &mut ParserState) -> Result<Expr> {
    let start_span = state.tokens.expect(&Token::If)?;
    // Check for if-let syntax
    if matches!(state.tokens.peek(), Some((Token::Let, _))) {
        parse_if_let_expression(state, start_span)
    } else {
        parse_regular_if_expression(state, start_span)
    }
}
/// Parse if-let expression: if let pattern = expr { then } [else { else }]
/// Complexity: <10
fn parse_if_let_expression(state: &mut ParserState, start_span: Span) -> Result<Expr> {
    state.tokens.advance(); // consume 'let'
                            // Parse the pattern
    let pattern = parse_match_pattern(state)
        .map_err(|e| anyhow::anyhow!("Expected pattern after 'if let': {e}"))?;
    // Expect '='
    state
        .tokens
        .expect(&Token::Equal)
        .map_err(|e| anyhow::anyhow!("Expected '=' after pattern in if-let: {e}"))?;
    // Parse the expression to match against
    let expr = Box::new(
        parse_expr_recursive(state)
            .map_err(|e| anyhow::anyhow!("Expected expression after '=' in if-let: {e}"))?,
    );
    // Parse then branch
    let then_branch = Box::new(parse_expr_recursive(state).map_err(|e| {
        anyhow::anyhow!("Expected body after if-let condition, typically {{ ... }}: {e}")
    })?);
    // Parse optional else branch
    let else_branch = parse_else_branch(state)?;
    Ok(Expr::new(
        ExprKind::IfLet {
            pattern,
            expr,
            then_branch,
            else_branch,
        },
        start_span,
    ))
}
/// Parse regular if expression: if condition { then } [else { else }]
/// Complexity: <10
fn parse_regular_if_expression(state: &mut ParserState, start_span: Span) -> Result<Expr> {
    // Parse condition with better error context
    let condition = Box::new(
        parse_expr_recursive(state)
            .map_err(|e| anyhow::anyhow!("Expected condition after 'if': {e}"))?,
    );
    // Parse then branch (expect block) with better error context
    let then_branch = Box::new(parse_expr_recursive(state).map_err(|e| {
        anyhow::anyhow!("Expected body after if condition, typically {{ ... }}: {e}")
    })?);
    // Parse optional else branch
    let else_branch = parse_else_branch(state)?;
    Ok(Expr::new(
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        },
        start_span,
    ))
}
/// Parse else branch for if/if-let expressions
/// Complexity: <10
fn parse_else_branch(state: &mut ParserState) -> Result<Option<Box<Expr>>> {
    if matches!(state.tokens.peek(), Some((Token::Else, _))) {
        state.tokens.advance(); // consume 'else'
                                // Check for else-if or else-if-let
        if matches!(state.tokens.peek(), Some((Token::If, _))) {
            // Let the recursive call handle else-if or else-if-let
            Ok(Some(Box::new(parse_if_expression(state)?)))
        } else {
            Ok(Some(Box::new(parse_expr_recursive(state).map_err(
                |e| anyhow::anyhow!("Expected body after 'else', typically {{ ... }}: {e}"),
            )?)))
        }
    } else {
        Ok(None)
    }
}
/// Parse match expression: match expr { pattern => result, ... }
/// Complexity target: <10 (using helper functions for TDG compliance)
pub(in crate::frontend::parser) fn parse_match_expression(state: &mut ParserState) -> Result<Expr> {
    let start_span = state.tokens.expect(&Token::Match)?;
    // Parse the expression to match on
    let expr = Box::new(
        parse_expr_recursive(state)
            .map_err(|e| anyhow::anyhow!("Expected expression after 'match': {e}"))?,
    );
    // Expect opening brace for match arms
    state
        .tokens
        .expect(&Token::LeftBrace)
        .map_err(|_| anyhow::anyhow!("Expected '{{' after match expression"))?;
    // Parse match arms
    let arms = parse_match_arms(state)?;
    // Expect closing brace
    state
        .tokens
        .expect(&Token::RightBrace)
        .map_err(|_| anyhow::anyhow!("Expected '}}' after match arms"))?;
    Ok(Expr::new(ExprKind::Match { expr, arms }, start_span))
}
/// Parse match arms with low complexity (helper function for TDG compliance)
fn parse_match_arms(state: &mut ParserState) -> Result<Vec<MatchArm>> {
    let mut arms = Vec::new();
    while !matches!(state.tokens.peek(), Some((Token::RightBrace, _)) | None) {
        // Parse single arm
        let arm = parse_single_match_arm(state)?;
        arms.push(arm);
        // Optional comma
        if matches!(state.tokens.peek(), Some((Token::Comma, _))) {
            state.tokens.advance();
        }
        // Check if we're done
        if matches!(state.tokens.peek(), Some((Token::RightBrace, _))) {
            break;
        }
    }
    if arms.is_empty() {
        bail!("Match expression must have at least one arm");
    }
    Ok(arms)
}
/// Parse guard expression in match arms
/// PARSER-071: Specialized parser that stops at `=>` and `->` to avoid treating them as lambda syntax
/// Complexity: 3 (simple delegation with context management)
fn parse_guard_expression(state: &mut ParserState) -> Result<Expr> {
    // Set guard context flag to prevent `=>` and `->` from being treated as lambda syntax
    let old_context = state.in_guard_context;
    state.in_guard_context = true;

    // Parse expression using standard parser
    let expr = parse_expr_recursive(state);

    // Restore previous context
    state.in_guard_context = old_context;

    // Return result (may be error)
    let expr = expr?;

    // Verify we stopped at a valid match arm delimiter
    if !matches!(
        state.tokens.peek(),
        Some((Token::FatArrow | Token::Arrow, _))
    ) {
        bail!("Guard expression did not stop at match arm delimiter => or ->");
    }

    Ok(expr)
}

/// Parse a single match arm: pattern [if guard] => expr
/// Complexity: <5 (simple sequential parsing)
fn parse_single_match_arm(state: &mut ParserState) -> Result<MatchArm> {
    let start_span = state.tokens.peek().map(|(_, s)| *s).unwrap_or_default();
    // Parse pattern
    let pattern = parse_match_pattern(state)?;
    // Parse optional guard (if condition)
    // PARSER-071: Use specialized guard parser to avoid treating `=>` as lambda arrow
    let guard = if matches!(state.tokens.peek(), Some((Token::If, _))) {
        state.tokens.advance(); // consume 'if'
        Some(Box::new(parse_guard_expression(state)?))
    } else {
        None
    };
    // PARSER-053: Support both => and -> in match arms for user convenience
    // Accept either Token::FatArrow (=>) or Token::Arrow (->)
    if !matches!(
        state.tokens.peek(),
        Some((Token::FatArrow | Token::Arrow, _))
    ) {
        bail!("Expected '=>' or '->' in match arm");
    }
    state.tokens.advance();
    // Parse result expression
    let body = Box::new(parse_expr_recursive(state)?);
    let end_span = body.span;
    Ok(MatchArm {
        pattern,
        guard,
        body,
        span: start_span.merge(end_span),
    })
}
/// Parse match pattern with low complexity
/// Complexity: <5 (simple pattern matching)
pub(in crate::frontend::parser) fn parse_match_pattern(state: &mut ParserState) -> Result<Pattern> {
    if state.tokens.peek().is_none() {
        bail!("Expected pattern in match arm");
    }
    // Delegate to focused helper functions
    let pattern = parse_single_pattern(state)?;
    // Handle multiple patterns with | (or)
    if matches!(state.tokens.peek(), Some((Token::Pipe, _))) {
        parse_or_pattern(state, pattern)
    } else {
        Ok(pattern)
    }
}
/// Parse a single pattern (delegates to specific pattern parsers)
/// Complexity: <8
pub(in crate::frontend::parser) fn parse_single_pattern(
    state: &mut ParserState,
) -> Result<Pattern> {
    let Some((token, _span)) = state.tokens.peek() else {
        bail!("Expected pattern");
    };
    match token {
        Token::Underscore => parse_wildcard_pattern(state),
        Token::Integer(_)
        | Token::Float(_)
        | Token::String(_)
        | Token::RawString(_)
        | Token::Char(_)
        | Token::Bool(_)
        | Token::Atom(_) => parse_literal_pattern(state),
        Token::Some | Token::None => parse_option_pattern(state),
        Token::Ok | Token::Err => parse_result_pattern(state),
        Token::Identifier(_) | Token::Result | Token::Var => {
            parse_identifier_or_constructor_pattern(state)
        }
        Token::LeftParen => parse_match_tuple_pattern(state),
        Token::LeftBracket => parse_match_list_pattern(state),
        Token::LeftBrace => parse_struct_pattern(state),
        _ => bail!("Unexpected token in pattern: {token:?}"),
    }
}
/// Parse wildcard pattern: _
/// Complexity: 1
fn parse_wildcard_pattern(state: &mut ParserState) -> Result<Pattern> {
    state.tokens.advance();
    Ok(Pattern::Wildcard)
}
/// Parse literal patterns: integers, floats, strings, chars, booleans
/// Complexity: <5
fn parse_literal_pattern(state: &mut ParserState) -> Result<Pattern> {
    let Some((token, _span)) = state.tokens.peek() else {
        bail!("Expected literal pattern");
    };
    let token = token.clone(); // Clone to avoid borrow issues
    let pattern = match token {
        Token::Integer(val) => parse_integer_literal_pattern(state, val)?,
        Token::Float(val) => parse_simple_literal_pattern(state, Literal::Float(val))?,
        Token::String(s) => parse_simple_literal_pattern(state, Literal::String(s))?,
        Token::RawString(s) => parse_simple_literal_pattern(state, Literal::String(s))?,
        Token::Char(c) => parse_char_literal_pattern(state, c)?,
        Token::Byte(b) => parse_simple_literal_pattern(state, Literal::Byte(b))?,
        Token::Bool(b) => parse_simple_literal_pattern(state, Literal::Bool(b))?,
        Token::Atom(s) => parse_simple_literal_pattern(state, Literal::Atom(s))?,
        _ => bail!("Expected literal pattern, got: {token:?}"),
    };
    Ok(pattern)
}

/// Extract method: Parse integer literal with optional range pattern - complexity: 8
fn parse_integer_literal_pattern(state: &mut ParserState, val: String) -> Result<Pattern> {
    state.tokens.advance();
    // Parse the integer value from string (ignore type suffix for pattern matching)
    let (num_part, type_suffix) = if let Some(pos) = val.find(|c: char| c.is_alphabetic()) {
        (&val[..pos], Some(val[pos..].to_string()))
    } else {
        (val.as_str(), None)
    };
    let parsed_val = num_part
        .parse::<i64>()
        .map_err(|_| anyhow::anyhow!("Invalid integer literal: {num_part}"))?;

    // Check for range patterns: 1..5 or 1..=5
    match state.tokens.peek() {
        Some((Token::DotDot, _)) => parse_integer_range_pattern(state, parsed_val, false),
        Some((Token::DotDotEqual, _)) => parse_integer_range_pattern(state, parsed_val, true),
        _ => Ok(Pattern::Literal(Literal::Integer(parsed_val, type_suffix))),
    }
}

/// Extract method: Parse integer range pattern - complexity: 6
fn parse_integer_range_pattern(
    state: &mut ParserState,
    start_val: i64,
    inclusive: bool,
) -> Result<Pattern> {
    state.tokens.advance(); // consume '..' or '..='
    if let Some((Token::Integer(end_val_str), _)) = state.tokens.peek() {
        let end_val_str = end_val_str.clone();
        state.tokens.advance();
        // Parse the end value
        let (num_part, _type_suffix) =
            if let Some(pos) = end_val_str.find(|c: char| c.is_alphabetic()) {
                (&end_val_str[..pos], Some(end_val_str[pos..].to_string()))
            } else {
                (end_val_str.as_str(), None)
            };
        let end_val = num_part
            .parse::<i64>()
            .map_err(|_| anyhow::anyhow!("Invalid integer literal: {num_part}"))?;
        Ok(Pattern::Range {
            start: Box::new(Pattern::Literal(Literal::Integer(start_val, None))),
            end: Box::new(Pattern::Literal(Literal::Integer(end_val, None))),
            inclusive,
        })
    } else {
        bail!("Expected integer after range operator");
    }
}

/// Extract method: Parse char literal with optional range pattern - complexity: 8
fn parse_char_literal_pattern(state: &mut ParserState, val: char) -> Result<Pattern> {
    state.tokens.advance();
    // Check for range patterns: 'a'..'z' or 'a'..='z'
    match state.tokens.peek() {
        Some((Token::DotDot, _)) => parse_char_range_pattern(state, val, false),
        Some((Token::DotDotEqual, _)) => parse_char_range_pattern(state, val, true),
        _ => Ok(Pattern::Literal(Literal::Char(val))),
    }
}

/// Extract method: Parse char range pattern - complexity: 6
fn parse_char_range_pattern(
    state: &mut ParserState,
    start_val: char,
    inclusive: bool,
) -> Result<Pattern> {
    state.tokens.advance(); // consume '..' or '..='
    if let Some((Token::Char(end_val), _)) = state.tokens.peek() {
        let end_val = *end_val;
        state.tokens.advance();
        Ok(Pattern::Range {
            start: Box::new(Pattern::Literal(Literal::Char(start_val))),
            end: Box::new(Pattern::Literal(Literal::Char(end_val))),
            inclusive,
        })
    } else {
        bail!("Expected char after range operator");
    }
}

/// Extract method: Parse simple literal patterns - complexity: 2
fn parse_simple_literal_pattern(state: &mut ParserState, literal: Literal) -> Result<Pattern> {
    state.tokens.advance();
    Ok(Pattern::Literal(literal))
}
/// Parse Option patterns: Some, None
/// Complexity: <5
fn parse_option_pattern(state: &mut ParserState) -> Result<Pattern> {
    let Some((token, _span)) = state.tokens.peek() else {
        bail!("Expected Option pattern");
    };
    match token {
        Token::Some => {
            state.tokens.advance();
            if matches!(state.tokens.peek(), Some((Token::LeftParen, _))) {
                parse_constructor_pattern(state, "Some".to_string())
            } else {
                Ok(Pattern::Identifier("Some".to_string()))
            }
        }
        Token::None => {
            state.tokens.advance();
            if matches!(state.tokens.peek(), Some((Token::LeftParen, _))) {
                parse_constructor_pattern(state, "None".to_string())
            } else {
                Ok(Pattern::Identifier("None".to_string()))
            }
        }
        _ => bail!("Expected Some or None pattern"),
    }
}
/// Parse Result patterns (Ok/Err)
/// Complexity: 4
fn parse_result_pattern(state: &mut ParserState) -> Result<Pattern> {
    let Some((token, _span)) = state.tokens.peek() else {
        bail!("Expected Result pattern");
    };
    match token {
        Token::Ok => {
            state.tokens.advance();
            if matches!(state.tokens.peek(), Some((Token::LeftParen, _))) {
                parse_constructor_pattern(state, "Ok".to_string())
            } else {
                Ok(Pattern::Identifier("Ok".to_string()))
            }
        }
        Token::Err => {
            state.tokens.advance();
            if matches!(state.tokens.peek(), Some((Token::LeftParen, _))) {
                parse_constructor_pattern(state, "Err".to_string())
            } else {
                Ok(Pattern::Identifier("Err".to_string()))
            }
        }
        _ => bail!("Expected Ok or Err pattern"),
    }
}
/// Parse identifier or constructor patterns
/// Complexity: <5
fn parse_identifier_or_constructor_pattern(state: &mut ParserState) -> Result<Pattern> {
    // Handle Token::Identifier and reserved keywords that can be used as enum type names or variable names
    let name = match state.tokens.peek() {
        Some((Token::Identifier(n), _)) => n.clone(),
        Some((Token::Result, _)) => "Result".to_string(),
        Some((Token::Var, _)) => "var".to_string(),
        _ => bail!("Expected identifier pattern"),
    };
    state.tokens.advance();

    // Check for @ bindings: name @ pattern
    if matches!(state.tokens.peek(), Some((Token::At, _))) {
        state.tokens.advance();
        let inner_pattern = parse_single_pattern(state)?;
        return Ok(Pattern::AtBinding {
            name,
            pattern: Box::new(inner_pattern),
        });
    }

    // Check for enum variant paths: Color::Red, Option::Some, etc.
    if matches!(state.tokens.peek(), Some((Token::ColonColon, _))) {
        let full_path = super::identifiers::parse_module_path_segments(state, name)?;
        // Check if followed by struct fields or tuple args
        return if matches!(state.tokens.peek(), Some((Token::LeftBrace, _))) {
            parse_struct_pattern_with_name(state, full_path)
        } else if matches!(state.tokens.peek(), Some((Token::LeftParen, _))) {
            parse_constructor_pattern(state, full_path)
        } else {
            // Unit enum variant like Color::Red - use QualifiedName
            let path_segments: Vec<String> =
                full_path.split("::").map(ToString::to_string).collect();
            Ok(Pattern::QualifiedName(path_segments))
        };
    }

    // Check for struct patterns: Point { x, y }
    if matches!(state.tokens.peek(), Some((Token::LeftBrace, _))) {
        parse_struct_pattern_with_name(state, name)
    }
    // Check for enum-like patterns: Ok(x), Err(e), etc.
    else if matches!(state.tokens.peek(), Some((Token::LeftParen, _))) {
        parse_constructor_pattern(state, name)
    } else {
        Ok(Pattern::Identifier(name))
    }
}
/// Parse match tuple pattern: (a, b, c)
/// Complexity: <7
fn parse_match_tuple_pattern(state: &mut ParserState) -> Result<Pattern> {
    state.tokens.expect(&Token::LeftParen)?;
    // Check for empty tuple ()
    if matches!(state.tokens.peek(), Some((Token::RightParen, _))) {
        state.tokens.advance();
        return Ok(Pattern::Tuple(vec![]));
    }
    // Parse pattern elements
    let mut patterns = vec![parse_match_pattern(state)?];
    while matches!(state.tokens.peek(), Some((Token::Comma, _))) {
        state.tokens.advance(); // consume comma
        if matches!(state.tokens.peek(), Some((Token::RightParen, _))) {
            break; // trailing comma
        }
        patterns.push(parse_match_pattern(state)?);
    }
    state.tokens.expect(&Token::RightParen)?;
    Ok(Pattern::Tuple(patterns))
}
/// Parse list pattern in match: [], [a], [a, b], [head, ...tail]
/// Complexity: <8
/// Parse rest pattern in list with .. (two dots): .. or ..tail
/// DEFECT-029 FIX: Support anonymous rest pattern (..) without identifier
/// Complexity: 3 (Toyota Way: <10 ✓)
fn parse_list_rest_pattern(state: &mut ParserState) -> Result<Pattern> {
    state.tokens.advance(); // consume ..
    if let Some((Token::Identifier(name), _)) = state.tokens.peek() {
        let name = name.clone();
        state.tokens.advance();
        Ok(Pattern::RestNamed(name))
    } else {
        // DEFECT-029 FIX: Allow anonymous rest pattern (..) without identifier
        Ok(Pattern::Rest)
    }
}

/// Parse single list pattern element (regular or rest)
/// Complexity: 5 (Toyota Way: <10 ✓)
/// PARSER-059: Support both ..tail (two dots) and ...tail (three dots) syntax
fn parse_list_pattern_element(state: &mut ParserState) -> Result<Pattern> {
    if matches!(state.tokens.peek(), Some((Token::DotDot, _))) {
        parse_list_rest_pattern(state)
    } else if matches!(state.tokens.peek(), Some((Token::DotDotDot, _))) {
        parse_rest_pattern(state)
    } else {
        parse_match_pattern(state)
    }
}

/// Parse list pattern: [a, b, ..rest, c]
/// Complexity: 4 (Toyota Way: <10 ✓) [Reduced from 11]
fn parse_match_list_pattern(state: &mut ParserState) -> Result<Pattern> {
    state.tokens.expect(&Token::LeftBracket)?;

    // Check for empty list []
    if matches!(state.tokens.peek(), Some((Token::RightBracket, _))) {
        state.tokens.advance();
        return Ok(Pattern::List(vec![]));
    }

    // Parse pattern elements
    let mut patterns = vec![];
    loop {
        patterns.push(parse_list_pattern_element(state)?);

        if matches!(state.tokens.peek(), Some((Token::Comma, _))) {
            state.tokens.advance();
            if matches!(state.tokens.peek(), Some((Token::RightBracket, _))) {
                break; // trailing comma
            }
        } else {
            break;
        }
    }

    state.tokens.expect(&Token::RightBracket)?;
    Ok(Pattern::List(patterns))
}
/// Parse constructor pattern: Some(x), Ok(value), etc.
/// Complexity: <5
fn parse_constructor_pattern(state: &mut ParserState, name: String) -> Result<Pattern> {
    state.tokens.expect(&Token::LeftParen)?;
    // Parse the pattern arguments
    let patterns = parse_constructor_arguments(state)?;
    state.tokens.expect(&Token::RightParen)?;
    // Delegate pattern creation to helper
    create_constructor_pattern(name, patterns)
}
/// Parse constructor arguments (complexity: 6)
fn parse_constructor_arguments(state: &mut ParserState) -> Result<Vec<Pattern>> {
    // Check for empty tuple
    if matches!(state.tokens.peek(), Some((Token::RightParen, _))) {
        return Ok(vec![]);
    }
    let mut patterns = vec![parse_match_pattern(state)?];
    // Parse additional patterns if comma-separated
    while matches!(state.tokens.peek(), Some((Token::Comma, _))) {
        state.tokens.advance(); // consume comma
        if matches!(state.tokens.peek(), Some((Token::RightParen, _))) {
            break; // trailing comma
        }
        patterns.push(parse_match_pattern(state)?);
    }
    Ok(patterns)
}
/// Create appropriate pattern based on constructor name (complexity: 8)
fn create_constructor_pattern(name: String, patterns: Vec<Pattern>) -> Result<Pattern> {
    match (name.as_str(), patterns.len()) {
        ("Ok", 1) => {
            // Ok(pattern) - Result success case
            Ok(Pattern::Ok(Box::new(patterns.into_iter().next().expect(
                "patterns.len() == 1, so next() must return Some",
            ))))
        }
        ("Err", 1) => {
            // Err(pattern) - Result error case
            Ok(Pattern::Err(Box::new(patterns.into_iter().next().expect(
                "patterns.len() == 1, so next() must return Some",
            ))))
        }
        ("Some", 1) => {
            // Some(pattern) - Option success case
            Ok(Pattern::Some(Box::new(patterns.into_iter().next().expect(
                "patterns.len() == 1, so next() must return Some",
            ))))
        }
        ("None", 0) => {
            // None - Option empty case
            Ok(Pattern::None)
        }
        (name, 0) => {
            // Empty constructor - check if qualified path or simple identifier
            if name.contains("::") {
                let path: Vec<String> = name.split("::").map(ToString::to_string).collect();
                Ok(Pattern::QualifiedName(path))
            } else {
                Ok(Pattern::Identifier(name.to_string()))
            }
        }
        (name, _) => {
            // Constructor with arguments - use TupleVariant for custom enums
            let path: Vec<String> = name.split("::").map(ToString::to_string).collect();
            Ok(Pattern::TupleVariant { path, patterns })
        }
    }
}
/// Parse or-pattern: pattern | pattern | ...
/// Complexity: <5
fn parse_or_pattern(state: &mut ParserState, first: Pattern) -> Result<Pattern> {
    let mut patterns = vec![first];
    while matches!(state.tokens.peek(), Some((Token::Pipe, _))) {
        state.tokens.advance(); // consume '|'
                                // Need to parse the next pattern without recursing into or-patterns again
        let next = parse_single_pattern(state)?;
        patterns.push(next);
    }
    // Use the Or pattern variant for multiple alternatives
    if patterns.len() == 1 {
        Ok(patterns
            .into_iter()
            .next()
            .expect("patterns.len() == 1, so next() must return Some"))
    } else {
        Ok(Pattern::Or(patterns))
    }
}

#[cfg(test)]
mod tests {

    use crate::frontend::parser::Parser;

    #[test]
    fn test_identifier_pattern() {
        let code = "let x = 42";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Identifier pattern should parse");
    }

    #[test]
    fn test_tuple_pattern() {
        let code = "let (x, y, z) = (1, 2, 3)";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Tuple pattern should parse");
    }

    #[test]
    fn test_list_pattern_with_rest() {
        let code = "let [first, ...rest] = [1, 2, 3, 4]";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "List pattern with rest should parse");
    }

    #[test]
    fn test_struct_pattern() {
        let code = "let Point { x, y } = point";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Struct pattern should parse");
    }

    #[test]
    fn test_some_pattern() {
        let code = "let Some(x) = maybe_value";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Some pattern should parse");
    }

    #[test]
    fn test_ok_pattern() {
        let code = "let Ok(val) = result";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Ok pattern should parse");
    }

    #[test]
    fn test_err_pattern() {
        let code = "let Err(e) = result";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Err pattern should parse");
    }

    #[test]
    fn test_none_pattern() {
        let code = "let None = maybe_value";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "None pattern should parse");
    }

    #[test]
    fn test_wildcard_pattern() {
        let code = "let _ = value";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Wildcard pattern should parse");
    }

    #[test]
    fn test_literal_pattern() {
        let code = "match x { 42 => true, _ => false }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Literal pattern in match should parse");
    }

    #[test]
    fn test_range_pattern() {
        let code = "match x { 1..10 => \"low\", _ => \"high\" }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Range pattern should parse");
    }

    #[test]
    fn test_or_pattern() {
        let code = "match x { Some(1) | Some(2) => true, _ => false }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Or pattern should parse");
    }

    // PARSER-082: Atom pattern tests
    #[test]
    fn test_parser_082_atom_pattern_simple() {
        let code = "match x { :ok => true, :error => false }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Atom pattern :ok should parse");
    }

    #[test]
    fn test_parser_082_atom_pattern_with_wildcard() {
        let code = "match status { :ok => handle_ok(), :error => handle_error(), _ => default() }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Atom patterns with wildcard should parse");
    }

    #[test]
    fn test_parser_082_atom_pattern_or() {
        let code = "match x { :ok | :success => true, _ => false }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Or patterns with atoms should parse");
    }

    #[test]
    fn test_parser_082_atom_pattern_in_tuple() {
        let code = "match pair { (:ok, value) => value, (:error, msg) => panic(msg) }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Atom in tuple pattern should parse");
    }

    // COVERAGE: Additional pattern tests
    #[test]
    fn test_nested_tuple_pattern() {
        let code = "let ((a, b), c) = ((1, 2), 3)";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Nested tuple pattern should parse");
    }

    #[test]
    fn test_list_pattern_without_rest() {
        let code = "let [a, b, c] = [1, 2, 3]";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "List pattern without rest should parse");
    }

    #[test]
    fn test_tuple_variant_pattern() {
        let code = "match x { Point(a, b) => a + b }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Tuple variant pattern should parse");
    }

    #[test]
    fn test_struct_pattern_with_rest() {
        let code = "let Point { x, .. } = point";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Struct pattern with rest should parse");
    }

    #[test]
    fn test_match_with_guard() {
        let code = "match x { n if n > 0 => true, _ => false }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Match with guard should parse");
    }

    #[test]
    fn test_match_inclusive_range() {
        let code = "match x { 1..=10 => \"in range\", _ => \"out\" }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Inclusive range pattern should parse");
    }

    #[test]
    fn test_if_let_expression() {
        let code = "if let Some(x) = maybe { x } else { 0 }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "If-let expression should parse");
    }

    #[test]
    fn test_string_literal_pattern() {
        let code = r#"match s { "hello" => true, _ => false }"#;
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "String literal pattern should parse");
    }

    #[test]
    fn test_bool_literal_pattern() {
        let code = "match b { true => 1, false => 0 }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Bool literal pattern should parse");
    }

    #[test]
    fn test_float_literal_pattern() {
        let code = "match f { 3.14 => \"pi\", _ => \"other\" }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Float literal pattern should parse");
    }

    #[test]
    fn test_multiple_or_patterns() {
        let code = "match x { 1 | 2 | 3 => true, _ => false }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Multiple or patterns should parse");
    }

    #[test]
    fn test_char_literal_pattern() {
        let code = "match c { 'a' => 1, 'b' => 2, _ => 0 }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Char literal pattern should parse");
    }

    #[test]
    fn test_char_range_pattern() {
        let code = "match c { 'a'..'z' => true, _ => false }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Char range pattern should parse");
    }

    #[test]
    fn test_match_with_wildcard_only() {
        // Match requires at least one arm
        let code = "match x { _ => 0 }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Match with wildcard arm should parse");
    }

    #[test]
    fn test_match_multiple_arms() {
        let code = "match n { 0 => \"zero\", 1 => \"one\", 2 => \"two\", _ => \"many\" }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Match with multiple arms should parse");
    }

    #[test]
    fn test_let_with_type_annotation() {
        let code = "let x: i32 = 42";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Let with type annotation should parse");
    }

    #[test]
    fn test_mutable_pattern() {
        let code = "let mut x = 42";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Mutable let should parse");
    }

    #[test]
    fn test_var_declaration() {
        let code = "var x = 42";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Var declaration should parse");
    }

    #[test]
    fn test_constructor_pattern_no_args() {
        let code = "match x { Unit => 0 }";
        let result = Parser::new(code).parse();
        assert!(
            result.is_ok(),
            "Constructor pattern without args should parse"
        );
    }

    #[test]
    fn test_constructor_pattern_with_args() {
        let code = "match x { Pair(a, b) => a + b }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Constructor pattern with args should parse");
    }

    #[test]
    fn test_nested_struct_pattern() {
        let code = "let Line { start: Point { x, y }, end } = line";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Nested struct pattern should parse");
    }

    #[test]
    fn test_struct_field_rename() {
        let code = "let Point { x: new_x, y: new_y } = point";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Struct field rename should parse");
    }

    #[test]
    fn test_complex_match_expression() {
        let code = r#"match result {
            Ok(value) if value > 0 => value * 2,
            Ok(0) => 0,
            Err(e) => -1
        }"#;
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Complex match expression should parse");
    }

    #[test]
    fn test_if_let_with_else_if() {
        let code = "if let Some(x) = a { x } else if let Some(y) = b { y } else { 0 }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Chained if-let should parse");
    }

    #[test]
    fn test_let_else_clause() {
        let code = "let Some(x) = maybe else { return 0 }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Let-else should parse");
    }

    #[test]
    fn test_pattern_with_default_value() {
        let code = "fun foo(x = 10) { x }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Pattern with default value should parse");
    }

    #[test]
    fn test_rest_pattern_only() {
        let code = "let [...all] = [1, 2, 3]";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Rest pattern only should parse");
    }

    #[test]
    fn test_large_integer_pattern() {
        // Use positive integer - negative literals in patterns may not be supported
        let code = "match x { 100 => \"hundred\", _ => \"other\" }";
        let result = Parser::new(code).parse();
        assert!(result.is_ok(), "Large integer pattern should parse");
    }

    // ============================================================
    // Additional comprehensive tests for EXTREME TDD coverage
    // ============================================================

    use crate::frontend::ast::{Expr, ExprKind};
    use crate::frontend::parser::Result;

    fn parse(code: &str) -> Result<Expr> {
        Parser::new(code).parse()
    }

    fn get_block_exprs(expr: &Expr) -> Option<&Vec<Expr>> {
        match &expr.kind {
            ExprKind::Block(exprs) => Some(exprs),
            _ => None,
        }
    }

    // ============================================================
    // Tuple pattern comprehensive tests
    // ============================================================

    #[test]
    fn test_tuple_pattern_empty() {
        let result = parse("let () = ()");
        assert!(result.is_ok(), "Empty tuple pattern should parse");
    }

    #[test]
    fn test_tuple_pattern_single() {
        let result = parse("let (x,) = (1,)");
        assert!(result.is_ok(), "Single element tuple should parse");
    }

    #[test]
    fn test_tuple_pattern_four_elements() {
        let result = parse("let (a, b, c, d) = (1, 2, 3, 4)");
        assert!(result.is_ok(), "Four element tuple should parse");
    }

    #[test]
    fn test_tuple_pattern_with_wildcards() {
        let result = parse("let (x, _, z) = (1, 2, 3)");
        assert!(result.is_ok(), "Tuple with wildcards should parse");
    }

    #[test]
    fn test_tuple_pattern_nested_three_levels() {
        let result = parse("let (((a, b), c), d) = (((1, 2), 3), 4)");
        assert!(result.is_ok(), "Deeply nested tuple should parse");
    }

    #[test]
    fn test_tuple_pattern_with_mut_element() {
        let result = parse("let (mut x, y) = (1, 2)");
        assert!(result.is_ok(), "Tuple with mut element should parse");
    }

    // ============================================================
    // List pattern comprehensive tests
    // ============================================================

    #[test]
    fn test_list_pattern_empty() {
        let result = parse("let [] = []");
        assert!(result.is_ok(), "Empty list pattern should parse");
    }

    #[test]
    fn test_list_pattern_single_element() {
        let result = parse("let [x] = [1]");
        assert!(result.is_ok(), "Single element list should parse");
    }

    #[test]
    fn test_list_pattern_with_trailing_rest() {
        let result = parse("let [first, second, ...rest] = arr");
        assert!(result.is_ok(), "List with trailing rest should parse");
    }

    #[test]
    fn test_list_pattern_with_two_dot_rest() {
        let result = parse("let [head, ..tail] = arr");
        assert!(result.is_ok(), "List with two-dot rest should parse");
    }

    #[test]
    fn test_list_pattern_rest_only() {
        let result = parse("let [..all] = arr");
        assert!(result.is_ok(), "List with only rest should parse");
    }

    #[test]
    fn test_list_pattern_with_wildcards() {
        let result = parse("let [first, _, third] = arr");
        assert!(result.is_ok(), "List with wildcards should parse");
    }

    // ============================================================
    // Struct pattern comprehensive tests
    // ============================================================

    #[test]
    fn test_struct_pattern_single_field() {
        let result = parse("let Point { x } = point");
        assert!(result.is_ok(), "Struct with single field should parse");
    }

    #[test]
    fn test_struct_pattern_three_fields() {
        let result = parse("let Color { r, g, b } = color");
        assert!(result.is_ok(), "Struct with three fields should parse");
    }

    #[test]
    fn test_struct_pattern_rest_only() {
        let result = parse("let Point { .. } = point");
        assert!(result.is_ok(), "Struct with only rest should parse");
    }

    #[test]
    fn test_struct_pattern_field_with_nested() {
        let result = parse("let Line { start: Point { x, y }, end } = line");
        assert!(result.is_ok(), "Struct with nested pattern should parse");
    }

    #[test]
    fn test_struct_pattern_anonymous() {
        let result = parse("let { name, age } = person");
        assert!(result.is_ok(), "Anonymous struct pattern should parse");
    }

    #[test]
    fn test_struct_pattern_trailing_comma() {
        let result = parse("let Point { x, y, } = point");
        assert!(result.is_ok(), "Struct with trailing comma should parse");
    }

    // ============================================================
    // Match expression comprehensive tests
    // ============================================================

    #[test]
    fn test_match_with_block_body() {
        let result = parse("match x { 1 => { let a = 1; a + 1 }, _ => 0 }");
        assert!(result.is_ok(), "Match with block body should parse");
    }

    #[test]
    fn test_match_arrow_syntax() {
        let result = parse("match x { 1 -> true, _ -> false }");
        assert!(result.is_ok(), "Match with arrow syntax should parse");
    }

    #[test]
    fn test_match_five_arms() {
        let result = parse(
            "match x { 0 => \"zero\", 1 => \"one\", 2 => \"two\", 3 => \"three\", _ => \"many\" }",
        );
        assert!(result.is_ok(), "Match with five arms should parse");
    }

    #[test]
    fn test_match_guard_with_function_call() {
        let result = parse("match x { n if is_valid(n) => true, _ => false }");
        assert!(
            result.is_ok(),
            "Match with function call guard should parse"
        );
    }

    #[test]
    fn test_match_guard_with_comparison() {
        let result = parse("match x { n if n >= 0 && n < 100 => true, _ => false }");
        assert!(result.is_ok(), "Match with comparison guard should parse");
    }

    #[test]
    fn test_match_nested() {
        let result =
            parse("match x { Some(y) => match y { 1 => true, _ => false }, None => false }");
        assert!(result.is_ok(), "Nested match should parse");
    }

    #[test]
    fn test_match_with_trailing_comma() {
        let result = parse("match x { 1 => true, 2 => false, }");
        assert!(result.is_ok(), "Match with trailing comma should parse");
    }

    // ============================================================
    // If-let comprehensive tests
    // ============================================================

    #[test]
    fn test_if_let_without_else() {
        let result = parse("if let Some(x) = opt { print(x) }");
        assert!(result.is_ok(), "If-let without else should parse");
    }

    #[test]
    fn test_if_let_nested_pattern() {
        let result = parse("if let Some((a, b)) = opt { a + b } else { 0 }");
        assert!(result.is_ok(), "If-let with nested pattern should parse");
    }

    #[test]
    fn test_if_let_ok_pattern() {
        let result = parse("if let Ok(val) = result { val } else { 0 }");
        assert!(result.is_ok(), "If-let with Ok should parse");
    }

    #[test]
    fn test_if_let_err_pattern() {
        let result = parse("if let Err(e) = result { log(e) }");
        assert!(result.is_ok(), "If-let with Err should parse");
    }

    #[test]
    fn test_if_let_struct_pattern() {
        let result = parse("if let Point { x, y } = point { x + y } else { 0 }");
        assert!(result.is_ok(), "If-let with struct should parse");
    }

    #[test]
    fn test_if_let_chain() {
        let result = parse("if let Some(x) = a { x } else if let Some(y) = b { y } else { 0 }");
        assert!(result.is_ok(), "If-let chain should parse");
    }

    // ============================================================
    // Or pattern comprehensive tests
    // ============================================================

    #[test]
    fn test_or_pattern_three_alternatives() {
        let result = parse("match x { 1 | 2 | 3 => true, _ => false }");
        assert!(result.is_ok(), "Three-way or should parse");
    }

    #[test]
    fn test_or_pattern_with_unit_variants() {
        // Or pattern with unit variants (no function calls in body)
        let result = parse("match x { A | B => 1, _ => 0 }");
        assert!(result.is_ok(), "Or with unit variants should parse");
    }

    #[test]
    fn test_or_pattern_strings() {
        let result = parse(r#"match s { "yes" | "y" | "Y" => true, _ => false }"#);
        assert!(result.is_ok(), "Or with strings should parse");
    }

    #[test]
    fn test_or_pattern_with_binding() {
        let result = parse("match x { Some(n) | Ok(n) => n, _ => 0 }");
        assert!(result.is_ok(), "Or with bindings should parse");
    }

    // ============================================================
    // Range pattern comprehensive tests
    // ============================================================

    #[test]
    fn test_range_pattern_exclusive() {
        let result = parse("match x { 0..10 => true, _ => false }");
        assert!(result.is_ok(), "Exclusive range should parse");
    }

    #[test]
    fn test_range_pattern_inclusive() {
        let result = parse("match x { 0..=10 => true, _ => false }");
        assert!(result.is_ok(), "Inclusive range should parse");
    }

    #[test]
    fn test_range_pattern_char_exclusive() {
        let result = parse("match c { 'a'..'z' => true, _ => false }");
        assert!(result.is_ok(), "Char exclusive range should parse");
    }

    #[test]
    fn test_range_pattern_char_inclusive() {
        let result = parse("match c { 'a'..='z' => true, _ => false }");
        assert!(result.is_ok(), "Char inclusive range should parse");
    }

    // ============================================================
    // At binding tests
    // ============================================================

    #[test]
    fn test_at_binding_simple() {
        let result = parse("match x { n @ 1..10 => n, _ => 0 }");
        assert!(result.is_ok(), "At binding with range should parse");
    }

    #[test]
    fn test_at_binding_with_pattern() {
        let result = parse("match opt { val @ Some(_) => val, None => None }");
        assert!(result.is_ok(), "At binding with Some should parse");
    }

    // ============================================================
    // Qualified path patterns
    // ============================================================

    #[test]
    fn test_qualified_enum_variant() {
        let result = parse("match x { Color::Red => 1, Color::Green => 2, _ => 0 }");
        assert!(result.is_ok(), "Qualified enum variant should parse");
    }

    #[test]
    fn test_qualified_tuple_variant() {
        // Qualified with two alternatives - simpler form
        let result = parse("match x { Color::RGB(r, g, b) => r, _ => 0 }");
        assert!(result.is_ok(), "Qualified tuple variant should parse");
    }

    #[test]
    fn test_qualified_struct_variant() {
        let result = parse("match x { Shape::Circle { radius } => radius, _ => 0.0 }");
        assert!(result.is_ok(), "Qualified struct variant should parse");
    }

    // ============================================================
    // Let-else pattern tests
    // ============================================================

    #[test]
    fn test_let_else_with_panic() {
        let result = parse("let Some(x) = opt else { panic(\"no value\") }");
        assert!(result.is_ok(), "Let-else with panic should parse");
    }

    #[test]
    fn test_let_else_with_ok() {
        let result = parse("let Ok(val) = result else { return Err(e) }");
        assert!(result.is_ok(), "Let-else with Ok should parse");
    }

    #[test]
    fn test_let_else_complex_block() {
        let result = parse(
            r#"let Some(x) = opt else {
            log("error")
            return 0
        }"#,
        );
        assert!(result.is_ok(), "Let-else with complex block should parse");
    }

    // ============================================================
    // Edge cases and special patterns
    // ============================================================

    #[test]
    fn test_pattern_in_function_param() {
        let result = parse("fun foo((x, y)) { x + y }");
        assert!(
            result.is_ok(),
            "Tuple pattern in function param should parse"
        );
    }

    #[test]
    fn test_pattern_with_type_keyword_field() {
        let result = parse("let { type } = config");
        // May or may not parse - checking it doesn't crash
        let _ = result;
    }

    #[test]
    fn test_constructor_empty_args() {
        let result = parse("match x { Unit() => true, _ => false }");
        assert!(result.is_ok(), "Empty constructor args should parse");
    }

    #[test]
    fn test_constructor_three_args() {
        let result = parse("match x { Triple(a, b, c) => a + b + c }");
        assert!(result.is_ok(), "Constructor with three args should parse");
    }

    #[test]
    fn test_match_complex_guard() {
        let result = parse("match (x, y) { (a, b) if a > 0 && b > 0 => true, _ => false }");
        assert!(result.is_ok(), "Match with complex guard should parse");
    }

    #[test]
    fn test_pattern_result_identifier() {
        // Result is a keyword but can be used as identifier in some contexts
        let result = parse("let Result = compute()");
        assert!(result.is_ok(), "'Result' as identifier should parse");
    }

    #[test]
    fn test_pattern_var_identifier() {
        let result = parse("let var = value");
        // May or may not work - var is a keyword
        let _ = result;
    }

    #[test]
    fn test_empty_tuple_in_match() {
        let result = parse("match x { () => true }");
        assert!(result.is_ok(), "Empty tuple in match should parse");
    }

    #[test]
    fn test_empty_list_in_match() {
        let result = parse("match arr { [] => true, _ => false }");
        assert!(result.is_ok(), "Empty list in match should parse");
    }

    // Property tests
    #[cfg(test)]
    mod property_tests {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            #[ignore = "Property tests run with --ignored flag"] // Run with: cargo test property_tests -- --ignored
            fn prop_identifier_patterns_parse(name in "[a-z][a-z0-9_]*") {
                let code = format!("let {name} = 42");
                let result = Parser::new(&code).parse();
                prop_assert!(result.is_ok());
            }

            #[test]
            #[ignore = "Property tests run with --ignored flag"]
            fn prop_tuple_patterns_parse(a in "[a-z]+", b in "[a-z]+") {
                let code = format!("let ({a}, {b}) = (1, 2)");
                let result = Parser::new(&code).parse();
                prop_assert!(result.is_ok());
            }

            #[test]
            #[ignore = "Property tests run with --ignored flag"]
            fn prop_list_patterns_parse(name in "[a-z]+") {
                let code = format!("let [{name}, ...rest] = [1, 2, 3]");
                let result = Parser::new(&code).parse();
                prop_assert!(result.is_ok());
            }

            #[test]
            #[ignore = "Property tests run with --ignored flag"]
            fn prop_some_patterns_parse(inner in "[a-z]+") {
                let code = format!("let Some({inner}) = value");
                let result = Parser::new(&code).parse();
                prop_assert!(result.is_ok());
            }

            #[test]
            #[ignore = "Property tests run with --ignored flag"]
            fn prop_wildcard_always_parses(_seed in any::<u32>()) {
                let code = "let _ = 42";
                let result = Parser::new(code).parse();
                prop_assert!(result.is_ok());
            }

            #[test]
            #[ignore = "Property tests run with --ignored flag"]
            fn prop_literal_patterns_parse(n in 0i32..1000) {
                let code = format!("match x {{ {n} => true, _ => false }}");
                let result = Parser::new(&code).parse();
                prop_assert!(result.is_ok());
            }

            #[test]
            #[ignore = "Property tests run with --ignored flag"]
            fn prop_struct_patterns_parse(field in "[a-z]+") {
                let code = format!("let Point {{ {field} }} = p");
                let result = Parser::new(&code).parse();
                prop_assert!(result.is_ok());
            }
        }
    }
}