grippo 0.2.1

Parse, match and scrub data faster and more efficiently.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
// Project:   grippo
// File:      src/grok/tests.rs
// Purpose:   Grok expansion, dialects and the grok list's semantics
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

#![allow(
    clippy::literal_string_with_formatting_args,
    reason = "grok's %{NAME:field} reads as a format argument"
)]

use super::*;
use crate::parse::{Fields, Parsed, Parser};
#[cfg(feature = "parse-backtracking")]
use crate::{parse::ParseError, tier::MatcherTier};

fn parse(g: &Grok, input: &str) -> Option<Vec<(String, String, Hint)>> {
    let mut out = Fields::new();
    match g.parse(input.as_bytes(), &mut out).unwrap() {
        Parsed::NoMatch => None,
        _ => Some(
            out.as_slice()
                .iter()
                .map(|(n, v)| {
                    (
                        n.clone(),
                        String::from_utf8_lossy(&v.bytes).into_owned(),
                        v.hint,
                    )
                })
                .collect(),
        ),
    }
}

fn grok(patterns: &[&str]) -> Grok {
    patterns
        .iter()
        .fold(Grok::builder("grok:test"), |b, p| b.pattern(*p))
        .build()
        .unwrap()
}

#[allow(clippy::unnecessary_wraps, reason = "compared with what parse returns")]
fn text(fields: &[(&str, &str)]) -> Option<Vec<(String, String, Hint)>> {
    Some(
        fields
            .iter()
            .map(|(n, v)| ((*n).to_owned(), (*v).to_owned(), Hint::Text))
            .collect(),
    )
}

#[test]
fn a_reference_expands_to_a_numbered_group_with_its_field() {
    let lib = Library::default();
    let e = expand(
        "%{WORD:verb} %{NUMBER:[http][bytes]:int} %{SPACE}",
        &lib,
        Dialect::Rust,
    )
    .unwrap();
    assert!(e.regex.starts_with(r"(?P<g0>\b\w+\b) "), "{}", e.regex);
    assert_eq!(
        e.captures,
        [
            Capture {
                field: "verb".into(),
                hint: Hint::Text,
                filter: None
            },
            Capture {
                field: "http.bytes".into(),
                hint: Hint::Int,
                filter: None
            },
        ]
    );
    // A dot inside a bracket is part of the key.
    let e = expand(
        "%{WORD:[a.b][c]} %{WORD:[x][y.z]} %{WORD:[q\"t]} %{WORD:d.e}",
        &lib,
        Dialect::Rust,
    )
    .unwrap();
    let fields: Vec<&str> = e.captures.iter().map(|c| c.field.as_str()).collect();
    assert_eq!(
        fields,
        [r#"["a.b"].c"#, r#"x["y.z"]"#, r#"["q\"t"]"#, "d.e"]
    );
    // An inline group in a definition is a capture too, renamed so names never clash.
    let e = expand("%{RCONTROLLER}", &lib, Dialect::Rust).unwrap();
    let fields: Vec<&str> = e.captures.iter().map(|c| c.field.as_str()).collect();
    assert_eq!(fields, ["controller", "action"]);
    assert!(!e.regex.contains("(?<controller>"));
}

#[test]
fn a_bad_reference_says_why() {
    let lib = Library::default();
    assert_eq!(
        expand("%{NOPE}", &lib, Dialect::Rust),
        Err(GrokError::Unknown("NOPE".into()))
    );
    assert!(matches!(
        expand("%{WORD:x:bytes}", &lib, Dialect::Rust),
        Err(GrokError::Malformed(_))
    ));
    assert!(matches!(
        expand("%{WORD", &lib, Dialect::Rust),
        Err(GrokError::Malformed(_))
    ));
    let mut looped = Library::empty();
    looped.add("A", "x%{B}");
    looped.add("B", "%{A}");
    assert_eq!(
        expand("%{A}", &looped, Dialect::Rust),
        Err(GrokError::Cycle("A".into()))
    );
    // A reference inside a class is the class's own characters.
    let e = expand("[%{]", &lib, Dialect::Rust).unwrap();
    assert_eq!(e.regex, "[%{]");
}

/// Every definition in the default library expands and builds on the linear
/// engine.
#[test]
fn every_library_definition_expands_and_the_linear_engine_runs_all() {
    let lib = Library::default();
    let mut refused: Vec<&str> = lib
        .defs
        .keys()
        .filter(|name| {
            let e = expand(&format!("%{{{name}}}"), &lib, Dialect::Rust).unwrap();
            regex_automata::meta::Regex::new(&e.regex).is_err()
        })
        .map(String::as_str)
        .collect();
    refused.sort_unstable();
    assert!(refused.is_empty(), "{refused:?}");
}

#[test]
fn the_earliest_match_wins_and_a_tie_goes_to_the_first_pattern() {
    let g = grok(&["%{INT:late}", "x %{WORD:early}"]);
    assert_eq!(parse(&g, "x a 23"), text(&[("early", "a")]));
    let g = grok(&["%{WORD:a}", "%{WORD:b}"]);
    assert_eq!(parse(&g, "hi"), text(&[("a", "hi")]));
    assert_eq!(parse(&g, "  "), None);
}

/// A field name and its value, as a table writes them.
type Pairs = &'static [(&'static str, &'static str)];

/// A list over [`Span::Whole`] in the Oniguruma dialect, empty captures
/// dropped, with `aliases`.
fn whole(patterns: &[&str], aliases: Pairs) -> Result<Grok, GrokBuildError> {
    let mut a = Library::empty();
    for (name, def) in aliases {
        a.add(*name, *def);
    }
    patterns
        .iter()
        .fold(Grok::builder("grok:w"), |b, p| b.pattern(*p))
        .aliases(a)
        .dialect(Dialect::Oniguruma)
        .span(Span::Whole)
        .drop_empty(true)
        .build()
}

/// The pattern that won and the fields it wrote, `None` for no match.
fn won(g: &Grok, input: &str) -> Option<(usize, Vec<(String, String)>)> {
    let mut out = Fields::new();
    let index = g.parse_indexed(input.as_bytes(), &mut out).unwrap()?;
    let fields = out
        .as_slice()
        .iter()
        .map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
        .collect();
    Some((index, fields))
}

/// Whole-line lists, each with its aliases, a line, and the pattern that wins
/// with the fields it writes.
#[test]
fn a_whole_line_list_takes_the_first_pattern_that_matches_all_of_it() {
    type Row = (
        &'static [&'static str],
        Pairs,
        &'static str,
        Option<(usize, Pairs)>,
    );
    let rows: [Row; 17] = [
        // An unanchored search written `.*?P` keeps its place in the list.
        (
            &[".*?=%{INT:n}", "%{WORD:w}=.*"],
            &[],
            "k=5",
            Some((0, &[("n", "5")])),
        ),
        (
            &["%{WORD:w}=.*", ".*?=%{INT:n}"],
            &[],
            "k=5",
            Some((0, &[("w", "k")])),
        ),
        // A pattern that matches part of the line doesn't win.
        (
            &["%{WORD:a}", "%{WORD:a} %{WORD:b}"],
            &[],
            "x y",
            Some((1, &[("a", "x"), ("b", "y")])),
        ),
        (&["%{WORD:a}"], &[], "x y", None),
        // `.` crosses a newline, in a library definition too.
        (
            &["%{WORD:a} %{GREEDYDATA:r}"],
            &[],
            "x y\nz",
            Some((0, &[("a", "x"), ("r", "y\nz")])),
        ),
        (&["%{DATA:d}!"], &[], "a\nb!", Some((0, &[("d", "a\nb")]))),
        // `^` and `$` match at lines inside the line.
        (
            &[".*?^%{INT:n}$.*"],
            &[],
            "a\n42\nb",
            Some((0, &[("n", "42")])),
        ),
        // A final `$` takes no line terminator: the line has to end there.
        (&["%{WORD:w}$"], &[], "a\n", None),
        (&["%{WORD:w}$"], &[], "a", Some((0, &[("w", "a")]))),
        // An alias shadows the library in the patterns and other aliases, and
        // a library definition's own references still find the library.
        (
            &["%{PORT:p}"],
            &[("PORT", "x+")],
            "xx",
            Some((0, &[("p", "xx")])),
        ),
        (
            &["%{HOSTPORT:hp}"],
            &[("PORT", "x+")],
            "h:80",
            Some((0, &[("hp", "h:80")])),
        ),
        (&["%{HOSTPORT:hp}"], &[("PORT", "x+")], "h:xx", None),
        (
            &["%{HDR} %{WORD:w}"],
            &[("HDR", "<%{PRI}>"), ("PRI", "%{INT:pri}")],
            "<13> up",
            Some((0, &[("pri", "13"), ("w", "up")])),
        ),
        // An empty capture writes nothing, and nor does a group that took no part.
        (
            &["%{DATA:a}=%{DATA:b}"],
            &[],
            "=x",
            Some((0, &[("b", "x")])),
        ),
        (
            &["%{WORD:a}(?: %{INT:n})?"],
            &[],
            "x",
            Some((0, &[("a", "x")])),
        ),
        // No pattern matches: nothing is written.
        (&["%{INT:n}", "%{WORD:w}"], &[], "a b", None),
        (&["%{INT:n}"], &[], "", None),
    ];
    for (patterns, aliases, input, want) in rows {
        let g = whole(patterns, aliases).unwrap();
        let want = want.map(|(i, f)| {
            let f = f.iter().map(|(n, v)| ((*n).to_owned(), (*v).to_owned()));
            (i, f.collect::<Vec<_>>())
        });
        assert_eq!(
            won(&g, input),
            want,
            "{patterns:?} {aliases:?} on {input:?}"
        );
    }
    // The default span takes the match that starts earliest instead.
    let part = Grok::builder("grok:p")
        .pattern("=%{INT:n}")
        .pattern("%{WORD:w}=")
        .build()
        .unwrap();
    assert_eq!(won(&part, "k=5"), Some((1, vec![("w".into(), "k".into())])));
    // So does an earlier pattern that matches part of the line.
    let part = grok(&["%{WORD:a}", "%{WORD:a} %{WORD:b}"]);
    assert_eq!(won(&part, "x y"), Some((0, vec![("a".into(), "x".into())])));
}

#[test]
fn an_alias_that_reaches_itself_or_nothing_says_why() {
    let cycle = whole(&["%{A}"], &[("A", "x%{B}"), ("B", "%{A}")]);
    assert!(
        matches!(cycle, Err(GrokBuildError::Expand { index: 0, source: GrokError::Cycle(ref n) }) if n == "A"),
        "{cycle:?}"
    );
    let unknown = whole(&["%{A}"], &[("A", "%{NOPE}")]);
    assert!(
        matches!(unknown, Err(GrokBuildError::Expand { source: GrokError::Unknown(ref n), .. }) if n == "NOPE"),
        "{unknown:?}"
    );
}

#[test]
fn aliases_load_from_json_and_a_later_definition_wins() {
    let mut a = Library::empty();
    a.add("A", "x");
    a.add_json(r#"{"A": "%{B}y", "B": "z"}"#).unwrap();
    a.add_json(r#"{"B": "q"}"#).unwrap();
    let g = Grok::builder("grok:j")
        .pattern("%{A:a}")
        .aliases(a.clone())
        .span(Span::Whole)
        .build()
        .unwrap();
    assert_eq!(won(&g, "qy"), Some((0, vec![("a".into(), "qy".into())])));
    assert_eq!(won(&g, "x"), None);
    for bad in ["[]", r#"{"A": 1}"#, "{", ""] {
        let mut b = a.clone();
        assert!(matches!(b.add_json(bad), Err(GrokError::Json(_))), "{bad}");
        assert_eq!(b.get("A"), Some("%{B}y"), "{bad} added nothing");
    }
}

#[test]
fn an_unknown_name_expands_to_the_definition_asked_for() {
    let lenient = |p: &str| {
        Grok::builder("grok:u")
            .pattern(p)
            .dialect(Dialect::Oniguruma)
            .unknown(".+?")
            .build()
            .unwrap()
    };
    let g = lenient("%{NOPE:f} x");
    assert_eq!(parse(&g, "ab x"), text(&[("f", "ab")]));
    assert_eq!(g.blocked(), [None]);
    // A name inside a definition, and a known one beside it.
    let mut lib = Library::default();
    lib.add("PAIR", "%{MISSING}=%{INT:v}");
    let g = Grok::builder("grok:u")
        .pattern("^%{PAIR}$")
        .library(lib)
        .unknown(".+?")
        .build()
        .unwrap();
    assert_eq!(parse(&g, "k=12"), text(&[("v", "12")]));
    assert_eq!(parse(&g, "=12"), None);
    // Without it the build says which name.
    assert!(matches!(
        Grok::builder("grok:u").pattern("%{NOPE:f}").build(),
        Err(GrokBuildError::Expand { source: GrokError::Unknown(ref n), .. }) if n == "NOPE"
    ));
}

/// The winning pattern's place in the list, on the default span.
#[test]
fn parse_indexed_names_the_pattern_that_won() {
    let g = grok(&["%{INT:late}", "x %{WORD:early}"]);
    assert_eq!(
        won(&g, "x a 23"),
        Some((1, vec![("early".into(), "a".into())]))
    );
    assert_eq!(won(&g, "23"), Some((0, vec![("late".into(), "23".into())])));
    assert_eq!(won(&g, "x"), None);
    let anchored = grok(&["^%{INT:n}", "^%{WORD:w}"]);
    assert_eq!(
        won(&anchored, "ab"),
        Some((1, vec![("w".into(), "ab".into())]))
    );
}

#[test]
fn empty_captures_are_dropped_on_the_default_span_too() {
    let g = Grok::builder("grok:e")
        .pattern("^%{WORD:a}(?: %{INT:b})?=%{DATA:c}$")
        .drop_empty(true)
        .build()
        .unwrap();
    assert_eq!(parse(&g, "hi="), text(&[("a", "hi")]));
    assert_eq!(
        parse(&g, "hi 3=x"),
        text(&[("a", "hi"), ("b", "3"), ("c", "x")])
    );
}

/// The lenient engine's `SYSLOG5424PRI` takes up to five digits and its
/// `PROG` takes a `:`. The stock definitions stop at 191 and before a `:`, and
/// a caller that wants the other reading defines it.
#[test]
fn stock_pri_and_prog_read_narrower_than_the_lenient_engine() {
    let build = |p: &str, lib: Library| {
        Grok::builder("grok:s")
            .pattern(p)
            .library(lib)
            .dialect(Dialect::Oniguruma)
            .build()
            .unwrap()
    };
    let pri = "^%{SYSLOG5424PRI}%{GREEDYDATA:rest}$";
    let stock = build(pri, Library::default());
    assert_eq!(parse(&stock, "<999>x"), None);
    assert_eq!(
        parse(&stock, "<165>x"),
        text(&[("syslog5424_pri", "165"), ("rest", "x")])
    );
    let mut wide = Library::default();
    wide.add("SYSLOG5424PRI", r"<(?P<syslog5424_pri>\d{1,5})>");
    assert_eq!(
        parse(&build(pri, wide), "<999>x"),
        text(&[("syslog5424_pri", "999"), ("rest", "x")])
    );
    let prog = "^%{PROG:p}%{GREEDYDATA:r}$";
    assert_eq!(
        parse(&build(prog, Library::default()), "a:b c"),
        text(&[("p", "a"), ("r", ":b c")])
    );
    let mut colon = Library::default();
    colon.add("PROG", r"[\x21-\x5a\x5c\x5e-\x7e]+");
    assert_eq!(
        parse(&build(prog, colon), "a:b c"),
        text(&[("p", "a:b"), ("r", " c")])
    );
}

#[test]
fn names_collect_a_list_unless_only_one_branch_can_take_part() {
    let g = grok(&["%{WORD:x} %{WORD:x}"]);
    assert_eq!(parse(&g, "a b"), text(&[("x", "a"), ("x", "b")]));
    let g = grok(&["(?:%{INT:v}|%{WORD:v})"]);
    assert_eq!(parse(&g, "abc"), text(&[("v", "abc")]));
}

#[test]
fn a_group_that_took_no_part_writes_nothing_and_an_empty_one_writes_empty() {
    let g = grok(&["^%{WORD:a}(?: %{INT:b})?=%{DATA:c}$"]);
    assert_eq!(parse(&g, "hi="), text(&[("a", "hi"), ("c", "")]));
    assert_eq!(
        parse(&g, "hi 3=x"),
        text(&[("a", "hi"), ("b", "3"), ("c", "x")])
    );
}

#[test]
fn a_type_suffix_sets_the_hint() {
    let g = grok(&["%{INT:n:int} %{NUMBER:f:float} %{WORD:b:boolean}"]);
    assert_eq!(
        parse(&g, "1 2.5 true"),
        Some(vec![
            ("n".into(), "1".into(), Hint::Int),
            ("f".into(), "2.5".into(), Hint::Float),
            ("b".into(), "true".into(), Hint::Bool),
        ])
    );
    // The spellings whole-line grok functions use, in a whole-line list.
    let g = whole(&["%{INT:n:integer} %{NUMBER:f:number} %{INT:i:int}"], &[]).unwrap();
    let mut out = Fields::new();
    g.parse(b"-7 2.5 3", &mut out).unwrap();
    let hints: Vec<(&str, Hint)> = out
        .as_slice()
        .iter()
        .map(|(n, v)| (n.as_str(), v.hint))
        .collect();
    assert_eq!(
        hints,
        [("n", Hint::Int), ("f", Hint::Float), ("i", Hint::Int)]
    );
}

#[test]
fn a_typed_capture_reads_as_the_number_its_suffix_names() {
    use crate::parse::Number;
    let g = grok(&[
        "%{INT:n:int} %{NUMBER:f:float} %{NUMBER:t} %{NUMBER:i:int} %{NUMBER:g:float} %{INT:u:long} %{INT:x:long}",
    ]);
    let mut out = Fields::new();
    let line = b"007 3 4 2.5 2.5 18446744073709551615 18446744073709551616";
    g.parse(line, &mut out).unwrap();
    let number = |name: &str| out.get(name).unwrap().number();
    assert_eq!(number("n"), Some(Number::Int(7)));
    assert_eq!(
        number("f"),
        Some(Number::Float(3.0)),
        "whole text, Float hint"
    );
    assert_eq!(number("t"), None, "no suffix is text");
    assert_eq!(number("i"), None, "2.5 is no whole number");
    assert_eq!(number("g"), Some(Number::Float(2.5)));
    assert_eq!(number("u"), Some(Number::UInt(u64::MAX)));
    assert_eq!(number("x"), None, "past u64");
}

#[test]
fn the_pcre_dialect_reads_patterns_written_for_it() {
    let rows: [(&str, &str, &[(&str, &str)]); 9] = [
        // `\<` and `\>` are the brackets, in a class too.
        (r"\<%{INT:n}\>", "<7>", &[("n", "7")]),
        (r"to=\<(?<to>[^\>\s]+)\>", "to=<a@b.c>", &[("to", "a@b.c")]),
        // A `{` that opens no interval is the brace.
        (
            r#"^{"time":"%{INT:t}"}"#,
            r#"{"time":"12"}"#,
            &[("t", "12")],
        ),
        (r"v=({.+?})", "v={a}", &[]),
        // An interval stays one, and `{,n}` is `{0,n}`.
        (r"a{2}b{,2}(?<n>\d)", "aab5", &[("n", "5")]),
        // A `[` in a class is the bracket, and `[:name:]` still a class.
        (r"(?<p>[\w [\]]+)!", "a [b]!", &[("p", "a [b]")]),
        (r"(?<k>[[:alpha:][]+)=", "a[b=", &[("k", "a[b")]),
        // A branch-reset group is a plain group: each branch names the field.
        (
            r#"^(?|"(?<d>[^"]+)"|(?<d>\S+)) x"#,
            r#""a b" x"#,
            &[("d", "a b")],
        ),
        (r#"^(?|"(?<d>[^"]+)"|(?<d>\S+)) x"#, "ab x", &[("d", "ab")]),
    ];
    for (pattern, input, want) in rows {
        let g = Grok::builder("grok:p")
            .pattern(pattern)
            .dialect(Dialect::Pcre)
            .build()
            .unwrap();
        assert_eq!(parse(&g, input), text(want), "{pattern} on {input}");
    }
    // As written, `\<` is a word boundary, so the brackets needn't be there.
    let angled = |dialect| {
        let g = Grok::builder("grok:a")
            .pattern(r"\<%{INT:n}\>")
            .dialect(dialect)
            .build();
        parse(&g.unwrap(), "7")
    };
    assert_eq!(angled(Dialect::Rust), text(&[("n", "7")]));
    assert_eq!(angled(Dialect::Pcre), None);
    // A library definition isn't PCRE: `UNIXPATH` nests a class.
    let path = Grok::builder("grok:u")
        .pattern("%{UNIXPATH:p}")
        .dialect(Dialect::Pcre)
        .build();
    assert_eq!(
        parse(&path.unwrap(), "/var/log"),
        text(&[("p", "/var/log")])
    );
}

#[test]
fn a_named_group_with_bracketed_keys_writes_its_field_path() {
    for (pattern, name) in [
        (r"(?<[a][b]>\d+)", "a.b"),
        (r"(?<[a.b][c]>\d+)", r#"["a.b"].c"#),
        (r"(?<x>\d+)", "x"),
    ] {
        let g = Grok::builder("grok:named")
            .pattern(pattern)
            .dialect(Dialect::Oniguruma)
            .build()
            .unwrap();
        let mut out = Fields::new();
        g.parse(b"12", &mut out).unwrap();
        let got = out
            .get(name)
            .map(|v| String::from_utf8_lossy(&v.bytes).into_owned());
        assert_eq!(got.as_deref(), Some("12"), "{pattern}");
        #[cfg(feature = "record")]
        {
            use crate::record::Record;
            let keys: Vec<_> = crate::path::keys(name).collect();
            let at = (&out).find(&keys[..]).unwrap();
            assert_eq!((&out).text(at).unwrap(), "12", "{pattern}");
        }
    }
}

#[test]
fn the_oniguruma_dialect_reads_patterns_written_for_it() {
    let onig = |p: &str| {
        Grok::builder("grok:o")
            .pattern(p)
            .dialect(Dialect::Oniguruma)
            .build()
            .unwrap()
    };
    // `\<` and `\>` are the brackets.
    assert_eq!(
        parse(&onig(r"\<%{INT:a}\.%{INT:b}\>"), "<0.222>"),
        text(&[("a", "0"), ("b", "222")])
    );
    // `^` and `$` match at lines.
    assert_eq!(
        parse(&onig("^%{WORD:w}$"), "one two\nthree"),
        text(&[("w", "three")])
    );
    // `(?m)` lets `.` cross a newline.
    assert_eq!(
        parse(&onig("(?m)a%{GREEDYDATA:r}"), "a1\n2"),
        text(&[("r", "1\n2")])
    );
    // `\h` is a hex digit.
    assert_eq!(
        parse(&onig("%{RUUID:id}"), "id=0123456789abcdef0123456789ABCDEF"),
        text(&[("id", "0123456789abcdef0123456789ABCDEF")])
    );
    // A `{` that opens no interval is the brace, `{,n}` is `{0,n}`, and
    // `(?'name'...)` is a named group.
    assert_eq!(
        parse(&onig("^{%{DATA:x}}$"), "{abc}"),
        text(&[("x", "abc")])
    );
    assert_eq!(
        parse(&onig(r"k={%{WORD:x}} a{,2}b x{2}"), "k={v} aab xx"),
        text(&[("x", "v")])
    );
    assert_eq!(parse(&onig("a{,2}b"), "aaab"), Some(Vec::new()));
    assert_eq!(parse(&onig("^a{,2}b"), "aaab"), None);
    assert_eq!(
        parse(&onig("(?'k.v'[0-9]+)"), "n=42"),
        text(&[("k.v", "42")])
    );
    // Names and suffixes in the Oniguruma dialect's form.
    let typed = |p: &str, input: &str| {
        let mut out = Fields::new();
        onig(p).parse(input.as_bytes(), &mut out).unwrap();
        out.as_slice()
            .iter()
            .map(|(n, v)| (n.clone(), v.hint))
            .collect::<Vec<_>>()
    };
    for (p, field, hint) in [
        (r"(?<INT:n.c:int>\d+)", "n.c", Hint::Int),
        (r"(?<n:long>\d+)", "n", Hint::Int),
        (r"(?<n:ip>\d+)", "n:ip", Hint::Text),
        ("%{INT:n:ip}", "n", Hint::Text),
        ("%{INT:n:}", "n", Hint::Text),
    ] {
        assert_eq!(typed(p, "42"), vec![(field.to_owned(), hint)], "{p}");
    }
    // Rust's dialect reads the same patterns as written.
    assert_eq!(parse(&grok(&["^%{WORD:w}$"]), "one two\nthree"), None);
}

#[test]
fn the_signature_comes_from_the_literals_every_match_starts_with() {
    let g = grok(&["CEF:%{INT:v}", "LEEF:%{INT:v}"]);
    assert!(g.signature().may_match(b"x CEF:1"));
    assert!(!g.signature().may_match(b"syslog line"));
    assert!(grok(&["%{IP:a}"]).signature().is_literal_free());
}

#[test]
fn lookaround_is_refused_on_the_linear_engine() {
    let built = Grok::builder("grok:x").pattern("(?<=a)%{WORD:f}").build();
    assert!(matches!(built, Err(GrokBuildError::Regex(_))));
    assert!(matches!(
        Grok::builder("grok:x").build(),
        Err(GrokBuildError::Empty)
    ));
}

/// A lone pattern runs its steps before the regex while lines mostly match
/// from the start, and the answer is the same either way.
#[test]
fn a_lone_pattern_stops_trying_first_on_a_run_of_misses() {
    let g = Grok::builder("grok:f")
        .pattern("%{INT:n} %{WORD:w}$")
        .build()
        .unwrap();
    let hit = text(&[("n", "7"), ("w", "up")]);
    assert!(g.tries_first());
    assert_eq!(parse(&g, "7 up"), hit);
    for _ in 0..40 {
        assert_eq!(parse(&g, "no match here"), None);
    }
    assert!(!g.tries_first());
    // A match later in the line counts against a first try too.
    assert_eq!(parse(&g, "x 7 up"), hit);
    assert!(!g.tries_first());
    for _ in 0..20 {
        assert_eq!(parse(&g, "7 up"), hit);
    }
    assert!(g.tries_first());
}

/// Compiled code tries first under the same score: a run of misses, early
/// or late, turns it off, and hits turn it back on.
#[test]
fn compiled_code_stops_trying_first_on_a_run_of_misses() {
    let g = Grok::builder("grok:a")
        .pattern("^%{COMBINEDAPACHELOG}$")
        .build()
        .unwrap();
    let hit = r#"127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /a.gif HTTP/1.0" 200 2326 "-" "curl/8""#;
    let late = r#"127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /a.gif HTTP/1.0" OK 2326"#;
    assert!(g.explain().contains("compiled code"));
    for miss in [r#"{"level":"info"}"#, late] {
        for _ in 0..40 {
            assert_eq!(parse(&g, miss), None);
        }
        assert!(!g.tries_first(), "{miss}");
        for _ in 0..20 {
            assert!(parse(&g, hit).is_some());
        }
        assert!(g.tries_first(), "{miss}");
    }
}

/// A possessive repeat never gives a character back. Where the next step
/// could use one, the greedy repeat would match lines PCRE doesn't.
#[test]
fn a_pcre_possessive_repeat_builds_only_where_it_is_the_greedy_one() {
    let pcre = |p: &str| Grok::builder("grok:p").pattern(p).dialect(Dialect::Pcre);
    // What follows can't start with a character of the run, or always matches.
    let rows: [(&str, &str, &[(&str, &str)]); 3] = [
        (
            r#""(?<q>[^"]*+)" (?<n>\d++)!"#,
            r#""a b" 42!"#,
            &[("q", "a b"), ("n", "42")],
        ),
        (r"ip=(?<ip>\d{1,3}+)", "ip=1234", &[("ip", "123")]),
        (r"(?<w>\w?+)-", "a-", &[("w", "a")]),
    ];
    for (pattern, input, want) in rows {
        let g = pcre(pattern).build().unwrap();
        assert_eq!(g.blocked(), [None], "{pattern}");
        assert_eq!(parse(&g, input), text(want), "{pattern} on {input}");
    }
    // `\w++\w` matches nothing in PCRE, and `ab` as the greedy repeat.
    let gives_back = r"(?<a>\w++)\w";
    assert!(matches!(
        pcre(gives_back).build(),
        Err(GrokBuildError::Possessive { index: 0, .. })
    ));
    // As written it's a repeat of a repeat, which gives back.
    let rust = Grok::builder("grok:r").pattern(gives_back).build().unwrap();
    assert_eq!(parse(&rust, "ab"), text(&[("a", "a")]));
    #[cfg(feature = "parse-backtracking")]
    {
        let g = Grok::builder("grok:b")
            .backtracking_pattern(gives_back)
            .dialect(Dialect::Pcre)
            .build()
            .unwrap();
        assert_eq!(g.tier(), MatcherTier::Backtracking);
        assert_eq!(parse(&g, "ab"), None);
    }
}

#[cfg(feature = "parse-backtracking")]
#[test]
fn a_pattern_that_opts_in_runs_on_backtracking() {
    let look = "(?<=id=)%{WORD:id}";
    assert!(matches!(
        Grok::builder("grok:b").pattern(look).build(),
        Err(GrokBuildError::Regex(_))
    ));
    let g = Grok::builder("grok:b")
        .backtracking_pattern(look)
        .build()
        .unwrap();
    assert_eq!(g.tier(), MatcherTier::Backtracking);
    assert!(g.explain().starts_with("0: backtracking"));
    assert_eq!(parse(&g, "x id=abc"), text(&[("id", "abc")]));
    assert_eq!(parse(&g, "x ix=abc"), None);
    let mut out = Fields::new();
    assert!(matches!(
        g.parse(b"\xff id=abc", &mut out),
        Ok(Parsed::Done)
    ));
    // A backreference by name follows its group's new name.
    for dialect in [Dialect::Rust, Dialect::Oniguruma] {
        let quoted = Grok::builder("grok:b")
            .backtracking_pattern(r#"(?<q>['"])%{WORD:w}\k<q>"#)
            .dialect(dialect)
            .build()
            .unwrap();
        assert_eq!(
            parse(&quoted, r#"say "hi""#),
            text(&[("q", "\""), ("w", "hi")])
        );
        assert_eq!(parse(&quoted, r#"say "hi'"#), None);
    }
    // A pattern that opts in but needs no backtracking stays linear.
    let plain = Grok::builder("grok:b")
        .backtracking_pattern("%{WORD:w}")
        .build()
        .unwrap();
    assert_ne!(plain.tier(), MatcherTier::Backtracking);
}

#[cfg(feature = "parse-backtracking")]
#[test]
fn the_earliest_match_wins_across_both_engines() {
    let list = |first: &str, second: &str, backtrack_first: bool| {
        let b = Grok::builder("grok:b");
        let b = if backtrack_first {
            b.backtracking_pattern(first).pattern(second)
        } else {
            b.pattern(first).backtracking_pattern(second)
        };
        b.build().unwrap()
    };
    let look = "(?=b)b%{INT:look}";
    // The linear pattern starts earlier.
    assert_eq!(
        parse(&list("a%{INT:lin}", look, false), "xa1b2"),
        text(&[("lin", "1")])
    );
    // The backtracking pattern starts earlier.
    assert_eq!(
        parse(&list("c%{INT:lin}", look, false), "b1c2"),
        text(&[("look", "1")])
    );
    // A tie goes to the pattern listed first, whichever engine it runs on.
    assert_eq!(
        parse(&list("b%{INT:lin}", look, false), "b1"),
        text(&[("lin", "1")])
    );
    // And with a second linear pattern, by each one's own place in the list.
    let three = Grok::builder("grok:b")
        .pattern("z%{INT:first}")
        .backtracking_pattern(look)
        .pattern("b%{INT:third}")
        .build()
        .unwrap();
    assert_eq!(parse(&three, "b1"), text(&[("look", "1")]));
    assert_eq!(parse(&three, "z7"), text(&[("first", "7")]));
    assert_eq!(
        parse(&list(look, "b%{INT:lin}", true), "b1"),
        text(&[("look", "1")])
    );
}

#[cfg(feature = "parse-backtracking")]
#[test]
fn a_blown_backtracking_budget_is_a_limit() {
    let g = Grok::builder("grok:b")
        .backtracking_pattern(r"^((a|a)*)\1c")
        .build()
        .unwrap();
    let mut out = Fields::new();
    let line = "a".repeat(40);
    assert!(matches!(
        g.parse(line.as_bytes(), &mut out),
        Err(ParseError::Limit { .. })
    ));
}

#[test]
fn only_named_fields_are_capture_slots() {
    use regex_automata::PatternID;
    use regex_automata::meta::Regex;
    let lib = Library::default();
    let mut checked = 0;
    for name in lib.defs.keys() {
        let e = expand(&format!("%{{{name}:f}}"), &lib, Dialect::Rust).unwrap();
        let Ok(regex) = Regex::new(&e.regex) else {
            continue;
        };
        let slots = regex.group_info().group_len(PatternID::ZERO) - 1;
        assert_eq!(slots, e.captures.len(), "{name}: {}", e.regex);
        checked += 1;
    }
    assert!(checked > 300, "only {checked} definitions built");
    // A numbered backreference counts groups as written, so they stay.
    let kept = expand(r"((a|b)*)\1c", &lib, Dialect::Rust).unwrap();
    assert_eq!(kept.regex, r"((a|b)*)\1c");
    let plain = expand("(a|b)+c", &lib, Dialect::Rust).unwrap();
    assert_eq!(plain.regex, "(?:a|b)+c");
}

/// Patterns a literal prefilter has got wrong elsewhere: an optional
/// character kept as required, a group's name read as text, an empty group
/// and an empty alternative.
#[test]
fn a_signature_never_rules_out_a_line_the_pattern_matches() {
    for (pattern, line) in [
        ("colou?r=%{INT:n}", "color=5"),
        ("(?<level>warn)ing %{INT:n}", "warning 5"),
        ("a()b%{INT:n}", "ab5"),
        ("(?:x|)y%{INT:n}", "y5"),
        ("%{WORD:w}(?:\\.)?end", "abc.end"),
        ("^(?:)a%{INT:n}", "a5"),
    ] {
        let g = grok(&[pattern]);
        assert!(parse(&g, line).is_some(), "{pattern} matches {line:?}");
        assert!(
            g.signature().may_match(line.as_bytes()),
            "{pattern}: the signature rules out {line:?}"
        );
    }
}

/// Each of grippo's own definitions reads its format's documented example,
/// natively where it lowers, and the same as the regex.
#[test]
fn grippo_definitions_read_their_formats_examples() {
    let alb = concat!(
        "http 2018-07-02T22:23:00.186641Z app/my-loadbalancer/50dc6c495c0c9188 ",
        "192.168.131.39:2817 10.0.0.1:80 0.000 0.001 0.000 200 200 34 366 ",
        "\"GET http://www.example.com:80/ HTTP/1.1\" \"curl/7.46.0\" - - ",
        "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 ",
        "\"Root=1-58337262-36d228ad5d99923122bbe354\" \"-\" \"-\" ",
        "0 2018-07-02T22:22:48.364000Z \"forward\" \"-\" \"-\" \"10.0.0.1:80\" \"200\" \"-\" \"-\" ",
        "TID_1234abcd5678ef90 \"-\" \"-\" \"-\"",
    );
    let ingress = concat!(
        "10.0.0.7 - - [27/Nov/2026:13:55:36 +1100] \"GET /a HTTP/1.1\" 200 612 \"-\" \"curl/8.0\" ",
        "78 0.004 [default-web-80] [] 10.1.0.5:80, 10.1.0.6:80 612, 612 0.003, 0.001 502, 200 ",
        "2c5e7e1f0b2d4e9a",
    );
    let rows: [(&str, &str, &[(&str, &str)]); 6] = [
        (
            "KLOG",
            "I1103 11:57:31.739339   24395 google.cc:2341] Command line: ./some_prog",
            &[
                ("level", "I"),
                ("thread", "24395"),
                ("file", "google.cc"),
                ("message", "Command line: ./some_prog"),
            ],
        ),
        (
            "GLOG",
            "W20261127 13:55:36.000012 7 main.cc:12] disk at 91%",
            &[
                ("level", "W"),
                ("year", "2026"),
                ("line", "12"),
                ("message", "disk at 91%"),
            ],
        ),
        (
            "NGINX_ERROR",
            "2026/11/27 13:55:36 [error] 1234#0: *5 open() \"/var/www/x\" failed (2: No such file or directory)",
            &[("level", "error"), ("pid", "1234"), ("connection", "5")],
        ),
        (
            "INGRESS_NGINX",
            ingress,
            &[
                ("upstream_addr", "10.1.0.5:80, 10.1.0.6:80"),
                ("upstream_status", "502, 200"),
                ("req_id", "2c5e7e1f0b2d4e9a"),
            ],
        ),
        (
            "VPC_FLOW_V2",
            "2 123456789010 eni-1235b8ca123456789 172.31.16.139 172.31.16.21 20641 22 6 20 4249 1418530010 1418530070 ACCEPT OK",
            &[
                ("srcaddr", "172.31.16.139"),
                ("dstport", "22"),
                ("action", "ACCEPT"),
                ("log_status", "OK"),
            ],
        ),
        (
            "ALB_ACCESS_LOG",
            alb,
            &[
                ("type", "http"),
                ("client", "192.168.131.39:2817"),
                ("request", "GET http://www.example.com:80/ HTTP/1.1"),
                ("actions_executed", "forward"),
            ],
        ),
    ];
    for (name, line, want) in rows {
        let g = Grok::builder("grok:own")
            .pattern(format!("^%{{{name}}}$"))
            .build()
            .unwrap();
        let got = parse(&g, line).unwrap_or_else(|| panic!("{name} misses its example"));
        for (field, value) in want {
            assert!(
                got.iter().any(|(f, v, _)| f == field && v == value),
                "{name}: {field} isn't {value:?} in {got:?}"
            );
        }
        let mut out = Fields::new();
        let by_regex = g.parse_regex(line.as_bytes(), &mut out).unwrap();
        assert_ne!(by_regex, Parsed::NoMatch, "{name}");
        let regex: Vec<(String, String)> = out
            .as_slice()
            .iter()
            .map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
            .collect();
        let native: Vec<(String, String)> = got.into_iter().map(|(n, v, _)| (n, v)).collect();
        assert_eq!(native, regex, "{name}");
    }
}

/// The third-party pattern files grippo's own definitions replace, kept
/// outside the repo and named by `GRIPPO_ORACLE_DIR`. `None` when the
/// variable or a file is missing, and the comparison with them is skipped.
#[cfg(feature = "parse-backtracking")]
fn oracle(names: &[&str]) -> Option<Library> {
    let dir = std::env::var_os("GRIPPO_ORACLE_DIR")?;
    let mut bundled = Library::default();
    for name in names {
        bundled.add_file(&std::fs::read_to_string(std::path::Path::new(&dir).join(name)).ok()?);
    }
    for f in FIELDS {
        bundled.add(f.name, f.regex);
    }
    Some(bundled)
}

/// Each base definition holds its hits and misses, and every line where it
/// answers differently from the bundled `grok-patterns` text is printed.
#[cfg(feature = "parse-backtracking")]
#[test]
#[allow(clippy::too_many_lines, reason = "one table of 32 definitions")]
fn base_definitions_hold_their_lines_and_report_where_the_bundled_ones_differ() {
    use fancy_regex::Regex;

    let bundled = oracle(&["grok-patterns"]);
    let own = Library::default();
    let accepts = |lib: &Library, name: &str, line: &str| {
        let e = expand(&format!("^%{{{name}}}$"), lib, Dialect::Rust).unwrap();
        Regex::new(&e.regex).unwrap().is_match(line).unwrap()
    };
    // (name, lines it must match, lines it must not, lines only compared)
    #[allow(clippy::type_complexity, reason = "a literal table")]
    let rows: &[(&str, &[&str], &[&str], &[&str])] = &[
        ("USER", &["root", "a.b-c_d"], &["a b", ""], &[]),
        (
            "QS",
            &[r#""a b""#, "'x'", r#""a\"b""#],
            &["abc", r#""open"#],
            &[],
        ),
        ("DATA", &["", "anything at all"], &[], &[]),
        (
            "BASE16FLOAT",
            &["1A", "0x1F.8", "-.5", "+0Xff.", "3.14"],
            &["", "g1", "1.2.3"],
            &["1.", "x1", "1.5e3"],
        ),
        (
            "URN",
            &[
                "urn:isbn:0451450523",
                "URN:ietf:rfc:2648",
                "urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66",
                "urn:example:a%20b",
                "urn:example:a/b?+r=1?=q=2#frag",
            ],
            &[
                "urn:a:x",
                "urn:-ab:x",
                "urn:ab-:x",
                "urn:example:",
                "urn:example:a b",
                "mailto:x",
            ],
            &["urn:example:a?b", "urn:example:%zz"],
        ),
        (
            "CISCOMAC",
            &["0011.2233.4455", "aAbB.cCdD.eEfF"],
            &["00:11:22:33:44:55", "0011.2233", "0011.2233.445g"],
            &[],
        ),
        (
            "WINDOWSMAC",
            &["00-11-22-33-44-55", "AA-bb-CC-dd-EE-ff"],
            &["00:11:22:33:44:55", "00-11-22-33-44", "00-11-22-33-44-5"],
            &[],
        ),
        (
            "COMMONMAC",
            &["00:11:22:33:44:55", "aa:BB:cc:DD:ee:FF"],
            &["00-11-22-33-44-55", "00:11:22:33:44", "00:11:22:33:44:gg"],
            &[],
        ),
        (
            "HOSTPORT",
            &["example.com:80", "10.0.0.1:8080", "host:0", "host:080"],
            &["example.com", "example.com:", "example.com:http"],
            &[],
        ),
        (
            "PATH",
            &[
                "/var/log/syslog",
                "/",
                r"C:\Windows\System32",
                r"\\srv\share\f.txt",
            ],
            &["relative/path", "var/log", ""],
            &[],
        ),
        (
            "TTY",
            &[
                "/dev/pts/0",
                "/dev/tty1",
                "/dev/ttyS0",
                "/dev/ttyUSB12",
                "/dev/ttyp3",
                "/dev/ttys003",
            ],
            &["/dev/tty", "/dev/pts/", "/dev/sda1", "tty1"],
            &["/dev/pts0", "/dev/tty/3", "/dev/ttyp"],
        ),
        (
            "URIHOST",
            &[
                "example.com",
                "example.com:8080",
                "10.1.2.3:80",
                "[::1]:443",
                "[2001:db8::1]",
            ],
            &["", "/path", "[::1"],
            &[],
        ),
        (
            "URIPATHPARAM",
            &["/a/b", "/a/b?x=1&y=2", "/", "/index.html?q=a%20b"],
            &["a/b", "?x=1", ""],
            &[],
        ),
        (
            "URI",
            &[
                "http://example.com",
                "https://example.com:8443/a/b?x=1",
                "ftp://user:pa55@host/file.txt",
                "file:///etc/hosts",
                "http://[::1]:80/x",
                "ldap://u@h",
            ],
            &[
                "example.com/a",
                "http:/example.com",
                "http//example.com",
                "",
            ],
            &["ftp://u:p ss@h/", "http://u:p@ss@h/"],
        ),
        (
            "MONTHNUM",
            &["1", "01", "9", "12"],
            &["0", "00", "13", "x"],
            &[],
        ),
        ("MONTHNUM2", &["01", "09", "12"], &["1", "00", "13"], &[]),
        (
            "DAY",
            &[
                "Mon", "Monday", "Tue", "Tuesday", "Wed", "Thu", "Fri", "Sat", "Sun", "Sunday",
            ],
            &["mon", "Mo", "Funday", ""],
            &[],
        ),
        (
            "DATE_US",
            &["12/31/2023", "1-2-23", "01/02/99"],
            &["13/01/2023", "12.31.2023"],
            &["12/32/2023"],
        ),
        (
            "DATE_EU",
            &["31/12/2023", "31.12.2023", "1-2-23"],
            &["31/13/2023", "31 12 2023"],
            &["32/12/2023"],
        ),
        (
            "ISO8601_SECOND",
            &["00", "59", "60", "05.123", "30,5"],
            &["5", "61", "70", ""],
            &["59:123"],
        ),
        (
            "DATE",
            &["12/31/2023", "31.12.2023"],
            &["2023-12-31", "x"],
            &[],
        ),
        (
            "DATESTAMP",
            &[
                "12/31/2023 23:59:59",
                "31.12.2023-01:02:03",
                "1-2-23 4:05:06",
            ],
            &["12/31/2023", "12/31/2023T23:59:59"],
            &[],
        ),
        (
            "TZ",
            &[
                "UTC", "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT", "AST",
            ],
            &["CET", "est", "ABC", ""],
            &["ADT"],
        ),
        (
            "DATESTAMP_RFC822",
            &[
                "Sat, 21 Aug 2021 10:11:12 GMT",
                "21 Aug 2021 10:11 UT",
                "Sat, 21 Aug 21 10:11:12 +0000",
                "Sat Aug 21 2021 10:11:12 EST",
            ],
            &[
                "Sat, 21 Aug 2021",
                "Sat, 21 Aug 2021 10:11:12",
                "2021-08-21 10:11:12 GMT",
            ],
            &["Sat, 21 Aug 2021 10:11:12 +00:00"],
        ),
        (
            "DATESTAMP_RFC2822",
            &[
                "Fri, 21 Nov 1997 09:55:06 -0600",
                "21 Nov 1997 09:55 +0000",
                "Tue, 1 Jul 2003 10:52:37 +0200",
                "Fri, 21 Nov 1997 09:55:06 GMT",
                "Fri, 21 Nov 1997 09:55:06 Z",
            ],
            &[
                "Fri 21 Nov 1997 09:55:06 -0600",
                "Fri, 21 Nov 1997 09:55:06",
                "1997-11-21 09:55:06 -0600",
            ],
            &["Fri, 21 Nov 1997 09:55:06 +06:00"],
        ),
        (
            "DATESTAMP_OTHER",
            &[
                "Tue Nov 28 12:00:00 UTC 2023",
                "Tue Nov  5 12:00:00 UTC 2023",
                "Tue Nov 5 12:00:00 EST 2023",
            ],
            &["Tue Nov 28 2023 12:00:00 UTC", "Nov 28 12:00:00 UTC 2023"],
            &[],
        ),
        (
            "DATESTAMP_EVENTLOG",
            &["20231128120000", "19991231235960"],
            &[
                "2023112812000",
                "20231328120000",
                "20231128246000",
                "2023-11-28 12:00:00",
            ],
            &["2023112812000000", "231128120000"],
        ),
        (
            "PROG",
            &["sshd", "systemd-logind", "CRON", "a/b.c_d"],
            &["", "a b", "a:b", "a[1]"],
            &["sshd:"],
        ),
        (
            "SYSLOGPROG",
            &["sshd", "sshd[1234]", "kernel[0]", "dhclient[99]"],
            &["", "sshd[]", "sshd[x]", "sshd [1]"],
            &[],
        ),
        (
            "SYSLOGHOST",
            &["host1", "host1.example.com", "10.0.0.1", "2001:db8::1"],
            &["", "a b"],
            &[],
        ),
        (
            "SYSLOGFACILITY",
            &["<1.6>", "<16.0>"],
            &["<1,6>", "<34>", "<a.b>", "1.6"],
            &["<1x6>"],
        ),
        (
            "SYSLOGBASE",
            &[
                "Jan  5 10:11:12 host sshd[42]:",
                "Nov 28 12:00:00 <4.6> host.example.com CRON:",
                "Dec 31 23:59:59 10.0.0.1 kernel[0]:",
            ],
            &[
                "Jan  5 10:11:12 host sshd",
                "host sshd[42]:",
                "2023-11-28T12:00:00 host sshd:",
            ],
            &[],
        ),
    ];
    assert_eq!(rows.len(), 32);
    let mut differences = Vec::new();
    let mut wrong = Vec::new();
    for (name, hits, misses, probes) in rows {
        for line in *hits {
            if !accepts(&own, name, line) {
                wrong.push(format!("{name} misses {line:?}"));
            }
        }
        for line in *misses {
            if accepts(&own, name, line) {
                wrong.push(format!("{name} matches {line:?}"));
            }
        }
        for line in hits.iter().chain(*misses).chain(*probes) {
            let Some(bundled) = &bundled else { continue };
            let (new, old) = (accepts(&own, name, line), accepts(bundled, name, line));
            if new != old {
                differences.push(format!("{name} {line:?}: base {new}, bundled {old}"));
            }
        }
    }
    for d in &differences {
        println!("DIFF {d}");
    }
    assert!(wrong.is_empty(), "{wrong:#?}");
}

/// Each of grippo's definitions for the linux-syslog, java, httpd, aws and firewalls
/// files holds its hits and misses, and every line where it answers
/// differently from the bundled text is printed.
#[cfg(feature = "parse-backtracking")]
#[test]
#[allow(clippy::too_many_lines, reason = "one table of 82 definitions")]
fn own_file_definitions_hold_their_lines_and_report_where_the_bundled_ones_differ() {
    use fancy_regex::Regex;

    let bundled = oracle(&["linux-syslog", "java", "httpd", "aws", "firewalls"]);
    let own = Library::default();
    let accepts = |lib: &Library, name: &str, line: &str| {
        let e = expand(&format!("^%{{{name}}}$"), lib, Dialect::Rust).unwrap();
        Regex::new(&e.regex).is_ok_and(|re| re.is_match(line).unwrap_or(false))
    };
    let s3 = concat!(
        "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be DOC-EXAMPLE-BUCKET1 ",
        "[06/Feb/2019:00:00:38 +0000] 192.0.2.3 ",
        "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be 3E57427F3EXAMPLE ",
        "REST.GET.VERSIONING - \"GET /DOC-EXAMPLE-BUCKET1?versioning HTTP/1.1\" 200 - 113 - 7 - ",
        "\"-\" \"S3Console/0.4\" -",
    );
    let s3_full = format!(
        "{s3} s9lzHYrFp76ZVxRcpX9+5cjAnEH2ROuNkd2BHfIa6UkFVdtjf5mKR3/eTPFvsiP/XV/VLi31234= \
         SigV2 ECDHE-RSA-AES128-GCM-SHA256 AuthHeader DOC-EXAMPLE-BUCKET1.s3.us-west-1.amazonaws.com TLSV1.1"
    );
    let s3_ap = format!("{s3_full} arn:aws:s3:us-west-1:123456789012:accesspoint/ap Yes");
    let cf_short = "2019-12-04\t21:02:31\tSFO5-C1\t392\t192.0.2.100\tGET\td111111abcdef8.cloudfront.net\t/index.html\t200\t-\tMozilla/5.0%20(Windows)\tkey1=value1\t-\tHit\tSOX4xwn4XV6Q4rgb7XiVGOHms_BGlTAC4KyHmureZmBNrjGdRLiNIQ==\td111111abcdef8.cloudfront.net\thttps\t23\t0.001\t-\tTLSv1.2\tECDHE-RSA-AES128-GCM-SHA256\tHit";
    let cf_full = format!("{cf_short}\tHTTP/2.0\t-\t-\t11040\t0.001\tHit\ttext/html\t78\t-\t-");
    let cf_spaces = cf_short.replace('\t', " ");
    let cf_cut = cf_short.rsplit_once('\t').unwrap().0.to_string();
    let elb = "2015-05-13T23:39:43.945958Z my-loadbalancer 192.168.131.39:2817 10.0.0.1:80 0.000073 0.001048 0.000057 200 200 0 29 \"GET http://www.example.com:80/ HTTP/1.1\"";
    let elb_full = format!("{elb} \"curl/7.38.0\" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2");
    let elb_down = "2015-05-13T23:39:43.945958Z lb 192.168.131.39:2817 - -1 -1 -1 503 0 0 0 \"GET http://www.example.com:80/ HTTP/1.1\" \"curl/7.38.0\" - -";
    let elb_cut = elb.rsplit_once(' ').unwrap().0.to_string();
    let rfc5424_a = r"<34>1 2003-10-11T22:14:15.003Z mymachine.example.com su - ID47 - 'su root' failed for lonvick on /dev/pts/8";
    let rfc5424_b = r#"<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut="3" eventSource="Application" eventID="1011"] An application event log entry"#;
    let rfc5424_nil = "<165>1 - - - - - -";
    let rfc5424_base = r#"<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut="3"]"#;
    let rfc5424_nosd = "<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47";
    let rfc5424_ver0 = "<165>0 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 -";
    let rfc5424_underscore = "<165>1 2003-10-11T22:14:15.003Z my_machine evntslog - ID47 -";
    let pam_open = "Oct 11 22:14:15 host sshd[1]: pam_unix(sshd:session): session opened for user root by (uid=0)";
    let pam_close =
        "Oct 11 22:14:15 host sshd[1]: pam_unix(sshd:session): session closed for user root";
    let pam_auth =
        "Oct 11 22:14:15 host sshd[1]: pam_unix(sshd:auth): authentication failure; logname= uid=0";
    let cron_hour =
        "Oct 11 22:15:01 host CRON[1234]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)";
    let cron_nested = "Oct 11 22:15:01 host CRON[1234]: (root) CMD (test -x /usr/sbin/anacron || ( cd / && run-parts))";
    let cron_reload = "Nov  1 03:00:00 host cron[9]: (alice) RELOAD (crontabs/alice)";
    let cron_lower = "Oct 11 22:15:01 host CRON[1234]: (root) cmd (x)";
    let cron_nouser = "Oct 11 22:15:01 host CRON[1234]: root CMD (x)";
    let common =
        r#"127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326"#;
    let common_dav = r#"10.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "M-SEARCH * HTTP/1.1" 200 -"#;
    let common_408 = r#"host.example.com - - [10/Oct/2000:13:55:36 +0000] "-" 408 -"#;
    let common_raw = r#"10.0.0.1 - - [10/Oct/2000:13:55:36 +0000] "GARBAGE" 400 226"#;
    let common_nobytes = r#"127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "GET / HTTP/1.1" 200"#;
    let common_badstatus = r#"127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "GET / HTTP/1.1" ok 12"#;
    let combined =
        format!(r#"{common} "http://example.com/start.html" "Mozilla/4.08 [en] (Win98; I ;Nav)""#);
    let combined_short = common;
    let err20 = "[Fri Sep 09 10:42:29 2011] [error] [client 72.15.99.187] File does not exist: /usr/local/apache2/htdocs/favicon.ico";
    let err20_notice = "[Fri Sep 09 10:42:29 2011] [notice] Apache/2.2.15 configured";
    let err20_nobracket = "[Fri Sep 09 10:42:29 2011] error [client 1.2.3.4] x";
    let err24 = "[Fri Sep 09 10:42:29.902022 2011] [core:error] [pid 35708:tid 4328636416] [client 72.15.99.187:50343] AH00124: Request exceeded the limit of 10 internal redirects";
    let err24_authz = "[Thu Mar 10 11:12:13.123456 2016] [authz_core:error] [pid 1:tid 2] [client 10.0.0.1:5000] AH01630: client denied by server configuration: /var/www/";
    let err24_os = "[Thu Mar 10 11:12:13.123456 2016] [core:error] [pid 3:tid 4] (13)Permission denied: [client 1.2.3.4:80] AH00035: access to / denied (filesystem path '/x') because search permissions are missing";
    let err24_start = "[Thu Mar 10 11:12:13.123456 2016] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.7 configured";
    let err24_nomodule = "[Thu Mar 10 11:12:13.123456 2016] [:error] [pid 1] AH00001: x";
    let err24_text = "[Fri Sep 09 10:42:29.902022 2011] [core:error] [pid 1:tid 2] [client 1.2.3.4:80] File does not exist: /x";
    let err24_nopid = "[Fri Sep 09 10:42:29.902022 2011] [core:error] [client 1.2.3.4:80] x";
    let err24_nocolon = "[Fri Sep 09 10:42:29.902022 2011] [error] [pid 1] x";
    let s3_trunc = "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be DOC-EXAMPLE-BUCKET1 [06/Feb/2019:00:00:38 +0000] 192.0.2.3";
    let ns = r#"Nov 21 10:00:00 10.0.0.1 ns204: NetScreen device_id=ns204 [Root]system-notification-00257(traffic): start_time="2007-04-30 13:25:22" duration=0 policy_id=2 service=udp/port:135 proto=17 src zone=Untrust dst zone=Trust action=Deny sent=0 rcvd=0 src=1.2.3.4 dst=5.6.7.8 src_port=1034 dst_port=135 src-xlated ip=1.2.3.4 port=1034 dst-xlated ip=5.6.7.8 port=135 session_id=0 reason=Close - AGE OUT"#;
    let ns_cut = ns.split(" reason=").next().unwrap().to_string();
    let t302013 = "Built inbound TCP connection 12345 for outside:10.1.1.1/1234 (10.1.1.1/1234) to inside:10.2.2.2/80 (10.2.2.2/80)";
    let t302014 = "Teardown TCP connection 12345 for outside:1.1.1.1/1 to inside:2.2.2.2/80 duration 0:00:05 bytes 1234 TCP FINs";
    let t302014_rst = "Teardown TCP connection 1 for outside:1.1.1.1/1 to inside:2.2.2.2/80 duration 0:00:05 bytes 1234 TCP Reset-I";
    let t302014_user = format!("{t302014} (bob)");
    let t302015 = "Built outbound UDP connection 2 for dmz:1.1.1.1/53 (1.1.1.1/53) to inside:2.2.2.2/53 (2.2.2.2/53)";
    let t302013_noid = "Built inbound TCP connection for outside:10.1.1.1/1234 (10.1.1.1/1234) to inside:10.2.2.2/80 (10.2.2.2/80)";
    let t313005 = "No matching connection for ICMP error message: icmp src outside:10.1.1.1 dst inside:10.2.2.2 (type 3, code 3) on outside interface.  Original IP payload: tcp src 10.2.2.2/1234 dst 10.3.3.3/80";
    let t313005_one = t313005.replace(".  Original", ". Original");
    let t313005_noport = t313005.replace("10.2.2.2/1234", "10.2.2.2");
    let t713172 = "Group = g1, IP = 1.1.1.1, Automatic NAT Detection Status:     Remote end    is NOT behind a NAT device     This   end   IS behind a NAT device";
    let t713172_cut = t713172.split("     This").next().unwrap().to_string();
    let t733100 = "[ 10.1.1.1] drop rate-1 exceeded. Current burst rate is 1 per second, max configured rate is 10; Current average rate is 0 per second, max configured rate is 5; Cumulative total count is 20";
    let t733100_cut = t733100.replace(
        "Cumulative total count is 20",
        "Cumulative total count is x",
    );
    let mac = "MAC=00:11:22:33:44:55:66:77:88:99:aa:bb:08:00";
    let nf_tcp = format!(
        "IN=eth0 OUT= {mac} SRC=1.2.3.4 DST=5.6.7.8 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=1234 DF PROTO=TCP SPT=1234 DPT=22 WINDOW=1 RES=0x00 SYN URGP=0"
    );
    let nf_icmp = format!(
        "IN=eth0 OUT= {mac} SRC=1.2.3.4 DST=5.6.7.8 LEN=84 TOS=0x00 PREC=0x00 TTL=64 ID=1 DF PROTO=ICMP TYPE=8 CODE=0 ID=1 SEQ=2"
    );
    let nf_out = "IN= OUT=eth1 SRC=1.2.3.4 DST=5.6.7.8 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=1 PROTO=UDP SPT=53 DPT=53 LEN=40";
    let shorewall = format!("Nov 27 10:00:00 fw kernel: Shorewall:net2fw:DROP:{nf_tcp}");
    let shorewall_icmp = format!("Nov 27 10:00:00 fw kernel: Shorewall:net2fw:DROP:{nf_icmp}");
    let shorewall_egress = format!("Nov 27 10:00:00 fw kernel: Shorewall:fw2net:ACCEPT:{nf_out}");
    let shorewall_cut = "Nov 27 10:00:00 fw kernel: Shorewall:net2fw:DROP:IN=eth0 OUT= SRC=1.2.3.4";
    let shorewall_noprefix = format!("Nov 27 10:00:00 fw kernel: {nf_tcp}");
    let sfw2 = format!("Nov 27 10:00:00 linux kernel: SFW2-INext-DROP-DEFLT {nf_tcp}");
    let sfw2_uptime =
        format!("Nov 27 10:00:00 linux kernel: [1234.5678] SFW2-INext-DROP-DEFLT {nf_tcp}");
    let sfw2_iso = format!("2023-11-27T10:00:00+11:00 linux kernel: SFW2-INext-ACC-TCP {nf_tcp}");
    let sfw2_icmp = format!("Nov 27 10:00:00 linux kernel: SFW2-INext-DROP-DEFLT {nf_icmp}");
    let sfw2_egress = format!("Nov 27 10:00:00 linux kernel: SFW2-OUT-DROP {nf_tcp}");
    let sfw2_cut = "Nov 27 10:00:00 linux kernel: SFW2-INext-DROP-DEFLT IN=eth0 OUT= MAC=";

    // (name, lines it must match, lines it must not, lines only compared)
    #[allow(clippy::type_complexity, reason = "a literal table")]
    let rows: Vec<(&str, Vec<&str>, Vec<&str>, Vec<&str>)> = vec![
        (
            "SYSLOG5424PRINTASCII",
            vec!["abc", "!~"],
            vec!["", "a b"],
            vec![],
        ),
        (
            "SYSLOG5424PRI",
            vec!["<0>", "<34>", "<191>"],
            vec!["<192>", "<>", "<034>", "<a>", "34"],
            vec!["<999>"],
        ),
        (
            "SYSLOG5424SD",
            vec![
                r#"[exampleSDID@32473 iut="3" eventSource="Application"]"#,
                r#"[a@1 x="1"][b@2 y="2"]"#,
                "[x]",
                r#"[a@1 m="say \"hi\" \] ok"]"#,
            ],
            vec!["-", "", "[a@1 x=1]", "[a b]"],
            vec!["[a@1 x=\"1\"] trailing"],
        ),
        (
            "SYSLOG5424BASE",
            vec![rfc5424_base, rfc5424_nil, rfc5424_underscore],
            vec![rfc5424_ver0, rfc5424_nosd, "<165>1"],
            vec![],
        ),
        (
            "SYSLOG5424LINE",
            vec![rfc5424_a, rfc5424_b],
            vec!["<34>1 x", "no priority here"],
            vec![],
        ),
        (
            "SYSLOGBASE2",
            vec![
                "Oct 11 22:14:15 mymachine",
                "Oct 11 22:14:15 mymachine su[12]:",
                "2003-10-11T22:14:15 host sshd:",
                "Oct 11 22:14:15 <4.6> host sshd:",
            ],
            vec!["mymachine su:", "Oct 11 22:14:15"],
            vec!["Oct 11 22:14:15 host sshd[12]: msg"],
        ),
        (
            "SYSLOGLINE",
            vec![
                "Oct 11 22:14:15 mymachine su: 'su root' failed",
                "Oct 11 22:14:15 host hello",
            ],
            vec!["Oct 11 22:14:15", "hello world"],
            vec![],
        ),
        (
            "SYSLOGPAMSESSION",
            vec![pam_open, pam_close],
            vec![
                pam_auth,
                "sshd[1]: pam_unix(sshd:session): session opened for user root",
            ],
            vec![],
        ),
        (
            "CRON_ACTION",
            vec!["CMD", "BEGIN EDIT", "RELOAD"],
            vec!["cmd", "", " CMD"],
            vec!["CMD "],
        ),
        (
            "CRONLOG",
            vec![cron_hour, cron_nested, cron_reload],
            vec![cron_lower, cron_nouser],
            vec![],
        ),
        (
            "JAVACLASS",
            vec![
                "java.lang.NullPointerException",
                "Foo",
                "com.example.Outer$Inner",
                "_a.$b",
            ],
            vec!["", "1abc", "a..b", ".a"],
            vec!["a.b."],
        ),
        (
            "JAVAFILE",
            vec!["Foo.java", "Native Method", "Unknown Source", "Foo$Bar.kt"],
            vec!["", "a(b)"],
            vec!["Foo.java:12"],
        ),
        (
            "JAVAMETHOD",
            vec!["main", "<init>", "<clinit>", "lambda$run$0"],
            vec!["", "<foo>", "1x"],
            vec![],
        ),
        (
            "JAVASTACKTRACEPART",
            vec![
                "\tat com.example.Foo.bar(Foo.java:42)",
                "    at java.lang.Thread.run(Thread.java:748)",
                "\tat com.example.Foo.<init>(Foo.java:10)",
                "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)",
                "\tat java.base/java.lang.Thread.run(Thread.java:834)",
                "\tat app//com.example.Foo.bar(Foo.java:7)",
                "\tat jdk.internal@17.0.1/jdk.internal.Foo.bar(Foo.java:7)",
                "\tat Foo.lambda$main$0(Foo.java:5)",
            ],
            vec![
                "\tat com.example.Foo.bar(Foo.java:abc)",
                "\tin com.example.Foo.bar(Foo.java:1)",
                "",
            ],
            vec![],
        ),
        (
            "JAVATHREAD",
            vec!["TP-Processor12", "HP-Processor1"],
            vec!["tp-Processor1", "TP-Processor", "main"],
            vec![],
        ),
        ("JAVALOGMESSAGE", vec!["", "any text"], vec![], vec![]),
        (
            "CATALINA_DATESTAMP",
            vec!["Jan 9, 2014 7:13:13 AM", "Dec 31, 2023 12:00:01 PM"],
            vec![
                "Jan 9, 2014 13:13:13 PM",
                "Jan 9, 14 7:13:13 AM",
                "Jan 9, 2014 7:13:13",
            ],
            vec!["Jan 9, 2014 07:13:13 AM", "Jan 9, 2014 7:13:13 am"],
        ),
        (
            "TOMCAT_DATESTAMP",
            vec!["2014-01-09 17:32:25,527 -0800", "2014-01-09 17:32:25 +0000"],
            vec!["2014-01-09 17:32:25,527", "14-01-09 17:32:25 -0800"],
            vec!["2014-1-9 17:32:25,527 -0800"],
        ),
        (
            "CATALINALOG",
            vec!["Jan 9, 2014 7:13:13 AM org.apache.catalina.core.AprLifecycleListener init"],
            vec!["org.apache.catalina.core.AprLifecycleListener init"],
            vec![],
        ),
        (
            "TOMCATLOG",
            vec![
                "2014-01-09 20:03:28,269 -0800 | ERROR | com.example.service.ExampleService - something happened",
            ],
            vec!["2014-01-09 20:03:28,269 -0800 ERROR | c - m"],
            vec![],
        ),
        (
            "HTTPDUSER",
            vec!["-", "alice", "alice@example.com"],
            vec!["", "a b"],
            vec![],
        ),
        (
            "HTTPDERROR_DATE",
            vec![
                "Fri Sep 09 10:42:29.902022 2011",
                "Fri Sep 09 10:42:29 2011",
            ],
            vec!["Sep 09 10:42:29 2011", "2011-09-09 10:42:29"],
            vec![],
        ),
        (
            "HTTPD_COMMONLOG",
            vec![common, common_dav, common_408, common_raw],
            vec![common_nobytes, common_badstatus, "no brackets here"],
            vec![],
        ),
        (
            "HTTPD_COMBINEDLOG",
            vec![&combined],
            vec![combined_short],
            vec![],
        ),
        (
            "HTTPD20_ERRORLOG",
            vec![err20, err20_notice],
            vec![err20_nobracket],
            vec![],
        ),
        (
            "HTTPD24_ERRORLOG",
            vec![err24, err24_authz, err24_os, err24_start, err24_nomodule],
            vec![err24_nopid, err24_nocolon],
            vec![err24_text],
        ),
        (
            "HTTPD_ERRORLOG",
            vec![err20, err24, err24_os],
            vec![err20_nobracket],
            vec![],
        ),
        (
            "COMMONAPACHELOG",
            vec![common],
            vec![common_nobytes],
            vec![],
        ),
        (
            "COMBINEDAPACHELOG",
            vec![&combined],
            vec![combined_short],
            vec![],
        ),
        (
            "S3_REQUEST_LINE",
            vec!["GET /b/k?x=1 HTTP/1.1", "-"],
            vec![],
            vec!["GET /b/k"],
        ),
        (
            "S3_ACCESS_LOG",
            vec![&s3, &s3_full, &s3_ap],
            vec![s3_trunc, ""],
            vec![],
        ),
        (
            "ELB_URIPATHPARAM",
            vec!["/a/b?x=1", "/"],
            vec!["a/b", "?x=1"],
            vec![],
        ),
        (
            "ELB_URI",
            vec![
                "http://www.example.com:80/",
                "https://host/p?q=1",
                "http://u:p@host:8080/x",
            ],
            vec!["www.example.com/", "/path"],
            vec!["http://[::1]:80/"],
        ),
        (
            "ELB_REQUEST_LINE",
            vec!["GET http://www.example.com:80/ HTTP/1.1", "- - - "],
            vec![],
            vec!["GET /relative HTTP/1.1"],
        ),
        (
            "ELB_ACCESS_LOG",
            vec![elb, &elb_full, elb_down],
            vec![&elb_cut, ""],
            vec![],
        ),
        (
            "CLOUDFRONT_ACCESS_LOG",
            vec![cf_short, &cf_full],
            vec![&cf_spaces, &cf_cut],
            vec![],
        ),
        (
            "NETSCREENSESSIONLOG",
            vec![ns],
            vec![&ns_cut, "NetScreen device_id=ns204"],
            vec![],
        ),
        (
            "CISCO_TAGGED_SYSLOG",
            vec![
                "<166>Jan 05 2023 10:11:12 fw01 : %ASA-6-302013:",
                "<166>Jan  5 10:11:12 : %ASA-4-106023:",
            ],
            vec![
                "<166>Jan 5 10:11:12 fw01 %ASA-6-302013:",
                "<166>Jan 5 10:11:12 fw01 : %ASA-9-302013:",
                "Jan 5 10:11:12 fw01 : %ASA-6-302013:",
            ],
            vec![],
        ),
        (
            "CISCOTIMESTAMP",
            vec!["Jan 05 2023 10:11:12", "Jan  5 10:11:12", "Nov 28 12:00:00"],
            vec!["2023-01-05 10:11:12", "Jan 05"],
            vec![],
        ),
        (
            "CISCOTAG",
            vec!["ASA-6-302013", "PIX-4-106023", "FWSM-1-105005"],
            vec!["ASA-9-302013", "ASA-6-", "asa-6-302013"],
            vec![],
        ),
        (
            "CISCO_ACTION",
            vec!["Built", "Denied", "denied by ACL", "Dropping"],
            vec!["", "Allowed"],
            vec![],
        ),
        (
            "CISCO_REASON",
            vec![
                "No matching connection",
                "TCP Reset-I",
                "TCP FINs",
                "Duplicate TCP SYN",
            ],
            vec!["", "TCP:"],
            vec!["a  b"],
        ),
        (
            "CISCO_DIRECTION",
            vec!["Inbound", "outbound"],
            vec!["inout", ""],
            vec![],
        ),
        (
            "CISCO_INTERVAL",
            vec!["first hit", "300-second interval"],
            vec!["second interval", "first"],
            vec![],
        ),
        (
            "CISCO_XLATE_TYPE",
            vec!["static", "dynamic"],
            vec!["Static", ""],
            vec![],
        ),
        (
            "CISCOFW104001",
            vec!["(Primary) Switching to ACTIVE - HELLO not heard from mate."],
            vec!["Switching to ACTIVE - x"],
            vec![],
        ),
        (
            "CISCOFW104002",
            vec!["(Secondary) Switching to STANDBY - Other unit set to Active"],
            vec!["(Third) Switching to STANDBY - x"],
            vec![],
        ),
        (
            "CISCOFW104003",
            vec!["(Primary) Switching to FAILED."],
            vec!["(Primary) Switching to FAILED"],
            vec![],
        ),
        (
            "CISCOFW104004",
            vec!["(Secondary) Switching to OK."],
            vec!["(Secondary) Switching to Ok."],
            vec![],
        ),
        (
            "CISCOFW105003",
            vec!["(Primary) Monitoring on interface outside waiting"],
            vec!["(Primary) Monitoring on interface waiting"],
            vec![],
        ),
        (
            "CISCOFW105004",
            vec!["(Primary) Monitoring on Interface inside normal"],
            vec!["(Primary) Monitoring on interface inside"],
            vec![],
        ),
        (
            "CISCOFW105005",
            vec!["(Primary) Lost Failover communications with mate on interface outside"],
            vec!["(Primary) Lost communications with mate on interface outside"],
            vec![],
        ),
        (
            "CISCOFW105008",
            vec!["(Primary) Testing Interface inside"],
            vec!["(Primary) Testing inside"],
            vec![],
        ),
        (
            "CISCOFW105009",
            vec!["(Primary) Testing on interface inside Passed"],
            vec!["(Primary) Testing on interface inside Maybe"],
            vec![],
        ),
        (
            "CISCOFW106001",
            vec![
                "Inbound TCP connection denied from 10.1.1.1/12345 to 10.2.2.2/80 flags SYN on interface outside",
            ],
            vec![
                "Inbound TCP connection denied from 10.1.1.1 to 10.2.2.2/80 flags SYN on interface outside",
            ],
            vec![],
        ),
        (
            "CISCOFW106006_106007_106010",
            vec![
                "Deny inbound UDP from 10.1.1.1/137 to 10.2.2.2/137 on interface outside",
                "Deny inbound UDP from 10.1.1.1/53 to 10.2.2.2/1024 due to DNS Response",
                "Deny inbound TCP from 10.1.1.1/1(bob) to 10.2.2.2/80(alice) on interface dmz",
            ],
            vec![
                "Deny inbound UDP from 10.1.1.1/137 to 10.2.2.2/137",
                "Allow inbound UDP from 10.1.1.1/137 to 10.2.2.2/137 on interface outside",
            ],
            vec![],
        ),
        (
            "CISCOFW106014",
            vec!["Deny inbound icmp src outside:10.1.1.1 dst inside:10.2.2.2 (type 8, code 0)"],
            vec!["Deny inbound icmp src outside:10.1.1.1 dst inside:10.2.2.2"],
            vec![],
        ),
        (
            "CISCOFW106015",
            vec![
                "Deny TCP (no connection) from 10.1.1.1/80 to 10.2.2.2/1234 flags RST on interface outside",
            ],
            vec!["Deny TCP from 10.1.1.1/80 to 10.2.2.2/1234 flags RST on interface outside"],
            vec![],
        ),
        (
            "CISCOFW106021",
            vec!["Deny tcp reverse path check from 10.1.1.1 to 10.2.2.2 on interface outside"],
            vec!["Deny tcp reverse path check from 10.1.1.1 to 10.2.2.2"],
            vec![],
        ),
        (
            "CISCOFW106023",
            vec![
                r#"Deny tcp src outside:10.1.1.1/1234 dst inside:10.2.2.2/80 by access-group "acl_in" [0x0, 0x0]"#,
                r#"Deny icmp src outside:10.1.1.1 dst inside:10.2.2.2 (type 8, code 0) by access-group "acl_in" [0x0, 0x0]"#,
            ],
            vec![
                "Deny tcp src outside:10.1.1.1/1234 dst inside:10.2.2.2/80 by access-group acl_in",
            ],
            vec![],
        ),
        (
            "CISCOFW106100_2_3",
            vec![
                "access-list acl_in permitted tcp for user 'bob' outside/10.1.1.1(1234) -> inside/10.2.2.2(80) hit-cnt 1 first hit [0x1a2b, 0x0]",
            ],
            vec![
                "access-list acl_in permitted tcp outside/10.1.1.1(1234) -> inside/10.2.2.2(80) hit-cnt 1 first hit [0x1a2b, 0x0]",
            ],
            vec![],
        ),
        (
            "CISCOFW106100",
            vec![
                "access-list acl_in permitted tcp outside/10.1.1.1(1234) -> inside/10.2.2.2(80) hit-cnt 1 first hit [0x1a2b3c4d, 0x0]",
                "access-list acl_in denied udp outside/10.1.1.1(53)(bob) -> inside/10.2.2.2(53)(alice) hit-cnt 3 300-second interval [0x1, 0x2]",
            ],
            vec![
                "access-list acl_in permitted tcp outside/10.1.1.1(1234) inside/10.2.2.2(80) hit-cnt 1 first hit [0x1, 0x0]",
            ],
            vec![],
        ),
        (
            "CISCOFW304001",
            vec![
                "10.1.1.1 Accessed URL 10.2.2.2:http://example.com/index.html",
                "10.1.1.1(bob) Accessed URL 10.2.2.2:http://example.com/",
            ],
            vec!["10.1.1.1 Visited URL 10.2.2.2:x"],
            vec![],
        ),
        (
            "CISCOFW110002",
            vec![
                "Failed to locate egress interface for TCP from outside:10.1.1.1/1234 to 10.2.2.2/80",
            ],
            vec!["Failed to locate egress interface for TCP from 10.1.1.1/1234 to 10.2.2.2/80"],
            vec![],
        ),
        (
            "CISCOFW302010",
            vec!["5 in use, 10 most used"],
            vec!["five in use, 10 most used"],
            vec![],
        ),
        (
            "CISCOFW302013_302014_302015_302016",
            vec![t302013, t302014, t302014_rst, &t302014_user, t302015],
            vec![t302013_noid],
            vec![],
        ),
        (
            "CISCOFW302020_302021",
            vec![
                "Built inbound ICMP connection for faddr 10.1.1.1/0 gaddr 10.2.2.2/0 laddr 10.2.2.2/0",
                "Teardown ICMP connection for faddr 1.1.1.1/1 gaddr 2.2.2.2/0 laddr 3.3.3.3/0 (bob)",
            ],
            vec!["Built inbound ICMP connection for faddr 10.1.1.1/0 gaddr 10.2.2.2/0"],
            vec![],
        ),
        (
            "CISCOFW305011",
            vec![
                "Built dynamic TCP translation from inside:10.2.2.2/1234 to outside:192.0.2.1/5678",
                "Built static TCP translation from inside:10.2.2.2 to outside:192.0.2.1/0",
            ],
            vec![
                "Built random TCP translation from inside:10.2.2.2/1234 to outside:192.0.2.1/5678",
            ],
            vec![],
        ),
        (
            "CISCOFW313001_313004_313008",
            vec![
                "Denied ICMP type=8, code=0 from 10.1.1.1 on interface outside",
                "Denied ICMP type=3, code=3 from 1.1.1.1 on interface outside to 2.2.2.2",
            ],
            vec!["Denied ICMP type=8 from 10.1.1.1 on interface outside"],
            vec![],
        ),
        (
            "CISCOFW313005",
            vec![t313005, &t313005_one],
            vec![&t313005_noport],
            vec![],
        ),
        (
            "CISCOFW321001",
            vec!["Resource 'conns' limit of 5000 reached for system"],
            vec!["Resource conns limit of 5000 reached for system"],
            vec![],
        ),
        (
            "CISCOFW402117",
            vec!["IPSEC: Received a non-IPSec packet (protocol= TCP) from 10.1.1.1 to 10.2.2.2"],
            vec!["IPSEC: Received a non-IPSec packet from 10.1.1.1 to 10.2.2.2"],
            vec![],
        ),
        (
            "CISCOFW402119",
            vec![
                "IPSEC: Received an ESP packet (SPI= 0x1234, sequence number= 0x5) from 10.1.1.1 (user= bob) to 10.2.2.2 that failed anti-replay checking",
            ],
            vec![
                "IPSEC: Received an ESP packet (SPI= 0x1234, sequence number= 0x5) from 10.1.1.1 (user= bob) to 10.2.2.2",
            ],
            vec![],
        ),
        (
            "CISCOFW419001",
            vec![
                "Dropping TCP packet from outside:1.1.1.1/1 to inside:2.2.2.2/80, reason: MSS exceeded, MSS 1380, data 1460",
            ],
            vec!["Dropping TCP packet from outside:1.1.1.1/1 to inside:2.2.2.2/80"],
            vec![],
        ),
        (
            "CISCOFW419002",
            vec![
                "Duplicate TCP SYN from outside:1.1.1.1/1 to inside:2.2.2.2/80 with different initial sequence number",
            ],
            vec!["Duplicate TCP SYN from outside:1.1.1.1/1 to inside:2.2.2.2/80"],
            vec![],
        ),
        (
            "CISCOFW500004",
            vec!["Invalid transport field for protocol=TCP, from 1.1.1.1/0 to 2.2.2.2/80"],
            vec!["Invalid transport field for protocol=TCP from 1.1.1.1/0 to 2.2.2.2/80"],
            vec![],
        ),
        (
            "CISCOFW602303_602304",
            vec![
                "IPSEC: An outbound LAN-to-LAN SA (SPI= 0x1234) between 1.1.1.1 and 2.2.2.2 (user= bob) has been created",
                "IPSEC: An inbound remote access SA (SPI= 0x1) between 1.1.1.1 and 2.2.2.2 (user= bob) has been deleted",
            ],
            vec![
                "IPSEC: An outbound LAN-to-LAN SA (SPI= 0x1234) between 1.1.1.1 and 2.2.2.2 (user= bob) has been renamed",
            ],
            vec![],
        ),
        (
            "CISCOFW710001_710002_710003_710005_710006",
            vec![
                "TCP access requested from 10.1.1.1/1234 to inside:10.2.2.2/22",
                "UDP request discarded from 10.1.1.1/53 to outside:10.2.2.2/53",
            ],
            vec!["TCP access requested from 10.1.1.1/1234 to 10.2.2.2/22"],
            vec![],
        ),
        ("CISCOFW713172", vec![t713172], vec![&t713172_cut], vec![]),
        ("CISCOFW733100", vec![t733100], vec![&t733100_cut], vec![]),
        (
            "SHOREWALL",
            vec![&shorewall, &shorewall_icmp, &shorewall_egress],
            vec![shorewall_cut, &shorewall_noprefix],
            vec![],
        ),
        (
            "SFW2",
            vec![&sfw2, &sfw2_uptime, &sfw2_iso, &sfw2_icmp],
            vec![&sfw2_egress, sfw2_cut],
            vec![],
        ),
    ];
    assert_eq!(rows.len(), 82);
    let mut differences = Vec::new();
    let mut wrong = Vec::new();
    for (name, hits, misses, probes) in &rows {
        for line in hits {
            if !accepts(&own, name, line) {
                wrong.push(format!("{name} misses {line:?}"));
            }
        }
        for line in misses {
            if accepts(&own, name, line) {
                wrong.push(format!("{name} matches {line:?}"));
            }
        }
        for line in hits.iter().chain(misses).chain(probes) {
            let Some(bundled) = &bundled else { continue };
            let (new, old) = (accepts(&own, name, line), accepts(bundled, name, line));
            if new != old {
                differences.push(format!("{name} {line:?}: own {new}, bundled {old}"));
            }
        }
    }
    for d in &differences {
        println!("DIFF {d}");
    }
    assert!(wrong.is_empty(), "{wrong:#?}");
    let g = Grok::builder("grok:own")
        .pattern("^%{SYSLOGPAMSESSION}$")
        .build()
        .unwrap();
    let got = parse(&g, pam_open).expect("SYSLOGPAMSESSION reads its example");
    for (field, value) in [
        ("pam_module", "pam_unix"),
        ("pam_caller", "sshd:session"),
        ("pam_session_state", "opened"),
        ("username", "root"),
        ("pam_by", "(uid=0)"),
        (
            "message",
            "pam_unix(sshd:session): session opened for user root by (uid=0)",
        ),
    ] {
        assert!(
            got.iter().any(|(f, v, _)| f == field && v == value),
            "{field} isn't {value:?} in {got:?}"
        );
    }
}

/// Each definition of the sixteen product files holds lines it must take and
/// lines it must refuse, and every line the bundled definition answers
/// differently from is printed.
#[cfg(feature = "parse-backtracking")]
#[test]
#[allow(clippy::too_many_lines, reason = "one table of 165 definitions")]
fn product_file_definitions_hold_their_lines_and_report_where_the_bundled_ones_differ() {
    use fancy_regex::Regex;

    const BUNDLED: [&str; 16] = [
        "bacula",
        "bind",
        "bro",
        "exim",
        "haproxy",
        "junos",
        "maven",
        "mcollective",
        "mcollective-patterns",
        "mongodb",
        "nagios",
        "postgresql",
        "rails",
        "redis",
        "ruby",
        "squid",
    ];
    let bundled = oracle(&BUNDLED);
    let own = Library::default();
    let accepts = |lib: &Library, name: &str, line: &str| {
        let e = expand(&format!("^%{{{name}}}$"), lib, Dialect::Rust).unwrap();
        Regex::new(&e.regex).is_ok_and(|re| re.is_match(line).unwrap_or(false))
    };
    let tabs = |cols: &[&str]| cols.join("\t");
    let r = |name: &str, hits: &[&str], misses: &[&str]| {
        (
            name.to_owned(),
            hits.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>(),
            misses.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>(),
        )
    };

    let conn_head = [
        "1357000000.123",
        "CHhAvVGS1DHFjwGM9",
        "10.0.0.1",
        "51234",
        "192.0.2.5",
        "80",
    ];
    let with = |head: &[&str], tail: &[&str]| tabs(&[head, tail].concat());
    let http = with(
        &conn_head,
        &[
            "1",
            "GET",
            "example.com",
            "/",
            "-",
            "curl/7.38.0",
            "0",
            "1256",
            "200",
            "OK",
            "-",
            "-",
            "-",
            "(empty)",
            "-",
            "-",
            "-",
            "-",
            "-",
            "FRxyz",
            "text/html",
        ],
    );
    let dns = with(
        &conn_head,
        &[
            "udp",
            "4242",
            "example.com",
            "1",
            "C_INTERNET",
            "1",
            "A",
            "0",
            "NOERROR",
            "F",
            "F",
            "T",
            "T",
            "0",
            "93.184.216.34",
            "3600.000000",
            "F",
        ],
    );
    let conn = with(
        &conn_head,
        &[
            "tcp", "http", "0.5", "100", "1256", "SF", "-", "0", "ShADadFf", "6", "400", "5",
            "1500", "(empty)",
        ],
    );
    let conn_unset = with(
        &conn_head,
        &[
            "tcp", "-", "-", "-", "-", "S0", "-", "0", "S", "1", "60", "0", "0", "(empty)",
        ],
    );
    let files = with(
        &["1357000000.123", "FRxyz"],
        &[
            "10.0.0.1,10.0.0.2",
            "192.0.2.5",
            "CHhAvVGS1DHFjwGM9",
            "HTTP",
            "0",
            "MD5,SHA1",
            "text/html",
            "-",
            "0.0",
            "-",
            "F",
            "1256",
            "1256",
            "0",
            "0",
            "F",
            "-",
            "-",
            "-",
            "-",
            "-",
        ],
    );
    let cut = |s: &str| s.rsplit_once('\t').unwrap().0.to_owned();

    let hap_http = r#"10.0.1.2:33317 [06/Feb/2009:12:14:14.655] http-in static/srv1 10/0/30/69/109 200 2750 - - ---- 1/1/1/1/0 0/0 {1wt.eu} {} "GET /index.html HTTP/1.1""#;
    let hap_syslog = format!("Feb  6 12:14:14 localhost haproxy[14389]: {hap_http}");
    let hap_iso = format!("2009-02-06T12:14:14+00:00 localhost haproxy[14389]: {hap_http}");
    let hap_bad = hap_http.replace("\"GET /index.html HTTP/1.1\"", "\"<BADREQ>\"");
    let hap_cookie = hap_http.replace(" - - ---- ", " SRV=1 - ---- ");
    let hap_nostatus = hap_http.replace(" 200 2750", "");
    let hap_tcp_base =
        "10.0.1.2:33313 [06/Feb/2009:12:12:51.443] fnt bck/srv1 0/0/5007 212 -- 0/0/0/0/3 0/0";
    let hap_tcp = format!("Feb  6 12:12:56 localhost haproxy[14387]: {hap_tcp_base}");
    let hap_tcp_cut = hap_tcp.rsplit_once(' ').unwrap().0.to_owned();

    let exim_head = "2002-10-31 08:57:53 16ZCW1-0005MB-00 <=";
    let exim_arrival = format!(
        "{exim_head} kryten@dwarf.fict.example H=mailer.fict.example (helo.example) [192.168.123.123]:25 U=exim P=smtp S=5678 id=abc@dwarf.fict.example"
    );
    let exim_pid = "2002-10-31 08:57:53 [1234] 16ZCW1-0005MB-00 <= ab@cd.example P=local S=10 for ef@gh.example";
    let exim_bounce = format!("{exim_head} <> R=16ZCW1-0005MB-00 U=mail P=local S=1234");
    let exim_long = "2002-10-31 08:57:53 1ZCW1a-0005MBabcde-0001 <= ab@cd.example P=local S=10";
    let exim_delivery =
        "2002-10-31 08:57:53 16ZCW1-0005MB-00 => a@b.example R=dnslookup T=remote_smtp";

    let junos_close = "RT_FLOW_SESSION_CLOSE: session closed TCP FIN: 10.1.1.1/54321->192.0.2.5/80 junos-http 203.0.113.1/54321->192.0.2.5/80 source-nat-rule None 6 allow-web trust untrust 1234567 12(1234) 10(4321) 30 UNKNOWN UNKNOWN N/A(N/A) ge-0/0/1.0 UNKNOWN";
    let junos_create = "RT_FLOW_SESSION_CREATE: session created 10.1.1.1/54321->192.0.2.5/80 junos-http 203.0.113.1/54321->192.0.2.5/80 source-nat-rule None 6 allow-web trust untrust 1234567 N/A(N/A) ge-0/0/1.0 UNKNOWN";
    let junos_deny = "RT_FLOW_SESSION_DENY: session denied 10.1.1.1/54321->192.0.2.5/22 junos-ssh 6(0) deny-all trust untrust UNKNOWN UNKNOWN N/A(N/A) ge-0/0/1.0";
    let junos_deny_icmp = junos_deny.replace("6(0)", "1(8)");

    let mongo_slow = "query test.foo query: { a: 1 } ntoreturn:0 ntoskip:0 nscanned:10 keyUpdates:0 numYields: 0 locks(micros) r:1234 nreturned:1 reslen:50 5ms";
    let mongo3 = "2016-01-12T10:00:00.123+0000 I NETWORK  [initandlisten] waiting for connections on port 27017";

    let rails_head = r#"Started GET "/users/1?x=2" for 127.0.0.1 at 2012-01-01 10:00:00 +0000"#;
    let rails_full = format!(
        "{rails_head}\nProcessing by UsersController#show as HTML\n  Parameters: {{\"id\"=>\"1\"}}\n  Rendered users/show.html.erb (1.0ms)\nCompleted 200 OK in 15ms (Views: 10.5ms | ActiveRecord: 2.0ms)"
    );

    let squid = "1157689312.049   5006 10.105.165.40 TCP_MISS/200 4087 GET http://www.example.com/x - DIRECT/93.184.216.34 text/html";
    let squid_host = squid.replace("10.105.165.40", "proxy.example.com");
    let squid_cut = squid.rsplit_once(' ').unwrap().0.to_owned();

    let mut rows = vec![
        // Bacula
        r(
            "BACULA_TIMESTAMP",
            &["09-Jan 14:05"],
            &["Jan 09 14:05", "09-Jan"],
        ),
        r("BACULA_HOST", &["backup-dir", "bacula-fd1"], &["a b", ""]),
        r("BACULA_VOLUME", &["Vol-0001", "Full.0001"], &["a b"]),
        r("BACULA_DEVICE", &["FileStorage", "Drive-1"], &["a b"]),
        r("BACULA_DEVICEPATH", &["/var/bacula/storage"], &["storage"]),
        r(
            "BACULA_CAPACITY",
            &["0", "1,234,567", "12345"],
            &["1,23", ",123", "a"],
        ),
        r("BACULA_VERSION", &["5.2.13"], &["5 2"]),
        r(
            "BACULA_JOB",
            &["BackupClient1.2013-01-09_14.05.00_03"],
            &["a b"],
        ),
        r(
            "BACULA_LOG_MAX_CAPACITY",
            &[
                r#"User defined maximum volume capacity 1,000,000 exceeded on device "FileStorage" (/var/bacula)"#,
            ],
            &[
                r#"User defined maximum volume capacity exceeded on device "FileStorage" (/var/bacula)"#,
            ],
        ),
        r(
            "BACULA_LOG_END_VOLUME",
            &[r#"End of medium on Volume "Vol-0001" Bytes=1,234 Blocks=5 at 09-Jan-2013 14:05."#],
            &[r#"End of medium on Volume "Vol-0001" Bytes=1,234 Blocks=5 at 09-Jan 14:05."#],
        ),
        r(
            "BACULA_LOG_NEW_VOLUME",
            &[r#"Created new Volume "Vol-0001" in catalog."#],
            &[r"Created new Volume Vol-0001 in catalog."],
        ),
        r(
            "BACULA_LOG_NEW_LABEL",
            &[r#"Labeled new Volume "Vol-0001" on device "Drive-1" (/dev/nst0)."#],
            &[r#"Labeled new Volume "Vol-0001" on device "Drive-1""#],
        ),
        r(
            "BACULA_LOG_WROTE_LABEL",
            &[r#"Wrote label to prelabeled Volume "Vol-0001" on device "Drive-1" (/dev/nst0)"#],
            &[r#"Wrote label to Volume "Vol-0001" on device "Drive-1" (/dev/nst0)"#],
        ),
        r(
            "BACULA_LOG_NEW_MOUNT",
            &[
                r#"New volume "Vol-0001" mounted on device "Drive-1" (/dev/nst0) at 09-Jan-2013 14:05."#,
            ],
            &[r#"New volume "Vol-0001" mounted on device "Drive-1" (/dev/nst0)"#],
        ),
        r(
            "BACULA_LOG_VOLUME_PREVWRITTEN",
            &[r#"Volume "Vol-0001" previously written, moving to end of data."#],
            &[r#"Volume "Vol-0001" written, moving to end of data."#],
        ),
        r(
            "BACULA_LOG_READYAPPEND",
            &[r#"Ready to append to end of Volume "Vol-0001" size=1234"#],
            &[r#"Ready to append to end of Volume "Vol-0001""#],
        ),
        r(
            "BACULA_LOG_USEDEVICE",
            &[r#"Using Device "Drive-1""#],
            &["Using Device Drive-1"],
        ),
        r(
            "BACULA_LOG_NOOPEN",
            &[
                "Cannot open /etc/shadow: ERR=Permission denied",
                "  Cannot open \"/x\": ERR=No such file",
            ],
            &["Cannot open /etc/shadow"],
        ),
        r(
            "BACULA_LOG_NOOPENDIR",
            &["Could not open directory /root: ERR=Permission denied"],
            &["Could not open directory /root"],
        ),
        r(
            "BACULA_LOG_NOSTAT",
            &["Could not stat /proc/1/fd: ERR=No such file"],
            &["Could not stat /proc/1/fd"],
        ),
        r(
            "BACULA_LOG_DIFF_FS",
            &["  /mnt/usb is a different filesystem. Will not descend from / into it."],
            &["/mnt/usb is a different filesystem."],
        ),
        r(
            "BACULA_LOG_NOJOBS",
            &[r#"There are no more Jobs associated with Volume "Vol-0001". Marking it purged."#],
            &[r#"There are no more Jobs associated with Volume "Vol-0001"."#],
        ),
        r(
            "BACULA_LOG_ALL_RECORDS_PRUNED",
            &[r#"All records pruned from Volume "Vol-0001"; marking it "Purged""#],
            &[r#"All records pruned from Volume "Vol-0001""#],
        ),
        r(
            "BACULA_LOG_BEGIN_PRUNE_JOBS",
            &[
                "Begin pruning Jobs older than 6 months .",
                "Begin pruning Jobs older than 1 month 5 days .",
            ],
            &["Begin pruning Jobs older than ."],
        ),
        r(
            "BACULA_LOG_BEGIN_PRUNE_FILES",
            &["Begin pruning Files."],
            &["Begin pruning Jobs."],
        ),
        r(
            "BACULA_LOG_PRUNED_JOBS",
            &[
                "Pruned 2 Jobs for client web-fd from catalog.",
                "Pruned 1 Job for client web-fd from catalog.",
            ],
            &["Pruned Jobs for client web-fd from catalog."],
        ),
        r(
            "BACULA_LOG_PRUNED_FILES",
            &["Pruned Files from 2 Jobs for client web-fd from catalog."],
            &["Pruned Files from Jobs for client web-fd from catalog."],
        ),
        r("BACULA_LOG_ENDPRUNE", &["End auto prune."], &["End prune."]),
        r(
            "BACULA_LOG_NOPRUNE_JOBS",
            &["No Jobs found to prune."],
            &["No Files found to prune."],
        ),
        r(
            "BACULA_LOG_NOPRUNE_FILES",
            &["No Files found to prune."],
            &["No Jobs found to prune."],
        ),
        r(
            "BACULA_LOG_STARTJOB",
            &["Start Backup JobId 123, Job=BackupClient1.2013-01-09_14.05.00_03"],
            &["Start Backup JobId 123"],
        ),
        r(
            "BACULA_LOG_STARTRESTORE",
            &["Start Restore Job RestoreFiles.2013-01-09_14.05.00_03"],
            &["Start Restore"],
        ),
        r(
            "BACULA_LOG_JOBEND",
            &[
                "Job write elapsed time = 00:01:02, Transfer rate = 7.35 M Bytes/second",
                "Job write elapsed time = 00:00:01, Transfer rate = 0  Bytes/second",
            ],
            &["Job write elapsed time = 00:01:02"],
        ),
        r(
            "BACULA_LOG_CANCELLING",
            &["Cancelling duplicate JobId=12."],
            &["Cancelling duplicate JobId=."],
        ),
        r(
            "BACULA_LOG_MARKCANCEL",
            &["JobId 12, Job BackupClient1.2013-01-09_14.05.00_03 marked to be canceled."],
            &["JobId 12, Job x"],
        ),
        r(
            "BACULA_LOG_CLIENT_RBJ",
            &[r#"shell command: run ClientRunBeforeJob "/bin/true""#],
            &["shell command: run ClientRunBeforeJob /bin/true"],
        ),
        r(
            "BACULA_LOG_VSS",
            &["VSS ", "Generate VSS Writer", "VSS Writer"],
            &["XVSS "],
        ),
        r(
            "BACULA_LOG_NOSUIT",
            &["No prior or suitable Full backup found in catalog. Doing FULL backup."],
            &["No prior Full backup found in catalog. Doing FULL backup."],
        ),
        r(
            "BACULA_LOG_NOPRIOR",
            &["No prior Full backup Job record found."],
            &["No Full backup Job record found."],
        ),
        r(
            "BACULA_LOG_MAXSTART",
            &["Fatal error: Job canceled because max start delay time exceeded."],
            &["Job canceled because max start delay time exceeded."],
        ),
        r(
            "BACULA_LOG_DUPLICATE",
            &["Fatal error: JobId 12 already running. Duplicate job not allowed."],
            &["Fatal error: JobId already running. Duplicate job not allowed."],
        ),
        r(
            "BACULA_LOG_NOJOBSTAT",
            &["Fatal error: No Job status returned from FD."],
            &["Fatal error: No Job status returned."],
        ),
        r(
            "BACULA_LOG_FATAL_CONN",
            &[
                "Fatal error: bsock.c:133 Unable to connect to Client: web-fd on web.example.com:9102. ERR=Connection refused",
                "Fatal error: bsock.c:127 Unable to connect to Storage daemon on sd.example.com:9103. ERR=timed out",
            ],
            &[
                "Fatal error: bsock.c:133 Unable to connect to Client: web-fd on web.example.com. ERR=x",
            ],
        ),
        r(
            "BACULA_LOG_NO_CONNECT",
            &[
                "Warning: bsock.c:127 Could not connect to Client: web-fd on web.example.com:9102. ERR=Connection refused",
            ],
            &["Warning: bsock.c:127 Could not connect to Client: web-fd. ERR=x"],
        ),
        r(
            "BACULA_LOG_NO_AUTH",
            &[
                "Fatal error: Unable to authenticate with File daemon at web.example.com. Possible causes:",
            ],
            &["Fatal error: Unable to authenticate with File daemon at web.example.com."],
        ),
        r(
            "BACULA_LOG_JOB",
            &[
                "Bacula backup-dir 5.2.13 (19Jan13):",
                "Error: Bacula backup-dir 5.2.13 (19Jan13):",
            ],
            &["Bacula backup-dir 5.2.13"],
        ),
        r(
            "BACULA_LOGLINE",
            &[
                "09-Jan 14:05 backup-dir JobId 12: Start Backup JobId 12, Job=BackupClient1.2013-01-09_14.05.00_03",
                "09-Jan 14:05 backup-sd: Using Device \"Drive-1\"",
                "09-Jan 14:05 backup-dir JobId 12: Pruned 2 Jobs for client web-fd from catalog.",
            ],
            &[
                "09-Jan 14:05 backup-dir JobId 12: Something else entirely",
                "backup-dir JobId 12: End auto prune.",
            ],
        ),
        // BIND
        r(
            "BIND9_TIMESTAMP",
            &["28-Jul-2022 10:15:12.123"],
            &["2022-07-28 10:15:12"],
        ),
        r(
            "BIND9",
            &[
                "28-Jul-2022 10:15:12.123 queries: info: client 192.0.2.1#53412 (example.com): query: example.com IN A + (192.0.2.53)",
                "28-Jul-2022 10:15:12.123 queries: info: client @0x7f1234 192.0.2.1#53412 (example.com): query: example.com IN AAAA +E(0) (192.0.2.53)",
                "28-Jul-2022 10:15:12.123 queries: info: client 192.0.2.1#53412 (example.com): view internal: query: example.com IN A + (192.0.2.53)",
            ],
            &[
                "28-Jul-2022 10:15:12.123 queries: info: client 192.0.2.1#53412 (example.com): query: example.com IN A +",
                "28-Jul-2022 10:15:12.123 security: info: client 192.0.2.1#53412 (example.com): query: example.com IN A + (192.0.2.53)",
            ],
        ),
        // Zeek
        r(
            "BRO_HTTP",
            &[&http],
            &[&cut(&http), &http.replace('\t', " ")],
        ),
        r("BRO_DNS", &[&dns], &[&cut(&dns)]),
        r("BRO_CONN", &[&conn, &conn_unset], &[&cut(&conn)]),
        r("BRO_FILES", &[&files], &[&cut(&files)]),
        // Exim
        r(
            "EXIM_MSGID",
            &["16ZCW1-0005MB-00", "1ZCW1a-0005MBabcde-0001"],
            &["16ZCW1-0005MB", "16ZCW1_0005MB_00"],
        ),
        r(
            "EXIM_FLAGS",
            &["<=", "=>", "->", ">>", "*>", "**", "==", "(="],
            &["<>", "=", "<<"],
        ),
        r(
            "EXIM_DATE",
            &["2002-10-31 08:57:53"],
            &["31/10/2002 08:57:53"],
        ),
        r("EXIM_PID", &["[1234]"], &["[abc]", "1234"]),
        r("EXIM_QT", &["3s", "1h2m3s", "2w1d"], &["1x", "s3"]),
        r(
            "EXIM_EXCLUDE_TERMS",
            &[
                "Message is frozen",
                "Start queue run",
                "End queue run",
                " Warning: ",
                " retry time not reached ",
                " no IP address found for host ",
                "another process is handling this message",
            ],
            &["queue running", "Message is thawed"],
        ),
        r(
            "EXIM_REMOTE_HOST",
            &[
                "H=[192.0.2.1]",
                "H=mail.example.org [192.0.2.1]:25",
                "H=mail.example.org (helo.example.org) [192.0.2.1]:25",
            ],
            &["H=[]", "H=mail.example.org", "[192.0.2.1]"],
        ),
        r(
            "EXIM_INTERFACE",
            &["I=[192.0.2.9]:25"],
            &["I=[192.0.2.9]", "I=192.0.2.9:25"],
        ),
        r("EXIM_PROTOCOL", &["P=esmtpsa"], &["P=", "esmtp"]),
        r("EXIM_MSG_SIZE", &["S=5678"], &["S=", "S=big"]),
        r("EXIM_HEADER_ID", &["id=abc@host.example"], &["id=", "id"]),
        r("EXIM_SUBJECT", &[r#"T="hello there""#], &["T=hello"]),
        r(
            "EXIM_UNKNOWN_FIELD",
            &["U=exim", "QT=3s", "DN=x"],
            &["U=", "toolong=1"],
        ),
        r(
            "EXIM_NAMED_FIELDS",
            &[" H=[192.0.2.1] P=smtp S=10", "", " U=exim QT=3s"],
            &["H=[192.0.2.1]"],
        ),
        r(
            "EXIM_MESSAGE_ARRIVAL",
            &[&exim_arrival, exim_pid, &exim_bounce, exim_long],
            &[exim_delivery, "2002-10-31 08:57:53 16ZCW1-0005MB-00 <= "],
        ),
        r("EXIM", &[&exim_arrival, &exim_bounce], &[exim_delivery]),
        // HAProxy
        r(
            "HAPROXYTIME",
            &["12:14:14", "07:01:02"],
            &["12:14", "12:14:99"],
        ),
        r(
            "HAPROXYDATE",
            &["06/Feb/2009:12:14:14.655"],
            &["06/Feb/2009:12:14:14", "06-Feb-2009:12:14:14.655"],
        ),
        r(
            "HAPROXYCAPTUREDREQUESTHEADERS",
            &["1wt.eu", "Host|Agent", ""],
            &["a}b"],
        ),
        r(
            "HAPROXYCAPTUREDRESPONSEHEADERS",
            &["text/html|gzip", ""],
            &["a}b"],
        ),
        r(
            "HAPROXYHTTPBASE",
            &[hap_http, &hap_bad, &hap_cookie],
            &[
                &hap_nostatus,
                "10.0.1.2:33317 [06/Feb/2009:12:14:14.655] http-in",
            ],
        ),
        r(
            "HAPROXYHTTP",
            &[&hap_syslog, &hap_iso],
            &[
                hap_http,
                &hap_syslog.replace("haproxy[14389]:", "haproxy[14389]"),
            ],
        ),
        r("HAPROXYTCP", &[&hap_tcp], &[&hap_tcp_cut, hap_tcp_base]),
        // Junos
        r(
            "RT_FLOW_EVENT",
            &[
                "RT_FLOW_SESSION_CREATE",
                "RT_FLOW_SESSION_CLOSE",
                "RT_FLOW_SESSION_DENY",
            ],
            &["RT_FLOW_SESSION_OPEN", "rt_flow_session_close"],
        ),
        r(
            "RT_FLOW1",
            &[junos_close],
            &[
                "RT_FLOW_SESSION_CLOSE: session closed TCP FIN: 10.1.1.1/54321->192.0.2.5/80 junos-http",
                junos_create,
            ],
        ),
        r("RT_FLOW2", &[junos_create], &[junos_close, junos_deny]),
        r(
            "RT_FLOW3",
            &[junos_deny, &junos_deny_icmp],
            &[
                junos_create,
                "RT_FLOW_SESSION_DENY: session denied 10.1.1.1/54321->192.0.2.5/22 junos-ssh 6 deny-all trust untrust x",
            ],
        ),
        // Maven
        r(
            "MAVEN_VERSION",
            &["1.2.3", "1.0-SNAPSHOT", "2.*", "3", "1.2.3-RELEASE"],
            &["abc", "1.2.3.4", "1.0-alpha"],
        ),
        // MCollective
        r(
            "MCOLLECTIVEAUDIT",
            &["2012-01-01T10:00:00.123:", "2012-01-01 10:00:00:"],
            &["2012-01-01T10:00:00.123", "audit:"],
        ),
        r(
            "MCOLLECTIVE",
            &[
                "I, [2012-01-01T10:00:00.123456 #1234]  INFO",
                "E, [2012-01-01T10:00:00.123456 #1]ERROR",
            ],
            &[
                "Q, [2012-01-01T10:00:00.123456 #1234]  INFO",
                "I, [2012-01-01T10:00:00 #x]  INFO",
            ],
        ),
        // MongoDB
        r(
            "MONGO_LOG",
            &[
                "Jan  3 12:00:00.123 [initandlisten] db version v2.4.1",
                "Mar 21 15:06:24 [conn5] end connection",
            ],
            &[
                "Thu Jan  3 12:00:00.123 [initandlisten] x",
                "Jan  3 12:00:00.123 initandlisten x",
            ],
        ),
        r("MONGO_WORDDASH", &["my-db_1", "users"], &["a.b", "a b", ""]),
        r(
            "MONGO_QUERY",
            &["{ a: 1 }", "{ a: { b: 1 } }"],
            &["a: 1", "{a: 1}"],
        ),
        r(
            "MONGO_SLOWQUERY",
            &[mongo_slow],
            &[
                "query test.foo query: { a: 1 } ntoreturn:0 ntoskip:0 nscanned:10 nreturned:1 reslen:50",
                "query foo query: { a: 1 } ntoreturn:0 ntoskip:0 nscanned:10 nreturned:1 reslen:50 5ms",
            ],
        ),
        r("MONGO3_SEVERITY", &["I", "F", "D"], &["X", "II", "i"]),
        r(
            "MONGO3_COMPONENT",
            &["NETWORK", "-", "STORAGE"],
            &["a b", ""],
        ),
        r(
            "MONGO3_LOG",
            &[
                mongo3,
                "2016-01-12T10:00:00.123+0000 W -  [conn3] slow thing",
                "2016-01-12T10:00:00.123+0000 I COMMAND  msg without context",
            ],
            &["garbage", "2016-01-12T10:00:00.123+0000 I"],
        ),
        // Nagios
        r(
            "NAGIOSTIME",
            &["[1357000000]", "[1357000000.5]"],
            &["[abc]", "1357000000"],
        ),
        r(
            "NAGIOS_WARNING",
            &[
                "Warning: Return code of 127 for check of host 'web01' was out of bounds.",
                "Warning:x",
            ],
            &["Warn: x", "warning: x"],
        ),
        r(
            "NAGIOS_CURRENT_SERVICE_STATE",
            &["CURRENT SERVICE STATE: web01;HTTP;OK;HARD;1;HTTP OK: 200"],
            &[
                "CURRENT SERVICE STATE: web01;HTTP;OK;HARD;1",
                "CURRENT HOST STATE: web01;UP;HARD;1;ok",
            ],
        ),
        r(
            "NAGIOS_CURRENT_HOST_STATE",
            &["CURRENT HOST STATE: web01;UP;HARD;1;PING OK"],
            &["CURRENT HOST STATE: web01;UP;HARD"],
        ),
        r(
            "NAGIOS_SERVICE_NOTIFICATION",
            &[
                "SERVICE NOTIFICATION: ops;web01;HTTP;CRITICAL;notify-service-by-email;Connection refused",
            ],
            &["SERVICE NOTIFICATION: ops;web01;HTTP;CRITICAL"],
        ),
        r(
            "NAGIOS_HOST_NOTIFICATION",
            &["HOST NOTIFICATION: ops;web01;DOWN;notify-host-by-email;PING CRITICAL"],
            &["HOST NOTIFICATION: ops;web01;DOWN"],
        ),
        r(
            "NAGIOS_SERVICE_ALERT",
            &["SERVICE ALERT: web01;HTTP;CRITICAL;SOFT;1;Connection refused"],
            &[
                "SERVICE ALERT: web01;HTTP;CRITICAL;SOFT;x;msg",
                "SERVICE ALERT: web01;HTTP;CRITICAL",
            ],
        ),
        r(
            "NAGIOS_HOST_ALERT",
            &["HOST ALERT: web01;DOWN;HARD;3;CRITICAL - Host Unreachable"],
            &["HOST ALERT: web01;DOWN;HARD;x;msg"],
        ),
        r(
            "NAGIOS_SERVICE_FLAPPING_ALERT",
            &[
                "SERVICE FLAPPING ALERT: web01;HTTP;STARTED; Service appears to have started flapping (21.5% change >= 20.0% threshold)",
            ],
            &["SERVICE FLAPPING ALERT: web01;HTTP"],
        ),
        r(
            "NAGIOS_HOST_FLAPPING_ALERT",
            &["HOST FLAPPING ALERT: web01;STOPPED; Host appears to have stopped flapping"],
            &["HOST FLAPPING ALERT: web01"],
        ),
        r(
            "NAGIOS_SERVICE_DOWNTIME_ALERT",
            &[
                "SERVICE DOWNTIME ALERT: web01;HTTP;STARTED; Service has entered a period of scheduled downtime",
            ],
            &["SERVICE DOWNTIME ALERT: web01;HTTP"],
        ),
        r(
            "NAGIOS_HOST_DOWNTIME_ALERT",
            &[
                "HOST DOWNTIME ALERT: web01;STARTED; Host has entered a period of scheduled downtime",
            ],
            &["HOST DOWNTIME ALERT: web01"],
        ),
        r(
            "NAGIOS_PASSIVE_SERVICE_CHECK",
            &["PASSIVE SERVICE CHECK: web01;HTTP;0;OK"],
            &["PASSIVE SERVICE CHECK: web01;HTTP"],
        ),
        r(
            "NAGIOS_PASSIVE_HOST_CHECK",
            &["PASSIVE HOST CHECK: web01;0;UP"],
            &["PASSIVE HOST CHECK: web01"],
        ),
        r(
            "NAGIOS_SERVICE_EVENT_HANDLER",
            &["SERVICE EVENT HANDLER: web01;HTTP;CRITICAL;SOFT;restart-httpd"],
            &[
                "SERVICE EVENT HANDLER: web01;HTTP;CRITICAL;SOFT;restart;extra",
                "SERVICE EVENT HANDLER: web01;HTTP",
            ],
        ),
        r(
            "NAGIOS_HOST_EVENT_HANDLER",
            &["HOST EVENT HANDLER: web01;DOWN;HARD;restart-host"],
            &[
                "HOST EVENT HANDLER: web01;DOWN;HARD;restart;extra",
                "HOST EVENT HANDLER: web01;DOWN",
            ],
        ),
        r(
            "NAGIOS_TIMEPERIOD_TRANSITION",
            &["TIMEPERIOD TRANSITION: 24x7;-1;1"],
            &["TIMEPERIOD TRANSITION: 24x7;a;1"],
        ),
        r(
            "NAGIOS_EC_LINE_DISABLE_SVC_CHECK",
            &["EXTERNAL COMMAND: DISABLE_SVC_CHECK;web01;HTTP"],
            &[
                "EXTERNAL COMMAND: DISABLE_SVC_CHECK;web01",
                "EXTERNAL COMMAND: ENABLE_SVC_CHECK;web01;HTTP",
            ],
        ),
        r(
            "NAGIOS_EC_LINE_DISABLE_HOST_CHECK",
            &["EXTERNAL COMMAND: DISABLE_HOST_CHECK;web01"],
            &[
                "EXTERNAL COMMAND: DISABLE_HOST_CHECK;web01;extra",
                "EXTERNAL COMMAND: DISABLE_HOST_CHECK",
            ],
        ),
        r(
            "NAGIOS_EC_LINE_ENABLE_SVC_CHECK",
            &["EXTERNAL COMMAND: ENABLE_SVC_CHECK;web01;HTTP"],
            &["EXTERNAL COMMAND: ENABLE_SVC_CHECK;web01"],
        ),
        r(
            "NAGIOS_EC_LINE_ENABLE_HOST_CHECK",
            &["EXTERNAL COMMAND: ENABLE_HOST_CHECK;web01"],
            &["EXTERNAL COMMAND: ENABLE_HOST_CHECK;web01;extra"],
        ),
        r(
            "NAGIOS_EC_LINE_PROCESS_SERVICE_CHECK_RESULT",
            &["EXTERNAL COMMAND: PROCESS_SERVICE_CHECK_RESULT;web01;HTTP;0;OK - fine"],
            &["EXTERNAL COMMAND: PROCESS_SERVICE_CHECK_RESULT;web01;HTTP"],
        ),
        r(
            "NAGIOS_EC_LINE_PROCESS_HOST_CHECK_RESULT",
            &["EXTERNAL COMMAND: PROCESS_HOST_CHECK_RESULT;web01;0;UP - fine"],
            &["EXTERNAL COMMAND: PROCESS_HOST_CHECK_RESULT;web01"],
        ),
        r(
            "NAGIOS_EC_LINE_DISABLE_HOST_SVC_NOTIFICATIONS",
            &["EXTERNAL COMMAND: DISABLE_HOST_SVC_NOTIFICATIONS;web01"],
            &["EXTERNAL COMMAND: DISABLE_HOST_SVC_NOTIFICATIONS"],
        ),
        r(
            "NAGIOS_EC_LINE_DISABLE_HOST_NOTIFICATIONS",
            &["EXTERNAL COMMAND: DISABLE_HOST_NOTIFICATIONS;web01"],
            &["EXTERNAL COMMAND: DISABLE_HOST_NOTIFICATIONS"],
        ),
        r(
            "NAGIOS_EC_LINE_DISABLE_SVC_NOTIFICATIONS",
            &["EXTERNAL COMMAND: DISABLE_SVC_NOTIFICATIONS;web01;HTTP"],
            &["EXTERNAL COMMAND: DISABLE_SVC_NOTIFICATIONS;web01"],
        ),
        r(
            "NAGIOS_EC_LINE_ENABLE_HOST_SVC_NOTIFICATIONS",
            &["EXTERNAL COMMAND: ENABLE_HOST_SVC_NOTIFICATIONS;web01"],
            &["EXTERNAL COMMAND: ENABLE_HOST_SVC_NOTIFICATIONS"],
        ),
        r(
            "NAGIOS_EC_LINE_ENABLE_HOST_NOTIFICATIONS",
            &["EXTERNAL COMMAND: ENABLE_HOST_NOTIFICATIONS;web01"],
            &["EXTERNAL COMMAND: ENABLE_HOST_NOTIFICATIONS"],
        ),
        r(
            "NAGIOS_EC_LINE_ENABLE_SVC_NOTIFICATIONS",
            &["EXTERNAL COMMAND: ENABLE_SVC_NOTIFICATIONS;web01;HTTP"],
            &["EXTERNAL COMMAND: ENABLE_SVC_NOTIFICATIONS;web01"],
        ),
        r(
            "NAGIOS_EC_LINE_SCHEDULE_HOST_DOWNTIME",
            &[
                "EXTERNAL COMMAND: SCHEDULE_HOST_DOWNTIME;web01;1357000000;1357003600;1;0;3600;ops;patching",
            ],
            &[
                "EXTERNAL COMMAND: SCHEDULE_HOST_DOWNTIME;web01;1357000000;1357003600;1;0;3600;ops",
                "EXTERNAL COMMAND: SCHEDULE_HOST_DOWNTIME;web01;a;b;1;0;3600;ops;x",
            ],
        ),
        r(
            "NAGIOSLOGLINE",
            &[
                "[1357000000] SERVICE ALERT: web01;HTTP;CRITICAL;SOFT;1;Connection refused",
                "[1357000000] Warning: something",
                "[1357000000] EXTERNAL COMMAND: ENABLE_HOST_CHECK;web01",
                "[1357000000] TIMEPERIOD TRANSITION: 24x7;-1;1",
            ],
            &[
                "1357000000 SERVICE ALERT: web01;HTTP;CRITICAL;SOFT;1;msg",
                "[1357000000] UNKNOWN ENTRY: a;b",
            ],
        ),
        // PostgreSQL
        r(
            "POSTGRESQL",
            &[
                "2013-01-09 12:00:00.123 UTC [1234]",
                "2013-01-09 12:00:00 AEDT [77]",
                "01/09/2013 12:00:00 UTC alice 50e0f3a2.1a2b 4321",
            ],
            &["2013-01-09 12:00:00.123 UTC 1234", "garbage"],
        ),
        // Rails
        r(
            "RUUID",
            &["0123456789abcdef0123456789ABCDEF"],
            &[
                "0123456789abcdef0123456789ABCDE",
                "0123456789abcdef0123456789ABCDEG",
            ],
        ),
        r(
            "RCONTROLLER",
            &["UsersController#show", "Admin::UsersController#index"],
            &["NoHash", "#show"],
        ),
        r(
            "RAILS3HEAD",
            &[
                rails_head,
                r#"Started POST "/login" for 10.0.0.1 at 2012-01-01 10:00:00 -0700"#,
            ],
            &[
                r#"Started "/" for 127.0.0.1 at 2012-01-01 10:00:00 +0000"#,
                r#"Started GET "/" for 127.0.0.1 at 2012-01-01 10:00:00"#,
            ],
        ),
        r(
            "RPROCESSING",
            &[
                "Processing by UsersController#show as HTML",
                "Processing by UsersController#show as JSON\n  Parameters: {\"id\"=>\"1\"}",
            ],
            &[
                "Processing UsersController#show as HTML",
                "Processing by UsersController as HTML",
            ],
        ),
        r(
            "RAILS3PROFILE",
            &[
                "(Views: 1.0ms | ActiveRecord: 2.0ms",
                "(ActiveRecord: 2.0ms",
                "(Views: 3.0ms",
                "",
            ],
            &["(Views", "Views: 1.0ms"],
        ),
        r(
            "RAILS3FOOT",
            &[
                "Completed 200 OK in 15ms (Views: 10.5ms | ActiveRecord: 2.0ms)",
                "Completed 302 Found in 5ms",
                "Completed 200 OK in 4ms (Views: 3.0ms)",
                "Completed 200 OK in 4ms (Views: 3.0ms | ActiveRecord: 1.0ms | Allocations: 1234)",
            ],
            &["Completed in 15ms", "Finished 200 OK in 15ms"],
        ),
        r(
            "RAILS3",
            &[&rails_full, rails_head],
            &["Processing by UsersController#show as HTML"],
        ),
        // Redis
        r(
            "REDISTIMESTAMP",
            &["14 Nov 07:01:22.119", "4 Nov 07:01:22"],
            &["Nov 14 07:01:22", "14 November"],
        ),
        r(
            "REDISLOG",
            &[
                "[4018] 14 Nov 07:01:22.119 * ",
                "1234:M 14 Nov 07:01:22.119 # ",
                "1234:S 14 Nov 07:01:22.119 - ",
            ],
            &[
                "[4018] 14 Nov 07:01:22.119 ? ",
                "[4018] 14 Nov 07:01:22.119 *",
            ],
        ),
        r(
            "REDISMONLOG",
            &[
                r#"1339518083.107412 [0 127.0.0.1:60866] "keys" "*""#,
                r#"1339518083.107412 [0 127.0.0.1:60866] "ping""#,
            ],
            &[
                r#"1339518083.107412 [0 lua] "get" "x""#,
                "1339518083.107412 [0 127.0.0.1:60866] keys",
            ],
        ),
        // Ruby
        r(
            "RUBY_LOGLEVEL",
            &["DEBUG", "FATAL", "ERROR", "WARN", "INFO", "ANY"],
            &["TRACE", "info"],
        ),
        r(
            "RUBY_LOGGER",
            &[
                "I, [2012-01-01T10:00:00.123456 #1234]  INFO -- app: started",
                "E, [2012-01-01T10:00:00.123456 #1234] ERROR -- : boom",
                "A, [2012-01-01T10:00:00.123456 #1]   ANY -- x: y",
            ],
            &[
                "X, [2012-01-01T10:00:00.123456 #1234]  INFO -- app: started",
                "I, [2012-01-01T10:00:00.123456 #1234]  INFO app: started",
            ],
        ),
        // Squid
        r(
            "SQUID3",
            &[
                squid,
                &squid_host,
                "1157689312.049      5 10.0.0.1 TCP_DENIED/403 3652 GET http://x.example/ alice NONE/- text/html",
            ],
            &[&squid_cut, "garbage"],
        ),
    ];
    for t in [
        "CURRENT_SERVICE_STATE",
        "CURRENT_HOST_STATE",
        "SERVICE_NOTIFICATION",
        "HOST_NOTIFICATION",
        "SERVICE_ALERT",
        "HOST_ALERT",
        "SERVICE_FLAPPING_ALERT",
        "HOST_FLAPPING_ALERT",
        "SERVICE_DOWNTIME_ALERT",
        "HOST_DOWNTIME_ALERT",
        "PASSIVE_SERVICE_CHECK",
        "PASSIVE_HOST_CHECK",
        "SERVICE_EVENT_HANDLER",
        "HOST_EVENT_HANDLER",
        "EXTERNAL_COMMAND",
        "TIMEPERIOD_TRANSITION",
    ] {
        let hit = t.replace('_', " ");
        let miss = hit.to_lowercase();
        rows.push(r(
            &format!("NAGIOS_TYPE_{t}"),
            &[&hit],
            &[&miss, "OTHER TYPE"],
        ));
    }
    for c in [
        "DISABLE_SVC_CHECK",
        "ENABLE_SVC_CHECK",
        "DISABLE_HOST_CHECK",
        "ENABLE_HOST_CHECK",
        "PROCESS_SERVICE_CHECK_RESULT",
        "PROCESS_HOST_CHECK_RESULT",
        "SCHEDULE_SERVICE_DOWNTIME",
        "SCHEDULE_HOST_DOWNTIME",
        "DISABLE_HOST_SVC_NOTIFICATIONS",
        "ENABLE_HOST_SVC_NOTIFICATIONS",
        "DISABLE_HOST_NOTIFICATIONS",
        "ENABLE_HOST_NOTIFICATIONS",
        "DISABLE_SVC_NOTIFICATIONS",
        "ENABLE_SVC_NOTIFICATIONS",
    ] {
        rows.push(r(
            &format!("NAGIOS_EC_{c}"),
            &[c],
            &[&c.to_lowercase(), "OTHER_COMMAND"],
        ));
    }

    let own_files: Vec<String> = BUNDLED
        .iter()
        .map(|n| {
            std::fs::read_to_string(format!(
                "{}/src/grok/patterns/{n}",
                env!("CARGO_MANIFEST_DIR")
            ))
            .unwrap_or_default()
        })
        .collect();
    let mut expected: Vec<&str> = own_files
        .iter()
        .flat_map(|f| f.lines())
        .filter(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))
        .filter_map(|l| l.split_whitespace().next())
        .collect();
    expected.sort_unstable();
    expected.dedup();
    let mut covered: Vec<&str> = rows.iter().map(|(n, _, _)| n.as_str()).collect();
    covered.sort_unstable();
    assert_eq!(
        covered, expected,
        "a bundled name has no row, or a row is repeated"
    );

    let mut differences = Vec::new();
    let mut wrong = Vec::new();
    for (name, hits, misses) in &rows {
        for line in hits {
            if !accepts(&own, name, line) {
                wrong.push(format!("{name} misses {line:?}"));
            }
        }
        for line in misses {
            if accepts(&own, name, line) {
                wrong.push(format!("{name} matches {line:?}"));
            }
        }
        for line in hits.iter().chain(misses) {
            let Some(bundled) = &bundled else { continue };
            let (new, old) = (accepts(&own, name, line), accepts(bundled, name, line));
            if new != old {
                differences.push(format!("{name} {line:?}: own {new}, bundled {old}"));
            }
        }
    }
    for d in &differences {
        println!("DIFF {d}");
    }
    assert!(wrong.is_empty(), "{wrong:#?}");
}

/// A definition written inside the reference, `%{NAME:field=regex}`, is used
/// for that name, as patterns written for other grok engines do.
#[test]
fn an_inline_definition_names_its_own_regex() {
    let rows: [(&str, &str, &[(&str, &str)]); 3] = [
        (
            r"^%{TICKET:t=[A-Z]{3}-[0-9]+} %{WORD:w}$",
            "ABC-12 open",
            &[("t", "ABC-12"), ("w", "open")],
        ),
        (
            r"^%{CODE=[0-9]{3}} %{TICKET:t=T[0-9]+}$",
            "404 T7",
            &[("t", "T7")],
        ),
        (r"^%{INT:n:int}$", "42", &[("n", "42")]),
    ];
    for (pattern, input, want) in rows {
        let g = Grok::builder("grok:i").pattern(pattern).build().unwrap();
        let got = parse(&g, input).unwrap_or_else(|| panic!("{pattern} misses {input}"));
        let got: Vec<(String, String)> = got.into_iter().map(|(n, v, _)| (n, v)).collect();
        let want: Vec<(String, String)> = want
            .iter()
            .map(|(n, v)| ((*n).to_owned(), (*v).to_owned()))
            .collect();
        assert_eq!(got, want, "{pattern}");
    }
    assert_eq!(
        parse(
            &Grok::builder("grok:i")
                .pattern("^%{TICKET:t=[A-Z]{3}-[0-9]+}$")
                .build()
                .unwrap(),
            "abc-12"
        ),
        None
    );
}

/// A suffix can filter a value as it's written: case, or no field at all for
/// a placeholder.
#[test]
fn a_filter_suffix_changes_or_drops_the_value() {
    let g = Grok::builder("grok:f")
        .pattern("^%{WORD:level:lowercase} %{WORD:host:uppercase} %{NOTSPACE:user:nullif(-)}$")
        .build()
        .unwrap();
    assert_eq!(
        parse(&g, "WARN web01 alice"),
        text(&[("level", "warn"), ("host", "WEB01"), ("user", "alice")])
    );
    assert_eq!(
        parse(&g, "Info Web01 -"),
        text(&[("level", "info"), ("host", "WEB01")])
    );
}

#[test]
fn a_date_format_matches_and_hints_a_timestamp() {
    let g = Grok::builder("grok:d")
        .pattern("^\\[%{:ts:date(%d/%b/%Y:%H:%M:%S %z)}\\] %{WORD:verb} %{:day:date(%F)}$")
        .build()
        .unwrap();
    assert!(
        g.explain().starts_with("0: native steps"),
        "{}",
        g.explain()
    );
    let ts = |n: &str, v: &str| (n.to_owned(), v.to_owned(), Hint::Timestamp);
    assert_eq!(
        parse(&g, "[27/Nov/2026:18:30:00 +1100] GET 2026-11-27"),
        Some(vec![
            ts("ts", "27/Nov/2026:18:30:00 +1100"),
            ("verb".to_owned(), "GET".to_owned(), Hint::Text),
            ts("day", "2026-11-27"),
        ])
    );
    // Month 13 and hour 24 are out of range, so the format doesn't match.
    assert_eq!(
        parse(&g, "[27/Nov/2026:24:30:00 +1100] GET 2026-13-27"),
        None
    );
    // A named pattern keeps its matcher and takes the hint.
    let e = expand(
        "%{NOTSPACE:ts:date(%s)}",
        &Library::default(),
        Dialect::Rust,
    )
    .unwrap();
    assert_eq!(e.captures[0].hint, Hint::Timestamp);
    assert!(matches!(
        expand("%{:ts:date(%Z)}", &Library::default(), Dialect::Rust),
        Err(GrokError::Date(_))
    ));
}

/// A cost priced from a plan's steps lands in the same 2x band as the grok
/// rows the table measured whole. One on the regex grows with its fields.
#[test]
fn a_priced_grok_cost_is_within_a_band_of_the_measured_one() {
    for (row, pattern) in [
        (
            "grok.cri",
            "^%{TIMESTAMP_ISO8601:timestamp} (?<stream>stdout|stderr) (?<flag>[FP]) %{GREEDYDATA:message}$",
        ),
        (
            "grok.syslog",
            "^<%{NONNEGINT:pri}>%{NONNEGINT:version} %{TIMESTAMP_ISO8601:timestamp} %{NOTSPACE:hostname} %{NOTSPACE:appname} %{NOTSPACE:procid} %{NOTSPACE:msgid} - %{GREEDYDATA:message}$",
        ),
        ("grok.access", "^%{COMBINEDAPACHELOG}$"),
    ] {
        let g = Grok::builder("grok:c").pattern(pattern).build().unwrap();
        let (priced, measured) = (g.cost().unwrap(), crate::cost::of(row).unwrap());
        let ratio = priced.label() / measured.label();
        assert!(
            (0.5..=2.0).contains(&ratio),
            "{row}: priced {priced:?}, measured {measured:?}"
        );
        assert!(g.explain().contains("ns a hit"), "{}", g.explain());
    }
    // A pattern on the regex is priced from its capture groups.
    let on_regex = |p: &str| Grok::builder("grok:r").pattern(p).build().unwrap();
    let (one, three) = (
        on_regex("^(?:%{WORD:w} )+$"),
        on_regex("^(?:%{WORD:w} )+%{INT:n} %{INT:m}$"),
    );
    assert!(one.blocked()[0].is_some() && three.blocked()[0].is_some());
    let (a, b) = (one.cost().unwrap(), three.cost().unwrap());
    assert!(b.hit.ns_per_byte > a.hit.ns_per_byte);
    assert_eq!(a.miss, crate::cost::of("lazy_dfa_find").unwrap().miss);
    assert!(one.explain().contains("ns a hit"), "{}", one.explain());
    // More than one pattern runs the DFA first, so it isn't priced.
    let two = Grok::builder("grok:c")
        .pattern("^a")
        .pattern("^b")
        .build()
        .unwrap();
    assert!(two.cost().is_none());
}

/// A parser that samples every line writes what one that samples none does.
#[test]
fn a_shadowed_parser_writes_the_same_fields() {
    let pattern = "^%{IPV4:ip} %{WORD:verb} %{NOTSPACE:path}( %{INT:n})?$";
    let plain = Grok::builder("grok:s").pattern(pattern).build().unwrap();
    let shadowed = Grok::builder("grok:s")
        .pattern(pattern)
        .shadow(std::num::NonZeroU32::MIN)
        .build()
        .unwrap();
    for line in [
        "10.0.0.1 GET /a 7",
        "10.0.0.1 GET /a",
        "nope",
        "10.0.0.1 GET /\u{e9}",
        "",
    ] {
        assert_eq!(parse(&shadowed, line), parse(&plain, line), "{line:?}");
    }
}

/// A lazy field up to a literal leaves later runs free to backtrack, so the
/// compiled code settles the line itself.
#[test]
fn compiled_code_backtracks_after_a_lazy_field() {
    let line = br#"Deny tcp src outside:192.0.2.10/41200 dst inside:10.1.2.3/443 by access-group "OUTSIDE_IN" [0x0, 0x0]"#;
    let (_, code) = super::stock::STOCK
        .iter()
        .find(|(p, _)| *p == "^%{CISCOFW106023}$")
        .unwrap();
    let mut caps = [super::spec::UNSET; super::spec::MAX_CAPTURES];
    assert_eq!(code(line, &mut caps), super::spec::Steps::Matched);
    assert_eq!(caps[3], (21, 31));
}

/// `explain` names `grok!` for a lone pattern it could compile, and not for
/// a compiled stock format, an unanchored pattern or a list.
#[test]
fn explain_names_the_macro_for_a_pattern_it_could_compile() {
    let says = |g: &Grok| g.explain().contains("grok! compiles it");
    let built = |ps: &[&str]| {
        ps.iter()
            .fold(Grok::builder("grok:m"), |b, p| b.pattern(*p))
            .build()
            .unwrap()
    };
    assert!(says(&built(&["^%{INT:n} %{WORD:w}$"])));
    for ps in [
        &["^%{SYSLOGLINE}$"][..],
        &["%{INT:n} %{WORD:w}$"],
        &["^%{INT:n} %{WORD:w}$", "^%{WORD:w}$"],
    ] {
        assert!(!says(&built(ps)), "{ps:?}");
    }
}

/// A pattern that can only match from the start of the input anchors its
/// signature there. One that can match anywhere keeps a searched literal.
#[test]
fn an_anchored_pattern_has_an_anchored_signature() {
    let anchored = Grok::builder("grok:a")
        .pattern("^job %{WORD:name} done$")
        .build()
        .unwrap();
    assert!(anchored.signature().may_match(b"job nightly done"));
    assert!(!anchored.signature().may_match(b"a job nightly done"));
    assert!(matches!(
        anchored.parse(b"a job nightly done", &mut Fields::new()),
        Ok(Parsed::NoMatch)
    ));

    let floating = Grok::builder("grok:b")
        .pattern("job %{WORD:name} done")
        .build()
        .unwrap();
    assert!(floating.signature().may_match(b"a job nightly done"));
    let mixed = Grok::builder("grok:c")
        .pattern("^job %{WORD:name} done$")
        .pattern("task %{WORD:name}")
        .build()
        .unwrap();
    assert!(mixed.signature().may_match(b"a job nightly done"));
    assert!(mixed.signature().may_match(b"x task nightly"));
}

/// (patterns, a line they match): on native steps, on the regex, and a list
/// whose second pattern takes the line.
const TIERS: [(&[&str], &str); 3] = [
    (&["^%{WORD:a} %{INT:b}$"], "alpha 42"),
    (&["^(?:%{WORD:w} )+%{INT:n}$"], "alpha beta 42"),
    (&["x%{INT:n}", "%{WORD:a} %{INT:b}"], "alpha 42"),
];

/// A sink that parses the line again, with the same parser, from inside its
/// first `field`.
struct Again<'g> {
    grok: &'g Grok,
    line: &'static str,
    outer: Vec<(String, String)>,
    inner: Option<Vec<(String, String, Hint)>>,
}

impl<'a> crate::parse::FieldSink<'a> for Again<'_> {
    fn field(&mut self, name: &str, value: crate::parse::FieldValue<'a>) {
        if self.outer.is_empty() {
            self.inner = parse(self.grok, self.line);
        }
        let text = String::from_utf8_lossy(&value.bytes).into_owned();
        self.outer.push((name.to_owned(), text));
    }
    fn push_prefix(&mut self, _: &str) {}
    fn pop_prefix(&mut self) {}
    fn mark(&self) -> crate::parse::SinkMark {
        crate::parse::SinkMark(self.outer.len())
    }
    fn rollback(&mut self, mark: crate::parse::SinkMark) {
        self.outer.truncate(mark.0);
    }
}

#[test]
fn the_tiers_are_the_ones_their_tests_mean() {
    assert_eq!(grok(TIERS[0].0).blocked(), [None]);
    assert!(grok(TIERS[1].0).blocked()[0].is_some());
    assert_eq!(grok(TIERS[2].0).blocked().len(), 2);
    // The thread bench's three cases: two on steps, one on the regex.
    let plan = |p: &str| grok(&[p]).explain();
    assert!(plan("%{COMBINEDAPACHELOG}").contains("native steps"));
    let flow = "%{IP:src}:%{INT:sport} -> %{IP:dst}:%{INT:dport} %{WORD:proto}";
    assert!(plan(flow).contains("native steps"));
    assert!(plan("^(?:%{WORD:w} )+%{INT:n}$").contains("regex:"));
}

#[test]
fn a_sink_that_parses_again_reads_the_same_fields_both_times() {
    for (patterns, line) in TIERS {
        let g = grok(patterns);
        let alone = parse(&g, line).unwrap();
        assert_ne!(alone.len(), 0, "{line}");
        let mut sink = Again {
            grok: &g,
            line,
            outer: Vec::new(),
            inner: None,
        };
        g.parse(line.as_bytes(), &mut sink).unwrap();
        let outer: Vec<(String, String)> = alone
            .iter()
            .map(|(n, v, _)| (n.clone(), v.clone()))
            .collect();
        assert_eq!(sink.outer, outer, "{line}");
        assert_eq!(sink.inner.as_ref(), Some(&alone), "{line}");
    }
}

#[test]
fn sixteen_threads_on_one_parser_read_what_one_reads() {
    for (patterns, line) in TIERS {
        let g = grok(patterns);
        let alone = parse(&g, line);
        std::thread::scope(|scope| {
            for _ in 0..16 {
                scope.spawn(|| {
                    for _ in 0..200 {
                        assert_eq!(parse(&g, line), alone, "{line}");
                        assert_eq!(parse(&g, "no match here"), None);
                    }
                });
            }
        });
    }
}

/// A sink that panics leaves the thread's buffers usable.
#[test]
fn a_parse_after_a_sink_panicked_reads_as_before() {
    struct Bang;
    impl<'a> crate::parse::FieldSink<'a> for Bang {
        fn field(&mut self, _: &str, _: crate::parse::FieldValue<'a>) {
            panic!("the sink gave up");
        }
        fn push_prefix(&mut self, _: &str) {}
        fn pop_prefix(&mut self) {}
        fn mark(&self) -> crate::parse::SinkMark {
            crate::parse::SinkMark(0)
        }
        fn rollback(&mut self, _: crate::parse::SinkMark) {}
    }
    for (patterns, line) in TIERS {
        let g = grok(patterns);
        let alone = parse(&g, line);
        let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = g.parse(line.as_bytes(), &mut Bang);
        }));
        assert!(caught.is_err(), "{line}");
        assert_eq!(parse(&g, line), alone, "{line}");
    }
}