nameparser/lib.rs
1// SPDX-License-Identifier: Apache-2.0
2
3//! A faithful Rust port of the GBIF scientific name parser. [`parse_name`] turns a scientific name into
4//! its structured atoms — genus, epithets, authorship, rank, nomenclatural code, notes, warnings —
5//! as a [`model::ParsedName`]. Byte-for-byte cross-validated against the Java `name-parser`
6//! (`NameParserImpl`) over 11,302 + 6.4M names (0 diffs). The same engine also ships as a native
7//! CLI and as Java/Python/R bindings — see the repository README.
8
9pub mod format;
10pub mod model;
11pub mod pipeline;
12pub mod regexes;
13pub mod token;
14pub mod unicode;
15pub mod viral;
16
17use model::{Informal, NameType, NomCode, ParseError, ParsedName, Rank};
18
19/// The lower-level raw parse: a scientific name — optionally alongside a separately supplied
20/// authorship string, a requested [`Rank`] and a requested [`NomCode`] — into a [`ParsedName`], or
21/// `Err(`[`ParseError`]`)` when the input cannot be parsed into a meaningful name. Delegates to
22/// [`pipeline::run`].
23///
24/// This is the raw `ParsedName`/error path — informal names come back as `Ok(ParsedName)` with
25/// `type == INFORMAL`, NOT split off. It backs the golden snapshot, the FFI/CLI/R encoders (which
26/// need the full `ParsedName` and derive the three-way at their own boundary), and any caller that
27/// wants the structured atoms directly. **Most callers want [`parse`] instead** — the primary 5.0.0
28/// exceptionless entry point that returns the three-way [`ParseResult`].
29pub fn parse_name(
30 name: &str,
31 authorship: Option<&str>,
32 rank: Option<Rank>,
33 code: Option<NomCode>,
34) -> Result<ParsedName, ParseError> {
35 pipeline::run(name, authorship, rank, code)
36}
37
38/// The 5.0.0 exceptionless result of [`parse`], mirroring Java
39/// `org.gbif.nameparser.api.ParseResult`: a structurally [`Parsed`](ParseResult::Parsed) name, an
40/// [`Informal`](ParseResult::Informal) semistructured name (a taxon anchor carrying a provisional
41/// designation, e.g. `Rhizobium sp. RMCC TR1811`), or an [`Unparsable`](ParseResult::Unparsable)
42/// classification (virus, hybrid formula, placeholder, BOLD BIN, ...). The 5.5%-of-corpus informal
43/// band is split off from `Parsed` at the [`parse`] boundary — see the verbatim-corpus study.
44///
45/// `Parsed` is far larger than the other two variants (it wraps the ~1 KB [`ParsedName`] vs ~56 B
46/// for [`Informal`]/[`ParseError`]), so `clippy::large_enum_variant` fires — but `Parsed` is the
47/// dominant outcome (≈89% of the corpus) and the value is decomposed immediately at the call
48/// boundary, so boxing it would add a heap allocation to the common path for no real gain. This
49/// mirrors [`parse_name`]'s own `Result<ParsedName, ParseError>`, which carries the identical size
50/// profile unboxed.
51#[allow(clippy::large_enum_variant)]
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum ParseResult {
54 /// A structurally parsed name carrying the full [`ParsedName`] atoms.
55 Parsed(ParsedName),
56 /// An informal / semistructured name: a supraspecific anchor + a provisional, non-code
57 /// designation, with no species epithet. See [`Informal`].
58 Informal(Informal),
59 /// A string that is not a parsable scientific name (virus, hybrid formula, placeholder, ...).
60 Unparsable(ParseError),
61}
62
63impl ParseResult {
64 /// The name type, available on every variant (Java `ParseResult.type()`).
65 pub fn type_(&self) -> NameType {
66 match self {
67 ParseResult::Parsed(pn) => pn.type_,
68 ParseResult::Informal(_) => NameType::Informal,
69 ParseResult::Unparsable(e) => e.type_,
70 }
71 }
72
73 /// The nomenclatural code when known, else `None` — available on every variant (Java `code()`).
74 pub fn code(&self) -> Option<NomCode> {
75 match self {
76 ParseResult::Parsed(pn) => pn.code,
77 ParseResult::Informal(i) => i.code,
78 ParseResult::Unparsable(e) => e.code,
79 }
80 }
81
82 /// The parsed name if this is [`ParseResult::Parsed`], else `None` (Java `parsed()`).
83 /// [`ParseResult::Informal`] and [`ParseResult::Unparsable`] carry no [`ParsedName`].
84 pub fn parsed(&self) -> Option<&ParsedName> {
85 match self {
86 ParseResult::Parsed(pn) => Some(pn),
87 _ => None,
88 }
89 }
90
91 /// True iff this carries a structured [`ParsedName`] — i.e. is a [`ParseResult::Parsed`]
92 /// (Java `isParsable()`).
93 pub fn is_parsable(&self) -> bool {
94 matches!(self, ParseResult::Parsed(_))
95 }
96}
97
98/// The primary 5.0.0 exceptionless entry point (mirrors Java `NameParser.parse()`): classifies a
99/// scientific name into the three-way [`ParseResult`] (`Parsed | Informal | Unparsable`) that every
100/// binding exposes, never throwing. The informal split is applied here — a supraspecific taxon
101/// carrying a provisional designation with NO species epithet becomes [`ParseResult::Informal`]; a
102/// name with a species epithet (including cf./aff. and infraspecific-indeterminate binomials) stays
103/// [`ParseResult::Parsed`], so its `specific_authorship` — which a flat anchor could not represent —
104/// is preserved. For the raw `ParsedName`/error shape (no informal split), use [`parse_name`].
105pub fn parse(
106 name: &str,
107 authorship: Option<&str>,
108 rank: Option<Rank>,
109 code: Option<NomCode>,
110) -> ParseResult {
111 match pipeline::run(name, authorship, rank, code) {
112 Ok(pn) if is_informal(&pn) => ParseResult::Informal(to_informal(pn)),
113 // `Parsed` may only carry a parsable type: a placeholder with its genus missing ("? alba
114 // Smith", "Missing penchinati Bourguignat, 1870") is reported unparsable, like any other
115 // placeholder; `parse_name` still returns its parts.
116 Ok(pn) if !pn.type_.is_parsable() => {
117 ParseResult::Unparsable(ParseError::new(pn.type_, pn.code, name))
118 }
119 Ok(pn) => ParseResult::Parsed(pn),
120 // `Unparsable` may only carry a non-parsable type (mirrors Java); the core's error path
121 // can still tag an informal-but-unrepresentable grouping as INFORMAL — clamp it to OTHER.
122 Err(e) => ParseResult::Unparsable(e.clamped_to_unparsable()),
123 }
124}
125
126/// The informal discriminator (settled via the 67.5M verbatim-corpus study): an `INFORMAL`-typed
127/// name with a real supraspecific anchor but NO species epithet is an [`ParseResult::Informal`];
128/// everything else parsable stays `Parsed`. Keying on `specific_epithet` routes cf./aff. and
129/// infraspecific-indeterminate binomials to `Parsed` automatically (they keep a species epithet),
130/// so their `epithet_qualifier` annotation and `specific_authorship` survive. An infraspecific
131/// epithet under a bare genus ("Navicula var. fasciata Grunow") stays `Parsed` for the same reason:
132/// the anchor has no slot for the epithet or its author. The anchor guard keeps a degenerate
133/// anchor-less `INFORMAL` (should not occur on the `Ok` path) out of `Informal`.
134fn is_informal(pn: &ParsedName) -> bool {
135 pn.type_ == NameType::Informal
136 && pn.specific_epithet.is_none()
137 && pn.infraspecific_epithet.is_none()
138 && (pn.genus.is_some() || pn.uninomial.is_some() || pn.infrageneric_epithet.is_some())
139}
140
141/// Derive the flat [`Informal`] anchor from an informal [`ParsedName`]. The anchor sits in the
142/// `genus` slot for the overwhelming `Genus sp. <tag>` majority (→ `taxon_rank = GENUS`, even when
143/// the word is really a family the unvalidated parser cannot know that); a bare supraspecific
144/// monomial falls back to `uninomial` (then `infrageneric`) at the name's own rank. Precondition:
145/// [`is_informal`] held, so at least one anchor slot is populated.
146fn to_informal(pn: ParsedName) -> Informal {
147 let (taxon, taxon_rank) = if let Some(g) = pn.genus.as_deref() {
148 (g.to_string(), Rank::Genus)
149 } else if let Some(u) = pn.uninomial.as_deref() {
150 (u.to_string(), pn.rank)
151 } else {
152 (pn.infrageneric_epithet.clone().unwrap_or_default(), pn.rank)
153 };
154 Informal {
155 taxon,
156 taxon_rank,
157 rank: pn.rank,
158 phrase: pn.phrase,
159 code: pn.code,
160 }
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166 use model::NameType;
167
168 #[test]
169 fn parse_delegates_to_pipeline_run() {
170 let pn = parse_name("Abies alba", None, None, None).expect("should parse");
171 assert_eq!(pn.type_, NameType::Scientific);
172 }
173
174 #[test]
175 fn parse_rejects_empty_input() {
176 let err = parse_name("", None, None, None).unwrap_err();
177 assert_eq!(err.type_, NameType::Other);
178 }
179
180 /// The three-way [`parse`] classifier + the flat [`Informal`] derivation, on cases whose
181 /// outcome is independent of the (separate) trailing-tag-capture parser change: an already-captured
182 /// phrase (`Serratia sp. RE1-2a`), a bare `Genus sp.`, and a numbered placeholder route to
183 /// `Informal`; a binomial core (species epithet present) and a bare determined genus stay `Parsed`;
184 /// empty input is `Unparsable`.
185 #[test]
186 fn parse_classifies_three_way() {
187 use model::Rank;
188
189 // --- Informal: supraspecific anchor + provisional designation, no species epithet ---
190 match parse("Serratia sp. RE1-2a", None, None, None) {
191 ParseResult::Informal(i) => {
192 assert_eq!(i.taxon, "Serratia");
193 assert_eq!(i.taxon_rank, Rank::Genus);
194 assert_eq!(i.rank, Rank::Species);
195 assert_eq!(i.phrase.as_deref(), Some("sp. RE1-2a"));
196 }
197 other => panic!("expected Informal, got {other:?}"),
198 }
199 // bare "Genus sp." — no distinguishing tag, but the verbatim marker is still the phrase
200 match parse("Rhizobium sp.", None, None, None) {
201 ParseResult::Informal(i) => {
202 assert_eq!(i.taxon, "Rhizobium");
203 assert_eq!(i.taxon_rank, Rank::Genus);
204 assert_eq!(i.rank, Rank::Species);
205 assert_eq!(i.phrase.as_deref(), Some("sp."));
206 }
207 other => panic!("expected Informal, got {other:?}"),
208 }
209 // numbered placeholder
210 match parse("Allium sp. 1", None, None, None) {
211 ParseResult::Informal(i) => {
212 assert_eq!(i.taxon, "Allium");
213 assert_eq!(i.phrase.as_deref(), Some("sp. 1"));
214 }
215 other => panic!("expected Informal, got {other:?}"),
216 }
217
218 // --- Parsed: a species epithet is present (binomial core), so it is NOT Informal ---
219 // infraspecific-indeterminate — authorship would land in specific_authorship, unrepresentable flat
220 assert!(
221 matches!(
222 parse("Salix alba subsp. B", None, None, None),
223 ParseResult::Parsed(_)
224 ),
225 "infraspecific-indet binomial must stay Parsed"
226 );
227 // cf. qualifier on a complete binomial — the qualifier is an annotation, not a reclassification
228 match parse("Salicornia cf. patula", None, None, None) {
229 ParseResult::Parsed(pn) => assert_eq!(pn.specific_epithet.as_deref(), Some("patula")),
230 other => panic!("expected Parsed, got {other:?}"),
231 }
232 // a plain determined binomial and a bare determined genus
233 assert!(parse("Abies alba", None, None, None).is_parsable());
234 assert!(parse("Rhizobium", None, None, None).is_parsable());
235
236 // --- Unparsable ---
237 match parse("", None, None, None) {
238 ParseResult::Unparsable(e) => assert_eq!(e.type_, NameType::Other),
239 other => panic!("expected Unparsable, got {other:?}"),
240 }
241 }
242
243 /// The 5.0.0 boundary clamp — a defensive invariant that `Unparsable` may only carry a
244 /// non-parsable type. Since the preflight informal-group rescue landed, NO real input produces an
245 /// error:INFORMAL anymore (anchored groupings are rescued to `Informal`; the rest emit OTHER —
246 /// see `pipeline::preflight`), so this exercises the clamp DIRECTLY on a synthetic `ParseError`,
247 /// then confirms an anchorless clade label is `Unparsable(OTHER)` end to end.
248 #[test]
249 fn clamped_to_unparsable_forces_a_nonparsable_type() {
250 use model::{NomCode, ParseError};
251
252 // a parsable error type is forced to OTHER; code preserved, message rebuilt for the new type
253 let clamped = ParseError::new(NameType::Informal, Some(NomCode::Bacterial), "X group")
254 .clamped_to_unparsable();
255 assert_eq!(clamped.type_, NameType::Other);
256 assert!(!clamped.type_.is_parsable());
257 assert_eq!(clamped.code, Some(NomCode::Bacterial));
258 assert_eq!(clamped.message, "Unparsable OTHER name: X group");
259
260 // a non-parsable error is left untouched
261 let other = ParseError::new(NameType::Other, None, "junk");
262 assert_eq!(other.clone().clamped_to_unparsable(), other);
263
264 // end to end: an anchorless clade label is Unparsable(OTHER)
265 match parse("Amauropeltoid clade", None, None, None) {
266 ParseResult::Unparsable(e) => assert_eq!(e.type_, NameType::Other),
267 other => panic!("expected Unparsable(OTHER), got {other:?}"),
268 }
269 }
270}