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