gbif-name-parser 0.2.2

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
// SPDX-License-Identifier: Apache-2.0
//! Java `org.gbif.nameparser.pipeline.Preflight` — the 33-pattern early gate that rejects
//! viruses, hybrid formulas, placeholders, OTU codes and other non-scientific-name input
//! before the rest of the pipeline tokenises it.

use std::sync::LazyLock;

use regex::Regex;

use crate::model::{NameType, NomCode, ParseError, Rank, State};
use crate::pipeline::ParseContext;
use crate::unicode::java_trim;
use crate::viral::is_viral;

// Per-pattern flag rule applied throughout this file (see the Task 5 brief/report for the
// full rationale, worked out once here rather than repeated per pattern):
//
//   * Java `Pattern.UNICODE_CHARACTER_CLASS` patterns keep the `regex` crate's DEFAULT
//     Unicode-aware shorthand classes (`\s`/`\d`/`\w`/`\b` all Unicode already) — no
//     `(?-u:…)` scoping. `\p{Lu}`/`\p{Ll}`/`\p{L}` are Unicode in both engines regardless.
//   * Java `CASE_INSENSITIVE`-or-no-flags patterns become `(?i)` (only where Java actually
//     set the flag/inline modifier) with every `\s`/`\d`/`\w`/`\b` ASCII-scoped via
//     `(?-u:…)`, since Java did NOT set UNICODE_CHARACTER_CLASS for these and so its
//     shorthand classes are ASCII-only. `\p{Lu}`/`\p{Ll}`/`\p{L}` (where present) are left
//     untouched in the ambient Unicode scope.
//   * Where a pattern has no `\p{…}` class at all, the WHOLE alternation is wrapped in one
//     `(?-u:…)` group rather than scoping each shorthand class individually — flag scoping
//     applies to the entire AST subtree under the group (including nested character
//     classes like `[\s_-]`), so this is exactly equivalent to per-atom scoping, just
//     shorter and harder to typo across a long alternation. This is NEVER done for a
//     pattern containing an unescaped wildcard `.` (disabling `u` turns `.` from "any
//     Unicode scalar value" into "any byte", a real semantic change — regex-syntax rejects
//     `(?-u:…)` outright when it contains `\p{…}`/`\W`, but silently changes `.`'s meaning
//     instead of erroring) — those patterns (DELETE_MARKER, NON_HOMONYM, NN_PLACEHOLDER)
//     scope only the individual `\s` atoms, leaving every `.` outside any `(?-u:…)` group so
//     it stays the default Unicode "any scalar value except newline".
//   * Java's possessive quantifiers (`++`, `*+`) appear only in `ZOOLOGICAL_BINOMIAL`;
//     dropped to plain greedy (`+`, `*`) per this port's established convention (see
//     `regexes.rs`'s module doc) — the `regex` crate is a linear-time automaton with no
//     backtracking, so possessive-vs-greedy cannot change whether an overall match exists.
//   * Every one of the 33 patterns below is expressible in the linear `regex` crate; NONE
//     needs `fancy_regex`. Exactly one, `PURE_ALPHANUM`, is restructured (its lookahead
//     `(?=.*\d)` dropped) rather than ported verbatim — see that pattern's own doc comment.

// ---------- VIRUS ----------
// Match anything ending in -virus / -viruses / -viroid / -viroids / -phage(s) /
// -satellite, plus standalone viral keywords. Word characters can precede the
// suffix (so "Sapovirus", "papillomavirus", "C2-like viruses" all match).
// Divergence from Java: `phages?` is anchored to a word end or a glued `_`/digit (`phage_Kente`,
// `phage1_…`), plus a word-initial `phage` followed by a mixed-case strain code (`phageBT1`) or
// `phagemid`. Java's unanchored `phages?` also fired inside words — Sphagesauridae,
// Sphagebranchus, `Treponema phagedenis` — rejecting ~460 real CLB names as viruses.
// Java: `Pattern.CASE_INSENSITIVE`. No `\p{…}`, so the whole alternation is `(?-u:…)`-wrapped.
static VIRUS: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(?-u:(?:viru(?:s|ses)\b|viroid(?:s)?\b|phages?(?:\b|[_\d])|\bphage(?:mids?\b|(?-i:[a-z]*[A-Z0-9_]))|virion(?:s)?\b|\bsatellite\b|(?:alpha|beta|delta|circular)[\s_-]*satellites?\b|\b(?:Clecru|Milvet|Subclov)satellite\b|bacteriophages?\b|\b[MSC]?NPV\b|\bGV\b|\bICTV\b|(?:fusion\s+)?vector\b|\bprions?\b|\bparticles?\b|\breplicons?\b|\bRNA\b))",
    )
    .unwrap()
});

// "Genus species [(Subgenus)] [Author], YYYY" — zoological author-year pattern.
// Allows VIRUS-matching epithets (vector, virus, phage) to be parsed as real species when
// an explicit Title-cased author + 4-digit year follows. Java: `Pattern.UNICODE_CHARACTER_CLASS`,
// every quantifier possessive (ReDoS-hardened — see Java's own comment); possessive → greedy
// per this port's convention (linear-time automaton, no backtracking to guard against).
static ZOOLOGICAL_BINOMIAL: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^\p{Lu}\p{Ll}+\s+(?:\(\p{Lu}\p{Ll}+\)\s+)?\p{Ll}[\p{Ll}\-]*\s+(?:\([^)]*\)\s*)?\p{Lu}[\p{Lu}.,&'\-\s]*\p{Ll}[\p{L}.,&'\-\s]*\b(1[6-9]\d\d|20\d\d)\b",
    )
    .unwrap()
});

/// Java: `Pattern.UNICODE_CHARACTER_CLASS`, no scoping.
static CLEAN_BINOMIAL: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\p{Lu}\p{Ll}+(?:\s+\(\p{Lu}\p{Ll}+\))?\s+\p{Ll}[\p{Ll}\d\-]*$").unwrap()
});
/// Java: `Pattern.UNICODE_CHARACTER_CLASS`, no scoping.
static CLEAN_MONOMIAL: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\p{Lu}[\p{Ll}\-]+$").unwrap());

/// Java: `Pattern.CASE_INSENSITIVE`. No `\s`/`\d`/`\w`/`\b` at all, so nothing to ASCII-scope.
static SOFT_WORD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(?:vector|prions?|particles?|replicons?|rna)$").unwrap());
// A soft virus-word appearing as the leading Title-cased GENUS token — "Prion vittatus",
// "Prion Lacépède, 1799". These are real animal genera (Prion = petrels), not viruses. The
// reject only fires on them when a genuinely viral token (HARD_VIRUS below) is also present.
// Case-sensitive and anchored so a lowercase epithet ("Euragallia prion") or a viral genus with
// a suffix ("Rnavirus …", where "Rna" is not followed by a word boundary) never matches.
// Java: no flags at all (deliberately case-SENSITIVE — no `(?i)`). Has `\b`, no `\p{…}` → whole
// pattern (after `^`) is `(?-u:…)`-wrapped.
static SOFT_GENUS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?-u:(?:Vector|Prions?|Particles?|Replicons?|Rna)\b)").unwrap());
// The genuinely viral triggers (VIRUS minus the ambiguous English SOFT_WORDs). When only a soft
// word matched, there is no real viral signal and a leading soft-genus is let through to parse.
// Java: `Pattern.CASE_INSENSITIVE`. Same treatment as VIRUS.
static HARD_VIRUS: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(?-u:(?:viru(?:s|ses)\b|viroid(?:s)?\b|phages?(?:\b|[_\d])|\bphage(?:mids?\b|(?-i:[a-z]*[A-Z0-9_]))|virion(?:s)?\b|\bsatellite\b|(?:alpha|beta|delta|circular)[\s_-]*satellites?\b|\b(?:Clecru|Milvet|Subclov)satellite\b|bacteriophages?\b|\b[MSC]?NPV\b|\bGV\b|\bICTV\b))",
    )
    .unwrap()
});
/// Java: `Pattern.CASE_INSENSITIVE`. No `\s`/`\d`/`\w`/`\b`, nothing to ASCII-scope.
static HARD_WORD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(?:virus|viroid|phages?|virion|satellite)$").unwrap());
/// Java: `Pattern.UNICODE_CHARACTER_CLASS`, no scoping.
static AUTH_ZOO: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\(?\p{Lu}\p{Ll}{2,}.*\b(?:1[6-9]\d\d|20\d\d)\b").unwrap());

// ---------- HYBRID FORMULA ----------
// Hybrid-formula detection is done structurally in looks_like_hybrid_formula() below
// rather than with a single regex — it needs to inspect the spans on either side of
// the cross to avoid false positives on single-genus notho markers.

// ---------- NO_NAME ----------
// Pure alphanumeric codes / OTU identifiers.
/// Java: `Pattern.CASE_INSENSITIVE`. No `\s`/`\d`/`\w`/`\b` (`[A-Z0-9]`/`[:_-]` are explicit
/// ranges, not shorthand classes), nothing to ASCII-scope.
static OTU_BOLD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)^BOLD[:_-][A-Z0-9]+$").unwrap());
/// Java: `Pattern.CASE_INSENSITIVE`. Has `\d` → scoped.
static OTU_SH: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)^SH(?-u:\d{6,})\.[0-9A-Z.]+$").unwrap());
/// Java: `Pattern.CASE_INSENSITIVE`. Has `\d` (in a class) → scoped.
static OTU_GTDB_UBA: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)^(?:UBA|GTDB|GCA|GCF)(?-u:[\d_-]+)$").unwrap());
/// 5.0.0 (no Java counterpart — these were plain OTHER in 4.2.0): further anchorless molecular
/// operational-unit schemes — OTU/ASV/ESV/zOTU (amplicon/exact sequence variants) and MAG
/// (metagenome-assembled genome). Whole string with a required trailing number, so it cannot sweep
/// up a genus that merely starts with the letters (e.g. "Uba fallai" — a real beetle genus).
static OTU_MOTU: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)^(?:z?OTU|ASV|ESV|MAG)(?-u:[ _-]?\d+)$").unwrap());
/// 5.0.0 (no Java counterpart): a STANDALONE culture-collection accession — one of the curated
/// [`super::culture_collections`] ALL-CAPS acronyms then an accession body ("DSM 10",
/// "ATCC BAA-123", "CBS 123.89", "ATCC-11775", "LMG 6923T"). Case-sensitive on the acronym
/// (conservative). The ANCHORED case (an accession trailing a determined name) is captured as a
/// phrase in `stripandstash` instead, not classified here.
static CULTURE_ACCESSION_STANDALONE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"^{}(?-u:[ :=_-]*(?:[A-Z]{{1,4}}-)?\d[\dA-Za-z.:-]*)$",
        super::culture_collections::acronym_alternation()
    ))
    .unwrap()
});
// Anything starting with a digit, or containing only mixed letters+digits (no Latin epithet
// shape). Java: `Pattern.UNICODE_CHARACTER_CLASS`, `^(?=.*\d)[\p{L}\d_.\-]+$` — a lookahead
// requiring a digit somewhere. RESTRUCTURED: the lookahead is dropped here (the `regex` crate
// has no lookaround at all) — this is sound rather than a behavioural gap because the ONLY
// call site (below, in `run`) already ANDs the match with a separate `has_digit(s)` check:
// Java's `PURE_ALPHANUM.matcher(s).matches() && hasDigit(s)` already has the digit requirement
// twice over (once via the lookahead, once via the explicit call), so
// `restructured_matches(s) && has_digit(s)` is exactly equivalent to Java's
// `PURE_ALPHANUM.matches(s) && hasDigit(s)` at that one call site.
static PURE_ALPHANUM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[\p{L}\d_.\-]+$").unwrap());
// Patterns like "Basal_Cryptophyceae-1" — single underscore-separated parts with a digit
// suffix. Java: `Pattern.UNICODE_CHARACTER_CLASS`, no scoping.
// NB (dead-code finding, not fixed — faithful port keeps it): every character PR2_LIKE's
// regex can match ({L, `_`, `-`, digit}) is already inside PURE_ALPHANUM's broader alphabet
// ({L, digit, `_`, `.`, `-`}), and both call sites require `hasDigit(s)`; the only extra
// requirement PR2_LIKE's caller adds is `s.contains("-")`. So whenever PR2_LIKE's full
// call-site condition would hold, PURE_ALPHANUM's (checked first, above) already does too —
// this appears to make PR2_LIKE unreachable in the ORIGINAL JAVA source itself (independent
// of the restructuring above), not something this port introduced. Ported verbatim anyway,
// dead code and all, since removing it would be an unfaithful "fix" of Preflight.java.
static PR2_LIKE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[\p{L}]+_[\p{L}\-]+(?:-\d+)?$").unwrap());
/// Java: `Pattern.CASE_INSENSITIVE`. Has `\s` (x3), no `\p{…}`, no wildcard `.` (only escaped
/// `\.`) → whole pattern (after `^`) is `(?-u:…)`-wrapped.
static GEN_NOV: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)^(?-u:Gen\.?\s*nov\.?(?:\s+(?:sp|species)\.?\s*nov\.?)?\s*)$").unwrap()
});
// GTDB/SILVA specimen codes: anything ending with "sp" + 8+ digits after whitespace.
/// Java: `Pattern.CASE_INSENSITIVE`. Has `\b`, `\d`, no `\p{…}` → whole pattern wrapped
/// (keeping the trailing `$` outside the wrap since anchors aren't `u`-sensitive either way).
static OTU_SPECIMEN_SUFFIX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(?-u:\bsp\d{8,})$").unwrap());

// ---------- PLACEHOLDER ----------
/// Java: `Pattern.CASE_INSENSITIVE`. Has `\s`/`\b` (many), no `\p{…}`, no wildcard `.` (only
/// escaped `\.`) → whole alternation `(?-u:…)`-wrapped.
static PLACEHOLDER_KEYWORDS: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(?-u:(?:\(delete\)|\b(?:incertae[\s_]*sedis|inc\.\s*sed\.?|incertaesedis|not\s+assigned|unassigned|unknown|unaccepted|unidentified|undetermined|undet|indet\.?|indeterminate|uncultured|undescribed(?:\s+(?:species|genus|family))?|temp\s+dummy(?:\s+name)?)\b))",
    )
    .unwrap()
});
// One to four lowercase words ending in a generic organism word. Group 1 = the qualifier words
// before it (`marine `, `delta `), group 2 = the remainder after it.
static ORGANISM_LABEL: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^((?:[a-z][a-z-]* ){0,4}?)[a-z]*(?:bacteri(?:um|a)|archae(?:on|a)|actinomycetes?|symbionts?|fung(?:us|al|i)|yeasts?|algae?|protists?|microorganisms?)(?: (.+))?$",
    )
    .unwrap()
});
// The authorship of a real epithet whose genus is missing (`fungi Meigen, 1830`).
static AUTHOR_YEAR: LazyLock<Regex> = LazyLock::new(|| {
    // a lowercase-bearing surname and a plausible year — `DSM 6505`, `RCC 1888` are accessions
    Regex::new(
        r"^\(?\p{Lu}\p{Ll}[\p{L}'.\-]*(?:(?:,? | & | et )\p{Lu}[\p{L}'.\-]+)*,? (?:1[789]\d\d|20[0-2]\d)\)?$",
    )
    .unwrap()
});
// What may precede the code: `enrichment culture`, then a `clone`/`strain`/`str.`/`isolate`/`sp.`.
static CODE_LEAD: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(?:enrichment culture )?(?:(?:clone|strain|str\.?|isolate|sp\.?) )?").unwrap()
});

/// [`ORGANISM_LABEL`]: `Some(Identifier)` when a strain/clone code follows the label, `Some(Other)`
/// for any other label, `None` when it is no such label — or the label word is a real epithet
/// with an authorship, its genus missing (`fungi Meigen, 1830`), left to the missing-genus path.
fn classify_organism_label(s: &str) -> Option<NameType> {
    let caps = ORGANISM_LABEL.captures(s)?;
    let Some(rest) = caps.get(2).map(|m| m.as_str()) else {
        return Some(NameType::Other);
    };
    if caps[1].is_empty() && AUTHOR_YEAR.is_match(rest) {
        return None;
    }
    let code = &rest[CODE_LEAD.find(rest).map_or(0, |m| m.end())..];
    let quoted = (code.starts_with('\'') && code.ends_with('\''))
        || (code.starts_with('"') && code.ends_with('"'));
    let tokens: Vec<&str> = code.split_whitespace().collect();
    let codeish = |t: &str| {
        t.chars().any(|c| c.is_ascii_digit()) || t.chars().filter(|c| c.is_uppercase()).count() >= 2
    };
    let is_code = quoted
        || tokens.len() == 1
        || (tokens.len() <= 3
            && (tokens
                .last()
                .is_some_and(|t| t.chars().any(|c| c.is_ascii_digit()))
                || tokens.iter().all(|t| codeish(t))));
    Some(if is_code {
        NameType::Identifier
    } else {
        NameType::Other
    })
}

/// The `unclassified` placeholder word, kept out of [`PLACEHOLDER_KEYWORDS`] so it is tested after
/// the virus gate.
static UNCLASSIFIED: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(?-u:\bunclassified\b)").unwrap());
/// Java: `Pattern.CASE_INSENSITIVE`. Has `\s` (in `[-\s]`), no `\p{…}` → whole pattern
/// (after `^`) wrapped.
static PLACEHOLDER_PREFIX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)^(?-u:(?:Unident|Undescribed|IncertaeSedis|Undet)(?:[-\s]|$))").unwrap()
});
/// Java: no flags. Has `\s` AND `\p{Ll}` → only `\s` is scoped (matches the brief's own
/// worked example verbatim: `^\?\s+\p{Ll}` → `^\?(?-u:\s+)\p{Ll}`).
static QUESTION_PREFIX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\?(?-u:\s+)\p{Ll}").unwrap());
// Two or more leading question marks ("?? not a name", "? ? foo"). A single leading "?" is a
// valid missing-genus placeholder ("? gryphoidis"), but a run of them is junk — the tokeniser
// would otherwise emit one "?" placeholder per mark and coerce the input into a nonsensical
// "? ? …" INFORMAL name. Reject as OTHER instead.
/// Java: no flags. Has `\s`, no `\p{…}` → whole pattern (after `^`) wrapped.
static MULTI_QUESTION_PREFIX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\?(?-u:\s*)\?").unwrap());
/// Java: no flags (deliberately case-sensitive: `[Nn]` spells out the one letter allowed to
/// vary, so a lowercase-only "n. n." never matches). Has `\s` (x3) AND a wildcard `.` inside
/// `\(.*\)` → only the three `\s` atoms are individually scoped, leaving the wildcard `.`
/// (and the two literal `\.` after "N"/"n") untouched.
static NN_PLACEHOLDER: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^N\.(?-u:\s*)[Nn]\.?(?:(?-u:\s*)\(.*\))?(?-u:\s*)$").unwrap());
// "Genus indet." / "Genus indet" patterns are INFORMAL, not PLACEHOLDER.
/// Java: `Pattern.UNICODE_CHARACTER_CLASS`, no scoping.
static INDET_SPECIES: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^[\p{Lu}][\p{L}\-]+(?:\s+[\p{Lu}][\p{L}]+)?\s+(?:indet|undet)\.?\s*$").unwrap()
});

// Two or more Title-case words and nothing else: an informal group label once its quotes are gone.
static QUOTED_LABEL: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\p{Lu}\p{Ll}+(?:[ -]\p{Lu}\p{Ll}+)+$").unwrap());

// "clade" as a standalone word: a phylogenetic clade label, not a Linnean name.
/// Java: `Pattern.CASE_INSENSITIVE`. Has `\b` (x2), no `\p{…}` → whole pattern wrapped.
static CLADE_KEYWORD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(?-u:\bclade\b)").unwrap());

// Monomial aggregate forms: "Iteaphila-group" / "Bartonella group" / "Foo-complex" — a single
// Title-case uninomial + an aggregate marker. Since the stem is regex-constrained to a Title-case
// all-letter word it is ALWAYS a clean genus-shaped anchor, so 5.0.0 RESCUES these into an
// `Informal` (anchor = the monomial, phrase = the marker) rather than erroring. Captures: group 1 =
// the stem, group 2 = the marker word. (Match set is unchanged from the Java port; capture groups
// added for stem/marker extraction.) Java origin: `Pattern.UNICODE_CHARACTER_CLASS`, no scoping.
static MONOMIAL_AGGREGATE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^([\p{Lu}][\p{L}]+)(?:-|\s+)(group|complex)$").unwrap());

// "-lineage" / " lineage" labels ("Vermistella-lineage", "NC12A-lineage", "he2-lineage"): informal
// phylogenetic lineage names. The stem accepts any letter case and embedded digits, so it may be a
// clean genus ("Vermistella") OR an OTU-/strain-like code ("NC12A", "he2"). 5.0.0 rescues only the
// clean-genus stems into an `Informal` (see `is_clean_genus_stem`); code-shaped stems have no real
// anchor and stay Unparsable(OTHER). Captures: group 1 = the stem, group 2 = "lineage". Java origin:
// `Pattern.UNICODE_CHARACTER_CLASS`, no scoping.
static LINEAGE_LABEL: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^([\p{L}][\p{L}\d]*)(?:-|\s+)(lineage)$").unwrap());

// Trace-fossil / ichnotaxon labels ("Echinoid trace fossils (ichnotaxa)", "Trilobita-trace fossils",
// "Trace fossils"): an informal grouping of ichnotaxa, optionally hung off an anchor. Captures:
// group 1 = the optional stem, group 2 = the marker (kept verbatim as the phrase). Only the whole
// words count — real genera like Ichnospongia or Ichnoceros never match.
static TRACE_FOSSIL_LABEL: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)^(?:(\p{L}+)(?:-|\s+))?((?:trace[-\s]+fossils?|ichnotax(?:a|on))(?:\s+\((?:ichnotaxa|ichnotaxon)\))?)$",
    )
    .unwrap()
});
// The same marker words anywhere in the string — a label the anchored form above can't take apart.
static TRACE_FOSSIL_WORD: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)(?-u:\b)(?:trace[-\s]+fossils?|ichnotax(?:a|on))(?-u:\b)").unwrap()
});

// ---------- Precompiled in-method literals ----------
/// Java: no flags. No `\s`/`\d`/`\w`/`\b`; called via `.matches()` on an UNANCHORED Java
/// pattern, so the Rust port adds explicit `^…$` to reproduce full-match semantics.
static HTML_ENTITY_NAMED: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?:&[a-zA-Z]+;)$").unwrap());
/// Java: no flags. Has `\d`; same unanchored-pattern-called-via-`.matches()` situation as
/// above → `^…$` added, `\d` scoped (no `\p{…}` present, safe to wrap the whole thing).
static HTML_ENTITY_NUMERIC: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?-u:&#\d+;)$").unwrap());
/// Java: no flags (moot — always called against an already-lowercased string). Has `\s`
/// (x3) AND wildcard `.` (in `.*`, x3) → only the `\s` atoms are individually scoped;
/// unanchored Java pattern called via `.matches()` → `^…$` added.
static DELETE_MARKER: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?:.*(?-u:\s))?delete(?:(?-u:\s).*|,.*|(?-u:\s*))$").unwrap());
/// Java: no compile flags, but an inline `(?i)` in the pattern text itself. Has `\s` (x2)
/// AND `\p{Lu}`/`\p{L}` AND wildcard `.` (in the trailing `.*`) → only the two `\s` atoms
/// are individually scoped; unanchored Java pattern called via `.matches()` → `^…$` added.
static NON_HOMONYM: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?i)non(?-u:\s+)\p{Lu}\p{L}+(?:(?-u:\s).*)?$").unwrap());
/// Java: no flags. Has `\s` (x2) AND `\p{Ll}` → only `\s` scoped; already `^…$`-anchored in
/// Java so no extra full-match wrap is needed.
static QUESTION_ONLY: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\?(?-u:\s+)\p{Ll}+(?-u:\s*)$").unwrap());
/// Java: `Pattern.UNICODE_CHARACTER_CLASS`, no scoping.
static LATIN_WORD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\p{L}][\p{L}.\-]+").unwrap());
/// Java: `Pattern.UNICODE_CHARACTER_CLASS`, no scoping.
static LATIN_WORD_MIN2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\p{L}]{2,}").unwrap());
/// Java: `Pattern.UNICODE_CHARACTER_CLASS`. Has `\b`, kept Unicode (matches Java exactly,
/// since UNICODE_CHARACTER_CLASS makes Java's own `\b` Unicode-aware here too).
static AUTHOR_ABBREV: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b[\p{Lu}][\p{L}]*\.").unwrap());

/// If the input matches a non-scientific category, returns `Err(ParseError)` with the
/// appropriate [`NameType`] (mirrors Java throwing `UnparsableNameException`). Otherwise
/// returns `Ok(())` silently, letting the rest of the pipeline continue.
///
/// Port of Java `Preflight.run(String original, ParseContext ctx)`. Control-flow order is
/// exactly Java's: empty → single-letter/abbrev → HTML-entity → delete-markers →
/// non-homonym → placeholder-keywords → virus gate → monomial-aggregate → lineage →
/// multi-question → question-placeholder → clade → OTU/code group → hybrid-formula.
pub fn run(original: &str, ctx: &mut ParseContext) -> Result<(), ParseError> {
    // `ctx.working` is a plain owned `String`; copy the trimmed text out so `s` doesn't
    // keep an outstanding borrow of `ctx` alive across the later `&mut ctx` needed by
    // `apply_virus_gate`.
    let mut s: String = java_trim(&ctx.working).to_string();
    if s.is_empty() {
        return Err(ParseError::new(NameType::Other, None, original));
    }

    // A whole multi-word input wrapped in one pair of double quotes is a CSV/export artefact
    // (`"Accipiter bicolor (Vieillot, 1817)"`): unwrap it so every stage sees the name itself.
    // A single quoted word (`"Prosthete"`) is left to StripAndStash's quoted-monomial step.
    let was_quoted = match unwrap_quoted_phrase(&s) {
        Some(inner) => {
            s = inner.to_string();
            ctx.working = s.clone();
            true
        }
        None => false,
    };

    // Inputs that are too short or that are just an HTML entity stub (no real name content)
    // — bail out before any regex work touches them. A single bare letter ("X" / "a") is not
    // a name. An abbreviated genus ("B.") is allowed because the dot marks it as a stand-in
    // for a longer name.
    //
    // Java re-trims the already-trimmed `s` into a local `t` (`String t = s.trim();`) —
    // trimming is idempotent, so `t` is always structurally identical to `s`; `s` is used
    // directly here instead of a redundant second trim.
    if count_letters(&s) == 1 {
        // Java indexes `t.charAt(0)`/`t.charAt(1)` (UTF-16 code units); ported as Unicode
        // scalar (`char`) indexing, the closest faithful analogue without a UTF-16
        // dependency (diverges only for astral-plane single-letter input, vanishingly rare
        // for genus abbreviations — same tradeoff already documented for `Pipeline::run`'s
        // `MAX_LENGTH` guard).
        let chars: Vec<char> = s.chars().collect();
        let is_abbrev = chars.len() == 2 && chars[1] == '.' && chars[0].is_alphabetic();
        if !is_abbrev {
            return Err(ParseError::new(NameType::Other, None, original));
        }
    }
    if HTML_ENTITY_NAMED.is_match(&s) || HTML_ENTITY_NUMERIC.is_match(&s) {
        return Err(ParseError::new(NameType::Other, None, original));
    }

    // NO_NAME markers (text deletion / discard tags). A leading "non " followed by a proper
    // Latin name is a homonym citation, not a deletion marker — leave those to the regular
    // parser path. Only reject "non" when it precedes a single short word or punctuation
    // (the typical checklist-cleanup leftover).
    //
    // Java's `s.toLowerCase()` uses the JVM default locale; Rust's `to_lowercase()` is the
    // full-Unicode default-locale-independent mapping. Every needle searched for below
    // ("tobedeleted", "(delete)", …) is pure ASCII, so the two only-`toLowerCase()`-flavour
    // divergences that exist in principle (Turkish dotless-I, etc.) cannot change whether
    // these ASCII substrings are found — inert for this call site.
    let lower = s.to_lowercase();
    if lower.contains("tobedeleted")
        || lower.contains("(delete)")
        || s.starts_with('@')
        || DELETE_MARKER.is_match(&lower)
        || lower.contains("[delete]")
        || lower.contains("[none]")
    {
        return Err(ParseError::new(NameType::Other, None, original));
    }
    if lower.starts_with("non ") && (!NON_HOMONYM.is_match(&s) || s.contains('=')) {
        return Err(ParseError::new(NameType::Other, None, original));
    }

    // Placeholder keywords first — some placeholder strings contain "virus" (e.g.
    // "uncultured virus") and the explicit keyword wins over the virus marker.
    if (PLACEHOLDER_KEYWORDS.is_match(&s)
        || NN_PLACEHOLDER.is_match(&s)
        || PLACEHOLDER_PREFIX.is_match(&s)
        || s.starts_with("[unassigned]")
        || s.eq_ignore_ascii_case("Unaccepted"))
        && !INDET_SPECIES.is_match(&s)
    {
        return Err(ParseError::new(NameType::Placeholder, None, original));
    }

    // Virus — check before the leading-question-mark placeholder so that "? circular
    // satellites" reads as a virus rather than an unstructured placeholder.
    // Clean ICTV binomials/monomials with a viral genus suffix are let through to parse;
    // legacy vernacular virus names become OTHER + NomCode::Virus.
    apply_virus_gate(&s, ctx, original)?;

    // `unclassified` (61k CLB names: `unclassified Aaadonta constricta`) is a placeholder like
    // `unidentified` — but checked only after the virus gate, so a virus that carries it
    // (`Grapevine red globe virus (unclassified)`) keeps its VIRUS code.
    if UNCLASSIFIED.is_match(&s) {
        return Err(ParseError::new(NameType::Placeholder, None, original));
    }

    // A generic organism label instead of a genus — `bacterium Ac10`, `marine actinobacterium F10`,
    // `bacterium enrichment culture clone OB115` (~90k CLB names): the label plus a strain/clone
    // code is an IDENTIFIER; any other label (`endosymbiont of Chlamys farreri`) is OTHER. These
    // used to come back as genus `?` + epithet `bacterium`, or as a SCIENTIFIC genus `marine`.
    if let Some(type_) = classify_organism_label(&s) {
        return Err(ParseError::new(type_, None, s));
    }

    // Monomial-aggregate forms ("Iteaphila-group", "Bartonella group", "Foo-complex"): a single
    // Title-case uninomial + an aggregate marker. The stem is always a clean genus-shaped anchor, so
    // 5.0.0 RESCUES this into an `Informal` (anchor = the monomial, phrase = the marker) rather than
    // erroring. (Was `Err(INFORMAL)` in 4.2.0.)
    if let Some(caps) = MONOMIAL_AGGREGATE.captures(&s) {
        rescue_informal_group(ctx, &caps[1], &caps[2]);
        return Ok(());
    }

    // "-lineage" / " lineage" labels. RESCUE to `Informal` only when the stem is a clean genus
    // ("Vermistella-lineage"); an OTU-/strain-like code stem ("NC12A-lineage", "he2-lineage") has no
    // real anchor and stays Unparsable(OTHER). (Was `Err(INFORMAL)` for both in 4.2.0.)
    if let Some(caps) = LINEAGE_LABEL.captures(&s) {
        if is_clean_genus_stem(&caps[1]) {
            rescue_informal_group(ctx, &caps[1], &caps[2]);
            return Ok(());
        }
        return Err(ParseError::new(NameType::Other, None, original));
    }

    // Trace-fossil / ichnotaxon labels. RESCUE to `Informal` when a clean anchor precedes the marker
    // ("Trilobita-trace fossils"); an anchorless label ("Trace fossils") or one the anchored form
    // can't take apart ("Trace-fossils attributed to") is Unparsable(OTHER).
    if let Some(caps) = TRACE_FOSSIL_LABEL.captures(&s) {
        if let Some(stem) = caps.get(1).filter(|m| is_clean_genus_stem(m.as_str())) {
            rescue_informal_group(ctx, stem.as_str(), &caps[2]);
            return Ok(());
        }
        return Err(ParseError::new(NameType::Other, None, original));
    }
    if TRACE_FOSSIL_WORD.is_match(&s) {
        return Err(ParseError::new(NameType::Other, None, original));
    }

    // Leading "?? …" — a run of two or more question marks is junk, not a missing-genus
    // placeholder (that is a single "?"). Reject before the single-"?" handling below.
    if MULTI_QUESTION_PREFIX.is_match(&s) {
        return Err(ParseError::new(NameType::Other, None, original));
    }

    // Leading "? <epithet>" — placeholder for missing genus. Only fully unparsable when
    // there's nothing else on the line; with authorship/year following, the missing-genus
    // form is reconstructed downstream (see StripAndStash).
    if QUESTION_PREFIX.is_match(&s) && !INDET_SPECIES.is_match(&s) && QUESTION_ONLY.is_match(&s) {
        return Err(ParseError::new(NameType::Placeholder, None, original));
    }

    // Phylogenetic clade label ("Amauropeltoid clade", "Unnamed clade") — an anchorless informal
    // grouping the model can't hang off a single taxon → Unparsable(OTHER). (Was `Err(INFORMAL)` in
    // 4.2.0; 5.0.0 forbids a parsable type in an unparsable result, and these have no clean anchor.)
    if CLADE_KEYWORD.is_match(&s) {
        return Err(ParseError::new(NameType::Other, None, original));
    }

    // A quoted label of Title-case words only ("Lower Heterobranchia", "Sieblosioid Group") is an
    // informal group name with no anchor — the quotes mark it as not-a-name.
    if was_quoted && QUOTED_LABEL.is_match(&s) && !s.starts_with("Candidatus ") {
        return Err(ParseError::new(NameType::Other, None, original));
    }

    // Anchorless, scheme-prefixed machine IDENTIFIERS — BOLD BINs, GTDB/assembly accessions,
    // OTU/ASV/ESV/zOTU/MAG operational units, and standalone culture-collection accessions
    // (DSM 10, ATCC 11775). Not names, but a more specific 5.0.0 classification than the catch-all
    // Other (in 4.2.0 these were all OTHER). Use the normalised (trimmed) form as the name.
    if OTU_BOLD.is_match(&s)
        || OTU_GTDB_UBA.is_match(&s)
        || OTU_MOTU.is_match(&s)
        || CULTURE_ACCESSION_STANDALONE.is_match(&s)
    {
        return Err(ParseError::new(NameType::Identifier, None, s));
    }
    // SH identifiers are canonical in uppercase.
    if OTU_SH.is_match(&s) {
        return Err(ParseError::new(
            NameType::Identifier,
            None,
            s.to_uppercase(),
        ));
    }
    // Non-identifier NO_NAME junk (gen. nov. placeholder, `@…`) stays OTHER.
    if GEN_NOV.is_match(&s)
        // Dead-but-faithful (same shape as the PR2_LIKE note above): the `@`-check in the delete-marker gate above (Preflight.java:212) already returns for any `s.starts_with('@')`, so this second one (Preflight.java:278) can never fire — ported verbatim anyway to stay faithful.
        || s.starts_with('@')
    {
        return Err(ParseError::new(NameType::Other, None, s));
    }
    // Pure alphanumeric mash with digit (no spaces) and no obvious Latin epithet.
    if !s.contains(' ')
        && PURE_ALPHANUM.is_match(&s)
        && has_digit(&s)
        && !is_plausible_single_word_name(&s)
    {
        return Err(ParseError::new(NameType::Other, None, s));
    }
    // PR2-style underscored name with hyphenated digit suffix → NO_NAME.
    if PR2_LIKE.is_match(&s) && s.contains('-') && has_digit(&s) {
        return Err(ParseError::new(NameType::Other, None, s));
    }
    // GTDB/SILVA specimen codes ending with "sp" + 8+ digits (e.g. "18JY21-1 sp004344915").
    if s.contains(' ') && OTU_SPECIMEN_SUFFIX.is_match(&s) {
        return Err(ParseError::new(NameType::Other, None, s));
    }
    // Multi-word input whose last token is a known OTU code (e.g. "Festuca sp. BOLD:ACW2100").
    if s.contains(' ') {
        let last = last_word(&s);
        if OTU_BOLD.is_match(last) {
            return Err(ParseError::new(NameType::Other, None, last));
        }
        if OTU_SH.is_match(last) {
            return Err(ParseError::new(NameType::Other, None, last.to_uppercase()));
        }
    }

    // Hybrid formula — only when the cross sits between two distinct name spans.
    if looks_like_hybrid_formula(&s) {
        return Err(ParseError::new(NameType::Formula, None, original));
    }

    Ok(())
}

/// True if `stem` is a clean genus-shaped anchor for the 5.0.0 informal-group rescue: Title-case
/// (uppercase first) AND all-alphabetic (no digits). Excludes OTU-/strain-like code stems ("NC12A",
/// "he2") that carry no real taxon anchor. (The monomial-aggregate stem is already regex-constrained
/// to this shape; only the looser lineage stem needs the runtime check.)
fn is_clean_genus_stem(stem: &str) -> bool {
    stem.chars().next().is_some_and(char::is_uppercase) && stem.chars().all(char::is_alphabetic)
}

/// Build a complete supraspecific `Informal`-shaped `ParsedName` for a rescued monomial-aggregate /
/// lineage grouping (5.0.0) and flag the pipeline to short-circuit ([`ParseContext::preflight_complete`]).
/// The anchor goes in the `genus` slot (so `parse`'s `to_informal` derives `taxon_rank = GENUS`),
/// `rank` is `UNRANKED` (the grouping carries no Linnean rank of its own), and the aggregate word
/// becomes the `phrase`; `type = INFORMAL` routes it to `ParseResult::Informal`.
fn rescue_informal_group(ctx: &mut ParseContext, taxon: &str, marker: &str) {
    ctx.name.genus = Some(taxon.to_string());
    ctx.name.rank = Rank::Unranked;
    ctx.name.phrase = Some(marker.to_string());
    ctx.name.type_ = NameType::Informal;
    ctx.name.state = State::Complete;
    ctx.preflight_complete = true;
}

/// Port of Java `private static void applyVirusGate(String s, ParseContext ctx, String
/// original)`. Bucket A: a clean uni/binomial whose genus/monomial carries a viral rank
/// suffix parses, recording `ctx.viral_shape`. Bucket B: everything else that trips the
/// VIRUS marker is either rescued (zoological author-year override, soft-genus, caller
/// asserted a non-virus code, soft/hard virus-word rescues) or rejected as
/// `OTHER + NomCode::Virus`.
fn apply_virus_gate(s: &str, ctx: &mut ParseContext, original: &str) -> Result<(), ParseError> {
    let clean = CLEAN_BINOMIAL.is_match(s) || CLEAN_MONOMIAL.is_match(s);
    let req = ctx.requested_code;

    // Bucket A: clean uni/binomial whose genus/monomial carries a viral rank suffix.
    if clean && is_viral(first_word(s)) {
        if req.is_none() || req == Some(NomCode::Virus) {
            ctx.viral_shape = true;
        }
        return Ok(()); // parse; a non-virus caller code is kept and wins over inference
    }
    if !VIRUS.is_match(s) {
        return Ok(()); // no viral trigger at all
    }
    // Inline "Genus [(Subgenus)] epithet Author, YYYY" overrides a stray viral token.
    if ZOOLOGICAL_BINOMIAL.is_match(s) {
        return Ok(());
    }
    if req == Some(NomCode::Virus) {
        if clean {
            ctx.viral_shape = true;
            return Ok(());
        }
        return Err(ParseError::new(
            NameType::Other,
            Some(NomCode::Virus),
            original,
        ));
    }
    // Soft virus-word as the leading GENUS with no genuinely viral token present → a real
    // animal genus (e.g. "Prion vittatus", "Prion Lacépède, 1799"), not a virus. Covers both
    // the clean binomial and the authored-monomial forms, which the last-word SOFT_WORD
    // rescue below misses.
    if SOFT_GENUS.is_match(s) && !HARD_VIRUS.is_match(s) {
        return Ok(());
    }
    if clean && req.is_some() {
        return Ok(()); // caller asserts a non-virus code for a clean binomial
    }
    if clean && SOFT_WORD.is_match(last_word(s)) {
        return Ok(()); // bucket B soft
    }
    if clean && HARD_WORD.is_match(last_word(s)) {
        if let Some(auth) = ctx.authorship_input.as_deref() {
            if AUTH_ZOO.is_match(java_trim(auth)) {
                return Ok(()); // bucket B hard, rescued by a separately supplied zoological author+year
            }
        }
    }
    Err(ParseError::new(
        NameType::Other,
        Some(NomCode::Virus),
        original,
    ))
}

fn first_word(s: &str) -> &str {
    match s.find(' ') {
        Some(idx) => &s[..idx],
        None => s,
    }
}

fn last_word(s: &str) -> &str {
    match s.rfind(' ') {
        Some(idx) => &s[idx + 1..],
        None => s,
    }
}

/// Port of Java `private static boolean looksLikeHybridFormula(String s)`. A hybrid formula
/// has the cross between two NAME spans where the left side contains a *binomial* (Genus +
/// epithet) or an authored monomial. A single "× epithet" (notho marker) on either side does
/// NOT count.
///
/// Java indexes UTF-16 code units (`s.charAt(i)`, `s.substring(..)`); ported here over
/// `char_indices()` (byte offset, Unicode scalar value) pairs — `i` becomes a char-position
/// index into that Vec, and the paired byte offsets are used for the actual `&str` slicing,
/// so multi-byte UTF-8 sequences are never bisected (Rust `char`s need no surrogate-pair
/// handling at all, unlike Java `char`).
fn looks_like_hybrid_formula(s: &str) -> bool {
    let cs: Vec<(usize, char)> = s.char_indices().collect();
    let n = cs.len();
    for i in 0..n {
        let c = cs[i].1;
        let cross = c == '×';
        let ascii_x = !cross
            && (c == 'x' || c == 'X')
            && i > 0
            && i + 1 < n
            && cs[i - 1].1 == ' '
            && cs[i + 1].1 == ' ';
        let plus = !cross
            && !ascii_x
            && c == '+'
            && i > 0
            && i + 1 < n
            && cs[i - 1].1 == ' '
            && cs[i + 1].1 == ' ';
        if !cross && !ascii_x && !plus {
            continue;
        }
        if i == 0 || cs[i - 1].1 != ' ' {
            continue;
        }
        // Right of cross must be whitespace-separated; otherwise ×x is a notho marker
        // glued to an epithet (e.g. "var. ×alpina").
        if i + 1 >= n || cs[i + 1].1 != ' ' {
            continue;
        }
        let left = java_trim(&s[..cs[i].0]);
        let right = java_trim(&s[cs[i + 1].0..]);
        // Accept "?" as a valid right side (the second taxon is unspecified).
        let right_ok = contains_latin_word(right) || right.starts_with('?');
        if !right_ok {
            continue;
        }
        if count_latin_words(left) >= 2 || has_author_abbrev(left) {
            return true;
        }
        // Graft-chimera formula: single genus on each side (e.g. "Crataegus + Mespilus").
        // Java re-trims `right.trim()` a second time here even though `right` is already
        // trimmed above; idempotent, so `right` is used directly.
        if plus
            && count_latin_words(left) == 1
            && !left.is_empty()
            && left.chars().next().is_some_and(|c| c.is_uppercase())
            && !right.is_empty()
            && right.chars().next().is_some_and(|c| c.is_uppercase())
        {
            return true;
        }
    }
    false
}

fn count_latin_words(s: &str) -> usize {
    LATIN_WORD.find_iter(s).count()
}

fn contains_latin_word(s: &str) -> bool {
    LATIN_WORD_MIN2.is_match(s)
}

fn has_author_abbrev(s: &str) -> bool {
    AUTHOR_ABBREV.is_match(s)
}

/// java.lang.Character.isLetter — see `token.rs`'s `is_letter` for the same approximation
/// (`is_alphabetic`, slightly broader than Java's L*-only category) used throughout this
/// port; kept as a separate private fn here since `token.rs`'s is module-private.
fn count_letters(s: &str) -> usize {
    s.chars().filter(|c| c.is_alphabetic()).count()
}

/// java.lang.Character.isDigit — see `token.rs`'s `is_digit` for the same ASCII-only
/// approximation used throughout this port (non-ASCII decimal digits are rare in names).
fn has_digit(s: &str) -> bool {
    s.chars().any(|c| c.is_ascii_digit())
}

/// Conservative check: a single-token name with at least one digit is plausibly NOT
/// scientific.
fn is_plausible_single_word_name(s: &str) -> bool {
    !has_digit(s)
}

/// The trimmed content of `"two or more words"` — one pair of double quotes wrapping the whole
/// input, with an inner space and no further double quote — or `None`.
fn unwrap_quoted_phrase(s: &str) -> Option<&str> {
    let inner = java_trim(s.strip_prefix('"')?.strip_suffix('"')?);
    (inner.contains(' ') && !inner.contains('"')).then_some(inner)
}

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

    /// Builds a fresh `ParseContext` the way `Pipeline::run` would just before calling
    /// `Preflight.run`, and calls it — per the brief, unit-testing Preflight directly
    /// rather than through the (still-skeletal) full pipeline.
    fn check(input: &str) -> Result<(), ParseError> {
        let mut ctx = ParseContext::new(input.to_string(), None, None, None);
        run(input, &mut ctx)
    }

    /// Run preflight and return the ctx, asserting it RESCUED the input into a complete informal
    /// name (5.0.0) rather than erroring — for inspecting the rescued `ctx.name`.
    fn rescued(input: &str) -> ParseContext {
        let mut ctx = ParseContext::new(input.to_string(), None, None, None);
        run(input, &mut ctx).unwrap_or_else(|e| panic!("`{input}` should be rescued, got {e:?}"));
        assert!(
            ctx.preflight_complete,
            "`{input}` should set preflight_complete"
        );
        ctx
    }

    // ---------- category: virus ----------

    #[test]
    fn virus_vernacular_name_is_rejected_other_virus() {
        let err = check("Tobacco mosaic virus").unwrap_err();
        assert_eq!(err.type_, NameType::Other);
        assert_eq!(err.code, Some(NomCode::Virus));
    }

    #[test]
    fn soft_genus_prion_is_rescued_and_parses() {
        // Prion (petrels) is a real animal genus; the soft word "prion" alone (no HARD_VIRUS
        // token also present) must not trip the virus gate. Java `virusFalsePositiveAnimals()`.
        assert!(check("Prion vittatus").is_ok());
    }

    #[test]
    fn zoological_binomial_with_author_year_overrides_stray_viral_token() {
        // Documented motivating example for ZOOLOGICAL_BINOMIAL (Java commit db606be): a real
        // species whose epithet is a VIRUS-triggering word ("vector") is rescued by an inline
        // "Genus species Author, YYYY" citation.
        assert!(check("Ceylonesmus vector Chamberlin, 1941").is_ok());
    }

    #[test]
    fn clean_ictv_binomial_parses_with_viral_shape_flag_set() {
        // Bucket A: a clean binomial whose genus carries an ICTV viral suffix parses, and
        // Preflight records viral_shape for a later Assemble stage to turn into NomCode::Virus.
        let mut ctx = ParseContext::new("Lausannevirus francensis".to_string(), None, None, None);
        assert!(run("Lausannevirus francensis", &mut ctx).is_ok());
        assert!(ctx.viral_shape);
    }

    // ---------- category: hybrid formula ----------

    #[test]
    fn cross_between_two_binomials_is_a_hybrid_formula() {
        let err = check("Homo sapiens x Homo neanderthalensis").unwrap_err();
        assert_eq!(err.type_, NameType::Formula);
        assert_eq!(err.code, None);
    }

    #[test]
    fn graft_chimera_plus_formula_is_rejected() {
        let err = check("Crataegus + Mespilus").unwrap_err();
        assert_eq!(err.type_, NameType::Formula);
    }

    // ---------- category: OTU / specimen code ----------

    #[test]
    fn bold_code_is_classified_identifier() {
        // 5.0.0: a BOLD BIN is an anchorless machine identifier -> NameType::Identifier (was OTHER).
        let err = check("BOLD:ACW2100").unwrap_err();
        assert_eq!(err.type_, NameType::Identifier);
        assert_eq!(err.code, None);
    }

    #[test]
    fn sh_code_is_classified_identifier_with_uppercased_name() {
        // 5.0.0: a UNITE species hypothesis -> Identifier (was OTHER); still uppercased canonical.
        let err = check("sh460441.07fu").unwrap_err();
        assert_eq!(err.type_, NameType::Identifier);
        assert_eq!(err.name, "SH460441.07FU");
    }

    #[test]
    fn otu_asv_mag_operational_units_are_classified_identifier() {
        // 5.0.0: further anchorless MOTU schemes -> Identifier (plain OTHER/unclassified in 4.2.0).
        for s in ["OTU-17", "OTU 34", "ASV_103", "zOTU44", "MAG-24"] {
            let err = check(s).unwrap_err();
            assert_eq!(
                err.type_,
                NameType::Identifier,
                "{s} should be an IDENTIFIER"
            );
        }
    }

    #[test]
    fn standalone_culture_collection_accession_is_classified_identifier() {
        // 5.0.0: a bare culture-collection accession (curated acronym + body) -> Identifier.
        for s in [
            "DSM 10",
            "ATCC 11775",
            "ATCC BAA-123",
            "CBS 123.89",
            "LMG 6923T",
            "ATCC-11775",
        ] {
            let err = check(s).unwrap_err();
            assert_eq!(
                err.type_,
                NameType::Identifier,
                "{s} should be an IDENTIFIER"
            );
        }
    }

    #[test]
    fn a_genus_starting_with_an_identifier_prefix_is_not_an_identifier() {
        // "Uba fallai" is a real beetle genus, NOT the UBA scheme — the whole-string + trailing-digit
        // guard (and the space) let it through to the parser instead of matching OTU_GTDB_UBA.
        assert!(check("Uba fallai Fletcher, 1938").is_ok());
    }

    #[test]
    fn trailing_bold_code_in_multiword_input_is_rejected_with_last_word_as_name() {
        let err = check("Festuca sp. BOLD:ACW2100").unwrap_err();
        assert_eq!(err.type_, NameType::Other);
        assert_eq!(err.name, "BOLD:ACW2100");
    }

    // ---------- category: informal (5.0.0 — anchored groupings RESCUED, anchorless → OTHER) --------

    #[test]
    fn monomial_group_aggregate_rescued_to_informal() {
        // The stem is always a clean genus-shaped anchor → always rescued.
        let ctx = rescued("Iteaphila-group");
        assert_eq!(ctx.name.type_, NameType::Informal);
        assert_eq!(ctx.name.genus.as_deref(), Some("Iteaphila"));
        assert_eq!(ctx.name.phrase.as_deref(), Some("group"));
        assert_eq!(ctx.name.rank, Rank::Unranked);
        assert!(ctx.name.specific_epithet.is_none());
        // spaced + "complex" variants likewise
        assert_eq!(
            rescued("Bartonella group").name.genus.as_deref(),
            Some("Bartonella")
        );
        assert_eq!(
            rescued("Foo-complex").name.phrase.as_deref(),
            Some("complex")
        );
    }

    #[test]
    fn lineage_with_clean_genus_stem_rescued_to_informal() {
        let ctx = rescued("Vermistella-lineage");
        assert_eq!(ctx.name.type_, NameType::Informal);
        assert_eq!(ctx.name.genus.as_deref(), Some("Vermistella"));
        assert_eq!(ctx.name.phrase.as_deref(), Some("lineage"));
    }

    #[test]
    fn trace_fossil_label_with_clean_stem_rescued_to_informal() {
        let n = rescued("Echinoid trace fossils (ichnotaxa)").name;
        assert_eq!(n.genus.as_deref(), Some("Echinoid"));
        assert_eq!(n.phrase.as_deref(), Some("trace fossils (ichnotaxa)"));
        assert_eq!(n.type_, NameType::Informal);
        let n = rescued("Trilobita-trace fossils").name;
        assert_eq!(n.genus.as_deref(), Some("Trilobita"));
        assert_eq!(n.phrase.as_deref(), Some("trace fossils"));
    }

    #[test]
    fn trace_fossil_label_without_stem_is_unparsable_other() {
        for label in [
            "Trace fossils",
            "Trace-fossils",
            "Trace-fossils attributed to",
            "ichnotaxa",
        ] {
            assert_eq!(check(label).unwrap_err().type_, NameType::Other, "{label}");
        }
        assert!(check("Ichnospongia").is_ok());
        assert!(check("Ichnoceros robustus").is_ok());
    }

    #[test]
    fn lineage_with_code_stem_is_unparsable_other() {
        // OTU-/strain-like code stems have no real anchor → Unparsable(OTHER), not rescued.
        assert_eq!(check("NC12A-lineage").unwrap_err().type_, NameType::Other);
        assert_eq!(check("he2-lineage").unwrap_err().type_, NameType::Other);
    }

    #[test]
    fn clade_keyword_is_unparsable_other() {
        // Clade labels are anchorless phylogenetic groupings → OTHER (5.0.0; was INFORMAL).
        assert_eq!(
            check("Amauropeltoid clade").unwrap_err().type_,
            NameType::Other
        );
        assert_eq!(check("Unnamed clade").unwrap_err().type_, NameType::Other);
    }

    // ---------- category: other (junk / non-names) ----------

    #[test]
    fn double_question_mark_prefix_is_other_not_informal() {
        let err = check("?? not a name").unwrap_err();
        assert_eq!(err.type_, NameType::Other);
    }

    #[test]
    fn bare_gen_nov_is_other() {
        let err = check("Gen.nov.").unwrap_err();
        assert_eq!(err.type_, NameType::Other);
    }

    #[test]
    fn delete_marker_is_other() {
        let err = check("Scelotes tobedeleted , 1999").unwrap_err();
        assert_eq!(err.type_, NameType::Other);
    }

    #[test]
    fn html_named_entity_only_is_other() {
        let err = check("&amp;").unwrap_err();
        assert_eq!(err.type_, NameType::Other);
    }

    #[test]
    fn single_bare_letter_is_other() {
        let err = check("X").unwrap_err();
        assert_eq!(err.type_, NameType::Other);
    }

    #[test]
    fn single_letter_abbreviation_with_dot_is_not_rejected_by_the_letter_count_guard() {
        // "B." is an abbreviated genus stand-in, not a bare letter -- Preflight's own
        // letter-count guard must let it through (downstream stages are responsible for
        // actually expanding/handling it).
        assert!(check("B.").is_ok());
    }

    #[test]
    fn empty_input_is_other() {
        let err = check("").unwrap_err();
        assert_eq!(err.type_, NameType::Other);
    }

    // ---------- category: placeholder ----------

    #[test]
    fn fully_quoted_multi_word_label_is_unparsable_other() {
        assert_eq!(
            check("\"Lower Heterobranchia\"").unwrap_err().type_,
            NameType::Other
        );
        assert_eq!(
            check("\"Sieblosioid Group\"").unwrap_err().type_,
            NameType::Other
        );
        assert!(check("\"Prosthete\"").is_ok());
        assert!(check("\"Candidatus Riegeria\"").is_ok());
        assert!(check("\"Aus\" bus").is_ok());
    }

    #[test]
    fn fully_quoted_name_is_unwrapped() {
        let input = "\"Accipiter bicolor (Vieillot, 1817)\"";
        let mut ctx = ParseContext::new(input.to_string(), None, None, None);
        assert!(run(input, &mut ctx).is_ok());
        assert_eq!(ctx.working, "Accipiter bicolor (Vieillot, 1817)");
    }

    #[test]
    fn incertae_sedis_is_placeholder() {
        let err = check("incertae sedis").unwrap_err();
        assert_eq!(err.type_, NameType::Placeholder);
    }

    #[test]
    fn nn_placeholder_is_placeholder() {
        let err = check("N.N.").unwrap_err();
        assert_eq!(err.type_, NameType::Placeholder);
    }

    #[test]
    fn single_question_mark_alone_is_placeholder() {
        let err = check("? unclassed").unwrap_err();
        assert_eq!(err.type_, NameType::Placeholder);
    }

    // ---------- category: scientific (Ok) ----------

    #[test]
    fn clean_binomial_parses() {
        assert!(check("Abies alba").is_ok());
    }

    // ---------- additional edge cases surfaced during the port ----------

    #[test]
    fn hard_virus_word_is_rescued_by_separately_supplied_zoological_authorship() {
        // Bucket B hard rescue (`apply_virus_gate`'s `clean && HARD_WORD.is_match(last_word)`
        // branch): "virus" IS a HARD_WORD (unlike the previous version of this test, which
        // used "vector" — a SOFT_WORD only, rescued several branches earlier and so never
        // actually reaching this one). "Exochus virus" is a clean binomial with no inline
        // author+year, but a separately supplied authorship string that itself looks like a
        // zoological author+year citation rescues it. Mirrors Java's
        // `virusFalsePositiveAnimals` two-argument `assertName` calls.
        let mut ctx = ParseContext::new(
            "Exochus virus".to_string(),
            Some("Gauld & Sithole, 2002".to_string()),
            None,
            None,
        );
        assert!(run("Exochus virus", &mut ctx).is_ok());

        // Proof the rescue above is load-bearing rather than the input already passing at an
        // earlier branch: the identical clean-binomial-with-HARD_WORD input, minus the
        // rescuing authorship, must be rejected as OTHER + Virus.
        let mut ctx_no_auth = ParseContext::new("Exochus virus".to_string(), None, None, None);
        let err = run("Exochus virus", &mut ctx_no_auth).unwrap_err();
        assert_eq!(err.type_, NameType::Other);
        assert_eq!(err.code, Some(NomCode::Virus));
    }

    #[test]
    fn clean_binomial_with_hard_virus_word_and_requested_non_virus_code_parses() {
        // `apply_virus_gate`'s `clean && req.is_some()` branch: the caller asserting ANY
        // non-virus code for a clean binomial is, by itself, enough to let a HARD_WORD-ending
        // epithet through — no authorship rescue needed at all. Same "Exochus virus" input as
        // the rule-H test above, this time with no authorship but an explicit requested code.
        let mut ctx = ParseContext::new(
            "Exochus virus".to_string(),
            None,
            None,
            Some(NomCode::Zoological),
        );
        assert!(run("Exochus virus", &mut ctx).is_ok());
    }

    #[test]
    fn requested_virus_code_sets_viral_shape_for_clean_input_and_rejects_non_clean_input() {
        // `apply_virus_gate`'s `req == Some(NomCode::Virus)` branch, both arms. (a) A clean
        // uni/binomial parses and records `viral_shape` for Assemble to turn into
        // `NomCode::Virus` later. (b) Non-clean (three-word vernacular) input is rejected as
        // OTHER + Virus regardless — the requested code cannot rescue a shape that was never
        // even a plausible uni/binomial.
        let mut ctx = ParseContext::new(
            "Exochus virus".to_string(),
            None,
            None,
            Some(NomCode::Virus),
        );
        assert!(run("Exochus virus", &mut ctx).is_ok());
        assert!(ctx.viral_shape);

        let mut ctx2 = ParseContext::new(
            "Tobacco mosaic virus".to_string(),
            None,
            None,
            Some(NomCode::Virus),
        );
        let err = run("Tobacco mosaic virus", &mut ctx2).unwrap_err();
        assert_eq!(err.type_, NameType::Other);
        assert_eq!(err.code, Some(NomCode::Virus));
    }

    #[test]
    fn gca_code_is_classified_identifier() {
        // Java test data only exercises the "UBA" alternative of OTU_GTDB_UBA directly;
        // this covers the untested "GCA" alternative in the same alternation. 5.0.0: Identifier.
        let err = check("GCA_000123").unwrap_err();
        assert_eq!(err.type_, NameType::Identifier);
    }

    #[test]
    fn non_prefix_followed_by_a_proper_latin_name_is_not_rejected() {
        // A leading "non " followed by what looks like a genuine homonym-citation author
        // name (NON_HOMONYM matches, no "=") must NOT be treated as a deletion marker.
        assert!(check("non Linnaeus").is_ok());
    }

    #[test]
    fn non_prefix_with_equals_sign_is_still_rejected() {
        // Even when NON_HOMONYM would otherwise match, an embedded "=" (a synonymy marker
        // in the typical checklist-cleanup leftover) still forces rejection.
        let err = check("non Linnaeus = Smith").unwrap_err();
        assert_eq!(err.type_, NameType::Other);
    }

    #[test]
    fn question_prefixed_epithet_with_trailing_authorship_is_not_preflight_rejected() {
        // QUESTION_ONLY only fires when there's nothing else on the line; with an author
        // citation following, the missing-genus placeholder is reconstructed downstream, so
        // Preflight itself must let it through.
        assert!(check("? gryphoidis Bourguignat 1870").is_ok());
    }

    #[test]
    fn virus_gate_classifies_adversarial_input_without_hanging() {
        // Java's `virusGateNoCatastrophicBacktracking` guards ZOOLOGICAL_BINOMIAL's
        // possessive-quantifier ReDoS hardening against a backtracking engine. The `regex`
        // crate has no backtracking at all (linear-time automaton), so this can't
        // pathologically hang here the way an unguarded Java `Matcher.find()` could — this
        // test documents that guarantee rather than defending against real risk.
        let adversarial = format!("Rnavirus bus {}", "Aa.-".repeat(30));
        let start = std::time::Instant::now();
        let _ = check(&adversarial);
        assert!(start.elapsed() < std::time::Duration::from_secs(3));
    }
}