synta-codegen 0.2.2

ASN.1 schema parser and Rust code generator for the synta library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
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
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
//! ASN.1 schema parser

use crate::ast::*;
use std::fmt;

#[derive(Debug, Clone, PartialEq)]
pub struct ParseError {
    pub message: String,
    pub line: usize,
    pub column: usize,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Parse error at {}:{}: {}",
            self.line, self.column, self.message
        )
    }
}

impl std::error::Error for ParseError {}

type Result<T> = std::result::Result<T, ParseError>;

// ASN.1 X.680 Reserved Keywords - All keywords are case-sensitive per X.680 specification
// These are organized by category for maintainability

/// Type constructor keywords
const TYPE_CONSTRUCTORS: &[&str] = &["SEQUENCE", "SET", "CHOICE", "OF"];

/// Field modifier keywords
const FIELD_MODIFIERS: &[&str] = &["OPTIONAL", "DEFAULT"];

/// Primitive type keywords (all uppercase per X.680)
const PRIMITIVE_TYPES: &[&str] = &[
    "INTEGER",
    "BOOLEAN",
    "OCTET",
    "STRING",
    "BIT",
    "OBJECT",
    "IDENTIFIER",
    "NULL",
    "REAL",
    "ENUMERATED",
];

/// Built-in string types (mixed case per X.680)
/// These can be used both as keywords and as type references
const STRING_TYPES: &[&str] = &[
    "UTF8String",
    "PrintableString",
    "IA5String",
    "TeletexString",
    "T61String",
    "BMPString",
    "UniversalString",
    "GeneralString",
    "GraphicString",
    "NumericString",
    "ObjectDescriptor",
    "VideotexString",
    "VisibleString",
    "ISO646String",
];

/// Time type keywords
const TIME_TYPES: &[&str] = &[
    "UTCTime",
    "GeneralizedTime",
    "DATE",
    "TIME",
    "TIME-OF-DAY",
    "DATE-TIME",
    "DURATION",
];

/// Tagging keywords
const TAGGING_KEYWORDS: &[&str] = &[
    "EXPLICIT",
    "IMPLICIT",
    "AUTOMATIC",
    "TAGS",
    "UNIVERSAL",
    "APPLICATION",
    "PRIVATE",
    "CONTEXT",
    "IMPLIED",
];

/// Module definition keywords
const MODULE_KEYWORDS: &[&str] = &["BEGIN", "END", "DEFINITIONS"];

/// Constraint keywords
const CONSTRAINT_KEYWORDS: &[&str] = &[
    "SIZE",
    "MIN",
    "MAX",
    "FROM",
    "PATTERN",
    "CONTAINING",
    "WITH",
    "COMPONENTS",
];

/// Set operation keywords
const SET_OPERATIONS: &[&str] = &["ALL", "EXCEPT", "INCLUDES", "INTERSECTION", "UNION"];

/// Import/export keywords
const IMPORT_EXPORT: &[&str] = &["IMPORTS", "EXPORTS"];

/// Special keywords
const SPECIAL_KEYWORDS: &[&str] = &[
    "ANY",
    "DEFINED",
    "BY",
    "ABSENT",
    "PRESENT",
    "TRUE",
    "FALSE",
    "EXTENSIBILITY",
    "ENCODED",
    "PLUS-INFINITY",
    "MINUS-INFINITY",
    "NOT-A-NUMBER",
];

/// Class-related keywords
const CLASS_KEYWORDS: &[&str] = &[
    "CLASS",
    "UNIQUE",
    "SYNTAX",
    "TYPE-IDENTIFIER",
    "ABSTRACT-SYNTAX",
];

/// Additional type keywords
const ADDITIONAL_TYPES: &[&str] = &[
    "EXTERNAL",
    "EMBEDDED",
    "PDV",
    "CHARACTER",
    "RELATIVE-OID",
    "OID-IRI",
    "RELATIVE-OID-IRI",
];

/// Check if a string is an ASN.1 reserved keyword
fn is_asn1_keyword(s: &str) -> bool {
    TYPE_CONSTRUCTORS.contains(&s)
        || FIELD_MODIFIERS.contains(&s)
        || PRIMITIVE_TYPES.contains(&s)
        || STRING_TYPES.contains(&s)
        || TIME_TYPES.contains(&s)
        || TAGGING_KEYWORDS.contains(&s)
        || MODULE_KEYWORDS.contains(&s)
        || CONSTRAINT_KEYWORDS.contains(&s)
        || SET_OPERATIONS.contains(&s)
        || IMPORT_EXPORT.contains(&s)
        || SPECIAL_KEYWORDS.contains(&s)
        || CLASS_KEYWORDS.contains(&s)
        || ADDITIONAL_TYPES.contains(&s)
}

/// Built-in types that can be used as type references (keywords that represent types)
fn is_builtin_type_keyword(s: &str) -> bool {
    STRING_TYPES.contains(&s) || TIME_TYPES.contains(&s) || ADDITIONAL_TYPES.contains(&s)
}

/// Tokenizer for ASN.1 schemas
#[derive(Clone)]
struct Lexer {
    input: Vec<char>,
    pos: usize,
    line: usize,
    column: usize,
}

#[derive(Debug, Clone, PartialEq)]
enum Token {
    Identifier(String),
    Number(u32),
    Keyword(String),
    Symbol(String),
    Eof,
}

impl Lexer {
    fn new(input: &str) -> Self {
        Self {
            input: input.chars().collect(),
            pos: 0,
            line: 1,
            column: 1,
        }
    }

    fn current(&self) -> Option<char> {
        self.input.get(self.pos).copied()
    }

    fn advance(&mut self) -> Option<char> {
        if let Some(ch) = self.current() {
            self.pos += 1;
            if ch == '\n' {
                self.line += 1;
                self.column = 1;
            } else {
                self.column += 1;
            }
            Some(ch)
        } else {
            None
        }
    }

    fn skip_whitespace(&mut self) {
        while let Some(ch) = self.current() {
            if ch.is_whitespace() {
                self.advance();
            } else if ch == '-' && self.peek(1) == Some('-') {
                // Skip comments (-- to end of line)
                while let Some(ch) = self.current() {
                    self.advance();
                    if ch == '\n' {
                        break;
                    }
                }
            } else {
                break;
            }
        }
    }

    fn peek(&self, offset: usize) -> Option<char> {
        self.input.get(self.pos + offset).copied()
    }

    fn next_token(&mut self) -> Result<Token> {
        self.skip_whitespace();

        let ch = match self.current() {
            Some(ch) => ch,
            None => return Ok(Token::Eof),
        };

        // Quoted strings
        if ch == '"' {
            self.advance(); // consume opening quote
            let mut string = String::new();
            while let Some(ch) = self.current() {
                if ch == '"' {
                    self.advance(); // consume closing quote
                    break;
                } else if ch == '\\' {
                    // Handle escape sequences
                    self.advance();
                    if let Some(escaped) = self.current() {
                        match escaped {
                            'n' => string.push('\n'),
                            't' => string.push('\t'),
                            'r' => string.push('\r'),
                            '\\' => string.push('\\'),
                            '"' => string.push('"'),
                            _ => string.push(escaped),
                        }
                        self.advance();
                    }
                } else {
                    string.push(ch);
                    self.advance();
                }
            }
            return Ok(Token::Identifier(string)); // Return as identifier for now
        }

        // Numbers
        if ch.is_ascii_digit() {
            let mut num = String::new();
            while let Some(ch) = self.current() {
                if ch.is_ascii_digit() {
                    num.push(ch);
                    self.advance();
                } else {
                    break;
                }
            }
            return Ok(Token::Number(num.parse().unwrap()));
        }

        // Class field references: &identifier (X.681 §9)
        // Consumed as a single Identifier token with the '&' prefix included.
        if ch == '&' && self.peek(1).is_some_and(|c| c.is_alphabetic()) {
            self.advance(); // consume '&'
            let mut ident = String::from("&");
            while let Some(ch) = self.current() {
                if ch.is_alphanumeric() || ch == '-' {
                    ident.push(ch);
                    self.advance();
                } else {
                    break;
                }
            }
            return Ok(Token::Identifier(ident));
        }

        // Identifiers and keywords
        if ch.is_alphabetic() {
            let mut ident = String::new();
            while let Some(ch) = self.current() {
                if ch.is_alphanumeric() || ch == '-' {
                    ident.push(ch);
                    self.advance();
                } else {
                    break;
                }
            }

            // X.680 specifies that ASN.1 keywords are case-sensitive.
            // Check if this identifier matches a reserved keyword exactly.
            if is_asn1_keyword(&ident) {
                return Ok(Token::Keyword(ident));
            }

            return Ok(Token::Identifier(ident));
        }

        // Multi-character symbols (check these first!)
        if ch == ':' && self.peek(1) == Some(':') && self.peek(2) == Some('=') {
            self.advance();
            self.advance();
            self.advance();
            return Ok(Token::Symbol("::=".to_string()));
        }

        if ch == '.' && self.peek(1) == Some('.') && self.peek(2) == Some('.') {
            self.advance();
            self.advance();
            self.advance();
            return Ok(Token::Symbol("...".to_string()));
        }

        if ch == '.' && self.peek(1) == Some('.') {
            self.advance();
            self.advance();
            return Ok(Token::Symbol("..".to_string()));
        }

        // Minus sign (but not if it's part of -- comment, which is handled in skip_whitespace)
        if ch == '-' && self.peek(1) != Some('-') {
            self.advance();
            return Ok(Token::Symbol("-".to_string()));
        }

        // Single-character symbols
        if matches!(
            ch,
            '{' | '}' | '[' | ']' | '(' | ')' | ',' | ':' | '|' | '^' | '@' | ';' | '.'
        ) {
            self.advance();
            return Ok(Token::Symbol(ch.to_string()));
        }

        Err(ParseError {
            message: format!("Unexpected character: {}", ch),
            line: self.line,
            column: self.column,
        })
    }
}

/// Parser for ASN.1 schemas
pub struct Parser {
    lexer: Lexer,
    current: Token,
    /// Default tagging mode derived from the module's `DEFINITIONS [IMPLICIT|EXPLICIT] TAGS`
    /// declaration.  Starts as `Explicit` (the ASN.1 default when no keyword is present) and is
    /// updated in `parse_module()` after the header is parsed.
    default_tagging: Tagging,
}

impl Parser {
    pub fn new(input: &str) -> Result<Self> {
        let mut lexer = Lexer::new(input);
        let current = lexer.next_token()?;
        Ok(Self {
            lexer,
            current,
            default_tagging: Tagging::Explicit,
        })
    }

    fn advance(&mut self) -> Result<()> {
        self.current = self.lexer.next_token()?;
        Ok(())
    }

    fn expect_keyword(&mut self, keyword: &str) -> Result<()> {
        if let Token::Keyword(kw) = &self.current {
            if kw == keyword {
                self.advance()?;
                return Ok(());
            }
        }
        Err(ParseError {
            message: format!("Expected keyword '{}', got {:?}", keyword, self.current),
            line: self.lexer.line,
            column: self.lexer.column,
        })
    }

    fn expect_symbol(&mut self, symbol: &str) -> Result<()> {
        if let Token::Symbol(sym) = &self.current {
            if sym == symbol {
                self.advance()?;
                return Ok(());
            }
        }
        Err(ParseError {
            message: format!("Expected symbol '{}', got {:?}", symbol, self.current),
            line: self.lexer.line,
            column: self.lexer.column,
        })
    }

    fn expect_identifier(&mut self) -> Result<String> {
        if let Token::Identifier(name) = &self.current {
            let result = name.clone();
            self.advance()?;
            return Ok(result);
        }
        Err(ParseError {
            message: format!("Expected identifier, got {:?}", self.current),
            line: self.lexer.line,
            column: self.lexer.column,
        })
    }

    /// Parse size constraint (e.g., (SIZE (16)) or (SIZE (1..64)))
    fn parse_size_constraint(&mut self) -> Result<Option<SizeConstraint>> {
        if !matches!(self.current, Token::Symbol(ref s) if s == "(") {
            return Ok(None);
        }

        self.advance()?; // consume '('

        // Check for SIZE keyword
        if !matches!(self.current, Token::Keyword(ref kw) if kw == "SIZE") {
            // Not a SIZE constraint - skip it
            while !matches!(self.current, Token::Symbol(ref s) if s == ")") {
                if matches!(self.current, Token::Eof) {
                    break;
                }
                self.advance()?;
            }
            if matches!(self.current, Token::Symbol(ref s) if s == ")") {
                self.advance()?;
            }
            return Ok(None);
        }

        self.advance()?; // consume SIZE
        self.expect_symbol("(")?;

        // Parse size value
        let min = if let Token::Number(n) = self.current {
            let val = n;
            self.advance()?;
            Some(val as u64)
        } else {
            None
        };

        let constraint = if matches!(self.current, Token::Symbol(ref s) if s == "..") {
            self.advance()?;
            let max = if let Token::Number(n) = self.current {
                let val = n;
                self.advance()?;
                Some(val as u64)
            } else {
                None
            };
            SizeConstraint::Range(min, max)
        } else if let Some(size) = min {
            SizeConstraint::Fixed(size)
        } else {
            return Ok(None);
        };

        self.expect_symbol(")")?; // inner paren
        self.expect_symbol(")")?; // outer paren

        Ok(Some(constraint))
    }

    /// Parse an integer value (positive or negative)
    fn parse_integer_value(&mut self) -> Result<Option<i64>> {
        // Check for negative sign
        let negative = if matches!(self.current, Token::Symbol(ref s) if s == "-") {
            self.advance()?;
            true
        } else {
            false
        };

        if let Token::Number(n) = self.current {
            let val = if negative { -(n as i64) } else { n as i64 };
            self.advance()?;
            Ok(Some(val))
        } else {
            Ok(None)
        }
    }

    /// Parse a constraint value (X.680: integer, named value, MIN, or MAX)
    fn parse_constraint_value(&mut self) -> Result<ConstraintValue> {
        // Check for MIN keyword
        if matches!(self.current, Token::Keyword(ref kw) if kw == "MIN") {
            self.advance()?;
            return Ok(ConstraintValue::Min);
        }

        // Check for MAX keyword
        if matches!(self.current, Token::Keyword(ref kw) if kw == "MAX") {
            self.advance()?;
            return Ok(ConstraintValue::Max);
        }

        // Check for named value (identifier)
        if let Token::Identifier(ref name) = self.current {
            let name = name.clone();
            self.advance()?;
            return Ok(ConstraintValue::NamedValue(name));
        }

        // Check for integer value
        if let Some(val) = self.parse_integer_value()? {
            return Ok(ConstraintValue::Integer(val));
        }

        Err(ParseError {
            message: "Expected constraint value (integer, MIN, MAX, or identifier)".to_string(),
            line: self.lexer.line,
            column: self.lexer.column,
        })
    }

    /// Parse a subtype constraint with union/intersection operators
    fn parse_subtype_constraint(&mut self) -> Result<SubtypeConstraint> {
        // Parse the first constraint element
        let first = self.parse_single_constraint()?;

        // Check for union (|) or intersection (^) operators
        let mut elements = vec![first];
        let mut is_union = false;
        let mut is_intersection = false;

        while matches!(self.current, Token::Symbol(ref s) if s == "|" || s == "^") {
            let op = if let Token::Symbol(ref s) = self.current {
                s.clone()
            } else {
                unreachable!()
            };

            if op == "|" {
                is_union = true;
            } else if op == "^" {
                is_intersection = true;
            }

            self.advance()?; // consume operator
            elements.push(self.parse_single_constraint()?);
        }

        // Return appropriate constraint type
        if is_union && is_intersection {
            return Err(ParseError {
                message: "Cannot mix union (|) and intersection (^) operators without parentheses"
                    .to_string(),
                line: self.lexer.line,
                column: self.lexer.column,
            });
        }

        if is_union {
            Ok(SubtypeConstraint::Union(elements))
        } else if is_intersection {
            Ok(SubtypeConstraint::Intersection(elements))
        } else {
            Ok(elements.into_iter().next().unwrap())
        }
    }

    /// Parse a single constraint element (value, range, or parenthesized constraint)
    fn parse_single_constraint(&mut self) -> Result<SubtypeConstraint> {
        // Check for ALL EXCEPT
        if matches!(self.current, Token::Keyword(ref kw) if kw == "ALL") {
            self.advance()?;
            self.expect_keyword("EXCEPT")?;
            let inner = self.parse_single_constraint()?;
            return Ok(SubtypeConstraint::Complement(Box::new(inner)));
        }

        // Check for parenthesized constraint
        if matches!(self.current, Token::Symbol(ref s) if s == "(") {
            self.advance()?; // consume '('
            let constraint = self.parse_subtype_constraint()?;
            self.expect_symbol(")")?;
            return Ok(constraint);
        }

        // Parse first value
        let first_value = self.parse_constraint_value()?;

        // Check for range operator (..)
        if matches!(self.current, Token::Symbol(ref s) if s == "..") {
            self.advance()?; // consume '..'
            let second_value = self.parse_constraint_value()?;
            return Ok(SubtypeConstraint::ValueRange {
                min: first_value,
                max: second_value,
            });
        }

        // Single value constraint
        Ok(SubtypeConstraint::SingleValue(first_value))
    }

    /// Parse a permitted alphabet constraint: FROM ("A".."Z" | "0".."9")
    fn parse_permitted_alphabet(&mut self) -> Result<SubtypeConstraint> {
        self.expect_keyword("FROM")?;
        self.expect_symbol("(")?;

        let mut ranges = Vec::new();

        loop {
            // Parse a string literal or character range
            if let Token::Identifier(ref s) = self.current {
                // String literal - extract character range
                let chars: Vec<char> = s.chars().collect();
                if chars.len() == 1 {
                    let ch = chars[0];
                    self.advance()?;

                    // Check for range operator
                    if matches!(self.current, Token::Symbol(ref sym) if sym == "..") {
                        self.advance()?; // consume '..'

                        // Parse end character
                        if let Token::Identifier(ref end_s) = self.current {
                            let end_chars: Vec<char> = end_s.chars().collect();
                            if end_chars.len() == 1 {
                                ranges.push(CharRange {
                                    min: ch,
                                    max: end_chars[0],
                                });
                                self.advance()?;
                            }
                        }
                    } else {
                        // Single character
                        ranges.push(CharRange { min: ch, max: ch });
                    }
                }
            }

            // Check for more ranges
            if matches!(self.current, Token::Symbol(ref s) if s == "|") {
                self.advance()?; // consume '|'
            } else {
                break;
            }
        }

        self.expect_symbol(")")?;
        Ok(SubtypeConstraint::PermittedAlphabet(ranges))
    }

    /// Parse a pattern constraint: PATTERN "regex"
    fn parse_pattern(&mut self) -> Result<SubtypeConstraint> {
        self.expect_keyword("PATTERN")?;

        // Pattern should be a string literal
        if let Token::Identifier(ref pattern) = self.current {
            let pattern_str = pattern.clone();
            self.advance()?;
            Ok(SubtypeConstraint::Pattern(pattern_str))
        } else {
            Err(ParseError {
                message: "Expected pattern string after PATTERN keyword".to_string(),
                line: self.lexer.line,
                column: self.lexer.column,
            })
        }
    }

    /// Parse a DEFAULT value (number, boolean, string, etc.)
    fn parse_default_value(&mut self) -> Result<String> {
        let value = match &self.current {
            Token::Number(n) => {
                let val = n.to_string();
                self.advance()?;
                val
            }
            Token::Symbol(s) if s == "-" => {
                // Negative number
                self.advance()?;
                if let Token::Number(n) = self.current {
                    let val = format!("-{}", n);
                    self.advance()?;
                    val
                } else {
                    return Err(ParseError {
                        message: "Expected number after '-'".to_string(),
                        line: self.lexer.line,
                        column: self.lexer.column,
                    });
                }
            }
            Token::Keyword(kw) if kw == "TRUE" => {
                self.advance()?;
                "true".to_string()
            }
            Token::Keyword(kw) if kw == "FALSE" => {
                self.advance()?;
                "false".to_string()
            }
            Token::Identifier(s) => {
                // Could be a string literal (from quoted string) or named value
                let val = s.clone();
                self.advance()?;
                // If it looks like a string literal, quote it
                // Otherwise assume it's a named constant
                val
            }
            _ => {
                return Err(ParseError {
                    message: format!("Unexpected token in DEFAULT value: {:?}", self.current),
                    line: self.lexer.line,
                    column: self.lexer.column,
                });
            }
        };

        Ok(value)
    }

    /// Helper to parse a string type with optional constraints
    /// This reduces code duplication for UTF8String, PrintableString, IA5String, etc.
    fn parse_string_type(&mut self, base_type: Type) -> Result<Type> {
        self.advance()?;

        // Check for X.680 string constraints (SIZE, FROM, PATTERN)
        if let Some(constraint) = self.parse_string_constraint()? {
            return Ok(Type::Constrained {
                base_type: Box::new(base_type),
                constraint: Constraint {
                    spec: ConstraintSpec::Subtype(constraint),
                    exception: None,
                },
            });
        }

        Ok(base_type)
    }

    /// Parse string constraints (SIZE, FROM, PATTERN)
    /// Supports combined constraints: (SIZE (...) FROM (...))
    fn parse_string_constraint(&mut self) -> Result<Option<SubtypeConstraint>> {
        if !matches!(self.current, Token::Symbol(ref s) if s == "(") {
            return Ok(None);
        }

        self.advance()?; // consume '('

        // Collect multiple constraints that can be combined
        let mut constraints = Vec::new();

        // Parse first constraint
        if let Some(constraint) = self.parse_single_string_constraint()? {
            constraints.push(constraint);
        }

        // Check for additional constraints (combined constraints)
        // e.g., (SIZE (4..6) FROM ("0".."9"))
        while !matches!(self.current, Token::Symbol(ref s) if s == ")") {
            if matches!(self.current, Token::Eof) {
                break;
            }

            // Try to parse another constraint keyword
            if let Some(constraint) = self.parse_single_string_constraint()? {
                constraints.push(constraint);
            } else {
                // If not a recognized constraint, skip to closing paren
                break;
            }
        }

        self.expect_symbol(")")?; // outer paren

        // Return appropriate constraint based on count
        match constraints.len() {
            0 => Ok(None),
            1 => Ok(Some(constraints.into_iter().next().unwrap())),
            _ => {
                // Multiple constraints - combine with Intersection
                Ok(Some(SubtypeConstraint::Intersection(constraints)))
            }
        }
    }

    /// Parse a single string constraint keyword (SIZE, FROM, PATTERN, CONTAINING)
    fn parse_single_string_constraint(&mut self) -> Result<Option<SubtypeConstraint>> {
        // Check for SIZE keyword
        if matches!(self.current, Token::Keyword(ref kw) if kw == "SIZE") {
            self.advance()?; // consume SIZE
            self.expect_symbol("(")?;

            // Parse size value or range
            let size_constraint = self.parse_subtype_constraint()?;

            self.expect_symbol(")")?; // inner paren
                                      // Don't consume outer paren here - let caller handle it

            return Ok(Some(SubtypeConstraint::SizeConstraint(Box::new(
                size_constraint,
            ))));
        }

        // Check for FROM keyword
        if matches!(self.current, Token::Keyword(ref kw) if kw == "FROM") {
            let constraint = self.parse_permitted_alphabet()?;
            // Don't consume outer paren here - let caller handle it
            return Ok(Some(constraint));
        }

        // Check for PATTERN keyword
        if matches!(self.current, Token::Keyword(ref kw) if kw == "PATTERN") {
            let constraint = self.parse_pattern()?;
            // Don't consume outer paren here - let caller handle it
            return Ok(Some(constraint));
        }

        // Check for CONTAINING keyword (Phase 3)
        if matches!(self.current, Token::Keyword(ref kw) if kw == "CONTAINING") {
            self.advance()?; // consume CONTAINING
            let contained_type = self.parse_type()?;
            // Don't consume outer paren here - let caller handle it
            return Ok(Some(SubtypeConstraint::ContainedSubtype(Box::new(
                contained_type,
            ))));
        }

        Ok(None)
    }

    /// Parse EXPORTS clause
    /// EXPORTS Type1, Type2, Type3; or EXPORTS ALL;
    fn parse_exports(&mut self) -> Result<Vec<String>> {
        let mut exports = Vec::new();

        // Check if EXPORTS keyword is present
        if !matches!(self.current, Token::Keyword(ref kw) if kw == "EXPORTS") {
            return Ok(exports);
        }

        self.advance()?; // consume EXPORTS

        // Check for "EXPORTS ALL;"
        if matches!(self.current, Token::Keyword(ref kw) if kw == "ALL") {
            self.advance()?; // consume ALL
            if matches!(self.current, Token::Symbol(ref s) if s == ";") {
                self.advance()?; // consume ';'
            }
            // Return empty vec - ALL means export everything
            // Code generator will handle this appropriately
            return Ok(exports);
        }

        // Parse exported symbol names
        loop {
            if matches!(self.current, Token::Symbol(ref s) if s == ";") {
                self.advance()?; // consume ';'
                break;
            }

            if matches!(self.current, Token::Eof)
                || matches!(self.current, Token::Keyword(ref kw) if kw == "IMPORTS" || kw == "END")
            {
                // Semicolon is optional in some cases
                break;
            }

            let name = self.expect_identifier()?;
            exports.push(name);

            // Check for comma
            if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                self.advance()?; // consume ','
            }
        }

        Ok(exports)
    }

    /// Parse IMPORTS clause
    /// IMPORTS Type1, Type2 FROM Module1 Type3 FROM Module2;
    fn parse_imports(&mut self) -> Result<Vec<Import>> {
        let mut imports = Vec::new();

        // Check if IMPORTS keyword is present
        if !matches!(self.current, Token::Keyword(ref kw) if kw == "IMPORTS") {
            return Ok(imports);
        }

        self.advance()?; // consume IMPORTS

        // Parse import declarations
        loop {
            if matches!(self.current, Token::Symbol(ref s) if s == ";") {
                self.advance()?; // consume ';'
                break;
            }

            if matches!(self.current, Token::Eof)
                || matches!(self.current, Token::Keyword(ref kw) if kw == "END")
            {
                // Semicolon is optional in some cases
                break;
            }

            // Parse symbols (Type1, Type2, ...)
            let mut symbols = Vec::new();
            loop {
                if matches!(self.current, Token::Keyword(ref kw) if kw == "FROM") {
                    break;
                }

                let name = self.expect_identifier()?;

                // Skip optional parameterized type arguments after identifier,
                // e.g. `AlgorithmIdentifier{}` or `AlgorithmIdentifier{T, {S}}`.
                if matches!(self.current, Token::Symbol(ref s) if s == "{") {
                    self.skip_balanced_braces()?;
                }

                symbols.push(name);

                // Check for comma
                if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                    self.advance()?; // consume ','
                } else {
                    break;
                }
            }

            // Expect FROM keyword
            self.expect_keyword("FROM")?;

            // Parse module name
            let module_name = self.expect_identifier()?;

            // Skip optional module OID block after the module name,
            // e.g. `FROM AlgorithmInformation-2009 { iso(1) ... }`.
            if matches!(self.current, Token::Symbol(ref s) if s == "{") {
                self.skip_balanced_braces()?;
            }

            imports.push(Import {
                symbols,
                module_name,
            });

            // Check if there are more imports or end of IMPORTS clause
            if matches!(self.current, Token::Symbol(ref s) if s == ";") {
                self.advance()?; // consume ';'
                break;
            }

            // If no semicolon, check for additional import groups or end
            if matches!(self.current, Token::Eof)
                || matches!(self.current, Token::Keyword(ref kw) if kw == "END")
                || !matches!(self.current, Token::Identifier(_))
            {
                break;
            }
        }

        Ok(imports)
    }

    /// Parse a complete module
    pub fn parse_module(&mut self) -> Result<Module> {
        let name = self.expect_identifier()?;

        // Parse optional module OID
        let oid = if let Token::Symbol(ref sym) = self.current {
            if sym == "{" {
                Some(self.parse_module_oid()?)
            } else {
                None
            }
        } else {
            None
        };

        self.expect_keyword("DEFINITIONS")?;

        // Parse optional tagging mode
        let tagging_mode = if let Token::Keyword(ref kw) = self.current {
            match kw.as_str() {
                "EXPLICIT" => {
                    self.advance()?;
                    self.expect_keyword("TAGS")?;
                    Some(crate::ast::TaggingMode::Explicit)
                }
                "IMPLICIT" => {
                    self.advance()?;
                    self.expect_keyword("TAGS")?;
                    Some(crate::ast::TaggingMode::Implicit)
                }
                "AUTOMATIC" => {
                    self.advance()?;
                    self.expect_keyword("TAGS")?;
                    Some(crate::ast::TaggingMode::Automatic)
                }
                _ => None,
            }
        } else {
            None
        };

        // Propagate the module-level tagging default to the parser so that bare [N] tags
        // in SEQUENCE fields use the correct default (IMPLICIT for "DEFINITIONS IMPLICIT TAGS",
        // etc.).  AUTOMATIC behaves like IMPLICIT for field tagging purposes.
        self.default_tagging = match &tagging_mode {
            Some(crate::ast::TaggingMode::Implicit) | Some(crate::ast::TaggingMode::Automatic) => {
                Tagging::Implicit
            }
            _ => Tagging::Explicit,
        };

        self.expect_symbol("::=")?;
        self.expect_keyword("BEGIN")?;

        // Parse EXPORTS if present
        let exports = self.parse_exports()?;

        // Parse IMPORTS if present
        let imports = self.parse_imports()?;

        // Parse definitions and value assignments
        let mut definitions = Vec::new();
        let mut values = Vec::new();
        while !matches!(self.current, Token::Keyword(ref kw) if kw == "END") {
            if matches!(self.current, Token::Eof) {
                break;
            }
            // Priority order:
            //  1. Classic value assignment (name OBJECT|INTEGER|BOOLEAN ::= value)
            //  2. IOC value assignment (name ClassName ::= { ... }) — consumed and discarded
            //  3. Type definition (TypeName ::= Type)
            if let Some(value_assignment) = self.try_parse_value_assignment()? {
                values.push(value_assignment);
            } else if self.try_skip_class_alias()? {
                // Class alias assignment (e.g. `MyClass ::= TYPE-IDENTIFIER`) consumed and discarded
            } else if self.try_skip_ioc_assignment()? {
                // IOC assignment consumed; loop continues to the next definition
            } else {
                definitions.push(self.parse_definition()?);
            }
        }

        if matches!(self.current, Token::Keyword(ref kw) if kw == "END") {
            self.advance()?;
        }

        Ok(Module {
            name,
            oid,
            tagging_mode,
            imports,
            exports,
            definitions,
            values,
        })
    }

    /// Parse module OID: { iso(1) identified-organization(3) ... }
    /// Returns a vector of OID components as strings for simplicity
    fn parse_module_oid(&mut self) -> Result<Vec<String>> {
        self.expect_symbol("{")?;
        let mut oid_parts = Vec::new();

        // Parse OID components until we hit the closing brace
        while !matches!(self.current, Token::Symbol(ref sym) if sym == "}") {
            match &self.current {
                Token::Identifier(id) => {
                    oid_parts.push(id.clone());
                    self.advance()?;

                    // Check for (number) after identifier
                    if let Token::Symbol(ref sym) = self.current {
                        if sym == "(" {
                            self.advance()?;
                            if let Token::Number(n) = self.current {
                                oid_parts.push(n.to_string());
                                self.advance()?;
                            }
                            self.expect_symbol(")")?;
                        }
                    }
                }
                Token::Number(n) => {
                    oid_parts.push(n.to_string());
                    self.advance()?;
                }
                Token::Eof => {
                    return Err(ParseError {
                        message: "Unexpected end of input in module OID".to_string(),
                        line: self.lexer.line,
                        column: self.lexer.column,
                    });
                }
                _ => {
                    // Skip other tokens (like whitespace, etc.)
                    self.advance()?;
                }
            }
        }

        self.expect_symbol("}")?;
        Ok(oid_parts)
    }

    fn parse_definition(&mut self) -> Result<Definition> {
        let name = self.expect_identifier()?;

        // Skip optional parameterized type formal parameters after the type name,
        // e.g. `AttributeSet{ATTRIBUTE:AttrSet} ::= SEQUENCE { ... }`.
        // The parameter list carries governance information only; no DER encoding
        // information is lost by discarding it.
        if matches!(self.current, Token::Symbol(ref s) if s == "{") {
            self.skip_balanced_braces()?;
        }

        self.expect_symbol("::=")?;
        let ty = self.parse_type()?;

        // Skip any trailing constraint expression that follows the type definition
        // in 2009-syntax modules.  The most common case is the `(WITH COMPONENTS { ... })`
        // subtype constraint after a SEQUENCE or CHOICE, e.g.:
        //   `AuthorityKeyIdentifier ::= SEQUENCE { ... } (WITH COMPONENTS { ... })`
        // These are value-range / component presence constraints that carry no
        // encoding information synta needs; discarding them is safe.
        if matches!(self.current, Token::Symbol(ref s) if s == "(") {
            self.skip_balanced_parens()?;
        }

        Ok(Definition { name, ty })
    }

    /// Try to parse a value assignment (e.g., oidName OBJECT IDENTIFIER ::= { 1 2 3 })
    /// Returns None if this is not a value assignment (it's a type definition instead)
    fn try_parse_value_assignment(&mut self) -> Result<Option<crate::ast::ValueAssignment>> {
        // Look ahead to determine if this is a value assignment
        // Value assignment: name Type ::= value
        // Type definition: TypeName ::= Type
        // We can distinguish by checking if there's a type keyword before ::=

        // We need at least: IDENTIFIER KEYWORD ::=
        // For value assignment, the second token should be OBJECT, INTEGER, BOOLEAN, etc.
        let is_value_assignment = if let Token::Identifier(_) = &self.current {
            // Peek ahead - if it's a type keyword, it's likely a value assignment
            matches!(self.peek_next_token(), Token::Keyword(ref kw)
                if kw == "OBJECT" || kw == "INTEGER" || kw == "BOOLEAN")
        } else {
            false
        };

        if !is_value_assignment {
            return Ok(None);
        }

        // Parse value assignment
        let name = self.expect_identifier()?;
        let ty = self.parse_type()?;
        self.expect_symbol("::=")?;
        let value = self.parse_value(&ty)?;

        Ok(Some(crate::ast::ValueAssignment { name, ty, value }))
    }

    /// Try to consume a class alias assignment of the form:
    ///   `TypeName ::= TYPE-IDENTIFIER` or `TypeName ::= ABSTRACT-SYNTAX`
    ///
    /// These are X.681 §14.2 built-in class assignments that carry no concrete
    /// DER encoding.  Returning `true` causes the module parser to discard the
    /// definition without generating any Rust type.
    fn try_skip_class_alias(&mut self) -> Result<bool> {
        // Pattern: Identifier ::= (TYPE-IDENTIFIER | ABSTRACT-SYNTAX)
        // We peek: current = Identifier, next = ::=, after-next = keyword
        let is_ident = matches!(self.current, Token::Identifier(_));
        if !is_ident {
            return Ok(false);
        }

        // Save state so we can restore if this is NOT a class alias
        let saved_lexer = self.lexer.clone();
        let saved_current = self.current.clone();

        self.advance()?; // consume identifier

        // Must be followed by ::=
        if !matches!(self.current, Token::Symbol(ref s) if s == "::=") {
            self.lexer = saved_lexer;
            self.current = saved_current;
            return Ok(false);
        }
        self.advance()?; // consume ::=

        // Check if the RHS is a class-defining keyword
        let is_class_keyword = matches!(
            self.current,
            Token::Keyword(ref kw) if kw == "TYPE-IDENTIFIER" || kw == "ABSTRACT-SYNTAX"
        );

        if !is_class_keyword {
            // Restore and let parse_definition handle it
            self.lexer = saved_lexer;
            self.current = saved_current;
            return Ok(false);
        }

        // Consume the class keyword (and any trailing parts)
        self.advance()?;
        Ok(true)
    }

    /// Try to consume an Information Object Set assignment (X.681 §12), returning
    /// `true` if one was consumed and `false` if the current token is not the start
    /// of an IOC assignment.
    ///
    /// Pattern: `name ClassName ::= { ... }` where `ClassName` is an identifier
    /// (not a built-in keyword).  This distinguishes IOC assignments from:
    ///  - Type definitions (`TypeName ::= ...`) where `::=` immediately follows
    ///    the first identifier.
    ///  - Classic value assignments where the second token is a built-in keyword
    ///    (`OBJECT`, `INTEGER`, `BOOLEAN`), handled by `try_parse_value_assignment`.
    ///
    /// IOC assignments carry no DER type information and are discarded.
    fn try_skip_ioc_assignment(&mut self) -> Result<bool> {
        // An IOC assignment begins with Identifier (name) followed by Identifier
        // (class name) — neither the assignment operator nor a built-in keyword.
        let is_ioc = if let Token::Identifier(_) = &self.current {
            matches!(self.peek_next_token(), Token::Identifier(_))
        } else {
            false
        };

        if !is_ioc {
            return Ok(false);
        }

        // Save state so we can backtrack if the two-identifier sequence is not
        // actually an IOC assignment (i.e. the mandatory '::=' is absent).
        let saved_lexer = self.lexer.clone();
        let saved_current = self.current.clone();

        // Consume: name  ClassName  ::=  { ... }
        self.advance()?; // consume assignment name
        self.advance()?; // consume class name

        if !matches!(self.current, Token::Symbol(ref s) if s == "::=") {
            // Not an IOC assignment — restore state and let the caller handle it.
            self.lexer = saved_lexer;
            self.current = saved_current;
            return Ok(false);
        }
        self.advance()?; // consume ::=

        if matches!(self.current, Token::Symbol(ref s) if s == "{") {
            self.skip_balanced_braces()?;
        } else {
            // Scalar value — consume single token
            self.advance()?;
        }

        Ok(true)
    }

    /// Peek at the next token without consuming it
    fn peek_next_token(&mut self) -> Token {
        // Save current state
        let saved_lexer = self.lexer.clone();
        let saved_current = self.current.clone();

        // Consume current token and get next
        let _ = self.advance();
        let next = self.current.clone();

        // Restore state
        self.lexer = saved_lexer;
        self.current = saved_current;

        next
    }

    /// Parse a value based on its type
    fn parse_value(&mut self, ty: &Type) -> Result<crate::ast::Value> {
        match ty {
            Type::ObjectIdentifier => {
                // Parse OID value: { ... }
                self.expect_symbol("{")?;
                let mut components = Vec::new();

                while !matches!(self.current, Token::Symbol(ref sym) if sym == "}") {
                    if matches!(self.current, Token::Eof) {
                        return Err(ParseError {
                            message: "Unexpected EOF in OID value".to_string(),
                            line: self.lexer.line,
                            column: self.lexer.column,
                        });
                    }

                    // Parse OID component: a plain number, a named reference, or the
                    // `name(number)` form used by RFC module OIDs (e.g. `iso(1)`).
                    // When `name(number)` is used, the numeric value is authoritative
                    // and the name is discarded.
                    match &self.current {
                        Token::Number(n) => {
                            components.push(crate::ast::OidComponent::Number(*n));
                            self.advance()?;
                        }
                        Token::Identifier(name) => {
                            let id = name.clone();
                            self.advance()?;
                            // Check for (number) suffix — `iso(1)`, `us(840)`, etc.
                            if matches!(self.current, Token::Symbol(ref s) if s == "(") {
                                self.advance()?; // consume '('
                                if let Token::Number(n) = self.current {
                                    self.advance()?;
                                    self.expect_symbol(")")?;
                                    components.push(crate::ast::OidComponent::Number(n));
                                } else {
                                    self.expect_symbol(")")?;
                                    components.push(crate::ast::OidComponent::NamedRef(id));
                                }
                            } else {
                                components.push(crate::ast::OidComponent::NamedRef(id));
                            }
                        }
                        _ => {
                            return Err(ParseError {
                                message: format!(
                                    "Expected number or identifier in OID value, got {:?}",
                                    self.current
                                ),
                                line: self.lexer.line,
                                column: self.lexer.column,
                            });
                        }
                    }
                }

                self.expect_symbol("}")?;
                Ok(crate::ast::Value::ObjectIdentifier(components))
            }
            Type::Integer(_, _) => {
                // Parse integer value
                if let Token::Number(n) = self.current {
                    self.advance()?;
                    Ok(crate::ast::Value::Integer(n as i64))
                } else {
                    Err(ParseError {
                        message: format!(
                            "Expected number for INTEGER value, got {:?}",
                            self.current
                        ),
                        line: self.lexer.line,
                        column: self.lexer.column,
                    })
                }
            }
            Type::Boolean => {
                // Parse boolean value
                match &self.current {
                    Token::Keyword(kw) if kw == "TRUE" => {
                        self.advance()?;
                        Ok(crate::ast::Value::Boolean(true))
                    }
                    Token::Keyword(kw) if kw == "FALSE" => {
                        self.advance()?;
                        Ok(crate::ast::Value::Boolean(false))
                    }
                    _ => Err(ParseError {
                        message: format!(
                            "Expected TRUE or FALSE for BOOLEAN value, got {:?}",
                            self.current
                        ),
                        line: self.lexer.line,
                        column: self.lexer.column,
                    }),
                }
            }
            _ => Err(ParseError {
                message: format!("Value assignments not supported for type {:?}", ty),
                line: self.lexer.line,
                column: self.lexer.column,
            }),
        }
    }

    fn parse_type(&mut self) -> Result<Type> {
        // Check for tagged type
        if let Token::Symbol(ref sym) = self.current {
            if sym == "[" {
                return self.parse_tagged_type();
            }
        }

        if let Token::Keyword(ref kw) = self.current.clone() {
            match kw.as_str() {
                "SEQUENCE" => {
                    self.advance()?;
                    // Handle SIZE constraint before OF: `SEQUENCE SIZE (1..MAX) OF ...`
                    if matches!(self.current, Token::Keyword(ref k) if k == "SIZE") {
                        self.advance()?; // consume SIZE
                                         // Skip the (min..max) constraint
                                         // Skip the (min..max) constraint
                        if matches!(self.current, Token::Symbol(ref s) if s == "(") {
                            self.skip_balanced_parens()?;
                        }
                    }
                    if matches!(self.current, Token::Keyword(ref k) if k == "OF") {
                        self.advance()?;
                        let inner = self.parse_type()?;
                        let size_constraint = self.parse_size_constraint()?;
                        return Ok(Type::SequenceOf(Box::new(inner), size_constraint));
                    }
                    self.expect_symbol("{")?;
                    let fields = self.parse_sequence_fields()?;
                    self.expect_symbol("}")?;
                    return Ok(Type::Sequence(fields));
                }
                "SET" => {
                    self.advance()?;
                    // Handle SIZE constraint before OF: `SET SIZE (1..MAX) OF ...`
                    if matches!(self.current, Token::Keyword(ref k) if k == "SIZE") {
                        self.advance()?; // consume SIZE
                                         // Skip the (min..max) constraint
                                         // Skip the (min..max) constraint
                        if matches!(self.current, Token::Symbol(ref s) if s == "(") {
                            self.skip_balanced_parens()?;
                        }
                    }
                    if matches!(self.current, Token::Keyword(ref k) if k == "OF") {
                        self.advance()?;
                        let inner = self.parse_type()?;
                        let size_constraint = self.parse_size_constraint()?;
                        return Ok(Type::SetOf(Box::new(inner), size_constraint));
                    }
                    self.expect_symbol("{")?;
                    let fields = self.parse_sequence_fields()?;
                    self.expect_symbol("}")?;
                    return Ok(Type::Set(fields));
                }
                "CHOICE" => {
                    self.advance()?;
                    self.expect_symbol("{")?;
                    let variants = self.parse_choice_variants()?;
                    self.expect_symbol("}")?;
                    return Ok(Type::Choice(variants));
                }
                "INTEGER" => {
                    self.advance()?;

                    // Check for named number list: INTEGER {name(value), ...}
                    let named_numbers = if matches!(self.current, Token::Symbol(ref s) if s == "{")
                    {
                        self.advance()?; // consume '{'
                        let numbers = self.parse_named_numbers()?;
                        self.expect_symbol("}")?;
                        numbers
                    } else {
                        Vec::new()
                    };

                    // Check for X.680 constraint
                    if matches!(self.current, Token::Symbol(ref s) if s == "(") {
                        self.advance()?; // consume '('
                        let constraint = self.parse_subtype_constraint()?;
                        self.expect_symbol(")")?;

                        // Create X.680 constrained type
                        return Ok(Type::Constrained {
                            base_type: Box::new(Type::Integer(None, named_numbers)),
                            constraint: Constraint {
                                spec: ConstraintSpec::Subtype(constraint),
                                exception: None,
                            },
                        });
                    }

                    // Return INTEGER with optional named numbers
                    return Ok(Type::Integer(None, named_numbers));
                }
                "ENUMERATED" => {
                    self.advance()?;

                    // ENUMERATED must have named values
                    self.expect_symbol("{")?;
                    let named_values = self.parse_named_numbers()?;
                    self.expect_symbol("}")?;

                    if named_values.is_empty() {
                        return Err(ParseError {
                            message: "ENUMERATED must have at least one named value".to_string(),
                            line: self.lexer.line,
                            column: self.lexer.column,
                        });
                    }

                    return Ok(Type::Enumerated(named_values));
                }
                "REAL" => {
                    self.advance()?;
                    return Ok(Type::Real);
                }
                "BOOLEAN" => {
                    self.advance()?;
                    return Ok(Type::Boolean);
                }
                "OCTET" => {
                    self.advance()?;
                    self.expect_keyword("STRING")?;

                    // Check for X.680 string constraints (SIZE, FROM, PATTERN)
                    if let Some(constraint) = self.parse_string_constraint()? {
                        return Ok(Type::Constrained {
                            base_type: Box::new(Type::OctetString(None)),
                            constraint: Constraint {
                                spec: ConstraintSpec::Subtype(constraint),
                                exception: None,
                            },
                        });
                    }

                    return Ok(Type::OctetString(None));
                }
                "BIT" => {
                    self.advance()?;
                    self.expect_keyword("STRING")?;

                    // Check for named bit list: { bitName(n), ... }
                    let named_bits = if matches!(self.current, Token::Symbol(ref s) if s == "{") {
                        self.advance()?; // consume '{'
                        let bits = self.parse_named_numbers()?;
                        self.expect_symbol("}")?;
                        bits
                    } else {
                        Vec::new()
                    };

                    // Check for X.680 string constraints (SIZE, FROM, PATTERN)
                    if let Some(size_constraint) = self.parse_string_constraint()? {
                        if named_bits.is_empty() {
                            return Ok(Type::Constrained {
                                base_type: Box::new(Type::BitString(None)),
                                constraint: Constraint {
                                    spec: ConstraintSpec::Subtype(size_constraint),
                                    exception: None,
                                },
                            });
                        } else {
                            // Named bits + size constraint: use Intersection
                            return Ok(Type::Constrained {
                                base_type: Box::new(Type::BitString(None)),
                                constraint: Constraint {
                                    spec: ConstraintSpec::Subtype(SubtypeConstraint::Intersection(
                                        vec![
                                            SubtypeConstraint::NamedBitList(named_bits),
                                            size_constraint,
                                        ],
                                    )),
                                    exception: None,
                                },
                            });
                        }
                    }

                    if !named_bits.is_empty() {
                        return Ok(Type::Constrained {
                            base_type: Box::new(Type::BitString(None)),
                            constraint: Constraint {
                                spec: ConstraintSpec::Subtype(SubtypeConstraint::NamedBitList(
                                    named_bits,
                                )),
                                exception: None,
                            },
                        });
                    }

                    return Ok(Type::BitString(None));
                }
                "OBJECT" => {
                    self.advance()?;
                    self.expect_keyword("IDENTIFIER")?;
                    return Ok(Type::ObjectIdentifier);
                }
                "NULL" => {
                    self.advance()?;
                    return Ok(Type::Null);
                }
                "UTF8String" => return self.parse_string_type(Type::Utf8String(None)),
                "PrintableString" => return self.parse_string_type(Type::PrintableString(None)),
                "IA5String" => return self.parse_string_type(Type::IA5String(None)),
                "TeletexString" | "T61String" => {
                    return self.parse_string_type(Type::TeletexString(None))
                }
                "UniversalString" => return self.parse_string_type(Type::UniversalString(None)),
                "BMPString" => return self.parse_string_type(Type::BmpString(None)),
                "GeneralString" => return self.parse_string_type(Type::GeneralString(None)),
                "NumericString" => return self.parse_string_type(Type::NumericString(None)),
                "VisibleString" => return self.parse_string_type(Type::VisibleString(None)),
                "UTCTime" => {
                    self.advance()?;
                    return Ok(Type::UtcTime);
                }
                "GeneralizedTime" => {
                    self.advance()?;
                    return Ok(Type::GeneralizedTime);
                }
                "ANY" => {
                    self.advance()?;
                    // Check for "DEFINED BY fieldname"
                    if matches!(self.current, Token::Keyword(ref kw) if kw == "DEFINED") {
                        self.advance()?; // consume DEFINED
                        self.expect_keyword("BY")?;
                        let field_name = self.expect_identifier()?;
                        return Ok(Type::AnyDefinedBy(field_name));
                    }
                    return Ok(Type::Any);
                }
                "CLASS" => {
                    self.advance()?;
                    return self.parse_class_body();
                }
                // Built-in information object classes used as type aliases (X.681 §14).
                // `TYPE-IDENTIFIER` and `ABSTRACT-SYNTAX` are class names that appear in
                // type-assignment position (e.g. `MyClass ::= TYPE-IDENTIFIER`).  Treat
                // them as ANY since they carry no concrete DER structure.
                "TYPE-IDENTIFIER" | "ABSTRACT-SYNTAX" => {
                    self.advance()?;
                    return Ok(Type::Any);
                }
                _ => {}
            }
        }

        // Type reference - accept both identifiers and keywords that represent built-in types
        // Per X.680, built-in types like TeletexString, BMPString, etc. are keywords but can be used as types
        let type_name = if let Token::Identifier(name) = &self.current {
            Some(name.clone())
        } else if let Token::Keyword(kw) = &self.current {
            // Allow built-in type names that are keywords but should be usable as types
            if is_builtin_type_keyword(kw) {
                Some(kw.clone())
            } else {
                None
            }
        } else {
            None
        };

        if let Some(result) = type_name {
            self.advance()?;

            // Skip optional parameterized type arguments,
            // e.g. `AlgorithmIdentifier{ KEM-ALGORITHM, {KEMAlgSet} }`.
            // The type is still resolved as a plain TypeRef; the parameter set
            // carries no DER encoding information.
            if matches!(self.current, Token::Symbol(ref s) if s == "{") {
                self.skip_balanced_braces()?;
            }

            // Handle `INSTANCE OF TypeName` (X.681 §14) — treat as ANY.
            // The `INSTANCE` identifier is already consumed as the TypeRef name.
            // The `OF` keyword and following class name are discarded.
            if result == "INSTANCE" && matches!(self.current, Token::Keyword(ref k) if k == "OF") {
                self.advance()?; // consume OF
                                 // Consume the class name (identifier)
                                 // Consume the class name (identifier)
                self.advance()?;
                // Skip optional parameterized arguments
                if matches!(self.current, Token::Symbol(ref s) if s == "{") {
                    self.skip_balanced_braces()?;
                }
                return Ok(Type::Any);
            }

            // Handle IOC field access notation: `ClassName.&field({params})`.
            // This appears in 2009-syntax modules as a field type, e.g.:
            //   `type  ATTRIBUTE.&id({AttrSet})`
            //   `parameters  ALGORITHM-TYPE.&Params({AlgorithmSet}{@algorithm}) OPTIONAL`
            //
            // For `&id` fields, the class definition always constrains the type to
            // `OBJECT IDENTIFIER UNIQUE`, so we resolve these to ObjectIdentifier.
            // All other IOC field accesses are treated as ANY (Type::Any).
            if matches!(self.current, Token::Symbol(ref s) if s == ".") {
                self.advance()?; // consume '.'
                                 // Consume the &field identifier and remember its name
                                 // Consume the &field identifier and remember its name
                let field_name = if let Token::Identifier(ref name) = self.current {
                    let n = name.clone();
                    self.advance()?;
                    n
                } else {
                    self.advance()?;
                    String::new()
                };
                // Skip any optional parameterized argument groups {..} or (..) after the field name
                loop {
                    if matches!(self.current, Token::Symbol(ref s) if s == "{") {
                        self.skip_balanced_braces()?;
                    } else if matches!(self.current, Token::Symbol(ref s) if s == "(") {
                        self.skip_balanced_parens()?;
                    } else {
                        break;
                    }
                }
                // Resolve &id to ObjectIdentifier (X.681 convention: &id fields are OIDs)
                if field_name == "&id" {
                    return Ok(Type::ObjectIdentifier);
                }
                return Ok(Type::Any);
            }

            // Check for constraint on type reference (subtype definition)
            if matches!(self.current, Token::Symbol(ref s) if s == "(") {
                // Peek ahead to determine if this is a string constraint or value constraint
                self.advance()?; // consume '('

                // Check if current token (after '(') is a string constraint keyword
                let is_string_constraint = if let Token::Keyword(ref kw) = self.current {
                    matches!(kw.as_str(), "SIZE" | "FROM" | "PATTERN" | "CONTAINING")
                } else {
                    false
                };

                // Parse the appropriate constraint type
                let constraint = if is_string_constraint {
                    // Parse string constraint (SIZE, FROM, PATTERN)
                    let mut constraints = Vec::new();

                    while !matches!(self.current, Token::Symbol(ref s) if s == ")") {
                        if matches!(self.current, Token::Eof) {
                            break;
                        }

                        if let Some(c) = self.parse_single_string_constraint()? {
                            constraints.push(c);
                        } else {
                            break;
                        }
                    }

                    self.expect_symbol(")")?;

                    match constraints.len() {
                        0 => {
                            return Err(ParseError {
                                message: "Expected string constraint".to_string(),
                                line: self.lexer.line,
                                column: self.lexer.column,
                            })
                        }
                        1 => constraints.into_iter().next().unwrap(),
                        _ => SubtypeConstraint::Intersection(constraints),
                    }
                } else {
                    // Parse value constraint (integer ranges, etc.)
                    let c = self.parse_subtype_constraint()?;
                    self.expect_symbol(")")?;
                    c
                };

                // Create X.680 constrained type with TypeRef as base
                return Ok(Type::Constrained {
                    base_type: Box::new(Type::TypeRef(result)),
                    constraint: Constraint {
                        spec: ConstraintSpec::Subtype(constraint),
                        exception: None,
                    },
                });
            }

            return Ok(Type::TypeRef(result));
        }

        Err(ParseError {
            message: format!("Expected type, got {:?}", self.current),
            line: self.lexer.line,
            column: self.lexer.column,
        })
    }

    fn parse_tagged_type(&mut self) -> Result<Type> {
        self.expect_symbol("[")?;

        // Check for optional tag class keyword: APPLICATION, UNIVERSAL, PRIVATE
        let class = if matches!(self.current, Token::Keyword(ref kw) if kw == "APPLICATION") {
            self.advance()?;
            TagClass::Application
        } else if matches!(self.current, Token::Keyword(ref kw) if kw == "UNIVERSAL") {
            self.advance()?;
            TagClass::Universal
        } else if matches!(self.current, Token::Keyword(ref kw) if kw == "PRIVATE") {
            self.advance()?;
            TagClass::Private
        } else {
            TagClass::ContextSpecific
        };

        let number = if let Token::Number(n) = self.current {
            self.advance()?;
            n
        } else {
            return Err(ParseError {
                message: "Expected tag number".to_string(),
                line: self.lexer.line,
                column: self.lexer.column,
            });
        };

        self.expect_symbol("]")?;

        // Check for EXPLICIT or IMPLICIT
        let tagging = if matches!(self.current, Token::Keyword(ref kw) if kw == "EXPLICIT") {
            self.advance()?;
            Tagging::Explicit
        } else if matches!(self.current, Token::Keyword(ref kw) if kw == "IMPLICIT") {
            self.advance()?;
            Tagging::Implicit
        } else {
            self.default_tagging.clone() // use the module-level default
        };

        let inner = self.parse_type()?;

        Ok(Type::Tagged {
            tag: TagInfo {
                class,
                number,
                tagging,
            },
            inner: Box::new(inner),
        })
    }

    fn parse_sequence_fields(&mut self) -> Result<Vec<SequenceField>> {
        let mut fields = Vec::new();

        while !matches!(self.current, Token::Symbol(ref s) if s == "}") {
            if matches!(self.current, Token::Eof) {
                break;
            }

            // Skip extension markers (...)
            if matches!(self.current, Token::Symbol(ref s) if s == "...") {
                self.advance()?;
                if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                    self.advance()?;
                }
                continue;
            }

            // Handle version extension addition groups: [[N: field1, field2, ... ]]
            // These are used in 2009-syntax modules to group optional extension fields
            // by version number.  The contained fields are flattened into the SEQUENCE.
            if matches!(self.current, Token::Symbol(ref s) if s == "[") {
                // Peek to see if the next token is also '[' (double bracket)
                let saved_lexer = self.lexer.clone();
                let saved_current = self.current.clone();
                self.advance()?; // consume first '['
                if matches!(self.current, Token::Symbol(ref s) if s == "[") {
                    self.advance()?; // consume second '['
                                     // Skip optional version number and colon: N:
                    if let Token::Number(_) = self.current {
                        self.advance()?; // consume N
                    }
                    if matches!(self.current, Token::Symbol(ref s) if s == ":") {
                        self.advance()?; // consume ':'
                    }
                    // Parse fields until ']]'
                    while !matches!(self.current, Token::Symbol(ref s) if s == "]" || s == "}") {
                        if matches!(self.current, Token::Eof) {
                            break;
                        }
                        // Skip extension markers inside the group
                        if matches!(self.current, Token::Symbol(ref s) if s == "...") {
                            self.advance()?;
                            if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                                self.advance()?;
                            }
                            continue;
                        }
                        let fname = self.expect_identifier()?;
                        let fty = self.parse_type()?;
                        let foptional = if matches!(self.current, Token::Keyword(ref kw) if kw == "OPTIONAL")
                        {
                            self.advance()?;
                            true
                        } else {
                            false
                        };
                        let fdefault = if matches!(self.current, Token::Keyword(ref kw) if kw == "DEFAULT")
                        {
                            self.advance()?;
                            let dv = self.parse_default_value()?;
                            Some(dv)
                        } else {
                            None
                        };
                        fields.push(SequenceField {
                            name: fname,
                            ty: fty,
                            optional: foptional,
                            default: fdefault,
                        });
                        if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                            self.advance()?;
                        }
                    }
                    // Consume closing ']]'
                    if matches!(self.current, Token::Symbol(ref s) if s == "]") {
                        self.advance()?; // first ']'
                    }
                    if matches!(self.current, Token::Symbol(ref s) if s == "]") {
                        self.advance()?; // second ']'
                    }
                    if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                        self.advance()?;
                    }
                    continue;
                } else {
                    // Not a double bracket — restore and fall through to normal parsing
                    self.lexer = saved_lexer;
                    self.current = saved_current;
                }
            }

            let name = self.expect_identifier()?;
            let ty = self.parse_type()?;

            let optional = if matches!(self.current, Token::Keyword(ref kw) if kw == "OPTIONAL") {
                self.advance()?;
                true
            } else {
                false
            };

            let default = if matches!(self.current, Token::Keyword(ref kw) if kw == "DEFAULT") {
                self.advance()?;
                // Parse the default value
                let default_value = self.parse_default_value()?;
                Some(default_value)
            } else {
                None
            };

            fields.push(SequenceField {
                name,
                ty,
                optional,
                default,
            });

            if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                self.advance()?;
            }
        }

        Ok(fields)
    }

    fn parse_choice_variants(&mut self) -> Result<Vec<ChoiceVariant>> {
        let mut variants = Vec::new();

        while !matches!(self.current, Token::Symbol(ref s) if s == "}") {
            if matches!(self.current, Token::Eof) {
                break;
            }

            // Skip extension markers (...)
            if matches!(self.current, Token::Symbol(ref s) if s == "...") {
                self.advance()?;
                if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                    self.advance()?;
                }
                continue;
            }

            let name = self.expect_identifier()?;
            let ty = self.parse_type()?;

            variants.push(ChoiceVariant { name, ty });

            if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                self.advance()?;
            }
        }

        Ok(variants)
    }

    /// Parse an ASN.1 Information Object Class body (X.681 §9).
    ///
    /// Called after the `CLASS` keyword has been consumed.  Parses:
    ///
    /// ```text
    /// CLASS { &field [TYPE] [UNIQUE] [OPTIONAL] [DEFAULT value], ... }
    ///         [WITH SYNTAX { ... }]
    /// ```
    ///
    /// The `WITH SYNTAX` block (if present) is consumed and discarded — its
    /// content is arbitrary keyword syntax and has no DER representation.
    /// The resulting [`Type::Class`] stores only the field names and the
    /// `UNIQUE`/`OPTIONAL` qualifiers; actual type expressions within the
    /// class body are also consumed and discarded.
    fn parse_class_body(&mut self) -> Result<Type> {
        self.expect_symbol("{")?;

        let mut fields = Vec::new();

        while !matches!(self.current, Token::Symbol(ref s) if s == "}") {
            if matches!(self.current, Token::Eof) {
                break;
            }

            // Skip extension markers
            if matches!(self.current, Token::Symbol(ref s) if s == "...") {
                self.advance()?;
                if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                    self.advance()?;
                }
                continue;
            }

            // Each field begins with &name
            let field_name = if let Token::Identifier(ref id) = self.current {
                if id.starts_with('&') {
                    let name = id.strip_prefix('&').unwrap_or(id).to_string();
                    self.advance()?;
                    name
                } else {
                    // Not a field reference — skip token and try to recover
                    self.advance()?;
                    continue;
                }
            } else {
                // Non-identifier token — skip and recover
                self.advance()?;
                continue;
            };

            // Consume optional type expression and qualifiers until ',', '}', or '...'
            // We track brace depth to handle nested { } in DEFAULT values.
            let mut unique = false;
            let mut optional = false;
            let mut depth = 0usize;

            loop {
                match &self.current {
                    Token::Symbol(ref s) if s == "}" && depth == 0 => break,
                    Token::Symbol(ref s) if s == "," && depth == 0 => break,
                    Token::Symbol(ref s) if s == "..." && depth == 0 => break,
                    Token::Symbol(ref s) if s == "{" => {
                        depth += 1;
                        self.advance()?;
                    }
                    Token::Symbol(ref s) if s == "}" => {
                        depth -= 1;
                        self.advance()?;
                    }
                    Token::Keyword(ref kw) if kw == "UNIQUE" && depth == 0 => {
                        unique = true;
                        self.advance()?;
                    }
                    Token::Keyword(ref kw) if kw == "OPTIONAL" && depth == 0 => {
                        optional = true;
                        self.advance()?;
                    }
                    Token::Eof => break,
                    _ => {
                        self.advance()?;
                    }
                }
            }

            fields.push(ClassField {
                name: field_name,
                unique,
                optional,
            });

            if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                self.advance()?;
            }
        }

        self.expect_symbol("}")?;

        // Consume optional WITH SYNTAX { ... } block
        if matches!(self.current, Token::Keyword(ref kw) if kw == "WITH") {
            self.advance()?; // consume WITH
            if matches!(self.current, Token::Keyword(ref kw) if kw == "SYNTAX") {
                self.advance()?; // consume SYNTAX
                                 // The syntax block is a balanced { ... } with arbitrary token content
                self.skip_balanced_braces()?;
            }
        }

        Ok(Type::Class(fields))
    }

    /// Consume a balanced `{ ... }` block, discarding all tokens inside.
    ///
    /// Handles nested braces.  Assumes the opening `{` is the current token.
    fn skip_balanced_braces(&mut self) -> Result<()> {
        self.expect_symbol("{")?;
        let mut depth = 1usize;
        while depth > 0 {
            match &self.current {
                Token::Symbol(ref s) if s == "{" => {
                    depth += 1;
                    self.advance()?;
                }
                Token::Symbol(ref s) if s == "}" => {
                    depth -= 1;
                    self.advance()?;
                }
                Token::Eof => {
                    return Err(ParseError {
                        message: "Unexpected EOF inside braced block".to_string(),
                        line: self.lexer.line,
                        column: self.lexer.column,
                    });
                }
                _ => {
                    self.advance()?;
                }
            }
        }
        Ok(())
    }

    /// Consume a balanced `( ... )` block, discarding all tokens inside.
    ///
    /// Used to skip parameterized argument groups in IOC field access expressions,
    /// e.g. the `({AttrSet})` and `({AttrSet}{@type})` parts of
    /// `ATTRIBUTE.&id({AttrSet})` and `ATTRIBUTE.&Type({AttrSet}{@type})`.
    fn skip_balanced_parens(&mut self) -> Result<()> {
        self.expect_symbol("(")?;
        let mut depth = 1usize;
        while depth > 0 {
            match &self.current {
                Token::Symbol(ref s) if s == "(" => {
                    depth += 1;
                    self.advance()?;
                }
                Token::Symbol(ref s) if s == ")" => {
                    depth -= 1;
                    self.advance()?;
                }
                Token::Eof => {
                    return Err(ParseError {
                        message: "Unexpected EOF inside parenthesized block".to_string(),
                        line: self.lexer.line,
                        column: self.lexer.column,
                    });
                }
                _ => {
                    self.advance()?;
                }
            }
        }
        Ok(())
    }

    /// Parse named number list: name1(value1), name2(value2), ...
    fn parse_named_numbers(&mut self) -> Result<Vec<NamedNumber>> {
        let mut numbers = Vec::new();

        while !matches!(self.current, Token::Symbol(ref s) if s == "}") {
            if matches!(self.current, Token::Eof) {
                break;
            }

            // Skip extension markers (...)
            if matches!(self.current, Token::Symbol(ref s) if s == "...") {
                self.advance()?;
                if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                    self.advance()?;
                }
                continue;
            }

            // Parse name
            let name = self.expect_identifier()?;

            // Optional explicit numeric value: name(N)
            // If absent, auto-number (X.680 §19.5 auto-numbering for ENUMERATED).
            let value = if matches!(self.current, Token::Symbol(ref s) if s == "(") {
                self.advance()?; // consume '('
                let v = self.parse_integer_value()?.ok_or_else(|| ParseError {
                    message: "Expected number value for named number".to_string(),
                    line: self.lexer.line,
                    column: self.lexer.column,
                })?;
                self.expect_symbol(")")?;
                v
            } else {
                // Auto-number: next value after the last one (or 0 for first)
                numbers
                    .last()
                    .map(|n: &NamedNumber| n.value + 1)
                    .unwrap_or(0)
            };

            numbers.push(NamedNumber { name, value });

            // Optional comma
            if matches!(self.current, Token::Symbol(ref s) if s == ",") {
                self.advance()?;
            }
        }

        Ok(numbers)
    }
}

/// Parse an ASN.1 module from a string
pub fn parse(input: &str) -> Result<Module> {
    let mut parser = Parser::new(input)?;
    parser.parse_module()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_simple_sequence() {
        let input = r#"
            TestModule DEFINITIONS ::= BEGIN
                SimpleSeq ::= SEQUENCE {
                    field1 INTEGER,
                    field2 OCTET STRING
                }
            END
        "#;

        let module = parse(input).unwrap();
        assert_eq!(module.name, "TestModule");
        assert_eq!(module.definitions.len(), 1);

        let def = &module.definitions[0];
        assert_eq!(def.name, "SimpleSeq");

        if let Type::Sequence(fields) = &def.ty {
            assert_eq!(fields.len(), 2);
            assert_eq!(fields[0].name, "field1");
            assert!(matches!(fields[0].ty, Type::Integer(_, _)));
        } else {
            panic!("Expected SEQUENCE type");
        }
    }

    #[test]
    fn test_parse_choice() {
        let input = r#"
            TestModule DEFINITIONS ::= BEGIN
                MyChoice ::= CHOICE {
                    option1 INTEGER,
                    option2 BOOLEAN
                }
            END
        "#;

        let module = parse(input).unwrap();
        let def = &module.definitions[0];

        if let Type::Choice(variants) = &def.ty {
            assert_eq!(variants.len(), 2);
            assert_eq!(variants[0].name, "option1");
        } else {
            panic!("Expected CHOICE type");
        }
    }

    #[test]
    fn test_parse_tagged_type() {
        let input = r#"
            TestModule DEFINITIONS ::= BEGIN
                TaggedSeq ::= SEQUENCE {
                    field1 [0] EXPLICIT INTEGER,
                    field2 [1] IMPLICIT OCTET STRING
                }
            END
        "#;

        let module = parse(input).unwrap();
        let def = &module.definitions[0];

        if let Type::Sequence(fields) = &def.ty {
            if let Type::Tagged { tag, .. } = &fields[0].ty {
                assert_eq!(tag.number, 0);
                assert_eq!(tag.tagging, Tagging::Explicit);
            } else {
                panic!("Expected tagged type");
            }
        } else {
            panic!("Expected SEQUENCE type");
        }
    }

    #[test]
    fn test_implicit_tags_module_default() {
        // In a "DEFINITIONS IMPLICIT TAGS" module, a bare [N] tag (no EXPLICIT/IMPLICIT keyword)
        // must default to IMPLICIT.  An explicitly-marked [N] EXPLICIT must remain EXPLICIT.
        let input = r#"
            TestModule DEFINITIONS IMPLICIT TAGS ::= BEGIN
                TaggedSeq ::= SEQUENCE {
                    field1 [0] INTEGER,
                    field2 [1] EXPLICIT OCTET STRING,
                    field3 [2] IMPLICIT BOOLEAN
                }
            END
        "#;

        let module = parse(input).unwrap();
        assert_eq!(module.tagging_mode, Some(crate::ast::TaggingMode::Implicit));
        let def = &module.definitions[0];
        if let Type::Sequence(fields) = &def.ty {
            // bare [0] — should inherit IMPLICIT from module header
            if let Type::Tagged { tag, .. } = &fields[0].ty {
                assert_eq!(tag.number, 0);
                assert_eq!(
                    tag.tagging,
                    Tagging::Implicit,
                    "bare tag should be IMPLICIT in IMPLICIT TAGS module"
                );
            } else {
                panic!("Expected tagged type for field1");
            }
            // [1] EXPLICIT — explicit keyword overrides module default
            if let Type::Tagged { tag, .. } = &fields[1].ty {
                assert_eq!(tag.number, 1);
                assert_eq!(
                    tag.tagging,
                    Tagging::Explicit,
                    "[1] EXPLICIT should stay EXPLICIT"
                );
            } else {
                panic!("Expected tagged type for field2");
            }
            // [2] IMPLICIT — explicit keyword matches module default
            if let Type::Tagged { tag, .. } = &fields[2].ty {
                assert_eq!(tag.number, 2);
                assert_eq!(tag.tagging, Tagging::Implicit);
            } else {
                panic!("Expected tagged type for field3");
            }
        } else {
            panic!("Expected SEQUENCE type");
        }
    }

    #[test]
    fn test_explicit_tags_module_default() {
        // In a "DEFINITIONS EXPLICIT TAGS" module (or no keyword — same thing), a bare [N]
        // tag must default to EXPLICIT.
        let input = r#"
            TestModule DEFINITIONS EXPLICIT TAGS ::= BEGIN
                TaggedSeq ::= SEQUENCE {
                    field1 [0] INTEGER
                }
            END
        "#;

        let module = parse(input).unwrap();
        let def = &module.definitions[0];
        if let Type::Sequence(fields) = &def.ty {
            if let Type::Tagged { tag, .. } = &fields[0].ty {
                assert_eq!(tag.number, 0);
                assert_eq!(
                    tag.tagging,
                    Tagging::Explicit,
                    "bare tag should be EXPLICIT in EXPLICIT TAGS module"
                );
            } else {
                panic!("Expected tagged type");
            }
        } else {
            panic!("Expected SEQUENCE type");
        }
    }

    #[test]
    fn test_parse_optional_field() {
        let input = r#"
            TestModule DEFINITIONS ::= BEGIN
                OptSeq ::= SEQUENCE {
                    required INTEGER,
                    optional BOOLEAN OPTIONAL
                }
            END
        "#;

        let module = parse(input).unwrap();
        let def = &module.definitions[0];

        if let Type::Sequence(fields) = &def.ty {
            assert!(!fields[0].optional);
            assert!(fields[1].optional);
        } else {
            panic!("Expected SEQUENCE type");
        }
    }

    #[test]
    fn test_parse_value_constraint_range() {
        let input = r#"
            TestModule DEFINITIONS ::= BEGIN
                Int32 ::= INTEGER (-2147483648..2147483647)
            END
        "#;

        let module = parse(input).unwrap();
        let def = &module.definitions[0];

        assert_eq!(def.name, "Int32");
        // Now expects X.680 Constrained type
        if let Type::Constrained {
            base_type,
            constraint,
        } = &def.ty
        {
            assert!(matches!(base_type.as_ref(), Type::Integer(None, _)));
            if let ConstraintSpec::Subtype(SubtypeConstraint::ValueRange { min, max }) =
                &constraint.spec
            {
                assert_eq!(*min, ConstraintValue::Integer(-2147483648));
                assert_eq!(*max, ConstraintValue::Integer(2147483647));
            } else {
                panic!("Expected SubtypeConstraint::ValueRange");
            }
        } else {
            panic!("Expected Constrained type");
        }
    }

    #[test]
    fn test_parse_value_constraint_single() {
        let input = r#"
            TestModule DEFINITIONS ::= BEGIN
                FixedValue ::= INTEGER (42)
            END
        "#;

        let module = parse(input).unwrap();
        let def = &module.definitions[0];

        // Now expects X.680 Constrained type
        if let Type::Constrained {
            base_type,
            constraint,
        } = &def.ty
        {
            assert!(matches!(base_type.as_ref(), Type::Integer(None, _)));
            if let ConstraintSpec::Subtype(SubtypeConstraint::SingleValue(val)) = &constraint.spec {
                assert_eq!(*val, ConstraintValue::Integer(42));
            } else {
                panic!("Expected SubtypeConstraint::SingleValue");
            }
        } else {
            panic!("Expected Constrained type");
        }
    }

    #[test]
    fn test_parse_size_constraint() {
        // Note: SIZE constraints are parsed but currently skipped
        // This test verifies that OCTET STRING with SIZE parses without error
        let input = r#"
TestModule DEFINITIONS ::= BEGIN
    ShortString ::= OCTET STRING
END
        "#;

        let module = parse(input).unwrap();
        let def = &module.definitions[0];

        // For now, OCTET STRING without constraint should parse fine
        assert!(matches!(def.ty, Type::OctetString(_)));
    }

    // X.680 Constraint Tests

    #[test]
    fn test_parse_constraint_value_min_max() {
        let mut parser = Parser::new("MIN..MAX").unwrap();

        let value1 = parser.parse_constraint_value().unwrap();
        assert_eq!(value1, ConstraintValue::Min);

        parser.expect_symbol("..").unwrap();

        let value2 = parser.parse_constraint_value().unwrap();
        assert_eq!(value2, ConstraintValue::Max);
    }

    #[test]
    fn test_parse_constraint_value_integer() {
        let mut parser = Parser::new("42").unwrap();

        let value = parser.parse_constraint_value().unwrap();
        assert_eq!(value, ConstraintValue::Integer(42));
    }

    #[test]
    fn test_parse_constraint_value_negative() {
        let mut parser = Parser::new("-100").unwrap();

        let value = parser.parse_constraint_value().unwrap();
        assert_eq!(value, ConstraintValue::Integer(-100));
    }

    #[test]
    fn test_parse_constraint_value_named() {
        let mut parser = Parser::new("maxValue").unwrap();

        let value = parser.parse_constraint_value().unwrap();
        assert_eq!(value, ConstraintValue::NamedValue("maxValue".to_string()));
    }

    #[test]
    fn test_parse_single_value_constraint() {
        let mut parser = Parser::new("42").unwrap();

        let constraint = parser.parse_single_constraint().unwrap();
        assert_eq!(
            constraint,
            SubtypeConstraint::SingleValue(ConstraintValue::Integer(42))
        );
    }

    #[test]
    fn test_parse_value_range_constraint() {
        let mut parser = Parser::new("0..100").unwrap();

        let constraint = parser.parse_single_constraint().unwrap();
        assert!(matches!(constraint, SubtypeConstraint::ValueRange { .. }));
    }

    #[test]
    fn test_parse_min_max_range() {
        let mut parser = Parser::new("MIN..MAX").unwrap();

        let constraint = parser.parse_single_constraint().unwrap();
        if let SubtypeConstraint::ValueRange { min, max } = constraint {
            assert_eq!(min, ConstraintValue::Min);
            assert_eq!(max, ConstraintValue::Max);
        } else {
            panic!("Expected ValueRange constraint");
        }
    }

    #[test]
    fn test_parse_union_constraint() {
        let mut parser = Parser::new("1 | 2 | 3").unwrap();

        let constraint = parser.parse_subtype_constraint().unwrap();
        if let SubtypeConstraint::Union(elements) = constraint {
            assert_eq!(elements.len(), 3);
        } else {
            panic!("Expected Union constraint");
        }
    }

    #[test]
    fn test_parse_intersection_constraint() {
        let mut parser = Parser::new("(0..100) ^ (10 | 20 | 30)").unwrap();

        let constraint = parser.parse_subtype_constraint().unwrap();
        if let SubtypeConstraint::Intersection(elements) = constraint {
            assert_eq!(elements.len(), 2);
        } else {
            panic!("Expected Intersection constraint");
        }
    }

    #[test]
    fn test_parse_complement_constraint() {
        let mut parser = Parser::new("ALL EXCEPT 0").unwrap();

        let constraint = parser.parse_single_constraint().unwrap();
        if let SubtypeConstraint::Complement(inner) = constraint {
            assert_eq!(
                *inner,
                SubtypeConstraint::SingleValue(ConstraintValue::Integer(0))
            );
        } else {
            panic!("Expected Complement constraint");
        }
    }

    #[test]
    fn test_parse_pattern_constraint() {
        let input = r#"
TestModule DEFINITIONS ::= BEGIN
    EmailPattern ::= IA5String (PATTERN "[a-z]+@[a-z]+\.[a-z]+")
END
        "#;

        let module = parse(input).unwrap();
        assert_eq!(module.definitions.len(), 1);

        let def = &module.definitions[0];
        assert_eq!(def.name, "EmailPattern");

        // Should be a constrained type
        if let Type::Constrained {
            base_type,
            constraint,
        } = &def.ty
        {
            // Accept either TypeRef or IA5String
            assert!(
                matches!(base_type.as_ref(), Type::IA5String(_))
                    || matches!(base_type.as_ref(), Type::TypeRef(s) if s == "IA5String")
            );
            if let ConstraintSpec::Subtype(SubtypeConstraint::Pattern(pattern)) = &constraint.spec {
                // Note: Single backslash in ASN.1 becomes single backslash in parsed string
                assert_eq!(pattern, "[a-z]+@[a-z]+.[a-z]+");
            } else {
                panic!("Expected Pattern constraint");
            }
        } else {
            panic!("Expected Constrained type");
        }
    }

    #[test]
    fn test_parse_permitted_alphabet() {
        let input = r#"
TestModule DEFINITIONS ::= BEGIN
    MyNumericString ::= IA5String (FROM ("0".."9"))
END
        "#;

        let module = parse(input).unwrap();
        let def = &module.definitions[0];

        if let Type::Constrained { constraint, .. } = &def.ty {
            if let ConstraintSpec::Subtype(SubtypeConstraint::PermittedAlphabet(ranges)) =
                &constraint.spec
            {
                assert_eq!(ranges.len(), 1);
                assert_eq!(ranges[0].min, '0');
                assert_eq!(ranges[0].max, '9');
            } else {
                panic!("Expected PermittedAlphabet constraint");
            }
        } else {
            panic!("Expected Constrained type");
        }
    }

    #[test]
    fn test_parse_containing_constraint() {
        let input = r#"
TestModule DEFINITIONS ::= BEGIN
    EncodedCert ::= OCTET STRING (CONTAINING INTEGER)
END
        "#;

        let module = parse(input).unwrap();
        let def = &module.definitions[0];

        if let Type::Constrained { constraint, .. } = &def.ty {
            if let ConstraintSpec::Subtype(SubtypeConstraint::ContainedSubtype(inner_type)) =
                &constraint.spec
            {
                assert!(matches!(inner_type.as_ref(), Type::Integer(_, _)));
            } else {
                panic!("Expected ContainedSubtype constraint");
            }
        } else {
            panic!("Expected Constrained type");
        }
    }

    #[test]
    fn test_parse_inner_type_constraint() {
        let input = r#"
TestModule DEFINITIONS ::= BEGIN
    PositiveList ::= SEQUENCE OF INTEGER (1..MAX)
END
        "#;

        let module = parse(input).unwrap();
        let def = &module.definitions[0];

        // Inner type constraints on SEQUENCE OF create a SequenceOf with constrained inner type
        if let Type::SequenceOf(inner_type, _) = &def.ty {
            // The inner type should be constrained
            if let Type::Constrained {
                base_type,
                constraint,
            } = inner_type.as_ref()
            {
                assert!(matches!(base_type.as_ref(), Type::Integer(_, _)));
                if let ConstraintSpec::Subtype(SubtypeConstraint::ValueRange { min, max }) =
                    &constraint.spec
                {
                    assert_eq!(*min, ConstraintValue::Integer(1));
                    assert_eq!(*max, ConstraintValue::Max);
                } else {
                    panic!("Expected ValueRange constraint on inner type");
                }
            } else {
                panic!("Expected inner type to be Constrained");
            }
        } else {
            panic!("Expected SequenceOf type, got: {:?}", def.ty);
        }
    }

    #[test]
    fn test_parse_complex_nested_union() {
        let input = r#"
TestModule DEFINITIONS ::= BEGIN
    ComplexRange ::= INTEGER (0..10 | 20..30 | 40..50)
END
        "#;

        let module = parse(input).unwrap();
        let def = &module.definitions[0];

        if let Type::Constrained { constraint, .. } = &def.ty {
            if let ConstraintSpec::Subtype(SubtypeConstraint::Union(elements)) = &constraint.spec {
                assert_eq!(elements.len(), 3);
                for element in elements {
                    assert!(matches!(element, SubtypeConstraint::ValueRange { .. }));
                }
            } else {
                panic!("Expected Union constraint");
            }
        } else {
            panic!("Expected Constrained type");
        }
    }

    #[test]
    fn test_parse_nested_parentheses() {
        let input = r#"
TestModule DEFINITIONS ::= BEGIN
    Nested ::= INTEGER ((0..10) | (20..30))
END
        "#;

        let module = parse(input).unwrap();
        let def = &module.definitions[0];

        if let Type::Constrained { constraint, .. } = &def.ty {
            if let ConstraintSpec::Subtype(SubtypeConstraint::Union(elements)) = &constraint.spec {
                assert_eq!(elements.len(), 2);
            } else {
                panic!("Expected Union constraint");
            }
        } else {
            panic!("Expected Constrained type");
        }
    }

    #[test]
    fn test_parse_size_constraint_on_string() {
        let input = r#"
TestModule DEFINITIONS ::= BEGIN
    ShortString ::= IA5String (SIZE (1..64))
END
        "#;

        let result = parse(input);
        if let Err(e) = &result {
            println!("Parse error: {}", e);
        }
        let module = result.unwrap();
        let def = &module.definitions[0];

        assert_eq!(def.name, "ShortString");
        // Expect Constrained type with SIZE constraint
        if let Type::Constrained {
            base_type,
            constraint,
        } = &def.ty
        {
            // The base type should be a TypeRef to IA5String now (not inline IA5String(None))
            // because the parser creates type references for known types
            println!("base_type: {:?}", base_type);
            // Accept either TypeRef or IA5String(None)
            assert!(
                matches!(base_type.as_ref(), Type::IA5String(None))
                    || matches!(base_type.as_ref(), Type::TypeRef(s) if s == "IA5String")
            );
            if let ConstraintSpec::Subtype(SubtypeConstraint::SizeConstraint(inner)) =
                &constraint.spec
            {
                // The inner constraint should be a ValueRange
                if let SubtypeConstraint::ValueRange { min, max } = inner.as_ref() {
                    assert_eq!(*min, ConstraintValue::Integer(1));
                    assert_eq!(*max, ConstraintValue::Integer(64));
                } else {
                    panic!("Expected ValueRange inside SIZE constraint");
                }
            } else {
                panic!("Expected SizeConstraint, got {:?}", constraint.spec);
            }
        } else {
            panic!("Expected Constrained type, got {:?}", def.ty);
        }
    }
}