gbif-name-parser 0.3.0

A faithful Rust port of the scientific name parser from the Global Biodiversity Information Facility (GBIF): parses biological scientific names into their structured components (genus, epithets, authorship, rank, nomenclatural code).
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
// SPDX-License-Identifier: Apache-2.0

//! Java `org.gbif.nameparser.pipeline.AuthorshipParser` (817 lines) — parses the
//! authorship section of a tokenised name into a basionym [`Authorship`] + a combination
//! [`Authorship`], plus a sanctioning author and a couple of parse-quality flags. Entirely
//! regex-free: pure `TokenKind` dispatch, `&str`/`char` tests, and two small fixed-string
//! membership sets ([`AUTHOR_SUFFIXES`], [`GENERATIONAL_SUFFIXES`]).
//!
//! [`parse_name`] runs in three phases over `tokens[from..]` (`from` is the authorship-section
//! boundary found by `AuthorshipSplit`, Phase 1 Slice 3):
//!   - **Phase A** — a leading `(...)` is a basionym candidate. [`find_close`] finds the
//!     matching close paren (a plain depth counter). Inside the parens, a top-level colon
//!     ([`find_last_colon`], paren/bracket-depth-aware) separates a basionym sanctioning
//!     author, kept on the basionym authorship when it is Fries or Persoon (`"(Wulfen : Fr.)
//!     Schum."`; Java dropped it).
//!     [`has_upper_word`] then gates whether this is really a
//!     basionym at all: a `(...)` containing no upper-case WORD (e.g. a malformed
//!     `"(ilic)"`) is NOT a basionym — it is parked as `unparsed_from`/`unparsed_text` and
//!     skipped over.
//!   - **Phase B** — the remaining span is the combination. A top-level trailing colon
//!     splits off a sanctioning author (`"Boletus versicolor L. : Fr."` →
//!     `sanctioning_author = Some("Fr.")`, also on the combination authorship; combination span
//!     truncated before the colon); a year after it is the combination's.
//!     Whatever remains (with or without a sanctioning author extracted) is parsed as the
//!     combination authors; the whole trailing span is consumed (`i` set to `tokens.len()`
//!     unconditionally) — nothing after the combination span is ever unparsed.
//!   - **Phase C** — a final `if i < n` catch-all that would record any remainder as
//!     unparsed. **This is unreachable given Phase B's unconditional `i = n`** (confirmed
//!     by exhaustive case analysis of every path through `parse`, and the Java source's own
//!     comment at that point already says as much: "nothing is unparsed afterwards").
//!     Ported verbatim anyway (branch-for-branch fidelity; it costs nothing and Rust proves
//!     it dead via a coverage-style regression test below rather than by deleting it).
//!
//! [`parse_authors`] is the 14-case token walk that actually builds author strings within
//! one span (basionym or combination), handling years (incl. bracketed/second-plain
//! imprint years and year ranges), `ex`-author splitting, separators, particles, the
//! surname/initials inversion (with its generational-suffix and "forename M.Surname"
//! carve-outs), suffix gluing, apostrophes, mid-initial hyphens and slashes. Its trailing
//! post-processing ([`invert_all`]/[`invert_author`]/[`format_initials`]) re-orders
//! "Surname, Initials"-shaped strings into the canonical "Initials.Surname" form.
//!
//! ## Quirks preserved verbatim (do not "fix" — see the plan's Global Constraints 1–6)
//! 1. `COMMA`'s three lookahead branches (comma+year / comma+capitalised-or-particle-word /
//!    anything else) all currently execute the identical `flush(); i++; continue;` — the
//!    classification is vestigial. Preserved as three branches, not collapsed.
//! 2. [`AUTHOR_SUFFIXES`] membership is checked **case-sensitively** in the post-surname
//!    chaining sub-loop (an uppercase "F" there is an initial, not the filius suffix) but
//!    **case-insensitively** in the standalone-after-separator branch.
//! 3. [`GENERATIONAL_SUFFIXES`] excludes bare `I`/`V`/`X` — those are genuine author
//!    initials, not generation-suffix Roman numerals. Deliberate divergence (#22): an
//!    undotted `I` is kept as the generation after an author with leading initials
//!    (`G. B. Sowerby I`) or in a team that also carries a later generation. Deliberate
//!    divergence too: a generation behind surname-first initials stays behind the surname
//!    (`Sowerby G.B. II` → `G.B.Sowerby II`, where Java gave `I.I.G.B.Sowerby`).
//! 4. A bracketed `[YYYY]` is the *imprint* year next to a plain year (`Storr, 1970 [1969]`);
//!    alone it is the year itself, established from external evidence (the cataloguers'
//!    convention: `Hübner, [1806]`) — Java made it the imprint year with no year at all. A second
//!    *plain* year is the imprint year; quotation marks around it and the `imprint`/`not` of
//!    ICZN Recommendation 22A.2.3 (`(Peters, 1876 (imprint 1877))`) are no authors. A
//!    year range (`NUMBER "-"|"/" NUMBER`) keeps only the first year and sets
//!    [`AuthState::year_range`].
//! 5. The surname-first "**M** Balsamo"-style inversion only fires when a real surname
//!    (not just particles) is already in the buffer — [`ends_with_particle_only`] guards
//!    this, so `"H.da C." + "Monteiro"` stays a single chained author, not an inversion.
//!    **The Java inline comment on this branch is stale relative to the actual code**: it
//!    claims an isolated undotted trailing initial ("Zhang F" at end-of-segment or before a
//!    separator) keeps the CJK surname-first form, but `middle_initial_surname_follows`
//!    requires having consumed at least one `DOT` after the initials token (`j > i + 1`) —
//!    an undotted token never satisfies that, so the flip fires unconditionally whenever a
//!    real surname precedes it, comment notwithstanding. Verified against
//!    `NameParserImplTest` (`"... Zhang F & Pan Z-X in Zhang, F, ..., 2016"` →
//!    `combAuthors(..., "F.Zhang", "Z-X.Pan")` — "F" is immediately followed by "&", a
//!    separator, and still flips) and against the Java repo's `CLAUDE.md` authorship-
//!    conventions note, which documents the flipping behaviour directly. Ported to match
//!    the verified *behaviour*. Deliberate divergence (#24): a dotted initial takes the rest
//!    of its run (`Sars G.O.` → `G.O.Sars`, where Java gave `O.G.Sars`), and the
//!    middle-initial check looks past the whole run (`Roy G.O. Taylor` stays one author).
//!    Further divergences: the run carries on through a particle (`Sowerby J. de C.` →
//!    `J.de C.Sowerby`, #26) and takes a spaced, undotted last initial that ends the author
//!    (`Sars G. O,` → `G.O.Sars`, #27), and a particle surname after the initials counts
//!    as the surname of a forename-first author (`Gosewijn W.J. van Niewenhuizen`, #25).
//! 6. `format_initials` keeps a dot-per-letter and the input case of a hyphenated
//!    lower-case follow-up for dotted input (`"Y.-j."` stays `"Y.-j."`), but upper-cases a
//!    dot-less CJK-style hyphenated pair and adds a single trailing dot (`"Z-X"` →
//!    `"Z-X."`).
//!
//! `invert_author` and `normalise_author_case` are package-private (widened visibility) in
//! Java; neither has any caller outside `AuthorshipParser` in this port, so both stay
//! private here.

use crate::model::Authorship;
use crate::pipeline::cjk_names::{self, GivenName};
use crate::pipeline::double_surnames;
use crate::pipeline::rank_markers;
use crate::token::{is_particle, Token, TokenKind};

/// Java `AuthorshipParser.AUTHOR_SUFFIXES` — tokens that are filius/junior/etc.
/// abbreviations gluing onto the previous author. Checked case-sensitively in the
/// post-surname chaining sub-loop of [`parse_authors`] and case-insensitively in the
/// standalone-after-separator branch (Quirk 2 above) — the same 14-entry set both times.
const AUTHOR_SUFFIXES: &[&str] = &[
    "f", "fil", "filius", "j", "jr", "junior", "jun", "sr", "senior", "sen", "ms", "ined", "Bis",
    "bis",
];

/// Java `AuthorshipParser.GENERATIONAL_SUFFIXES` — Roman-numeral generational suffixes on a
/// surname ("Loeblich III" = Loeblich the third). Kept verbatim (upper-case) behind the
/// surname, never read as the initials "I.I.I.". Single letters (I/V/X) are deliberately
/// excluded — those are author initials, not suffixes — except for the `I` that
/// [`parse_authors`] can tell is a generation (#22).
const GENERATIONAL_SUFFIXES: &[&str] = &["II", "III", "IV", "VI", "VII", "VIII", "IX"];

/// Spellings of the anonymous author, compared case-insensitively and without a trailing dot:
/// "Anon.", "anon.", "Anonymous", "Anonymus", "Anonyme", "Anonym", "Anonymi". Alone in an author
/// slot they are [`Authorship::anonymous`], not an author.
const ANON_WORDS: &[&str] = &[
    "anon",
    "anonymous",
    "anonymus",
    "anonyme",
    "anonym",
    "anonymi",
];

/// Capitalised words that open a note, an annotation or a manuscript marker, never an author,
/// inside square brackets ("[Orth. error]", "[Sensu Smith]", "[M. Sars MS]").
const BRACKET_NOTE_WORDS: &[&str] = &[
    "auct",
    "auctt",
    "auctorum",
    "hort",
    "sensu",
    "non",
    "nec",
    "not",
    "sec",
    "emend",
    "fide",
    "orth",
    "nom",
    "comb",
    "sic",
    "corrig",
    "error",
    "lapsus",
    "misspelling",
    "ms",
    "msc",
    "ined",
];

/// Java `AuthorshipParser.AuthState` (package-private nested class). All fields were
/// package-private in Java; kept `pub` here (the enclosing struct is already capped at
/// `pub(crate)`, so this changes nothing about actual visibility, matching the interface
/// contract this type was specified against).
#[derive(Debug, Clone)]
pub(crate) struct AuthState {
    pub combination: Authorship,
    pub basionym: Authorship,
    pub basionym_present: bool,
    pub year_range: bool,
    /// True when an "f."/"fil."/"filius" suffix appeared on any author — botanical signal.
    pub has_filius: bool,
    /// True when the combination's year follows a comma ("Smith, 1900"), the zoological style.
    pub combination_year_after_comma: bool,
    /// True when a combination author is written with dotted initials before the surname
    /// ("M.A. Curtis"), not behind it ("Lindberg H").
    pub combination_initials_first: bool,
    /// An ex-author is a manuscript name another published ("Carpenter MS, Dall", `"Dall" Pils.`
    /// rewritten so), zoology's usage as much as botany's: no botanical evidence.
    pub manuscript_ex: bool,
    /// Java `int unparsedFrom = -1;` — kept as a sentinel `i32`, matching the established
    /// convention for this exact shape of field elsewhere in the port (see
    /// `ParseContext::mid_author_from`/`mid_author_to`).
    pub unparsed_from: i32,
    pub unparsed_text: Option<String>,
}

impl Default for AuthState {
    fn default() -> Self {
        AuthState {
            combination: Authorship::default(),
            basionym: Authorship::default(),
            basionym_present: false,
            year_range: false,
            has_filius: false,
            combination_year_after_comma: false,
            combination_initials_first: false,
            manuscript_ex: false,
            unparsed_from: -1,
            unparsed_text: None,
        }
    }
}

/// Java `AuthorshipParser.parse(List<Token> tokens, int from)` (`AuthorshipParser.java:48-109`).
/// See the module doc comment for the phase A/B/C walkthrough.
pub(crate) fn parse(tokens: &[Token], from: usize) -> AuthState {
    let mut s = AuthState::default();
    let mut i = from;
    let n = tokens.len();

    // Phase A: leading "(...)" basionym candidate.
    if i < n && tokens[i].kind == TokenKind::OpenParen {
        if let Some(close) = find_close(tokens, i) {
            // Inside the basionym brackets, a colon also separates the original author
            // from the sanctioning author ("(Wulfen : Fr.)"), kept on the basionym authorship
            // when it is Fries or Persoon — Java dropped it. Anything else after the colon is
            // dropped as before ("(Baba 1949: Burn 1962)" is no sanctioning).
            let bas_from = i + 1;
            let mut bas_end = close;
            let mut bas_sanctioning = None;
            if let Some(bas_colon) = find_last_colon(tokens, bas_from, bas_end) {
                if bas_colon > bas_from {
                    let mut sb = String::new();
                    append_author_words(tokens, bas_colon + 1, close, &mut sb);
                    bas_sanctioning = is_sanctioning_author(&sb).then_some(sb);
                    bas_end = bas_colon;
                }
            }
            // Reject a basionym made up of only lowercase tokens (no real surname).
            // "(ilic)" is malformed — capture it as unparsed instead. An anonymous author
            // ("(anon.)", "(anon., 1830)") is a basionym all the same.
            if has_upper_word(tokens, bas_from, bas_end) || has_anon_word(tokens, bas_from, bas_end)
            {
                let yr = parse_authors(tokens, bas_from, bas_end, &mut s.basionym);
                s.year_range |= yr;
                s.has_filius |= contains_filius_suffix(tokens, bas_from, bas_end);
                s.manuscript_ex |= has_manuscript_ex(tokens, bas_from, bas_end);
                s.basionym_present = true;
                s.basionym.sanctioning_author = bas_sanctioning;
                take_sanctioning_year(&tokens[bas_end..close], &mut s.basionym);
            } else {
                // Park the whole "(...)" span as unparsed and skip past it.
                let open_tok = &tokens[i];
                let close_tok = &tokens[close];
                s.unparsed_from = i as i32;
                s.unparsed_text = Some(slice_text(tokens, open_tok.start, close_tok.end));
            }
            i = close + 1;
        } else if let Some((bas_from, bas_end)) = unclosed_basionym(tokens, i) {
            let yr = parse_authors(tokens, bas_from, bas_end, &mut s.basionym);
            s.year_range |= yr;
            s.has_filius |= contains_filius_suffix(tokens, bas_from, bas_end);
            s.basionym_present = true;
            i = bas_end;
        }
    }

    // Phase B: whatever remains is the combination (+ optional trailing sanctioning author).
    if i < n {
        let comb_from = i;
        let mut comb_end = n;
        let mut comb_sanctioning = None;
        // pull out a colon + sanctioning author at the end of the combination span
        if let Some(colon) = find_last_colon(tokens, comb_from, comb_end) {
            if colon > comb_from {
                let mut sb = String::new();
                append_author_words(tokens, colon + 1, comb_end, &mut sb);
                if !sb.is_empty() {
                    comb_sanctioning = Some(sb);
                    comb_end = colon;
                }
            }
        }
        // A lower-case word that no author carries ends the authorship: the rest is left unparsed
        // ("Loranthus incanus Schumach. & Thonn. sessilis Sprague", "(L. f.) typica Rosent").
        let mut sanctioning_from = comb_end;
        if s.unparsed_from < 0 {
            if let Some(k) = sentence_after_authorship(tokens, comb_from, comb_end)
                .or_else(|| stray_lower_word(tokens, comb_from, comb_end, s.basionym_present))
            {
                s.unparsed_from = k as i32;
                s.unparsed_text = Some(spaced_text(&tokens[k..n]));
                comb_end = k;
                comb_sanctioning = None;
                sanctioning_from = n;
            }
        }
        let yr = parse_authors(tokens, comb_from, comb_end, &mut s.combination);
        s.year_range |= yr;
        s.manuscript_ex |= has_manuscript_ex(tokens, comb_from, comb_end);
        s.combination_year_after_comma = (comb_from..comb_end)
            .find(|&k| is_year(&tokens[k]))
            .is_some_and(|k| k > comb_from && tokens[k - 1].kind == TokenKind::Comma);
        s.combination_initials_first = (comb_from..comb_end).any(|k| {
            let initial = |j: usize| {
                j + 1 < comb_end
                    && tokens[j].kind == TokenKind::Word
                    && tokens[j].text.chars().count() == 1
                    && is_all_upper(&tokens[j].text)
                    && tokens[j + 1].kind == TokenKind::Dot
            };
            let mut j = k;
            while initial(j) {
                j += 2;
            }
            j > k
                && j < comb_end
                && tokens[j].kind == TokenKind::Word
                && starts_upper(&tokens[j].text)
                && contains_lower(&tokens[j].text)
        });
        s.has_filius |= contains_filius_suffix(tokens, comb_from, comb_end);
        s.combination.sanctioning_author = comb_sanctioning;
        take_sanctioning_year(&tokens[sanctioning_from..n], &mut s.combination);
        // Whether or not a sanctioning author was extracted, the entire trailing span
        // belongs to combination + sanctioning; nothing is unparsed afterwards.
        i = n;
    }

    // Phase C: catch-all for any remainder. Unreachable in practice — Phase B above
    // unconditionally sets `i = n` whenever it runs at all, and it runs whenever `i < n`
    // going in; so by this point `i == n` on every path. Ported verbatim regardless (see
    // the module doc comment) rather than dropped as "dead code".
    if i < n {
        let first = &tokens[i];
        let last = &tokens[n - 1];
        s.unparsed_from = i as i32;
        s.unparsed_text = Some(slice_text(tokens, first.start, last.end));
    }
    s
}

/// Lower-case words an author citation carries besides the particles and [`AUTHOR_SUFFIXES`]:
/// connectors, particles the table lacks ("ver Steeg"), brothers, manuscript and herbarium marks.
const LOWER_AUTHOR_WORDS: &[&str] = &[
    "ex", "et", "and", "und", "den", "dem", "ver", "fils", "fratr", "frat", "fratt", "mss", "msc",
    "mscr", "hort", "apud", "litt", "herb", "sched",
];

/// The first lower-case word of the combination span `tokens[from..to)` that no author carries — a
/// misplaced epithet ("Schumach. & Thonn. sessilis Sprague"), an English phrase, a note — once an
/// author has been read (`after_author`: a basionym came before the span). Only a whole word of
/// three or more lower-case letters outside any bracket, after a dot, comma, ampersand, bracket or
/// year, counts: a shorter one is an initial or a particle, and a fragment glued to its neighbour
/// is a broken character (`Kützing`).
fn stray_lower_word(tokens: &[Token], from: usize, to: usize, after_author: bool) -> Option<usize> {
    let mut depth = 0i32;
    let mut seen_author = after_author;
    for k in from..to {
        let t = &tokens[k];
        match t.kind {
            TokenKind::OpenParen | TokenKind::OpenBracket => depth += 1,
            TokenKind::CloseParen | TokenKind::CloseBracket => depth -= 1,
            _ => {}
        }
        if depth != 0 || t.kind != TokenKind::Word {
            continue;
        }
        if starts_upper(&t.text) {
            seen_author = true;
            continue;
        }
        // Right after another word it is a surname's tail: a lower-cased one ("De man") or one cut
        // by a broken character ("Hal csy" for Halácsy).
        let after_word = k > from && tokens[k - 1].kind == TokenKind::Word;
        let glued_before = k > 0 && tokens[k - 1].end == t.start;
        let glued_after = tokens.get(k + 1).is_some_and(|nx| {
            nx.start == t.end && matches!(nx.kind, TokenKind::Word | TokenKind::Other)
        });
        let w = t.text.as_str();
        // "of" before a lower-case word is English, no author's particle: "Natica of nidus",
        // "Nassellarid genera of uncertain affinities" — "Trustees of the British Museum" stays
        let next_lower = tokens.get(k + 1).filter(|nx| {
            k + 1 < to
                && nx.kind == TokenKind::Word
                && nx.text.chars().count() >= 3
                && nx.text.chars().all(|c| c.is_lowercase())
                && !is_particle(&nx.text)
                && nx.text != "the"
        });
        if w == "of" && next_lower.is_some() {
            return Some(k);
        }
        // a rank marker in the authorship, after an author too: "Reeve var of cornea Linn"
        if seen_author
            && !glued_before
            && w.chars().count() >= 3
            && rank_markers::match_infraspecific(w).is_some()
        {
            return Some(k);
        }
        if seen_author
            && !after_word
            && !glued_before
            && !glued_after
            && w.chars().count() >= 3
            && w.chars().all(|c| c.is_alphabetic() && c.is_lowercase())
            && !is_particle(w)
            && !AUTHOR_SUFFIXES.contains(&w)
            && !LOWER_AUTHOR_WORDS.contains(&w)
            && !ANON_WORDS.contains(&w)
        {
            return Some(k);
        }
    }
    None
}

/// Where a new sentence or name starts in the combination span `tokens[from..to)`: at a leading "&",
/// after the dot ending a
/// year ("Barnes & McDunnough 1913. Next sentence", "Mello-Leitão 1918. Rev. Soc. Brasil. Sci."),
/// or after the dot ending the epithet when prose follows, a capitalised word and a lower-case one
/// ("Negalasa fumalis. Next sentence", not "Sphagnum contortulum. H. Crum, 1991"). What follows is
/// a reference or prose, no author.
fn sentence_after_authorship(tokens: &[Token], from: usize, to: usize) -> Option<usize> {
    let word_at = |k: usize| k < to && tokens[k].kind == TokenKind::Word;
    // an "&" leading the span before a genus and its epithet joins another name: "Mesalia zinkeni
    // (Dunker 1851) & Promathildia turritella (Dunker 1851)", "Acanthopagrus butcheri & A. australis"
    let lower_word_at = |k: usize| {
        word_at(k)
            && tokens[k].text.chars().all(|c| c.is_lowercase())
            && !is_particle(&tokens[k].text)
    };
    let name_after_ampersand = tokens[from].kind == TokenKind::Ampersand
        && word_at(from + 1)
        && starts_upper(&tokens[from + 1].text)
        && (lower_word_at(from + 2)
            || (from + 2 < to
                && tokens[from + 2].kind == TokenKind::Dot
                && lower_word_at(from + 3)));
    if name_after_ampersand {
        return Some(from);
    }
    let epithet_before = from > 0 && {
        let w = tokens[from - 1].text.as_str();
        tokens[from - 1].kind == TokenKind::Word
            && w.chars().count() >= 5
            && w.chars().all(|c| c.is_lowercase())
            && rank_markers::match_infraspecific_allow_notho(w).is_none()
            && rank_markers::match_infrageneric_allow_notho(w).is_none()
    };
    let prose_after = word_at(from + 1)
        && starts_upper(&tokens[from + 1].text)
        && contains_lower(&tokens[from + 1].text)
        && word_at(from + 2)
        && tokens[from + 2].text.chars().all(|c| c.is_lowercase())
        && !is_particle(&tokens[from + 2].text)
        && !LOWER_AUTHOR_WORDS.contains(&tokens[from + 2].text.as_str());
    if tokens[from].kind == TokenKind::Dot && epithet_before && prose_after {
        return Some(from + 1);
    }
    let mut depth = 0i32;
    for k in from..to {
        match tokens[k].kind {
            TokenKind::OpenParen | TokenKind::OpenBracket => depth += 1,
            TokenKind::CloseParen | TokenKind::CloseBracket => depth -= 1,
            _ => {}
        }
        // a dot or a semicolon after a year: another sentence or another citation ("Baird and
        // Girard, 1852; H.B. Shaffer et al., 2004")
        if depth == 0
            && is_year(&tokens[k])
            && tokens[k].text.chars().count() == 4
            && k + 1 < to
            && matches!(tokens[k + 1].kind, TokenKind::Dot | TokenKind::Semicolon)
            && word_at(k + 2)
        {
            return Some(k + 2);
        }
    }
    None
}

/// The basionym of a bracket opened at `tokens[open]` but never closed, as `(from, end)`, where the
/// string shows where it ends: after its year (`( Dejean, 1831 Mill.`) or after a filius
/// (`( (L. f. Klatt`), with the combination author following straight on. Java read the whole
/// span as one combination authorship (`Dejean, Mill.`, `L.f.Klatt`). Without such an end the
/// bracket is left as it was.
fn unclosed_basionym(tokens: &[Token], open: usize) -> Option<(usize, usize)> {
    let mut from = open + 1;
    while from < tokens.len() && tokens[from].kind == TokenKind::OpenParen {
        from += 1;
    }
    if tokens[from..]
        .iter()
        .any(|t| t.kind == TokenKind::CloseParen)
    {
        return None;
    }
    let surname_at = |k: usize| {
        tokens
            .get(k)
            .is_some_and(|t| t.kind == TokenKind::Word && starts_upper(&t.text))
    };
    (from..tokens.len()).find_map(|k| {
        let t = &tokens[k];
        if is_year(t) && k > from && surname_at(k + 1) {
            return Some((from, k + 1));
        }
        let filius = t.kind == TokenKind::Word
            && AUTHOR_SUFFIXES.contains(&t.text.as_str())
            && k > from
            && tokens.get(k + 1).is_some_and(|d| d.kind == TokenKind::Dot)
            && surname_at(k + 2)
            && contains_lower(&tokens[k + 2].text);
        filius.then_some((from, k + 2))
    })
}

/// Java `AuthorshipParser.findLastColon(List<Token>, int, int)`. Depth-aware over both
/// paren and bracket nesting; `None` where Java returns `-1`.
fn find_last_colon(tokens: &[Token], from: usize, to: usize) -> Option<usize> {
    let mut depth = 0i32;
    let mut last = None;
    for (j, tok) in tokens.iter().enumerate().take(to).skip(from) {
        match tok.kind {
            TokenKind::OpenParen | TokenKind::OpenBracket => depth += 1,
            TokenKind::CloseParen | TokenKind::CloseBracket => depth -= 1,
            TokenKind::Colon if depth == 0 => last = Some(j),
            _ => {}
        }
    }
    last
}

/// Java `AuthorshipParser.findClose(List<Token>, int)`. Plain paren-depth counter (brackets
/// are not tracked here, unlike [`find_last_colon`]); `None` where Java returns `-1`.
fn find_close(tokens: &[Token], open_idx: usize) -> Option<usize> {
    let mut depth = 1i32;
    for (j, tok) in tokens.iter().enumerate().skip(open_idx + 1) {
        match tok.kind {
            TokenKind::OpenParen => depth += 1,
            TokenKind::CloseParen => {
                depth -= 1;
                if depth == 0 {
                    return Some(j);
                }
            }
            _ => {}
        }
    }
    None
}

/// Java `AuthorshipParser.parseAuthors(List<Token>, int, int, Authorship, AuthState)`.
/// The `AuthState state` parameter is accepted but never read anywhere in the Java method
/// body (verified against the source) — dropped here rather than carried as an unused Rust
/// parameter; this is a zero-behaviour-change omission, not a port gap.
///
/// Parses the author list within `tokens[from..to)`, populating `into`. Handles `ex`
/// splitting (ex authors come before main authors). A second 4-digit year encountered after
/// the first, or a bracketed year next to a plain one, becomes `into`'s imprint year, sitting next
/// to its publication year on the [`Authorship`]; a bracketed year on its own is the year. Returns `true` if a year range was detected
/// (e.g. "1845-1847", "1987-92").
fn parse_authors(tokens: &[Token], from: usize, to: usize, into: &mut Authorship) -> bool {
    let mut authors: Vec<String> = Vec::new();
    let mut ex_authors: Option<Vec<String>> = None;
    // Indices into `authors` of the authors that follow an `&` / `and` / `et` / `y` / `;`, which
    // [`invert_all`] joins to the author before them only as a comma-lost `Lea & A.M.` (#21).
    let mut after_separator: Vec<usize> = Vec::new();
    let mut ex_after_separator: Vec<usize> = Vec::new();
    let mut cur = String::new();
    let mut year_range = false;
    let mut bracketed_year: Option<String> = None;
    let mut i = from;
    // A later generation in the same team (`Sowerby I & Sowerby II`) tells that a trailing `I`
    // is a generation too (#22).
    let team_has_generation = tokens[from..to].windows(2).any(|w| {
        w[0].kind == TokenKind::Word
            && contains_lower(&w[0].text)
            && w[1].kind == TokenKind::Word
            && starts_upper(&w[1].text)
            && GENERATIONAL_SUFFIXES.contains(&w[1].text.to_uppercase().as_str())
    });
    let brackets = BracketedAuthors::read(tokens, from, to);

    while i < to {
        // "Anonymous [Bennett]": the anonymous word gives way to the attributed authors
        if brackets.skip.is_some_and(|(start, _)| i == start) {
            i = brackets.skip.expect("just checked").1;
            continue;
        }
        // "[Tourn.] L.": the pre-starting-point author ends where the bracket closes
        if brackets.ex_at == Some(i) {
            start_ex_authors(
                &mut cur,
                &mut authors,
                &mut ex_authors,
                &mut after_separator,
                &mut ex_after_separator,
            );
            i += 1;
            continue;
        }
        let t = &tokens[i];

        // year
        if t.kind == TokenKind::Number && (3..=4).contains(&t.text.chars().count()) {
            flush(&mut cur, &mut authors);
            let mut year = t.text.clone();
            // Detect a bracketed year: "[YYYY]" / "[YYYY?]": the imprint year next to a plain
            // year, else the year itself (decided once the whole authorship is read).
            let in_brackets_initial = i > from && tokens[i - 1].kind == TokenKind::OpenBracket;
            i += 1;
            // Uncertain year: a trailing "?" is part of the year ("198?" → year="198?").
            if i < to && tokens[i].kind == TokenKind::Other && tokens[i].text == "?" {
                year.push('?');
                i += 1;
            }
            // Confirm we're still inside the brackets (close-bracket follows the year).
            let in_brackets =
                in_brackets_initial && i < to && tokens[i].kind == TokenKind::CloseBracket;
            if in_brackets {
                bracketed_year.get_or_insert(year);
                i += 1; // skip CLOSE_BRACKET
                continue;
            }
            // First year wins — imprint dates ("Linnaeus, 1898, 1897") keep the first
            // (the actual publication year); the second becomes this authorship's imprint year.
            if into.year.is_none() {
                into.year = Some(year);
            } else if into.imprint_year.is_none() {
                into.imprint_year = Some(year);
            }
            // Detect year range: NUMBER + OTHER("-" or "/") + NUMBER → keep first year only
            if i + 1 < to {
                let sep = &tokens[i];
                if sep.kind == TokenKind::Other && (sep.text == "-" || sep.text == "/") {
                    let nx = &tokens[i + 1];
                    if nx.kind == TokenKind::Number && (1..=4).contains(&nx.text.chars().count()) {
                        year_range = true;
                        i += 2;
                    }
                }
            }
            // Drop a single trailing lowercase-letter year disambiguator ("1935h" / "1935 h",
            // or "193k7" where the k is an OCR/typo artifact followed by digits).
            if i < to {
                let nx = &tokens[i];
                if nx.kind == TokenKind::Word
                    && starts_lower(&nx.text)
                    && is_year_disambiguator(&nx.text)
                {
                    i += 1;
                }
            }
            continue;
        }

        // "(Peters, 1876 (imprint 1877))", "(not 1877)": the keyword of an imprint year cited
        // after the actual year (ICZN Recommendation 22A.2.3) is no author; the year that follows
        // becomes the imprint year like any second year.
        if t.kind == TokenKind::Word
            && (t.text.eq_ignore_ascii_case("imprint") || t.text.eq_ignore_ascii_case("not"))
            && into.year.is_some()
            && i > from
            && matches!(
                tokens[i - 1].kind,
                TokenKind::OpenParen | TokenKind::OpenBracket
            )
            && i + 1 < to
            && tokens[i + 1].kind == TokenKind::Number
            && tokens[i + 1].text.chars().count() == 4
        {
            i += 1;
            continue;
        }

        // "Carpenter MS, Dall", "Arn. ms., Grunow": the name of a manuscript, published by the
        // author after the comma — an ex citation
        if let Some(len) = manuscript_ex_at(tokens, i, to) {
            start_ex_authors(
                &mut cur,
                &mut authors,
                &mut ex_authors,
                &mut after_separator,
                &mut ex_after_separator,
            );
            i += len;
            continue;
        }

        // ex separator
        if t.kind == TokenKind::Word && t.text == "ex" {
            start_ex_authors(
                &mut cur,
                &mut authors,
                &mut ex_authors,
                &mut after_separator,
                &mut ex_after_separator,
            );
            i += 1;
            continue;
        }

        // a y joining the two surnames of one person: "Bolívar y Pieltain", "Dus. y Alon."
        if t.kind == TokenKind::Word && t.text == "y" && y_joins_surnames(tokens, i, from, to) {
            cur.push_str(" y");
            i += 1;
            continue;
        }

        // separators
        if t.kind == TokenKind::Ampersand
            || (t.kind == TokenKind::Word
                && (t.text.eq_ignore_ascii_case("and") || t.text.eq_ignore_ascii_case("et")))
            || (t.kind == TokenKind::Word && t.text == "y")
        {
            flush(&mut cur, &mut authors);
            after_separator.push(authors.len());
            i += 1;
            continue;
        }

        if t.kind == TokenKind::Semicolon {
            // Semicolons separate authors in citation lists ("Choi,J.H.; Im,W.T.; …")
            flush(&mut cur, &mut authors);
            after_separator.push(authors.len());
            i += 1;
            continue;
        }

        if t.kind == TokenKind::Comma {
            // peek next token to decide: comma+year, comma+author, comma+& etc.
            //
            // Quirk 1 (preserved verbatim, do not "fix"): all three outcomes below run the
            // exact same `flush(); i += 1; continue;` regardless of which lookahead branch
            // matched — the classification is vestigial in the current Java source.
            let mut j = i + 1;
            while j < to
                && (tokens[j].kind == TokenKind::Ampersand
                    || (tokens[j].kind == TokenKind::Word
                        && (tokens[j].text.eq_ignore_ascii_case("and")
                            || tokens[j].text.eq_ignore_ascii_case("et"))))
            {
                j += 1;
            }
            if j < to {
                let next = &tokens[j];
                if next.kind == TokenKind::Number {
                    flush(&mut cur, &mut authors);
                    i += 1;
                    continue;
                }
                if next.kind == TokenKind::Word
                    && (starts_upper(&next.text) || is_particle(&next.text))
                {
                    flush(&mut cur, &mut authors);
                    i += 1;
                    continue;
                }
            }
            flush(&mut cur, &mut authors);
            i += 1;
            continue;
        }

        // particle
        if t.kind == TokenKind::Word && starts_lower(&t.text) && is_particle(&t.text) {
            append_space(&mut cur);
            cur.push_str(&t.text);
            i += 1;
            // Pull through abbreviation dots that follow ("v." / "v.d." style particles).
            while i < to && tokens[i].kind == TokenKind::Dot {
                cur.push('.');
                i += 1;
            }
            continue;
        }

        // surname token
        if t.kind == TokenKind::Word && starts_upper(&t.text) {
            let text = t.text.clone();
            // A roman-numeral generational suffix directly after a complete surname
            // ("Loeblich III" = Loeblich the third) stays behind the surname as a suffix,
            // rendered upper-case ("Iii" → "III") — it is NOT the initials "I.I.I." that
            // the all-caps-trailing-initials inversion below would otherwise produce.
            // An undotted `I` is the first generation when nothing else can be meant: the
            // author already has leading initials (`G. B. Sowerby I`), or another author
            // of the team carries a later generation (#22). Java read it as an initial.
            // After leading initials a dotted `I.` that ends the author is the generation
            // too (`G.B. Sowerby I.`): such an author carries no initials behind the surname.
            let dotted = i + 1 < to && tokens[i + 1].kind == TokenKind::Dot;
            let generation_i = text == "I"
                && if dotted {
                    starts_with_initial(&cur) && author_ends_at(tokens, i + 2, to)
                } else {
                    starts_with_initial(&cur) || team_has_generation
                };
            if !cur.is_empty()
                && contains_lower(&cur)
                && !cur.ends_with('.')
                && !ends_with_particle_only(&cur)
                && (generation_i || GENERATIONAL_SUFFIXES.contains(&text.to_uppercase().as_str()))
            {
                append_space(&mut cur);
                cur.push_str(&text.to_uppercase());
                i += 1 + usize::from(generation_i && dotted);
                continue;
            }
            // No-comma "<Surname> <Initials>" inversion pattern: if cur already holds a
            // Latin surname AND the incoming token is a short all-caps word, treat it as
            // the initials trailing the surname and flush as a single inverted author. A
            // trailing dot in cur means we are mid-abbreviation (e.g. "v.d." awaiting
            // "L"), not after a complete surname — skip the inversion in that case.
            if !cur.is_empty()
                && text.chars().count() <= 3
                && is_all_upper(&text)
                && contains_lower(&cur)
                && !cur.ends_with('.')
                && !ends_with_particle_only(&cur)
            {
                let mut initials = text.clone();
                let mut j = i + 1;
                while j < to && tokens[j].kind == TokenKind::Dot {
                    initials.push('.');
                    j += 1;
                }
                // Take the rest of a dotted run ("Sars G.O.", "Smith A.B.C."). Stopping
                // after the first letter left "O." as an author of its own, which
                // invert_all then put in front: "O.G.Sars" (#24). Java does the same. A
                // particle inside the run ("Sowerby J. de C.") is kept with the initials
                // after it, rendered like the initials-first "J.de C.Sowerby" (#26).
                let mut particle_initials = String::new();
                if j > i + 1 {
                    j = take_initials_run(tokens, j, to, &mut initials);
                    if j + 2 < to
                        && tokens[j].kind == TokenKind::Word
                        && starts_lower(&tokens[j].text)
                        && is_particle(&tokens[j].text)
                        && tokens[j + 1].kind == TokenKind::Word
                        && tokens[j + 1].text.chars().count() == 1
                        && is_all_upper(&tokens[j + 1].text)
                        && tokens[j + 2].kind == TokenKind::Dot
                    {
                        let mut after = String::new();
                        let end = take_initials_run(tokens, j + 1, to, &mut after);
                        particle_initials =
                            format!("{} {}", tokens[j].text, format_initials(&after));
                        j = end;
                    }
                }
                // Pick up an optional "-X" continuation so "Pan Z-X" is treated as one
                // author pair (initials "Z-X") rather than two. (In practice the
                // tokenizer already glues an undotted "Z-X" into one WORD token, so this
                // peek only ever fires when a DOT separates the hyphen from what came
                // before, e.g. "Pan Z.-X" / "Pan Z .-X".)
                let mut k = j;
                if k < to {
                    let peek = &tokens[k];
                    if peek.kind == TokenKind::Other
                        && peek.text == "-"
                        && k + 1 < to
                        && tokens[k + 1].kind == TokenKind::Word
                        && tokens[k + 1].text.chars().count() == 1
                    {
                        initials.push('-');
                        initials.push_str(&tokens[k + 1].text);
                        k += 2;
                        while k < to && tokens[k].kind == TokenKind::Dot {
                            initials.push('.');
                            k += 1;
                        }
                    }
                }
                // "Forename M. Surname": a DOTTED middle initial followed by a
                // capitalised surname-shaped word means the all-caps token is a middle
                // initial of a single spelled-out-forename author ("Roy L.Taylor"), not
                // the inversion "L.Roy" + "Taylor". Skip the flip in that case and let
                // the normal surname handling below build the full author. Only dotted
                // initials qualify (`j > i + 1` requires at least one DOT consumed) — an
                // undotted run-on ("Balsamo M Fregni") still flips to end the current
                // author, and always does so regardless of what follows (see the module
                // doc comment's Quirk 5 note on the stale Java inline comment here).
                //
                // A generation after the initials ("Sowerby G.B. II", "Turnbow R.H. Jr.")
                // belongs to the surname: Java read "II" as the initials "I.I." and "Jr"
                // as the surname of a spelled-out-forename author. A particle surname
                // counts as a surname here ("Gosewijn W.J. van Niewenhuizen", #25).
                let generation = generation_after_initials(tokens, k, to);
                let middle_initial_surname_follows = generation.is_none()
                    && j > i + 1
                    && k < to
                    && tokens[k].kind == TokenKind::Word
                    && ((starts_upper(&tokens[k].text) && contains_lower(&tokens[k].text))
                        || particle_surname_at(tokens, k, to));
                if !middle_initial_surname_follows {
                    let surname = cur.trim().to_string();
                    cur.clear();
                    let mut author = format!(
                        "{}{}{}",
                        format_initials(&initials),
                        particle_initials,
                        surname
                    );
                    if let Some((suffix, next)) = generation {
                        author.push(' ');
                        author.push_str(&suffix);
                        k = next;
                    }
                    authors.push(author);
                    i = k;
                    continue;
                }
            }
            // If full ALL-CAPS author name (e.g. FISCHER) length > 1, normalise to title case
            let text = normalise_author_case(&t.text);
            append_space(&mut cur);
            cur.push_str(&text);
            i += 1;
            // A single capital letter without a trailing dot is an abbreviated initial —
            // supply the dot so subsequent tokens chain ("A S. Xu" → "A.S.Xu").
            if text.chars().count() == 1
                && text.chars().next().is_some_and(|c| c.is_uppercase())
                && (i >= to || tokens[i].kind != TokenKind::Dot)
            {
                cur.push('.');
            }
            // chain "<DOT> [WORD]" sequences for "Müll.Arg." style and "L. f" style.
            while i < to {
                let nx = &tokens[i];
                if nx.kind == TokenKind::Dot {
                    cur.push('.');
                    i += 1;
                    continue;
                }
                if nx.kind == TokenKind::Word {
                    let nxt = nx.text.clone();
                    // Filius / junior / etc. — case-sensitive: lowercase only. An
                    // uppercase "F" following a surname is an initial, not the filius
                    // suffix, so we don't collapse it here.
                    if AUTHOR_SUFFIXES.contains(&nxt.as_str())
                        && manuscript_ex_at(tokens, i, to).is_none()
                    {
                        // abbreviated surname ends with '.': "Burm.f." — no separator needed
                        // full surname ends with a letter: "Hooker f." — use a space
                        if !cur.is_empty() && !cur.ends_with('.') {
                            cur.push(' ');
                        }
                        cur.push_str(&nxt);
                        i += 1;
                        // optional dot after suffix
                        if i < to && tokens[i].kind == TokenKind::Dot {
                            cur.push('.');
                            i += 1;
                        }
                        continue;
                    }
                    // continued upper-case piece (common in compound surnames
                    // "Saint-Lager", "Müll.Arg.")
                    if starts_upper(&nx.text) && !cur.is_empty() && cur.ends_with('.') {
                        cur.push_str(&normalise_author_case(&nx.text));
                        i += 1;
                        continue;
                    }
                    break;
                }
                break;
            }
            continue;
        }

        // lone "f." or "f" sitting after a separator: treat as filius glued to last author
        if t.kind == TokenKind::Word
            && t.text.chars().count() <= 3
            && AUTHOR_SUFFIXES.contains(&t.text.to_lowercase().as_str())
        {
            // attach to the last completed author if any, else to current buffer
            if cur.is_empty() && !authors.is_empty() {
                let mut last = authors.pop().expect("just checked non-empty");
                if !last.ends_with('.') {
                    last.push('.');
                }
                last.push_str(&t.text);
                authors.push(last);
            } else {
                if !cur.is_empty() && !cur.ends_with('.') {
                    cur.push('.');
                }
                cur.push_str(&t.text);
            }
            i += 1;
            if i < to && tokens[i].kind == TokenKind::Dot {
                if !cur.is_empty() && !cur.ends_with('.') {
                    cur.push('.');
                } else if !authors.is_empty() {
                    let last_idx = authors.len() - 1;
                    if !authors[last_idx].ends_with('.') {
                        authors[last_idx].push('.');
                    }
                }
                i += 1;
            }
            continue;
        }

        if t.kind == TokenKind::Word {
            append_space(&mut cur);
            cur.push_str(&t.text);
            i += 1;
            // chain trailing dot for abbreviations like "al."
            if i < to && tokens[i].kind == TokenKind::Dot {
                cur.push('.');
                i += 1;
            }
            continue;
        }

        // An apostrophe next to a year is a quotation mark around it ("2018 ['2019']"), not part
        // of an author name.
        if t.kind == TokenKind::Other
            && t.text == "'"
            && ((i > from && tokens[i - 1].kind == TokenKind::Number)
                || (i + 1 < to && tokens[i + 1].kind == TokenKind::Number))
        {
            i += 1;
            continue;
        }
        // Apostrophe between authors / inside an author span — preserve it so that
        // names with internal apostrophes ("L.'t Mannetje", "M'Coy", "d'Urv.", "'t Hart")
        // render verbatim. Glue to the preceding character when there's no whitespace
        // gap in the input ("d'Urv"); otherwise insert a space ("Henk 't").
        // …but an apostrophe opening an author before a capitalised surname, and never closed, is
        // a stray quote, no elision ("Nereidavus kulkovi 'Kulkov"); "'t Hart" keeps its "t".
        if t.kind == TokenKind::Other
            && t.text == "'"
            && cur.is_empty()
            && tokens.get(i + 1).is_some_and(|nx| {
                nx.kind == TokenKind::Word && nx.start == t.end && starts_upper(&nx.text)
            })
            && !tokens[i + 1..to]
                .iter()
                .any(|q| q.kind == TokenKind::Other && q.text == "'")
        {
            i += 1;
            continue;
        }
        if t.kind == TokenKind::Other && t.text == "'" {
            let has_gap = !cur.is_empty() && i > 0 && tokens[i - 1].end < t.start;
            if has_gap {
                append_space(&mut cur);
            }
            cur.push('\'');
            i += 1;
            if i < to && tokens[i].kind == TokenKind::Word {
                cur.push_str(&tokens[i].text);
                i += 1;
            }
            continue;
        }
        // "?" inside an author span (typically a transcription artefact for a missing
        // letter, "Istv?nffi") — silently glue the next word onto cur without a space.
        if t.kind == TokenKind::Other && t.text == "?" && !cur.is_empty() {
            i += 1;
            if i < to && tokens[i].kind == TokenKind::Word {
                cur.push_str(&tokens[i].text);
                i += 1;
            }
            continue;
        }
        // Hyphen between abbreviated initial parts ("C.-K.", "J.-j.") — keep the hyphen
        // and preserve the input case of the single-letter follow-up so compound initials
        // round-trip cleanly ("Y.-j." stays "Y.-j.", "C.-K." stays "C.-K.").
        if t.kind == TokenKind::Other
            && t.text == "-"
            && !cur.is_empty()
            && cur.ends_with('.')
            && i + 1 < to
            && tokens[i + 1].kind == TokenKind::Word
        {
            let nx_text = tokens[i + 1].text.clone();
            cur.push('-');
            if nx_text.chars().count() == 1 {
                cur.push_str(&nx_text);
                i += 2;
                if i < to && tokens[i].kind == TokenKind::Dot {
                    cur.push('.');
                    i += 1;
                }
                continue;
            }
            i += 1;
            continue;
        }
        // "/" between two author words ("Smith/Jones") marks alternative authorship. Keep
        // the slash glued (no surrounding spaces) so the ambiguity stays visible in the
        // output; the name is already flagged UNCERTAIN_AUTHORSHIP upstream.
        if t.kind == TokenKind::Other
            && t.text == "/"
            && !cur.is_empty()
            && i + 1 < to
            && tokens[i + 1].kind == TokenKind::Word
        {
            cur.push('/');
            cur.push_str(&tokens[i + 1].text);
            i += 2;
            continue;
        }
        // Unknown punctuation in an author run — skip silently
        i += 1;
    }
    flush(&mut cur, &mut authors);

    // A bracketed year is the imprint year printed on the work next to the actual year ("Storr,
    // 1970 [1969]", ICZN Recommendation 22A.2.3); on its own it is the actual year, established
    // from external evidence (the cataloguers' convention: "Hübner, [1806]").
    if let Some(year) = bracketed_year {
        if into.year.is_none() {
            into.year = Some(year);
        } else if into.imprint_year.is_none() {
            into.imprint_year = Some(year);
        }
    }

    // An anonymous author alone ("Anon., 1830", "(Fr.) anon.", "Sw. ex Anon.") is the work's
    // anonymity, not an author. In a team ("Anonymous & Bennett") or as the ex author ("Anon. ex
    // Schltdl.") it stays an author string: the flag cannot say which author it means.
    if authors.len() == 1 && is_anon_word(&authors[0]) {
        authors.clear();
        into.anonymous = true;
    }
    if brackets.attributed {
        into.anonymous = true;
    }

    // An "ex" with no author after it ("Capuron ex ?", "Mill. ex") leaves the authors before it
    // as the only ones, instead of dropping them all; an anonymous one is an author ("Sw. ex
    // anon.").
    if authors.is_empty() && !into.anonymous {
        if let Some(ex) = ex_authors.take() {
            authors = ex;
            after_separator = std::mem::take(&mut ex_after_separator);
        }
    }
    if !authors.is_empty() {
        into.authors = invert_all(&authors, &after_separator);
    }
    if let Some(ex) = ex_authors {
        if !ex.is_empty() {
            into.ex_authors = invert_all(&ex, &ex_after_separator);
        }
    }
    year_range
}

/// Java `AuthorshipParser.invertAll(List<String>)`. Walks the author list applying two
/// transforms: (1) merge pairs where author N is a surname and author N+1 is initials
/// only, producing the combined "Initials.Surname" form ("LeConte" + "J.L." →
/// "J.L.LeConte"); (2) invert single authors of the form "Surname X.Y." or "Surname,
/// X.Y." into the same canonical form.
///
/// Unlike Java, (1) is restricted across an `&` / `and` / `et` / `y` / `;` (`after_separator`
/// holds the indices of the authors that follow one), which separate two authors: `Lam. & DC.`
/// is Lamarck and de Candolle, not `D.C.Lam.` (#21). A join across one survives only for a
/// full surname followed by dotted or hyphenated initials, because sources that turn the comma
/// of `Lea, A.M.` into `Lea & A.M.` are common (4,272 ChecklistBank rows). It is refused when
/// the left author is an abbreviation (`Lam.`, `Lap. & G.` = Laporte & Gory) or the right one
/// has a capital run (`DC.`, `A.DC.`, `HBK.`, `MULSANT & REY`). The rare initials written as a
/// run after a full surname (`Sclater & PL`) are the cost.
///
/// A lone initial before a separator shares the surname of the single-initialled author after
/// it: `A. & D. Löve` are A.Löve and D.Löve, `R. & G. Forst.` the two Forsters (5,267
/// ChecklistBank rows, all such family pairs). Java kept `A.` as an author of its own. `L.` is
/// left alone: it is Linnaeus.
///
/// A Chinese, Korean or Taiwanese surname and the spelled-out given name after its comma are one
/// person, rendered given name first: `Liu, Xian-wei` is `Xian-wei Liu`, `Park, Jong-Seok` is
/// `Jong-Seok Park` (see [`cjk_names`]). An unhyphenated given name (`Wang, Yuwen`) joins only
/// when no other author of the team is a bare surname: `Fan, Chiba & Wang` are three people.
/// Java kept both words as authors.
fn invert_all(authors: &[String], after_separator: &[usize]) -> Vec<String> {
    let mut out = Vec::with_capacity(authors.len());
    let mut i = 0;
    while i < authors.len() {
        let cur = &authors[i];
        if i + 1 < authors.len() {
            let next = &authors[i + 1];
            if !after_separator.contains(&(i + 1)) {
                let joins = match cjk_names::given_name_after(cur, next) {
                    Some(GivenName::Hyphenated) => true,
                    Some(GivenName::Joined) => !authors
                        .iter()
                        .enumerate()
                        .any(|(j, a)| j != i && j != i + 1 && cjk_names::is_bare_surname(a)),
                    None => false,
                };
                if joins {
                    out.push(format!("{next} {cur}"));
                    i += 2;
                    continue;
                }
            }
            if after_separator.contains(&(i + 1)) && cur != "L." {
                if let Some(surname) = shared_surname(cur, next) {
                    out.push(format!("{cur}{surname}"));
                    i += 1;
                    continue;
                }
            }
            let joinable = !after_separator.contains(&(i + 1))
                || (!cur.ends_with('.') && !has_capital_run(next));
            if joinable && looks_like_surname(cur) && looks_like_initials(next) {
                out.push(format!("{}{}", format_initials(next), cur));
                i += 2;
                continue;
            }
        }
        out.push(invert_author(cur));
        i += 1;
    }
    out
}

/// The surname `next` lends to the lone initial `cur` in [`invert_all`]: `cur` is one capital
/// and its dot (`A.`), `next` one initial and a surname (`D.Löve`, `G.Forst.`) — returned as
/// `Löve`, `Forst.`.
fn shared_surname<'a>(cur: &str, next: &'a str) -> Option<&'a str> {
    let one_initial = |s: &str| {
        let mut cs = s.chars();
        cs.next().is_some_and(char::is_uppercase) && cs.next() == Some('.')
    };
    if cur.chars().count() != 2 || !one_initial(cur) || !one_initial(next) {
        return None;
    }
    let surname = next[next.find('.')? + 1..].trim_start();
    let mut cs = surname.chars();
    (cs.next().is_some_and(char::is_uppercase) && cs.next().is_some_and(char::is_lowercase))
        .then_some(surname)
}

/// Java `AuthorshipParser.invertAuthor(String)`. Re-orders names like "Surname, J.L." or
/// "Surname Initials" into the canonical "J.L.Surname" form (no space between dotted
/// initials and the surname). Package-private in Java (widened visibility); no caller
/// outside this module in this port, so kept private here (see the module doc comment).
fn invert_author(s: &str) -> String {
    let s = s.trim();
    if s.is_empty() {
        return String::new();
    }

    // Pattern A: "Surname, X.Y." or "Surname, XY" — exactly one comma, not at position 0.
    if let Some(comma) = s.find(',') {
        if comma > 0 && !s[comma + 1..].contains(',') {
            let surname = s[..comma].trim();
            let initials = s[comma + 1..].trim();
            if looks_like_surname(surname) && looks_like_initials(initials) {
                return format!("{}{}", format_initials(initials), surname);
            }
        }
    }
    // Pattern B: "Surname X.Y." (trailing dotted initials). Without a dot the trailing
    // all-caps part is a CJK-style surname-first author ("Zhang F", "Pan Z-X") and must
    // be preserved verbatim. Particles like "Van", "de" must be kept on the surname side.
    if let Some(last_space) = s.rfind(' ') {
        if last_space > 0 {
            let first = s[..last_space].trim();
            let last = s[last_space + 1..].trim();
            if last.contains('.')
                && looks_like_surname(first)
                && looks_like_initials(last)
                && !contains_particle(first)
            {
                return format!("{}{}", format_initials(last), first);
            }
        }
    }
    s.to_string()
}

/// Takes the single-capital initials of a run from `tokens[j]` on into `out`, with their
/// dots, and returns the index past them. A capital qualifies when a dot follows it, when
/// it is glued to the token before it (`de Souza J.I`), or when the author ends right after
/// it (`Sars G. O, 1903`, #27). A spaced, undotted `I` at the end is left for
/// [`generation_after_initials`] (`Sowerby G.B. I`).
fn take_initials_run(tokens: &[Token], mut j: usize, to: usize, out: &mut String) -> usize {
    while j < to
        && tokens[j].kind == TokenKind::Word
        && tokens[j].text.chars().count() == 1
        && is_all_upper(&tokens[j].text)
        && ((j + 1 < to && tokens[j + 1].kind == TokenKind::Dot)
            || tokens[j].start == tokens[j - 1].end
            || (tokens[j].text != "I" && author_ends_at(tokens, j + 1, to)))
    {
        out.push_str(&tokens[j].text);
        j += 1;
        while j < to && tokens[j].kind == TokenKind::Dot {
            out.push('.');
            j += 1;
        }
    }
    j
}

/// True when the author being read ends before `tokens[k]`: the end of the span, a
/// separator, a year or a closing bracket, or an `in`/`ex` citation.
fn author_ends_at(tokens: &[Token], k: usize, to: usize) -> bool {
    if k >= to {
        return true;
    }
    let t = &tokens[k];
    match t.kind {
        TokenKind::Comma
        | TokenKind::Semicolon
        | TokenKind::Ampersand
        | TokenKind::Number
        | TokenKind::CloseParen
        | TokenKind::CloseBracket => true,
        TokenKind::Word => {
            ["in", "ex", "y"].contains(&t.text.as_str())
                || t.text.eq_ignore_ascii_case("and")
                || t.text.eq_ignore_ascii_case("et")
        }
        _ => false,
    }
}

/// True when the `y` at `tokens[i]` joins the paternal and maternal surname of one person listed in
/// [`double_surnames`] (`Bolívar y Pieltain`, `Dusmet y Alonso`, `Caballero y C.`, `Graells y de la
/// Agüera`); Java read every `y` as `&`. Any other `y` still separates two people: the string
/// cannot tell `Dusmet y Alonso` (one person) from `Spix y Agassiz` (two).
fn y_joins_surnames(tokens: &[Token], i: usize, from: usize, to: usize) -> bool {
    // the word before the y, behind an abbreviation's dot ("Dus. y Alon.")
    let left = match tokens[from..i].iter().rev().take(2).collect::<Vec<_>>()[..] {
        [w, ..] if w.kind == TokenKind::Word => w,
        [d, w] if d.kind == TokenKind::Dot && w.kind == TokenKind::Word => w,
        _ => return false,
    };
    // the first word after it that is no particle ("Asso y del Río")
    let right = tokens[i + 1..to]
        .iter()
        .take_while(|t| t.kind == TokenKind::Word)
        .find(|t| !double_surnames::skips(&t.text));
    right.is_some_and(|right| double_surnames::joins(&left.text, &right.text))
}

/// True when `tokens[k]` starts a particle surname: one or more particles (`de`, `van den`,
/// `v.`) and then a capitalised word with a lower-case letter (`van Niewenhuizen`). Not
/// when an initial follows that surname (`van Hoof R.`): that author is surname-first
/// itself, so it has no use for the initials in front of it.
fn particle_surname_at(tokens: &[Token], mut k: usize, to: usize) -> bool {
    let start = k;
    while k < to
        && tokens[k].kind == TokenKind::Word
        && starts_lower(&tokens[k].text)
        && is_particle(&tokens[k].text)
    {
        k += 1;
        while k < to && tokens[k].kind == TokenKind::Dot {
            k += 1;
        }
    }
    let initial_follows = k + 1 < to
        && tokens[k + 1].kind == TokenKind::Word
        && tokens[k + 1].text.chars().count() == 1
        && is_all_upper(&tokens[k + 1].text);
    k > start
        && k < to
        && tokens[k].kind == TokenKind::Word
        && starts_upper(&tokens[k].text)
        && contains_lower(&tokens[k].text)
        && !initial_follows
}

/// The generation at `tokens[k]` behind a surname-first author's initials, rendered as it
/// goes after the surname (`II`, `Jr.`), and the index past it. Roman numerals come out
/// upper-case and lose a trailing dot. A spaced, undotted `I` counts too, since the author
/// already has initials (#22); a dotted `I.` is another initial, and so is an `I` glued to
/// the run (`J.I`), which the caller has taken already.
fn generation_after_initials(tokens: &[Token], k: usize, to: usize) -> Option<(String, usize)> {
    if k >= to || tokens[k].kind != TokenKind::Word {
        return None;
    }
    let text = &tokens[k].text;
    let dotted = k + 1 < to && tokens[k + 1].kind == TokenKind::Dot;
    let next = if dotted { k + 2 } else { k + 1 };
    let upper = text.to_uppercase();
    if GENERATIONAL_SUFFIXES.contains(&upper.as_str()) || (text == "I" && !dotted) {
        return Some((upper, next));
    }
    let lower = text.to_lowercase();
    if ["jr", "junior", "jun", "sr", "senior", "sen"].contains(&lower.as_str()) {
        // ASCII by the match above, so slicing at 1 is safe.
        let dot = if dotted { "." } else { "" };
        let suffix = format!("{}{}{dot}", &upper[..1], &lower[1..]);
        return Some((suffix, next));
    }
    None
}

/// Two capitals in a row (`DC`, `A.DC.`, `HBK.`), as opposed to one initial per letter
/// (`A.M.`, `J-R`).
fn has_capital_run(s: &str) -> bool {
    let mut prev_upper = false;
    for c in s.chars() {
        let upper = c.is_uppercase();
        if upper && prev_upper {
            return true;
        }
        prev_upper = upper;
    }
    false
}

/// Java `AuthorshipParser.looksLikeSurname(String)`.
fn looks_like_surname(s: &str) -> bool {
    if s.chars().count() < 2 {
        return false;
    }
    match s.chars().next() {
        Some(c) if c.is_uppercase() => {}
        _ => return false,
    }
    s.chars().any(|c| c.is_lowercase())
}

/// Java `AuthorshipParser.looksLikeInitials(String)`. Initials are ≤4 single letters, the
/// first upper-case. A lower-case letter is only allowed immediately after a hyphen —
/// that is a hyphenated given-name initial ("Y.-j.", "C.-K."). This still rejects
/// abbreviated surnames ("Fr.", "Liu", "Sacc.") whose lower-case follow-up letters are NOT
/// preceded by a hyphen.
fn looks_like_initials(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    let mut letters = 0u32;
    let mut first_letter_seen = false;
    let mut prev_hyphen = false;
    for c in s.chars() {
        if c == '.' || c == ' ' {
            continue;
        }
        if c == '-' {
            prev_hyphen = true;
            continue;
        }
        if !c.is_alphabetic() {
            return false;
        }
        letters += 1;
        if letters > 4 {
            return false;
        }
        let upper = c.is_uppercase();
        if !first_letter_seen {
            if !upper {
                return false;
            }
            first_letter_seen = true;
        } else if !upper && !prev_hyphen {
            return false;
        }
        prev_hyphen = false;
    }
    letters > 0
}

/// Java `AuthorshipParser.formatInitials(String)`. Dotted hyphenated initials ("C.-K.",
/// "Y.-j.") get a dot after each letter and keep the input case of a single-letter
/// follow-up so compound initials round-trip cleanly. Dot-less CJK-style hyphenated
/// initials ("Z-X") get a single trailing dot, upper-cased. Plain (non-hyphenated) input
/// gets one dot per letter, upper-cased.
fn format_initials(s: &str) -> String {
    let had_dots = s.contains('.');
    let cleaned: String = s.chars().filter(|&c| c != '.' && c != ' ').collect();
    if cleaned.contains('-') {
        let mut b = String::new();
        for c in cleaned.chars() {
            if c == '-' {
                b.push('-');
            } else if had_dots {
                b.push(c);
                b.push('.');
            } else {
                b.extend(c.to_uppercase());
            }
        }
        if !had_dots {
            b.push('.');
        }
        return b;
    }
    let mut b = String::new();
    for c in cleaned.chars() {
        b.extend(c.to_uppercase());
        b.push('.');
    }
    b
}

/// Java `AuthorshipParser.isYearDisambiguator(String)`. True when the token text looks
/// like a year-disambiguator suffix that should be dropped after a year token: a single
/// lowercase letter optionally followed by all-digit characters — e.g. "h" (from
/// "1935h"), "k7" (OCR-garbled year-suffix artifact in "193k7").
fn is_year_disambiguator(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_lowercase() => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_digit())
}

/// Java `AuthorshipParser.isAllUpper(String)` — this class's own copy (distinct from the
/// tokenizer's and from `AuthorshipSplit`'s own same-named private helpers).
fn is_all_upper(s: &str) -> bool {
    let mut any = false;
    for c in s.chars() {
        if c.is_alphabetic() {
            any = true;
            if !c.is_uppercase() {
                return false;
            }
        }
    }
    any
}

/// True when the token text starts with an upper-case character — Java `Token.startsUpper()`
/// applied here to a plain `&str` (this file has no `Token` in scope at every call site,
/// e.g. inside `invert_author`/`looks_like_surname`, so it's a free `&str` function rather
/// than a `Token` method, matching `authorship_split.rs`'s own established pattern of
/// small per-file free-function bridges).
fn starts_upper(s: &str) -> bool {
    s.chars().next().is_some_and(|c| c.is_uppercase())
}

/// Java `Token.startsLower()` — see [`starts_upper`]'s doc comment for why this is a free
/// `&str` function here.
fn starts_lower(s: &str) -> bool {
    s.chars().next().is_some_and(|c| c.is_lowercase())
}

/// Java `AuthorshipParser.endsWithParticleOnly(StringBuilder)`. True when the accumulated
/// buffer ends with a particle word (or is just particles). In that case the next
/// all-caps token is the next author's initial, not a trailing surname-inversion signal —
/// there's no real surname accumulated yet. Particle attached to a preceding dot
/// ("H.da") is still considered a particle tail — split on whitespace and dots to find
/// the last word-ish token.
fn ends_with_particle_only(cur: &str) -> bool {
    let s = cur.trim();
    if s.is_empty() {
        return true;
    }
    let last = s
        .split(|c: char| c.is_whitespace() || c == '.')
        .rfind(|p| !p.is_empty())
        .unwrap_or("");
    is_particle(last)
}

/// True when the author buffer opens with a dotted initial (`G.B.Sowerby`, `A.Murray`).
fn starts_with_initial(cur: &str) -> bool {
    let mut cs = cur.chars();
    cs.next().is_some_and(char::is_uppercase) && cs.next() == Some('.')
}

/// Java `AuthorshipParser.containsLower(CharSequence)`.
fn contains_lower(s: &str) -> bool {
    s.chars().any(|c| c.is_lowercase())
}

/// Java `AuthorshipParser.containsParticle(String)`.
fn contains_particle(s: &str) -> bool {
    s.split_whitespace().any(is_particle)
}

/// Java `AuthorshipParser.flush(StringBuilder, List<String>)`.
fn flush(cur: &mut String, authors: &mut Vec<String>) {
    if !cur.is_empty() {
        authors.push(cur.trim().to_string());
        cur.clear();
    }
}

/// A year after the sanctioning author (ICN Art. 15: Fries or Persoon) is the name's own, as the
/// source writes it: "Pers.:Fr., 1801", "Retz.:Fr., 1769" predate Fries' sanctioning work. Java
/// dropped it. Any other "sanctioning author" is a colon misread ("C. Mu:2ller"). `tokens` is the
/// span from the colon on.
fn take_sanctioning_year(tokens: &[Token], auth: &mut Authorship) {
    if auth.year.is_none()
        && auth
            .sanctioning_author
            .as_deref()
            .is_some_and(is_sanctioning_author)
    {
        auth.year = tokens
            .iter()
            .find(|t| {
                t.kind == TokenKind::Number
                    && t.text.len() == 4
                    && t.text
                        .parse::<u16>()
                        .is_ok_and(|y| (1700..2100).contains(&y))
            })
            .map(|t| t.text.clone());
    }
}

/// Fries or Persoon, the two sanctioning authors (ICN Art. 15), with or without the abbreviation's
/// dot — anything else after a colon is a misread colon ("C. Mu:2ller").
pub(crate) fn is_sanctioning_author(author: &str) -> bool {
    ["Fr", "Fries", "Pers", "Persoon"].iter().any(|f| {
        author
            .strip_prefix(f)
            .is_some_and(|rest| !rest.starts_with(char::is_alphabetic))
    })
}

/// Java `AuthorshipParser.appendSpace(StringBuilder)`.
fn append_space(cur: &mut String) {
    match cur.chars().last() {
        Some(' ') | Some('.') | Some('-') | None => {}
        Some(_) => cur.push(' '),
    }
}

/// Java `AuthorshipParser.appendAuthorWords(List<Token>, int, int, StringBuilder)`. Used
/// only to render the sanctioning-author span (a plain word+dot run, no separators/years).
fn append_author_words(tokens: &[Token], from: usize, to: usize, sb: &mut String) {
    let mut i = from;
    while i < to {
        if tokens[i].kind == TokenKind::Word {
            if !sb.is_empty() && !sb.ends_with('.') {
                sb.push(' ');
            }
            sb.push_str(&normalise_author_case(&tokens[i].text));
            i += 1;
            while i < to && tokens[i].kind == TokenKind::Dot {
                sb.push('.');
                i += 1;
            }
        } else {
            i += 1;
        }
    }
}

/// Java `AuthorshipParser.normaliseAuthorCase(String)`. Normalises an ALL-CAPS author word
/// to title case ("FISCHER" → "Fischer"). Short all-caps tokens (< 4 chars) are kept
/// as-is — they are likely initials ("MA", "DC"). Package-private in Java (widened
/// visibility); no caller outside this module in this port, so kept private here.
fn normalise_author_case(s: &str) -> String {
    if s.chars().count() < 4 {
        return s.to_string();
    }
    let all_upper = !s.chars().any(|c| c.is_alphabetic() && !c.is_uppercase());
    if !all_upper {
        return s.to_string();
    }
    let mut b = String::with_capacity(s.len());
    let mut first = true;
    for c in s.chars() {
        if c.is_alphabetic() {
            if first {
                b.push(c);
                first = false;
            } else {
                b.extend(c.to_lowercase());
            }
        } else {
            b.push(c);
            first = true;
        }
    }
    b
}

/// Java `AuthorshipParser.sliceText(List<Token>, int, int)`. Iterates the FULL token list
/// (not just a sub-range by index) filtering by absolute character-offset containment —
/// matches the Java source's own (slightly unusual but harmless) structure.
fn slice_text(tokens: &[Token], start: usize, end: usize) -> String {
    let mut sb = String::new();
    for t in tokens {
        if t.start >= start && t.end <= end {
            sb.push_str(&t.text);
        }
    }
    sb
}

/// The tokens' text, with a space wherever the source had a gap between two of them.
fn spaced_text(tokens: &[Token]) -> String {
    let mut sb = String::new();
    for (k, t) in tokens.iter().enumerate() {
        if k > 0 && tokens[k - 1].end < t.start {
            sb.push(' ');
        }
        sb.push_str(&t.text);
    }
    sb
}

/// Java `AuthorshipParser.hasUpperWord(List<Token>, int, int)`. True if any token in
/// `[from, to)` is a WORD that starts with an upper-case letter — or, unlike Java, a surname
/// behind an elided particle (`d'Orbigny`, `d'Urv.`, `l'Hér.`), which the tokenizer keeps as
/// one lower-case-initial WORD. Java rejected `(d'Orbigny, 1826)` as a basionym, parking it as
/// unparsed on the name string and dropping it silently from a separately supplied authorship.
fn has_upper_word(tokens: &[Token], from: usize, to: usize) -> bool {
    tokens[from..to].iter().any(|t| {
        t.kind == TokenKind::Word && (starts_upper(&t.text) || is_elided_particle_surname(&t.text))
    })
}

/// A word like `d'Orbigny`: an apostrophe directly followed by an upper-case letter.
fn is_elided_particle_surname(s: &str) -> bool {
    s.split('\'').skip(1).any(starts_upper)
}

/// A spelling of the anonymous author, see [`ANON_WORDS`].
fn is_anon_word(s: &str) -> bool {
    let word = s.trim_end_matches('.');
    ANON_WORDS.iter().any(|a| word.eq_ignore_ascii_case(a))
}

/// Does `tokens[from..to)` hold a word spelling the anonymous author?
fn has_anon_word(tokens: &[Token], from: usize, to: usize) -> bool {
    tokens[from..to]
        .iter()
        .any(|t| t.kind == TokenKind::Word && is_anon_word(&t.text))
}

/// A manuscript mark, its dot and the comma after it ("MS,", "ms.,", "Ms.,"), between an author and
/// the one who published the name: its token count at `i`, else `None`.
fn manuscript_ex_at(tokens: &[Token], i: usize, to: usize) -> Option<usize> {
    let t = &tokens[i];
    if t.kind != TokenKind::Word || !matches!(t.text.as_str(), "ms" | "MS" | "Ms" | "mss" | "MSS") {
        return None;
    }
    let mut k = i + 1;
    if k < to && tokens[k].kind == TokenKind::Dot {
        k += 1;
    }
    let author_follows = k + 1 < to
        && tokens[k].kind == TokenKind::Comma
        && tokens[k + 1].kind == TokenKind::Word
        && (starts_upper(&tokens[k + 1].text) || is_particle(&tokens[k + 1].text));
    (i > 0 && author_follows).then_some(k + 1 - i)
}

/// The span `tokens[from..to)` cites a manuscript name as an ex-author ("Carpenter MS, Dall").
pub(crate) fn has_manuscript_ex(tokens: &[Token], from: usize, to: usize) -> bool {
    (from..to).any(|k| manuscript_ex_at(tokens, k, to).is_some())
}

/// "Everything collected so far becomes ex authors": the authors before an `ex`, or before the
/// closing bracket of a pre-starting-point author ("[Tourn.] L.").
fn start_ex_authors(
    cur: &mut String,
    authors: &mut Vec<String>,
    ex_authors: &mut Option<Vec<String>>,
    after_separator: &mut Vec<usize>,
    ex_after_separator: &mut Vec<usize>,
) {
    flush(cur, authors);
    *ex_authors = Some(std::mem::take(authors));
    *ex_after_separator = std::mem::take(after_separator);
}

/// A year the [`parse_authors`] walk reads as one: a 3-4 digit number.
fn is_year(t: &Token) -> bool {
    t.kind == TokenKind::Number && (3..=4).contains(&t.text.chars().count())
}

/// Square brackets around authors, read by their shape, for every nomenclatural code. The walk
/// in [`parse_authors`] skips the bracket tokens themselves; this says what they meant.
///
/// - The whole author slot in brackets — `[Denis & Schiffermüller], 1775`, `([Lightfoot],
///   1786)`, `(Gouan) [Clairv.]`, `L'Her. ex [Soland.]` — or an anonymous word followed by one —
///   `Anonymous [Bennett], 1830`: the work was published anonymously and its authors are known
///   from external evidence, "enclosed in square brackets to show the original anonymity" (ICZN
///   Recommendation 51D, <https://code.iczn.org/authorship/article-51-citation-of-names-of-authors/>).
///   Sets [`Authorship::anonymous`] and keeps the bracketed authors.
/// - Bracketed authors followed by a real author — `Lupinus [Tourn.] L.`, `[Kar. & Kir.] Regel`:
///   a pre-starting-point author, which the botanical code cited "preferably between square
///   brackets or by the use of the word ex" (Paris Code 1956, Recommendation 50D,
///   <https://www.iapt-taxon.org/historic/1956.htm>). Current codes keep only the *ex* form
///   (Tokyo 1994 Art. 46.5; Shenzhen 2018 Art. 46.7, Ex. 40: "Lupinus Tourn. ex L.",
///   <https://www.iapt-taxon.org/nomen/pages/main/art_46.html>; the Madrid Code 2025 was not
///   checked), so the bracketed authors become ex authors.
/// - Any other bracket — supplied initials (`Gerstaecker, [C.E.] A.`), dates (`Fieber [Nov.
///   1860]`), a year inside (`[Hübner, 1806]`), annotations (`[Orth. error]`) — keeps the walk's
///   behaviour: the brackets are dropped.
#[derive(Debug, Default)]
struct BracketedAuthors {
    /// The whole author slot is bracketed: the authors are attributed to an anonymous work.
    attributed: bool,
    /// `(anonymous word, opening bracket)` of "Anonymous [Bennett]": the walk jumps over the word.
    skip: Option<(usize, usize)>,
    /// The closing bracket of a pre-starting-point author, read like an `ex`.
    ex_at: Option<usize>,
}

impl BracketedAuthors {
    fn read(tokens: &[Token], from: usize, to: usize) -> Self {
        let mut shape = BracketedAuthors::default();
        let head = author_head_end(tokens, from, to);
        // the authors after the last `ex` outside brackets ("L'Her. ex [Soland.]")
        let run = last_ex_outside_brackets(tokens, from, head).map_or(from, |ex| ex + 1);
        if run >= head {
            return shape;
        }
        let first = &tokens[run];
        if first.kind == TokenKind::OpenBracket {
            let Some(close) = matching_bracket(tokens, run, head) else {
                return shape;
            };
            if close + 1 == head && looks_like_author_run(tokens, run + 1, close, false) {
                shape.attributed = true;
            } else if run == from
                && close + 1 < head
                && tokens[close + 1].kind == TokenKind::Word
                && starts_upper(&tokens[close + 1].text)
                && looks_like_author_run(tokens, run + 1, close, true)
            {
                // "[Sawada ex] Goh" already carries its `ex`
                if tokens[close - 1].text != "ex" {
                    shape.ex_at = Some(close);
                }
            }
        } else if first.kind == TokenKind::Word && is_anon_word(&first.text) {
            let mut open = run + 1;
            if open < head && tokens[open].kind == TokenKind::Dot {
                open += 1;
            }
            if open < head && tokens[open].kind == TokenKind::OpenBracket {
                if let Some(close) = matching_bracket(tokens, open, head) {
                    if close + 1 == head && looks_like_author_run(tokens, open + 1, close, false) {
                        shape.attributed = true;
                        shape.skip = Some((run, open));
                    }
                }
            }
        }
        shape
    }
}

/// Where the author names of `tokens[from..to)` end: at the first year outside brackets or an
/// bracketed year ("[Hübner], [1806]"), less the commas before it.
fn author_head_end(tokens: &[Token], from: usize, to: usize) -> usize {
    let mut depth = 0i32;
    let mut end = to;
    for j in from..to {
        match tokens[j].kind {
            TokenKind::OpenBracket if j + 1 < to && is_year(&tokens[j + 1]) => {
                end = j;
                break;
            }
            TokenKind::OpenBracket => depth += 1,
            TokenKind::CloseBracket => depth -= 1,
            TokenKind::Number if depth == 0 && is_year(&tokens[j]) => {
                end = j;
                break;
            }
            _ => {}
        }
    }
    while end > from && tokens[end - 1].kind == TokenKind::Comma {
        end -= 1;
    }
    end
}

/// The last `ex` of `tokens[from..to)` that is not inside square brackets.
fn last_ex_outside_brackets(tokens: &[Token], from: usize, to: usize) -> Option<usize> {
    let mut depth = 0i32;
    let mut last = None;
    for (j, t) in tokens.iter().enumerate().take(to).skip(from) {
        match t.kind {
            TokenKind::OpenBracket => depth += 1,
            TokenKind::CloseBracket => depth -= 1,
            TokenKind::Word if depth == 0 && t.text == "ex" => last = Some(j),
            _ => {}
        }
    }
    last
}

/// The `]` closing the `[` at `open`, within `tokens[..to)`.
fn matching_bracket(tokens: &[Token], open: usize, to: usize) -> Option<usize> {
    let mut depth = 0i32;
    for (j, t) in tokens.iter().enumerate().take(to).skip(open) {
        match t.kind {
            TokenKind::OpenBracket => depth += 1,
            TokenKind::CloseBracket => {
                depth -= 1;
                if depth == 0 {
                    return Some(j);
                }
            }
            _ => {}
        }
    }
    None
}

/// Is `tokens[from..to)` nothing but author names: at least one surname-like word (a capital and
/// one more letter, or `d'Orbigny`-style — bare initials are no author run), lower-case words
/// only as particles, team separators, author suffixes or anonymous words, no numbers, colons or
/// nested brackets, no note word, no in-citation ("[Péron in] Lamarck"), and ending in a word or
/// a dot ("[Bethune-] Baker" and "[Lambillion &] Cabeau" are no author runs). `trailing_ex` admits
/// a final `ex` ("[Sawada ex] Goh").
fn looks_like_author_run(tokens: &[Token], from: usize, to: usize, trailing_ex: bool) -> bool {
    if from >= to || !matches!(tokens[to - 1].kind, TokenKind::Word | TokenKind::Dot) {
        return false;
    }
    let mut surname = false;
    for (j, t) in tokens.iter().enumerate().take(to).skip(from) {
        match t.kind {
            TokenKind::Word => {
                let word = t.text.as_str();
                let lower = word.to_lowercase();
                if lower == "in" || lower == "apud" {
                    return false;
                }
                if starts_upper(word) || is_elided_particle_surname(word) {
                    if BRACKET_NOTE_WORDS.contains(&lower.as_str()) {
                        return false;
                    }
                    surname |= word.chars().filter(|c| c.is_alphabetic()).count() >= 2;
                } else if !(is_particle(word)
                    || matches!(word, "et" | "and" | "y" | "al")
                    || AUTHOR_SUFFIXES.contains(&lower.as_str())
                    || is_anon_word(word)
                    || (trailing_ex && word == "ex" && j + 1 == to))
                {
                    return false;
                }
            }
            TokenKind::Dot | TokenKind::Comma | TokenKind::Ampersand => {}
            TokenKind::Other if t.text == "-" || t.text == "'" => {}
            _ => return false,
        }
    }
    surname
}

/// Java `AuthorshipParser.containsFiliusSuffix(List<Token>, int, int)`. Scans the token
/// range for an "f"/"fil"/"filius" word — botanical filius marker. Pre-"ex" tokens are
/// skipped: a filius on an ex-author isn't a code signal because the author itself was
/// never the validating author. The "f"/"fil" token must be preceded by whitespace in the
/// input to count as a filius marker; an adjacent "L.f" (no space) is just another
/// initial.
fn contains_filius_suffix(tokens: &[Token], from: usize, to: usize) -> bool {
    let mut start = from;
    for (j, tok) in tokens.iter().enumerate().take(to).skip(from) {
        if tok.kind == TokenKind::Word && tok.text == "ex" {
            start = j + 1;
        }
    }
    for j in start..to {
        let t = &tokens[j];
        if t.kind != TokenKind::Word {
            continue;
        }
        let w = t.text.as_str();
        if !(w == "f" || w == "fil" || w == "filius") {
            continue;
        }
        // spaced ("Hook. f.") or glued to an abbreviated surname ("Hook.f.", "L.f.")
        if j > 0 && (tokens[j - 1].end < t.start || tokens[j - 1].kind == TokenKind::Dot) {
            return true;
        }
        if j == 0 {
            return true;
        }
    }
    false
}

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

    fn parse_str(input: &str) -> AuthState {
        let tokens = tokenize(input);
        parse(&tokens, 0)
    }

    fn authors(state: &AuthState) -> &[String] {
        &state.combination.authors
    }

    // ---- basic surname/initials inversion -------------------------------------------

    #[test]
    fn walker_f_flips_to_f_walker() {
        assert_eq!(authors(&parse_str("Walker F")), &["F.Walker".to_string()]);
    }

    #[test]
    fn run_on_all_caps_list_flips_every_author() {
        // The star example from the brief: three "Surname Initial(s)" pairs run
        // together with no separators at all — every all-caps token is undotted, so
        // every one flips (Quirk 5).
        assert_eq!(
            authors(&parse_str("Balsamo M Fregni E Tongiorgi MA")),
            &[
                "M.Balsamo".to_string(),
                "E.Fregni".to_string(),
                "M.A.Tongiorgi".to_string()
            ]
        );
    }

    #[test]
    fn balsamo_m_todaro_ma_variant() {
        assert_eq!(
            authors(&parse_str("Balsamo M Todaro MA")),
            &["M.Balsamo".to_string(), "M.A.Todaro".to_string()]
        );
    }

    #[test]
    fn comma_form_walker_f_also_flips() {
        assert_eq!(authors(&parse_str("Walker, F.")), &["F.Walker".to_string()]);
        assert_eq!(authors(&parse_str("Walker, F")), &["F.Walker".to_string()]);
    }

    #[test]
    fn particle_chain_keeps_h_da_c_monteiro_together() {
        // "H.da C." followed by "Monteiro": the buffer ends with a particle-only tail
        // ("da"/"C." — endsWithParticleOnly guards on the PARTICLE word, not the
        // trailing initial), so no inversion fires; it stays one chained author.
        assert_eq!(
            authors(&parse_str("H. da C. Monteiro")),
            &["H.da C.Monteiro".to_string()]
        );
    }

    #[test]
    fn isolated_zhang_f_before_separator_still_flips() {
        // Verified against NameParserImplTest's
        // "... Zhang F & Pan Z-X in Zhang, F, Pan, Z-X, ..., 2016" -> combAuthors(...,
        // "F.Zhang", "Z-X.Pan") — "F" is immediately followed by "&" (a separator, not
        // another surname) and still flips. This directly contradicts the Java inline
        // comment on this branch (see the module doc comment's Quirk 5 note); ported to
        // match the verified behaviour.
        assert_eq!(
            authors(&parse_str("Zhang F & Pan Z-X")),
            &["F.Zhang".to_string(), "Z-X.Pan".to_string()]
        );
    }

    #[test]
    fn trailing_dotted_initials_keep_their_order() {
        // #24: "Sars G.O." used to flip only "G." onto the surname and leave "O." as an
        // author of its own, which invert_all then put in front: "O.G.Sars".
        assert_eq!(authors(&parse_str("Sars G.O.")), &["G.O.Sars".to_string()]);
        assert_eq!(authors(&parse_str("Sars G. O.")), &["G.O.Sars".to_string()]);
        assert_eq!(authors(&parse_str("Sars G.O")), &["G.O.Sars".to_string()]);
        assert_eq!(
            authors(&parse_str("de Souza J.I")),
            &["J.I.de Souza".to_string()]
        );
        assert_eq!(
            authors(&parse_str("Smith A.B.C.")),
            &["A.B.C.Smith".to_string()]
        );
        assert_eq!(
            authors(&parse_str("Sars G.O. & Smith A.B.")),
            &["G.O.Sars".to_string(), "A.B.Smith".to_string()]
        );
    }

    #[test]
    fn particle_surname_after_the_initials_keeps_them() {
        // #25: initials followed by a particle surname belong to that surname, the same
        // "Forename M. Surname" shape as "Roy L. Taylor" — not to the word in front.
        assert_eq!(
            authors(&parse_str("Gosewijn W.J. van Niewenhuizen")),
            &["Gosewijn W.J.van Niewenhuizen".to_string()]
        );
        assert_eq!(
            authors(&parse_str("Dumas & Wagner Rafael M. de Souza")),
            &["Dumas".to_string(), "Wagner Rafael M.de Souza".to_string()]
        );
        assert_eq!(
            authors(&parse_str("W.J. de Wilde")),
            &["W.J.de Wilde".to_string()]
        );
        // A particle author with initials of its own after it is surname-first too, so
        // the initials in front stay with the surname in front.
        assert_eq!(
            authors(&parse_str("Zijlstra C. van Hoof R. and Cook R.")),
            &[
                "C.Zijlstra".to_string(),
                "R.van Hoof".to_string(),
                "R.Cook".to_string()
            ]
        );
    }

    #[test]
    fn particle_inside_trailing_initials_keeps_one_author() {
        // #26: "Sowerby J. de C." is James de Carle Sowerby, written like the
        // initials-first "J. de C. Sowerby" → "J.de C.Sowerby".
        assert_eq!(
            authors(&parse_str("Sowerby J. de C.")),
            &["J.de C.Sowerby".to_string()]
        );
        assert_eq!(
            authors(&parse_str("Sowerby J.de C.")),
            &["J.de C.Sowerby".to_string()]
        );
        assert_eq!(
            authors(&parse_str("Cicchino & Castro D. del C.")),
            &["Cicchino".to_string(), "D.del C.Castro".to_string()]
        );
    }

    #[test]
    fn spaced_undotted_last_initial_keeps_its_place() {
        // #27: a last initial with neither a dot nor contact with the one before it.
        assert_eq!(authors(&parse_str("Sars G. O")), &["G.O.Sars".to_string()]);
        assert_eq!(
            authors(&parse_str("Machingambi N. M, Dreyer L. L & Roets F.")),
            &[
                "N.M.Machingambi".to_string(),
                "L.L.Dreyer".to_string(),
                "F.Roets".to_string()
            ]
        );
        assert_eq!(
            authors(&parse_str("Sharma Y. P & Mehmood")),
            &["Y.P.Sharma".to_string(), "Mehmood".to_string()]
        );
        // Followed by a surname it may start the next author, so it is left alone.
        assert_eq!(
            authors(&parse_str("Balsamo M. F Tongiorgi")),
            &["M.Balsamo".to_string(), "F.Tongiorgi".to_string()]
        );
    }

    #[test]
    fn generation_after_trailing_initials_stays_behind_the_surname() {
        // A generation written after surname-first initials belongs to that surname:
        // "Sowerby G.B. II" was read as the initials "I.I." (I.I.G.B.Sowerby) and
        // "Stekhoven J.H. Jr" as a forename-initials-surname author.
        assert_eq!(
            authors(&parse_str("Sowerby G.B. II")),
            &["G.B.Sowerby II".to_string()]
        );
        assert_eq!(
            authors(&parse_str("Sowerby G. III")),
            &["G.Sowerby III".to_string()]
        );
        assert_eq!(
            authors(&parse_str("Sowerby G.B. I")),
            &["G.B.Sowerby I".to_string()]
        );
        assert_eq!(
            authors(&parse_str("Schuurmans Stekhoven J.H. Jr")),
            &["J.H.Schuurmans Stekhoven Jr".to_string()]
        );
        assert_eq!(
            authors(&parse_str("TURNBOW R. H. JR., FRANKLIN R. T.")),
            &["R.H.Turnbow Jr.".to_string(), "R.T.Franklin".to_string()]
        );
        // A dotted "I." is still an initial ("Kim I." = I. Kim).
        assert_eq!(authors(&parse_str("Kim I.")), &["I.Kim".to_string()]);
    }

    #[test]
    fn several_middle_initials_before_a_surname_keep_one_author() {
        // #24: the same split turned "Roy G.O. Taylor" into "G.Roy" + "O.Taylor", while
        // "Roy L. Taylor" with one middle initial stayed a single author.
        assert_eq!(
            authors(&parse_str("Roy G.O. Taylor")),
            &["Roy G.O.Taylor".to_string()]
        );
    }

    #[test]
    fn middle_initial_surname_follows_keeps_one_author() {
        // "Roy L. Taylor": a DOTTED middle initial followed by a capitalised
        // surname-shaped word means this is ONE author with a spelled-out forename,
        // not an inversion.
        assert_eq!(
            authors(&parse_str("Calder & Roy L. Taylor")),
            &["Calder".to_string(), "Roy L.Taylor".to_string()]
        );
    }

    // ---- hyphenated initials ----------------------------------------------------------

    #[test]
    fn dotted_hyphenated_initials_preserve_case_and_dots() {
        assert_eq!(
            authors(&parse_str("Y.-j. Wang")),
            &["Y.-j.Wang".to_string()]
        );
        assert_eq!(
            authors(&parse_str("C.-K. Yang")),
            &["C.-K.Yang".to_string()]
        );
    }

    #[test]
    fn comma_inverted_hyphenated_initials() {
        assert_eq!(
            authors(&parse_str("Wang, Y.-j.")),
            &["Y.-j.Wang".to_string()]
        );
        assert_eq!(
            authors(&parse_str("Yang, C.-K.")),
            &["C.-K.Yang".to_string()]
        );
        assert_eq!(
            authors(&parse_str("Wang, Y.-j. & Liu, Z.-q.")),
            &["Y.-j.Wang".to_string(), "Z.-q.Liu".to_string()]
        );
    }

    // ---- generational suffix ------------------------------------------------------------

    #[test]
    fn generational_suffix_stays_upper_and_behind_surname() {
        assert_eq!(
            authors(&parse_str("Loeblich III")),
            &["Loeblich III".to_string()]
        );
    }

    #[test]
    fn generational_suffix_is_matched_case_insensitively_but_rendered_upper() {
        assert_eq!(
            authors(&parse_str("Loeblich Iii")),
            &["Loeblich III".to_string()]
        );
    }

    #[test]
    fn generational_suffix_with_year_and_basionym() {
        let s = parse_str("(Paulsen) Loeblich III, 1969");
        assert_eq!(s.basionym.authors, vec!["Paulsen".to_string()]);
        assert_eq!(s.combination.authors, vec!["Loeblich III".to_string()]);
        assert_eq!(s.combination.year, Some("1969".to_string()));
        assert!(s.basionym_present);
    }

    #[test]
    fn bare_initials_i_v_x_are_not_generational_suffixes() {
        // Single-letter I/V/X are genuine author initials, not generation-suffix Roman
        // numerals — GENERATIONAL_SUFFIXES deliberately excludes them, so these still go
        // through the ordinary (undotted, run-on) flip instead.
        assert_eq!(authors(&parse_str("Smith V")), &["V.Smith".to_string()]);
    }

    // ---- apostrophes ------------------------------------------------------------------

    #[test]
    fn dot_then_apostrophe_particle_glues_with_no_gap() {
        assert_eq!(
            authors(&parse_str("L.'t Mannetje")),
            &["L.'t Mannetje".to_string()]
        );
    }

    #[test]
    fn glued_apostrophe_inside_a_word_is_a_single_token_already() {
        assert_eq!(authors(&parse_str("M'Coy")), &["M'Coy".to_string()]);
        assert_eq!(
            authors(&parse_str("Abdallah & Sa'ad")),
            &["Abdallah".to_string(), "Sa'ad".to_string()]
        );
    }

    #[test]
    fn leading_apostrophe_particle_with_no_preceding_gap() {
        assert_eq!(authors(&parse_str("'t Hart")), &["'t Hart".to_string()]);
    }

    #[test]
    fn apostrophe_particle_preceded_by_a_space_gets_a_space_back() {
        assert_eq!(
            authors(&parse_str("Henk 't Hart")),
            &["Henk 't Hart".to_string()]
        );
    }

    #[test]
    fn question_mark_transcription_artefact_glues_silently() {
        assert_eq!(
            authors(&parse_str("Istv?nffi, 1898")),
            &["Istvnffi".to_string()]
        );
        assert_eq!(
            parse_str("Istv?nffi, 1898").combination.year,
            Some("1898".to_string())
        );
    }

    // ---- basionym / phase A ------------------------------------------------------------

    #[test]
    fn basionym_and_combination_authors_with_year() {
        let s = parse_str("(L.) L., 1753");
        assert_eq!(s.basionym.authors, vec!["L.".to_string()]);
        assert_eq!(s.combination.authors, vec!["L.".to_string()]);
        assert_eq!(s.combination.year, Some("1753".to_string()));
        assert!(s.basionym_present);
    }

    #[test]
    fn basionym_only_no_trailing_combination() {
        let s = parse_str("(Wang & Liu, 1996)");
        assert_eq!(
            s.basionym.authors,
            vec!["Wang".to_string(), "Liu".to_string()]
        );
        assert_eq!(s.basionym.year, Some("1996".to_string()));
        assert!(s.basionym_present);
        assert!(s.combination.authors.is_empty());
        assert_eq!(s.unparsed_from, -1);
    }

    #[test]
    fn basionym_bracketed_imprint_year() {
        let s = parse_str("(Peters, 1876 [1877])");
        assert_eq!(s.basionym.authors, vec!["Peters".to_string()]);
        assert_eq!(s.basionym.year, Some("1876".to_string()));
        assert_eq!(s.basionym.imprint_year, Some("1877".to_string()));
    }

    #[test]
    fn lowercase_only_parens_are_not_a_basionym_and_are_parked_unparsed() {
        // hasUpperWord guard: "(ilic)" has no upper-case WORD inside, so it is NOT read
        // as a basionym — it is captured as unparsed and skipped, and parsing continues
        // with the trailing "L." as the combination.
        let s = parse_str("(ilic) L.");
        assert!(!s.basionym_present);
        assert!(s.basionym.authors.is_empty());
        assert_eq!(s.unparsed_from, 0);
        assert_eq!(s.unparsed_text, Some("(ilic)".to_string()));
        assert_eq!(s.combination.authors, vec!["L.".to_string()]);
    }

    #[test]
    fn an_elided_particle_surname_is_a_basionym_author() {
        // `d'Orbigny` starts lower-case but is a surname, not the malformed `(ilic)` the
        // hasUpperWord guard exists for. Rejecting it parked (or, on a separately supplied
        // authorship, silently dropped) ~15k d'Orbigny / d'Archiac / d'Urv. basionyms.
        let s = parse_str("(d'Orbigny, 1826)");
        assert!(s.basionym_present);
        assert_eq!(s.basionym.authors, vec!["d'Orbigny".to_string()]);
        assert_eq!(s.basionym.year, Some("1826".to_string()));
        assert_eq!(s.unparsed_from, -1);

        let s = parse_str("(d'Urv.) Mill.");
        assert_eq!(s.basionym.authors, vec!["d'Urv.".to_string()]);
        assert_eq!(s.combination.authors, vec!["Mill.".to_string()]);
    }

    #[test]
    fn basionym_colon_sanctioning_is_kept_on_the_basionym() {
        // "(Wulfen : Fr.)": the colon inside the basionym parens separates the original author
        // from the basionym's sanctioning author. Java dropped it.
        let s = parse_str("(Wulfen : Fr.) Schum.");
        assert_eq!(s.basionym.authors, vec!["Wulfen".to_string()]);
        assert_eq!(s.basionym.sanctioning_author.as_deref(), Some("Fr."));
        assert_eq!(s.combination.authors, vec!["Schum.".to_string()]);
        assert_eq!(s.combination.sanctioning_author, None);
    }

    // ---- sanctioning author (phase B, top-level colon) --------------------------------

    #[test]
    fn top_level_colon_splits_off_sanctioning_author() {
        let s = parse_str("L. : Fr.");
        assert_eq!(s.combination.authors, vec!["L.".to_string()]);
        assert_eq!(s.combination.sanctioning_author, Some("Fr.".to_string()));
    }

    #[test]
    fn a_basionym_keeps_only_fries_or_persoon_after_its_colon() {
        // without the abbreviation's dot too
        let s = parse_str("(Pers. : Fr)");
        assert_eq!(s.basionym.sanctioning_author.as_deref(), Some("Fr"));
        // a colon before anyone else is no sanctioning
        let s = parse_str("(Baba 1949: Burn 1962)");
        assert_eq!(s.basionym.authors, vec!["Baba".to_string()]);
        assert_eq!(s.basionym.sanctioning_author, None);
    }

    #[test]
    fn sanctioning_authors_are_fries_and_persoon() {
        for a in ["Fr.", "Fr", "Fries", "Pers.", "Pers", "Persoon"] {
            assert!(is_sanctioning_author(a), "{a}");
        }
        for a in ["Fritsch", "Persson", "2ller", "Burn"] {
            assert!(!is_sanctioning_author(a), "{a}");
        }
    }

    #[test]
    fn pers_colon_fr_sanctioning() {
        let s = parse_str("Pers. : Fr.");
        assert_eq!(s.combination.authors, vec!["Pers.".to_string()]);
        assert_eq!(s.combination.sanctioning_author, Some("Fr.".to_string()));
    }

    // ---- years --------------------------------------------------------------------------

    #[test]
    fn plain_year_only() {
        let s = parse_str("1771");
        assert_eq!(s.combination.year, Some("1771".to_string()));
        assert!(s.combination.authors.is_empty());
    }

    #[test]
    fn second_plain_year_becomes_imprint_year() {
        // No brackets at all: "Ehrenberg, 1870, 1869" — second plain year is the
        // imprint year (first-wins for the main year).
        let s = parse_str("Ehrenberg, 1870, 1869");
        assert_eq!(s.combination.authors, vec!["Ehrenberg".to_string()]);
        assert_eq!(s.combination.year, Some("1870".to_string()));
        assert_eq!(s.combination.imprint_year, Some("1869".to_string()));
    }

    #[test]
    fn unquoted_bracketed_year_is_imprint_year() {
        let s = parse_str("Storr, 1970 [1969]");
        assert_eq!(s.combination.authors, vec!["Storr".to_string()]);
        assert_eq!(s.combination.year, Some("1970".to_string()));
        assert_eq!(s.combination.imprint_year, Some("1969".to_string()));
    }

    #[test]
    fn a_bracketed_year_on_its_own_is_the_year() {
        // the actual year, established from external evidence
        let s = parse_str("Fruhstorfer, [1912]");
        assert_eq!(s.combination.authors, vec!["Fruhstorfer".to_string()]);
        assert_eq!(s.combination.year, Some("1912".to_string()));
        assert_eq!(s.combination.imprint_year, None);
    }

    #[test]
    fn year_range_with_hyphen_keeps_first_year_and_sets_flag() {
        let s = parse_str("Smith, 1845-1847");
        assert_eq!(s.combination.year, Some("1845".to_string()));
        assert!(s.year_range);
    }

    #[test]
    fn year_range_with_short_second_year_and_slash() {
        let s = parse_str("Smith, 1987/92");
        assert_eq!(s.combination.year, Some("1987".to_string()));
        assert!(s.year_range);
    }

    #[test]
    fn non_range_year_does_not_set_year_range_flag() {
        let s = parse_str("Smith, 1987");
        assert_eq!(s.combination.year, Some("1987".to_string()));
        assert!(!s.year_range);
    }

    #[test]
    fn uncertain_trailing_question_mark_folds_into_year() {
        let s = parse_str("Smith, 198?");
        assert_eq!(s.combination.year, Some("198?".to_string()));
    }

    #[test]
    fn trailing_year_disambiguator_letter_is_dropped() {
        let s = parse_str("Smith, 1935h");
        assert_eq!(s.combination.year, Some("1935".to_string()));
        assert_eq!(s.combination.authors, vec!["Smith".to_string()]);
    }

    #[test]
    fn short_number_that_is_not_year_shaped_is_silently_dropped() {
        // A 1-2 digit number doesn't match the year branch (3-4 digits required) and
        // isn't any other token kind either, so it falls through to the catch-all and
        // is silently dropped rather than glued into the author text.
        let s = parse_str("Smith 12");
        assert_eq!(s.combination.authors, vec!["Smith".to_string()]);
        assert_eq!(s.combination.year, None);
    }

    // ---- ex-authors ---------------------------------------------------------------------

    #[test]
    fn ex_author_split() {
        let s = parse_str("Wedd. ex Sch. Bip.");
        assert_eq!(s.combination.ex_authors, vec!["Wedd.".to_string()]);
        assert_eq!(s.combination.authors, vec!["Sch.Bip.".to_string()]);
    }

    #[test]
    fn hort_ex_author_already_normalised_by_stripandstash() {
        // NB: the "Hort."/"hortus(a)" -> lower-case "hort." normalisation is
        // StripAndStash's job (a separate, already-ported stage) — by the time
        // AuthorshipParser sees tokens the word is already "hort.". This test exercises
        // AuthorshipParser's own ex-author handling directly on that post-normalisation
        // form, not the raw "Hort. ex Vilmorin" input.
        let s = parse_str("hort. ex Vilmorin");
        assert_eq!(s.combination.ex_authors, vec!["hort.".to_string()]);
        assert_eq!(s.combination.authors, vec!["Vilmorin".to_string()]);
    }

    // ---- suffixes (AUTHOR_SUFFIXES dual case-discipline) --------------------------------

    #[test]
    fn dot_glued_filius_chains_case_sensitively_no_separator() {
        assert_eq!(authors(&parse_str("L.f")), &["L.f".to_string()]);
    }

    #[test]
    fn spaced_filius_chains_with_a_separating_space() {
        assert_eq!(authors(&parse_str("Hooker f.")), &["Hooker f.".to_string()]);
    }

    #[test]
    fn bis_suffix_chains_onto_the_surname() {
        assert_eq!(
            authors(&parse_str("Yong Wang bis")),
            &["Yong Wang bis".to_string()]
        );
        assert_eq!(
            authors(&parse_str("A.Murray bis")),
            &["A.Murray bis".to_string()]
        );
    }

    #[test]
    fn lone_suffix_after_comma_attaches_to_the_previous_completed_author() {
        // Constructed to exercise the case-insensitive standalone-after-separator
        // branch specifically (Quirk 2): after the COMMA flush, `cur` is empty and
        // "jr" arrives as a fresh top-level token (not chained from "Smith" within the
        // same pass), so it hits the `cur.is_empty() && !authors.is_empty()` arm which
        // pops the last author, appends a trailing dot if missing, then glues "jr" —
        // this is a structurally distinct code path from the chain sub-loop exercised
        // by `bis_suffix_chains_onto_the_surname` above (verified by tracing the Java
        // source; no directly analogous assertion exists in `NameParserImplTest` or the
        // corpus for this exact input).
        let s = parse_str("Smith, jr");
        assert_eq!(s.combination.authors, vec!["Smith.jr".to_string()]);
    }

    #[test]
    fn author_suffixes_case_insensitive_lone_branch_accepts_mixed_case_too() {
        // "jR" (lower-case first letter, so it does NOT hit the surname/upper-case
        // branch first — that branch would otherwise intercept anything starting
        // upper-case, e.g. a fully-capitalised "JR", before the lone-suffix branch ever
        // gets a look) still matches AUTHOR_SUFFIXES via the case-insensitive
        // `.to_lowercase()` comparison, and is glued on using its ORIGINAL casing.
        assert_eq!(authors(&parse_str("Smith, jR")), &["Smith.jR".to_string()]);
    }

    // ---- filius flag (has_filius) -------------------------------------------------------

    #[test]
    fn spaced_f_sets_has_filius_flag() {
        assert!(parse_str("Hooker f.").has_filius);
    }

    #[test]
    fn glued_f_after_an_abbreviation_sets_has_filius_flag() {
        // "Burm.f." is as much Burman filius as "Burm. f."; Java needed the space
        assert!(parse_str("Burm.f.").has_filius);
    }

    #[test]
    fn filius_before_ex_does_not_count() {
        // "Baker f. ex Rose": the filius marker is on the EX author, which was never
        // the validating author — containsFiliusSuffix skips everything before the
        // LAST "ex" token.
        assert!(!parse_str("Baker f. ex Rose").has_filius);
    }

    // ---- semicolon-separated citation list ----------------------------------------------

    #[test]
    fn semicolon_separated_citation_list() {
        assert_eq!(
            authors(&parse_str("Choi,J.H.; Im,W.T.; Yoo,J.S.")),
            &[
                "J.H.Choi".to_string(),
                "W.T.Im".to_string(),
                "J.S.Yoo".to_string()
            ]
        );
    }

    // ---- slash between authors -----------------------------------------------------------

    #[test]
    fn slash_between_two_authors_stays_glued() {
        assert_eq!(
            authors(&parse_str("Smith/Jones")),
            &["Smith/Jones".to_string()]
        );
    }

    // ---- malformed / catch-all ------------------------------------------------------------

    #[test]
    fn stray_unmatched_open_paren_is_silently_skipped() {
        let s = parse_str("Wedd. ex Sch. Bip. (");
        assert_eq!(s.combination.ex_authors, vec!["Wedd.".to_string()]);
        assert_eq!(s.combination.authors, vec!["Sch.Bip.".to_string()]);
    }

    #[test]
    fn diacritic_surname_chains_through_dot() {
        assert_eq!(authors(&parse_str("Müll.Arg.")), &["Müll.Arg.".to_string()]);
    }

    #[test]
    fn all_caps_long_surname_is_title_cased() {
        let s = parse_str("FISCHER 1885");
        assert_eq!(s.combination.authors, vec!["Fischer".to_string()]);
        assert_eq!(s.combination.year, Some("1885".to_string()));
    }

    #[test]
    fn short_all_caps_word_is_kept_as_initials_not_title_cased() {
        // normaliseAuthorCase only title-cases ALL-CAPS words of length >= 4; "MA" (2
        // chars) stays untouched, matching its role as initials rather than a shouted
        // surname.
        assert_eq!(
            authors(&parse_str("Balsamo M Todaro MA")),
            &["M.Balsamo".to_string(), "M.A.Todaro".to_string()]
        );
    }

    // ---- particles -----------------------------------------------------------------------

    #[test]
    fn van_der_particle_chain_stays_lower_case() {
        assert_eq!(
            authors(&parse_str("van der Wulp")),
            &["van der Wulp".to_string()]
        );
    }

    #[test]
    fn capitalised_van_particle_chain() {
        assert_eq!(
            authors(&parse_str("Van de Putte")),
            &["Van de Putte".to_string()]
        );
    }

    // ---- multi-author separators ----------------------------------------------------------

    #[test]
    fn ampersand_and_et_and_y_separators() {
        assert_eq!(
            authors(&parse_str("Xing, Yan & Yin")),
            &["Xing".to_string(), "Yan".to_string(), "Yin".to_string()]
        );
        // a y between two surnames is one person; it separates where the string shows two
        assert_eq!(
            authors(&parse_str("Martinez y Saez")),
            &["Martinez y Saez".to_string()]
        );
        assert_eq!(
            authors(&parse_str("Ruiz-Carranza y Lynch")),
            &["Ruiz-Carranza".to_string(), "Lynch".to_string()]
        );
        // an & before an earlier year belongs to another team: this y closes a list
        assert_eq!(
            authors(&parse_str("Isbrücker & Nico, 1992 Nijssen, Ortega y Nico")),
            &["Isbrücker", "Nico", "Nijssen", "Ortega", "Nico"].map(String::from)
        );
    }

    #[test]
    fn literal_or_is_not_a_recognised_separator() {
        // "or" is not "and"/"et"/"y"/"&" — it glues into a single literal author string.
        assert_eq!(
            authors(&parse_str("Jarocki or Schinz")),
            &["Jarocki or Schinz".to_string()]
        );
    }

    // ---- edge cases / dead-code confirmation ----------------------------------------------

    #[test]
    fn empty_span_returns_a_fully_default_state_without_panicking() {
        let tokens = tokenize("Aus bus");
        // `from == tokens.len()`: both phase-A and phase-B guards are false, so phase C's
        // guard is also false on entry (see the module doc comment) — nothing panics and
        // nothing is recorded as unparsed.
        let s = parse(&tokens, tokens.len());
        assert!(s.combination.authors.is_empty());
        assert_eq!(s.unparsed_from, -1);
        assert_eq!(s.unparsed_text, None);
    }

    #[test]
    fn phase_c_never_fires_a_regression_pin() {
        // Phase B unconditionally sets `i = n` whenever it runs, and it runs whenever
        // `i < n` on entry — so by construction `i == n` on every path through `parse`,
        // meaning Phase C's own `if i < n` can never be true. This is a regression pin
        // for that observation across a handful of shapes that might plausibly have
        // been thought to reach it (a trailing unmatched paren, a basionym-only input, a
        // combination with a sanctioning author).
        // NB: "(ilic) L." is deliberately NOT in this list — it sets `unparsed_from`
        // too, but via Phase A's own malformed-basionym guard (`hasUpperWord` failing),
        // a completely different branch from Phase C; see
        // `lowercase_only_parens_are_not_a_basionym_and_are_parked_unparsed` above.
        for input in ["Wedd. ex Sch. Bip. (", "(Wang & Liu, 1996)", "L. : Fr."] {
            let s = parse_str(input);
            assert_eq!(
                s.unparsed_from, -1,
                "input {input:?} unexpectedly hit phase C"
            );
        }
    }
}