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