use std::collections::HashSet;
use std::sync::LazyLock;
use regex::Regex;
use crate::model::{warnings, NomCode};
use crate::pipeline::assemble;
use crate::pipeline::authorship_parser::{is_sanctioning_author, AuthState};
use crate::pipeline::ParseContext;
static ICN_STATUS: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?-u:\b(?:illeg|inval|superfl|super|cons|rej|rejic|ambig|confus))").unwrap()
});
static ICZN_STATUS: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?-u:\b(?:oblitum|protectum)\b)").unwrap());
static INED: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i-u:\bined\b|\bcomb\.\s*nud\b)").unwrap());
pub(crate) fn infer(ctx: &mut ParseContext, auth_state: Option<&AuthState>) {
if let Some(rank_code) = ctx.name.rank.code() {
ctx.name.code = Some(rank_code);
return;
}
let hybrid = ctx.name.notho.as_ref().is_some_and(|n| !n.is_empty());
if hybrid && ctx.name.infrageneric_epithet.is_none() {
ctx.name.code = Some(NomCode::Botanical);
return;
}
let sanctioned = [
auth_state.and_then(|st| st.combination.sanctioning_author.as_deref()),
auth_state.and_then(|st| st.basionym.sanctioning_author.as_deref()),
ctx.name
.combination_authorship
.sanctioning_author
.as_deref(),
ctx.name.basionym_authorship.sanctioning_author.as_deref(),
];
if sanctioned.into_iter().flatten().any(is_sanctioning_author) {
ctx.name.code = Some(NomCode::Botanical);
return;
}
if ctx.approved_lists {
ctx.name.code = Some(NomCode::Bacterial);
return;
}
if let Some(note_code) = code_from_nom_note(ctx.name.nomenclatural_note.as_deref()) {
ctx.name.code = Some(note_code);
return;
}
let mut votes: HashSet<NomCode> = HashSet::new();
if hybrid {
votes.insert(NomCode::Botanical);
}
if ctx.name.candidatus {
votes.insert(NomCode::Bacterial);
}
if let Some(auth_state) = auth_state {
authorship_votes(ctx, auth_state, false, &mut votes);
}
if let Some(species) = ctx.species_code_state.take() {
authorship_votes(ctx, &species, true, &mut votes);
}
if ctx
.name
.taxonomic_note
.as_deref()
.is_some_and(|n| n.starts_with("emend"))
{
votes.remove(&NomCode::Zoological);
}
if ctx.coded_diacritics {
votes.remove(&NomCode::Zoological);
votes.insert(NomCode::Botanical);
}
if votes.len() == 1 {
ctx.name.code = votes.into_iter().next();
}
}
fn authorship_votes(
ctx: &ParseContext,
auth_state: &AuthState,
species: bool,
votes: &mut HashSet<NomCode>,
) {
let dated = |y: &Option<String>| {
y.as_deref().is_some_and(|y| {
!assemble::is_unlikely_year(Some(y))
|| (y.len() == 3 && y.parse::<u32>().is_ok_and(|v| (150..=210).contains(&v)))
})
};
let bas_year = auth_state.basionym_present
&& dated(&auth_state.basionym.year)
&& auth_state.basionym.has_authors_or_anon();
let comb_year =
dated(&auth_state.combination.year) && auth_state.combination.has_authors_or_anon();
let any_author_year = bas_year || comb_year;
let botanical_style_year =
!auth_state.combination_year_after_comma && auth_state.combination_initials_first;
let zoological_year = bas_year
|| (comb_year
&& !all_abbreviated(&auth_state.combination.authors)
&& !botanical_style_year);
if auth_state.combination.sanctioning_author.is_some()
|| ctx.name.combination_authorship.sanctioning_author.is_some()
{
votes.insert(NomCode::Botanical);
}
if auth_state.basionym_present && auth_state.combination.has_authors_or_anon() {
votes.insert(NomCode::Botanical);
}
if (!auth_state.combination.ex_authors.is_empty() || !auth_state.basionym.ex_authors.is_empty())
&& !auth_state.manuscript_ex
{
votes.insert(NomCode::Botanical);
}
if auth_state.has_filius && !any_author_year {
votes.insert(NomCode::Botanical);
}
let years = [&auth_state.combination.year, &auth_state.basionym.year];
let pre_zoological = years
.iter()
.filter_map(|y| y.as_deref().and_then(|y| y.get(..4)?.parse::<u32>().ok()))
.any(|y| (1500..1758).contains(&y));
if years
.iter()
.filter_map(|y| y.as_deref().and_then(|y| y.get(..4)?.parse::<u32>().ok()))
.any(|y| (1753..1758).contains(&y))
{
votes.insert(NomCode::Botanical);
}
let unpublished_combination = ctx
.name
.nomenclatural_note
.as_deref()
.is_some_and(|n| INED.is_match(n));
if auth_state.basionym_present
&& !auth_state.combination.has_authors_or_anon()
&& !unpublished_combination
&& !((species || ctx.name.specific_authorship.is_some())
&& auth_state.basionym.year.is_none())
{
votes.insert(NomCode::Zoological);
}
if zoological_year && !pre_zoological {
votes.insert(NomCode::Zoological);
}
}
fn all_abbreviated(authors: &[String]) -> bool {
let base = |a: &str| {
let a = a.trim_end();
[".f.", " f.", ".fil.", " fil.", " filius"]
.iter()
.find_map(|suffix| {
a.strip_suffix(suffix)
.map(|b| format!("{b}{}", &suffix[..1]))
})
.map(|b| b.trim_end().to_string())
.unwrap_or_else(|| a.to_string())
};
!authors.is_empty() && authors.iter().all(|a| base(a).ends_with('.'))
}
pub(crate) fn code_from_nom_note(note: Option<&str>) -> Option<NomCode> {
let note = note?;
let s = note.to_lowercase();
if ICN_STATUS.is_match(&s) && !s.contains("illegitimum") {
return Some(NomCode::Botanical);
}
if ICZN_STATUS.is_match(&s) {
return Some(NomCode::Zoological);
}
None
}
pub(crate) fn apply_rank_code_mismatch(ctx: &mut ParseContext) {
let pinned = ctx.name.rank.code();
if let (Some(pinned), Some(existing), Some(requested)) =
(pinned, ctx.name.code, ctx.requested_code)
{
if existing != pinned && requested != pinned {
ctx.name.code = Some(pinned);
ctx.name.add_warning(warnings::CODE_MISMATCH);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::Rank;
use crate::pipeline::authorship_parser::parse as parse_auth;
use crate::token::tokenize;
fn auth_state(input: &str) -> AuthState {
let tokens = tokenize(input);
parse_auth(&tokens, 0)
}
fn ctx_with_rank(rank: Rank) -> ParseContext {
let mut ctx = ParseContext::new("x".to_string(), None, None, None);
ctx.name.rank = rank;
ctx
}
#[test]
fn pin1_code_exclusive_rank_wins_outright_even_against_contradicting_votes() {
let mut ctx = ctx_with_rank(Rank::Cultivar); let auth = auth_state("(DC.) L., 1901");
infer(&mut ctx, Some(&auth));
assert_eq!(ctx.name.code, Some(NomCode::Cultivars));
}
#[test]
fn pin2_nom_cons_pins_botanical() {
let mut ctx = ctx_with_rank(Rank::Unranked);
ctx.name.nomenclatural_note = Some("nom. cons.".to_string());
infer(&mut ctx, None);
assert_eq!(ctx.name.code, Some(NomCode::Botanical));
}
#[test]
fn pin2_nomen_oblitum_pins_zoological() {
let mut ctx = ctx_with_rank(Rank::Unranked);
ctx.name.nomenclatural_note = Some("nomen oblitum".to_string());
infer(&mut ctx, None);
assert_eq!(ctx.name.code, Some(NomCode::Zoological));
}
#[test]
fn code_from_nom_note_returns_none_for_a_shared_status() {
assert_eq!(code_from_nom_note(Some("nom. nud.")), None);
}
#[test]
fn code_from_nom_note_returns_none_for_none_input() {
assert_eq!(code_from_nom_note(None), None);
}
#[test]
fn code_from_nom_note_does_not_match_a_word_that_merely_contains_the_token() {
assert_eq!(code_from_nom_note(Some("reconsider this")), None);
}
#[test]
fn basionym_recombination_votes_botanical() {
let mut ctx = ctx_with_rank(Rank::Unranked);
let auth = auth_state("(DC.) L."); infer(&mut ctx, Some(&auth));
assert_eq!(ctx.name.code, Some(NomCode::Botanical));
}
#[test]
fn basionym_only_author_year_votes_zoological() {
let mut ctx = ctx_with_rank(Rank::Unranked);
let auth = auth_state("(Vasileyev, 1939)"); infer(&mut ctx, Some(&auth));
assert_eq!(ctx.name.code, Some(NomCode::Zoological));
}
#[test]
fn candidatus_votes_bacterial() {
let mut ctx = ctx_with_rank(Rank::Unranked);
ctx.name.candidatus = true;
infer(&mut ctx, None);
assert_eq!(ctx.name.code, Some(NomCode::Bacterial));
}
#[test]
fn contradicting_votes_leave_code_unset() {
let mut ctx = ctx_with_rank(Rank::Unranked);
let auth = auth_state("(DC.) Linnaeus, 1901");
infer(&mut ctx, Some(&auth));
assert_eq!(ctx.name.code, None);
}
#[test]
fn no_signal_at_all_leaves_code_unset() {
let mut ctx = ctx_with_rank(Rank::Unranked);
infer(&mut ctx, None);
assert_eq!(ctx.name.code, None);
}
#[test]
fn rank_code_mismatch_overrides_and_warns() {
let mut ctx = ctx_with_rank(Rank::SupersectionBotany); ctx.name.code = Some(NomCode::Zoological);
ctx.requested_code = Some(NomCode::Zoological);
apply_rank_code_mismatch(&mut ctx);
assert_eq!(ctx.name.code, Some(NomCode::Botanical));
assert!(ctx
.name
.warnings
.contains(&warnings::CODE_MISMATCH.to_string()));
}
#[test]
fn rank_code_mismatch_skips_when_requested_code_matches_pinned() {
let mut ctx = ctx_with_rank(Rank::SupersectionBotany);
ctx.name.code = Some(NomCode::Zoological);
ctx.requested_code = Some(NomCode::Botanical); apply_rank_code_mismatch(&mut ctx);
assert_eq!(
ctx.name.code,
Some(NomCode::Zoological),
"no override: requested == pinned"
);
assert!(ctx.name.warnings.is_empty());
}
#[test]
fn rank_code_mismatch_skips_when_requested_code_is_none() {
let mut ctx = ctx_with_rank(Rank::SupersectionBotany);
ctx.name.code = Some(NomCode::Zoological);
ctx.requested_code = None;
apply_rank_code_mismatch(&mut ctx);
assert_eq!(ctx.name.code, Some(NomCode::Zoological));
assert!(ctx.name.warnings.is_empty());
}
#[test]
fn rank_code_mismatch_skips_when_rank_has_no_code() {
let mut ctx = ctx_with_rank(Rank::Genus); ctx.name.code = Some(NomCode::Zoological);
ctx.requested_code = Some(NomCode::Botanical);
apply_rank_code_mismatch(&mut ctx);
assert_eq!(ctx.name.code, Some(NomCode::Zoological));
assert!(ctx.name.warnings.is_empty());
}
#[test]
fn rank_code_mismatch_skips_when_code_already_matches_pinned() {
let mut ctx = ctx_with_rank(Rank::SupersectionBotany);
ctx.name.code = Some(NomCode::Botanical); ctx.requested_code = Some(NomCode::Zoological);
apply_rank_code_mismatch(&mut ctx);
assert_eq!(ctx.name.code, Some(NomCode::Botanical));
assert!(ctx.name.warnings.is_empty());
}
}