cdx 0.1.23

Library and application for text file manipulation and command line data mining, a little like the gnu textutils
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
//! Test if a [`TextLine`], `str` or `&[u8]` matches a pattern
//!
//! A `Matcher` is a generalization of a Regular Expression.
//! It answers "does a pattern match a target", but you supply a
//! method, in addition to a pattern. The `regex` crate provides
//! one such method, but many other, simpler, methods are also available.
//! See <https://avjewe.github.io/cdxdoc/Matcher.html> for a list of matchers,
//! and other details about the syntax for specifying languages,
//!
//! Most uses will involve [Matcher]s, collected into [`MatcherList`]s, or
//!
//!```
//! use cdx::matcher::*;
//! use cdx::prelude::*;
//! cdx::util::init();
//! let matcher = MatchMaker::make("prefix,abc")?;
//! assert!(matcher.umatch(b"abcdef"));
//! assert!(!matcher.umatch(b"bcdef"));
//! assert!(matcher.smatch("abcdef"));
//! assert!(!matcher.smatch("bcdef"));
//!
//! let mut list = LineMatcherList::new_with(Combiner::And);
//! list.push("two,glob,b*")?;
//! let input = "<< CDX\tone\ttwo\naaa\tbbb\nccc\tddd\n";
//! let mut reader = Reader::new(&TextFileMode::default());
//! reader.open(input);
//! list.lookup(&reader.names())?;
//! assert!(list.ok(reader.curr_line()));
//! reader.get_line()?;
//! assert!(!list.ok(reader.curr_line()));
//! # Ok::<(), cdx::util::Error>(())
//!```

use crate::comp::{Comp, CompMaker};
use crate::num;
use crate::prelude::*;
use crate::util::{self, CheckBuff, CompareOp};
use memchr::memmem::find;
use regex::Regex;
use std::collections::HashSet;
use std::fmt::Write;
use std::sync::Mutex;

/// Match against [`TextLine`]
pub trait LineMatch {
    /// Is this line ok?
    fn ok(&mut self, line: &TextLine) -> bool;
    /// Resolve any named columns.
    fn lookup(&mut self, field_names: &[&str]) -> Result<()>;
    /// Human readable description
    fn show(&self) -> String;
    /// Is this line ok? If not, write explanation to stderr
    fn ok_verbose(&mut self, line: &TextLine, line_num: usize, fname: &str) -> bool {
        let ret = self.ok(line);
        if !ret {
            eprintln!("Line {} of {} failed to {}", line_num, fname, self.show());
        }
        ret
    }
}

const fn not_str(negate: bool) -> &'static str {
    if negate { "not-" } else { "" }
}

/// Match against `str` or `&[u8]`
pub trait Match {
    /// Are these characters ok?
    fn smatch(&self, buff: &str) -> bool;
    /// Are these bytes ok?
    fn umatch(&self, buff: &[u8]) -> bool;
    /// Human readable description
    fn show(&self) -> String {
        format!("stuff {}", 27)
    }
    /// smatch, but print to stderr if fail
    fn verbose_smatch(&self, buff: &str, negate: bool) -> bool {
        let res = self.smatch(buff);
        if res != negate {
            eprintln!("Failed to {}match {} against {}", not_str(negate), buff, self.show());
        }
        res
    }
    /// umatch, but print to stderr if fail
    fn verbose_umatch(&self, buff: &[u8], negate: bool) -> bool {
        let res = self.umatch(buff);
        if res != negate {
            eprintln!(
                "Failed to {}match {} against {}",
                not_str(negate),
                String::from_utf8_lossy(buff),
                self.show()
            );
        }
        res
    }
}

impl fmt::Debug for dyn Match + '_ {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.show())
    }
}
impl fmt::Display for dyn Match + '_ {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.show())
    }
}
impl fmt::Debug for dyn LineMatch + '_ {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.show())
    }
}
impl fmt::Display for dyn LineMatch + '_ {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.show())
    }
}

/// a threshold
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Thresh {
    /// number of items
    Count(usize),
    /// must be 0.0..=1.0
    /// 0/0 == 0
    Frac(f64),
}
impl Default for Thresh {
    fn default() -> Self {
        Self::Count(0)
    }
}
impl Thresh {
    /// If decimal point then frac, else count
    pub fn new(spec: &str) -> Result<Self> {
        if spec.contains('.') {
            Self::new_frac(spec.to_f64_whole(spec.as_bytes(), "Threshold for Determiner")?)
        } else {
            Ok(Self::new_count(spec.to_usize_whole(spec.as_bytes(), "Threshold for Determiner")?))
        }
    }
    /// new Count
    #[must_use]
    pub const fn new_count(c: usize) -> Self {
        Self::Count(c)
    }
    /// new Frac
    pub fn new_frac(c: f64) -> Result<Self> {
        if (0.0..=1.0).contains(&c) {
            Ok(Self::Frac(c))
        } else {
            err!("Value {c} must be between 0 and 1 inclusive")
        }
    }
    /// we've seen this many, with more to come. Are we done yet?
    #[must_use]
    pub const fn at_most_mid(&self, n: usize) -> Tri {
        match self {
            Self::Count(c) => Tri::no_if(n > *c),
            Self::Frac(_) => Tri::Maybe,
        }
    }
    /// we've seen this many, with more to come. Are we done yet?
    #[must_use]
    pub const fn at_least_mid(&self, n: usize) -> Tri {
        match self {
            Self::Count(c) => Tri::yes_if(n >= *c),
            Self::Frac(_) => Tri::Maybe,
        }
    }
    /// we've seen this many, is that a match?
    #[must_use]
    pub fn at_most_final(&self, n: usize, tot: usize) -> bool {
        match self {
            Self::Count(c) => n <= *c,
            Self::Frac(f) => num::f64_less(*f, n, tot),
        }
    }
    /// we've seen this many, is that a match?
    #[must_use]
    pub fn at_least_final(&self, n: usize, tot: usize) -> bool {
        match self {
            Self::Count(c) => n >= *c,
            Self::Frac(f) => num::f64_greater(*f, n, tot),
        }
    }
    /// we've seen this many, is that a match?
    #[must_use]
    pub fn exactly(&self, n: usize, tot: usize) -> bool {
        match self {
            Self::Count(c) => n == *c,
            Self::Frac(f) => num::f64_equal(*f, n, tot),
        }
    }
}

/// Given some YES's and some NO's, do we match?
#[derive(Copy, Clone, Debug, PartialEq, Default)]
pub enum Determiner {
    /// no occurrences of NO
    All,
    /// at least 1 YES
    #[default]
    Some,
    /// no occurrences of YES
    None,
    /// at least 1 NO
    NotAll,
    /// at least 1 NO and at least 1 YES
    Mixed,
    /// either All or None
    Uniform,
    /// At most this many YES's,
    AtMost(Thresh),
    /// At least this many YES's,
    AtLeast(Thresh),
    /// Exactly this many YES's,
    Exactly(Thresh),
    /// At most this many NO's,
    AtMostNo(Thresh),
    /// At least this many NO's,
    AtLeastNo(Thresh),
    /// Exactly this many NO's,
    ExactlyNo(Thresh),
}

impl Determiner {
    /// new from spec  "all" or "atleast,42"
    pub fn new(spec: &str) -> Result<Self> {
        Ok(if spec.eq_ignore_ascii_case("all") {
            Self::All
        } else if spec.eq_ignore_ascii_case("some") {
            Self::Some
        } else if spec.eq_ignore_ascii_case("none") {
            Self::None
        } else if spec.eq_ignore_ascii_case("notall") {
            Self::NotAll
        } else if spec.eq_ignore_ascii_case("mixed") {
            Self::Mixed
        } else if spec.eq_ignore_ascii_case("uniform") {
            Self::Uniform
        } else if let Some(thresh) = spec.strip_prefix("atmost,") {
            Self::AtMost(Thresh::new(thresh)?)
        } else if let Some(thresh) = spec.strip_prefix("atleast,") {
            Self::AtLeast(Thresh::new(thresh)?)
        } else if let Some(thresh) = spec.strip_prefix("exactly,") {
            Self::Exactly(Thresh::new(thresh)?)
        } else if let Some(thresh) = spec.strip_prefix("atmostno,") {
            Self::AtMostNo(Thresh::new(thresh)?)
        } else if let Some(thresh) = spec.strip_prefix("atleastno,") {
            Self::AtLeastNo(Thresh::new(thresh)?)
        } else if let Some(thresh) = spec.strip_prefix("exactlyno,") {
            Self::ExactlyNo(Thresh::new(thresh)?)
        } else {
            return err!("Unknown Determiner {spec}");
        })
    }
    /// we've seen this many yes's and this many no's, with more to come. Are we done yet?
    #[must_use]
    pub const fn match_mid(&self, yes: usize, no: usize) -> Tri {
        use Determiner::{
            All, AtLeast, AtLeastNo, AtMost, AtMostNo, Exactly, ExactlyNo, Mixed, None, NotAll,
            Some, Uniform,
        };
        match self {
            All => Tri::no_if(no > 0),
            Some => Tri::yes_if(yes > 0),
            None => Tri::no_if(yes > 0),
            NotAll => Tri::yes_if(no > 0),
            Mixed => Tri::yes_if(yes > 0 && no > 0),
            Uniform => Tri::no_if(yes > 0 && no > 0),
            AtMost(t) => t.at_most_mid(yes),
            AtLeast(t) => t.at_least_mid(yes),
            Exactly(t) => t.at_most_mid(yes),
            AtMostNo(t) => t.at_most_mid(no),
            AtLeastNo(t) => t.at_least_mid(no),
            ExactlyNo(t) => t.at_most_mid(no),
        }
    }

    /// we've seen this many yes's and this many no's, with more to come. Is that a match?
    #[must_use]
    pub fn match_final(&self, yes: usize, no: usize) -> bool {
        use Determiner::{
            All, AtLeast, AtLeastNo, AtMost, AtMostNo, Exactly, ExactlyNo, Mixed, None, NotAll,
            Some, Uniform,
        };
        let tot = yes + no;
        match self {
            All => no == 0,
            Some => yes > 0,
            None => yes == 0,
            NotAll => no > 0,
            Mixed => yes > 0 && no > 0,
            Uniform => yes == 0 || no == 0,
            AtMost(t) => t.at_most_final(yes, tot),
            AtLeast(t) => t.at_least_final(yes, tot),
            Exactly(t) => t.exactly(yes, tot),
            AtMostNo(t) => t.at_most_final(no, tot),
            AtLeastNo(t) => t.at_least_final(no, tot),
            ExactlyNo(t) => t.exactly(no, tot),
        }
    }
}

impl Match for CheckBuff {
    fn smatch(&self, buff: &str) -> bool {
        self.umatch(buff.as_bytes())
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        self.buff_ok(buff)
    }
    fn show(&self) -> String {
        "Compare Match".to_string() // FIXME
    }
}

// pattern is prefix of string
#[derive(Debug, Clone)]
struct PrefixMatch {
    data: String,
}

impl PrefixMatch {
    fn new(data: &str) -> Self {
        Self { data: data.to_string() }
    }
}
impl Match for PrefixMatch {
    fn smatch(&self, buff: &str) -> bool {
        buff.starts_with(&self.data)
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        buff.starts_with(self.data.as_bytes())
    }
    fn show(&self) -> String {
        format!("Prefix Match of {}", self.data)
    }
}
/*
pub fn extend_to_lowercase(src: &str, dst: &mut String) {
    let (mut s, rest) = convert_while_ascii(self, u8::to_ascii_lowercase);

    let prefix_len = s.len();

    for (i, c) in rest.char_indices() {
        if c == 'Σ' {
            // Σ maps to σ, except at the end of a word where it maps to ς.
            // This is the only conditional (contextual) but language-independent mapping
            // in `SpecialCasing.txt`,
            // so hard-code it rather than have a generic "condition" mechanism.
            // See https://github.com/rust-lang/rust/issues/26035
            let sigma_lowercase = map_uppercase_sigma(self, prefix_len + i);
            s.push(sigma_lowercase);
        } else {
            match conversions::to_lower(c) {
                [a, '\0', _] => s.push(a),
                [a, b, '\0'] => {
                    s.push(a);
                    s.push(b);
                }
                [a, b, c] => {
                    s.push(a);
                    s.push(b);
                    s.push(c);
                }
            }
        }
    }
    return s;
}
*/

#[derive(Debug, Clone, Copy)]
struct CountedValue<T> {
    thresh: usize,
    value: T,
}

impl CountedValue<char> {
    fn count_str(&self, data: &str) -> usize {
        let mut ret = 0usize;
        for x in data.chars() {
            if x == self.value {
                ret += 1;
            }
        }
        ret
    }
    fn count_str_insensitive(&self, data: &str) -> usize {
        let mut ret = 0usize;
        for x in data.chars() {
            let y = x.to_lowercase().next().unwrap();
            if y == self.value {
                ret += 1;
            }
        }
        ret
    }
    fn keep_str(&self, data: &str) -> bool {
        self.count_str(data) >= self.thresh
    }
    fn reject_str(&self, data: &str) -> bool {
        self.count_str(data) < self.thresh
    }
    fn ok_str(&self, data: &str, keep: bool) -> bool {
        if keep { self.keep_str(data) } else { self.reject_str(data) }
    }
    fn keep_str_insensitive(&self, data: &str) -> bool {
        self.count_str_insensitive(data) >= self.thresh
    }
    fn reject_str_insensitive(&self, data: &str) -> bool {
        self.count_str_insensitive(data) < self.thresh
    }
    fn ok_str_insensitive(&self, data: &str, keep: bool) -> bool {
        if keep { self.keep_str_insensitive(data) } else { self.reject_str_insensitive(data) }
    }
}

impl<T: Copy + PartialEq + fmt::Debug> CountedValue<T> {
    const fn new(value: T) -> Self {
        Self { thresh: 1, value }
    }
    fn count<F>(&self, data: &[T], f: F) -> usize
    where
        F: Fn(T) -> T,
    {
        let mut ret = 0usize;
        for x in data {
            if f(*x) == self.value {
                ret += 1;
            }
        }
        ret
    }
    fn increment(item: T, data: &mut Vec<Self>) {
        for x in data.iter_mut() {
            if item == x.value {
                x.thresh += 1;
                return;
            }
        }
        data.push(Self::new(item));
    }
    fn with_data<F>(data: &[T], f: F) -> Vec<Self>
    where
        F: Fn(T) -> T,
    {
        let mut ret = Vec::with_capacity(data.len());
        for x in data {
            Self::increment(f(*x), &mut ret);
        }
        ret
    }
    fn keep<F>(&self, data: &[T], f: F) -> bool
    where
        F: Fn(T) -> T,
    {
        self.count(data, f) >= self.thresh
    }
    fn reject<F>(&self, data: &[T], f: F) -> bool
    where
        F: Fn(T) -> T,
    {
        self.count(data, f) < self.thresh
    }
    fn ok<F>(&self, data: &[T], keep: bool, f: F) -> bool
    where
        F: Fn(T) -> T,
    {
        if keep { self.keep(data, f) } else { self.reject(data, f) }
    }
}

#[derive(Debug, Clone)]
/// match if value contains all of these characters
struct OccurMatch {
    s_data: Vec<CountedValue<char>>,
    u_data: Vec<CountedValue<u8>>,
    case: Case,
    keep: bool,
}

impl OccurMatch {
    fn new(data: &str, matcher: &Matcher, keep: bool) -> Self {
        let case = matcher.case;
        let u_data = if case == Case::Insens {
            CountedValue::with_data(data.as_bytes(), |x| x.to_ascii_lowercase())
        } else {
            CountedValue::with_data(data.as_bytes(), |x| x)
        };
        let mut s_data = Vec::new();
        if case == Case::Insens {
            for x in data.chars() {
                if x.is_ascii() {
                    CountedValue::increment(x.to_ascii_lowercase(), &mut s_data);
                } else {
                    CountedValue::increment(x.to_lowercase().next().unwrap(), &mut s_data);
                }
            }
        } else {
            for x in data.chars() {
                CountedValue::increment(x, &mut s_data);
            }
        }

        Self { s_data, u_data, case, keep }
    }
}

impl Match for OccurMatch {
    fn smatch(&self, buff: &str) -> bool {
        if self.case == Case::Sens {
            for ch in &self.s_data {
                if !ch.ok_str(buff, self.keep) {
                    return false;
                }
            }
        } else {
            for ch in &self.s_data {
                if !ch.ok_str_insensitive(buff, self.keep) {
                    return false;
                }
            }
        }
        true
    }

    fn umatch(&self, buff: &[u8]) -> bool {
        if self.case == Case::Sens {
            for ch in &self.u_data {
                if !ch.ok(buff, self.keep, |x| x) {
                    return false;
                }
            }
        } else {
            for ch in &self.u_data {
                if !ch.ok(buff, self.keep, |x| x.to_ascii_lowercase()) {
                    return false;
                }
            }
        }
        true
    }
}

#[derive(Debug, Clone)]
/// pattern is prefix of string, case insensitive
struct PrefixMatchC {
    s_data: String,
    u_data: Vec<u8>,
}
impl PrefixMatchC {
    fn new(data: &str) -> Self {
        Self { s_data: data.to_lowercase(), u_data: data.as_bytes().to_ascii_lowercase() }
    }
}

fn scase_prefix(haystack: &str, needle: &str) -> bool {
    let mut iter1 = needle.chars();
    let mut iter2 = haystack.chars().flat_map(char::to_lowercase);
    loop {
        let c1 = iter1.next();
        let c2 = iter2.next();
        if c1.is_none() {
            return true;
        }
        if c2.is_none() {
            return false;
        }
        if c1.unwrap() != c2.unwrap() {
            return false;
        }
    }
}

fn bcase_prefix(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.len() > haystack.len() {
        return false;
    }
    for x in 0..needle.len() {
        if haystack[x].to_ascii_lowercase() != needle[x] {
            return false;
        }
    }
    true
}

fn bcase_suffix(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.len() > haystack.len() {
        return false;
    }
    let hay_len = haystack.len() - 1;
    let nee_len = needle.len() - 1;
    for x in 0..needle.len() {
        if haystack[hay_len - x].to_ascii_lowercase() != needle[nee_len - x] {
            return false;
        }
    }
    true
}

// needle is already lowercase
fn scase_suffix(haystack: &str, needle: &str) -> bool {
    let needle_len = needle.chars().count();
    let haystack_len = haystack.chars().flat_map(char::to_lowercase).count();
    if needle_len > haystack_len {
        return false;
    }
    let mut needle_it = needle.chars();
    let mut haystack_it =
        haystack.chars().flat_map(char::to_lowercase).skip(haystack_len - needle_len);

    // at this moment, needle_it.chars().count() == haystack_it.chars().count()
    for _ in 0..needle_len {
        if needle_it.next().unwrap() != haystack_it.next().unwrap() {
            return false;
        }
    }
    true
}

impl Match for PrefixMatchC {
    fn smatch(&self, buff: &str) -> bool {
        scase_prefix(buff, &self.s_data)
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        bcase_prefix(buff, &self.u_data)
    }
    fn show(&self) -> String {
        format!("Case-insensitive refix Match of {}", self.s_data)
    }
}

#[derive(Debug, Clone)]
/// pattern is suffix of string
struct SuffixMatch {
    data: String,
}
impl SuffixMatch {
    fn new(data: &str) -> Self {
        Self { data: data.to_string() }
    }
}
impl Match for SuffixMatch {
    fn smatch(&self, buff: &str) -> bool {
        buff.ends_with(&self.data)
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        buff.ends_with(self.data.as_bytes())
    }
    fn show(&self) -> String {
        format!("Suffix Match of {}", self.data)
    }
}

#[derive(Debug, Clone)]
/// pattern is suffix of string, case insensitive
struct SuffixMatchC {
    s_data: String,
    u_data: Vec<u8>,
}
impl SuffixMatchC {
    fn new(data: &str) -> Self {
        Self { s_data: data.to_lowercase(), u_data: data.as_bytes().to_ascii_lowercase() }
    }
}
impl Match for SuffixMatchC {
    fn smatch(&self, buff: &str) -> bool {
        scase_suffix(buff, &self.s_data)
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        bcase_suffix(buff, &self.u_data)
    }
    fn show(&self) -> String {
        format!("Case-insensitive suffix Match of {}", self.s_data)
    }
}

#[derive(Debug, Clone)]
/// pattern is substring of string, case insensitive
struct InfixMatchC {
    s_data: String,
    u_data: Vec<u8>,
}
impl InfixMatchC {
    fn new(data: &str) -> Self {
        Self { s_data: data.to_lowercase(), u_data: data.as_bytes().to_ascii_lowercase() }
    }
}
impl Match for InfixMatchC {
    fn smatch(&self, buff: &str) -> bool {
        buff.to_lowercase().contains(&self.s_data) // PERF allocation
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        find(&buff.to_ascii_lowercase(), &self.u_data).is_some() // PERF allocation
    }
    fn show(&self) -> String {
        format!("Case insensitive substring Match of {}", self.s_data)
    }
}

#[derive(Debug, Clone)]
/// pattern is substring of string
struct InfixMatch {
    needle: String,
}
impl InfixMatch {
    fn new(data: &str) -> Self {
        Self { needle: data.to_string() }
    }
}
impl Match for InfixMatch {
    fn smatch(&self, buff: &str) -> bool {
        find(buff.as_bytes(), self.needle.as_bytes()).is_some()
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        find(buff, self.needle.as_bytes()).is_some()
    }
    fn show(&self) -> String {
        format!("Substring Match of {}", self.needle)
    }
}

#[derive(Debug, Clone)]
/// bytes regex
struct RegexMatch {
    s_data: Regex,
    u_data: regex::bytes::Regex,
    pattern: String,
}
impl RegexMatch {
    fn new(data: &str, case: Case) -> Result<Self> {
        Ok(Self {
            s_data: regex::RegexBuilder::new(data)
                .case_insensitive(case == Case::Insens)
                .build()?,
            u_data: regex::bytes::RegexBuilder::new(data)
                .case_insensitive(case == Case::Insens)
                .build()?,
            pattern: data.to_string(),
        })
    }
}
impl Match for RegexMatch {
    fn smatch(&self, buff: &str) -> bool {
        self.s_data.is_match(buff)
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        self.u_data.is_match(buff)
    }
    fn show(&self) -> String {
        format!("Regex Match of {}", self.pattern)
    }
}

#[derive(Debug, Clone)]
/// string exactly matches pattern
struct ExactMatch {
    data: String,
}
impl ExactMatch {
    fn new(data: &str) -> Self {
        Self { data: data.to_string() }
    }
}
impl Match for ExactMatch {
    fn smatch(&self, buff: &str) -> bool {
        self.data == buff
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        self.data.as_bytes() == buff
    }
    fn show(&self) -> String {
        format!("Exact Match of {}", self.data)
    }
}

fn load_hashset(data: &mut HashSet<Vec<u8>>, fname: &str) -> Result<()> {
    let mut f = Reader::new(&TextFileMode::default());
    f.do_split(false);
    f.open(fname)?;
    if f.is_done() {
        return Ok(());
    }
    loop {
        let line = &f.curr().line();
        if line.len() > 1 {
            data.insert(line[0..line.len() - 1].to_vec());
        }
        if f.get_line()? {
            break;
        }
    }
    Ok(())
}

#[derive(Debug, Clone)]
/// pattern is file name. String exactly matches one line of file.
struct FileExactMatch {
    data: HashSet<Vec<u8>>,
    file_name: String,
}
impl FileExactMatch {
    fn new(file_name: &str) -> Result<Self> {
        let mut d = HashSet::new();
        load_hashset(&mut d, file_name)?;
        Ok(Self { data: d, file_name: file_name.to_string() })
    }
}
impl Match for FileExactMatch {
    fn smatch(&self, buff: &str) -> bool {
        self.data.contains(buff.as_bytes())
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        self.data.contains(buff)
    }
    fn show(&self) -> String {
        format!("Exact Match of one line in file {}", self.file_name)
    }
}

fn load_hashset_c(data: &mut HashSet<Vec<u8>>, fname: &str, unicode: bool) -> Result<()> {
    let mut f = Reader::new(&TextFileMode::default());
    f.do_split(false);
    f.open(fname)?;
    if f.is_done() {
        return Ok(());
    }
    loop {
        let mut line: &[u8] = f.curr().line();
        if line.len() > 1 {
            if line.last().unwrap() == &b'\n' {
                line = &line[..line.len() - 1];
            }
            if unicode {
                data.insert(String::from_utf8(line.to_vec())?.new_lower().into_bytes());
            // PERF - 2 allocations
            } else {
                data.insert(line.new_lower());
            }
        }
        if f.get_line()? {
            break;
        }
    }
    Ok(())
}

#[derive(Debug, Clone)]
/// pattern is file name. String exactly matches one line of file, case insensitive
struct FileExactMatchC {
    data: HashSet<Vec<u8>>,
    file_name: String,
}
impl FileExactMatchC {
    fn new(file_name: &str, unicode: bool) -> Result<Self> {
        let mut d = HashSet::new();
        load_hashset_c(&mut d, file_name, unicode)?;
        Ok(Self { data: d, file_name: file_name.to_string() })
    }
}
impl Match for FileExactMatchC {
    fn smatch(&self, buff: &str) -> bool {
        self.data.contains(&buff.new_lower().into_bytes()) // PERF allocation
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        self.data.contains(&buff.new_lower()) // PERF allocation
    }
    fn show(&self) -> String {
        format!("Case insensitive match of one line in file {}", self.file_name)
    }
}

#[derive(Debug, Clone)]
/// shell style wildcard match
struct GlobMatch {
    data: String,
    ic: Case,
}
impl GlobMatch {
    fn new(data: &str, ic: Case) -> Self {
        Self { data: data.to_string(), ic }
    }
}
impl Match for GlobMatch {
    fn smatch(&self, buff: &str) -> bool {
        buff.glob(&self.data, self.ic)
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        buff.glob(self.data.as_bytes(), self.ic)
    }
    fn show(&self) -> String {
        let prefix = if self.ic == Case::Insens { "in" } else { "" };
        format!("Case {}sensitive match of glob {}", prefix, self.data)
    }
}

#[derive(Debug, Clone)]
/// string exactly matches pattern, case insensitive
struct ExactMatchC {
    s_data: String,
    u_data: Vec<u8>,
}

impl ExactMatchC {
    fn new(data: &str) -> Self {
        Self { s_data: data.new_lower(), u_data: data.as_bytes().new_lower() }
    }
}
impl Match for ExactMatchC {
    fn smatch(&self, buff: &str) -> bool {
        buff.equal_insens_quick(&self.s_data)
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        buff.equal_insens_quick(&self.u_data)
    }
    fn show(&self) -> String {
        format!("Case insensitive exact match of {}", self.s_data)
    }
}

#[derive(Debug, Clone, Default, Copy)]
/// Always Matches
struct YesMatch {}
impl Match for YesMatch {
    fn smatch(&self, _buff: &str) -> bool {
        true
    }
    fn umatch(&self, _buff: &[u8]) -> bool {
        true
    }
    fn show(&self) -> String {
        "Always Matches".to_string()
    }
}

#[derive(Debug, Clone, Default, Copy)]
/// Never Matches
struct NoMatch {}
impl Match for NoMatch {
    fn smatch(&self, _buff: &str) -> bool {
        false
    }
    fn umatch(&self, _buff: &[u8]) -> bool {
        false
    }
    fn show(&self) -> String {
        "Never Matches".to_string()
    }
}

#[derive(Debug, Clone, Default, Copy)]
/// match length
struct LengthMatch {
    min: usize,
    max: Option<usize>,
}
impl LengthMatch {
    /// new
    fn new(data: &str) -> Result<Self> {
        if data.is_empty() {
            return err!("Length spec can't be empty");
        }
        let mut val = Self::default();
        for (n, x) in data.split(',').enumerate() {
            if n == 0 {
                val.min = x.to_usize_whole(data.as_bytes(), "length matcher")?;
            } else if n == 1 {
                val.max = Some(x.to_usize_whole(data.as_bytes(), "length matcher")?);
            } else {
                return err!("Length spec can't have more than one comma.");
            }
        }
        Ok(val)
    }
    /*
        /// new from actual numbers
        fn with_sizes(min : usize, max : Option<usize>) -> Self {
        Self {min, max}
        }
    */
}

impl Match for LengthMatch {
    fn smatch(&self, buff: &str) -> bool {
        let len = buff.chars().count();
        if len < self.min {
            return false;
        }
        if self.max.is_none() {
            return true;
        }
        len <= self.max.unwrap()
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        let len = buff.len();
        if len < self.min {
            return false;
        }
        if self.max.is_none() {
            return true;
        }
        len <= self.max.unwrap()
    }
    fn show(&self) -> String {
        if let Some(max) = self.max {
            format!("String of at least {}, but no more than {}  bytes", self.min, max)
        } else if self.min == 0 {
            "Empty String".to_string()
        } else {
            format!("String of at least {} bytes", self.min)
        }
    }
}

/// Mode for combining parts of a multi-match
#[derive(Debug, PartialEq, Eq, Copy, Clone, Default)]
pub enum Combiner {
    /// matches if any match
    Or,
    /// matches only if all match
    #[default]
    And,
}
impl fmt::Display for Combiner {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Or => Ok(write!(f, "OR")?),
            Self::And => Ok(write!(f, "AND")?),
        }
    }
}

// single column (title,foo), whole line (,foo) or column set with determiner
// [this-that],foo or [all,this-that],foo
#[derive(Debug, Default)]
struct ColGroup {
    col: ColumnSet,
    det: Determiner,
    #[allow(dead_code)]
    has_col: bool,
}
impl ColGroup {
    fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.col.lookup(field_names)
    }
    fn new_with(spec: &str) -> Result<(Self, &str)> {
        if spec.is_empty() {
            Ok((Self::default(), spec))
        } else if spec.first() == ',' {
            Ok((Self::default(), &spec[1..]))
        } else if spec.first() == '[' {
            let len = util::find_close(spec)?;
            let cols = &spec[1..len];
            let rest = &spec[(len + 1)..];
            Ok((
                Self {
                    col: ColumnSet::from_spec(cols)?,
                    det: Determiner::default(),
                    has_col: true,
                },
                rest,
            ))
        } else if let Some((a, b)) = spec.split_once(',') {
            Ok((
                Self { col: ColumnSet::from_spec(a)?, det: Determiner::default(), has_col: true },
                b,
            ))
        } else {
            Ok((
                Self {
                    col: ColumnSet::from_spec(spec)?,
                    det: Determiner::default(),
                    has_col: true,
                },
                "",
            ))
        }
    }
}

//COLUMN,comp,OPCOLGROUP,PATTERN
// title,comp,<author
// title,comp,<[all,author-date]
// title,comp,LT.author,plain
#[derive(Debug)]
struct CompMatcher {
    target: NamedCol,
    op: CompareOp,
    col: ColGroup,
    comp: Comp,
}
impl CompMatcher {
    fn new(incol: &str, mut pattern: &str) -> Result<Self> {
        let target = NamedCol::new_from(incol)?;
        if pattern.len() < 3 {
            return err!("CompMatcher format is OpColumns,Comparator, '{}'", pattern);
        }
        // FIXME - factor out this CompareOp parsing
        let op1 = pattern[0..2].parse::<CompareOp>();
        let op;
        if let Ok(o) = op1 {
            pattern = &pattern[2..];
            op = o;
        } else {
            let op1 = pattern[0..1].parse::<CompareOp>();
            if let Ok(o) = op1 {
                pattern = &pattern[1..];
                op = o;
            } else if let Some((a, b)) = pattern.split_once('.') {
                op = a.parse::<CompareOp>()?;
                pattern = b;
            } else {
                return err!("CompMatcher format is OpColumns,Comparator, '{}'", pattern);
            }
        }
        let (col, rest) = ColGroup::new_with(pattern)?;
        let comp = CompMaker::make_comp(rest)?;
        Ok(Self { target, op, col, comp })
    }
}
impl LineMatch for CompMatcher {
    fn ok(&mut self, line: &TextLine) -> bool {
        let mut yes: usize = 0;
        let mut no: usize = 0;
        for x in self.col.col.get_cols() {
            let o = self.comp.comp(line.get(self.target.num), line.get(x.num));
            if self.op.ord_ok(o) {
                yes += 1;
            } else {
                no += 1;
            }
            let t = self.col.det.match_mid(yes, no);
            if t != Tri::Maybe {
                return t == Tri::Yes;
            }
        }
        self.col.det.match_final(yes, no)
    }
    fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.target.lookup(field_names)?;
        self.col.lookup(field_names)
    }

    fn show(&self) -> String {
        format!("CompMatcher {:?} {:?} {:?} {:?}", self.target, self.op, self.col, self.comp)
    }
}

/// Does the whole line match a pattern. Implements `LineMatch`
#[derive(Debug)]
struct WholeMatcher {
    matcher: Matcher,
}

impl WholeMatcher {
    fn new(method: &str, pattern: &str) -> Result<Self> {
        Ok(Self { matcher: MatchMaker::make2(method, pattern)? })
    }
}

// LineMatch::matcher could return Result<bool> and then we can put strict back
impl LineMatch for WholeMatcher {
    fn ok(&mut self, line: &TextLine) -> bool {
        self.matcher.negate
            ^ if self.matcher.string {
                self.matcher.smatch(&String::from_utf8_lossy(line.line_nl()))
            } else {
                self.matcher.umatch(line.line_nl())
            }
    }

    fn lookup(&mut self, _field_names: &[&str]) -> Result<()> {
        Ok(())
    }
    fn show(&self) -> String {
        format!("match whole line against {}", self.matcher)
    }
}

/// Does the line have a certain number of columns
#[derive(Debug)]
struct CountMatcher {
    count: usize,
}

impl CountMatcher {
    fn new(pattern: &str) -> Result<Self> {
        Ok(Self { count: pattern.to_usize_whole(pattern.as_bytes(), "count matcher")? })
    }
}

// LineMatch::matcher could return Result<bool> and then we can put strict back
impl LineMatch for CountMatcher {
    fn ok(&mut self, line: &TextLine) -> bool {
        line.len() == self.count
    }

    fn lookup(&mut self, _field_names: &[&str]) -> Result<()> {
        Ok(())
    }
    fn show(&self) -> String {
        format!("Does line have {} columns", self.count)
    }
    fn ok_verbose(&mut self, line: &TextLine, line_num: usize, fname: &str) -> bool {
        let ret = self.ok(line);
        if !ret {
            eprintln!(
                "Line {} of {} had {} columns where {} were expected.",
                line_num,
                fname,
                line.len(),
                self.count
            );
        }
        ret
    }
}

/// Does a particular column of a line match a pattern. Implements `LineMatch`
#[derive(Debug)]
struct ColSetMatcher {
    matcher: Matcher,
    col: ColumnSet,
    det: Determiner,
}

impl ColSetMatcher {
    /// new from parts
    fn new(cols: &str, method: &str, pattern: &str) -> Result<Self> {
        if let Some((a, b)) = cols.split_once(',') {
            Ok(Self {
                matcher: MatchMaker::make2(method, pattern)?,
                col: ColumnSet::from_spec(b)?,
                det: Determiner::new(a)?,
            })
        } else {
            err!("ColumnGroup format is Determiner,ColumnSet")
        }
    }
}

impl LineMatch for ColSetMatcher {
    fn ok(&mut self, line: &TextLine) -> bool {
        let mut yes = 0;
        let mut no = 0;
        for x in self.col.get_cols() {
            let did_match = if self.matcher.string {
                self.matcher.smatch(&String::from_utf8_lossy(line.get(x.num)))
            } else {
                self.matcher.umatch(line.get(x.num))
            };
            if did_match {
                yes += 1;
            } else {
                no += 1;
            }
            let res = self.det.match_mid(yes, no);
            if res != Tri::Maybe {
                return self.matcher.negate ^ (res == Tri::Yes);
            }
        }
        self.matcher.negate ^ self.det.match_final(yes, no)
    }

    fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.col.lookup(field_names)
    }
    fn show(&self) -> String {
        format!("match {:?} against {}", self.col, self.matcher)
    }
}

/// Does a particular column of a line match a pattern. Implements `LineMatch`
#[derive(Debug)]
struct ColMatcher {
    matcher: Matcher,
    col: NamedCol,
}

impl ColMatcher {
    /// Column,Spec,Pattern
    /// Pattern may have additional commas
    fn new(cols: &str, method: &str, pattern: &str) -> Result<Self> {
        let mut nc = NamedCol::new();
        nc.parse(cols)?;
        Ok(Self { matcher: MatchMaker::make2(method, pattern)?, col: nc })
    }
}

// LineMatch::matcher could return Result<bool> and then we can put strict back
impl LineMatch for ColMatcher {
    fn ok(&mut self, line: &TextLine) -> bool {
        self.matcher.negate
            ^ if self.matcher.string {
                self.matcher.smatch(&String::from_utf8_lossy(line.get(self.col.num)))
            } else {
                self.matcher.umatch(line.get(self.col.num))
            }
    }

    fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.col.lookup(field_names)
    }
    fn show(&self) -> String {
        format!("match {} against {}", self.col, self.matcher)
    }
}

/// List of [`LineMatch`], combined with AND or OR
#[derive(Default)]
pub struct LineMatcherList {
    /// the mode
    pub multi: Combiner,
    /// the matchers
    pub matchers: Vec<Box<dyn LineMatch>>,
}
impl fmt::Debug for LineMatcherList {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "LineMatcherList {}", self.multi)
    }
}

impl LineMatcherList {
    /// new
    #[must_use]
    pub fn new() -> Self {
        Self { multi: Combiner::Or, matchers: Vec::new() }
    }
    /// new with combiner
    #[must_use]
    pub fn new_with(multi: Combiner) -> Self {
        Self { multi, matchers: Vec::new() }
    }
    /// add Matcher to list
    pub fn push(&mut self, item: &str) -> Result<()> {
        self.matchers.push(MatchMaker::make_line(item)?);
        Ok(())
    }
    /// is empty list?
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.matchers.is_empty()
    }
    /// ok, with supplied Combiner
    pub fn ok_tagged(&mut self, line: &TextLine, multi: Combiner) -> bool {
        match multi {
            Combiner::And => self.ok_and(line),
            Combiner::Or => self.ok_or(line),
        }
    }
    /// `ok_verbose`, with supplied Combiner
    pub fn ok_verbose_tagged(
        &mut self,
        line: &TextLine,
        multi: Combiner,
        line_num: usize,
        fname: &str,
    ) -> bool {
        match multi {
            Combiner::And => self.ok_verbose_and(line, line_num, fname),
            Combiner::Or => self.ok_verbose_or(line, line_num, fname),
        }
    }
    /// ok, with AND
    pub fn ok_and(&mut self, line: &TextLine) -> bool {
        for x in &mut self.matchers {
            if !x.ok(line) {
                return false;
            }
        }
        true
    }
    /// `ok_verbose`, with AND
    pub fn ok_verbose_and(&mut self, line: &TextLine, line_num: usize, fname: &str) -> bool {
        let mut ret = true;
        for x in &mut self.matchers {
            if !x.ok_verbose(line, line_num, fname) {
                ret = false;
            }
        }
        ret
    }
    /// ok, with OR
    pub fn ok_or(&mut self, line: &TextLine) -> bool {
        for x in &mut self.matchers {
            if x.ok(line) {
                return true;
            }
        }
        false
    }
    /// ok, with OR
    pub fn ok_verbose_or(&mut self, line: &TextLine, line_num: usize, fname: &str) -> bool {
        for x in &mut self.matchers {
            if x.ok(line) {
                // NOT ok_verbose
                return true;
            }
        }
        // FIXME - some report of each thing?
        eprintln!("Line {line_num} of {fname} failed to match OR matcher");
        false
    }
    /// Is this line ok?
    pub fn ok(&mut self, line: &TextLine) -> bool {
        self.ok_tagged(line, self.multi)
    }
    /// Is this line ok? If not, write explanation to stderr
    pub fn ok_verbose(&mut self, line: &TextLine, line_num: usize, fname: &str) -> bool {
        self.ok_verbose_tagged(line, self.multi, line_num, fname)
    }
    /// resolve any named columns
    pub fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        for x in &mut self.matchers {
            x.lookup(field_names)?;
        }
        Ok(())
    }
    /// Human readable description
    fn show(&self) -> String {
        if self.is_empty() {
            format!("Empty {} LineMatcherList", self.multi)
        } else if self.matchers.len() == 1 {
            format!("{}", self.matchers[0])
        } else {
            let mut ret = format!("{}", self.matchers[0]);
            for x in self.matchers.iter().skip(1) {
                write!(ret, "{} {}", self.multi, x).unwrap();
            }
            ret
        }
    }
}

impl LineMatch for LineMatcherList {
    fn ok(&mut self, line: &TextLine) -> bool {
        self.ok(line)
    }
    fn ok_verbose(&mut self, line: &TextLine, line_num: usize, fname: &str) -> bool {
        self.ok_verbose(line, line_num, fname)
    }
    fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.lookup(field_names)
    }
    fn show(&self) -> String {
        self.show()
    }
}

/// List of [Matcher], combined with AND or OR
#[derive(Default)]
pub struct MatcherList {
    /// the mode
    pub multi: Combiner,
    /// the matchers
    pub matchers: Vec<Matcher>,
}
impl fmt::Debug for MatcherList {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MatcherList {}", self.multi)
    }
}

impl MatcherList {
    /// new `MatcherList` with Or
    #[must_use]
    pub const fn new() -> Self {
        Self { multi: Combiner::Or, matchers: Vec::new() }
    }
    /// new `MatcherList` with given mode
    #[must_use]
    pub const fn new_with(multi: Combiner) -> Self {
        Self { multi, matchers: Vec::new() }
    }
    /// add Matcher to list
    pub fn push(&mut self, item: &str) -> Result<()> {
        self.matchers.push(MatchMaker::make(item)?);
        Ok(())
    }
    /// add Matcher to list
    fn push_obj(&mut self, item: Matcher) {
        self.matchers.push(item);
    }
    /// Are there any matchers in the list?
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.matchers.is_empty()
    }
    fn smatch_tagged(&self, buff: &str, multi: Combiner) -> bool {
        match multi {
            Combiner::And => self.smatch_and(buff),
            Combiner::Or => self.smatch_or(buff),
        }
    }
    fn smatch_and(&self, buff: &str) -> bool {
        for x in &self.matchers {
            if !x.smatch(buff) {
                return false;
            }
        }
        true
    }
    fn smatch_or(&self, buff: &str) -> bool {
        for x in &self.matchers {
            if x.smatch(buff) {
                return true;
            }
        }
        false
    }
    fn umatch_tagged(&self, buff: &[u8], multi: Combiner) -> bool {
        match multi {
            Combiner::And => self.umatch_and(buff),
            Combiner::Or => self.umatch_or(buff),
        }
    }
    fn umatch_and(&self, buff: &[u8]) -> bool {
        for x in &self.matchers {
            if !x.umatch(buff) {
                return false;
            }
        }
        true
    }
    fn umatch_or(&self, buff: &[u8]) -> bool {
        for x in &self.matchers {
            if x.umatch(buff) {
                return true;
            }
        }
        false
    }
    /// Human readable description
    #[must_use]
    pub fn show(&self) -> String {
        if self.is_empty() {
            format!("Empty {} MatcherList", self.multi)
        } else if self.matchers.len() == 1 {
            format!("{}", self.matchers[0])
        } else {
            let mut ret = format!("{}", self.matchers[0]);
            for x in self.matchers.iter().skip(1) {
                write!(ret, "{} {}", self.multi, x).unwrap();
            }
            ret
        }
    }
    /// Are these characters ok?
    #[must_use]
    pub fn smatch(&self, buff: &str) -> bool {
        self.smatch_tagged(buff, self.multi)
    }
    /// Are these bytes ok?
    #[must_use]
    pub fn umatch(&self, buff: &[u8]) -> bool {
        self.umatch_tagged(buff, self.multi)
    }
    /// smatch, but print to stderr if fail
    #[must_use]
    pub fn verbose_smatch(&self, buff: &str, negate: bool) -> bool {
        let res = self.smatch(buff);
        if res != negate {
            eprintln!("Failed to {}match {} against {}", not_str(negate), buff, self.show());
        }
        res
    }
}

impl Match for MatcherList {
    fn smatch(&self, buff: &str) -> bool {
        self.smatch(buff)
    }
    fn umatch(&self, buff: &[u8]) -> bool {
        self.umatch(buff)
    }
    fn show(&self) -> String {
        self.show()
    }
    fn verbose_smatch(&self, buff: &str, negate: bool) -> bool {
        self.verbose_smatch(buff, negate)
    }
}

/// Match a pattern against a target, i.e. a Match with some context.
#[derive(Debug)]
#[allow(clippy::struct_field_names)]
#[allow(clippy::struct_excessive_bools)]
pub struct Matcher {
    /// general type, e.g. "regex"
    ctype: String,
    /// true for unicode and &str, false for bytes an &[u8]
    string: bool,
    // u8 to unicode error, true for error, false for lossy
    // strict : bool,
    /// should match be case sensitive
    case: Case,
    /// true to invert the match
    negate: bool,
    /// true to remove leading and trailing whitespace before matching
    trim: bool,
    /// true if an empty buffer should match too
    empty: bool,
    /// for multi-matches, combine with AND or OR
    multi_mode: Option<Combiner>,
    /// the matching object
    matcher: Box<dyn Match>,
}

impl fmt::Display for Matcher {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.trim {
            write!(f, "trimmed ")?;
        }
        if self.negate {
            write!(f, "negated ")?;
        }
        if self.empty {
            write!(f, "empty-accepting  ")?;
        }
        write!(f, "{}", self.matcher)
    }
}

impl Default for Matcher {
    fn default() -> Self {
        Self {
            ctype: "regex".to_string(),
            string: false,
            case: Case::Sens,
            negate: false,
            trim: false,
            empty: false,
            multi_mode: None,
            matcher: Box::new(YesMatch {}),
        }
    }
}

impl Clone for Matcher {
    fn clone(&self) -> Self {
        Self {
            ctype: self.ctype.clone(),
            string: self.string,
            case: self.case,
            negate: self.negate,
            trim: self.trim,
            empty: self.empty,
            multi_mode: self.multi_mode,
            matcher: Box::new(YesMatch {}),
        }
    }
}

impl Matcher {
    /// Are these characters ok?
    #[must_use]
    pub fn smatch(&self, mut buff: &str) -> bool {
        if self.trim {
            buff = buff.trimw();
        }
        if self.empty && buff.is_empty() { true } else { self.matcher.smatch(buff) }
    }
    /// Are these bytes ok?
    #[must_use]
    pub fn umatch(&self, mut buff: &[u8]) -> bool {
        if self.trim {
            buff = buff.trimw();
        }
        if self.empty && buff.is_empty() { true } else { self.matcher.umatch(buff) }
    }
    /// umatch or smatch, depending on self.string
    pub fn do_match(&self, buff: &[u8]) -> Result<bool> {
        if self.string {
            Ok(self.smatch(std::str::from_utf8(buff)?))
        } else {
            Ok(self.umatch(buff))
        }
    }

    /// umatch or smatch, depending on self.string ;
    /// Failure to convert to utf8 is simply 'does not match'
    #[must_use]
    pub fn do_match_safe(&self, buff: &[u8]) -> bool {
        if self.string {
            if let Ok(x) = std::str::from_utf8(buff) { self.smatch(x) } else { false }
        } else {
            self.umatch(buff)
        }
    }
}

type MakerBox = Box<dyn Fn(&mut Matcher, &str) -> Result<Box<dyn Match>> + Send>;
/// A named constructor for a [Match], used by [`MatchMaker`]
struct MatchMakerItem {
    /// matched against `Matcher::ctype`
    tag: &'static str,
    /// what this matcher does
    help: &'static str,
    /// Create a dyn Match from a pattern
    maker: MakerBox,
}

struct MatchMakerAlias {
    old_name: &'static str,
    new_name: &'static str,
}

static MATCH_MAKER: Mutex<Vec<MatchMakerItem>> = Mutex::new(Vec::new());
static MATCH_ALIAS: Mutex<Vec<MatchMakerAlias>> = Mutex::new(Vec::new());
const MODIFIERS: &[&str] = &["utf8", "not", "trim", "null", "case", "and", "or"];

/// Makes a [Matcher]
#[derive(Debug, PartialEq, Eq, Copy, Clone, Default, Hash)]
pub struct MatchMaker {}

impl MatchMaker {
    /// add standard match makers
    pub(crate) fn init() -> Result<()> {
        if !MATCH_MAKER.lock().unwrap().is_empty() {
            return err!("Double init of MatchMaker not allowed");
        }
        Self::do_add_alias("infix", "substr")?;
        Self::do_add_alias("infix", "substring")?;
        Self::do_add_alias("file-exact", "fileexact")?;
        Self::do_push("prefix", "Is the pattern a prefix of the target?", |m, p| {
            Ok(if m.case == Case::Insens {
                Box::new(PrefixMatchC::new(p))
            } else {
                Box::new(PrefixMatch::new(p))
            })
        })?;
        Self::do_push("solve", "Does the target match the given solver pattern?", |_m, p| {
            Ok(Box::new(crate::solve::SolverMatch::new(p)?))
        })?;
        Self::do_push("keep", "Match values that contain all of these characters.", |m, p| {
            Ok(Box::new(OccurMatch::new(p, m, true)))
        })?;
        Self::do_push("reject", "Reject values that contain any of these characters.", |m, p| {
            Ok(Box::new(OccurMatch::new(p, m, false)))
        })?;
        Self::do_push("float", "Valid floating point number", |_m, _p| {
            Ok(Box::new(RegexMatch::new("^[-]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$", Case::Sens)?))
        })?;
        Self::do_push("integer", "Valid integer", |_m, _p| {
            Ok(Box::new(RegexMatch::new("^[-]?[0-9]+$", Case::Sens)?))
        })?;
        Self::do_push(
            "number",
            "Valid number, with optional decimal, e.g. 42 or 1.23",
            |_m, _p| Ok(Box::new(RegexMatch::new("^[-]?[0-9]+(\\.[0-9]+)?$", Case::Sens)?)),
        )?;
        Self::do_push("ip", "Valid IPv4 address", |_m, _p| {
            Ok(Box::new(RegexMatch::new(
                "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$",
                Case::Sens,
            )?))
        })?;
        Self::do_push(
            "regex",
            "Interpret the pattern as a regex, as per the eponymous crate",
            |m, p| Ok(Box::new(RegexMatch::new(p, m.case)?)),
        )?;
        Self::do_push("range", "Match using a CompareOp and a Comparator", |_m, p| {
            Ok(Box::new(CheckBuff::new(p)?))
        })?;
        Self::do_push(
            "file-exact",
            "Is the target exactly one one the lines in this file?",
            |m, p| {
                Ok(if m.case == Case::Insens {
                    Box::new(FileExactMatchC::new(p, m.string)?)
                } else {
                    Box::new(FileExactMatch::new(p)?)
                })
            },
        )?;
        Self::do_push("exact", "Does the target exactly match the pattern", |m, p| {
            Ok(if m.case == Case::Insens {
                Box::new(ExactMatchC::new(p))
            } else {
                Box::new(ExactMatch::new(p))
            })
        })?;
        Self::do_push(
            "length",
            "For the pattern X,Y, length is between X and Y inclusive",
            |_m, p| Ok(Box::new(LengthMatch::new(p)?)),
        )?;
        Self::do_push("yes", "always matches", |_m, _p| Ok(Box::new(YesMatch {})))?;
        Self::do_push("suffix", "Is the pattern a suffix of the target?", |m, p| {
            Ok(if m.case == Case::Insens {
                Box::new(SuffixMatchC::new(p))
            } else {
                Box::new(SuffixMatch::new(p))
            })
        })?;
        Self::do_push("infix", "Is the pattern a substring of the target?", |m, p| {
            Ok(if m.case == Case::Insens {
                Box::new(InfixMatchC::new(p))
            } else {
                Box::new(InfixMatch::new(p))
            })
        })?;
        Self::do_push("glob", "Treat the pattern as a shell glob", |m, p| {
            Ok(Box::new(GlobMatch::new(p, m.case)))
        })?;
        Self::do_push("empty", "Is the target empty, i.e. zero bytes", |_m, _p| {
            Ok(Box::new(LengthMatch::new("0,0")?))
        })?;
        Self::do_push("blank", "Is the target made entirely of white space", |m, _p| {
            m.trim = true;
            m.empty = true;
            Ok(Box::new(NoMatch {}))
        })?;
        Self::do_push("comment", "Is the target white space followed by the pattern?", |m, p| {
            m.trim = true;
            m.empty = true;
            Ok(Box::new(PrefixMatch::new(p)))
        })?;
        Self::do_push(
            "hash",
            "Is the target white space followed by the # character?",
            |m, _p| {
                m.trim = true;
                m.empty = true;
                Ok(Box::new(PrefixMatch::new("#")))
            },
        )?;
        Self::do_push("slash", "Is the target white space followed by //", |m, _p| {
            m.trim = true;
            m.empty = true;
            Ok(Box::new(PrefixMatch::new("//")))
        })
    }
    /// Add a new matcher. If a Matcher already exists by that name, replace it.
    pub fn push<F>(tag: &'static str, help: &'static str, maker: F) -> Result<()>
    where
        F: Fn(&mut Matcher, &str) -> Result<Box<dyn Match>> + Send + 'static,
    {
        Self::do_push(tag, help, maker)
    }
    /// Add a new alias. If an alias already exists by that name, replace it.
    pub fn add_alias(old_name: &'static str, new_name: &'static str) -> Result<()> {
        Self::do_add_alias(old_name, new_name)
    }
    /// Return name, replaced by its alias, if any.
    fn resolve_alias(name: String) -> String {
        for x in MATCH_ALIAS.lock().unwrap().iter_mut() {
            if x.new_name == name {
                return x.old_name.to_string();
            }
        }
        name
    }
    fn do_add_alias(old_name: &'static str, new_name: &'static str) -> Result<()> {
        if MODIFIERS.contains(&new_name) {
            return err!(
                "You can't add an alias named {new_name} because that is reserved for a modifier"
            );
        }
        let m = MatchMakerAlias { old_name, new_name };
        let mut mm = MATCH_ALIAS.lock().unwrap();
        for x in mm.iter_mut() {
            if x.new_name == m.new_name {
                *x = m;
                return Ok(());
            }
        }
        mm.push(m);
        drop(mm);
        Ok(())
    }
    fn do_push<F>(tag: &'static str, help: &'static str, maker: F) -> Result<()>
    where
        F: Fn(&mut Matcher, &str) -> Result<Box<dyn Match>> + Send + 'static,
    {
        if MODIFIERS.contains(&tag) {
            return err!(
                "You can't add a matcher named {tag} because that is reserved for a modifier"
            );
        }
        let m = MatchMakerItem { tag, help, maker: Box::new(maker) };
        let mut mm = MATCH_MAKER.lock().unwrap();
        for x in mm.iter_mut() {
            if x.tag == m.tag {
                *x = m;
                return Ok(());
            }
        }
        mm.push(m);
        drop(mm);
        Ok(())
    }
    /// Print all available Matchers to stdout.
    pub fn help() {
        println!("Modifiers :");
        println!("utf8  Operations are on utf8 strings, rather than the default u8 bytes.");
        println!("not   Treat a match as a non-match, and vice versa.");
        println!("case  Ignore case. Exact behavior depends on 'utf8' setting.");
        println!("trim  Remove leading and trailing whitespace before checking.");
        println!("null  An empty string also matches. This check happens after trimming.");
        println!("and   Interpret pattern as a multi-pattern, Match with AND.");
        println!("or    Interpret pattern as a multi-pattern, Match with OR.\n");
        println!("Methods :");
        let mut results = Vec::new();
        for x in &*MATCH_MAKER.lock().unwrap() {
            results.push(format!("{:12}{}", x.tag, x.help));
        }
        results.sort();
        for x in results {
            println!("{x}");
        }
        println!("See also https://avjewe.github.io/cdxdoc/Matcher.html.");
    }
    /// Create a Matcher from a matcher spec and a pattern
    pub fn make2(matcher: &str, pattern: &str) -> Result<Matcher> {
        let mut m = Matcher::default();
        if !matcher.is_empty() {
            for x in matcher.split('.') {
                if x.eq_ignore_ascii_case("utf8") {
                    m.string = true;
                } else if x.eq_ignore_ascii_case("not") {
                    m.negate = true;
                } else if x.eq_ignore_ascii_case("trim") {
                    m.trim = true;
                } else if x.eq_ignore_ascii_case("null") {
                    m.negate = true;
                } else if x.eq_ignore_ascii_case("case") {
                    m.case = Case::Insens;
                } else if x.eq_ignore_ascii_case("and") {
                    m.multi_mode = Some(Combiner::And);
                } else if x.eq_ignore_ascii_case("or") {
                    m.multi_mode = Some(Combiner::Or);
                } else {
                    m.ctype = x.to_string();
                }
            }
            m.ctype = Self::resolve_alias(m.ctype);
        }
        if let Some(mm) = m.multi_mode {
            let mut outer = Box::new(MatcherList::new_with(mm));
            let mut pattern = pattern;
            let delim = pattern.first();
            pattern = pattern.skip_first();
            for x in pattern.split(delim) {
                let mut m2 = m.clone();
                m2.multi_mode = None; // not really necessary
                Self::remake(&mut m2, x)?;
                outer.push_obj(m2);
            }
            m.matcher = outer;
        } else {
            Self::remake(&mut m, pattern)?;
        }
        Ok(m)
    }
    /// Create a matcher from a full spec, i.e. "Matcher,Pattern"
    pub fn make(spec: &str) -> Result<Matcher> {
        if let Some((a, b)) = spec.split_once(',') {
            Self::make2(a, b)
        } else {
            Self::make2(spec, "")
        }
    }
    /// Create a matcher from a full spec, i.e. "Matcher,Pattern"
    pub fn make_line3(cols: &str, method: &str, pattern: &str) -> Result<Box<dyn LineMatch>> {
        if method == "expr" {
            if cols.is_empty() {
                Ok(Box::new(ExprMatcher::new(pattern)?))
            } else {
                err!("'expr' matcher spec only works on whole lines")
            }
        } else if method == "comp" {
            Ok(Box::new(CompMatcher::new(cols, pattern)?))
        } else if method == "count" {
            if cols.is_empty() {
                Ok(Box::new(CountMatcher::new(pattern)?))
            } else {
                err!("'count' matcher spec only works on whole lines")
            }
        } else if cols.is_empty() {
            Ok(Box::new(WholeMatcher::new(method, pattern)?))
        } else if !cols.is_empty() && cols.first() == '[' {
            Ok(Box::new(ColSetMatcher::new(&cols[1..cols.len() - 1], method, pattern)?))
        } else {
            Ok(Box::new(ColMatcher::new(cols, method, pattern)?))
        }
    }
    /// Create a matcher from a full spec, i.e. "Matcher,Pattern"
    pub fn make_line(spec: &str) -> Result<Box<dyn LineMatch>> {
        if !spec.is_empty() && spec.first() == '[' {
            let len = util::find_close(spec)?;
            let cols = &spec[1..len];
            let rest = &spec[(len + 1)..];
            if let Some((c, d)) = rest.split_once(',') {
                Self::make_line3(cols, c, d)
            } else {
                Self::make_line3(cols, rest, "")
            }
        } else if let Some((a, b)) = spec.split_once(',') {
            if let Some((c, d)) = b.split_once(',') {
                Self::make_line3(a, c, d)
            } else {
                Self::make_line3(a, b, "")
            }
        } else {
            Self::make_line3(spec, "", "")
        }
    }
    /// Remake the dyn Match based on current contents.
    pub fn remake(m: &mut Matcher, pattern: &str) -> Result<()> {
        for x in &*MATCH_MAKER.lock().unwrap() {
            if x.tag == m.ctype {
                m.matcher = (x.maker)(m, pattern)?;
                return Ok(());
            }
        }
        err!("Unknown matcher : {}", m.ctype)
    }
}

/// Match if arithmetic expression is non-zero
#[derive(Debug)]
struct ExprMatcher {
    con: Expr,
}

impl ExprMatcher {
    /// new from expression
    fn new(ex: &str) -> Result<Self> {
        Ok(Self { con: Expr::new(ex)? })
    }
}

impl LineMatch for ExprMatcher {
    fn ok(&mut self, line: &TextLine) -> bool {
        self.con.eval(line) != 0.0
    }
    fn ok_verbose(&mut self, line: &TextLine, line_num: usize, fname: &str) -> bool {
        if self.con.eval(line) == 0.0 {
            eprintln!(
                "For line {} of {} the value of {} was zero",
                line_num,
                fname,
                self.con.expr()
            );
            false
        } else {
            true
        }
    }
    fn lookup(&mut self, field_names: &[&str]) -> Result<()> {
        self.con.lookup(field_names)
    }

    fn show(&self) -> String {
        format!("Floating Point Expression must be non-zero : {}", self.con.expr())
    }
}

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

    #[test]
    fn keep() -> Result<()> {
        util::init()?;
        let c = MatchMaker::make("keep,abc")?;
        assert!(c.umatch(b"azbzc"));
        assert!(!c.umatch(b"azzc"));
        assert!(c.smatch("azbzc"));
        assert!(!c.smatch("azzc"));
        let c = MatchMaker::make("keep.case,AbC")?;
        assert!(c.umatch(b"AzbzC"));
        assert!(c.umatch(b"azBzC"));
        assert!(!c.umatch(b"AZZC"));
        assert!(c.smatch("azBzC"));
        assert!(!c.smatch("AZZC"));
        let c = MatchMaker::make("reject,abc")?;
        assert!(c.umatch(b"defgh"));
        assert!(!c.umatch(b"defagh"));
        assert!(c.smatch("defgh"));
        assert!(!c.smatch("defcgh"));
        let c = MatchMaker::make("reject.case,AbC")?;
        assert!(c.umatch(b"defgh"));
        assert!(!c.umatch(b"defagh"));
        assert!(!c.umatch(b"defAgh"));
        assert!(!c.umatch(b"defcgh"));
        assert!(!c.umatch(b"defCgh"));
        assert!(c.smatch("defgh"));
        assert!(!c.smatch("defcgh"));

        let c = MatchMaker::make("keep,abbc")?;
        assert!(!c.umatch(b"azbzc"));
        assert!(c.umatch(b"azbbzc"));
        assert!(c.umatch(b"azbbbzc"));
        assert!(!c.smatch("azbzc"));
        assert!(c.smatch("azbbzc"));
        assert!(c.smatch("azbbbzc"));
        let c = MatchMaker::make("keep.case,AbBC")?;
        assert!(!c.umatch(b"AzbzC"));
        assert!(!c.umatch(b"AzBzC"));
        assert!(c.umatch(b"azbbzC"));
        assert!(c.umatch(b"azBBzC"));
        assert!(c.umatch(b"azBBBzC"));
        assert!(!c.smatch("AzbzC"));
        assert!(!c.smatch("AzBzC"));
        assert!(c.smatch("azbbzC"));
        assert!(c.smatch("azBBzC"));
        assert!(c.smatch("azBBBzC"));
        let c = MatchMaker::make("reject,abbc")?;
        assert!(c.umatch(b"defgh"));
        assert!(c.umatch(b"defbgh"));
        assert!(!c.umatch(b"defbbgh"));
        assert!(!c.umatch(b"defbbbgh"));
        assert!(c.smatch("defgh"));
        assert!(c.smatch("defbgh"));
        assert!(!c.smatch("defbbgh"));
        assert!(!c.smatch("defbbbgh"));
        let c = MatchMaker::make("reject.case,ABbC")?;
        assert!(c.umatch(b"defgh"));
        assert!(c.umatch(b"defbgh"));
        assert!(!c.umatch(b"defbbgh"));
        assert!(!c.umatch(b"defbbbgh"));
        assert!(c.umatch(b"defgh"));
        assert!(c.umatch(b"defBgh"));
        assert!(!c.umatch(b"defBBgh"));
        assert!(!c.umatch(b"defBBBgh"));
        assert!(c.smatch("defgh"));
        assert!(c.smatch("defbgh"));
        assert!(!c.smatch("defbbgh"));
        assert!(!c.smatch("defbbbgh"));
        assert!(c.smatch("defgh"));
        assert!(c.smatch("defBgh"));
        assert!(!c.smatch("defBBgh"));
        assert!(!c.smatch("defBBBgh"));
        Ok(())
    }

    #[test]
    fn range() -> Result<()> {
        util::init()?;
        let c = MatchMaker::make("range,plain,<=dog>cat")?;
        assert!(c.smatch("ccc"));
        assert!(!c.smatch("cat"));
        assert!(c.smatch("dog"));
        assert!(!c.smatch("doh"));
        assert!(c.smatch("dof"));
        let c = MatchMaker::make("range,<dog>=cat")?;
        assert!(c.smatch("cat"));
        let c = MatchMaker::make("range,!=cat")?;
        assert!(!c.smatch("cat"));
        assert!(c.smatch("dog"));
        let c = MatchMaker::make("range,GT,cat,LE,dog")?;
        assert!(!c.smatch("cat"));
        assert!(c.smatch("dog"));
        let c = MatchMaker::make("range,LE,dog")?;
        assert!(c.smatch("cat"));
        assert!(c.smatch("dog"));
        assert!(!c.smatch("doh"));
        let c = MatchMaker::make("range,lower,LE,dog")?;
        assert!(c.smatch("Cat"));
        assert!(c.smatch("Dog"));
        assert!(!c.smatch("Doh"));
        Ok(())
    }
}