nameparser/model/mod.rs
1// SPDX-License-Identifier: Apache-2.0
2pub mod enums;
3pub use enums::*;
4pub mod name;
5pub use name::*;
6
7/// Java `Enum.name()` — the exact SCREAMING_SNAKE_CASE identifier (e.g. `OTHER`), as opposed to
8/// Rust's `{:?}` (e.g. `Other`). Reuses each wire enum's own `Serialize` impl — which already
9/// carries `#[serde(rename_all = "SCREAMING_SNAKE_CASE")]` — rather than a hand-maintained match,
10/// so the two representations cannot drift apart.
11fn java_name<T: serde::Serialize>(value: &T) -> String {
12 serde_json::to_string(value)
13 .expect("wire enums always serialize to a JSON string")
14 .trim_matches('"')
15 .to_string()
16}
17
18/// Rust equivalent of Java UnparsableNameException (type/code/name/message).
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct ParseError {
21 pub type_: NameType,
22 pub code: Option<NomCode>,
23 pub name: String,
24 pub message: String,
25}
26impl ParseError {
27 pub fn new(type_: NameType, code: Option<NomCode>, name: impl Into<String>) -> Self {
28 let name = name.into();
29 // Java: `"Unparsable " + type + " name: " + name`, where `type` is a NameType and string
30 // concatenation calls its (un-overridden) `Enum.toString()`, i.e. `.name()` — UPPERCASE.
31 let message = format!("Unparsable {} name: {name}", java_name(&type_));
32 Self {
33 type_,
34 code,
35 name,
36 message,
37 }
38 }
39
40 /// Clamp a parsable [`NameType`] to [`NameType::Other`] so this error is legal as a 5.0.0
41 /// `Unparsable` result. The core's error path can still tag an unrepresentable-but-informal
42 /// grouping (`"Bartonella group"`, `"Amauropeltoid clade"`) as `INFORMAL`, but the 5.0.0
43 /// `ParseResult::Unparsable` variant — mirroring Java's, whose record rejects `isParsable()`
44 /// types — may only carry a non-parsable type. Applied ONLY at the 5.0.0 boundaries
45 /// ([`crate::parse`] and the FFI); [`crate::parse_name`] (the raw path, cross-validated
46 /// byte-for-byte against Java 4.2.0) keeps the original `INFORMAL`, so the golden oracles are
47 /// untouched. Rebuilds the message via [`Self::new`] so it names the clamped type.
48 pub fn clamped_to_unparsable(self) -> ParseError {
49 if self.type_.is_parsable() {
50 ParseError::new(NameType::Other, self.code, self.name)
51 } else {
52 self
53 }
54 }
55}
56
57/// An informal / semistructured name — the payload of [`crate::ParseResult::Informal`], mirroring
58/// Java `org.gbif.nameparser.api.ParseResult.Informal`.
59///
60/// A real supraspecific taxon ([`Self::taxon`], a genus or higher uninomial) carrying a provisional,
61/// non-code designation instead of a determined species epithet: a molecular provisional species
62/// (`Rhizobium sp. RMCC TR1811`), a numbered placeholder (`Allium sp. 1`), or an informal group.
63/// The 67.5M verbatim-corpus study found these are 5.5% of all real
64/// names — 1 in 18 — hence a first-class representation.
65///
66/// Deliberately a FLAT type, not a reused [`ParsedName`]: the anchor lives in one place
67/// ([`Self::taxon`] + [`Self::taxon_rank`]) and is never mislabelled as a backbone-validated
68/// "genus". Derived from an informal `ParsedName` at the [`crate::parse`] boundary. Only
69/// names with NO species epithet land here; a binomial core (incl. cf./aff. and infraspecific-indet)
70/// stays [`crate::ParseResult::Parsed`] so its `specific_authorship` is preserved.
71#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
72#[serde(rename_all = "camelCase")]
73pub struct Informal {
74 /// The supraspecific taxon it hangs off (`"Rhizobium"`, `"Ichneumonidae"`) — the parser's best
75 /// guess, NOT validated against a taxonomic backbone.
76 pub taxon: String,
77 /// That taxon's rank — `GENUS` for the overwhelming `Genus sp.` majority (the anchor sits in the
78 /// genus slot); a bare supraspecific monomial carries its own rank. The parser's best guess.
79 pub taxon_rank: Rank,
80 /// The rank the informal name purports to be — `SPECIES` for `"sp."`, `UNRANKED` for a group.
81 pub rank: Rank,
82 /// The VERBATIM tail, from the rank marker to the end of the input (`"sp. RMCC TR1811"`,
83 /// `"sp. 1"`); `None` only when there is no tail at all. An informal name is not fully
84 /// parsable by definition, so the tail is captured whole and nothing in it is interpreted —
85 /// it may therefore contain what looks like an **author citation**
86 /// (`"sp. Forster, 1968"`), which is NOT separately parsed. That is deliberate: the parser
87 /// cannot reliably tell a citation from a specimen or culture code (43% of the tails the
88 /// pre-5.0.0 rule read as authorship were spurious — impossible years, collection acronyms
89 /// like `ZRC`/`MNHN`), and on the genuinely authored minority the citation belongs to the
90 /// [`Self::taxon`] anchor rather than to the undetermined species. `taxon` + `" "` + `phrase`
91 /// reproduces the input exactly.
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub phrase: Option<String>,
94 /// The nomenclatural code when known, else `None`.
95 #[serde(skip_serializing_if = "Option::is_none")]
96 pub code: Option<NomCode>,
97}
98
99#[cfg(test)]
100mod tests {
101 use super::*;
102
103 #[test]
104 fn parse_error_message_matches_java_default() {
105 let err = ParseError::new(NameType::Other, None, "BOLD:ACW2100");
106 assert_eq!(err.message, "Unparsable OTHER name: BOLD:ACW2100");
107 }
108
109 /// `model::{NameType, NomCode, NamePart, State, Rank}` and `model::warnings` are the
110 /// documented public interface — reached via the `pub use enums::*;` re-export above, not
111 /// only via `model::enums::…`. Exercised here through fully crate-qualified paths so a future
112 /// refactor of the re-export can't silently narrow the interface without a test failure.
113 #[test]
114 fn wire_enums_and_warnings_are_reachable_at_model_top_level() {
115 assert_eq!(crate::model::warnings::LONG_NAME, "unusually long name");
116 let _: crate::model::NameType = crate::model::NameType::Scientific;
117 let _: crate::model::NomCode = crate::model::NomCode::Zoological;
118 let _: crate::model::NamePart = crate::model::NamePart::Generic;
119 let _: crate::model::State = crate::model::State::Complete;
120 let _: crate::model::Rank = crate::model::Rank::Unranked;
121 }
122
123 /// `model::{Authorship, CombinedAuthorship, ParsedName}` are likewise reached directly
124 /// under `model::`, via the `pub use name::*;` re-export above, not only via
125 /// `model::name::…`.
126 #[test]
127 fn wire_name_structs_are_reachable_at_model_top_level() {
128 let _: crate::model::Authorship = crate::model::Authorship::default();
129 let _: crate::model::CombinedAuthorship = crate::model::CombinedAuthorship::default();
130 let _: crate::model::ParsedName = crate::model::ParsedName::default();
131 }
132}