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    /// Rust-only so far (name-parser-api has no constant for it yet): a separately supplied
1158    /// authorship differs from the one in the name string beyond holding less of it.
1159    pub const AUTHORSHIP_CONFLICT: &str = "separate authorship differs from the name string's";
1160    /// Rust-only so far: a species epithet written with a capital, as Linnaeus did (`Ovis Aries`),
1161    /// was put in lower case (ICZN Art. 28).
1162    pub const CAPITALISED_EPITHET: &str = "capitalised epithet put in lower case";
1163}
1164
1165#[cfg(test)]
1166mod tests {
1167    use super::*;
1168
1169    #[test]
1170    fn name_type_scientific_serializes_uppercase() {
1171        assert_eq!(
1172            serde_json::to_string(&NameType::Scientific).unwrap(),
1173            "\"SCIENTIFIC\""
1174        );
1175    }
1176
1177    #[test]
1178    fn name_type_first_and_last_variant() {
1179        assert_eq!(
1180            serde_json::to_string(&NameType::Scientific).unwrap(),
1181            "\"SCIENTIFIC\""
1182        );
1183        assert_eq!(
1184            serde_json::to_string(&NameType::Other).unwrap(),
1185            "\"OTHER\""
1186        );
1187    }
1188
1189    #[test]
1190    fn nom_code_first_last_and_zoological() {
1191        assert_eq!(
1192            serde_json::to_string(&NomCode::Bacterial).unwrap(),
1193            "\"BACTERIAL\""
1194        );
1195        assert_eq!(serde_json::to_string(&NomCode::Phylo).unwrap(), "\"PHYLO\"");
1196        assert_eq!(
1197            serde_json::to_string(&NomCode::Zoological).unwrap(),
1198            "\"ZOOLOGICAL\""
1199        );
1200    }
1201
1202    #[test]
1203    fn name_part_first_and_last_variant() {
1204        assert_eq!(
1205            serde_json::to_string(&NamePart::Generic).unwrap(),
1206            "\"GENERIC\""
1207        );
1208        assert_eq!(
1209            serde_json::to_string(&NamePart::Infraspecific).unwrap(),
1210            "\"INFRASPECIFIC\""
1211        );
1212    }
1213
1214    #[test]
1215    fn state_first_and_last_variant() {
1216        assert_eq!(
1217            serde_json::to_string(&State::Complete).unwrap(),
1218            "\"COMPLETE\""
1219        );
1220        assert_eq!(serde_json::to_string(&State::None).unwrap(), "\"NONE\"");
1221    }
1222
1223    #[test]
1224    fn rank_stub_unranked() {
1225        assert_eq!(
1226            serde_json::to_string(&Rank::Unranked).unwrap(),
1227            "\"UNRANKED\""
1228        );
1229    }
1230
1231    #[test]
1232    fn rank_stub_species_and_subspecies() {
1233        assert_eq!(
1234            serde_json::to_string(&Rank::Species).unwrap(),
1235            "\"SPECIES\""
1236        );
1237        assert_eq!(
1238            serde_json::to_string(&Rank::Subspecies).unwrap(),
1239            "\"SUBSPECIES\""
1240        );
1241    }
1242
1243    /// Phase 1 Slice 2 batch 2b additions: `StripAndStash::strip_nom_note`'s rank-hint
1244    /// switch (Genus/Family/Variety/Form) and `strip_cultivar_group_grex`/
1245    /// `strip_quoted_cultivar` (Cultivar/CultivarGroup/Grex) — verifies the
1246    /// `SCREAMING_SNAKE_CASE` rename produces the exact Java enum constant name for each,
1247    /// in particular that `CultivarGroup`'s two-word boundary renders as the
1248    /// underscore-joined `CULTIVAR_GROUP` Java uses (`Rank.CULTIVAR_GROUP`).
1249    #[test]
1250    fn rank_stub_batch_2b_variants() {
1251        assert_eq!(serde_json::to_string(&Rank::Genus).unwrap(), "\"GENUS\"");
1252        assert_eq!(serde_json::to_string(&Rank::Family).unwrap(), "\"FAMILY\"");
1253        assert_eq!(
1254            serde_json::to_string(&Rank::Variety).unwrap(),
1255            "\"VARIETY\""
1256        );
1257        assert_eq!(serde_json::to_string(&Rank::Form).unwrap(), "\"FORM\"");
1258        assert_eq!(
1259            serde_json::to_string(&Rank::Cultivar).unwrap(),
1260            "\"CULTIVAR\""
1261        );
1262        assert_eq!(
1263            serde_json::to_string(&Rank::CultivarGroup).unwrap(),
1264            "\"CULTIVAR_GROUP\""
1265        );
1266        assert_eq!(serde_json::to_string(&Rank::Grex).unwrap(), "\"GREX\"");
1267    }
1268
1269    /// Phase 1 Slice 2 batch 2e additions: `StripAndStash` steps 53-55's suprageneric
1270    /// family-group ranks (step 53) and the infrageneric botany/zoology section-series
1271    /// pairs (step 54's `RANK_MARKER_MAP_INFRAGENERIC` subset + `BOT_TO_ZOOL`) — verifies
1272    /// the `SCREAMING_SNAKE_CASE` rename produces the exact Java enum constant name for
1273    /// each, in particular that the two-word `*Botany`/`*Zoology` variants render with the
1274    /// underscore Java uses (`Rank.SECTION_BOTANY`, `Rank.SUPERSERIES_ZOOLOGY`).
1275    #[test]
1276    fn rank_stub_batch_2e_variants() {
1277        assert_eq!(
1278            serde_json::to_string(&Rank::Subfamily).unwrap(),
1279            "\"SUBFAMILY\""
1280        );
1281        assert_eq!(serde_json::to_string(&Rank::Tribe).unwrap(), "\"TRIBE\"");
1282        assert_eq!(
1283            serde_json::to_string(&Rank::Subtribe).unwrap(),
1284            "\"SUBTRIBE\""
1285        );
1286        assert_eq!(
1287            serde_json::to_string(&Rank::Supertribe).unwrap(),
1288            "\"SUPERTRIBE\""
1289        );
1290        assert_eq!(
1291            serde_json::to_string(&Rank::Infratribe).unwrap(),
1292            "\"INFRATRIBE\""
1293        );
1294        assert_eq!(
1295            serde_json::to_string(&Rank::Subgenus).unwrap(),
1296            "\"SUBGENUS\""
1297        );
1298        assert_eq!(
1299            serde_json::to_string(&Rank::SectionBotany).unwrap(),
1300            "\"SECTION_BOTANY\""
1301        );
1302        assert_eq!(
1303            serde_json::to_string(&Rank::SubsectionBotany).unwrap(),
1304            "\"SUBSECTION_BOTANY\""
1305        );
1306        assert_eq!(
1307            serde_json::to_string(&Rank::SupersectionBotany).unwrap(),
1308            "\"SUPERSECTION_BOTANY\""
1309        );
1310        assert_eq!(
1311            serde_json::to_string(&Rank::SeriesBotany).unwrap(),
1312            "\"SERIES_BOTANY\""
1313        );
1314        assert_eq!(
1315            serde_json::to_string(&Rank::SubseriesBotany).unwrap(),
1316            "\"SUBSERIES_BOTANY\""
1317        );
1318        assert_eq!(
1319            serde_json::to_string(&Rank::SuperseriesBotany).unwrap(),
1320            "\"SUPERSERIES_BOTANY\""
1321        );
1322        assert_eq!(
1323            serde_json::to_string(&Rank::SectionZoology).unwrap(),
1324            "\"SECTION_ZOOLOGY\""
1325        );
1326        assert_eq!(
1327            serde_json::to_string(&Rank::SubsectionZoology).unwrap(),
1328            "\"SUBSECTION_ZOOLOGY\""
1329        );
1330        assert_eq!(
1331            serde_json::to_string(&Rank::SupersectionZoology).unwrap(),
1332            "\"SUPERSECTION_ZOOLOGY\""
1333        );
1334        assert_eq!(
1335            serde_json::to_string(&Rank::SeriesZoology).unwrap(),
1336            "\"SERIES_ZOOLOGY\""
1337        );
1338        assert_eq!(
1339            serde_json::to_string(&Rank::SubseriesZoology).unwrap(),
1340            "\"SUBSERIES_ZOOLOGY\""
1341        );
1342        assert_eq!(
1343            serde_json::to_string(&Rank::SuperseriesZoology).unwrap(),
1344            "\"SUPERSERIES_ZOOLOGY\""
1345        );
1346    }
1347
1348    /// Phase 1 Slice 3 Task 1 additions: every `Rank` value the two `RankMarkers` maps
1349    /// (`pipeline::rank_markers`) reference that wasn't already present — verifies the
1350    /// `SCREAMING_SNAKE_CASE` rename produces the exact Java enum constant name for each,
1351    /// in particular the two-word `InfraspecificName`/`DivisionBotany` (`INFRASPECIFIC_NAME`
1352    /// / `DIVISION_BOTANY`, matching Java's own multi-word constants).
1353    #[test]
1354    fn rank_stub_slice3_task1_variants() {
1355        assert_eq!(serde_json::to_string(&Rank::Other).unwrap(), "\"OTHER\"");
1356        assert_eq!(
1357            serde_json::to_string(&Rank::Subvariety).unwrap(),
1358            "\"SUBVARIETY\""
1359        );
1360        assert_eq!(
1361            serde_json::to_string(&Rank::Subform).unwrap(),
1362            "\"SUBFORM\""
1363        );
1364        assert_eq!(
1365            serde_json::to_string(&Rank::Pathovar).unwrap(),
1366            "\"PATHOVAR\""
1367        );
1368        assert_eq!(serde_json::to_string(&Rank::Biovar).unwrap(), "\"BIOVAR\"");
1369        assert_eq!(
1370            serde_json::to_string(&Rank::Chemoform).unwrap(),
1371            "\"CHEMOFORM\""
1372        );
1373        assert_eq!(
1374            serde_json::to_string(&Rank::Serovar).unwrap(),
1375            "\"SEROVAR\""
1376        );
1377        assert_eq!(serde_json::to_string(&Rank::Morph).unwrap(), "\"MORPH\"");
1378        assert_eq!(
1379            serde_json::to_string(&Rank::Morphovar).unwrap(),
1380            "\"MORPHOVAR\""
1381        );
1382        assert_eq!(
1383            serde_json::to_string(&Rank::Phagovar).unwrap(),
1384            "\"PHAGOVAR\""
1385        );
1386        assert_eq!(serde_json::to_string(&Rank::Natio).unwrap(), "\"NATIO\"");
1387        assert_eq!(
1388            serde_json::to_string(&Rank::Mutatio).unwrap(),
1389            "\"MUTATIO\""
1390        );
1391        assert_eq!(
1392            serde_json::to_string(&Rank::Convariety).unwrap(),
1393            "\"CONVARIETY\""
1394        );
1395        assert_eq!(serde_json::to_string(&Rank::Proles).unwrap(), "\"PROLES\"");
1396        assert_eq!(
1397            serde_json::to_string(&Rank::Aberration).unwrap(),
1398            "\"ABERRATION\""
1399        );
1400        assert_eq!(serde_json::to_string(&Rank::Strain).unwrap(), "\"STRAIN\"");
1401        assert_eq!(
1402            serde_json::to_string(&Rank::InfraspecificName).unwrap(),
1403            "\"INFRASPECIFIC_NAME\""
1404        );
1405        assert_eq!(
1406            serde_json::to_string(&Rank::DivisionBotany).unwrap(),
1407            "\"DIVISION_BOTANY\""
1408        );
1409    }
1410
1411    /// Phase 1 Slice 3 Task 3 additions (`NameTokens`): the three bare `Rank.XXX` literals
1412    /// `NameTokens.classify` references that Task 1's `RankMarkers` maps didn't already pull
1413    /// in — verifies the `SCREAMING_SNAKE_CASE` rename produces the exact Java enum constant
1414    /// name for each, in particular that `FormaSpecialis`'s two-word boundary renders as the
1415    /// underscore-joined `FORMA_SPECIALIS` Java uses.
1416    #[test]
1417    fn rank_stub_slice3_task3_variants() {
1418        assert_eq!(
1419            serde_json::to_string(&Rank::FormaSpecialis).unwrap(),
1420            "\"FORMA_SPECIALIS\""
1421        );
1422        assert_eq!(
1423            serde_json::to_string(&Rank::InfrasubspecificName).unwrap(),
1424            "\"INFRASUBSPECIFIC_NAME\""
1425        );
1426        assert_eq!(
1427            serde_json::to_string(&Rank::InfragenericName).unwrap(),
1428            "\"INFRAGENERIC_NAME\""
1429        );
1430    }
1431
1432    /// `Rank::code()` — spot-checks against `Rank.java`'s own constructor arguments (see
1433    /// `code()`'s doc comment for the exact source lines): most ranks are code-agnostic
1434    /// (`None`); `Grex`/`CultivarGroup`/`Cultivar` anchor to `CULTIVARS`; the `*Botany` /
1435    /// `*Zoology` section-series pairs anchor to `BOTANICAL` / `ZOOLOGICAL` respectively;
1436    /// `Subgenus` (unlike its `*Botany` siblings) carries no code at all in Java.
1437    #[test]
1438    fn rank_code_matches_java_get_code() {
1439        assert_eq!(Rank::Unranked.code(), None);
1440        assert_eq!(Rank::Species.code(), None);
1441        assert_eq!(Rank::Subgenus.code(), None);
1442        assert_eq!(Rank::Tribe.code(), None);
1443        assert_eq!(Rank::Grex.code(), Some(NomCode::Cultivars));
1444        assert_eq!(Rank::CultivarGroup.code(), Some(NomCode::Cultivars));
1445        assert_eq!(Rank::Cultivar.code(), Some(NomCode::Cultivars));
1446        assert_eq!(Rank::SectionBotany.code(), Some(NomCode::Botanical));
1447        assert_eq!(Rank::SubsectionBotany.code(), Some(NomCode::Botanical));
1448        assert_eq!(Rank::SupersectionBotany.code(), Some(NomCode::Botanical));
1449        assert_eq!(Rank::SeriesBotany.code(), Some(NomCode::Botanical));
1450        assert_eq!(Rank::SubseriesBotany.code(), Some(NomCode::Botanical));
1451        assert_eq!(Rank::SuperseriesBotany.code(), Some(NomCode::Botanical));
1452        assert_eq!(Rank::SectionZoology.code(), Some(NomCode::Zoological));
1453        assert_eq!(Rank::SubsectionZoology.code(), Some(NomCode::Zoological));
1454        assert_eq!(Rank::SupersectionZoology.code(), Some(NomCode::Zoological));
1455        assert_eq!(Rank::SeriesZoology.code(), Some(NomCode::Zoological));
1456        assert_eq!(Rank::SubseriesZoology.code(), Some(NomCode::Zoological));
1457        assert_eq!(Rank::SuperseriesZoology.code(), Some(NomCode::Zoological));
1458    }
1459
1460    /// `Rank::code()` — Phase 1 Slice 3 Task 1 additions: the new `BACTERIAL` group
1461    /// (`Pathovar`/`Biovar`/`Chemoform`/`Serovar`/`Morphovar`/`Phagovar`, all microbial
1462    /// ranks under the Bacteriological Code), the legacy `ZOOLOGICAL` ranks
1463    /// (`Morph`/`Natio`/`Mutatio`/`Aberration`), `Convariety` (`CULTIVARS`, joining
1464    /// `Grex`/`CultivarGroup`/`Cultivar`), `Proles`/`DivisionBotany` (`BOTANICAL`, joining
1465    /// the `*Botany` section-series group), and the code-agnostic stragglers
1466    /// (`Other`/`Subvariety`/`Subform`/`Strain`/`InfraspecificName`) — each cross-checked
1467    /// against `Rank.java`'s own constructor argument (see `RankMarkers.java`'s ported
1468    /// values in `pipeline::rank_markers` for where each of these is actually looked up).
1469    #[test]
1470    fn rank_code_matches_java_get_code_slice3_task1_variants() {
1471        assert_eq!(Rank::Pathovar.code(), Some(NomCode::Bacterial));
1472        assert_eq!(Rank::Biovar.code(), Some(NomCode::Bacterial));
1473        assert_eq!(Rank::Chemoform.code(), Some(NomCode::Bacterial));
1474        assert_eq!(Rank::Serovar.code(), Some(NomCode::Bacterial));
1475        assert_eq!(Rank::Morphovar.code(), Some(NomCode::Bacterial));
1476        assert_eq!(Rank::Phagovar.code(), Some(NomCode::Bacterial));
1477        assert_eq!(Rank::Morph.code(), Some(NomCode::Zoological));
1478        assert_eq!(Rank::Natio.code(), Some(NomCode::Zoological));
1479        assert_eq!(Rank::Mutatio.code(), Some(NomCode::Zoological));
1480        assert_eq!(Rank::Aberration.code(), Some(NomCode::Zoological));
1481        assert_eq!(Rank::Convariety.code(), Some(NomCode::Cultivars));
1482        assert_eq!(Rank::Proles.code(), Some(NomCode::Botanical));
1483        assert_eq!(Rank::DivisionBotany.code(), Some(NomCode::Botanical));
1484        assert_eq!(Rank::Other.code(), None);
1485        assert_eq!(Rank::Subvariety.code(), None);
1486        assert_eq!(Rank::Subform.code(), None);
1487        assert_eq!(Rank::Strain.code(), None);
1488        assert_eq!(Rank::InfraspecificName.code(), None);
1489    }
1490
1491    /// `Rank::code()` — Phase 1 Slice 3 Task 3 additions: `FormaSpecialis` joins the
1492    /// `BOTANICAL` group (`Rank.java`'s own `FORMA_SPECIALIS(NomCode.BOTANICAL, "f.sp.")`);
1493    /// `InfrasubspecificName`/`InfragenericName` are code-agnostic, like their
1494    /// `InfraspecificName`/`Other` siblings (Java's marker-only, no-code constructor).
1495    #[test]
1496    fn rank_code_matches_java_get_code_slice3_task3_variants() {
1497        assert_eq!(Rank::FormaSpecialis.code(), Some(NomCode::Botanical));
1498        assert_eq!(Rank::InfrasubspecificName.code(), None);
1499        assert_eq!(Rank::InfragenericName.code(), None);
1500    }
1501
1502    #[test]
1503    fn name_part_ord_matches_java_ordinal_order() {
1504        let mut parts = vec![
1505            NamePart::Infraspecific,
1506            NamePart::Generic,
1507            NamePart::Specific,
1508            NamePart::Infrageneric,
1509        ];
1510        parts.sort();
1511        assert_eq!(
1512            parts,
1513            vec![
1514                NamePart::Generic,
1515                NamePart::Infrageneric,
1516                NamePart::Specific,
1517                NamePart::Infraspecific,
1518            ]
1519        );
1520    }
1521
1522    // ============================================================================
1523    // Phase 1 Slice 4 Task 1: full 117-constant `Rank` + ordinal predicates.
1524    // ============================================================================
1525
1526    /// The exhaustive round-trip: every one of the 117 `Rank` variants, in exact Java
1527    /// declaration/ordinal order, serializes to its exact Java `.name()` string. This both
1528    /// locks in declaration order (a mismatch here means an ordinal-compare predicate would
1529    /// silently disagree with Java) and empirically confirms
1530    /// `#[serde(rename_all = "SCREAMING_SNAKE_CASE")]` needed no per-variant
1531    /// `#[serde(rename = "…")]` override for any multi-word constant (`SUPERSECTION_BOTANY`,
1532    /// `INFRASPECIFIC_NAME`, `FORMA_SPECIALIS`, …) — generated mechanically from `Rank.java`
1533    /// itself, not hand-transcribed.
1534    #[test]
1535    fn rank_all_117_variants_in_java_declaration_order() {
1536        let expected: [(Rank, &str); 117] = [
1537            (Rank::Superdomain, "SUPERDOMAIN"),
1538            (Rank::Domain, "DOMAIN"),
1539            (Rank::Subdomain, "SUBDOMAIN"),
1540            (Rank::Infradomain, "INFRADOMAIN"),
1541            (Rank::Empire, "EMPIRE"),
1542            (Rank::Realm, "REALM"),
1543            (Rank::Subrealm, "SUBREALM"),
1544            (Rank::Superkingdom, "SUPERKINGDOM"),
1545            (Rank::Kingdom, "KINGDOM"),
1546            (Rank::Subkingdom, "SUBKINGDOM"),
1547            (Rank::Infrakingdom, "INFRAKINGDOM"),
1548            (Rank::Superphylum, "SUPERPHYLUM"),
1549            (Rank::Phylum, "PHYLUM"),
1550            (Rank::Subphylum, "SUBPHYLUM"),
1551            (Rank::Infraphylum, "INFRAPHYLUM"),
1552            (Rank::Parvphylum, "PARVPHYLUM"),
1553            (Rank::Microphylum, "MICROPHYLUM"),
1554            (Rank::Nanophylum, "NANOPHYLUM"),
1555            (Rank::Claudius, "CLAUDIUS"),
1556            (Rank::Gigaclass, "GIGACLASS"),
1557            (Rank::Megaclass, "MEGACLASS"),
1558            (Rank::Superclass, "SUPERCLASS"),
1559            (Rank::Class, "CLASS"),
1560            (Rank::Subclass, "SUBCLASS"),
1561            (Rank::Infraclass, "INFRACLASS"),
1562            (Rank::Subterclass, "SUBTERCLASS"),
1563            (Rank::Parvclass, "PARVCLASS"),
1564            (Rank::Superdivision, "SUPERDIVISION"),
1565            (Rank::DivisionZoology, "DIVISION_ZOOLOGY"),
1566            (Rank::Subdivision, "SUBDIVISION"),
1567            (Rank::Infradivision, "INFRADIVISION"),
1568            (Rank::Superlegion, "SUPERLEGION"),
1569            (Rank::Legion, "LEGION"),
1570            (Rank::Sublegion, "SUBLEGION"),
1571            (Rank::Infralegion, "INFRALEGION"),
1572            (Rank::Megacohort, "MEGACOHORT"),
1573            (Rank::Supercohort, "SUPERCOHORT"),
1574            (Rank::Cohort, "COHORT"),
1575            (Rank::Subcohort, "SUBCOHORT"),
1576            (Rank::Infracohort, "INFRACOHORT"),
1577            (Rank::Gigaorder, "GIGAORDER"),
1578            (Rank::Magnorder, "MAGNORDER"),
1579            (Rank::Grandorder, "GRANDORDER"),
1580            (Rank::Mirorder, "MIRORDER"),
1581            (Rank::Superorder, "SUPERORDER"),
1582            (Rank::Order, "ORDER"),
1583            (Rank::Nanorder, "NANORDER"),
1584            (Rank::Hypoorder, "HYPOORDER"),
1585            (Rank::Minorder, "MINORDER"),
1586            (Rank::Suborder, "SUBORDER"),
1587            (Rank::Infraorder, "INFRAORDER"),
1588            (Rank::Parvorder, "PARVORDER"),
1589            (Rank::SupersectionZoology, "SUPERSECTION_ZOOLOGY"),
1590            (Rank::SectionZoology, "SECTION_ZOOLOGY"),
1591            (Rank::SubsectionZoology, "SUBSECTION_ZOOLOGY"),
1592            (Rank::SuperseriesZoology, "SUPERSERIES_ZOOLOGY"),
1593            (Rank::SeriesZoology, "SERIES_ZOOLOGY"),
1594            (Rank::SubseriesZoology, "SUBSERIES_ZOOLOGY"),
1595            (Rank::Falanx, "FALANX"),
1596            (Rank::Gigafamily, "GIGAFAMILY"),
1597            (Rank::Megafamily, "MEGAFAMILY"),
1598            (Rank::Grandfamily, "GRANDFAMILY"),
1599            (Rank::Superfamily, "SUPERFAMILY"),
1600            (Rank::Epifamily, "EPIFAMILY"),
1601            (Rank::Family, "FAMILY"),
1602            (Rank::Subfamily, "SUBFAMILY"),
1603            (Rank::Infrafamily, "INFRAFAMILY"),
1604            (Rank::Supertribe, "SUPERTRIBE"),
1605            (Rank::Tribe, "TRIBE"),
1606            (Rank::Subtribe, "SUBTRIBE"),
1607            (Rank::Infratribe, "INFRATRIBE"),
1608            (Rank::SupragenericName, "SUPRAGENERIC_NAME"),
1609            (Rank::Supergenus, "SUPERGENUS"),
1610            (Rank::Genus, "GENUS"),
1611            (Rank::Subgenus, "SUBGENUS"),
1612            (Rank::Infragenus, "INFRAGENUS"),
1613            (Rank::DivisionBotany, "DIVISION_BOTANY"),
1614            (Rank::SupersectionBotany, "SUPERSECTION_BOTANY"),
1615            (Rank::SectionBotany, "SECTION_BOTANY"),
1616            (Rank::SubsectionBotany, "SUBSECTION_BOTANY"),
1617            (Rank::SuperseriesBotany, "SUPERSERIES_BOTANY"),
1618            (Rank::SeriesBotany, "SERIES_BOTANY"),
1619            (Rank::SubseriesBotany, "SUBSERIES_BOTANY"),
1620            (Rank::InfragenericName, "INFRAGENERIC_NAME"),
1621            (Rank::SpeciesAggregate, "SPECIES_AGGREGATE"),
1622            (Rank::Species, "SPECIES"),
1623            (Rank::InfraspecificName, "INFRASPECIFIC_NAME"),
1624            (Rank::Grex, "GREX"),
1625            (Rank::Klepton, "KLEPTON"),
1626            (Rank::Subspecies, "SUBSPECIES"),
1627            (Rank::CultivarGroup, "CULTIVAR_GROUP"),
1628            (Rank::Convariety, "CONVARIETY"),
1629            (Rank::InfrasubspecificName, "INFRASUBSPECIFIC_NAME"),
1630            (Rank::Proles, "PROLES"),
1631            (Rank::Natio, "NATIO"),
1632            (Rank::Aberration, "ABERRATION"),
1633            (Rank::Morph, "MORPH"),
1634            (Rank::Supervariety, "SUPERVARIETY"),
1635            (Rank::Variety, "VARIETY"),
1636            (Rank::Subvariety, "SUBVARIETY"),
1637            (Rank::Superform, "SUPERFORM"),
1638            (Rank::Form, "FORM"),
1639            (Rank::Subform, "SUBFORM"),
1640            (Rank::Pathovar, "PATHOVAR"),
1641            (Rank::Biovar, "BIOVAR"),
1642            (Rank::Chemovar, "CHEMOVAR"),
1643            (Rank::Morphovar, "MORPHOVAR"),
1644            (Rank::Phagovar, "PHAGOVAR"),
1645            (Rank::Serovar, "SEROVAR"),
1646            (Rank::Chemoform, "CHEMOFORM"),
1647            (Rank::FormaSpecialis, "FORMA_SPECIALIS"),
1648            (Rank::Lusus, "LUSUS"),
1649            (Rank::Cultivar, "CULTIVAR"),
1650            (Rank::Mutatio, "MUTATIO"),
1651            (Rank::Strain, "STRAIN"),
1652            (Rank::Other, "OTHER"),
1653            (Rank::Unranked, "UNRANKED"),
1654        ];
1655        assert_eq!(expected.len(), 117);
1656        assert_eq!(Rank::ALL.len(), 117);
1657        for (i, (rank, name)) in expected.iter().enumerate() {
1658            assert_eq!(Rank::ALL[i], *rank, "Rank::ALL[{i}] should be {rank:?}");
1659            assert_eq!(rank.ordinal(), i, "{rank:?}.ordinal() should be {i}");
1660            assert_eq!(
1661                serde_json::to_string(rank).unwrap(),
1662                format!("\"{name}\""),
1663                "{rank:?} should serialize to \"{name}\""
1664            );
1665        }
1666    }
1667
1668    /// TDD sample from the task brief: a handful of code-carrying ranks not already
1669    /// exercised above, including the new `REALM` (`VIRUS`) variant.
1670    #[test]
1671    fn rank_code_tdd_sample() {
1672        assert_eq!(Rank::Cultivar.code(), Some(NomCode::Cultivars));
1673        assert_eq!(Rank::Subgenus.code(), None);
1674        assert_eq!(Rank::Pathovar.code(), Some(NomCode::Bacterial));
1675        assert_eq!(Rank::SectionBotany.code(), Some(NomCode::Botanical));
1676        assert_eq!(Rank::Realm.code(), Some(NomCode::Virus));
1677        assert_eq!(Rank::Subrealm.code(), Some(NomCode::Virus));
1678    }
1679
1680    /// TDD sample from the task brief: the ordinal predicates.
1681    #[test]
1682    fn rank_ordinal_predicates_tdd_sample() {
1683        assert!(Rank::Subspecies.is_infraspecific());
1684        assert!(!Rank::Species.is_infraspecific());
1685        assert!(Rank::Subgenus.is_infrageneric_strictly());
1686        assert!(!Rank::Genus.is_infrageneric_strictly());
1687        assert!(!Rank::Species.is_infrageneric_strictly());
1688        assert!(Rank::Family.is_suprageneric());
1689        assert!(!Rank::Genus.is_suprageneric());
1690        assert!(Rank::Genus.higher_than(Rank::Species));
1691        assert!(!Rank::Species.higher_than(Rank::Genus));
1692        assert!(Rank::Species.higher_than(Rank::Subspecies));
1693        assert!(Rank::Subspecies.lower_than(Rank::Species));
1694        assert!(!Rank::Genus.higher_than(Rank::Other));
1695        assert!(!Rank::Genus.higher_than(Rank::Unranked));
1696    }
1697
1698    #[test]
1699    fn rank_markers_tdd_sample() {
1700        assert_eq!(Rank::Subspecies.marker(), Some("subsp."));
1701        assert_eq!(Rank::Species.marker(), Some("sp."));
1702        assert_eq!(Rank::CultivarGroup.marker(), None);
1703        assert_eq!(Rank::Other.marker(), None);
1704        assert_eq!(Rank::Unranked.marker(), None);
1705        // Zoology/botany pairs share their marker text verbatim.
1706        assert_eq!(Rank::SectionZoology.marker(), Rank::SectionBotany.marker());
1707        assert_eq!(
1708            Rank::DivisionZoology.marker(),
1709            Rank::DivisionBotany.marker()
1710        );
1711    }
1712
1713    #[test]
1714    fn rank_plural_sample() {
1715        assert_eq!(Rank::Species.plural(), Some("species"));
1716        assert_eq!(Rank::Genus.plural(), Some("genera"));
1717        assert_eq!(Rank::Falanx.plural(), Some("falanges"));
1718        assert_eq!(Rank::Lusus.plural(), Some("lusi"));
1719        assert_eq!(Rank::CultivarGroup.plural(), None);
1720        assert_eq!(Rank::Other.plural(), None);
1721        assert_eq!(Rank::Unranked.plural(), None);
1722        // Java's un-de-underscored default plural (`name().toLowerCase() + "s"`),
1723        // transcribed verbatim rather than "fixed".
1724        assert_eq!(Rank::DivisionZoology.plural(), Some("division_zoologys"));
1725        assert_eq!(Rank::SectionBotany.plural(), Some("section_botanys"));
1726        // Explicit Java plural shared by a zoology/botany pair.
1727        assert_eq!(Rank::SeriesZoology.plural(), Some("series"));
1728        assert_eq!(Rank::SeriesBotany.plural(), Some("series"));
1729    }
1730
1731    #[test]
1732    fn rank_is_family_group_and_genus_group() {
1733        assert!(Rank::Family.is_family_group());
1734        assert!(Rank::Gigafamily.is_family_group());
1735        assert!(!Rank::SupragenericName.is_family_group());
1736        assert!(!Rank::Genus.is_family_group());
1737        assert!(Rank::Genus.is_genus_group());
1738        assert!(Rank::Supergenus.is_genus_group());
1739        assert!(Rank::Subgenus.is_genus_group());
1740        assert!(!Rank::SpeciesAggregate.is_genus_group());
1741        assert!(!Rank::SupragenericName.is_genus_group());
1742    }
1743
1744    #[test]
1745    fn rank_is_species_or_below() {
1746        assert!(Rank::SpeciesAggregate.is_species_or_below());
1747        assert!(Rank::Species.is_species_or_below());
1748        assert!(Rank::Subspecies.is_species_or_below());
1749        assert!(!Rank::Genus.is_species_or_below());
1750        assert!(!Rank::Other.is_species_or_below());
1751        assert!(!Rank::Unranked.is_species_or_below());
1752    }
1753
1754    #[test]
1755    fn rank_is_uncomparable() {
1756        assert!(Rank::SupragenericName.is_uncomparable());
1757        assert!(Rank::InfragenericName.is_uncomparable());
1758        assert!(Rank::InfraspecificName.is_uncomparable());
1759        assert!(Rank::InfrasubspecificName.is_uncomparable());
1760        assert!(Rank::Other.is_uncomparable());
1761        assert!(Rank::Unranked.is_uncomparable());
1762        assert!(!Rank::Species.is_uncomparable());
1763        assert!(!Rank::Genus.is_uncomparable());
1764    }
1765
1766    #[test]
1767    fn rank_is_legacy() {
1768        for r in [
1769            Rank::Morph,
1770            Rank::Aberration,
1771            Rank::Natio,
1772            Rank::Proles,
1773            Rank::Convariety,
1774            Rank::Klepton,
1775            Rank::Falanx,
1776            Rank::Lusus,
1777        ] {
1778            assert!(r.is_legacy(), "{r:?} should be legacy");
1779        }
1780        assert!(!Rank::Species.is_legacy());
1781        assert!(!Rank::Subspecies.is_legacy());
1782    }
1783
1784    #[test]
1785    fn rank_is_linnean() {
1786        for r in Rank::LINNEAN_RANKS {
1787            assert!(r.is_linnean(), "{r:?} should be Linnean");
1788        }
1789        assert!(!Rank::Subgenus.is_linnean());
1790        assert!(!Rank::Subspecies.is_linnean());
1791        assert_eq!(Rank::LINNEAN_RANKS.len(), 7);
1792    }
1793
1794    #[test]
1795    fn rank_is_restricted_to_code_matches_code() {
1796        assert_eq!(
1797            Rank::Cultivar.is_restricted_to_code(),
1798            Rank::Cultivar.code()
1799        );
1800        assert_eq!(Rank::Species.is_restricted_to_code(), Rank::Species.code());
1801    }
1802
1803    #[test]
1804    fn rank_has_ambiguous_marker() {
1805        // The 7 zoology/botany pairs that share marker text are ambiguous...
1806        for r in [
1807            Rank::DivisionZoology,
1808            Rank::DivisionBotany,
1809            Rank::SectionZoology,
1810            Rank::SectionBotany,
1811            Rank::SubsectionZoology,
1812            Rank::SubsectionBotany,
1813            Rank::SupersectionZoology,
1814            Rank::SupersectionBotany,
1815            Rank::SeriesZoology,
1816            Rank::SeriesBotany,
1817            Rank::SubseriesZoology,
1818            Rank::SubseriesBotany,
1819            Rank::SuperseriesZoology,
1820            Rank::SuperseriesBotany,
1821        ] {
1822            assert!(r.has_ambiguous_marker(), "{r:?} should be ambiguous");
1823        }
1824        // ...but a rank with a unique marker is not.
1825        assert!(!Rank::Species.has_ambiguous_marker());
1826        assert!(!Rank::Genus.has_ambiguous_marker());
1827        assert!(!Rank::Cultivar.has_ambiguous_marker());
1828    }
1829
1830    /// `Rank::get_major_rank()` — the automatic prefix-strip cases (no manual fix needed).
1831    #[test]
1832    fn rank_get_major_rank_automatic() {
1833        assert_eq!(Rank::Subphylum.get_major_rank(), Rank::Phylum);
1834        assert_eq!(Rank::Nanophylum.get_major_rank(), Rank::Phylum);
1835        assert_eq!(Rank::Subclass.get_major_rank(), Rank::Class);
1836        // Greedy `SUBTER` (tried before plain `SUB`) strips correctly to `CLASS`.
1837        assert_eq!(Rank::Subterclass.get_major_rank(), Rank::Class);
1838        assert_eq!(Rank::SubsectionBotany.get_major_rank(), Rank::SectionBotany);
1839        assert_eq!(
1840            Rank::SupersectionZoology.get_major_rank(),
1841            Rank::SectionZoology
1842        );
1843        // A rank with no prefix at all maps to itself (never `None`/a sentinel).
1844        assert_eq!(Rank::Species.get_major_rank(), Rank::Species);
1845        assert_eq!(Rank::Genus.get_major_rank(), Rank::Genus);
1846        assert_eq!(Rank::Other.get_major_rank(), Rank::Other);
1847        assert_eq!(Rank::Unranked.get_major_rank(), Rank::Unranked);
1848    }
1849
1850    /// `Rank::get_major_rank()` — the 6 manual fixes (`Rank.java:399-407`), each a case the
1851    /// automatic algorithm alone cannot resolve (see [`MAJOR_RANKS`]'s own doc comment).
1852    #[test]
1853    fn rank_get_major_rank_manual_fixes() {
1854        assert_eq!(Rank::Nanorder.get_major_rank(), Rank::Order);
1855        assert_eq!(Rank::SpeciesAggregate.get_major_rank(), Rank::Species);
1856        assert_eq!(Rank::InfragenericName.get_major_rank(), Rank::Genus);
1857        assert_eq!(Rank::Superdivision.get_major_rank(), Rank::DivisionZoology);
1858        assert_eq!(Rank::Subdivision.get_major_rank(), Rank::DivisionZoology);
1859        assert_eq!(Rank::Infradivision.get_major_rank(), Rank::DivisionZoology);
1860    }
1861
1862    /// `Rank::get_major_rank()` — every infraspecific rank (ordinal-wise, per
1863    /// `is_infraspecific()`) collapses to `INFRASPECIFIC_NAME`, including ones that aren't
1864    /// obviously "infraspecific" by name (`KLEPTON`, `CULTIVAR_GROUP`).
1865    #[test]
1866    fn rank_get_major_rank_infraspecific_collapse() {
1867        for r in [
1868            Rank::Grex,
1869            Rank::Klepton,
1870            Rank::Subspecies,
1871            Rank::CultivarGroup,
1872            Rank::Variety,
1873            Rank::Cultivar,
1874            Rank::Strain,
1875        ] {
1876            assert_eq!(
1877                r.get_major_rank(),
1878                Rank::InfraspecificName,
1879                "{r:?} should collapse to INFRASPECIFIC_NAME"
1880            );
1881        }
1882    }
1883
1884    /// `rank_utils::suffices_rank_map` — Assemble step 14's suffix->rank data, per code.
1885    #[test]
1886    fn rank_utils_suffices_rank_map_sample() {
1887        let bot = rank_utils::suffices_rank_map(NomCode::Botanical).unwrap();
1888        assert!(bot.contains(&("aceae", Rank::Family)));
1889        assert!(bot.contains(&("oideae", Rank::Subfamily)));
1890
1891        let zoo = rank_utils::suffices_rank_map(NomCode::Zoological).unwrap();
1892        assert!(zoo.contains(&("idae", Rank::Family)));
1893        assert!(zoo.contains(&("oidae", Rank::Epifamily)));
1894        // "idae" means FAMILY under zoology but SUBCLASS under botany/bacteriology —
1895        // confirms the map is genuinely per-code, not a single global lookup.
1896        let bact = rank_utils::suffices_rank_map(NomCode::Bacterial).unwrap();
1897        assert!(bact.contains(&("idae", Rank::Subclass)));
1898
1899        let virus = rank_utils::suffices_rank_map(NomCode::Virus).unwrap();
1900        assert!(virus.contains(&("viridae", Rank::Family)));
1901
1902        // Codes with no suffix map at all return None (mirrors Java's `Map.get` on a
1903        // missing key), not an empty slice.
1904        assert_eq!(rank_utils::suffices_rank_map(NomCode::Cultivars), None);
1905        assert_eq!(rank_utils::suffices_rank_map(NomCode::Phyto), None);
1906        assert_eq!(rank_utils::suffices_rank_map(NomCode::Phylo), None);
1907    }
1908
1909    // ---- Phase 3 (FFM binding): Rank::from_name / NomCode::from_name ----
1910
1911    /// Every one of the 117 `Rank` variants round-trips through its own wire name — the
1912    /// exhaustive version of the pin below, covering multi-word constants like
1913    /// `SUPERSECTION_BOTANY` and `FORMA_SPECIALIS` too, not just a hand-picked sample.
1914    #[test]
1915    fn rank_from_name_round_trips_every_variant_via_its_own_serialize_impl() {
1916        for &r in Rank::ALL.iter() {
1917            let name = rank_wire_name(r);
1918            assert_eq!(
1919                Rank::from_name(&name),
1920                Some(r),
1921                "round-trip failed for {r:?}"
1922            );
1923        }
1924    }
1925
1926    #[test]
1927    fn rank_from_name_pins_a_multi_word_constant_and_rejects_nonsense() {
1928        assert_eq!(Rank::from_name("SPECIES"), Some(Rank::Species));
1929        assert_eq!(
1930            Rank::from_name("DIVISION_ZOOLOGY"),
1931            Some(Rank::DivisionZoology)
1932        );
1933        assert_eq!(Rank::from_name("NONSENSE"), None);
1934        assert_eq!(Rank::from_name(""), None);
1935    }
1936
1937    /// Every one of the 7 `NomCode` variants round-trips through its own wire name —
1938    /// guards `NomCode::from_name`'s hand-written match against drifting from the real
1939    /// `#[derive(Serialize)]` output it's meant to reverse.
1940    #[test]
1941    fn nomcode_from_name_round_trips_every_variant_via_its_own_serialize_impl() {
1942        for &c in &[
1943            NomCode::Bacterial,
1944            NomCode::Botanical,
1945            NomCode::Cultivars,
1946            NomCode::Phyto,
1947            NomCode::Virus,
1948            NomCode::Zoological,
1949            NomCode::Phylo,
1950        ] {
1951            let name = serde_json::to_string(&c)
1952                .unwrap()
1953                .trim_matches('"')
1954                .to_string();
1955            assert_eq!(
1956                NomCode::from_name(&name),
1957                Some(c),
1958                "round-trip failed for {c:?}"
1959            );
1960        }
1961    }
1962
1963    #[test]
1964    fn nomcode_from_name_pins_botanical_and_rejects_nonsense() {
1965        assert_eq!(NomCode::from_name("BOTANICAL"), Some(NomCode::Botanical));
1966        assert_eq!(NomCode::from_name("NONSENSE"), None);
1967    }
1968}