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