Skip to main content

nameparser/model/
enums.rs

1// SPDX-License-Identifier: Apache-2.0
2use serde::Serialize;
3use std::collections::{HashMap, HashSet};
4use std::sync::LazyLock;
5
6/// Java `org.gbif.nameparser.api.NameType`. A short classification of scientific name strings.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
8#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
9pub enum NameType {
10    Scientific,
11    Formula,
12    Informal,
13    Placeholder,
14    /// An anchorless, scheme-prefixed *machine identifier* — a UNITE species hypothesis
15    /// (`SH1957732.10FU`), a BOLD BIN (`BOLD:AAA0001`), an OTU/ASV/… operational unit, or a
16    /// standalone culture-collection accession (`DSM 10`). Not a name the parser can express as a
17    /// [`crate::model::ParsedName`], so — like `Other` — it is **not parsable** and only ever
18    /// appears in a `ParseResult::Unparsable`; it just carries a more specific classification than
19    /// the catch-all `Other`. Placed before `Other` so the catch-all stays last; this makes it
20    /// FFI-wire ordinal 4 and shifts `Other` to 5 (a lockstep change gated by the ABI-version bump).
21    Identifier,
22    Other,
23}
24
25impl NameType {
26    /// Java `NameType.isParsable()` (`NameType.java`): true iff the parser can express such a name
27    /// as a [`crate::model::ParsedName`] — `SCIENTIFIC` or `INFORMAL`. The 5.0.0
28    /// `ParseResult.Unparsable` variant (Java + Rust) may only carry a non-parsable type, so this
29    /// gates the [`crate::ParseError::clamped_to_unparsable`] normalization.
30    pub fn is_parsable(&self) -> bool {
31        matches!(self, NameType::Scientific | NameType::Informal)
32    }
33}
34
35/// Java `org.gbif.nameparser.api.NomCode`. Nomenclatural codes governing biological taxonomic
36/// nomenclature.
37///
38/// `Hash` (beyond the `Rank`-parity `Debug, Clone, Copy, PartialEq, Eq, Serialize` set) is
39/// needed for `pipeline::code_inference::infer`'s vote tally, a `HashSet<NomCode>` mirroring
40/// Java's `EnumSet<NomCode> votes` (`CodeInference.java:66`) — added here (Phase 1 Slice 4
41/// Task 3) rather than duplicated as a local newtype, since `Rank` already sets this same
42/// precedent (it derives `Hash` for its own `HashMap`/`HashSet` static tables above).
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
44#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
45pub enum NomCode {
46    Bacterial,
47    Botanical,
48    Cultivars,
49    Phyto,
50    Virus,
51    Zoological,
52    Phylo,
53}
54
55/// Java `org.gbif.nameparser.api.NamePart`. Indicates a part of a canonical scientific name.
56///
57/// Declaration order below matches Java's ordinal order (verified against
58/// `NamePart.java`), and carries `PartialOrd, Ord` so it can be used as a `BTreeMap` key
59/// for `ParsedName::epithet_qualifier` — Java's own `EnumMap<NamePart, String>` there
60/// iterates in the same ordinal order, so a `BTreeMap` reproduces it on the wire.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
62#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
63pub enum NamePart {
64    Generic,
65    Infrageneric,
66    Specific,
67    Infraspecific,
68}
69
70/// Java `org.gbif.nameparser.api.ParsedName.State`. Degree of parsing a `ParsedName` reflects.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
72#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
73pub enum State {
74    Complete,
75    Partial,
76    None,
77}
78
79// ================================================================================================
80// Rank
81// ================================================================================================
82
83/// Java `org.gbif.nameparser.api.Rank` (`Rank.java`, 637 lines) — the full 117-constant
84/// taxonomic rank enumeration, ported in EXACT Java declaration order (verified mechanically
85/// against `Rank.java` line-by-line, `SUPERDOMAIN` first through `UNRANKED` last — see the
86/// exhaustive round-trip test `rank_all_117_variants_in_java_declaration_order` below).
87/// Declaration order is load-bearing: Rust numbers enum discriminants 0..117 in declaration
88/// order exactly like Java's `Enum.ordinal()`, so [`Rank::ordinal`] and every ordinal-compare
89/// predicate below (`is_infraspecific`, `higher_than`, `is_family_group`, …) reproduce Java's
90/// behaviour by construction, not by coincidence.
91///
92/// Each constant carries the same `code`/`marker`/`plural` triple as its Java constructor call
93/// — see [`Rank::code`], [`Rank::marker`], [`Rank::plural`]. 67 of the 117 are code-restricted
94/// (44 `ZOOLOGICAL`, 10 `BOTANICAL`, 7 `BACTERIAL`, 4 `CULTIVARS`, 2 `VIRUS` — counted by
95/// grepping `NomCode\.` inside `Rank.java`'s own constant-declaration block, lines 25-311); the
96/// remaining 50 are code-agnostic (`None`).
97///
98/// `#[serde(rename_all = "SCREAMING_SNAKE_CASE")]` reproduces Java's `.name()` wire form for
99/// every one of the 117, including multi-word constants like `SUPERSECTION_BOTANY`,
100/// `INFRASPECIFIC_NAME` and `FORMA_SPECIALIS` — verified by the exhaustive round-trip test
101/// below (`rank_all_117_variants_in_java_declaration_order`), so no `#[serde(rename = "…")]`
102/// overrides were needed.
103///
104/// This is the crate's single source of truth for rank data and predicates: the ordinal
105/// predicates here replace the former ad-hoc `rank_is_infrageneric_strictly`
106/// (`pipeline::authorship_split`) and `rank_is_infraspecific` / `rank_marker`
107/// (`pipeline::name_tokens`) — both were explicit stand-ins for a not-yet-full `Rank`; those
108/// two files now call [`Rank::is_infrageneric_strictly`], [`Rank::is_infraspecific`] and
109/// [`Rank::marker`] directly instead of carrying their own copies.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
111#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
112pub enum Rank {
113    Superdomain,
114    Domain,
115    Subdomain,
116    Infradomain,
117    Empire,
118    Realm,
119    Subrealm,
120    Superkingdom,
121    Kingdom,
122    Subkingdom,
123    Infrakingdom,
124    Superphylum,
125    Phylum,
126    Subphylum,
127    Infraphylum,
128    Parvphylum,
129    Microphylum,
130    Nanophylum,
131    Claudius,
132    Gigaclass,
133    Megaclass,
134    Superclass,
135    Class,
136    Subclass,
137    Infraclass,
138    Subterclass,
139    Parvclass,
140    Superdivision,
141    DivisionZoology,
142    Subdivision,
143    Infradivision,
144    Superlegion,
145    Legion,
146    Sublegion,
147    Infralegion,
148    Megacohort,
149    Supercohort,
150    Cohort,
151    Subcohort,
152    Infracohort,
153    Gigaorder,
154    Magnorder,
155    Grandorder,
156    Mirorder,
157    Superorder,
158    Order,
159    Nanorder,
160    Hypoorder,
161    Minorder,
162    Suborder,
163    Infraorder,
164    Parvorder,
165    SupersectionZoology,
166    SectionZoology,
167    SubsectionZoology,
168    SuperseriesZoology,
169    SeriesZoology,
170    SubseriesZoology,
171    Falanx,
172    Gigafamily,
173    Megafamily,
174    Grandfamily,
175    Superfamily,
176    Epifamily,
177    Family,
178    Subfamily,
179    Infrafamily,
180    Supertribe,
181    Tribe,
182    Subtribe,
183    Infratribe,
184    SupragenericName,
185    Supergenus,
186    Genus,
187    Subgenus,
188    Infragenus,
189    DivisionBotany,
190    SupersectionBotany,
191    SectionBotany,
192    SubsectionBotany,
193    SuperseriesBotany,
194    SeriesBotany,
195    SubseriesBotany,
196    InfragenericName,
197    SpeciesAggregate,
198    Species,
199    InfraspecificName,
200    Grex,
201    Klepton,
202    Subspecies,
203    CultivarGroup,
204    Convariety,
205    InfrasubspecificName,
206    Proles,
207    Natio,
208    Aberration,
209    Morph,
210    Supervariety,
211    Variety,
212    Subvariety,
213    Superform,
214    Form,
215    Subform,
216    Pathovar,
217    Biovar,
218    Chemovar,
219    Morphovar,
220    Phagovar,
221    Serovar,
222    Chemoform,
223    FormaSpecialis,
224    Lusus,
225    Cultivar,
226    Mutatio,
227    Strain,
228    Other,
229    Unranked,
230}
231
232/// Java `Rank.UNCOMPARABLE_RANKS` (`Rank.java:341-353`, `private`): ranks which represent a
233/// "range" rather than a single comparable level, so [`Rank::is_uncomparable`] excludes them
234/// from ordinal comparisons.
235const UNCOMPARABLE_RANKS: [Rank; 6] = [
236    Rank::SupragenericName,
237    Rank::InfragenericName,
238    Rank::InfraspecificName,
239    Rank::InfrasubspecificName,
240    Rank::Other,
241    Rank::Unranked,
242];
243
244/// Java `Rank.LEGACY_RANKS` (`Rank.java:355-364`, `private`): ranks considered legacy, not
245/// used in current nomenclature.
246const LEGACY_RANKS: [Rank; 8] = [
247    Rank::Morph,
248    Rank::Aberration,
249    Rank::Natio,
250    Rank::Proles,
251    Rank::Convariety,
252    Rank::Klepton,
253    Rank::Falanx,
254    Rank::Lusus,
255];
256
257/// Java `Rank.MAJOR_RANKS`'s static-init prefix-stripping regex,
258/// `^(SUPER|SUB(?:TER)?|INFRA|MICRO|NANO|GIGA|MAGN|GRAND|MIR|NAN|HYPO|MIN|PARV|MEGA|EPI)`
259/// (`Rank.java:373`), transcribed as an ordered list of literal prefixes tried left-to-right
260/// — reproducing Java regex alternation's ordered-choice semantics without pulling `regex`
261/// into the model layer. `SUBTER` is listed before the plain `SUB` so a name like
262/// `SUBTERCLASS` strips the full `SUBTER` (the `(?:TER)?` group is greedy and tried first),
263/// not just `SUB` (which would leave the unmappable remainder `TERCLASS`). `NAN` (after
264/// `MIR`) is unreachable in practice — every current rank name starting "NAN" also starts
265/// "NANO", which is tried earlier in this same list — kept only because the source regex
266/// still lists it (same "port the whole literal, faithfully, even the unreachable part"
267/// precedent as `bot_to_zool` in `pipeline::stripandstash`).
268const MAJOR_RANK_PREFIXES: [&str; 16] = [
269    "SUPER", "SUBTER", "SUB", "INFRA", "MICRO", "NANO", "GIGA", "MAGN", "GRAND", "MIR", "NAN",
270    "HYPO", "MIN", "PARV", "MEGA", "EPI",
271];
272
273/// Strips the first matching prefix from [`MAJOR_RANK_PREFIXES`] (tried in order), or
274/// returns `None` if none match — the literal-prefix-list equivalent of applying Java's
275/// `prefixes.matcher(r.name())` + `m.replaceFirst("")` (`Rank.java:388-390`).
276fn strip_major_rank_prefix(name: &str) -> Option<&str> {
277    for prefix in MAJOR_RANK_PREFIXES {
278        if let Some(rest) = name.strip_prefix(prefix) {
279            return Some(rest);
280        }
281    }
282    None
283}
284
285/// The exact Java `.name()` string for a rank (e.g. `Rank::DivisionZoology` ->
286/// `"DIVISION_ZOOLOGY"`), reusing `Rank`'s own `Serialize` impl (rather than a second,
287/// hand-duplicated name table) so this can never drift from the wire form. Used only by the
288/// [`MAJOR_RANKS`] static-init below, mirroring how `Rank.java`'s own static block calls
289/// `r.name()` (`Rank.java:388`).
290fn rank_wire_name(rank: Rank) -> String {
291    serde_json::to_string(&rank)
292        .expect("Rank always serializes to a JSON string")
293        .trim_matches('"')
294        .to_string()
295}
296
297/// Java `Rank.MAJOR_RANKS` (`Rank.java:367-410`, `private`, built in a static initializer):
298/// for every rank, the "major" rank it belongs to once its prefix (`SUPER-`/`SUB-`/…) is
299/// stripped — infraspecific ranks all collapse to `INFRASPECIFIC_NAME` first, then the
300/// prefix-strip + name lookup runs for everything else, then 6 manual fixes are layered on
301/// top for the cases the automatic algorithm can't resolve (verified against Java's own
302/// static block line-by-line; see [`Rank::get_major_rank`]'s tests for the specific cases).
303static MAJOR_RANKS: LazyLock<HashMap<Rank, Rank>> = LazyLock::new(|| {
304    let name_to_rank: HashMap<String, Rank> =
305        Rank::ALL.iter().map(|&r| (rank_wire_name(r), r)).collect();
306
307    let mut map = HashMap::with_capacity(Rank::ALL.len());
308    for &r in Rank::ALL.iter() {
309        let major = if r.is_infraspecific() {
310            Rank::InfraspecificName
311        } else {
312            strip_major_rank_prefix(&rank_wire_name(r))
313                .and_then(|rest| name_to_rank.get(rest))
314                .copied()
315                .unwrap_or(r)
316        };
317        map.insert(r, major);
318    }
319    // Manual fixes (`Rank.java:399-407`): `NANORDER` strips (via `NANO`, tried before the
320    // unreachable `NAN`) to the unmapped "RDER"; `SPECIES_AGGREGATE`/`INFRAGENERIC_NAME`
321    // match no prefix at all; and the zoological division ranks were renamed to
322    // `*_ZOOLOGY`, so `SUPERDIVISION`/`SUBDIVISION`/`INFRADIVISION` can no longer strip to
323    // a plain "DIVISION" (Java's own comment on this exact point, `Rank.java:403-404`).
324    map.insert(Rank::Nanorder, Rank::Order);
325    map.insert(Rank::SpeciesAggregate, Rank::Species);
326    map.insert(Rank::InfragenericName, Rank::Genus);
327    map.insert(Rank::Superdivision, Rank::DivisionZoology);
328    map.insert(Rank::Subdivision, Rank::DivisionZoology);
329    map.insert(Rank::Infradivision, Rank::DivisionZoology);
330    map
331});
332
333/// Java `Rank.AMBIGUOUS_MARKER` (`Rank.java:366-382`, `private`, same static initializer as
334/// `MAJOR_RANKS`): the set of ranks whose marker text is shared with at least one other
335/// rank (the 7 zoology/botany pairs — `div.`, `sect.`, `subsect.`, `supersect.`, `ser.`,
336/// `subser.`, `superser.` — 14 ranks total), computed by walking [`Rank::ALL`] in ordinal
337/// order and flagging both ranks the first time a marker string repeats.
338static AMBIGUOUS_MARKER: LazyLock<HashSet<Rank>> = LazyLock::new(|| {
339    let mut ambiguous = HashSet::new();
340    let mut seen: HashMap<&'static str, Rank> = HashMap::new();
341    for &r in Rank::ALL.iter() {
342        if let Some(marker) = r.marker() {
343            if let Some(&earlier) = seen.get(marker) {
344                ambiguous.insert(r);
345                ambiguous.insert(earlier);
346            } else {
347                seen.insert(marker, r);
348            }
349        }
350    }
351    ambiguous
352});
353
354impl Rank {
355    /// All 117 constants, in Java declaration/ordinal order — the Rust equivalent of the
356    /// compiler-generated Java `Rank.values()`, needed since Rust has no built-in enum
357    /// reflection. Used internally to build [`MAJOR_RANKS`]/[`AMBIGUOUS_MARKER`] and by
358    /// this module's own tests.
359    pub const ALL: [Rank; 117] = [
360        Rank::Superdomain,
361        Rank::Domain,
362        Rank::Subdomain,
363        Rank::Infradomain,
364        Rank::Empire,
365        Rank::Realm,
366        Rank::Subrealm,
367        Rank::Superkingdom,
368        Rank::Kingdom,
369        Rank::Subkingdom,
370        Rank::Infrakingdom,
371        Rank::Superphylum,
372        Rank::Phylum,
373        Rank::Subphylum,
374        Rank::Infraphylum,
375        Rank::Parvphylum,
376        Rank::Microphylum,
377        Rank::Nanophylum,
378        Rank::Claudius,
379        Rank::Gigaclass,
380        Rank::Megaclass,
381        Rank::Superclass,
382        Rank::Class,
383        Rank::Subclass,
384        Rank::Infraclass,
385        Rank::Subterclass,
386        Rank::Parvclass,
387        Rank::Superdivision,
388        Rank::DivisionZoology,
389        Rank::Subdivision,
390        Rank::Infradivision,
391        Rank::Superlegion,
392        Rank::Legion,
393        Rank::Sublegion,
394        Rank::Infralegion,
395        Rank::Megacohort,
396        Rank::Supercohort,
397        Rank::Cohort,
398        Rank::Subcohort,
399        Rank::Infracohort,
400        Rank::Gigaorder,
401        Rank::Magnorder,
402        Rank::Grandorder,
403        Rank::Mirorder,
404        Rank::Superorder,
405        Rank::Order,
406        Rank::Nanorder,
407        Rank::Hypoorder,
408        Rank::Minorder,
409        Rank::Suborder,
410        Rank::Infraorder,
411        Rank::Parvorder,
412        Rank::SupersectionZoology,
413        Rank::SectionZoology,
414        Rank::SubsectionZoology,
415        Rank::SuperseriesZoology,
416        Rank::SeriesZoology,
417        Rank::SubseriesZoology,
418        Rank::Falanx,
419        Rank::Gigafamily,
420        Rank::Megafamily,
421        Rank::Grandfamily,
422        Rank::Superfamily,
423        Rank::Epifamily,
424        Rank::Family,
425        Rank::Subfamily,
426        Rank::Infrafamily,
427        Rank::Supertribe,
428        Rank::Tribe,
429        Rank::Subtribe,
430        Rank::Infratribe,
431        Rank::SupragenericName,
432        Rank::Supergenus,
433        Rank::Genus,
434        Rank::Subgenus,
435        Rank::Infragenus,
436        Rank::DivisionBotany,
437        Rank::SupersectionBotany,
438        Rank::SectionBotany,
439        Rank::SubsectionBotany,
440        Rank::SuperseriesBotany,
441        Rank::SeriesBotany,
442        Rank::SubseriesBotany,
443        Rank::InfragenericName,
444        Rank::SpeciesAggregate,
445        Rank::Species,
446        Rank::InfraspecificName,
447        Rank::Grex,
448        Rank::Klepton,
449        Rank::Subspecies,
450        Rank::CultivarGroup,
451        Rank::Convariety,
452        Rank::InfrasubspecificName,
453        Rank::Proles,
454        Rank::Natio,
455        Rank::Aberration,
456        Rank::Morph,
457        Rank::Supervariety,
458        Rank::Variety,
459        Rank::Subvariety,
460        Rank::Superform,
461        Rank::Form,
462        Rank::Subform,
463        Rank::Pathovar,
464        Rank::Biovar,
465        Rank::Chemovar,
466        Rank::Morphovar,
467        Rank::Phagovar,
468        Rank::Serovar,
469        Rank::Chemoform,
470        Rank::FormaSpecialis,
471        Rank::Lusus,
472        Rank::Cultivar,
473        Rank::Mutatio,
474        Rank::Strain,
475        Rank::Other,
476        Rank::Unranked,
477    ];
478
479    /// Java `Rank.LINNEAN_RANKS` (`Rank.java:313-324`, `public`): the 7 main Linnean ranks,
480    /// ordered. Backs [`Rank::is_linnean`].
481    pub const LINNEAN_RANKS: [Rank; 7] = [
482        Rank::Kingdom,
483        Rank::Phylum,
484        Rank::Class,
485        Rank::Order,
486        Rank::Family,
487        Rank::Genus,
488        Rank::Species,
489    ];
490
491    /// Java `Enum.ordinal()` — this rank's 0-based position in declaration order, i.e. its
492    /// index into [`Rank::ALL`]. Every ordinal-compare predicate below spells this out
493    /// explicitly (`self.ordinal() > Rank::Species.ordinal()`, …) to mirror each Java method
494    /// body line-for-line rather than relying on a derived `Ord`.
495    pub fn ordinal(&self) -> usize {
496        *self as usize
497    }
498
499    /// Java `Rank.getCode()` (`Rank.java:469-474`): the single nomenclatural code a rank
500    /// constant is anchored to (set via that constant's own constructor argument), or
501    /// `None` for a code-agnostic rank (most of them — `Rank`'s own class doc: "The ranks
502    /// listed are code agnostic" unless stated otherwise). Exhaustive `match` grouped by
503    /// code, not a wildcard fallback: a future variant addition gets a compile error here
504    /// until it's assigned a code explicitly. Verified against every one of `Rank.java`'s
505    /// 117 constructor calls (67 code-carrying: 44 `ZOOLOGICAL`, 10 `BOTANICAL`, 7
506    /// `BACTERIAL`, 4 `CULTIVARS`, 2 `VIRUS`; 50 `None`).
507    pub fn code(&self) -> Option<NomCode> {
508        match self {
509            // -> VIRUS (2)
510            Rank::Realm | Rank::Subrealm => Some(NomCode::Virus),
511            // -> ZOOLOGICAL (44)
512            Rank::Parvphylum
513            | Rank::Microphylum
514            | Rank::Nanophylum
515            | Rank::Claudius
516            | Rank::Gigaclass
517            | Rank::Megaclass
518            | Rank::Subterclass
519            | Rank::Parvclass
520            | Rank::Superdivision
521            | Rank::DivisionZoology
522            | Rank::Subdivision
523            | Rank::Infradivision
524            | Rank::Superlegion
525            | Rank::Legion
526            | Rank::Sublegion
527            | Rank::Infralegion
528            | Rank::Megacohort
529            | Rank::Supercohort
530            | Rank::Cohort
531            | Rank::Subcohort
532            | Rank::Infracohort
533            | Rank::Gigaorder
534            | Rank::Magnorder
535            | Rank::Grandorder
536            | Rank::Mirorder
537            | Rank::Nanorder
538            | Rank::Hypoorder
539            | Rank::Minorder
540            | Rank::Parvorder
541            | Rank::SupersectionZoology
542            | Rank::SectionZoology
543            | Rank::SubsectionZoology
544            | Rank::SuperseriesZoology
545            | Rank::SeriesZoology
546            | Rank::SubseriesZoology
547            | Rank::Gigafamily
548            | Rank::Megafamily
549            | Rank::Grandfamily
550            | Rank::Epifamily
551            | Rank::Klepton
552            | Rank::Natio
553            | Rank::Aberration
554            | Rank::Morph
555            | Rank::Mutatio => Some(NomCode::Zoological),
556            // -> BOTANICAL (10)
557            Rank::DivisionBotany
558            | Rank::SupersectionBotany
559            | Rank::SectionBotany
560            | Rank::SubsectionBotany
561            | Rank::SuperseriesBotany
562            | Rank::SeriesBotany
563            | Rank::SubseriesBotany
564            | Rank::Proles
565            | Rank::FormaSpecialis
566            | Rank::Lusus => Some(NomCode::Botanical),
567            // -> CULTIVARS (4)
568            Rank::Grex | Rank::CultivarGroup | Rank::Convariety | Rank::Cultivar => {
569                Some(NomCode::Cultivars)
570            }
571            // -> BACTERIAL (7)
572            Rank::Pathovar
573            | Rank::Biovar
574            | Rank::Chemovar
575            | Rank::Morphovar
576            | Rank::Phagovar
577            | Rank::Serovar
578            | Rank::Chemoform => Some(NomCode::Bacterial),
579            // -> None (50)
580            Rank::Superdomain
581            | Rank::Domain
582            | Rank::Subdomain
583            | Rank::Infradomain
584            | Rank::Empire
585            | Rank::Superkingdom
586            | Rank::Kingdom
587            | Rank::Subkingdom
588            | Rank::Infrakingdom
589            | Rank::Superphylum
590            | Rank::Phylum
591            | Rank::Subphylum
592            | Rank::Infraphylum
593            | Rank::Superclass
594            | Rank::Class
595            | Rank::Subclass
596            | Rank::Infraclass
597            | Rank::Superorder
598            | Rank::Order
599            | Rank::Suborder
600            | Rank::Infraorder
601            | Rank::Falanx
602            | Rank::Superfamily
603            | Rank::Family
604            | Rank::Subfamily
605            | Rank::Infrafamily
606            | Rank::Supertribe
607            | Rank::Tribe
608            | Rank::Subtribe
609            | Rank::Infratribe
610            | Rank::SupragenericName
611            | Rank::Supergenus
612            | Rank::Genus
613            | Rank::Subgenus
614            | Rank::Infragenus
615            | Rank::InfragenericName
616            | Rank::SpeciesAggregate
617            | Rank::Species
618            | Rank::InfraspecificName
619            | Rank::Subspecies
620            | Rank::InfrasubspecificName
621            | Rank::Supervariety
622            | Rank::Variety
623            | Rank::Subvariety
624            | Rank::Superform
625            | Rank::Form
626            | Rank::Subform
627            | Rank::Strain
628            | Rank::Other
629            | Rank::Unranked => None,
630        }
631    }
632
633    /// Java `Rank.isRestrictedToCode()` (`Rank.java:590-597`, `@Deprecated` in favour of
634    /// `getCode()`, kept as a plain alias) — ported for call-site parity with any future
635    /// port that still names it this way.
636    pub fn is_restricted_to_code(&self) -> Option<NomCode> {
637        self.code()
638    }
639
640    /// Java `Rank.getMarker()` (`Rank.java:457-459`): this rank's own marker string literal
641    /// (e.g. `SUBSPECIES` -> `"subsp."`), or `None` for the 3 constants with no marker at
642    /// all (`CULTIVAR_GROUP`, `OTHER`, `UNRANKED`). Exhaustive `match`, grouped by identical
643    /// marker text where Java's own constants share one (the 7 zoology/botany pairs, e.g.
644    /// `SECTION_ZOOLOGY`/`SECTION_BOTANY` both `"sect."`) — verified against every one of
645    /// `Rank.java`'s 117 constructor calls (114 marker-carrying, 3 `None`).
646    pub fn marker(&self) -> Option<&'static str> {
647        match self {
648            Rank::Superdomain => Some("superdom."),
649            Rank::Domain => Some("dom."),
650            Rank::Subdomain => Some("subdom."),
651            Rank::Infradomain => Some("infradom."),
652            Rank::Empire => Some("imp."),
653            Rank::Realm => Some("realm"),
654            Rank::Subrealm => Some("subrealm"),
655            Rank::Superkingdom => Some("superreg."),
656            Rank::Kingdom => Some("regn."),
657            Rank::Subkingdom => Some("subreg."),
658            Rank::Infrakingdom => Some("infrareg."),
659            Rank::Superphylum => Some("superphyl."),
660            Rank::Phylum => Some("phyl."),
661            Rank::Subphylum => Some("subphyl."),
662            Rank::Infraphylum => Some("infraphyl."),
663            Rank::Parvphylum => Some("parvphyl."),
664            Rank::Microphylum => Some("microphyl."),
665            Rank::Nanophylum => Some("nanophyl."),
666            Rank::Claudius => Some("claud."),
667            Rank::Gigaclass => Some("gigacl."),
668            Rank::Megaclass => Some("megacl."),
669            Rank::Superclass => Some("supercl."),
670            Rank::Class => Some("cl."),
671            Rank::Subclass => Some("subcl."),
672            Rank::Infraclass => Some("infracl."),
673            Rank::Subterclass => Some("subtercl."),
674            Rank::Parvclass => Some("parvcl."),
675            Rank::Superdivision => Some("superdiv."),
676            Rank::DivisionZoology | Rank::DivisionBotany => Some("div."),
677            Rank::Subdivision => Some("subdiv."),
678            Rank::Infradivision => Some("infradiv."),
679            Rank::Superlegion => Some("superleg."),
680            Rank::Legion => Some("leg."),
681            Rank::Sublegion => Some("subleg."),
682            Rank::Infralegion => Some("infraleg."),
683            Rank::Megacohort => Some("megacohort"),
684            Rank::Supercohort => Some("supercohort"),
685            Rank::Cohort => Some("cohort"),
686            Rank::Subcohort => Some("subcohort"),
687            Rank::Infracohort => Some("infracohort"),
688            Rank::Gigaorder => Some("gigaord."),
689            Rank::Magnorder => Some("magnord."),
690            Rank::Grandorder => Some("grandord."),
691            Rank::Mirorder => Some("mirord."),
692            Rank::Superorder => Some("superord."),
693            Rank::Order => Some("ord."),
694            Rank::Nanorder => Some("nanord."),
695            Rank::Hypoorder => Some("hypoord."),
696            Rank::Minorder => Some("minord."),
697            Rank::Suborder => Some("subord."),
698            Rank::Infraorder => Some("infraord."),
699            Rank::Parvorder => Some("parvord."),
700            Rank::SupersectionZoology | Rank::SupersectionBotany => Some("supersect."),
701            Rank::SectionZoology | Rank::SectionBotany => Some("sect."),
702            Rank::SubsectionZoology | Rank::SubsectionBotany => Some("subsect."),
703            Rank::SuperseriesZoology | Rank::SuperseriesBotany => Some("superser."),
704            Rank::SeriesZoology | Rank::SeriesBotany => Some("ser."),
705            Rank::SubseriesZoology | Rank::SubseriesBotany => Some("subser."),
706            Rank::Falanx => Some("falanx"),
707            Rank::Gigafamily => Some("gigafam."),
708            Rank::Megafamily => Some("megafam."),
709            Rank::Grandfamily => Some("grandfam."),
710            Rank::Superfamily => Some("superfam."),
711            Rank::Epifamily => Some("epifam."),
712            Rank::Family => Some("fam."),
713            Rank::Subfamily => Some("subfam."),
714            Rank::Infrafamily => Some("infrafam."),
715            Rank::Supertribe => Some("supertrib."),
716            Rank::Tribe => Some("trib."),
717            Rank::Subtribe => Some("subtrib."),
718            Rank::Infratribe => Some("infratrib."),
719            Rank::SupragenericName => Some("supragen."),
720            Rank::Supergenus => Some("supergen."),
721            Rank::Genus => Some("gen."),
722            Rank::Subgenus => Some("subgen."),
723            Rank::Infragenus => Some("infrag."),
724            Rank::InfragenericName => Some("infragen."),
725            Rank::SpeciesAggregate => Some("agg."),
726            Rank::Species => Some("sp."),
727            Rank::InfraspecificName => Some("infrasp."),
728            Rank::Grex => Some("gx"),
729            Rank::Klepton => Some("klepton"),
730            Rank::Subspecies => Some("subsp."),
731            Rank::Convariety => Some("convar."),
732            Rank::InfrasubspecificName => Some("infrasubsp."),
733            Rank::Proles => Some("prol."),
734            Rank::Natio => Some("natio"),
735            Rank::Aberration => Some("ab."),
736            Rank::Morph => Some("morph"),
737            Rank::Supervariety => Some("supervar."),
738            Rank::Variety => Some("var."),
739            Rank::Subvariety => Some("subvar."),
740            Rank::Superform => Some("superf."),
741            Rank::Form => Some("f."),
742            Rank::Subform => Some("subf."),
743            Rank::Pathovar => Some("pv."),
744            Rank::Biovar => Some("biovar"),
745            Rank::Chemovar => Some("chemovar"),
746            Rank::Morphovar => Some("morphovar"),
747            Rank::Phagovar => Some("phagovar"),
748            Rank::Serovar => Some("serovar"),
749            Rank::Chemoform => Some("chemoform"),
750            Rank::FormaSpecialis => Some("f.sp."),
751            Rank::Lusus => Some("lusus"),
752            Rank::Cultivar => Some("cv."),
753            Rank::Mutatio => Some("mut."),
754            Rank::Strain => Some("strain"),
755            Rank::CultivarGroup | Rank::Other | Rank::Unranked => None,
756        }
757    }
758
759    /// Java `Rank.getPlural()` (`Rank.java:465-467`): this rank's plural word — either the
760    /// explicit third constructor argument, or (when a rank has a marker but no explicit
761    /// plural) Java's own default `rank.name().toLowerCase() + "s"` computed once and
762    /// transcribed here literally. That default is applied VERBATIM even where it reads
763    /// oddly (e.g. `DIVISION_ZOOLOGY` -> `"division_zoologys"`, `SECTION_BOTANY` ->
764    /// `"section_botanys"` — the Java default never strips the constant's own `_` word
765    /// separators before appending `"s"`) — faithful port, not a fix. `None` for the same 3
766    /// markerless constants as [`Rank::marker`] (a rank's `plural` field is only ever set
767    /// alongside a `marker` in every one of Java's 5 constructors).
768    pub fn plural(&self) -> Option<&'static str> {
769        match self {
770            Rank::Superdomain => Some("superdomains"),
771            Rank::Domain => Some("domains"),
772            Rank::Subdomain => Some("subdomains"),
773            Rank::Infradomain => Some("infradomains"),
774            Rank::Empire => Some("empires"),
775            Rank::Realm => Some("realms"),
776            Rank::Subrealm => Some("subrealms"),
777            Rank::Superkingdom => Some("superkingdoms"),
778            Rank::Kingdom => Some("kingdoms"),
779            Rank::Subkingdom => Some("subkingdoms"),
780            Rank::Infrakingdom => Some("infrakingdoms"),
781            Rank::Superphylum => Some("superphyla"),
782            Rank::Phylum => Some("phyla"),
783            Rank::Subphylum => Some("subphyla"),
784            Rank::Infraphylum => Some("infraphyla"),
785            Rank::Parvphylum => Some("parvphyla"),
786            Rank::Microphylum => Some("microphyla"),
787            Rank::Nanophylum => Some("nanophyla"),
788            Rank::Claudius => Some("claudius"),
789            Rank::Gigaclass => Some("gigaclasses"),
790            Rank::Megaclass => Some("megaclasses"),
791            Rank::Superclass => Some("superclasses"),
792            Rank::Class => Some("classes"),
793            Rank::Subclass => Some("subclasses"),
794            Rank::Infraclass => Some("infraclasses"),
795            Rank::Subterclass => Some("subterclasses"),
796            Rank::Parvclass => Some("parvclasses"),
797            Rank::Superdivision => Some("superdivisions"),
798            Rank::DivisionZoology => Some("division_zoologys"),
799            Rank::Subdivision => Some("subdivisions"),
800            Rank::Infradivision => Some("infradivisions"),
801            Rank::Superlegion => Some("superlegions"),
802            Rank::Legion => Some("legions"),
803            Rank::Sublegion => Some("sublegions"),
804            Rank::Infralegion => Some("infralegions"),
805            Rank::Megacohort => Some("megacohorts"),
806            Rank::Supercohort => Some("supercohorts"),
807            Rank::Cohort => Some("cohorts"),
808            Rank::Subcohort => Some("subcohorts"),
809            Rank::Infracohort => Some("infracohorts"),
810            Rank::Gigaorder => Some("gigaorders"),
811            Rank::Magnorder => Some("magnorders"),
812            Rank::Grandorder => Some("grandorders"),
813            Rank::Mirorder => Some("mirorders"),
814            Rank::Superorder => Some("superorders"),
815            Rank::Order => Some("orders"),
816            Rank::Nanorder => Some("nanorders"),
817            Rank::Hypoorder => Some("hypoorders"),
818            Rank::Minorder => Some("minorders"),
819            Rank::Suborder => Some("suborders"),
820            Rank::Infraorder => Some("infraorders"),
821            Rank::Parvorder => Some("parvorders"),
822            Rank::SupersectionZoology => Some("supersection_zoologys"),
823            Rank::SectionZoology => Some("section_zoologys"),
824            Rank::SubsectionZoology => Some("subsection_zoologys"),
825            Rank::SuperseriesZoology | Rank::SuperseriesBotany => Some("superseries"),
826            Rank::SeriesZoology | Rank::SeriesBotany => Some("series"),
827            Rank::SubseriesZoology | Rank::SubseriesBotany => Some("subseries"),
828            Rank::Falanx => Some("falanges"),
829            Rank::Gigafamily => Some("gigafamilies"),
830            Rank::Megafamily => Some("megafamilies"),
831            Rank::Grandfamily => Some("grandfamilies"),
832            Rank::Superfamily => Some("superfamilies"),
833            Rank::Epifamily => Some("epifamilies"),
834            Rank::Family => Some("families"),
835            Rank::Subfamily => Some("subfamilies"),
836            Rank::Infrafamily => Some("infrafamilies"),
837            Rank::Supertribe => Some("supertribes"),
838            Rank::Tribe => Some("tribes"),
839            Rank::Subtribe => Some("subtribes"),
840            Rank::Infratribe => Some("infratribes"),
841            Rank::SupragenericName => Some("suprageneric_names"),
842            Rank::Supergenus => Some("supergenera"),
843            Rank::Genus => Some("genera"),
844            Rank::Subgenus => Some("subgenera"),
845            Rank::Infragenus => Some("infragenera"),
846            Rank::DivisionBotany => Some("divisions"),
847            Rank::SupersectionBotany => Some("supersection_botanys"),
848            Rank::SectionBotany => Some("section_botanys"),
849            Rank::SubsectionBotany => Some("subsection_botanys"),
850            Rank::InfragenericName => Some("infrageneric_names"),
851            Rank::SpeciesAggregate => Some("species_aggregates"),
852            Rank::Species => Some("species"),
853            Rank::InfraspecificName => Some("infraspecific_names"),
854            Rank::Grex => Some("grexs"),
855            Rank::Klepton => Some("kleptons"),
856            Rank::Subspecies => Some("subspecies"),
857            Rank::Convariety => Some("convarieties"),
858            Rank::InfrasubspecificName => Some("infrasubspecific_names"),
859            Rank::Proles => Some("proles"),
860            Rank::Natio => Some("natios"),
861            Rank::Aberration => Some("aberrations"),
862            Rank::Morph => Some("morphs"),
863            Rank::Supervariety => Some("supervarieties"),
864            Rank::Variety => Some("varieties"),
865            Rank::Subvariety => Some("subvarieties"),
866            Rank::Superform => Some("superforms"),
867            Rank::Form => Some("forms"),
868            Rank::Subform => Some("subforms"),
869            Rank::Pathovar => Some("pathovars"),
870            Rank::Biovar => Some("biovars"),
871            Rank::Chemovar => Some("chemovars"),
872            Rank::Morphovar => Some("morphovars"),
873            Rank::Phagovar => Some("phagovars"),
874            Rank::Serovar => Some("serovars"),
875            Rank::Chemoform => Some("chemoforms"),
876            Rank::FormaSpecialis => Some("forma_specialiss"),
877            Rank::Lusus => Some("lusi"),
878            Rank::Cultivar => Some("cultivars"),
879            Rank::Mutatio => Some("mutatios"),
880            Rank::Strain => Some("strains"),
881            Rank::CultivarGroup | Rank::Other | Rank::Unranked => None,
882        }
883    }
884
885    /// Java `Rank.hasAmbiguousMarker()` (`Rank.java:461-463`). See [`AMBIGUOUS_MARKER`].
886    pub fn has_ambiguous_marker(&self) -> bool {
887        AMBIGUOUS_MARKER.contains(self)
888    }
889
890    /// Java `Rank.notOtherOrUnranked()` (`Rank.java:529-531`).
891    pub fn not_other_or_unranked(&self) -> bool {
892        *self != Rank::Other && *self != Rank::Unranked
893    }
894
895    /// Java `Rank.otherOrUnranked()` (`Rank.java:533-535`).
896    pub fn other_or_unranked(&self) -> bool {
897        !self.not_other_or_unranked()
898    }
899
900    /// Java `Rank.isInfraspecific()` (`Rank.java:476-481`): true for infraspecific ranks,
901    /// excluding `SPECIES` itself.
902    pub fn is_infraspecific(&self) -> bool {
903        self.ordinal() > Rank::Species.ordinal() && self.not_other_or_unranked()
904    }
905
906    /// Java `Rank.isInfrageneric()` (`Rank.java:490-495`): true for any rank below genus —
907    /// also true for species and infraspecific ranks (see [`Rank::is_infrageneric_strictly`]
908    /// for the narrower, "strictly infrageneric" version).
909    pub fn is_infrageneric(&self) -> bool {
910        self.ordinal() > Rank::Genus.ordinal() && self.not_other_or_unranked()
911    }
912
913    /// Java `Rank.isInfragenericStrictly()` (`Rank.java:497-502`): true for real
914    /// infrageneric ranks (an infrageneric epithet, strictly below genus and above species
915    /// aggregate) — e.g. `SUBGENUS`, `SECTION_BOTANY`. Replaces the former ad-hoc
916    /// `authorship_split::rank_is_infrageneric_strictly`.
917    pub fn is_infrageneric_strictly(&self) -> bool {
918        self.is_infrageneric() && self.ordinal() < Rank::SpeciesAggregate.ordinal()
919    }
920
921    /// Java `Rank.isLinnean()` (`Rank.java:504-514`): true for the 7 main Linnean ranks.
922    pub fn is_linnean(&self) -> bool {
923        Self::LINNEAN_RANKS.contains(self)
924    }
925
926    /// Java `Rank.getMajorRank()` (`Rank.java:516-523`): the major rank (incl. all Linnean
927    /// ranks) this rank belongs to, stripping its prefix (e.g. `PHYLUM` for `SUBPHYLUM`).
928    /// Infraspecific ranks return `INFRASPECIFIC_NAME`. Ranks that can't be mapped to a
929    /// major rank return themselves — never a sentinel/`None` (matches Java's own doc:
930    /// "never null"). See [`MAJOR_RANKS`].
931    pub fn get_major_rank(&self) -> Rank {
932        *MAJOR_RANKS
933            .get(self)
934            .expect("MAJOR_RANKS is populated for every Rank in Rank::ALL")
935    }
936
937    /// Java `Rank.isSpeciesOrBelow()` (`Rank.java:525-527`).
938    pub fn is_species_or_below(&self) -> bool {
939        self.ordinal() >= Rank::SpeciesAggregate.ordinal() && self.not_other_or_unranked()
940    }
941
942    /// Java `Rank.isFamilyGroup()` (`Rank.java:537-542`): true for family-group ranks,
943    /// between `GIGAFAMILY` (inclusive) and `GENUS`-side `SUPRAGENERIC_NAME` (exclusive).
944    pub fn is_family_group(&self) -> bool {
945        Rank::Gigafamily.ordinal() <= self.ordinal()
946            && self.ordinal() < Rank::SupragenericName.ordinal()
947    }
948
949    /// Java `Rank.isGenusGroup()` (`Rank.java:544-549`): true for genus-group ranks,
950    /// between `SUPERGENUS` (inclusive) and `SPECIES_AGGREGATE` (exclusive).
951    pub fn is_genus_group(&self) -> bool {
952        Rank::Supergenus.ordinal() <= self.ordinal()
953            && self.ordinal() < Rank::SpeciesAggregate.ordinal()
954    }
955
956    /// Java `Rank.isSuprageneric()` (`Rank.java:551-556`): true for any rank above genus.
957    pub fn is_suprageneric(&self) -> bool {
958        self.ordinal() < Rank::Genus.ordinal()
959    }
960
961    /// Java `Rank.isUncomparable()` (`Rank.java:572-581`). See [`UNCOMPARABLE_RANKS`].
962    pub fn is_uncomparable(&self) -> bool {
963        UNCOMPARABLE_RANKS.contains(self)
964    }
965
966    /// Java `Rank.isLegacy()` (`Rank.java:583-588`). See [`LEGACY_RANKS`].
967    pub fn is_legacy(&self) -> bool {
968        LEGACY_RANKS.contains(self)
969    }
970
971    /// Java `Rank.higherThan(Rank)` (`Rank.java:606-613`): true if this rank is higher than
972    /// `other`, excluding `OTHER`/`UNRANKED` from the comparison (checked on `other`, not
973    /// `self` — this asymmetry with [`Rank::lower_than`] is exactly Java's own).
974    pub fn higher_than(&self, other: Rank) -> bool {
975        self.ordinal() < other.ordinal() && other.not_other_or_unranked()
976    }
977
978    /// Java `Rank.lowerThan(Rank)` (`Rank.java:615-622`): true if this rank is lower than
979    /// `other`, excluding `OTHER`/`UNRANKED` from the comparison (checked on `self`, not
980    /// `other` — see [`Rank::higher_than`]'s doc comment for the same asymmetry).
981    pub fn lower_than(&self, other: Rank) -> bool {
982        self.ordinal() > other.ordinal() && self.not_other_or_unranked()
983    }
984}
985
986/// Phase 3 (FFM binding) additions — purely additive, nothing above this point is touched.
987/// The FFI crate (`nameparser-ffi`) needs to turn a Java `Rank.name()` / `NomCode.name()`
988/// string (received across the C ABI as a plain `&str`) back into the corresponding enum
989/// variant. Neither `Rank` nor `NomCode` derives `serde::Deserialize` (only `Serialize`, for
990/// the wire-JSON output direction), so this is a hand-written reverse lookup rather than a
991/// `serde_json::from_value` round-trip.
992impl Rank {
993    /// Looks up a variant by its serialized SCREAMING_SNAKE name (Java `Rank.name()`), the
994    /// exact inverse of [`rank_wire_name`] — which itself is built on this type's own
995    /// `Serialize` impl, so `from_name` can never silently drift from the wire form it
996    /// reverses. A linear scan over all 117 variants; `Rank::from_name` is only ever called
997    /// once per FFI parse call, not in a hot inner loop. Returns `None` for an unrecognized
998    /// name — mirrors Java's `Rank.valueOf(name)` throwing `IllegalArgumentException`, folded
999    /// to `None`/absent here since the FFI caller treats an unrecognized rank hint the same
1000    /// as an absent one rather than propagating a Java exception type across the C ABI.
1001    pub fn from_name(name: &str) -> Option<Rank> {
1002        Rank::ALL
1003            .iter()
1004            .copied()
1005            .find(|&r| rank_wire_name(r) == name)
1006    }
1007}
1008
1009impl NomCode {
1010    /// Looks up a variant by its serialized SCREAMING_SNAKE name (Java `NomCode.name()`).
1011    /// A hand-written match, unlike [`Rank::from_name`], since `NomCode` has no `ALL`-style
1012    /// constant to reverse-search over — but each arm's string literal is exactly this type's
1013    /// own `#[serde(rename_all = "SCREAMING_SNAKE_CASE")]` output for that variant, pinned
1014    /// against the real `Serialize` impl by
1015    /// `nomcode_from_name_round_trips_every_variant_via_its_own_serialize_impl` below, so the
1016    /// two representations cannot silently drift apart. Returns `None` for an unrecognized
1017    /// name, same rationale as `Rank::from_name`.
1018    pub fn from_name(name: &str) -> Option<NomCode> {
1019        match name {
1020            "BACTERIAL" => Some(NomCode::Bacterial),
1021            "BOTANICAL" => Some(NomCode::Botanical),
1022            "CULTIVARS" => Some(NomCode::Cultivars),
1023            "PHYTO" => Some(NomCode::Phyto),
1024            "VIRUS" => Some(NomCode::Virus),
1025            "ZOOLOGICAL" => Some(NomCode::Zoological),
1026            "PHYLO" => Some(NomCode::Phylo),
1027            _ => None,
1028        }
1029    }
1030}
1031
1032/// Java `org.gbif.nameparser.util.RankUtils`'s rank-lookup statics not already covered by
1033/// `Rank`'s own instance methods — ported as a `pub mod` the same way `Warnings` (a separate
1034/// Java class) is ported as this file's own `pub mod warnings` below.
1035///
1036/// **Not ported: `RankUtils.GLOBAL_SUFFICES_RANK_MAP`** (`RankUtils.java:262-292`, the
1037/// cross-code-deduplicated, length-sorted derivative of `SUFFICES_RANK_MAP`). It backs only
1038/// `RankUtils.inferRank(LinneanName)`, a public utility method no Phase 1 pipeline stage
1039/// calls — confirmed by reading `Assemble.java` itself: its own `rankFromGlobalSuffix`
1040/// helper (the "no code known" fallback for step 14) hardcodes exactly the two globally
1041/// unambiguous suffixes ("aceae"/"oideae") rather than consulting the derived global map at
1042/// all. Porting `GLOBAL_SUFFICES_RANK_MAP`'s length-then-alphabetical custom `Comparator`
1043/// and cross-code non-unique-key removal would be pure dead weight for this crate's actual
1044/// call graph; left unported with this note rather than stubbed.
1045pub mod rank_utils {
1046    use super::{NomCode, Rank};
1047
1048    /// Java `RankUtils.SUFFICES_RANK_MAP` (`RankUtils.java:204-260`): per-`NomCode`
1049    /// name-suffix -> `Rank` lookup, used by `Assemble.rankFromSuffix` (Phase 1 Slice 4
1050    /// Task 3's "step 14" — suffix-based rank inference for a monomial once its code is
1051    /// known, e.g. bacterial "...aceae" -> `FAMILY`). Each code's list is manually ordered
1052    /// longest/most-specific-suffix first in Java's own source (that field's own doc
1053    /// comment) — NOT re-sorted here; slice iteration order is exactly Java's
1054    /// `LinkedHashMap` insertion order, so a first-match-wins linear scan by the consuming
1055    /// task (`.iter().find(|(suffix, _)| name.ends_with(suffix))`) reproduces the same
1056    /// "most specific first" behaviour with no sort needed on either side. Only the 4 codes
1057    /// below appear at all in Java's map (`CULTIVARS`/`PHYTO`/`PHYLO` have no entry, matching
1058    /// `Map.of(...)`'s fixed 4-key literal) — `None` for those three, mirroring `Map.get`'s
1059    /// null for an absent key (`Assemble.rankFromSuffix`'s own `if (suffixes == null) return
1060    /// null;` guard).
1061    pub fn suffices_rank_map(code: NomCode) -> Option<&'static [(&'static str, Rank)]> {
1062        match code {
1063            NomCode::Bacterial => Some(&[
1064                ("oideae", Rank::Subfamily),
1065                ("aceae", Rank::Family),
1066                ("ineae", Rank::Suborder),
1067                ("ales", Rank::Order),
1068                ("idae", Rank::Subclass),
1069                ("inae", Rank::Subtribe),
1070                ("eae", Rank::Tribe),
1071                ("ia", Rank::Class),
1072            ]),
1073            NomCode::Botanical => Some(&[
1074                ("mycetidae", Rank::Subclass),
1075                ("phycidae", Rank::Subclass),
1076                ("mycotina", Rank::Subphylum),
1077                ("phytina", Rank::Subphylum),
1078                ("mycetes", Rank::Class),
1079                ("phyceae", Rank::Class),
1080                ("mycota", Rank::Phylum),
1081                ("opsida", Rank::Class),
1082                ("oideae", Rank::Subfamily),
1083                ("phyta", Rank::Phylum),
1084                ("ineae", Rank::Suborder),
1085                ("aceae", Rank::Family),
1086                ("idae", Rank::Subclass),
1087                ("anae", Rank::Superorder),
1088                ("acea", Rank::Superfamily),
1089                ("aria", Rank::Infraorder),
1090                ("ales", Rank::Order),
1091                ("inae", Rank::Subtribe),
1092                ("eae", Rank::Tribe),
1093            ]),
1094            NomCode::Zoological => Some(&[
1095                ("oidea", Rank::Superfamily),
1096                ("oidae", Rank::Epifamily),
1097                ("idae", Rank::Family),
1098                ("inae", Rank::Subfamily),
1099                ("ini", Rank::Tribe),
1100                ("ina", Rank::Subtribe),
1101            ]),
1102            NomCode::Virus => Some(&[
1103                ("viricetidae", Rank::Subclass),
1104                ("viricotina", Rank::Subphylum),
1105                ("viricetes", Rank::Class),
1106                ("viricota", Rank::Phylum),
1107                ("virineae", Rank::Suborder),
1108                ("virites", Rank::Subkingdom),
1109                ("virales", Rank::Order),
1110                ("viridae", Rank::Family),
1111                ("virinae", Rank::Subfamily),
1112                ("viriae", Rank::Kingdom),
1113                ("viria", Rank::Realm),
1114                ("vira", Rank::Subrealm),
1115            ]),
1116            NomCode::Cultivars | NomCode::Phyto | NomCode::Phylo => None,
1117        }
1118    }
1119}
1120
1121/// String constants from `org.gbif.nameparser.api.Warnings`, transcribed verbatim (values, not
1122/// the Java constant names, though names are kept identical — including `HOMOGLYHPS`, which is
1123/// a typo in the Java constant name itself, not in its value — so call sites ported later match
1124/// the Java source 1:1).
1125pub mod warnings {
1126    pub const NULL_EPITHET: &str = "epithet with literal value null";
1127    /// NB: `HOMOGLYHPS` is the Java constant name's own typo (for "homoglyphs"); kept verbatim.
1128    pub const HOMOGLYHPS: &str = "homoglyphs replaced";
1129    pub const UNUSUAL_CHARACTERS: &str = "unusual characters";
1130    pub const SUBSPECIES_ASSIGNED: &str =
1131        "Name was considered species but contains infraspecific epithet";
1132    pub const LC_MONOMIAL: &str = "lower case monomial match";
1133    pub const INDETERMINED: &str = "indetermined name missing its terminal epithet";
1134    pub const HIGHER_RANK_BINOMIAL: &str = "binomial with rank higher than species aggregate";
1135    pub const QUESTION_MARKS_REMOVED: &str = "question marks removed";
1136    pub const REPL_ENCLOSING_QUOTE: &str = "removed enclosing quotes";
1137    pub const MISSING_GENUS: &str = "epithet without genus";
1138    pub const DOUBTFUL_GENUS: &str = "genus quoted or in square brackets";
1139    pub const RANK_MISMATCH: &str = "rank does not fit the parsed name";
1140    pub const CODE_MISMATCH: &str = "nomenclatural code does not fit the parsed name";
1141    pub const HTML_ENTITIES: &str = "html entities unescaped";
1142    pub const XML_TAGS: &str = "xml tags removed";
1143    pub const BLACKLISTED_EPITHET: &str = "blacklisted epithet used";
1144    pub const NOMENCLATURAL_REFERENCE: &str = "nomenclatural reference removed";
1145    pub const AUTHORSHIP_REMOVED: &str = "authorship placeholder removed";
1146    /// NB: "was extract" (not "was extracted") is verbatim from the Java source.
1147    pub const YEAR_INTERPRETED: &str =
1148        "authorship year was extract but originally was a year range or other form of year";
1149    pub const UNLIKELY_YEAR: &str = "unlikely authorship year";
1150    pub const UNCERTAIN_AUTHORSHIP: &str = "authorship marked as uncertain";
1151    pub const QUADRINOMIAL: &str = "name was quadrinomial";
1152    pub const ABBREVIATED_GENUS: &str = "abbreviated genus name";
1153    pub const ABBREVIATED_SUBGENUS: &str = "abbreviated subgenus name";
1154    /// NB: trailing space before the closing quote is verbatim from the Java source.
1155    pub const REMOVED_PREFIX: &str = "Removed: ";
1156    pub const LONG_NAME: &str = "unusually long name";
1157}
1158
1159#[cfg(test)]
1160mod tests {
1161    use super::*;
1162
1163    #[test]
1164    fn name_type_scientific_serializes_uppercase() {
1165        assert_eq!(
1166            serde_json::to_string(&NameType::Scientific).unwrap(),
1167            "\"SCIENTIFIC\""
1168        );
1169    }
1170
1171    #[test]
1172    fn name_type_first_and_last_variant() {
1173        assert_eq!(
1174            serde_json::to_string(&NameType::Scientific).unwrap(),
1175            "\"SCIENTIFIC\""
1176        );
1177        assert_eq!(
1178            serde_json::to_string(&NameType::Other).unwrap(),
1179            "\"OTHER\""
1180        );
1181    }
1182
1183    #[test]
1184    fn nom_code_first_last_and_zoological() {
1185        assert_eq!(
1186            serde_json::to_string(&NomCode::Bacterial).unwrap(),
1187            "\"BACTERIAL\""
1188        );
1189        assert_eq!(serde_json::to_string(&NomCode::Phylo).unwrap(), "\"PHYLO\"");
1190        assert_eq!(
1191            serde_json::to_string(&NomCode::Zoological).unwrap(),
1192            "\"ZOOLOGICAL\""
1193        );
1194    }
1195
1196    #[test]
1197    fn name_part_first_and_last_variant() {
1198        assert_eq!(
1199            serde_json::to_string(&NamePart::Generic).unwrap(),
1200            "\"GENERIC\""
1201        );
1202        assert_eq!(
1203            serde_json::to_string(&NamePart::Infraspecific).unwrap(),
1204            "\"INFRASPECIFIC\""
1205        );
1206    }
1207
1208    #[test]
1209    fn state_first_and_last_variant() {
1210        assert_eq!(
1211            serde_json::to_string(&State::Complete).unwrap(),
1212            "\"COMPLETE\""
1213        );
1214        assert_eq!(serde_json::to_string(&State::None).unwrap(), "\"NONE\"");
1215    }
1216
1217    #[test]
1218    fn rank_stub_unranked() {
1219        assert_eq!(
1220            serde_json::to_string(&Rank::Unranked).unwrap(),
1221            "\"UNRANKED\""
1222        );
1223    }
1224
1225    #[test]
1226    fn rank_stub_species_and_subspecies() {
1227        assert_eq!(
1228            serde_json::to_string(&Rank::Species).unwrap(),
1229            "\"SPECIES\""
1230        );
1231        assert_eq!(
1232            serde_json::to_string(&Rank::Subspecies).unwrap(),
1233            "\"SUBSPECIES\""
1234        );
1235    }
1236
1237    /// Phase 1 Slice 2 batch 2b additions: `StripAndStash::strip_nom_note`'s rank-hint
1238    /// switch (Genus/Family/Variety/Form) and `strip_cultivar_group_grex`/
1239    /// `strip_quoted_cultivar` (Cultivar/CultivarGroup/Grex) — verifies the
1240    /// `SCREAMING_SNAKE_CASE` rename produces the exact Java enum constant name for each,
1241    /// in particular that `CultivarGroup`'s two-word boundary renders as the
1242    /// underscore-joined `CULTIVAR_GROUP` Java uses (`Rank.CULTIVAR_GROUP`).
1243    #[test]
1244    fn rank_stub_batch_2b_variants() {
1245        assert_eq!(serde_json::to_string(&Rank::Genus).unwrap(), "\"GENUS\"");
1246        assert_eq!(serde_json::to_string(&Rank::Family).unwrap(), "\"FAMILY\"");
1247        assert_eq!(
1248            serde_json::to_string(&Rank::Variety).unwrap(),
1249            "\"VARIETY\""
1250        );
1251        assert_eq!(serde_json::to_string(&Rank::Form).unwrap(), "\"FORM\"");
1252        assert_eq!(
1253            serde_json::to_string(&Rank::Cultivar).unwrap(),
1254            "\"CULTIVAR\""
1255        );
1256        assert_eq!(
1257            serde_json::to_string(&Rank::CultivarGroup).unwrap(),
1258            "\"CULTIVAR_GROUP\""
1259        );
1260        assert_eq!(serde_json::to_string(&Rank::Grex).unwrap(), "\"GREX\"");
1261    }
1262
1263    /// Phase 1 Slice 2 batch 2e additions: `StripAndStash` steps 53-55's suprageneric
1264    /// family-group ranks (step 53) and the infrageneric botany/zoology section-series
1265    /// pairs (step 54's `RANK_MARKER_MAP_INFRAGENERIC` subset + `BOT_TO_ZOOL`) — verifies
1266    /// the `SCREAMING_SNAKE_CASE` rename produces the exact Java enum constant name for
1267    /// each, in particular that the two-word `*Botany`/`*Zoology` variants render with the
1268    /// underscore Java uses (`Rank.SECTION_BOTANY`, `Rank.SUPERSERIES_ZOOLOGY`).
1269    #[test]
1270    fn rank_stub_batch_2e_variants() {
1271        assert_eq!(
1272            serde_json::to_string(&Rank::Subfamily).unwrap(),
1273            "\"SUBFAMILY\""
1274        );
1275        assert_eq!(serde_json::to_string(&Rank::Tribe).unwrap(), "\"TRIBE\"");
1276        assert_eq!(
1277            serde_json::to_string(&Rank::Subtribe).unwrap(),
1278            "\"SUBTRIBE\""
1279        );
1280        assert_eq!(
1281            serde_json::to_string(&Rank::Supertribe).unwrap(),
1282            "\"SUPERTRIBE\""
1283        );
1284        assert_eq!(
1285            serde_json::to_string(&Rank::Infratribe).unwrap(),
1286            "\"INFRATRIBE\""
1287        );
1288        assert_eq!(
1289            serde_json::to_string(&Rank::Subgenus).unwrap(),
1290            "\"SUBGENUS\""
1291        );
1292        assert_eq!(
1293            serde_json::to_string(&Rank::SectionBotany).unwrap(),
1294            "\"SECTION_BOTANY\""
1295        );
1296        assert_eq!(
1297            serde_json::to_string(&Rank::SubsectionBotany).unwrap(),
1298            "\"SUBSECTION_BOTANY\""
1299        );
1300        assert_eq!(
1301            serde_json::to_string(&Rank::SupersectionBotany).unwrap(),
1302            "\"SUPERSECTION_BOTANY\""
1303        );
1304        assert_eq!(
1305            serde_json::to_string(&Rank::SeriesBotany).unwrap(),
1306            "\"SERIES_BOTANY\""
1307        );
1308        assert_eq!(
1309            serde_json::to_string(&Rank::SubseriesBotany).unwrap(),
1310            "\"SUBSERIES_BOTANY\""
1311        );
1312        assert_eq!(
1313            serde_json::to_string(&Rank::SuperseriesBotany).unwrap(),
1314            "\"SUPERSERIES_BOTANY\""
1315        );
1316        assert_eq!(
1317            serde_json::to_string(&Rank::SectionZoology).unwrap(),
1318            "\"SECTION_ZOOLOGY\""
1319        );
1320        assert_eq!(
1321            serde_json::to_string(&Rank::SubsectionZoology).unwrap(),
1322            "\"SUBSECTION_ZOOLOGY\""
1323        );
1324        assert_eq!(
1325            serde_json::to_string(&Rank::SupersectionZoology).unwrap(),
1326            "\"SUPERSECTION_ZOOLOGY\""
1327        );
1328        assert_eq!(
1329            serde_json::to_string(&Rank::SeriesZoology).unwrap(),
1330            "\"SERIES_ZOOLOGY\""
1331        );
1332        assert_eq!(
1333            serde_json::to_string(&Rank::SubseriesZoology).unwrap(),
1334            "\"SUBSERIES_ZOOLOGY\""
1335        );
1336        assert_eq!(
1337            serde_json::to_string(&Rank::SuperseriesZoology).unwrap(),
1338            "\"SUPERSERIES_ZOOLOGY\""
1339        );
1340    }
1341
1342    /// Phase 1 Slice 3 Task 1 additions: every `Rank` value the two `RankMarkers` maps
1343    /// (`pipeline::rank_markers`) reference that wasn't already present — verifies the
1344    /// `SCREAMING_SNAKE_CASE` rename produces the exact Java enum constant name for each,
1345    /// in particular the two-word `InfraspecificName`/`DivisionBotany` (`INFRASPECIFIC_NAME`
1346    /// / `DIVISION_BOTANY`, matching Java's own multi-word constants).
1347    #[test]
1348    fn rank_stub_slice3_task1_variants() {
1349        assert_eq!(serde_json::to_string(&Rank::Other).unwrap(), "\"OTHER\"");
1350        assert_eq!(
1351            serde_json::to_string(&Rank::Subvariety).unwrap(),
1352            "\"SUBVARIETY\""
1353        );
1354        assert_eq!(
1355            serde_json::to_string(&Rank::Subform).unwrap(),
1356            "\"SUBFORM\""
1357        );
1358        assert_eq!(
1359            serde_json::to_string(&Rank::Pathovar).unwrap(),
1360            "\"PATHOVAR\""
1361        );
1362        assert_eq!(serde_json::to_string(&Rank::Biovar).unwrap(), "\"BIOVAR\"");
1363        assert_eq!(
1364            serde_json::to_string(&Rank::Chemoform).unwrap(),
1365            "\"CHEMOFORM\""
1366        );
1367        assert_eq!(
1368            serde_json::to_string(&Rank::Serovar).unwrap(),
1369            "\"SEROVAR\""
1370        );
1371        assert_eq!(serde_json::to_string(&Rank::Morph).unwrap(), "\"MORPH\"");
1372        assert_eq!(
1373            serde_json::to_string(&Rank::Morphovar).unwrap(),
1374            "\"MORPHOVAR\""
1375        );
1376        assert_eq!(
1377            serde_json::to_string(&Rank::Phagovar).unwrap(),
1378            "\"PHAGOVAR\""
1379        );
1380        assert_eq!(serde_json::to_string(&Rank::Natio).unwrap(), "\"NATIO\"");
1381        assert_eq!(
1382            serde_json::to_string(&Rank::Mutatio).unwrap(),
1383            "\"MUTATIO\""
1384        );
1385        assert_eq!(
1386            serde_json::to_string(&Rank::Convariety).unwrap(),
1387            "\"CONVARIETY\""
1388        );
1389        assert_eq!(serde_json::to_string(&Rank::Proles).unwrap(), "\"PROLES\"");
1390        assert_eq!(
1391            serde_json::to_string(&Rank::Aberration).unwrap(),
1392            "\"ABERRATION\""
1393        );
1394        assert_eq!(serde_json::to_string(&Rank::Strain).unwrap(), "\"STRAIN\"");
1395        assert_eq!(
1396            serde_json::to_string(&Rank::InfraspecificName).unwrap(),
1397            "\"INFRASPECIFIC_NAME\""
1398        );
1399        assert_eq!(
1400            serde_json::to_string(&Rank::DivisionBotany).unwrap(),
1401            "\"DIVISION_BOTANY\""
1402        );
1403    }
1404
1405    /// Phase 1 Slice 3 Task 3 additions (`NameTokens`): the three bare `Rank.XXX` literals
1406    /// `NameTokens.classify` references that Task 1's `RankMarkers` maps didn't already pull
1407    /// in — verifies the `SCREAMING_SNAKE_CASE` rename produces the exact Java enum constant
1408    /// name for each, in particular that `FormaSpecialis`'s two-word boundary renders as the
1409    /// underscore-joined `FORMA_SPECIALIS` Java uses.
1410    #[test]
1411    fn rank_stub_slice3_task3_variants() {
1412        assert_eq!(
1413            serde_json::to_string(&Rank::FormaSpecialis).unwrap(),
1414            "\"FORMA_SPECIALIS\""
1415        );
1416        assert_eq!(
1417            serde_json::to_string(&Rank::InfrasubspecificName).unwrap(),
1418            "\"INFRASUBSPECIFIC_NAME\""
1419        );
1420        assert_eq!(
1421            serde_json::to_string(&Rank::InfragenericName).unwrap(),
1422            "\"INFRAGENERIC_NAME\""
1423        );
1424    }
1425
1426    /// `Rank::code()` — spot-checks against `Rank.java`'s own constructor arguments (see
1427    /// `code()`'s doc comment for the exact source lines): most ranks are code-agnostic
1428    /// (`None`); `Grex`/`CultivarGroup`/`Cultivar` anchor to `CULTIVARS`; the `*Botany` /
1429    /// `*Zoology` section-series pairs anchor to `BOTANICAL` / `ZOOLOGICAL` respectively;
1430    /// `Subgenus` (unlike its `*Botany` siblings) carries no code at all in Java.
1431    #[test]
1432    fn rank_code_matches_java_get_code() {
1433        assert_eq!(Rank::Unranked.code(), None);
1434        assert_eq!(Rank::Species.code(), None);
1435        assert_eq!(Rank::Subgenus.code(), None);
1436        assert_eq!(Rank::Tribe.code(), None);
1437        assert_eq!(Rank::Grex.code(), Some(NomCode::Cultivars));
1438        assert_eq!(Rank::CultivarGroup.code(), Some(NomCode::Cultivars));
1439        assert_eq!(Rank::Cultivar.code(), Some(NomCode::Cultivars));
1440        assert_eq!(Rank::SectionBotany.code(), Some(NomCode::Botanical));
1441        assert_eq!(Rank::SubsectionBotany.code(), Some(NomCode::Botanical));
1442        assert_eq!(Rank::SupersectionBotany.code(), Some(NomCode::Botanical));
1443        assert_eq!(Rank::SeriesBotany.code(), Some(NomCode::Botanical));
1444        assert_eq!(Rank::SubseriesBotany.code(), Some(NomCode::Botanical));
1445        assert_eq!(Rank::SuperseriesBotany.code(), Some(NomCode::Botanical));
1446        assert_eq!(Rank::SectionZoology.code(), Some(NomCode::Zoological));
1447        assert_eq!(Rank::SubsectionZoology.code(), Some(NomCode::Zoological));
1448        assert_eq!(Rank::SupersectionZoology.code(), Some(NomCode::Zoological));
1449        assert_eq!(Rank::SeriesZoology.code(), Some(NomCode::Zoological));
1450        assert_eq!(Rank::SubseriesZoology.code(), Some(NomCode::Zoological));
1451        assert_eq!(Rank::SuperseriesZoology.code(), Some(NomCode::Zoological));
1452    }
1453
1454    /// `Rank::code()` — Phase 1 Slice 3 Task 1 additions: the new `BACTERIAL` group
1455    /// (`Pathovar`/`Biovar`/`Chemoform`/`Serovar`/`Morphovar`/`Phagovar`, all microbial
1456    /// ranks under the Bacteriological Code), the legacy `ZOOLOGICAL` ranks
1457    /// (`Morph`/`Natio`/`Mutatio`/`Aberration`), `Convariety` (`CULTIVARS`, joining
1458    /// `Grex`/`CultivarGroup`/`Cultivar`), `Proles`/`DivisionBotany` (`BOTANICAL`, joining
1459    /// the `*Botany` section-series group), and the code-agnostic stragglers
1460    /// (`Other`/`Subvariety`/`Subform`/`Strain`/`InfraspecificName`) — each cross-checked
1461    /// against `Rank.java`'s own constructor argument (see `RankMarkers.java`'s ported
1462    /// values in `pipeline::rank_markers` for where each of these is actually looked up).
1463    #[test]
1464    fn rank_code_matches_java_get_code_slice3_task1_variants() {
1465        assert_eq!(Rank::Pathovar.code(), Some(NomCode::Bacterial));
1466        assert_eq!(Rank::Biovar.code(), Some(NomCode::Bacterial));
1467        assert_eq!(Rank::Chemoform.code(), Some(NomCode::Bacterial));
1468        assert_eq!(Rank::Serovar.code(), Some(NomCode::Bacterial));
1469        assert_eq!(Rank::Morphovar.code(), Some(NomCode::Bacterial));
1470        assert_eq!(Rank::Phagovar.code(), Some(NomCode::Bacterial));
1471        assert_eq!(Rank::Morph.code(), Some(NomCode::Zoological));
1472        assert_eq!(Rank::Natio.code(), Some(NomCode::Zoological));
1473        assert_eq!(Rank::Mutatio.code(), Some(NomCode::Zoological));
1474        assert_eq!(Rank::Aberration.code(), Some(NomCode::Zoological));
1475        assert_eq!(Rank::Convariety.code(), Some(NomCode::Cultivars));
1476        assert_eq!(Rank::Proles.code(), Some(NomCode::Botanical));
1477        assert_eq!(Rank::DivisionBotany.code(), Some(NomCode::Botanical));
1478        assert_eq!(Rank::Other.code(), None);
1479        assert_eq!(Rank::Subvariety.code(), None);
1480        assert_eq!(Rank::Subform.code(), None);
1481        assert_eq!(Rank::Strain.code(), None);
1482        assert_eq!(Rank::InfraspecificName.code(), None);
1483    }
1484
1485    /// `Rank::code()` — Phase 1 Slice 3 Task 3 additions: `FormaSpecialis` joins the
1486    /// `BOTANICAL` group (`Rank.java`'s own `FORMA_SPECIALIS(NomCode.BOTANICAL, "f.sp.")`);
1487    /// `InfrasubspecificName`/`InfragenericName` are code-agnostic, like their
1488    /// `InfraspecificName`/`Other` siblings (Java's marker-only, no-code constructor).
1489    #[test]
1490    fn rank_code_matches_java_get_code_slice3_task3_variants() {
1491        assert_eq!(Rank::FormaSpecialis.code(), Some(NomCode::Botanical));
1492        assert_eq!(Rank::InfrasubspecificName.code(), None);
1493        assert_eq!(Rank::InfragenericName.code(), None);
1494    }
1495
1496    #[test]
1497    fn name_part_ord_matches_java_ordinal_order() {
1498        let mut parts = vec![
1499            NamePart::Infraspecific,
1500            NamePart::Generic,
1501            NamePart::Specific,
1502            NamePart::Infrageneric,
1503        ];
1504        parts.sort();
1505        assert_eq!(
1506            parts,
1507            vec![
1508                NamePart::Generic,
1509                NamePart::Infrageneric,
1510                NamePart::Specific,
1511                NamePart::Infraspecific,
1512            ]
1513        );
1514    }
1515
1516    // ============================================================================
1517    // Phase 1 Slice 4 Task 1: full 117-constant `Rank` + ordinal predicates.
1518    // ============================================================================
1519
1520    /// The exhaustive round-trip: every one of the 117 `Rank` variants, in exact Java
1521    /// declaration/ordinal order, serializes to its exact Java `.name()` string. This both
1522    /// locks in declaration order (a mismatch here means an ordinal-compare predicate would
1523    /// silently disagree with Java) and empirically confirms
1524    /// `#[serde(rename_all = "SCREAMING_SNAKE_CASE")]` needed no per-variant
1525    /// `#[serde(rename = "…")]` override for any multi-word constant (`SUPERSECTION_BOTANY`,
1526    /// `INFRASPECIFIC_NAME`, `FORMA_SPECIALIS`, …) — generated mechanically from `Rank.java`
1527    /// itself, not hand-transcribed.
1528    #[test]
1529    fn rank_all_117_variants_in_java_declaration_order() {
1530        let expected: [(Rank, &str); 117] = [
1531            (Rank::Superdomain, "SUPERDOMAIN"),
1532            (Rank::Domain, "DOMAIN"),
1533            (Rank::Subdomain, "SUBDOMAIN"),
1534            (Rank::Infradomain, "INFRADOMAIN"),
1535            (Rank::Empire, "EMPIRE"),
1536            (Rank::Realm, "REALM"),
1537            (Rank::Subrealm, "SUBREALM"),
1538            (Rank::Superkingdom, "SUPERKINGDOM"),
1539            (Rank::Kingdom, "KINGDOM"),
1540            (Rank::Subkingdom, "SUBKINGDOM"),
1541            (Rank::Infrakingdom, "INFRAKINGDOM"),
1542            (Rank::Superphylum, "SUPERPHYLUM"),
1543            (Rank::Phylum, "PHYLUM"),
1544            (Rank::Subphylum, "SUBPHYLUM"),
1545            (Rank::Infraphylum, "INFRAPHYLUM"),
1546            (Rank::Parvphylum, "PARVPHYLUM"),
1547            (Rank::Microphylum, "MICROPHYLUM"),
1548            (Rank::Nanophylum, "NANOPHYLUM"),
1549            (Rank::Claudius, "CLAUDIUS"),
1550            (Rank::Gigaclass, "GIGACLASS"),
1551            (Rank::Megaclass, "MEGACLASS"),
1552            (Rank::Superclass, "SUPERCLASS"),
1553            (Rank::Class, "CLASS"),
1554            (Rank::Subclass, "SUBCLASS"),
1555            (Rank::Infraclass, "INFRACLASS"),
1556            (Rank::Subterclass, "SUBTERCLASS"),
1557            (Rank::Parvclass, "PARVCLASS"),
1558            (Rank::Superdivision, "SUPERDIVISION"),
1559            (Rank::DivisionZoology, "DIVISION_ZOOLOGY"),
1560            (Rank::Subdivision, "SUBDIVISION"),
1561            (Rank::Infradivision, "INFRADIVISION"),
1562            (Rank::Superlegion, "SUPERLEGION"),
1563            (Rank::Legion, "LEGION"),
1564            (Rank::Sublegion, "SUBLEGION"),
1565            (Rank::Infralegion, "INFRALEGION"),
1566            (Rank::Megacohort, "MEGACOHORT"),
1567            (Rank::Supercohort, "SUPERCOHORT"),
1568            (Rank::Cohort, "COHORT"),
1569            (Rank::Subcohort, "SUBCOHORT"),
1570            (Rank::Infracohort, "INFRACOHORT"),
1571            (Rank::Gigaorder, "GIGAORDER"),
1572            (Rank::Magnorder, "MAGNORDER"),
1573            (Rank::Grandorder, "GRANDORDER"),
1574            (Rank::Mirorder, "MIRORDER"),
1575            (Rank::Superorder, "SUPERORDER"),
1576            (Rank::Order, "ORDER"),
1577            (Rank::Nanorder, "NANORDER"),
1578            (Rank::Hypoorder, "HYPOORDER"),
1579            (Rank::Minorder, "MINORDER"),
1580            (Rank::Suborder, "SUBORDER"),
1581            (Rank::Infraorder, "INFRAORDER"),
1582            (Rank::Parvorder, "PARVORDER"),
1583            (Rank::SupersectionZoology, "SUPERSECTION_ZOOLOGY"),
1584            (Rank::SectionZoology, "SECTION_ZOOLOGY"),
1585            (Rank::SubsectionZoology, "SUBSECTION_ZOOLOGY"),
1586            (Rank::SuperseriesZoology, "SUPERSERIES_ZOOLOGY"),
1587            (Rank::SeriesZoology, "SERIES_ZOOLOGY"),
1588            (Rank::SubseriesZoology, "SUBSERIES_ZOOLOGY"),
1589            (Rank::Falanx, "FALANX"),
1590            (Rank::Gigafamily, "GIGAFAMILY"),
1591            (Rank::Megafamily, "MEGAFAMILY"),
1592            (Rank::Grandfamily, "GRANDFAMILY"),
1593            (Rank::Superfamily, "SUPERFAMILY"),
1594            (Rank::Epifamily, "EPIFAMILY"),
1595            (Rank::Family, "FAMILY"),
1596            (Rank::Subfamily, "SUBFAMILY"),
1597            (Rank::Infrafamily, "INFRAFAMILY"),
1598            (Rank::Supertribe, "SUPERTRIBE"),
1599            (Rank::Tribe, "TRIBE"),
1600            (Rank::Subtribe, "SUBTRIBE"),
1601            (Rank::Infratribe, "INFRATRIBE"),
1602            (Rank::SupragenericName, "SUPRAGENERIC_NAME"),
1603            (Rank::Supergenus, "SUPERGENUS"),
1604            (Rank::Genus, "GENUS"),
1605            (Rank::Subgenus, "SUBGENUS"),
1606            (Rank::Infragenus, "INFRAGENUS"),
1607            (Rank::DivisionBotany, "DIVISION_BOTANY"),
1608            (Rank::SupersectionBotany, "SUPERSECTION_BOTANY"),
1609            (Rank::SectionBotany, "SECTION_BOTANY"),
1610            (Rank::SubsectionBotany, "SUBSECTION_BOTANY"),
1611            (Rank::SuperseriesBotany, "SUPERSERIES_BOTANY"),
1612            (Rank::SeriesBotany, "SERIES_BOTANY"),
1613            (Rank::SubseriesBotany, "SUBSERIES_BOTANY"),
1614            (Rank::InfragenericName, "INFRAGENERIC_NAME"),
1615            (Rank::SpeciesAggregate, "SPECIES_AGGREGATE"),
1616            (Rank::Species, "SPECIES"),
1617            (Rank::InfraspecificName, "INFRASPECIFIC_NAME"),
1618            (Rank::Grex, "GREX"),
1619            (Rank::Klepton, "KLEPTON"),
1620            (Rank::Subspecies, "SUBSPECIES"),
1621            (Rank::CultivarGroup, "CULTIVAR_GROUP"),
1622            (Rank::Convariety, "CONVARIETY"),
1623            (Rank::InfrasubspecificName, "INFRASUBSPECIFIC_NAME"),
1624            (Rank::Proles, "PROLES"),
1625            (Rank::Natio, "NATIO"),
1626            (Rank::Aberration, "ABERRATION"),
1627            (Rank::Morph, "MORPH"),
1628            (Rank::Supervariety, "SUPERVARIETY"),
1629            (Rank::Variety, "VARIETY"),
1630            (Rank::Subvariety, "SUBVARIETY"),
1631            (Rank::Superform, "SUPERFORM"),
1632            (Rank::Form, "FORM"),
1633            (Rank::Subform, "SUBFORM"),
1634            (Rank::Pathovar, "PATHOVAR"),
1635            (Rank::Biovar, "BIOVAR"),
1636            (Rank::Chemovar, "CHEMOVAR"),
1637            (Rank::Morphovar, "MORPHOVAR"),
1638            (Rank::Phagovar, "PHAGOVAR"),
1639            (Rank::Serovar, "SEROVAR"),
1640            (Rank::Chemoform, "CHEMOFORM"),
1641            (Rank::FormaSpecialis, "FORMA_SPECIALIS"),
1642            (Rank::Lusus, "LUSUS"),
1643            (Rank::Cultivar, "CULTIVAR"),
1644            (Rank::Mutatio, "MUTATIO"),
1645            (Rank::Strain, "STRAIN"),
1646            (Rank::Other, "OTHER"),
1647            (Rank::Unranked, "UNRANKED"),
1648        ];
1649        assert_eq!(expected.len(), 117);
1650        assert_eq!(Rank::ALL.len(), 117);
1651        for (i, (rank, name)) in expected.iter().enumerate() {
1652            assert_eq!(Rank::ALL[i], *rank, "Rank::ALL[{i}] should be {rank:?}");
1653            assert_eq!(rank.ordinal(), i, "{rank:?}.ordinal() should be {i}");
1654            assert_eq!(
1655                serde_json::to_string(rank).unwrap(),
1656                format!("\"{name}\""),
1657                "{rank:?} should serialize to \"{name}\""
1658            );
1659        }
1660    }
1661
1662    /// TDD sample from the task brief: a handful of code-carrying ranks not already
1663    /// exercised above, including the new `REALM` (`VIRUS`) variant.
1664    #[test]
1665    fn rank_code_tdd_sample() {
1666        assert_eq!(Rank::Cultivar.code(), Some(NomCode::Cultivars));
1667        assert_eq!(Rank::Subgenus.code(), None);
1668        assert_eq!(Rank::Pathovar.code(), Some(NomCode::Bacterial));
1669        assert_eq!(Rank::SectionBotany.code(), Some(NomCode::Botanical));
1670        assert_eq!(Rank::Realm.code(), Some(NomCode::Virus));
1671        assert_eq!(Rank::Subrealm.code(), Some(NomCode::Virus));
1672    }
1673
1674    /// TDD sample from the task brief: the ordinal predicates.
1675    #[test]
1676    fn rank_ordinal_predicates_tdd_sample() {
1677        assert!(Rank::Subspecies.is_infraspecific());
1678        assert!(!Rank::Species.is_infraspecific());
1679        assert!(Rank::Subgenus.is_infrageneric_strictly());
1680        assert!(!Rank::Genus.is_infrageneric_strictly());
1681        assert!(!Rank::Species.is_infrageneric_strictly());
1682        assert!(Rank::Family.is_suprageneric());
1683        assert!(!Rank::Genus.is_suprageneric());
1684        assert!(Rank::Genus.higher_than(Rank::Species));
1685        assert!(!Rank::Species.higher_than(Rank::Genus));
1686        assert!(Rank::Species.higher_than(Rank::Subspecies));
1687        assert!(Rank::Subspecies.lower_than(Rank::Species));
1688        assert!(!Rank::Genus.higher_than(Rank::Other));
1689        assert!(!Rank::Genus.higher_than(Rank::Unranked));
1690    }
1691
1692    #[test]
1693    fn rank_markers_tdd_sample() {
1694        assert_eq!(Rank::Subspecies.marker(), Some("subsp."));
1695        assert_eq!(Rank::Species.marker(), Some("sp."));
1696        assert_eq!(Rank::CultivarGroup.marker(), None);
1697        assert_eq!(Rank::Other.marker(), None);
1698        assert_eq!(Rank::Unranked.marker(), None);
1699        // Zoology/botany pairs share their marker text verbatim.
1700        assert_eq!(Rank::SectionZoology.marker(), Rank::SectionBotany.marker());
1701        assert_eq!(
1702            Rank::DivisionZoology.marker(),
1703            Rank::DivisionBotany.marker()
1704        );
1705    }
1706
1707    #[test]
1708    fn rank_plural_sample() {
1709        assert_eq!(Rank::Species.plural(), Some("species"));
1710        assert_eq!(Rank::Genus.plural(), Some("genera"));
1711        assert_eq!(Rank::Falanx.plural(), Some("falanges"));
1712        assert_eq!(Rank::Lusus.plural(), Some("lusi"));
1713        assert_eq!(Rank::CultivarGroup.plural(), None);
1714        assert_eq!(Rank::Other.plural(), None);
1715        assert_eq!(Rank::Unranked.plural(), None);
1716        // Java's un-de-underscored default plural (`name().toLowerCase() + "s"`),
1717        // transcribed verbatim rather than "fixed".
1718        assert_eq!(Rank::DivisionZoology.plural(), Some("division_zoologys"));
1719        assert_eq!(Rank::SectionBotany.plural(), Some("section_botanys"));
1720        // Explicit Java plural shared by a zoology/botany pair.
1721        assert_eq!(Rank::SeriesZoology.plural(), Some("series"));
1722        assert_eq!(Rank::SeriesBotany.plural(), Some("series"));
1723    }
1724
1725    #[test]
1726    fn rank_is_family_group_and_genus_group() {
1727        assert!(Rank::Family.is_family_group());
1728        assert!(Rank::Gigafamily.is_family_group());
1729        assert!(!Rank::SupragenericName.is_family_group());
1730        assert!(!Rank::Genus.is_family_group());
1731        assert!(Rank::Genus.is_genus_group());
1732        assert!(Rank::Supergenus.is_genus_group());
1733        assert!(Rank::Subgenus.is_genus_group());
1734        assert!(!Rank::SpeciesAggregate.is_genus_group());
1735        assert!(!Rank::SupragenericName.is_genus_group());
1736    }
1737
1738    #[test]
1739    fn rank_is_species_or_below() {
1740        assert!(Rank::SpeciesAggregate.is_species_or_below());
1741        assert!(Rank::Species.is_species_or_below());
1742        assert!(Rank::Subspecies.is_species_or_below());
1743        assert!(!Rank::Genus.is_species_or_below());
1744        assert!(!Rank::Other.is_species_or_below());
1745        assert!(!Rank::Unranked.is_species_or_below());
1746    }
1747
1748    #[test]
1749    fn rank_is_uncomparable() {
1750        assert!(Rank::SupragenericName.is_uncomparable());
1751        assert!(Rank::InfragenericName.is_uncomparable());
1752        assert!(Rank::InfraspecificName.is_uncomparable());
1753        assert!(Rank::InfrasubspecificName.is_uncomparable());
1754        assert!(Rank::Other.is_uncomparable());
1755        assert!(Rank::Unranked.is_uncomparable());
1756        assert!(!Rank::Species.is_uncomparable());
1757        assert!(!Rank::Genus.is_uncomparable());
1758    }
1759
1760    #[test]
1761    fn rank_is_legacy() {
1762        for r in [
1763            Rank::Morph,
1764            Rank::Aberration,
1765            Rank::Natio,
1766            Rank::Proles,
1767            Rank::Convariety,
1768            Rank::Klepton,
1769            Rank::Falanx,
1770            Rank::Lusus,
1771        ] {
1772            assert!(r.is_legacy(), "{r:?} should be legacy");
1773        }
1774        assert!(!Rank::Species.is_legacy());
1775        assert!(!Rank::Subspecies.is_legacy());
1776    }
1777
1778    #[test]
1779    fn rank_is_linnean() {
1780        for r in Rank::LINNEAN_RANKS {
1781            assert!(r.is_linnean(), "{r:?} should be Linnean");
1782        }
1783        assert!(!Rank::Subgenus.is_linnean());
1784        assert!(!Rank::Subspecies.is_linnean());
1785        assert_eq!(Rank::LINNEAN_RANKS.len(), 7);
1786    }
1787
1788    #[test]
1789    fn rank_is_restricted_to_code_matches_code() {
1790        assert_eq!(
1791            Rank::Cultivar.is_restricted_to_code(),
1792            Rank::Cultivar.code()
1793        );
1794        assert_eq!(Rank::Species.is_restricted_to_code(), Rank::Species.code());
1795    }
1796
1797    #[test]
1798    fn rank_has_ambiguous_marker() {
1799        // The 7 zoology/botany pairs that share marker text are ambiguous...
1800        for r in [
1801            Rank::DivisionZoology,
1802            Rank::DivisionBotany,
1803            Rank::SectionZoology,
1804            Rank::SectionBotany,
1805            Rank::SubsectionZoology,
1806            Rank::SubsectionBotany,
1807            Rank::SupersectionZoology,
1808            Rank::SupersectionBotany,
1809            Rank::SeriesZoology,
1810            Rank::SeriesBotany,
1811            Rank::SubseriesZoology,
1812            Rank::SubseriesBotany,
1813            Rank::SuperseriesZoology,
1814            Rank::SuperseriesBotany,
1815        ] {
1816            assert!(r.has_ambiguous_marker(), "{r:?} should be ambiguous");
1817        }
1818        // ...but a rank with a unique marker is not.
1819        assert!(!Rank::Species.has_ambiguous_marker());
1820        assert!(!Rank::Genus.has_ambiguous_marker());
1821        assert!(!Rank::Cultivar.has_ambiguous_marker());
1822    }
1823
1824    /// `Rank::get_major_rank()` — the automatic prefix-strip cases (no manual fix needed).
1825    #[test]
1826    fn rank_get_major_rank_automatic() {
1827        assert_eq!(Rank::Subphylum.get_major_rank(), Rank::Phylum);
1828        assert_eq!(Rank::Nanophylum.get_major_rank(), Rank::Phylum);
1829        assert_eq!(Rank::Subclass.get_major_rank(), Rank::Class);
1830        // Greedy `SUBTER` (tried before plain `SUB`) strips correctly to `CLASS`.
1831        assert_eq!(Rank::Subterclass.get_major_rank(), Rank::Class);
1832        assert_eq!(Rank::SubsectionBotany.get_major_rank(), Rank::SectionBotany);
1833        assert_eq!(
1834            Rank::SupersectionZoology.get_major_rank(),
1835            Rank::SectionZoology
1836        );
1837        // A rank with no prefix at all maps to itself (never `None`/a sentinel).
1838        assert_eq!(Rank::Species.get_major_rank(), Rank::Species);
1839        assert_eq!(Rank::Genus.get_major_rank(), Rank::Genus);
1840        assert_eq!(Rank::Other.get_major_rank(), Rank::Other);
1841        assert_eq!(Rank::Unranked.get_major_rank(), Rank::Unranked);
1842    }
1843
1844    /// `Rank::get_major_rank()` — the 6 manual fixes (`Rank.java:399-407`), each a case the
1845    /// automatic algorithm alone cannot resolve (see [`MAJOR_RANKS`]'s own doc comment).
1846    #[test]
1847    fn rank_get_major_rank_manual_fixes() {
1848        assert_eq!(Rank::Nanorder.get_major_rank(), Rank::Order);
1849        assert_eq!(Rank::SpeciesAggregate.get_major_rank(), Rank::Species);
1850        assert_eq!(Rank::InfragenericName.get_major_rank(), Rank::Genus);
1851        assert_eq!(Rank::Superdivision.get_major_rank(), Rank::DivisionZoology);
1852        assert_eq!(Rank::Subdivision.get_major_rank(), Rank::DivisionZoology);
1853        assert_eq!(Rank::Infradivision.get_major_rank(), Rank::DivisionZoology);
1854    }
1855
1856    /// `Rank::get_major_rank()` — every infraspecific rank (ordinal-wise, per
1857    /// `is_infraspecific()`) collapses to `INFRASPECIFIC_NAME`, including ones that aren't
1858    /// obviously "infraspecific" by name (`KLEPTON`, `CULTIVAR_GROUP`).
1859    #[test]
1860    fn rank_get_major_rank_infraspecific_collapse() {
1861        for r in [
1862            Rank::Grex,
1863            Rank::Klepton,
1864            Rank::Subspecies,
1865            Rank::CultivarGroup,
1866            Rank::Variety,
1867            Rank::Cultivar,
1868            Rank::Strain,
1869        ] {
1870            assert_eq!(
1871                r.get_major_rank(),
1872                Rank::InfraspecificName,
1873                "{r:?} should collapse to INFRASPECIFIC_NAME"
1874            );
1875        }
1876    }
1877
1878    /// `rank_utils::suffices_rank_map` — Assemble step 14's suffix->rank data, per code.
1879    #[test]
1880    fn rank_utils_suffices_rank_map_sample() {
1881        let bot = rank_utils::suffices_rank_map(NomCode::Botanical).unwrap();
1882        assert!(bot.contains(&("aceae", Rank::Family)));
1883        assert!(bot.contains(&("oideae", Rank::Subfamily)));
1884
1885        let zoo = rank_utils::suffices_rank_map(NomCode::Zoological).unwrap();
1886        assert!(zoo.contains(&("idae", Rank::Family)));
1887        assert!(zoo.contains(&("oidae", Rank::Epifamily)));
1888        // "idae" means FAMILY under zoology but SUBCLASS under botany/bacteriology —
1889        // confirms the map is genuinely per-code, not a single global lookup.
1890        let bact = rank_utils::suffices_rank_map(NomCode::Bacterial).unwrap();
1891        assert!(bact.contains(&("idae", Rank::Subclass)));
1892
1893        let virus = rank_utils::suffices_rank_map(NomCode::Virus).unwrap();
1894        assert!(virus.contains(&("viridae", Rank::Family)));
1895
1896        // Codes with no suffix map at all return None (mirrors Java's `Map.get` on a
1897        // missing key), not an empty slice.
1898        assert_eq!(rank_utils::suffices_rank_map(NomCode::Cultivars), None);
1899        assert_eq!(rank_utils::suffices_rank_map(NomCode::Phyto), None);
1900        assert_eq!(rank_utils::suffices_rank_map(NomCode::Phylo), None);
1901    }
1902
1903    // ---- Phase 3 (FFM binding): Rank::from_name / NomCode::from_name ----
1904
1905    /// Every one of the 117 `Rank` variants round-trips through its own wire name — the
1906    /// exhaustive version of the pin below, covering multi-word constants like
1907    /// `SUPERSECTION_BOTANY` and `FORMA_SPECIALIS` too, not just a hand-picked sample.
1908    #[test]
1909    fn rank_from_name_round_trips_every_variant_via_its_own_serialize_impl() {
1910        for &r in Rank::ALL.iter() {
1911            let name = rank_wire_name(r);
1912            assert_eq!(
1913                Rank::from_name(&name),
1914                Some(r),
1915                "round-trip failed for {r:?}"
1916            );
1917        }
1918    }
1919
1920    #[test]
1921    fn rank_from_name_pins_a_multi_word_constant_and_rejects_nonsense() {
1922        assert_eq!(Rank::from_name("SPECIES"), Some(Rank::Species));
1923        assert_eq!(
1924            Rank::from_name("DIVISION_ZOOLOGY"),
1925            Some(Rank::DivisionZoology)
1926        );
1927        assert_eq!(Rank::from_name("NONSENSE"), None);
1928        assert_eq!(Rank::from_name(""), None);
1929    }
1930
1931    /// Every one of the 7 `NomCode` variants round-trips through its own wire name —
1932    /// guards `NomCode::from_name`'s hand-written match against drifting from the real
1933    /// `#[derive(Serialize)]` output it's meant to reverse.
1934    #[test]
1935    fn nomcode_from_name_round_trips_every_variant_via_its_own_serialize_impl() {
1936        for &c in &[
1937            NomCode::Bacterial,
1938            NomCode::Botanical,
1939            NomCode::Cultivars,
1940            NomCode::Phyto,
1941            NomCode::Virus,
1942            NomCode::Zoological,
1943            NomCode::Phylo,
1944        ] {
1945            let name = serde_json::to_string(&c)
1946                .unwrap()
1947                .trim_matches('"')
1948                .to_string();
1949            assert_eq!(
1950                NomCode::from_name(&name),
1951                Some(c),
1952                "round-trip failed for {c:?}"
1953            );
1954        }
1955    }
1956
1957    #[test]
1958    fn nomcode_from_name_pins_botanical_and_rejects_nonsense() {
1959        assert_eq!(NomCode::from_name("BOTANICAL"), Some(NomCode::Botanical));
1960        assert_eq!(NomCode::from_name("NONSENSE"), None);
1961    }
1962}