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::{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. It backs the golden snapshot, the FFI/CLI/R encoders
25/// and any caller that wants the structured atoms of every input, placeholders without a genus
26/// included. **Most callers want [`parse`] instead** — the exceptionless entry point that returns a
27/// [`ParseResult`].
28pub fn parse_name(
29 name: &str,
30 authorship: Option<&str>,
31 rank: Option<Rank>,
32 code: Option<NomCode>,
33) -> Result<ParsedName, ParseError> {
34 pipeline::run(name, authorship, rank, code)
35}
36
37/// The exceptionless result of [`parse`], mirroring Java `org.gbif.nameparser.api.ParseResult`: a
38/// structurally [`Parsed`](ParseResult::Parsed) name or an [`Unparsable`](ParseResult::Unparsable)
39/// classification (virus, hybrid formula, placeholder, BOLD BIN, ...). Informal names — provisional,
40/// open-nomenclature and indetermined ones like `Rhizobium sp. RMCC TR1811` or `Abies cf. alba` —
41/// are `Parsed` names of type [`NameType::Informal`]; [`ParsedName::anchor`] gives the real taxon
42/// they hang off.
43///
44/// `Parsed` is far larger than `Unparsable` (it wraps the ~1 KB [`ParsedName`] vs ~56 B for a
45/// [`ParseError`]), so `clippy::large_enum_variant` fires — but `Parsed` is the dominant outcome
46/// (≈95% of the corpus) and the value is decomposed immediately at the call boundary, so boxing it
47/// would add a heap allocation to the common path for no real gain. This mirrors [`parse_name`]'s
48/// own `Result<ParsedName, ParseError>`, which carries the identical size profile unboxed.
49#[allow(clippy::large_enum_variant)]
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub enum ParseResult {
52 /// A structurally parsed name carrying the full [`ParsedName`] atoms, informal names included.
53 Parsed(ParsedName),
54 /// A string that is not a parsable scientific name (virus, hybrid formula, placeholder, ...).
55 Unparsable(ParseError),
56}
57
58impl ParseResult {
59 /// The name type, available on both variants (Java `ParseResult.type()`).
60 pub fn type_(&self) -> NameType {
61 match self {
62 ParseResult::Parsed(pn) => pn.type_,
63 ParseResult::Unparsable(e) => e.type_,
64 }
65 }
66
67 /// The nomenclatural code when known, else `None` — available on both variants (Java `code()`).
68 pub fn code(&self) -> Option<NomCode> {
69 match self {
70 ParseResult::Parsed(pn) => pn.code,
71 ParseResult::Unparsable(e) => e.code,
72 }
73 }
74
75 /// The parsed name if this is [`ParseResult::Parsed`], else `None` (Java `parsed()`).
76 /// [`ParseResult::Unparsable`] carries no [`ParsedName`].
77 pub fn parsed(&self) -> Option<&ParsedName> {
78 match self {
79 ParseResult::Parsed(pn) => Some(pn),
80 ParseResult::Unparsable(_) => None,
81 }
82 }
83
84 /// True iff this carries a structured [`ParsedName`] — i.e. is a [`ParseResult::Parsed`]
85 /// (Java `isParsable()`).
86 pub fn is_parsable(&self) -> bool {
87 matches!(self, ParseResult::Parsed(_))
88 }
89}
90
91/// The primary exceptionless entry point (mirrors Java `NameParser.parse()`): classifies a
92/// scientific name into the [`ParseResult`] (`Parsed | Unparsable`) that every binding exposes,
93/// never throwing. Informal names are `Parsed`, typed [`NameType::Informal`]. For the raw
94/// `ParsedName`/error shape, use [`parse_name`].
95pub fn parse(
96 name: &str,
97 authorship: Option<&str>,
98 rank: Option<Rank>,
99 code: Option<NomCode>,
100) -> ParseResult {
101 match pipeline::run(name, authorship, rank, code) {
102 // `Parsed` carries a parsable type, or a placeholder hanging off a real taxon, its anchor
103 // ("Chromista incertae sedis", #185). A placeholder with its genus missing ("? alba Smith",
104 // "Missing penchinati Bourguignat, 1870") has none and is reported unparsable, like any other
105 // placeholder; `parse_name` still returns its parts.
106 Ok(pn)
107 if !pn.type_.is_parsable()
108 && !(pn.type_ == NameType::Placeholder && pn.anchor().is_some()) =>
109 {
110 ParseResult::Unparsable(ParseError::new(pn.type_, pn.code, name))
111 }
112 Ok(pn) => ParseResult::Parsed(pn),
113 // `Unparsable` may only carry a non-parsable type (mirrors Java); the core's error path
114 // can still tag an informal-but-unrepresentable grouping as INFORMAL — clamp it to OTHER.
115 Err(e) => ParseResult::Unparsable(e.clamped_to_unparsable()),
116 }
117}
118
119#[cfg(test)]
120mod tests {
121 use super::*;
122 use model::NameType;
123
124 #[test]
125 fn parse_delegates_to_pipeline_run() {
126 let pn = parse_name("Abies alba", None, None, None).expect("should parse");
127 assert_eq!(pn.type_, NameType::Scientific);
128 }
129
130 #[test]
131 fn parse_rejects_empty_input() {
132 let err = parse_name("", None, None, None).unwrap_err();
133 assert_eq!(err.type_, NameType::Other);
134 }
135
136 /// [`parse`] returns informal names as `Parsed` names of type INFORMAL, their anchor derived on
137 /// demand; empty input is `Unparsable`.
138 #[test]
139 fn parse_returns_informal_names_parsed() {
140 use model::Rank;
141
142 for (input, anchor, anchor_rank, phrase) in [
143 (
144 "Serratia sp. RE1-2a",
145 "Serratia",
146 Rank::Genus,
147 Some("sp. RE1-2a"),
148 ),
149 // bare "Genus sp." — no distinguishing tag, but the verbatim marker is still the phrase
150 ("Rhizobium sp.", "Rhizobium", Rank::Genus, Some("sp.")),
151 ("Allium sp. 1", "Allium", Rank::Genus, Some("sp. 1")),
152 // a qualified epithet is no part of the anchor
153 ("Salicornia cf. patula", "Salicornia", Rank::Genus, None),
154 (
155 "Salix alba subsp. B",
156 "Salix alba subsp. B",
157 Rank::Subspecies,
158 None,
159 ),
160 ] {
161 match parse(input, None, None, None) {
162 ParseResult::Parsed(pn) => {
163 assert_eq!(pn.type_, NameType::Informal, "{input}");
164 assert_eq!(pn.phrase.as_deref(), phrase, "{input}");
165 let a = pn.anchor().expect("an anchor");
166 assert_eq!(
167 a.canonical_name_without_authorship().as_deref(),
168 Some(anchor),
169 "{input}"
170 );
171 assert_eq!(a.rank, anchor_rank, "{input}");
172 }
173 other => panic!("expected Parsed, got {other:?}"),
174 }
175 }
176 // a plain determined binomial and a bare determined genus
177 assert!(parse("Abies alba", None, None, None).is_parsable());
178 assert!(parse("Rhizobium", None, None, None).is_parsable());
179
180 match parse("", None, None, None) {
181 ParseResult::Unparsable(e) => assert_eq!(e.type_, NameType::Other),
182 other => panic!("expected Unparsable, got {other:?}"),
183 }
184 }
185
186 /// The boundary clamp — a defensive invariant that `Unparsable` may only carry a non-parsable
187 /// type. Since the preflight informal-group rescue landed, NO real input produces an
188 /// error:INFORMAL anymore (anchored groupings are rescued to an INFORMAL name; the rest emit
189 /// OTHER — see `pipeline::preflight`), so this exercises the clamp DIRECTLY on a synthetic
190 /// `ParseError`, then confirms an anchorless clade label is `Unparsable(OTHER)` end to end.
191 #[test]
192 fn clamped_to_unparsable_forces_a_nonparsable_type() {
193 use model::{NomCode, ParseError};
194
195 // a parsable error type is forced to OTHER; code preserved, message rebuilt for the new type
196 let clamped = ParseError::new(NameType::Informal, Some(NomCode::Bacterial), "X group")
197 .clamped_to_unparsable();
198 assert_eq!(clamped.type_, NameType::Other);
199 assert!(!clamped.type_.is_parsable());
200 assert_eq!(clamped.code, Some(NomCode::Bacterial));
201 assert_eq!(clamped.message, "Unparsable OTHER name: X group");
202
203 // a non-parsable error is left untouched
204 let other = ParseError::new(NameType::Other, None, "junk");
205 assert_eq!(other.clone().clamped_to_unparsable(), other);
206
207 // end to end: an anchorless clade label is Unparsable(OTHER)
208 match parse("Amauropeltoid clade", None, None, None) {
209 ParseResult::Unparsable(e) => assert_eq!(e.type_, NameType::Other),
210 other => panic!("expected Unparsable(OTHER), got {other:?}"),
211 }
212 }
213}