nameparser/format.rs
1// SPDX-License-Identifier: Apache-2.0
2
3//! Port of Java `org.gbif.nameparser.util.NameFormatter` — renders a [`ParsedName`] back
4//! into a formatted scientific-name string.
5//!
6//! The Java class exposes a family of convenience methods (`canonical`,
7//! `canonicalWithoutAuthorship`, `canonicalMinimal`, `canonicalComplete`,
8//! `canonicalCompleteHtml`, `authorshipComplete`, `authorString`) that all delegate to one
9//! private `buildName(ParsedName, 16 booleans)`. This port keeps that exact shape: the 16
10//! positional booleans become a named [`Flags`] struct (safer to read than 16 positional
11//! `bool`s while preserving the same semantics), each public method fills the same flag
12//! values Java passes, and [`build_name`] mirrors the Java control flow statement for
13//! statement. The public entry points hang off [`ParsedName`] as methods so bindings can
14//! call e.g. `pn.canonical_name()`.
15//!
16//! Cross-validated byte-for-byte against Java `NameFormatter` over the full corpus by
17//! `tests/format_golden.rs` (the Java oracle emits the same five renderings per name).
18
19use std::sync::LazyLock;
20
21use regex::Regex;
22use unicode_normalization::UnicodeNormalization;
23
24use crate::model::enums::{NamePart, NameType, NomCode, Rank};
25use crate::model::name::{Authorship, CombinedAuthorship, ParsedName};
26use crate::model::Informal;
27use crate::unicode::java_trim;
28
29const HYBRID_MARKER: char = '×';
30const NOTHO_PREFIX: &str = "notho";
31const ET_AL: &str = "et al.";
32const ITALICS_OPEN: &str = "<i>";
33const ITALICS_CLOSE: &str = "</i>";
34
35/// Java `NameFormatter.AL` = `^al\.?$`, tested with `Matcher.find()`. Detects a trailing
36/// "al"/"al." author so `X, al.` renders with " et al." rather than " & al.". The `^…$`
37/// anchors make find() a whole-string test for every real author token; the one Java/Rust
38/// `$` difference (Java `$` also matches just before a trailing `\n`, Rust `$` = `\z` does
39/// not) is unreachable — author tokens never carry a trailing line terminator.
40static AL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^al\.?$").unwrap());
41
42/// Java `NameFormatter.PHRASE_SPECIES_MARKER` = `^(?:species|spec|sp)\b.*`
43/// (CASE_INSENSITIVE, tested with `Matcher.matches()`). Java's `\b` here is ASCII (no
44/// UNICODE_CHARACTER_CLASS flag on this pattern), so it is pinned to `(?-u:\b)`. Detects a
45/// phrase that already spells out the species marker as its leading word ("species 1"), so
46/// the formatter must not also synthesise an "sp." marker. Extended beyond Java with the
47/// underscore-glued designations (`n_sp_NIWA_SO254`, `sp_JAVA`, `n_gen n_sp_…`): `\b` sees no
48/// boundary between `sp` and `_`, which rendered "Aulocalyx sp. n_sp_NIWA_SO254". And with the
49/// open-nomenclature qualifiers that stand for the species marker in a phrase (`cf.`, `aff.`,
50/// `nr.`, `near`: "Formicidae cf.", "Acroceridae aff. Terphis sp. SLW-2002"), which rendered
51/// "Formicidae sp. cf.". And with the generic organism labels that open the phrase of an unnamed
52/// species (`Wolbachia endosymbiont of Leptogenys gracilis`, `Acidimicrobiales bacterium JGI
53/// 01_E13`), which rendered "Wolbachia sp. endosymbiont of …".
54static PHRASE_SPECIES_MARKER: LazyLock<Regex> = LazyLock::new(|| {
55 Regex::new(
56 r"(?i)^(?:(?:species|spec|spp|sp|cf|aff|nr|near|[a-z]*(?:bacteri(?:um|a)|archae(?:on|a|ote)|symbionts?))(?-u:\b)|(?:n_)?sp_|n_gen(?-u:\b)).*$",
57 )
58 .unwrap()
59});
60
61/// Java's inline author-tail pattern `(?U)[\p{Lu}](?:\.[\p{Lu}])*\..+`, tested with
62/// `String.matches()` (full match → anchored `^…$` here). Recognises an author-shaped tail
63/// after a phrase's parenthesised collector reference (e.g. "…(D.Murfet 3190) R.J.Bates"),
64/// which canonical rendering drops. `\p{Lu}` is Unicode by default in the Rust `regex`
65/// crate, matching Java's `(?U)` flag. The `.`/`$` line-terminator set differs subtly from
66/// Java's (Rust `.` excludes only `\n`; Java's also excludes `\r`/U+0085/U+2028/U+2029), but
67/// the tail is `java_trim`'d and realistic author tails contain no embedded line terminators,
68/// so it is not observable. The sibling `PHRASE_SPECIES_MARKER` shares this caveat.
69static PHRASE_AUTHOR_TAIL: LazyLock<Regex> =
70 LazyLock::new(|| Regex::new(r"^[\p{Lu}](?:\.[\p{Lu}])*\..+$").unwrap());
71
72/// The 16 boolean knobs of Java `NameFormatter.buildName`, one named field per positional
73/// argument (declaration order matches Java's parameter order). See the Java Javadoc for
74/// each flag's meaning; the field docs below repeat the load-bearing ones.
75struct Flags {
76 /// include the hybrid marker (×) with the name if existing
77 hybrid_marker: bool,
78 /// include the infraspecific or infrageneric rank marker with the name if existing
79 rank_marker: bool,
80 /// include the name's authorship (author team and year)
81 authorship: bool,
82 /// show the genus for infrageneric names
83 genus_for_infrageneric: bool,
84 /// include the infrageneric name in brackets for species or infraspecies
85 infrageneric: bool,
86 /// decompose unicode ligatures into their ascii ones, e.g. æ becomes ae
87 decomposition: bool,
88 /// transform unicode letters into their ascii ones, e.g. ø becomes o and ü u
89 ascii_only: bool,
90 /// include the epithet qualifiers
91 show_qualifier: bool,
92 /// include the rank marker for incomplete determinations, e.g. Puma spec.
93 show_indet: bool,
94 /// include nomenclatural notes
95 nom_note: bool,
96 /// include the sensu/sec taxonomic note
97 show_sensu: bool,
98 /// include the cultivar epithet
99 show_cultivar: bool,
100 /// include the phrase name
101 show_phrase: bool,
102 /// include the strain (a non-phrase `phrase` value)
103 show_strain: bool,
104 /// render the genus author of an infrageneric name and the species author of a
105 /// below-species name
106 show_extra_authorship: bool,
107 /// add html `<i>` markup around the italicised parts
108 html: bool,
109}
110
111impl Informal {
112 /// The canonical string form of this informal name — e.g. `"Rhizobium sp. RMCC TR1811"`,
113 /// `"Ichneumonidae sp."`, `"Bartonella group"`. Mirrors Java `NameFormatter.canonical(Informal)`:
114 /// it rebuilds the equivalent `INFORMAL` [`ParsedName`] — the [`Informal::taxon`] in the genus
115 /// slot, or the uninomial slot for a non-genus anchor — and renders it through
116 /// [`ParsedName::canonical_name_without_authorship`], so the synthetic `sp.` marker and the
117 /// phrase land exactly where the parser would place them. Never empty: falls back to the bare
118 /// taxon should the rebuilt name render nothing. Named to parallel
119 /// [`ParsedName::canonical_name`] so bindings expose one method across both result variants.
120 pub fn canonical_name(&self) -> String {
121 let pn = ParsedName {
122 type_: NameType::Informal,
123 rank: self.rank,
124 code: self.code,
125 phrase: self.phrase.clone(),
126 candidatus: self.candidatus,
127 genus: (self.taxon_rank == Rank::Genus).then(|| self.taxon.clone()),
128 uninomial: (self.taxon_rank != Rank::Genus).then(|| self.taxon.clone()),
129 ..ParsedName::default()
130 };
131 pn.canonical_name_without_authorship()
132 .unwrap_or_else(|| self.taxon.clone())
133 }
134}
135
136impl ParsedName {
137 /// Java `NameFormatter.canonical(ParsedName)`. A full scientific name with authorship in
138 /// its canonical form. Autonym authorship is placed per the nomenclatural code (after the
139 /// species epithet for botany, at the very end for zoology); subspecies use the `subsp.`
140 /// rank marker unless the name is zoological.
141 pub fn canonical_name(&self) -> Option<String> {
142 build_name(
143 self,
144 &Flags {
145 hybrid_marker: true,
146 rank_marker: true,
147 authorship: true,
148 genus_for_infrageneric: true,
149 infrageneric: false,
150 decomposition: false,
151 ascii_only: false,
152 show_qualifier: true,
153 show_indet: true,
154 nom_note: false,
155 show_sensu: false,
156 show_cultivar: true,
157 show_phrase: true,
158 show_strain: true,
159 show_extra_authorship: false,
160 html: false,
161 },
162 )
163 }
164
165 /// Java `NameFormatter.canonicalWithoutAuthorship(ParsedName)`. As [`Self::canonical_name`]
166 /// but omitting any authorship.
167 pub fn canonical_name_without_authorship(&self) -> Option<String> {
168 build_name(
169 self,
170 &Flags {
171 hybrid_marker: true,
172 rank_marker: true,
173 authorship: false,
174 genus_for_infrageneric: true,
175 infrageneric: false,
176 decomposition: false,
177 ascii_only: false,
178 show_qualifier: true,
179 show_indet: true,
180 nom_note: false,
181 show_sensu: false,
182 show_cultivar: true,
183 show_phrase: true,
184 show_strain: true,
185 show_extra_authorship: false,
186 html: false,
187 },
188 )
189 }
190
191 /// Java `NameFormatter.canonicalMinimal(ParsedName)`. Just the three main name parts
192 /// (genus, species, infraspecific) — no rank or hybrid markers, no authorship, cultivar
193 /// or strain. Infrageneric names are shown without a leading genus. Unicode characters
194 /// are folded to their ascii equivalents.
195 pub fn canonical_name_minimal(&self) -> Option<String> {
196 build_name(
197 self,
198 &Flags {
199 hybrid_marker: false,
200 rank_marker: false,
201 authorship: false,
202 genus_for_infrageneric: false,
203 infrageneric: false,
204 decomposition: true,
205 ascii_only: true,
206 show_qualifier: false,
207 show_indet: false,
208 nom_note: false,
209 show_sensu: false,
210 show_cultivar: false,
211 show_phrase: false,
212 show_strain: false,
213 show_extra_authorship: false,
214 html: false,
215 },
216 )
217 }
218
219 /// Java `NameFormatter.canonicalComplete(ParsedName)`. A full name with all details,
220 /// including non-code-compliant informal remarks (subgenus in brackets, strain, sensu,
221 /// nom. note, extra authorship). Unicode ligatures are decomposed.
222 pub fn canonical_name_complete(&self) -> Option<String> {
223 build_name(self, &complete_flags(false))
224 }
225
226 /// Java `NameFormatter.canonicalCompleteHtml(ParsedName)`. As
227 /// [`Self::canonical_name_complete`] but with `<i>…</i>` markup around the italicised
228 /// name parts.
229 pub fn canonical_name_complete_html(&self) -> Option<String> {
230 build_name(self, &complete_flags(true))
231 }
232
233 /// Java `NameFormatter.authorshipComplete(ParsedName)`. The full concatenated authorship
234 /// (basionym in brackets, combination, sanctioning author, years) using the name's own
235 /// nomenclatural code, or `None` when the name carries no authorship.
236 pub fn authorship_complete(&self) -> Option<String> {
237 let mut sb = String::new();
238 append_authorship_parts(
239 &mut sb,
240 &self.basionym_authorship,
241 &self.combination_authorship,
242 true,
243 self.code,
244 );
245 if sb.is_empty() {
246 None
247 } else {
248 Some(sb)
249 }
250 }
251
252 // ---- ParsedName predicates the formatter relies on (Java `ParsedName` API) ----
253
254 /// Java `ParsedName.hasGenericAuthorship()`: the infrageneric genus author slot carries
255 /// an actual authorship.
256 pub fn has_generic_authorship(&self) -> bool {
257 self.generic_authorship
258 .as_ref()
259 .is_some_and(CombinedAuthorship::has_authorship)
260 }
261
262 /// Java `ParsedName.hasSpecificAuthorship()`: the below-species species-author slot
263 /// carries an actual authorship.
264 pub fn has_specific_authorship(&self) -> bool {
265 self.specific_authorship
266 .as_ref()
267 .is_some_and(CombinedAuthorship::has_authorship)
268 }
269
270 /// Java `ParsedName.hasEpithetQualifier(NamePart)`: a qualifier (cf./aff./…) is recorded
271 /// for the given name part.
272 pub fn has_epithet_qualifier(&self, part: NamePart) -> bool {
273 self.epithet_qualifier
274 .as_ref()
275 .is_some_and(|m| m.contains_key(&part))
276 }
277
278 /// Java `ParsedName.isHybridName()`: at least one part is marked notho- (a named hybrid).
279 pub fn is_hybrid_name(&self) -> bool {
280 self.notho.as_ref().is_some_and(|s| !s.is_empty())
281 }
282
283 /// Java `ParsedName.isPhraseName()`: the `phrase` field is set and non-empty.
284 pub fn is_phrase_name(&self) -> bool {
285 self.phrase.as_ref().is_some_and(|p| !p.is_empty())
286 }
287}
288
289/// Shared flag set for `canonicalComplete` / `canonicalCompleteHtml` — identical except for
290/// the trailing `html` knob.
291fn complete_flags(html: bool) -> Flags {
292 Flags {
293 hybrid_marker: true,
294 rank_marker: true,
295 authorship: true,
296 genus_for_infrageneric: true,
297 infrageneric: true,
298 decomposition: true,
299 ascii_only: false,
300 show_qualifier: true,
301 show_indet: true,
302 nom_note: true,
303 show_sensu: true,
304 show_cultivar: true,
305 show_phrase: true,
306 show_strain: true,
307 show_extra_authorship: true,
308 html,
309 }
310}
311
312/// Java `NameFormatter.hasNotho(ParsedName, NamePart)`.
313fn has_notho(n: &ParsedName, part: NamePart) -> bool {
314 n.notho.as_ref().is_some_and(|s| s.contains(&part))
315}
316
317/// Java `NameFormatter.isUnknown(Rank)` — `r == null || r.otherOrUnranked()`. Rank is never
318/// null in this port (defaults to `Unranked`), so it reduces to `other_or_unranked()`.
319fn is_unknown(r: Rank) -> bool {
320 r.other_or_unranked()
321}
322
323/// Java `NameFormatter.isInfraspecificMarker(Rank)`.
324fn is_infraspecific_marker(r: Rank) -> bool {
325 r.is_infraspecific() && !r.is_uncomparable()
326}
327
328fn append_in_italics(sb: &mut String, x: &str, html: bool) {
329 if html {
330 sb.push_str(ITALICS_OPEN);
331 sb.push_str(x);
332 sb.push_str(ITALICS_CLOSE);
333 } else {
334 sb.push_str(x);
335 }
336}
337
338/// Java `NameFormatter.appendIfNotEmpty(StringBuilder, String)` — append only when `sb` is
339/// already non-empty.
340fn append_if_not_empty(sb: &mut String, to_append: &str) {
341 if !sb.is_empty() {
342 sb.push_str(to_append);
343 }
344}
345
346/// Java `NameFormatter.phraseLeadsWithSpeciesMarker(ParsedName)`.
347fn phrase_leads_with_species_marker(n: &ParsedName) -> bool {
348 n.is_phrase_name()
349 && PHRASE_SPECIES_MARKER.is_match(java_trim(n.phrase.as_deref().unwrap_or("")))
350}
351
352/// gbif/name-parser-rust#16: true when an informal phrase already OPENS with this name's own
353/// rank marker, spelled out verbatim — "sect. 1" on a `SECTION_BOTANY`, "strain T101" on a
354/// `STRAIN`, "var 3" on a `VARIETY`. `StripAndStash::stash_trailing_rank_marker_code` keeps the
355/// source spelling of an indeterminate `Genus <marker> <code>` in the phrase, so synthesising the
356/// marker from the rank as well would double it ("Trachelomonas strain strain T101"). Compared
357/// dot-insensitively, since the marker is stored with its dot ("var.") and the source may write
358/// it without one.
359///
360/// The sibling [`phrase_leads_with_species_marker`] stays separate rather than folding into this:
361/// it matches the SPELLED-OUT species markers ("species 1", "spec 3"), none of which equal
362/// `Rank::Species`'s own marker "sp.", and it is a faithful port of a Java pattern.
363fn phrase_leads_with_rank_marker(n: &ParsedName) -> bool {
364 let Some(marker) = n.rank.marker() else {
365 return false;
366 };
367 let phrase = java_trim(n.phrase.as_deref().unwrap_or(""));
368 let Some(lead) = phrase.split_whitespace().next() else {
369 return false;
370 };
371 lead.trim_end_matches('.')
372 .eq_ignore_ascii_case(marker.trim_end_matches('.'))
373}
374
375/// Java `NameFormatter.appendRankMarker(sb, rank, ifRank, nothoPrefix)` (both the 3- and
376/// 4-arg overloads; the 3-arg one passes `if_rank = None`). Returns true if a marker was
377/// appended.
378fn append_rank_marker(
379 sb: &mut String,
380 rank: Rank,
381 if_rank: Option<fn(Rank) -> bool>,
382 notho_prefix: bool,
383) -> bool {
384 if let Some(marker) = rank.marker() {
385 if if_rank.is_none_or(|f| f(rank)) {
386 if notho_prefix {
387 sb.push_str(NOTHO_PREFIX);
388 }
389 sb.push_str(marker);
390 return true;
391 }
392 }
393 false
394}
395
396/// Java `NameFormatter.appendGenus(sb, n, hybridMarker, showQualifier, html)`.
397fn append_genus(
398 sb: &mut String,
399 n: &ParsedName,
400 hybrid_marker: bool,
401 show_qualifier: bool,
402 html: bool,
403) {
404 if show_qualifier && n.has_epithet_qualifier(NamePart::Generic) {
405 sb.push_str(qualifier(n, NamePart::Generic));
406 sb.push(' ');
407 }
408 if hybrid_marker && has_notho(n, NamePart::Generic) {
409 sb.push(HYBRID_MARKER);
410 sb.push(' ');
411 }
412 // In every call site the genus is Some (guarded by the caller), matching Java's
413 // unconditional n.getGenus() dereference here.
414 append_in_italics(sb, n.genus.as_deref().unwrap_or(""), html);
415}
416
417/// Java `NameFormatter.appendInfraspecific(...)`.
418fn append_infraspecific(
419 sb: &mut String,
420 n: &ParsedName,
421 hybrid_marker: bool,
422 show_qualifier: bool,
423 rank_marker: bool,
424 force_rank_marker: bool,
425 html: bool,
426) {
427 sb.push(' ');
428 if show_qualifier && n.has_epithet_qualifier(NamePart::Infraspecific) {
429 sb.push_str(qualifier(n, NamePart::Infraspecific));
430 sb.push(' ');
431 }
432 if hybrid_marker && has_notho(n, NamePart::Infraspecific) {
433 if rank_marker && is_infraspecific_marker(n.rank) {
434 sb.push_str("notho");
435 } else {
436 sb.push(HYBRID_MARKER);
437 sb.push(' ');
438 }
439 }
440 // Render the infraspecific rank marker. Other ranks always show it; the subspecies
441 // marker is hidden only for zoological names (ICZN trinomials carry no marker).
442 // Kept as Java's two nested `if`s (not collapsed) because the inner condition's
443 // `append_rank_marker` has a side effect (it appends the marker) — folding it into the
444 // outer guard would bury that write inside a compound boolean.
445 #[allow(clippy::collapsible_if)]
446 if force_rank_marker
447 || (rank_marker
448 && (n.code != Some(NomCode::Zoological)
449 || n.rank != Rank::Subspecies
450 || n.is_hybrid_name()))
451 {
452 if append_rank_marker(sb, n.rank, Some(is_infraspecific_marker), false)
453 && n.infraspecific_epithet.is_some()
454 {
455 sb.push(' ');
456 }
457 }
458 if let Some(ie) = &n.infraspecific_epithet {
459 append_in_italics(sb, ie, html);
460 }
461}
462
463/// Fetch an epithet qualifier known to exist (caller guards with `has_epithet_qualifier`).
464fn qualifier(n: &ParsedName, part: NamePart) -> &str {
465 n.epithet_qualifier
466 .as_ref()
467 .and_then(|m| m.get(&part))
468 .map(String::as_str)
469 .unwrap_or("")
470}
471
472/// Java `NameFormatter.joinAuthors(List<String>, Integer maxAuthors)`.
473fn join_authors(authors: &[String], max_authors: Option<usize>) -> String {
474 if let Some(max) = max_authors {
475 if authors.len() > max {
476 return format!("{} {}", authors[0], ET_AL);
477 }
478 }
479 if authors.len() > 1 {
480 let last = &authors[authors.len() - 1];
481 let end = if AL.is_match(last) {
482 format!(" {ET_AL}")
483 } else {
484 format!(" & {last}")
485 };
486 return format!("{}{}", authors[..authors.len() - 1].join(", "), end);
487 }
488 authors.join(", ")
489}
490
491/// Java `NameFormatter.appendAuthorship(StringBuilder, Authorship, boolean, NomCode)`.
492/// Java `NameFormatter.anonymousAuthor(NomCode)`: the author citation of an anonymous work
493/// without attributed authors — "anon." in the botanical codes, "Anon." (ICZN Recommendation 51D)
494/// in all others and when the code is unknown.
495pub fn anonymous_author(code: Option<NomCode>) -> &'static str {
496 match code {
497 Some(NomCode::Botanical | NomCode::Cultivars | NomCode::Phyto) => "anon.",
498 _ => "Anon.",
499 }
500}
501
502fn append_authorship(
503 sb: &mut String,
504 auth: &Authorship,
505 include_year: bool,
506 code: Option<NomCode>,
507) {
508 if !auth.exists() {
509 return;
510 }
511 let mut authors_appended = false;
512 let max = if code == Some(NomCode::Bacterial) {
513 Some(2)
514 } else {
515 None
516 };
517 if !auth.ex_authors.is_empty() {
518 sb.push_str(&join_authors(&auth.ex_authors, max));
519 sb.push_str(" ex ");
520 authors_appended = true;
521 }
522 if auth.anonymous {
523 // attributed authors of an anonymous work go in square brackets (ICZN Recommendation 51D)
524 if auth.authors.is_empty() {
525 sb.push_str(anonymous_author(code));
526 } else {
527 sb.push('[');
528 sb.push_str(&join_authors(&auth.authors, max));
529 sb.push(']');
530 }
531 authors_appended = true;
532 } else if !auth.authors.is_empty() {
533 sb.push_str(&join_authors(&auth.authors, max));
534 authors_appended = true;
535 }
536 if include_year {
537 if let Some(year) = &auth.year {
538 if authors_appended {
539 if code != Some(NomCode::Bacterial) {
540 sb.push(',');
541 }
542 sb.push(' ');
543 }
544 // a year established from external evidence is cited in square brackets (ICZN
545 // Rec. 22A.2.3)
546 if auth.bracketed_year {
547 sb.push('[');
548 sb.push_str(year);
549 sb.push(']');
550 } else {
551 sb.push_str(year);
552 }
553 }
554 if let Some(iy) = &auth.imprint_year {
555 sb.push_str(" [");
556 sb.push_str(iy);
557 sb.push(']');
558 }
559 }
560 // the sanctioning author via colon, inside the brackets of a basionym (ICN Rec. 50E)
561 if let Some(sanct) = &auth.sanctioning_author {
562 sb.push_str(" : ");
563 sb.push_str(sanct);
564 }
565}
566
567/// Java `NameFormatter.appendAuthorship(StringBuilder, CombinedAuthorshipIF, boolean,
568/// NomCode)` — used both for a name's own authorship (its flattened
569/// combination/basionym fields) and for the nested
570/// generic/specific `CombinedAuthorship` slots.
571fn append_authorship_parts(
572 sb: &mut String,
573 basionym: &Authorship,
574 combination: &Authorship,
575 include_year: bool,
576 code: Option<NomCode>,
577) {
578 let orig_len = sb.len();
579 if basionym.exists() {
580 sb.push('(');
581 append_authorship(sb, basionym, include_year, code);
582 sb.push(')');
583 }
584 if combination.exists() {
585 if orig_len < sb.len() {
586 sb.push(' ');
587 }
588 append_authorship(sb, combination, include_year, code);
589 }
590}
591
592/// Append the name's OWN authorship — Java `appendAuthorship(sb, n, includeYear, code)`
593/// where `n` (a `ParsedName`) is the `CombinedAuthorshipIF`.
594fn append_name_authorship(sb: &mut String, n: &ParsedName, include_year: bool) {
595 append_authorship_parts(
596 sb,
597 &n.basionym_authorship,
598 &n.combination_authorship,
599 include_year,
600 n.code,
601 );
602}
603
604/// Append a nested `CombinedAuthorship` slot (generic or specific authorship).
605fn append_combined_authorship(
606 sb: &mut String,
607 c: &CombinedAuthorship,
608 include_year: bool,
609 code: Option<NomCode>,
610) {
611 append_authorship_parts(
612 sb,
613 &c.basionym_authorship,
614 &c.combination_authorship,
615 include_year,
616 code,
617 );
618}
619
620/// Java `UnicodeUtils.decompose(String)` — expands the fixed set of two-letter ligatures.
621/// Every search key is a single unicode scalar and no replacement contains a search key, so
622/// a single char-by-char pass reproduces `StringUtils.replaceEach` exactly.
623fn decompose(x: &str) -> String {
624 let mut out = String::with_capacity(x.len());
625 for c in x.chars() {
626 match c {
627 'æ' => out.push_str("ae"),
628 'Æ' => out.push_str("Ae"),
629 'œ' => out.push_str("oe"),
630 'Œ' => out.push_str("Oe"),
631 'IJ' => out.push_str("Ij"),
632 'ij' => out.push_str("ij"),
633 'Lj' => out.push_str("Lj"),
634 'lj' => out.push_str("lj"),
635 'ȸ' => out.push_str("db"),
636 'ȹ' => out.push_str("qp"),
637 'ß' => out.push_str("ss"),
638 'st' => out.push_str("st"),
639 'ſt' => out.push_str("ft"),
640 'ff' => out.push_str("ff"),
641 'fi' => out.push_str("fi"),
642 'fl' => out.push_str("fl"),
643 'ffi' => out.push_str("ffi"),
644 'ffl' => out.push_str("ffl"),
645 other => out.push(other),
646 }
647 }
648 out
649}
650
651/// Java `UnicodeUtils.replaceSpecialCases(String)` — cases the java Normalizer misses.
652fn replace_special_cases(x: &str) -> String {
653 let mut out = String::with_capacity(x.len());
654 for c in x.chars() {
655 match c {
656 'ß' => out.push_str("ss"),
657 'ſ' => out.push('s'),
658 'Æ' => out.push_str("AE"),
659 'æ' => out.push_str("ae"),
660 'Ð' => out.push('D'),
661 'đ' => out.push('d'),
662 'ð' => out.push('d'),
663 'Ø' => out.push('O'),
664 'ø' => out.push('o'),
665 'Œ' => out.push_str("OE"),
666 'œ' => out.push_str("oe"),
667 'Ŧ' => out.push('T'),
668 'ŧ' => out.push('t'),
669 'Ł' => out.push('L'),
670 'ł' => out.push('l'),
671 other => out.push(other),
672 }
673 }
674 out
675}
676
677/// Java `UnicodeUtils.MARKER` = `Pattern.compile("\\p{M}")` — the Unicode general category
678/// Mark (Mn/Mc/Me). The `regex` crate's `\p{M}` is the same category, so this reproduces
679/// Java's `MARKER.matcher(x).replaceAll("")` byte-for-byte (no hand-rolled range set).
680static MARK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\p{M}").unwrap());
681
682/// Java `UnicodeUtils.foldToAscii(String)` — `replaceSpecialCases`, then Unicode NFD (which
683/// splits accented letters into base + combining mark), then drop all `\p{M}` marks, leaving
684/// the ascii base letters.
685pub(crate) fn fold_to_ascii(x: &str) -> String {
686 let x = replace_special_cases(x);
687 let nfd: String = x.nfd().collect();
688 MARK.replace_all(&nfd, "").into_owned()
689}
690
691/// Java `NameFormatter.buildName(ParsedName, 16 booleans)` — the core renderer every public
692/// method delegates to. Ported statement-for-statement; see the field docs on [`Flags`] for
693/// each knob.
694fn build_name(n: &ParsedName, f: &Flags) -> Option<String> {
695 let mut sb = String::new();
696
697 // `html`/`authorship` are reassigned below (Candidatus turns html off; several indet
698 // branches turn authorship off), so shadow them as locals like Java's mutable params.
699 let mut html = f.html;
700 let mut authorship = f.authorship;
701
702 let mut candidate_italics = false;
703 if n.candidatus {
704 sb.push('"');
705 if html {
706 sb.push_str(ITALICS_OPEN);
707 candidate_italics = true;
708 // the entire name goes in italics, so turn off per-part html
709 html = false;
710 }
711 sb.push_str("Candidatus ");
712 }
713
714 if let Some(uninomial) = &n.uninomial {
715 // higher rank names being just a uninomial!
716 if f.hybrid_marker && has_notho(n, NamePart::Generic) {
717 sb.push(HYBRID_MARKER);
718 sb.push(' ');
719 }
720 append_in_italics(&mut sb, uninomial, html);
721 } else {
722 // bi- or trinomials or infrageneric names
723 if let Some(infrageneric_epithet) = &n.infrageneric_epithet {
724 if (is_unknown(n.rank) && n.specific_epithet.is_none())
725 || n.rank.is_infrageneric_strictly()
726 {
727 let mut show_infra_gen = true;
728 // the infrageneric is the terminal rank. Always show it and wrap it with its
729 // genus if requested
730 if n.genus.is_some() && f.genus_for_infrageneric {
731 append_genus(&mut sb, n, f.hybrid_marker, f.show_qualifier, html);
732 // The genus author of an infrageneric name sits between the genus and the
733 // rank marker ("Cordia (Adans.) Kuntze sect. Salimori").
734 if f.show_extra_authorship && n.has_generic_authorship() {
735 sb.push(' ');
736 append_combined_authorship(
737 &mut sb,
738 n.generic_authorship.as_ref().unwrap(),
739 true,
740 n.code,
741 );
742 }
743 sb.push(' ');
744 // we show zoological infragenerics in brackets, but use rank markers for
745 // botanical names (unless its no defined rank)
746 if n.code == Some(NomCode::Zoological) {
747 sb.push('(');
748 if f.hybrid_marker && has_notho(n, NamePart::Infrageneric) {
749 sb.push(HYBRID_MARKER);
750 sb.push(' ');
751 }
752 append_in_italics(&mut sb, infrageneric_epithet, html);
753 sb.push(')');
754 show_infra_gen = false;
755 }
756 }
757 if show_infra_gen {
758 if f.rank_marker {
759 // If we know the rank we use explicit rank markers — this is how
760 // botanical infrageneric names are formed, see
761 // http://www.iapt-taxon.org/nomen/main.php?page=art21
762 if append_rank_marker(
763 &mut sb,
764 n.rank,
765 None,
766 f.hybrid_marker && has_notho(n, NamePart::Infrageneric),
767 ) {
768 sb.push(' ');
769 }
770 }
771 append_in_italics(&mut sb, infrageneric_epithet, html);
772 }
773 } else {
774 if n.genus.is_some() {
775 append_genus(&mut sb, n, f.hybrid_marker, f.show_qualifier, html);
776 }
777 if f.infrageneric {
778 // additional subgenus shown for binomial. Always shown in brackets
779 sb.push_str(" (");
780 append_in_italics(&mut sb, infrageneric_epithet, html);
781 sb.push(')');
782 }
783 }
784 } else if n.genus.is_some() {
785 append_genus(&mut sb, n, f.hybrid_marker, f.show_qualifier, html);
786 }
787
788 if n.specific_epithet.is_none() {
789 if (f.show_indet && n.genus.is_some() && n.cultivar_epithet.is_none())
790 || (f.show_phrase && n.is_phrase_name())
791 {
792 if n.rank.is_species_or_below() {
793 // no species epithet given, indetermined!
794 if n.rank.is_infraspecific() {
795 // maybe we have an infraspecific epithet? force to show the rank marker —
796 // unless the phrase already spells that marker out ("strain T101"), in
797 // which case synthesising it would double it.
798 if !phrase_leads_with_rank_marker(n) {
799 append_infraspecific(
800 &mut sb,
801 n,
802 f.hybrid_marker,
803 f.show_qualifier,
804 f.rank_marker,
805 true,
806 html,
807 );
808 }
809 } else if !phrase_leads_with_species_marker(n) {
810 // Skip the synthetic "sp." when an informal phrase already spells out
811 // the species marker verbatim ("Allium species 1") — the phrase
812 // carries it.
813 sb.push(' ');
814 // Java `sb.append(n.getRank().getMarker())`. Here the rank is
815 // species-or-below-but-not-infraspecific (SPECIES / SPECIES_AGGREGATE),
816 // both of which always have a marker, so the default is never taken; unlike
817 // line 757 there is no null-marker rank to mirror Java's "null" for.
818 sb.push_str(n.rank.marker().unwrap_or(""));
819 }
820 // An infraspecific epithet under a bare genus ("Navicula var. fasciata
821 // Grunow") is no indetermined name: its author stays.
822 if n.infraspecific_epithet.is_none() {
823 authorship = false;
824 }
825 }
826 } else if n.infraspecific_epithet.is_some() {
827 append_infraspecific(
828 &mut sb,
829 n,
830 f.hybrid_marker,
831 f.show_qualifier,
832 f.rank_marker,
833 false,
834 html,
835 );
836 }
837 } else {
838 // species part
839 sb.push(' ');
840 if f.show_qualifier && n.has_epithet_qualifier(NamePart::Specific) {
841 sb.push_str(qualifier(n, NamePart::Specific));
842 sb.push(' ');
843 }
844 if f.hybrid_marker && has_notho(n, NamePart::Specific) {
845 sb.push(HYBRID_MARKER);
846 sb.push(' ');
847 }
848 append_in_italics(&mut sb, n.specific_epithet.as_deref().unwrap_or(""), html);
849 // The species author of a below-species name (cultivar / trinomial) sits right
850 // after the species epithet ("Acer campestre L. 'Elsrijk' Broerse").
851 if f.show_extra_authorship && n.has_specific_authorship() {
852 sb.push(' ');
853 append_combined_authorship(
854 &mut sb,
855 n.specific_authorship.as_ref().unwrap(),
856 true,
857 n.code,
858 );
859 }
860
861 if n.infraspecific_epithet.is_none() {
862 // Indetermined infraspecies? Only show indet cultivar marker if no cultivar
863 // epithet exists
864 if f.show_indet
865 && n.rank.is_infraspecific()
866 && (n.rank.is_restricted_to_code() != Some(NomCode::Cultivars)
867 || n.cultivar_epithet.is_none())
868 {
869 // no infraspecific epitheton given, but rank below species. Indetermined!
870 // use ssp. for subspecies in case of indetermined names
871 if n.rank == Rank::Subspecies {
872 sb.push_str(" ssp.");
873 } else {
874 sb.push(' ');
875 // Faithful to Java `sb.append(n.getRank().getMarker())`: when the marker
876 // is null Java's `StringBuilder.append((String) null)` appends the literal
877 // "null". The only infraspecific rank with a null marker is CULTIVAR_GROUP
878 // (which reaches here only for a specific-but-no-infraspecific, no-cultivar
879 // name — not producible by `parse()`, but the formatter is public API over
880 // any hand-built ParsedName), so mirror the "null" rather than dropping it.
881 sb.push_str(n.rank.marker().unwrap_or("null"));
882 }
883 authorship = false;
884 }
885 } else {
886 // Autonym authorship placement follows the codes. The autonym's final epithet
887 // never carries an author of its own; the author shown is the species author.
888 // ICN Art. 22.1/26.1 (botany): cite it right after the species epithet.
889 // ICZN (zoology): cite it at the very end of the trinomen.
890 // Only an explicit botanical code triggers the after-species placement;
891 // zoological and unknown-code autonyms keep the author in its default end
892 // position below.
893 if n.is_autonym() && n.code == Some(NomCode::Botanical) {
894 if authorship && n.has_authorship() {
895 sb.push(' ');
896 append_name_authorship(&mut sb, n, true);
897 }
898 authorship = false;
899 }
900 // infraspecific part
901 append_infraspecific(
902 &mut sb,
903 n,
904 f.hybrid_marker,
905 f.show_qualifier,
906 f.rank_marker,
907 false,
908 html,
909 );
910 }
911 }
912 }
913
914 // closing quotes for Candidatus names
915 if n.candidatus {
916 if candidate_italics {
917 sb.push_str(ITALICS_CLOSE);
918 }
919 sb.push('"');
920 }
921
922 // uninomial, genus, infragen, species or infraspecies authorship. For a cultivar the
923 // name's authorship IS the cultivar author, rendered AFTER the cultivar epithet below,
924 // so it is suppressed here.
925 let cultivar_shown = f.show_cultivar && n.cultivar_epithet.is_some();
926 if authorship && n.has_authorship() && !cultivar_shown {
927 sb.push(' ');
928 append_name_authorship(&mut sb, n, true);
929 }
930
931 // add strain name (phrase names get special treatment)
932 if f.show_strain && n.phrase.is_some() && !n.is_phrase_name() {
933 sb.push(' ');
934 sb.push_str(n.phrase.as_deref().unwrap_or(""));
935 }
936
937 // add cultivar name
938 if f.show_cultivar {
939 if let Some(cultivar) = &n.cultivar_epithet {
940 if n.rank == Rank::CultivarGroup {
941 sb.push(' ');
942 sb.push_str(cultivar);
943 sb.push_str(" Group");
944 } else if n.rank == Rank::Grex {
945 sb.push(' ');
946 sb.push_str(cultivar);
947 sb.push_str(" gx");
948 } else {
949 sb.push_str(" '");
950 sb.push_str(cultivar);
951 sb.push('\'');
952 }
953 // The cultivar author follows the cultivar epithet ("Acer campestre 'Elsrijk'
954 // Broerse").
955 if authorship && n.has_authorship() {
956 sb.push(' ');
957 append_name_authorship(&mut sb, n, true);
958 }
959 }
960 }
961
962 // Add phrase name. Phrase values may include a trailing author span after the collector
963 // parenthesised reference ("Sandheath (D.Murfet 3190) R.J.Bates"); for canonical
964 // rendering we drop that author-shaped tail so the output stays clean while the stored
965 // phrase keeps the full annotation. A non-author suffix (e.g. "NT Herbarium") is kept.
966 if f.show_phrase && n.is_phrase_name() {
967 let phrase_full = n.phrase.as_deref().unwrap_or("");
968 let mut phrase = phrase_full;
969 if let Some(last_close) = phrase_full.rfind(')') {
970 // ')' is ASCII (1 byte), so the byte comparison matches Java's char check for
971 // "is there content after the last ')'".
972 if last_close < phrase_full.len() - 1 {
973 let tail = java_trim(&phrase_full[last_close + 1..]);
974 // Author-shaped tail: initials with dots (e.g. "R.J.Bates").
975 if PHRASE_AUTHOR_TAIL.is_match(tail) {
976 phrase = &phrase_full[..last_close + 1];
977 }
978 }
979 }
980 append_if_not_empty(&mut sb, " ");
981 sb.push_str(phrase);
982 }
983
984 // add sensu/sec reference
985 if f.show_sensu {
986 if let Some(tn) = &n.taxonomic_note {
987 append_if_not_empty(&mut sb, " ");
988 sb.push_str(tn);
989 }
990 }
991
992 // add nom status
993 if f.nom_note {
994 if let Some(nn) = &n.nomenclatural_note {
995 append_if_not_empty(&mut sb, ", ");
996 sb.push_str(nn);
997 }
998 }
999
1000 // final char transformations
1001 let mut name = java_trim(&sb).to_string();
1002 if f.decomposition {
1003 name = decompose(&name);
1004 }
1005 if f.ascii_only {
1006 name = fold_to_ascii(&name);
1007 }
1008 // Java StringUtils.trimToNull: trim again, null if empty.
1009 let name = java_trim(&name);
1010 if name.is_empty() {
1011 None
1012 } else {
1013 Some(name.to_string())
1014 }
1015}
1016
1017#[cfg(test)]
1018mod tests {
1019 //! Always-on formatter regression guards. Every `expect_*` value here is
1020 //! **Java-authoritative** — produced by running the input through the real Java
1021 //! `NameFormatter` (via the `FormatOracle`, same tool `tests/format_golden.rs` uses), not
1022 //! hand-derived — so these pin the exact Java behaviour for the structural rendering
1023 //! paths (autonym placement, infrageneric markers, notho/hybrid spacing, Candidatus
1024 //! quoting, sanctioning author, cultivar, ascii folding, html) without needing the oracle
1025 //! present at test time.
1026
1027 use crate::parse_name as parse;
1028
1029 /// Parse with the default (no hints) entry point; panics if the name is unparsable — every
1030 /// input below is a parseable name chosen precisely to exercise a formatter path.
1031 fn p(input: &str) -> crate::model::ParsedName {
1032 parse(input, None, None, None).unwrap_or_else(|_| panic!("should parse: {input:?}"))
1033 }
1034
1035 #[test]
1036 fn informal_canonical_rebuilds_the_parser_rendering() {
1037 use crate::model::enums::Rank;
1038 use crate::model::Informal;
1039 let inf = |taxon: &str, taxon_rank, rank, phrase: Option<&str>| Informal {
1040 taxon: taxon.into(),
1041 taxon_rank,
1042 rank,
1043 phrase: phrase.map(str::to_string),
1044 code: None,
1045 candidatus: false,
1046 };
1047 // genus-anchored provisional species with a captured phrase tag
1048 assert_eq!(
1049 inf(
1050 "Rhizobium",
1051 Rank::Genus,
1052 Rank::Species,
1053 Some("sp. RMCC TR1811")
1054 )
1055 .canonical_name(),
1056 "Rhizobium sp. RMCC TR1811"
1057 );
1058 // numbered placeholder
1059 assert_eq!(
1060 inf("Allium", Rank::Genus, Rank::Species, Some("1")).canonical_name(),
1061 "Allium sp. 1"
1062 );
1063 // bare "Genus sp." — no phrase (a higher-taxon anchor still sits in the genus slot)
1064 assert_eq!(
1065 inf("Ichneumonidae", Rank::Genus, Rank::Species, None).canonical_name(),
1066 "Ichneumonidae sp."
1067 );
1068 // informal group — UNRANKED, the phrase carries the designation (no synthetic sp.)
1069 assert_eq!(
1070 inf("Bartonella", Rank::Genus, Rank::Unranked, Some("group")).canonical_name(),
1071 "Bartonella group"
1072 );
1073 // Candidatus status, quoted around the name as on a parsed name (#76)
1074 let candidatus = Informal {
1075 candidatus: true,
1076 ..inf(
1077 "Pelagibacter",
1078 Rank::Genus,
1079 Rank::Species,
1080 Some("sp. HTCC7211"),
1081 )
1082 };
1083 assert_eq!(
1084 candidatus.canonical_name(),
1085 "\"Candidatus Pelagibacter\" sp. HTCC7211"
1086 );
1087 }
1088
1089 #[test]
1090 fn basic_binomial_with_author() {
1091 let n = p("Abies alba Mill.");
1092 assert_eq!(n.canonical_name().as_deref(), Some("Abies alba Mill."));
1093 assert_eq!(
1094 n.canonical_name_without_authorship().as_deref(),
1095 Some("Abies alba")
1096 );
1097 assert_eq!(n.canonical_name_minimal().as_deref(), Some("Abies alba"));
1098 assert_eq!(
1099 n.canonical_name_complete().as_deref(),
1100 Some("Abies alba Mill.")
1101 );
1102 assert_eq!(n.authorship_complete().as_deref(), Some("Mill."));
1103 }
1104
1105 #[test]
1106 fn authorless_name_has_no_authorship_string() {
1107 let n = p("Abies alba");
1108 assert_eq!(n.canonical_name().as_deref(), Some("Abies alba"));
1109 assert_eq!(n.authorship_complete(), None);
1110 }
1111
1112 #[test]
1113 fn zoological_subspecies_shows_no_rank_marker() {
1114 // ICZN trinomials carry no infraspecific marker.
1115 let n = p("Vulpes vulpes silaceus Miller, 1907");
1116 assert_eq!(
1117 n.canonical_name().as_deref(),
1118 Some("Vulpes vulpes silaceus Miller, 1907")
1119 );
1120 assert_eq!(
1121 n.canonical_name_without_authorship().as_deref(),
1122 Some("Vulpes vulpes silaceus")
1123 );
1124 assert_eq!(n.authorship_complete().as_deref(), Some("Miller, 1907"));
1125 }
1126
1127 #[test]
1128 fn botanical_autonym_keeps_marker_but_minimal_drops_it() {
1129 let n = p("Acer rubrum var. rubrum");
1130 assert_eq!(
1131 n.canonical_name().as_deref(),
1132 Some("Acer rubrum var. rubrum")
1133 );
1134 // canonicalMinimal drops the rank marker: three bare epithets.
1135 assert_eq!(
1136 n.canonical_name_minimal().as_deref(),
1137 Some("Acer rubrum rubrum")
1138 );
1139 }
1140
1141 #[test]
1142 fn botanical_autonym_places_author_after_species_epithet() {
1143 // ICN Art. 22.1/26.1: the species author sits before the (repeated) rank marker. Parsed,
1144 // it is the specific authorship, the autonym having none of its own (#86).
1145 let n = p("Trimezia spathata (Klatt) Baker subsp. spathata");
1146 assert_eq!(
1147 n.canonical_name_complete().as_deref(),
1148 Some("Trimezia spathata (Klatt) Baker subsp. spathata")
1149 );
1150 assert_eq!(
1151 n.canonical_name().as_deref(),
1152 Some("Trimezia spathata subsp. spathata")
1153 );
1154 assert_eq!(n.authorship_complete(), None);
1155 // one given as the autonym's goes to the same place
1156 let mut n = p("Trimezia spathata subsp. spathata (Klatt) Baker");
1157 n.code = Some(crate::model::NomCode::Botanical);
1158 assert_eq!(
1159 n.canonical_name().as_deref(),
1160 Some("Trimezia spathata (Klatt) Baker subsp. spathata")
1161 );
1162 }
1163
1164 #[test]
1165 fn infrageneric_botanical_uses_rank_marker_and_minimal_drops_genus() {
1166 // "subg." normalises to the "subgen." marker; minimal shows only the terminal epithet.
1167 let n = p("Astragalus subg. Cercidothrix");
1168 assert_eq!(
1169 n.canonical_name().as_deref(),
1170 Some("Astragalus subgen. Cercidothrix")
1171 );
1172 assert_eq!(n.canonical_name_minimal().as_deref(), Some("Cercidothrix"));
1173 }
1174
1175 #[test]
1176 fn basionym_and_combination_authorship() {
1177 let n = p("Baeomyces rufus (Huds.) Rebent.");
1178 assert_eq!(
1179 n.canonical_name().as_deref(),
1180 Some("Baeomyces rufus (Huds.) Rebent.")
1181 );
1182 assert_eq!(
1183 n.canonical_name_without_authorship().as_deref(),
1184 Some("Baeomyces rufus")
1185 );
1186 assert_eq!(n.authorship_complete().as_deref(), Some("(Huds.) Rebent."));
1187 }
1188
1189 #[test]
1190 fn basionym_parens_with_year() {
1191 let n = p("Oenanthe oenanthe (Linnaeus, 1758)");
1192 assert_eq!(
1193 n.canonical_name().as_deref(),
1194 Some("Oenanthe oenanthe (Linnaeus, 1758)")
1195 );
1196 assert_eq!(n.authorship_complete().as_deref(), Some("(Linnaeus, 1758)"));
1197 }
1198
1199 #[test]
1200 fn sanctioning_author_rendered_with_colon() {
1201 // http://www.iapt-taxon.org/nomen/main.php?page=r50E — sanctioning author after " : ".
1202 let n = p("Agaricus campestris L. : Fr.");
1203 assert_eq!(
1204 n.canonical_name().as_deref(),
1205 Some("Agaricus campestris L. : Fr.")
1206 );
1207 assert_eq!(n.authorship_complete().as_deref(), Some("L. : Fr."));
1208 }
1209
1210 #[test]
1211 fn basionym_sanctioning_author_rendered_inside_the_brackets() {
1212 let n = p("Merulius lacrimans (Wulfen : Fr.) Schum.");
1213 assert_eq!(
1214 n.canonical_name().as_deref(),
1215 Some("Merulius lacrimans (Wulfen : Fr.) Schum.")
1216 );
1217 let n = p("Boletus edulis Bull. : Fr., 1821");
1218 assert_eq!(
1219 n.authorship_complete().as_deref(),
1220 Some("Bull., 1821 : Fr.")
1221 );
1222 }
1223
1224 #[test]
1225 fn notho_genus_hybrid_marker_with_space() {
1226 let n = p("×Agropogon littoralis");
1227 assert_eq!(
1228 n.canonical_name().as_deref(),
1229 Some("× Agropogon littoralis")
1230 );
1231 // minimal drops the hybrid marker.
1232 assert_eq!(
1233 n.canonical_name_minimal().as_deref(),
1234 Some("Agropogon littoralis")
1235 );
1236 }
1237
1238 #[test]
1239 fn notho_species_hybrid_marker() {
1240 let n = p("Salix ×capreola Andersson");
1241 assert_eq!(
1242 n.canonical_name().as_deref(),
1243 Some("Salix × capreola Andersson")
1244 );
1245 assert_eq!(
1246 n.canonical_name_minimal().as_deref(),
1247 Some("Salix capreola")
1248 );
1249 }
1250
1251 #[test]
1252 fn cultivar_epithet_in_single_quotes_and_minimal_drops_it() {
1253 let n = p("Acer campestre 'Elsrijk'");
1254 assert_eq!(
1255 n.canonical_name().as_deref(),
1256 Some("Acer campestre 'Elsrijk'")
1257 );
1258 assert_eq!(
1259 n.canonical_name_minimal().as_deref(),
1260 Some("Acer campestre")
1261 );
1262 }
1263
1264 #[test]
1265 fn candidatus_wraps_in_quotes_with_bacterial_comma_less_year() {
1266 // Candidatus implies the bacterial code: the year carries no comma, and the whole
1267 // name is wrapped in double quotes.
1268 let n = p("Candidatus Nanopelagicus abundans Ghai, 2013");
1269 assert_eq!(
1270 n.canonical_name().as_deref(),
1271 Some("\"Candidatus Nanopelagicus abundans\" Ghai 2013")
1272 );
1273 assert_eq!(n.authorship_complete().as_deref(), Some("Ghai 2013"));
1274 }
1275
1276 #[test]
1277 fn minimal_folds_ligatures_and_diacritics_to_ascii() {
1278 // decompose expands the "æ" ligature; foldToAscii's NFD strips the "ü" umlaut.
1279 assert_eq!(
1280 p("Læptura").canonical_name_minimal().as_deref(),
1281 Some("Laeptura")
1282 );
1283 assert_eq!(
1284 p("Rübsaamenia excelsa").canonical_name_minimal().as_deref(),
1285 Some("Rubsaamenia excelsa")
1286 );
1287 // ...but the non-minimal renderings keep the original unicode.
1288 assert_eq!(p("Læptura").canonical_name().as_deref(), Some("Læptura"));
1289 }
1290
1291 #[test]
1292 fn cultivar_group_indet_mirrors_javas_null_marker_append() {
1293 // Latent faithfulness case flagged by review, unreachable via parse(): a CULTIVAR_GROUP
1294 // name with a specific but no infraspecific/cultivar epithet. CULTIVAR_GROUP is
1295 // infraspecific yet has a null rank marker, so Java's
1296 // `sb.append(n.getRank().getMarker())` appends the literal "null"
1297 // (`StringBuilder.append((String) null)`). Java-verified: `canonical(pn)` == "Aaa bbb
1298 // null". The formatter is public API over any hand-built ParsedName, so we mirror it.
1299 use crate::model::{ParsedName, Rank};
1300 let pn = ParsedName {
1301 rank: Rank::CultivarGroup,
1302 genus: Some("Aaa".to_string()),
1303 specific_epithet: Some("bbb".to_string()),
1304 ..Default::default()
1305 };
1306 assert_eq!(pn.canonical_name().as_deref(), Some("Aaa bbb null"));
1307 assert_eq!(
1308 pn.canonical_name_complete().as_deref(),
1309 Some("Aaa bbb null")
1310 );
1311 }
1312
1313 #[test]
1314 fn complete_html_italicises_name_parts() {
1315 assert_eq!(
1316 p("Abies alba Mill.")
1317 .canonical_name_complete_html()
1318 .as_deref(),
1319 Some("<i>Abies</i> <i>alba</i> Mill.")
1320 );
1321 // notho marker sits (un-italicised) between the italic parts.
1322 assert_eq!(
1323 p("Salix ×capreola Andersson")
1324 .canonical_name_complete_html()
1325 .as_deref(),
1326 Some("<i>Salix</i> × <i>capreola</i> Andersson")
1327 );
1328 assert_eq!(
1329 p("Astragalus subg. Cercidothrix")
1330 .canonical_name_complete_html()
1331 .as_deref(),
1332 Some("<i>Astragalus</i> subgen. <i>Cercidothrix</i>")
1333 );
1334 }
1335}