Skip to main content

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