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