tokmat 0.3.1

Standalone high-performance Canadian address parsing engine core
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
//! Extraction engine ported from the Python wanParser implementation.

use crate::error::ParseError;
use crate::tel::{
    CompiledClassSegment, CompiledPattern, Quantity, TelSegment, TokenInfo, apply_match_mode,
    apply_segment_to_class_type,
};
use crate::tokenizer::{
    TokenClassList, TokenDefinition, split_input_tokens, tokenize_and_classify,
};
use crate::word_definition::{boundary_pattern, word_regex};
use lru::LruCache;
use pcre2::bytes::{
    Captures as Pcre2Captures, Regex as Pcre2Regex, RegexBuilder as Pcre2RegexBuilder,
};
use std::collections::HashMap;
use std::hash::Hash;
use std::num::NonZeroUsize;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjComparatorTokenInfo {
    pub segment: TelSegment,
    pub class_comparator_substring: String,
    pub multi_group_optional: Option<String>,
    pub new_class_type: Option<String>,
    pub regex_pattern: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseOutput {
    pub uid: String,
    pub fields: HashMap<String, String>,
    pub complement: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExtractorConfig {
    pub compiled_pattern_cache_capacity: usize,
    pub object_plan_cache_capacity: usize,
    pub fallback_regex_cache_capacity: usize,
}

impl Default for ExtractorConfig {
    fn default() -> Self {
        Self {
            // Sized to cover the observed working set of the imported upstream
            // wanParser corpus without pathological eviction churn.
            compiled_pattern_cache_capacity: 512,
            object_plan_cache_capacity: 2048,
            fallback_regex_cache_capacity: 2048,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CacheStats {
    pub capacity: usize,
    pub len: usize,
    pub hits: usize,
    pub misses: usize,
    pub inserts: usize,
    pub evictions: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ExtractorStats {
    pub compiled_pattern_cache: CacheStats,
    pub object_plan_cache: CacheStats,
    pub fallback_regex_cache: CacheStats,
    pub unique_plan_signature_count: usize,
    pub direct_only_plan_count: usize,
    pub with_fallback_plan_count: usize,
    pub total_plan_steps: usize,
    pub single_token_step_count: usize,
    pub captured_span_step_count: usize,
    pub literal_step_count: usize,
    pub direct_execution_attempts: usize,
    pub direct_execution_hits: usize,
    pub fallback_execution_count: usize,
    pub fallback_regex_realizations: usize,
    pub profiled_rows: usize,
    pub profile_total_ns: u128,
    pub profile_class_join_ns: u128,
    pub profile_class_regex_ns: u128,
    pub profile_offset_work_ns: u128,
    pub profile_object_join_ns: u128,
    pub profile_direct_execution_ns: u128,
    pub profile_fallback_regex_ns: u128,
}

pub struct Extractor {
    config: ExtractorConfig,
    token_definitions: TokenDefinition,
    token_class_list: TokenClassList,
    token_definition_map: HashMap<String, String>,
    compiled_pattern_cache: Mutex<BoundedCache<String, Arc<CompiledPattern>>>,
    object_plan_cache: Mutex<BoundedCache<ObjectPlanCacheKey, Arc<CachedObjectPlan>>>,
    fallback_regex_cache: Mutex<BoundedCache<String, Arc<Pcre2Regex>>>,
    execution_counters: ExecutionCounters,
}

pub use crate::tel::MatchMode;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ObjectPlanCacheKey {
    pattern_source: String,
    mode: MatchMode,
    captured_groups: Vec<Option<String>>,
    any_prefix_len: Option<usize>,
}

#[derive(Debug, Clone)]
struct CachedObjectPlan {
    steps: Vec<ObjectPlanStep>,
    allow_direct: bool,
    fallback: Arc<ObjectRegexFallback>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum ObjectPlanStep {
    Literal {
        tokens: Vec<String>,
    },
    CapturedSpan {
        class_text: Option<String>,
        capture_name: Option<String>,
        is_vanishing: bool,
    },
    SingleToken {
        capture_name: Option<String>,
        is_vanishing: bool,
        consume_trailing_space: bool,
    },
}

#[derive(Debug)]
struct ObjectRegexFallback {
    pattern: Arc<str>,
    variable_names: Vec<String>,
}

/// Lock-free execution counters. Per-row increments are the hot path under
/// parallel extraction, so these are atomics (relaxed) rather than a
/// `Mutex<…>`: a global mutex per row serialized all worker threads. Durations
/// are accumulated as nanoseconds.
#[derive(Debug, Default)]
struct ExecutionCounters {
    direct_execution_attempts: AtomicU64,
    direct_execution_hits: AtomicU64,
    fallback_execution_count: AtomicU64,
    fallback_regex_realizations: AtomicU64,
    profiled_rows: AtomicU64,
    profile_total_ns: AtomicU64,
    profile_class_join_ns: AtomicU64,
    profile_class_regex_ns: AtomicU64,
    profile_offset_work_ns: AtomicU64,
    profile_object_join_ns: AtomicU64,
    profile_direct_execution_ns: AtomicU64,
    profile_fallback_regex_ns: AtomicU64,
}

#[derive(Debug)]
struct BoundedCache<K: Eq + Hash, V> {
    capacity: usize,
    values: LruCache<K, V>,
    hits: usize,
    misses: usize,
    inserts: usize,
    evictions: usize,
}

impl<K, V> BoundedCache<K, V>
where
    K: Clone + Eq + Hash,
{
    fn new(capacity: usize) -> Self {
        let effective_capacity = capacity.max(1);
        Self {
            capacity,
            values: LruCache::new(
                NonZeroUsize::new(effective_capacity)
                    .expect("effective cache capacity is non-zero"),
            ),
            hits: 0,
            misses: 0,
            inserts: 0,
            evictions: 0,
        }
    }

    fn get_cloned(&mut self, key: &K) -> Option<V>
    where
        V: Clone,
    {
        let Some(value) = self.values.get(key).cloned() else {
            self.misses += 1;
            return None;
        };
        self.hits += 1;
        Some(value)
    }

    fn insert(&mut self, key: K, value: V) {
        if self.capacity == 0 {
            return;
        }

        let existed = self.values.contains(&key);
        let evicted = self.values.push(key, value);
        if evicted.is_some() && !existed {
            self.evictions += 1;
        }
        self.inserts += 1;
    }

    fn stats(&self) -> CacheStats {
        CacheStats {
            capacity: self.capacity,
            len: self.values.len(),
            hits: self.hits,
            misses: self.misses,
            inserts: self.inserts,
            evictions: self.evictions,
        }
    }
}

impl Extractor {
    /// Create a new extractor from token definitions and classes.
    #[must_use]
    pub fn new(token_definitions: TokenDefinition, token_class_list: TokenClassList) -> Self {
        Self::new_with_config(
            token_definitions,
            token_class_list,
            ExtractorConfig::default(),
        )
    }

    /// Create a new extractor with explicit cache configuration.
    #[must_use]
    pub fn new_with_config(
        token_definitions: TokenDefinition,
        token_class_list: TokenClassList,
        config: ExtractorConfig,
    ) -> Self {
        let token_definition_map = token_definitions
            .iter()
            .map(|(name, pattern)| (name.clone(), pattern.clone()))
            .collect();
        Self {
            config,
            token_definitions,
            token_class_list,
            token_definition_map,
            compiled_pattern_cache: Mutex::new(BoundedCache::new(
                config.compiled_pattern_cache_capacity,
            )),
            object_plan_cache: Mutex::new(BoundedCache::new(config.object_plan_cache_capacity)),
            fallback_regex_cache: Mutex::new(BoundedCache::new(
                config.fallback_regex_cache_capacity,
            )),
            execution_counters: ExecutionCounters::default(),
        }
    }

    #[must_use]
    pub const fn config(&self) -> ExtractorConfig {
        self.config
    }

    /// Return current cache statistics for the extractor instance.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidPattern`] if an internal cache mutex is poisoned.
    pub fn stats(&self) -> Result<ExtractorStats, ParseError> {
        let compiled_pattern_cache = self
            .compiled_pattern_cache
            .lock()
            .map_err(|error| {
                ParseError::InvalidPattern(format!("compiled pattern cache poisoned: {error}"))
            })?
            .stats();
        let object_plan_cache = self
            .object_plan_cache
            .lock()
            .map_err(|error| {
                ParseError::InvalidPattern(format!("object plan cache poisoned: {error}"))
            })?
            .stats();
        let fallback_regex_cache = self
            .fallback_regex_cache
            .lock()
            .map_err(|error| {
                ParseError::InvalidPattern(format!("fallback regex cache poisoned: {error}"))
            })?
            .stats();
        let counters = &self.execution_counters;
        let (
            unique_plan_signature_count,
            direct_only_plan_count,
            with_fallback_plan_count,
            total_plan_steps,
            single_token_step_count,
            captured_span_step_count,
            literal_step_count,
        ) = {
            let cache = self.object_plan_cache.lock().map_err(|error| {
                ParseError::InvalidPattern(format!("object plan cache poisoned: {error}"))
            })?;
            let unique_plan_signature_count = cache.values.len();
            let mut direct_only_plan_count = 0;
            let mut with_fallback_plan_count = 0;
            let mut total_plan_steps = 0;
            let mut single_token_step_count = 0;
            let mut captured_span_step_count = 0;
            let mut literal_step_count = 0;
            for (_, plan) in &cache.values {
                if plan.allow_direct {
                    direct_only_plan_count += 1;
                } else {
                    with_fallback_plan_count += 1;
                }
                total_plan_steps += plan.steps.len();
                for step in &plan.steps {
                    match step {
                        ObjectPlanStep::SingleToken { .. } => single_token_step_count += 1,
                        ObjectPlanStep::CapturedSpan { .. } => captured_span_step_count += 1,
                        ObjectPlanStep::Literal { .. } => literal_step_count += 1,
                    }
                }
            }
            (
                unique_plan_signature_count,
                direct_only_plan_count,
                with_fallback_plan_count,
                total_plan_steps,
                single_token_step_count,
                captured_span_step_count,
                literal_step_count,
            )
        };

        Ok(ExtractorStats {
            compiled_pattern_cache,
            object_plan_cache,
            fallback_regex_cache,
            unique_plan_signature_count,
            direct_only_plan_count,
            with_fallback_plan_count,
            total_plan_steps,
            single_token_step_count,
            captured_span_step_count,
            literal_step_count,
            direct_execution_attempts: counters.direct_execution_attempts.load(Ordering::Relaxed)
                as usize,
            direct_execution_hits: counters.direct_execution_hits.load(Ordering::Relaxed) as usize,
            fallback_execution_count: counters.fallback_execution_count.load(Ordering::Relaxed)
                as usize,
            fallback_regex_realizations: counters
                .fallback_regex_realizations
                .load(Ordering::Relaxed) as usize,
            profiled_rows: counters.profiled_rows.load(Ordering::Relaxed) as usize,
            profile_total_ns: u128::from(counters.profile_total_ns.load(Ordering::Relaxed)),
            profile_class_join_ns: u128::from(
                counters.profile_class_join_ns.load(Ordering::Relaxed),
            ),
            profile_class_regex_ns: u128::from(
                counters.profile_class_regex_ns.load(Ordering::Relaxed),
            ),
            profile_offset_work_ns: u128::from(
                counters.profile_offset_work_ns.load(Ordering::Relaxed),
            ),
            profile_object_join_ns: u128::from(
                counters.profile_object_join_ns.load(Ordering::Relaxed),
            ),
            profile_direct_execution_ns: u128::from(
                counters.profile_direct_execution_ns.load(Ordering::Relaxed),
            ),
            profile_fallback_regex_ns: u128::from(
                counters.profile_fallback_regex_ns.load(Ordering::Relaxed),
            ),
        })
    }

    /// Parse the WAN DSL pattern into token metadata.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidPattern`] when the pattern contains an unsupported token.
    pub fn compile_pattern(&self, pattern: &str) -> Result<CompiledPattern, ParseError> {
        CompiledPattern::compile(pattern)
    }

    /// Parse the WAN DSL pattern into token metadata.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidPattern`] when the pattern contains an unsupported token.
    pub fn extract_token_info(&self, pattern: &str) -> Result<Vec<TokenInfo>, ParseError> {
        Ok(self.compile_pattern(pattern)?.token_info().to_vec())
    }

    /// Parse using pre-tokenized string and class lists.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidPattern`] when the generated regex cannot be compiled or the
    /// DSL pattern is invalid.
    #[allow(clippy::too_many_lines)]
    pub fn parse_tokens(
        &self,
        uid: &str,
        obj_string_list: &[String],
        obj_class_list: &[String],
        pattern: &str,
        mode: MatchMode,
    ) -> Result<ParseOutput, ParseError> {
        let compiled_pattern = self.get_or_compile_pattern(pattern)?;
        self.parse_compiled_tokens(
            uid,
            obj_string_list,
            obj_class_list,
            &compiled_pattern,
            mode,
        )
    }

    /// Parse using borrowed class values while compiling or reusing a cached TEL pattern.
    ///
    /// This avoids forcing callers to materialize owned `String` values for every
    /// class token when they already have a compact or borrowed representation.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidPattern`] when the generated regex cannot be compiled.
    pub fn parse_tokens_with_classes<S: AsRef<str>>(
        &self,
        uid: &str,
        obj_string_list: &[String],
        obj_class_list: &[S],
        pattern: &str,
        mode: MatchMode,
    ) -> Result<ParseOutput, ParseError> {
        let compiled_pattern = self.get_or_compile_pattern(pattern)?;
        self.parse_compiled_tokens_with_classes(
            uid,
            obj_string_list,
            obj_class_list,
            &compiled_pattern,
            mode,
        )
    }

    /// Parse using pre-tokenized borrowed token and class lists while compiling or reusing a
    /// cached TEL pattern.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidPattern`] when the generated regex cannot be compiled.
    pub fn parse_tokens_with_views<T: AsRef<str>, S: AsRef<str>>(
        &self,
        uid: &str,
        obj_string_list: &[T],
        obj_class_list: &[S],
        pattern: &str,
        mode: MatchMode,
    ) -> Result<ParseOutput, ParseError> {
        let compiled_pattern = self.get_or_compile_pattern(pattern)?;
        self.parse_compiled_tokens_with_views(
            uid,
            obj_string_list,
            obj_class_list,
            &compiled_pattern,
            mode,
        )
    }

    /// Parse using a precompiled TEL pattern.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidPattern`] when the generated regex cannot be compiled.
    #[allow(clippy::too_many_lines)]
    pub fn parse_compiled_tokens(
        &self,
        uid: &str,
        obj_string_list: &[String],
        obj_class_list: &[String],
        compiled_pattern: &CompiledPattern,
        mode: MatchMode,
    ) -> Result<ParseOutput, ParseError> {
        self.parse_compiled_tokens_with_views(
            uid,
            obj_string_list,
            obj_class_list,
            compiled_pattern,
            mode,
        )
    }

    /// Parse using a precompiled TEL pattern and borrowed class values.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidPattern`] when the generated regex cannot be compiled.
    #[allow(clippy::too_many_lines)]
    pub fn parse_compiled_tokens_with_classes<S: AsRef<str>>(
        &self,
        uid: &str,
        obj_string_list: &[String],
        obj_class_list: &[S],
        compiled_pattern: &CompiledPattern,
        mode: MatchMode,
    ) -> Result<ParseOutput, ParseError> {
        self.parse_compiled_tokens_with_views(
            uid,
            obj_string_list,
            obj_class_list,
            compiled_pattern,
            mode,
        )
    }

    /// Parse using a precompiled TEL pattern and borrowed token/class values.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidPattern`] when the generated regex cannot be compiled.
    #[allow(clippy::too_many_lines)]
    pub fn parse_compiled_tokens_with_views<T: AsRef<str>, S: AsRef<str>>(
        &self,
        uid: &str,
        obj_string_list: &[T],
        obj_class_list: &[S],
        compiled_pattern: &CompiledPattern,
        mode: MatchMode,
    ) -> Result<ParseOutput, ParseError> {
        let profiling = profile_enabled();
        let total_start = profiling.then(Instant::now);
        let leading_space_removed = starts_with_space_pair(obj_string_list, obj_class_list);
        let trailing_space_removed = ends_with_space_pair(obj_string_list, obj_class_list);
        let class_join_start = profiling.then(Instant::now);
        let (raw_class_string, class_offsets) = join_class_tokens_with_offsets(obj_class_list);
        let obj_class = trim_with_space_flags(
            raw_class_string.as_str(),
            leading_space_removed,
            trailing_space_removed,
        );
        let class_join_elapsed = elapsed_since(class_join_start);

        let class_pattern = compiled_pattern.class_pattern(mode);
        let class_regex = compiled_pattern.class_regex(mode)?;
        let class_regex_start = profiling.then(Instant::now);
        let class_captures =
            run_pcre2_captures(class_regex, obj_class, "class comparator", class_pattern)?;
        let class_regex_elapsed = elapsed_since(class_regex_start);

        let Some(class_match) = class_captures else {
            self.record_profile_timing(ProfileTiming {
                rows: 1,
                total: elapsed_since(total_start),
                class_join: class_join_elapsed,
                class_regex: class_regex_elapsed,
                ..ProfileTiming::default()
            })?;
            return Ok(ParseOutput {
                uid: uid.to_string(),
                fields: HashMap::new(),
                complement: join_tokens(obj_string_list),
            });
        };

        let raw_groups = capture_groups(&class_match);
        if raw_groups.iter().any(|group| group.as_deref() == Some(" ")) {
            self.record_profile_timing(ProfileTiming {
                rows: 1,
                total: elapsed_since(total_start),
                class_join: class_join_elapsed,
                class_regex: class_regex_elapsed,
                ..ProfileTiming::default()
            })?;
            return Ok(ParseOutput {
                uid: uid.to_string(),
                fields: HashMap::new(),
                complement: join_tokens(obj_string_list),
            });
        }

        let offset_work_start = profiling.then(Instant::now);
        let object_offsets = token_offsets_ref(obj_string_list);
        let left_trim = if leading_space_removed {
            obj_class_list
                .first()
                .map_or(0, |token| token.as_ref().len())
        } else {
            0
        };

        let (aligned_obj_start, _aligned_obj_end) = if mode == MatchMode::Any {
            align_any_match(
                &class_match,
                &class_offsets,
                &object_offsets,
                obj_class_list,
                left_trim,
            )
        } else {
            (None, None)
        };

        let captured_multi_or_optional_groups =
            filter_class_groups(&raw_groups, compiled_pattern.class_segments());

        let object_plan = self.get_or_build_object_plan(
            compiled_pattern,
            captured_multi_or_optional_groups.as_deref().unwrap_or(&[]),
            mode,
            if mode == MatchMode::Any {
                aligned_obj_start
            } else {
                None
            },
        )?;

        let full_match = class_match.get(0).ok_or_else(|| {
            ParseError::InvalidPattern(
                "class comparator matched without a full match group".to_string(),
            )
        })?;
        let Some(match_range) = match_token_index_range(
            &class_offsets,
            left_trim,
            full_match.start(),
            full_match.end(),
        ) else {
            self.record_profile_timing(ProfileTiming {
                rows: 1,
                total: elapsed_since(total_start),
                class_join: class_join_elapsed,
                class_regex: class_regex_elapsed,
                offset_work: elapsed_since(offset_work_start),
                ..ProfileTiming::default()
            })?;
            return Ok(ParseOutput {
                uid: uid.to_string(),
                fields: HashMap::new(),
                complement: join_tokens(obj_string_list),
            });
        };
        let offset_work_elapsed = elapsed_since(offset_work_start);

        let object_join_start = profiling.then(Instant::now);
        let full_obj_string = join_tokens(obj_string_list);
        let obj_string = trim_with_space_flags(
            full_obj_string.as_str(),
            leading_space_removed,
            trailing_space_removed,
        );
        let object_join_elapsed = elapsed_since(object_join_start);

        let direct_execution_start = profiling.then(Instant::now);
        let direct_execution = if leading_space_removed {
            None
        } else {
            self.record_direct_execution_attempt()?;
            execute_object_plan(
                &object_plan,
                obj_string_list,
                obj_class_list,
                obj_string,
                &object_offsets,
                match_range,
            )
        };
        let direct_execution_elapsed = elapsed_since(direct_execution_start);

        let mut fallback_regex_elapsed = Duration::ZERO;
        let (fields, mut complement) = if let Some(execution) = direct_execution {
            self.record_direct_execution_hit()?;
            (
                execution.fields,
                get_complement_of_spans(obj_string, &execution.capture_spans)
                    .trim_start()
                    .to_string(),
            )
        } else {
            self.record_fallback_execution()?;
            let fallback_regex =
                self.get_or_compile_fallback_regex(object_plan.fallback.pattern.as_ref())?;
            let fallback_regex_start = profiling.then(Instant::now);
            let obj_captures = run_pcre2_captures(
                fallback_regex.as_ref(),
                obj_string,
                "object comparator",
                object_plan.fallback.pattern.as_ref(),
            )?;
            fallback_regex_elapsed = elapsed_since(fallback_regex_start);

            let Some(obj_match) = obj_captures else {
                self.record_profile_timing(ProfileTiming {
                    rows: 1,
                    total: elapsed_since(total_start),
                    class_join: class_join_elapsed,
                    class_regex: class_regex_elapsed,
                    offset_work: offset_work_elapsed,
                    object_join: object_join_elapsed,
                    direct_execution: direct_execution_elapsed,
                    fallback_regex: fallback_regex_elapsed,
                })?;
                return Ok(ParseOutput {
                    uid: uid.to_string(),
                    fields: HashMap::new(),
                    complement: full_obj_string,
                });
            };

            let mut fields = HashMap::new();
            for (index, name) in object_plan
                .fallback
                .variable_names
                .as_slice()
                .iter()
                .enumerate()
            {
                if let Some(value) = obj_match
                    .get(index + 1)
                    .and_then(|matched| std::str::from_utf8(matched.as_bytes()).ok())
                    .map(str::trim)
                {
                    if value.is_empty() {
                        continue;
                    }
                    fields
                        .entry(name.clone())
                        .and_modify(|existing: &mut String| {
                            existing.push(' ');
                            existing.push_str(value);
                        })
                        .or_insert_with(|| value.to_string());
                }
            }

            (
                fields,
                get_complement_of_captured_groups(obj_string, &obj_match),
            )
        };

        if leading_space_removed {
            complement.insert(0, ' ');
        }

        self.record_profile_timing(ProfileTiming {
            rows: 1,
            total: elapsed_since(total_start),
            class_join: class_join_elapsed,
            class_regex: class_regex_elapsed,
            offset_work: offset_work_elapsed,
            object_join: object_join_elapsed,
            direct_execution: direct_execution_elapsed,
            fallback_regex: fallback_regex_elapsed,
        })?;

        Ok(ParseOutput {
            uid: uid.to_string(),
            fields,
            complement,
        })
    }

    /// Compatibility wrapper that tokenizes the input and parses using whole-string matching.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidPattern`] when the pattern cannot be compiled.
    pub fn parse_string(
        &self,
        raw_value: &str,
        pattern: &str,
    ) -> Result<(String, HashMap<String, String>, String), ParseError> {
        let tokenized = tokenize_and_classify(
            raw_value,
            &self.token_definitions,
            Some(&self.token_class_list),
        );
        let output = self.parse_tokens(
            raw_value,
            &tokenized.tokens,
            &tokenized.classes,
            pattern,
            MatchMode::Whole,
        )?;
        Ok((output.uid, output.fields, output.complement))
    }
}

#[derive(Debug, Clone)]
struct DirectExecutionResult {
    fields: HashMap<String, String>,
    capture_spans: Vec<(usize, usize)>,
}

fn create_object_plan_steps(
    augmented_extracted_token_info: &[CompiledClassSegment],
    captured_multi_groups_optional: Option<Vec<Option<String>>>,
) -> (Vec<ObjectPlanStep>, bool) {
    let mut captured_multi_groups_optional = captured_multi_groups_optional.unwrap_or_default();
    let mut steps = Vec::with_capacity(augmented_extracted_token_info.len());
    let mut requires_regex_fallback = false;

    for token_info in augmented_extracted_token_info {
        let segment = &token_info.segment;
        let token = &segment.token_info.token;

        if segment.token_info.kind == crate::tel::TokenKind::Literal {
            let literal_tokens = split_input_tokens(token);
            requires_regex_fallback = true;
            steps.push(ObjectPlanStep::Literal {
                tokens: literal_tokens,
            });
            continue;
        }

        let flags = segment.token_info.flags;
        let needs_captured_class = flags.multi_group || flags.optional || !flags.strict_class;
        if needs_captured_class {
            let captured = if captured_multi_groups_optional.is_empty() {
                None
            } else {
                captured_multi_groups_optional.remove(0)
            };
            let can_collapse_to_single = !flags.multi_group
                && captured
                    .as_deref()
                    .is_some_and(|value| !value.contains(char::is_whitespace));
            if can_collapse_to_single {
                steps.push(ObjectPlanStep::SingleToken {
                    capture_name: segment.token_info.var_name.clone(),
                    is_vanishing: segment.token_info.is_vanishing_group(),
                    consume_trailing_space: true,
                });
                continue;
            }
            requires_regex_fallback = true;
            steps.push(ObjectPlanStep::CapturedSpan {
                class_text: captured,
                capture_name: segment.token_info.var_name.clone(),
                is_vanishing: segment.token_info.is_vanishing_group(),
            });
            continue;
        }

        steps.push(ObjectPlanStep::SingleToken {
            capture_name: segment.token_info.var_name.clone(),
            is_vanishing: segment.token_info.is_vanishing_group(),
            consume_trailing_space: true,
        });
    }

    (steps, requires_regex_fallback)
}

fn execute_object_plan(
    plan: &CachedObjectPlan,
    obj_string_list: &[impl AsRef<str>],
    obj_class_list: &[impl AsRef<str>],
    obj_string: &str,
    object_offsets: &[(usize, usize)],
    match_range: (usize, usize),
) -> Option<DirectExecutionResult> {
    let execution = execute_object_plan_steps(
        &plan.steps,
        obj_string_list,
        obj_class_list,
        obj_string,
        object_offsets,
        match_range,
    )?;

    if !plan.allow_direct {
        return None;
    }

    // Validate the reconstructed spans against the current object string bounds.
    if execution
        .capture_spans
        .iter()
        .any(|(start, end)| start > end || *end > obj_string.len())
    {
        return None;
    }

    Some(execution)
}

fn execute_object_plan_steps(
    steps: &[ObjectPlanStep],
    obj_string_list: &[impl AsRef<str>],
    obj_class_list: &[impl AsRef<str>],
    obj_string: &str,
    object_offsets: &[(usize, usize)],
    match_range: (usize, usize),
) -> Option<DirectExecutionResult> {
    let mut current = match_range.0;
    let mut fields = HashMap::new();
    let mut capture_spans = Vec::new();

    for step in steps {
        match step {
            ObjectPlanStep::Literal { tokens } => {
                let start = skip_whitespace_tokens(obj_string_list, current, match_range.1);
                let end = start + tokens.len();
                if end > match_range.1 {
                    return None;
                }
                if !obj_string_list[start..end]
                    .iter()
                    .map(AsRef::as_ref)
                    .eq(tokens.iter().map(String::as_str))
                {
                    return None;
                }
                current = end;
            }
            ObjectPlanStep::CapturedSpan {
                class_text,
                capture_name,
                is_vanishing,
            } => {
                let Some(class_text) = class_text.as_deref() else {
                    continue;
                };
                if class_text.is_empty() {
                    continue;
                }

                let start = skip_whitespace_tokens(obj_class_list, current, match_range.1);
                let end = consume_class_text(obj_class_list, start, match_range.1, class_text)?;
                if let Some(name) = capture_name
                    && !is_vanishing
                {
                    let span = object_span_for_tokens(object_offsets, start, end);
                    if let Some((span_start, span_end)) = span {
                        append_field_from_span(&mut fields, name, span_start, span_end, obj_string);
                        capture_spans.push((span_start, span_end));
                    }
                }
                current = end;
            }
            ObjectPlanStep::SingleToken {
                capture_name,
                is_vanishing,
                consume_trailing_space,
            } => {
                let start = skip_whitespace_tokens(obj_class_list, current, match_range.1);
                if start >= match_range.1 {
                    return None;
                }
                let mut end = start + 1;
                if *consume_trailing_space {
                    while end < match_range.1
                        && obj_class_list[end]
                            .as_ref()
                            .chars()
                            .all(char::is_whitespace)
                    {
                        end += 1;
                    }
                }
                if let Some(name) = capture_name
                    && !is_vanishing
                {
                    let span = object_span_for_tokens(object_offsets, start, end);
                    if let Some((span_start, span_end)) = span {
                        append_field_from_span(&mut fields, name, span_start, span_end, obj_string);
                        capture_spans.push((span_start, span_end));
                    }
                }
                current = end;
            }
        }
    }

    Some(DirectExecutionResult {
        fields,
        capture_spans,
    })
}

fn skip_whitespace_tokens<S: AsRef<str>>(tokens: &[S], mut index: usize, end: usize) -> usize {
    while index < end && tokens[index].as_ref().chars().all(char::is_whitespace) {
        index += 1;
    }
    index
}

fn consume_class_text<S: AsRef<str>>(
    obj_class_list: &[S],
    start: usize,
    end: usize,
    class_text: &str,
) -> Option<usize> {
    let mut accumulated = String::new();
    for (index, token) in obj_class_list.iter().enumerate().take(end).skip(start) {
        accumulated.push_str(token.as_ref());
        if accumulated == class_text {
            return Some(index + 1);
        }
        if !class_text.starts_with(&accumulated) {
            return None;
        }
    }
    None
}

fn object_span_for_tokens(
    object_offsets: &[(usize, usize)],
    start: usize,
    end: usize,
) -> Option<(usize, usize)> {
    if start >= end {
        return None;
    }
    Some((object_offsets.get(start)?.0, object_offsets.get(end - 1)?.1))
}

fn append_field_from_span(
    fields: &mut HashMap<String, String>,
    name: &str,
    start: usize,
    end: usize,
    obj_string: &str,
) {
    let Some(value) = obj_string.get(start..end).map(str::trim) else {
        return;
    };
    let value = value.to_string();
    if value.is_empty() {
        return;
    }
    fields
        .entry(name.to_string())
        .and_modify(|existing| {
            existing.push(' ');
            existing.push_str(&value);
        })
        .or_insert(value);
}

fn match_token_index_range(
    class_offsets: &[(usize, usize)],
    left_trim: usize,
    match_start: usize,
    match_end: usize,
) -> Option<(usize, usize)> {
    let raw_start = left_trim + match_start;
    let raw_end = left_trim + match_end;

    let mut start_index = None;
    let mut end_index = None;
    for (index, (token_start, token_end)) in class_offsets.iter().enumerate() {
        if start_index.is_none() && *token_start <= raw_start && raw_start < *token_end {
            start_index = Some(index);
        }
        if raw_end <= *token_end && *token_start < raw_end {
            end_index = Some(index + 1);
            break;
        }
    }

    match (start_index, end_index) {
        (Some(start), Some(end)) if start < end => Some((start, end)),
        _ => None,
    }
}

impl Extractor {
    fn get_or_compile_pattern(&self, pattern: &str) -> Result<Arc<CompiledPattern>, ParseError> {
        let cached = self
            .compiled_pattern_cache
            .lock()
            .map_err(|error| {
                ParseError::InvalidPattern(format!("compiled pattern cache poisoned: {error}"))
            })?
            .get_cloned(&pattern.to_string());
        if let Some(compiled) = cached {
            return Ok(compiled);
        }

        let compiled = Arc::new(self.compile_pattern(pattern)?);
        self.compiled_pattern_cache
            .lock()
            .map_err(|error| {
                ParseError::InvalidPattern(format!("compiled pattern cache poisoned: {error}"))
            })?
            .insert(pattern.to_string(), Arc::clone(&compiled));
        Ok(compiled)
    }

    fn get_or_build_object_plan(
        &self,
        compiled_pattern: &CompiledPattern,
        captured_groups: &[Option<String>],
        mode: MatchMode,
        any_prefix_len: Option<usize>,
    ) -> Result<Arc<CachedObjectPlan>, ParseError> {
        let key = ObjectPlanCacheKey {
            pattern_source: compiled_pattern.source().to_string(),
            mode,
            captured_groups: captured_groups.to_vec(),
            any_prefix_len,
        };

        let cached = self
            .object_plan_cache
            .lock()
            .map_err(|error| {
                ParseError::InvalidPattern(format!("object plan cache poisoned: {error}"))
            })?
            .get_cloned(&key);
        if let Some(plan) = cached {
            return Ok(plan);
        }

        let (steps, requires_regex_fallback) = create_object_plan_steps(
            compiled_pattern.class_segments(),
            if captured_groups.is_empty() {
                None
            } else {
                Some(captured_groups.to_vec())
            },
        );

        let (mut comparator, augmented_info) = create_obj_comparator_string(
            compiled_pattern.class_segments(),
            if captured_groups.is_empty() {
                None
            } else {
                Some(captured_groups.to_vec())
            },
            &self.token_definition_map,
        );
        comparator = apply_match_mode(&comparator, mode);
        if mode == MatchMode::Any
            && let Some(start) = any_prefix_len
        {
            comparator = if start > 0 {
                format!(r"(?s)^(?:.{{{start}}}){comparator}(?:.*)$")
            } else {
                format!(r"(?s)^{comparator}(?:.*)$")
            };
        }
        let variable_names = augmented_info
            .iter()
            .filter(|info| {
                !info.segment.token_info.is_vanishing_group()
                    && (info.segment.token_info.is_capturing_group()
                        || info.segment.token_info.flags.optional)
                    && info
                        .regex_pattern
                        .as_deref()
                        .is_some_and(|pattern| !pattern.is_empty())
            })
            .filter_map(|info| info.segment.token_info.var_name.clone())
            .collect();
        let fallback = Arc::new(ObjectRegexFallback {
            pattern: Arc::<str>::from(comparator),
            variable_names,
        });

        let plan = Arc::new(CachedObjectPlan {
            steps,
            allow_direct: !requires_regex_fallback,
            fallback,
        });

        self.object_plan_cache
            .lock()
            .map_err(|error| {
                ParseError::InvalidPattern(format!("object plan cache poisoned: {error}"))
            })?
            .insert(key, Arc::clone(&plan));
        Ok(plan)
    }

    fn get_or_compile_fallback_regex(&self, pattern: &str) -> Result<Arc<Pcre2Regex>, ParseError> {
        if let Some(regex) = self
            .fallback_regex_cache
            .lock()
            .map_err(|error| {
                ParseError::InvalidPattern(format!("fallback regex cache poisoned: {error}"))
            })?
            .get_cloned(&pattern.to_string())
        {
            return Ok(regex);
        }

        let compiled = Arc::new(compile_pcre2_regex(pattern, "object comparator")?);
        self.fallback_regex_cache
            .lock()
            .map_err(|error| {
                ParseError::InvalidPattern(format!("fallback regex cache poisoned: {error}"))
            })?
            .insert(pattern.to_string(), Arc::clone(&compiled));
        self.execution_counters
            .fallback_regex_realizations
            .fetch_add(1, Ordering::Relaxed);
        Ok(compiled)
    }

    fn record_direct_execution_attempt(&self) -> Result<(), ParseError> {
        self.execution_counters
            .direct_execution_attempts
            .fetch_add(1, Ordering::Relaxed);
        Ok(())
    }

    fn record_direct_execution_hit(&self) -> Result<(), ParseError> {
        self.execution_counters
            .direct_execution_hits
            .fetch_add(1, Ordering::Relaxed);
        Ok(())
    }

    fn record_fallback_execution(&self) -> Result<(), ParseError> {
        self.execution_counters
            .fallback_execution_count
            .fetch_add(1, Ordering::Relaxed);
        Ok(())
    }

    #[allow(clippy::cast_possible_truncation)]
    fn record_profile_timing(&self, timing: ProfileTiming) -> Result<(), ParseError> {
        if !profile_enabled() {
            return Ok(());
        }
        let counters = &self.execution_counters;
        counters
            .profiled_rows
            .fetch_add(timing.rows as u64, Ordering::Relaxed);
        counters
            .profile_total_ns
            .fetch_add(timing.total.as_nanos() as u64, Ordering::Relaxed);
        counters
            .profile_class_join_ns
            .fetch_add(timing.class_join.as_nanos() as u64, Ordering::Relaxed);
        counters
            .profile_class_regex_ns
            .fetch_add(timing.class_regex.as_nanos() as u64, Ordering::Relaxed);
        counters
            .profile_offset_work_ns
            .fetch_add(timing.offset_work.as_nanos() as u64, Ordering::Relaxed);
        counters
            .profile_object_join_ns
            .fetch_add(timing.object_join.as_nanos() as u64, Ordering::Relaxed);
        counters
            .profile_direct_execution_ns
            .fetch_add(timing.direct_execution.as_nanos() as u64, Ordering::Relaxed);
        counters
            .profile_fallback_regex_ns
            .fetch_add(timing.fallback_regex.as_nanos() as u64, Ordering::Relaxed);
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, Default)]
struct ProfileTiming {
    rows: usize,
    total: Duration,
    class_join: Duration,
    class_regex: Duration,
    offset_work: Duration,
    object_join: Duration,
    direct_execution: Duration,
    fallback_regex: Duration,
}

fn starts_with_space_pair(
    obj_string_list: &[impl AsRef<str>],
    obj_class_list: &[impl AsRef<str>],
) -> bool {
    !obj_string_list.is_empty()
        && !obj_class_list.is_empty()
        && obj_string_list[0].as_ref().chars().all(char::is_whitespace)
        && obj_class_list[0].as_ref().chars().all(char::is_whitespace)
}

fn ends_with_space_pair(
    obj_string_list: &[impl AsRef<str>],
    obj_class_list: &[impl AsRef<str>],
) -> bool {
    !obj_string_list.is_empty()
        && !obj_class_list.is_empty()
        && obj_string_list[obj_string_list.len() - 1]
            .as_ref()
            .chars()
            .all(char::is_whitespace)
        && obj_class_list[obj_class_list.len() - 1]
            .as_ref()
            .chars()
            .all(char::is_whitespace)
}

fn capture_groups(captures: &Pcre2Captures) -> Vec<Option<String>> {
    (1..captures.len())
        .map(|index| {
            captures.get(index).and_then(|matched| {
                std::str::from_utf8(matched.as_bytes())
                    .ok()
                    .map(ToString::to_string)
            })
        })
        .collect()
}

fn compile_pcre2_regex(pattern: &str, label: &str) -> Result<Pcre2Regex, ParseError> {
    Pcre2RegexBuilder::new()
        .utf(true)
        .ucp(true)
        .jit_if_available(true)
        // No custom JIT stack size: `max_jit_stack_size(Some(..))` makes the pcre2
        // crate create (mmap) and free (munmap) a JIT stack inside every
        // `MatchData`, and `captures()` allocates a fresh `MatchData` per call --
        // i.e. an mmap/munmap per matched row, which dominates extraction and
        // serializes parallel work on the kernel mmap lock. The default JIT stack
        // is used instead. (Trade-off: less JIT backtracking headroom.)
        .build(pattern)
        .map_err(|error| {
            ParseError::InvalidPattern(format!("error compiling {label} '{pattern}': {error}"))
        })
}

fn run_pcre2_captures<'a>(
    regex: &Pcre2Regex,
    text: &'a str,
    label: &str,
    pattern: &str,
) -> Result<Option<Pcre2Captures<'a>>, ParseError> {
    regex.captures(text.as_bytes()).map_err(|error| {
        ParseError::InvalidPattern(format!("error running {label} '{pattern}': {error}"))
    })
}

fn filter_class_groups(
    raw_groups: &[Option<String>],
    augmented_extracted_token_info: &[CompiledClassSegment],
) -> Option<Vec<Option<String>>> {
    if raw_groups.is_empty() {
        return None;
    }

    let mut filtered_groups: Vec<Option<String>> = Vec::new();
    let mut group_index = 0_usize;
    let total_groups = raw_groups.len();

    for token_info in augmented_extracted_token_info {
        let group_count = token_info.capturing_group_count;
        if group_count == 0 {
            continue;
        }

        let next_index = group_index + group_count;
        if next_index > total_groups {
            break;
        }

        let group_slice = &raw_groups[group_index..next_index];
        let flags = token_info.segment.token_info.flags;
        if flags.multi_group
            || flags.optional
            || !flags.strict_class
            || token_info.segment.token_info.is_vanishing_group()
        {
            filtered_groups.extend(group_slice.iter().cloned());
        }

        group_index = next_index;
    }

    filtered_groups.extend(raw_groups[group_index..].iter().cloned());

    if filtered_groups.is_empty() {
        None
    } else {
        Some(filtered_groups)
    }
}

fn align_any_match(
    class_match: &Pcre2Captures,
    class_offsets: &[(usize, usize)],
    obj_offsets: &[(usize, usize)],
    obj_class_list: &[impl AsRef<str>],
    left_trim: usize,
) -> (Option<usize>, Option<usize>) {
    let Some(full_match) = class_match.get(0) else {
        return (None, None);
    };

    let class_start_raw = left_trim + full_match.start();
    let class_end_raw = left_trim + full_match.end();
    let mut start_token_index = None;
    let mut end_token_index = None;

    for (index, (start, end)) in class_offsets.iter().enumerate() {
        if start_token_index.is_none() && *start <= class_start_raw && class_start_raw < *end {
            start_token_index = Some(index);
        }
        if *start < class_end_raw && class_end_raw <= *end {
            end_token_index = Some(index);
        }
    }

    let (Some(mut start_token_index), Some(mut end_token_index)) =
        (start_token_index, end_token_index)
    else {
        return (None, None);
    };

    while start_token_index < obj_class_list.len()
        && obj_class_list[start_token_index].as_ref().trim().is_empty()
    {
        start_token_index += 1;
    }
    while end_token_index > 0 && obj_class_list[end_token_index].as_ref().trim().is_empty() {
        end_token_index -= 1;
    }

    if start_token_index > end_token_index {
        return (None, None);
    }

    (
        obj_offsets.get(start_token_index).map(|(start, _)| *start),
        obj_offsets.get(end_token_index).map(|(_, end)| *end),
    )
}

fn trim_with_space_flags(
    text: &str,
    leading_space_removed: bool,
    trailing_space_removed: bool,
) -> &str {
    let text = if leading_space_removed {
        text.trim_start()
    } else {
        text
    };
    if trailing_space_removed {
        text.trim_end()
    } else {
        text
    }
}

fn token_offsets_ref<S: AsRef<str>>(tokens: &[S]) -> Vec<(usize, usize)> {
    let mut offset = 0_usize;
    let mut result = Vec::with_capacity(tokens.len());
    for token in tokens {
        let start = offset;
        offset += token.as_ref().len();
        result.push((start, offset));
    }
    result
}

fn join_tokens<T: AsRef<str>>(tokens: &[T]) -> String {
    let total_len = tokens.iter().map(|token| token.as_ref().len()).sum();
    let mut out = String::with_capacity(total_len);
    for token in tokens {
        out.push_str(token.as_ref());
    }
    out
}

/// `\b`-relevant word character: matches the classes the class comparator wraps
/// its fragments in (`\b...\b`). Class names are `[A-Za-z0-9_]`.
fn is_class_word_char(character: char) -> bool {
    character.is_alphanumeric() || character == '_'
}

/// Build the class-name string the class comparator matches against, together
/// with byte offsets parallel to `tokens`.
///
/// The comparator anchors class fragments with word boundaries (`\b...\b`) and
/// relies on the source text's whitespace/punctuation to separate them. But a
/// model word definition can split a run like `11-47` into *adjacent* tokens
/// (`11`,`-`,`47`) whose class names (`NUM`,`DASH`,`NUM`) would otherwise
/// concatenate to `NUMDASHNUM` -- leaving the `\b`-wrapped fragments with no
/// boundary to match. Insert a single space between two adjacent tokens only
/// when both sides would merge (previous ends and next starts with a word
/// char), so whitespace/punctuation-separated inputs stay byte-for-byte
/// identical and only the otherwise-unmatchable adjacency gains a boundary.
fn join_class_tokens_with_offsets<S: AsRef<str>>(tokens: &[S]) -> (String, Vec<(usize, usize)>) {
    let mut out = String::new();
    let mut offsets = Vec::with_capacity(tokens.len());
    let mut prev_last: Option<char> = None;
    for token in tokens {
        let text = token.as_ref();
        if let (Some(prev), Some(next)) = (prev_last, text.chars().next())
            && is_class_word_char(prev)
            && is_class_word_char(next)
        {
            out.push(' ');
        }
        let start = out.len();
        out.push_str(text);
        offsets.push((start, out.len()));
        if let Some(last) = text.chars().last() {
            prev_last = Some(last);
        }
    }
    (out, offsets)
}

fn profile_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| {
        std::env::var("TOKMAT_PROFILE")
            .map(|value| value != "0" && !value.is_empty())
            .unwrap_or(false)
    })
}

fn elapsed_since(start: Option<Instant>) -> Duration {
    start.map_or(Duration::ZERO, |start| start.elapsed())
}

fn strip_word_boundaries(pattern: &str) -> &str {
    let boundary = boundary_pattern();
    pattern
        .strip_prefix(&*boundary)
        .and_then(|stripped| stripped.strip_suffix(&*boundary))
        .unwrap_or(pattern)
}

fn create_obj_comparator_string(
    augmented_extracted_token_info: &[CompiledClassSegment],
    captured_multi_groups_optional: Option<Vec<Option<String>>>,
    token_definitions: &HashMap<String, String>,
) -> (String, Vec<ObjComparatorTokenInfo>) {
    let mut captured_multi_groups_optional = captured_multi_groups_optional.unwrap_or_default();
    let mut comparator_parts = Vec::new();
    let mut augmented = Vec::new();

    for token_info in augmented_extracted_token_info {
        let token = &token_info.segment.token_info.token;
        if token_info.segment.token_info.kind == crate::tel::TokenKind::Literal {
            let escaped = escape_regex_literal(token);
            comparator_parts.push(escaped.clone());
            augmented.push(ObjComparatorTokenInfo {
                segment: token_info.segment.clone(),
                class_comparator_substring: token_info.class_comparator_substring.clone(),
                multi_group_optional: None,
                new_class_type: None,
                regex_pattern: Some(escaped),
            });
            continue;
        }

        let flags = token_info.segment.token_info.flags;
        let needs_captured_class = flags.multi_group || flags.optional || !flags.strict_class;
        let (multi_group_optional, new_class_type) = if needs_captured_class {
            if captured_multi_groups_optional.is_empty() {
                continue;
            }
            let captured = captured_multi_groups_optional.remove(0);
            let new_class_type = captured.as_ref().and_then(|value| {
                if value.is_empty() {
                    None
                } else {
                    Some(value.clone())
                }
            });
            (captured, new_class_type)
        } else {
            (None, token_info.segment.token_info.class_type.clone())
        };

        let regex_pattern = create_regex_pattern(
            token,
            new_class_type.as_deref(),
            &token_info.segment,
            token_definitions,
        );
        comparator_parts.push(regex_pattern.clone());
        augmented.push(ObjComparatorTokenInfo {
            segment: token_info.segment.clone(),
            class_comparator_substring: token_info.class_comparator_substring.clone(),
            multi_group_optional,
            new_class_type,
            regex_pattern: Some(regex_pattern),
        });
    }

    (comparator_parts.join(r"\s*"), augmented)
}

#[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)]
fn create_regex_pattern(
    token: &str,
    class_type_string: Option<&str>,
    segment: &TelSegment,
    token_definitions: &HashMap<String, String>,
) -> String {
    let token_info = &segment.token_info;
    let is_capturing_group = token_info.is_capturing_group();
    let is_optional = matches!(segment.quantity, Quantity::Optional);
    let is_vanishing_group = token_info.is_vanishing_group();

    if is_optional && class_type_string.is_none() {
        return String::new();
    }
    if class_type_string == Some("") {
        return escape_regex_literal(token);
    }

    let resolved_class_type = if is_vanishing_group && class_type_string.is_none() {
        token_info.class_type.clone()
    } else {
        class_type_string.map(ToOwned::to_owned)
    };

    let Some(class_type_string) = resolved_class_type else {
        return String::new();
    };

    let mut regex_fragments = Vec::new();
    for class_type in class_type_string.split_whitespace() {
        let fragment =
            resolve_class_pattern(class_type, segment, token_definitions).unwrap_or_default();
        regex_fragments.push(fragment);
    }

    let mut final_regex = format!(r"{}\s*", regex_fragments.join(r"\s*"));
    final_regex = wrap_regex_group(
        &final_regex,
        is_capturing_group,
        is_optional,
        is_vanishing_group,
    );

    if is_capturing_group || is_vanishing_group {
        final_regex
    } else {
        replace_literal_token_prefix(token, final_regex.as_str())
    }
}

fn resolve_class_pattern(
    class_type: &str,
    segment: &TelSegment,
    token_definitions: &HashMap<String, String>,
) -> Option<String> {
    expand_dictionary_class_type(class_type, segment, token_definitions)
        .or_else(|| modifier_only_fallback(segment))
}

fn replace_literal_token_prefix(token: &str, pattern: &str) -> String {
    let prefix_len = literal_token_prefix_len(token);
    if prefix_len == 0 {
        token.to_string()
    } else {
        format!("{pattern}{}", &token[prefix_len..])
    }
}

fn literal_token_prefix_len(token: &str) -> usize {
    let mut prefix_len = 0_usize;
    for (index, character) in token.char_indices() {
        if character.is_alphanumeric()
            || character == '_'
            || matches!(character, '@' | '#' | ',' | '+' | '?' | '|')
        {
            prefix_len = index + character.len_utf8();
        } else {
            break;
        }
    }
    prefix_len
}

fn escape_regex_literal(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());
    for character in text.chars() {
        if matches!(
            character,
            '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '^' | '$' | '|'
        ) {
            escaped.push('\\');
        }
        escaped.push(character);
    }
    escaped
}

fn expand_dictionary_class_type(
    class_type: &str,
    segment: &TelSegment,
    token_definitions: &HashMap<String, String>,
) -> Option<String> {
    if class_type.is_empty() || token_definitions.is_empty() {
        return None;
    }

    let class_type_list: Vec<&str> = if class_type.starts_with('(') && class_type.ends_with(')') {
        class_type
            .get(3..class_type.len().saturating_sub(1))
            .unwrap_or_default()
            .split('|')
            .collect()
    } else {
        vec![strip_word_boundaries(class_type)]
    };

    let mut regex_patterns = Vec::new();
    let mut fallback_pattern = None;
    for class_name in class_type_list {
        if let Some(pattern) = token_definitions.get(class_name) {
            regex_patterns.push(trim_regex_anchors(pattern).to_string());
        } else {
            fallback_pattern = convert_segment_type_modifier_to_regex(segment);
        }
    }

    if regex_patterns.is_empty() {
        fallback_pattern
    } else {
        Some(format!("(?:{})", regex_patterns.join("|")))
    }
}

fn modifier_only_fallback(segment: &TelSegment) -> Option<String> {
    let modifier = segment.token_info.modifier.as_deref();
    if modifier.is_some_and(|value| {
        value
            .chars()
            .any(|character| matches!(character, '%' | '=' | '$' | '['))
    }) {
        let temp = apply_segment_to_class_type(segment, None);
        if temp.is_some() {
            return temp;
        }
    }
    convert_segment_type_modifier_to_regex(segment)
}

fn trim_regex_anchors(pattern: &str) -> &str {
    let without_start = pattern.strip_prefix('^').unwrap_or(pattern);
    without_start.strip_suffix('$').unwrap_or(without_start)
}

fn wrap_regex_group(
    base_regex: &str,
    is_capturing_group: bool,
    is_optional: bool,
    is_vanishing_group: bool,
) -> String {
    if is_vanishing_group {
        let base_regex = make_non_capturing(base_regex);
        if is_optional {
            format!("({base_regex})?")
        } else {
            base_regex
        }
    } else if is_capturing_group {
        let base_regex = format!("({base_regex})");
        if is_optional {
            format!("{base_regex}?")
        } else {
            base_regex
        }
    } else {
        let base_regex = make_non_capturing(base_regex);
        if is_optional {
            format!("({base_regex})?")
        } else {
            base_regex
        }
    }
}

fn make_non_capturing(pattern: &str) -> String {
    let chars: Vec<char> = pattern.chars().collect();
    let mut output = String::with_capacity(pattern.len());
    let mut index = 0_usize;
    let mut escaped = false;

    while index < chars.len() {
        let character = chars[index];
        if escaped {
            output.push(character);
            escaped = false;
            index += 1;
            continue;
        }
        if character == '\\' {
            output.push(character);
            escaped = true;
            index += 1;
            continue;
        }
        if character == '(' {
            if index + 1 < chars.len() && chars[index + 1] == '?' {
                if index + 3 < chars.len()
                    && chars[index + 1] == '?'
                    && chars[index + 2] == 'P'
                    && chars[index + 3] == '<'
                {
                    output.push_str("(?:");
                    index += 4;
                    while index < chars.len() && chars[index] != '>' {
                        index += 1;
                    }
                    if index < chars.len() && chars[index] == '>' {
                        index += 1;
                    }
                    continue;
                }
                output.push(character);
                index += 1;
                continue;
            }
            output.push_str("(?:");
            index += 1;
            continue;
        }

        output.push(character);
        index += 1;
    }

    output
}

fn get_complement_of_captured_groups(text: &str, matched: &Pcre2Captures) -> String {
    let mut complement_parts = Vec::new();
    let mut start = 0_usize;

    let mut spans = Vec::new();
    for index in 1..matched.len() {
        if let Some(group) = matched.get(index) {
            spans.push((group.start(), group.end()));
        }
    }
    spans.sort_unstable();

    for (group_start, group_end) in spans {
        if group_start > start {
            complement_parts.push(&text[start..group_start]);
        }
        start = group_end;
    }

    if start < text.len() {
        complement_parts.push(&text[start..]);
    }

    complement_parts.concat()
}

fn get_complement_of_spans(text: &str, spans: &[(usize, usize)]) -> String {
    if spans.is_empty() {
        return text.to_string();
    }

    let mut sorted_spans = spans.to_vec();
    sorted_spans.sort_unstable();

    let mut complement_parts = Vec::new();
    let mut start = 0_usize;
    for (span_start, span_end) in sorted_spans {
        if span_start > start {
            complement_parts.push(&text[start..span_start]);
        }
        start = start.max(span_end);
    }
    if start < text.len() {
        complement_parts.push(&text[start..]);
    }

    complement_parts.concat()
}

fn convert_segment_type_modifier_to_regex(segment: &TelSegment) -> Option<String> {
    match filter_for_class_type_modifier(segment).as_deref() {
        None => Some(word_regex().to_string()),
        Some("@") => Some(r"[a-zA-Z]+".to_string()),
        Some("#") => Some(r"[\d]+".to_string()),
        Some(",") => Some(r"[,\-:;]+".to_string()),
        _ => None,
    }
}

fn filter_for_class_type_modifier(segment: &TelSegment) -> Option<String> {
    let mut filtered = String::new();
    if segment.type_modifiers.alpha {
        filtered.push('@');
    }
    if segment.type_modifiers.numeric {
        filtered.push('#');
    }
    if segment
        .token_info
        .modifier
        .as_deref()
        .is_some_and(|value| value.contains(','))
    {
        filtered.push(',');
    }
    if filtered.is_empty() {
        None
    } else {
        Some(filtered)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tel::{TokenKind, split_parse_tokens};
    use std::collections::HashSet;

    fn mock_extractor() -> Extractor {
        let defs = vec![
            ("NUM".to_string(), r"^\d+$".to_string()),
            ("ALPHA".to_string(), r"^[A-Z]+$".to_string()),
            ("STREETTYPE".to_string(), r"^(?:ST|AVE)$".to_string()),
            ("PROV".to_string(), r"^(?:NS|ON)$".to_string()),
        ];
        let classes = vec![(
            "STREETTYPE".to_string(),
            vec!["ST", "AVE"]
                .into_iter()
                .map(String::from)
                .collect::<HashSet<_>>(),
        )];
        Extractor::new(defs, classes)
    }

    #[test]
    fn test_split_parse_tokens_preserves_literal_blocks_and_modifiers() {
        assert_eq!(
            split_parse_tokens("{{Unit}} <<UNIT#?>>"),
            vec!["{{Unit}}", " ", "<<UNIT#?>>"]
        );
        assert_eq!(
            split_parse_tokens(r"ALPHA \(<<TITLE>>\) ALPHA"),
            vec!["ALPHA", " ", "(", "<<TITLE>>", ")", " ", "ALPHA"]
        );
    }

    #[test]
    fn test_extract_token_info_handles_capturing_and_literals() {
        let extractor = mock_extractor();
        let infos = extractor
            .extract_token_info("<<CIVIC#>> \"<<TITLE>>\" <<LAST>>")
            .expect("pattern should parse");
        assert_eq!(infos.len(), 5);
        assert_eq!(infos[0].var_name.as_deref(), Some("CIVIC"));
        assert!(infos[0].is_capturing_group());
        assert_eq!(infos[1].kind, TokenKind::Literal);
        assert_eq!(infos[2].var_name.as_deref(), Some("TITLE"));
    }

    #[test]
    fn test_parse_tokens_matches_python_like_simple_address() {
        let extractor = mock_extractor();
        let tokens = vec![
            "123".to_string(),
            " ".to_string(),
            "MAIN".to_string(),
            " ".to_string(),
            "ST".to_string(),
        ];
        let classes = vec![
            "NUM".to_string(),
            " ".to_string(),
            "ALPHA".to_string(),
            " ".to_string(),
            "STREETTYPE".to_string(),
        ];
        let output = extractor
            .parse_tokens(
                "123 MAIN ST",
                &tokens,
                &classes,
                "<<CIVIC#>> <<STREET@>> <<TYPE::STREETTYPE>>",
                MatchMode::Whole,
            )
            .expect("pattern should parse");
        assert_eq!(output.fields.get("CIVIC").map(String::as_str), Some("123"));
        assert_eq!(
            output.fields.get("STREET").map(String::as_str),
            Some("MAIN")
        );
        assert_eq!(output.fields.get("TYPE").map(String::as_str), Some("ST"));
        assert_eq!(output.complement, "");
    }

    #[test]
    fn test_class_comparator_filters_expected_groups() {
        let extractor = mock_extractor();
        let compiled = extractor
            .compile_pattern("<<CIVIC#>> <<STREET@>> <<TYPE>>")
            .expect("pattern should parse");
        let class_pattern = compiled.class_pattern(MatchMode::Whole).to_string();
        let class_regex = compiled
            .class_regex(MatchMode::Whole)
            .expect("class regex compiles");
        let captures = class_regex
            .captures(b"NUM ALPHA STREETTYPE")
            .expect("class regex runs")
            .unwrap_or_else(|| panic!("class comparator should match: {class_pattern}"));
        let groups = capture_groups(&captures);
        let filtered = filter_class_groups(&groups, compiled.class_segments());

        assert_eq!(
            groups,
            vec![
                Some("NUM".to_string()),
                Some("ALPHA".to_string()),
                Some("STREETTYPE".to_string()),
            ]
        );
        assert_eq!(
            filtered,
            Some(vec![
                Some("NUM".to_string()),
                Some("ALPHA".to_string()),
                Some("STREETTYPE".to_string()),
            ])
        );
    }

    #[test]
    fn test_parse_tokens_matches_python_like_class_filter_case() {
        let extractor = mock_extractor();
        let tokens = vec!["TEST".to_string()];
        let classes = vec!["ALPHA".to_string()];
        let output = extractor
            .parse_tokens(
                "TEST",
                &tokens,
                &classes,
                "<<VAR[ALPHA|NUM]>>",
                MatchMode::Whole,
            )
            .expect("pattern should parse");

        assert_eq!(output.fields.get("VAR").map(String::as_str), Some("TEST"));
        assert_eq!(output.complement, "");
    }

    #[test]
    fn test_parse_tokens_matches_python_like_optional_prefix_case() {
        let extractor = mock_extractor();
        let tokens = vec!["NS".to_string()];
        let classes = vec!["PROV".to_string()];
        let output = extractor
            .parse_tokens(
                "NS",
                &tokens,
                &classes,
                "<<MUN@+?#>> <<PROV::PROV>>",
                MatchMode::Whole,
            )
            .expect("pattern should parse");

        assert_eq!(output.fields.get("PROV").map(String::as_str), Some("NS"));
        assert_eq!(output.fields.get("MUN"), None);
        assert_eq!(output.complement, "");
    }

    #[test]
    fn test_parse_tokens_matches_python_like_start_mode_prefix_case() {
        let extractor = mock_extractor();
        let tokens = vec![
            "123".to_string(),
            " ".to_string(),
            "MAIN".to_string(),
            " ".to_string(),
            "ST".to_string(),
            " ".to_string(),
            "EXTRA".to_string(),
        ];
        let classes = vec![
            "NUM".to_string(),
            " ".to_string(),
            "ALPHA".to_string(),
            " ".to_string(),
            "ALPHA".to_string(),
            " ".to_string(),
            "ALPHA".to_string(),
        ];
        let output = extractor
            .parse_tokens(
                "123 MAIN ST EXTRA",
                &tokens,
                &classes,
                "<<CIVIC#>> <<STREET@>>",
                MatchMode::Start,
            )
            .expect("pattern should parse");

        assert_eq!(output.fields.get("CIVIC").map(String::as_str), Some("123"));
        assert_eq!(
            output.fields.get("STREET").map(String::as_str),
            Some("MAIN")
        );
        assert_eq!(output.complement, "ST EXTRA");
    }

    #[test]
    fn test_borrowed_parse_entry_points_match_owned_parse_tokens() {
        let extractor = mock_extractor();
        let tokens = vec![
            " ".to_string(),
            "123".to_string(),
            " ".to_string(),
            "MAIN".to_string(),
            " ".to_string(),
            "ST".to_string(),
            " ".to_string(),
        ];
        let classes = vec![
            " ".to_string(),
            "NUM".to_string(),
            " ".to_string(),
            "ALPHA".to_string(),
            " ".to_string(),
            "STREETTYPE".to_string(),
            " ".to_string(),
        ];
        let class_views: Vec<&str> = classes.iter().map(String::as_str).collect();
        let token_views: Vec<&str> = tokens.iter().map(String::as_str).collect();
        let pattern = "<<CIVIC#>> <<STREET@>> <<TYPE::STREETTYPE>>";

        let owned = extractor
            .parse_tokens(
                " 123 MAIN ST ",
                &tokens,
                &classes,
                pattern,
                MatchMode::Whole,
            )
            .expect("owned parse should succeed");
        let borrowed_classes = extractor
            .parse_tokens_with_classes(
                " 123 MAIN ST ",
                &tokens,
                &class_views,
                pattern,
                MatchMode::Whole,
            )
            .expect("borrowed class parse should succeed");
        let borrowed_views = extractor
            .parse_tokens_with_views(
                " 123 MAIN ST ",
                &token_views,
                &class_views,
                pattern,
                MatchMode::Whole,
            )
            .expect("borrowed token/class parse should succeed");

        assert_eq!(borrowed_classes, owned);
        assert_eq!(borrowed_views, owned);
        assert_eq!(owned.complement, " ");
    }

    #[test]
    fn test_join_class_tokens_inserts_separator_only_when_merging() {
        // Adjacent word-class names gain a single space so the `\b`-wrapped
        // class fragments have a boundary to match on.
        let (joined, offsets) = join_class_tokens_with_offsets(&["NUM", "DASH", "NUM"]);
        assert_eq!(joined, "NUM DASH NUM");
        assert_eq!(offsets, vec![(0, 3), (4, 8), (9, 12)]);

        // Whitespace/punctuation-separated names are byte-for-byte unchanged.
        let (spaced, spaced_offsets) = join_class_tokens_with_offsets(&["NUM", " ", "ALPHA"]);
        assert_eq!(spaced, "NUM ALPHA");
        assert_eq!(spaced_offsets, vec![(0, 3), (3, 4), (4, 9)]);
        let (punct, _) = join_class_tokens_with_offsets(&["N", ", ", "MUN"]);
        assert_eq!(punct, "N, MUN");
    }

    #[test]
    fn test_extracts_from_adjacent_dash_split_tokens() {
        // Regression: a model word definition that excludes `-` splits "11-47"
        // into adjacent tokens (11, -, 47) whose class names would otherwise
        // concatenate to "NUMDASHNUM" and never match. A vanishing group
        // consumes the dash; the two numbers extract cleanly.
        let defs = vec![
            ("NUM".to_string(), r"^\d+$".to_string()),
            ("DASH".to_string(), r"^-$".to_string()),
        ];
        let extractor = Extractor::new(defs, vec![]);
        let tokens = vec!["11".to_string(), "-".to_string(), "47".to_string()];
        let classes = vec!["NUM".to_string(), "DASH".to_string(), "NUM".to_string()];
        let output = extractor
            .parse_tokens(
                "11-47",
                &tokens,
                &classes,
                "<<UNIT::NUM>> <!DASH!> <<CIVIC::NUM>>",
                MatchMode::Start,
            )
            .expect("pattern should parse");
        assert_eq!(output.fields.get("UNIT").map(String::as_str), Some("11"));
        assert_eq!(output.fields.get("CIVIC").map(String::as_str), Some("47"));
    }

    #[test]
    fn test_vanishing_group_is_class_strict() {
        // Regression: `<!DASH!>` must require a DASH-class token, not skip any
        // word token -- the legacy behavior let `<<U::NUM>> <!DASH!> <<C::NUM>>`
        // match "1500 HWY 7" by silently consuming the STREETTYPE token.
        let defs = vec![
            ("NUM".to_string(), r"^\d+$".to_string()),
            ("ALPHA".to_string(), r"^[A-Z]+$".to_string()),
            ("DASH".to_string(), r"^-$".to_string()),
        ];
        let extractor = Extractor::new(defs, vec![]);
        let tokens = vec!["1500".to_string(), "HWY".to_string(), "7".to_string()];
        let classes = vec!["NUM".to_string(), "ALPHA".to_string(), "NUM".to_string()];
        let output = extractor
            .parse_tokens(
                "1500 HWY 7",
                &tokens,
                &classes,
                "<<UNIT::NUM>> <!DASH!> <<CIVIC::NUM>>",
                MatchMode::Start,
            )
            .expect("pattern should parse");
        assert!(
            !output.fields.contains_key("UNIT"),
            "a vanishing group must not consume a token of another class"
        );
    }

    #[test]
    fn test_vanishing_wordx_skips_any_token() {
        // `<!WORDX!>` is the sanctioned skip-any wildcard: it resolves to the
        // word-shape regex instead of a class name, so it consumes one token
        // regardless of its class.
        let defs = vec![
            ("NUM".to_string(), r"^\d+$".to_string()),
            ("ALPHA".to_string(), r"^[A-Z]+$".to_string()),
        ];
        let extractor = Extractor::new(defs, vec![]);
        let tokens = vec!["1500".to_string(), "HWY".to_string(), "7".to_string()];
        let classes = vec!["NUM".to_string(), "ALPHA".to_string(), "NUM".to_string()];
        let output = extractor
            .parse_tokens(
                "1500 HWY 7",
                &tokens,
                &classes,
                "<<UNIT::NUM>> <!WORDX!> <<CIVIC::NUM>>",
                MatchMode::Start,
            )
            .expect("pattern should parse");
        assert_eq!(output.fields.get("UNIT").map(String::as_str), Some("1500"));
        assert_eq!(output.fields.get("CIVIC").map(String::as_str), Some("7"));
    }
}