use std::sync::OnceLock;
use regex::{Regex, RegexSet};
use crate::sec_tr_data as data;
pub const NS: &str = "http://www.sec.gov/inlineXBRL/transformation/2015-08-31";
pub const FORMATS: &[&str] = &[
"duryear",
"durmonth",
"durweek",
"durday",
"durhour",
"datequarterend",
"numinf",
"numneginf",
"numnan",
"numwordsen",
"durwordsen",
"boolballotbox",
"yesnoballotbox",
"countrynameen",
"stateprovnameen",
"edgarprovcountryen",
"exchnameen",
"entityfilercategoryen",
];
pub fn is_defined(local: &str) -> bool {
FORMATS.contains(&local)
}
pub fn apply(local: &str, s: &str) -> Option<String> {
match local {
"duryear" => {
let (n, sign) = number(s)?;
let years = n.trunc();
let months = (n - years) * 12.0;
let days = ((months - months.trunc()) * 30.4375).trunc();
Some(duration_value(
Some(years as i64),
Some(months.trunc() as i64),
Some(days as i64),
None,
sign,
))
}
"durmonth" => {
let (n, sign) = number(s)?;
let months = n.trunc();
let days = ((n - months) * 30.4375).trunc();
Some(duration_value(
None,
Some(months as i64),
Some(days as i64),
None,
sign,
))
}
"durweek" => {
let (n, sign) = number(s)?;
Some(duration_value(
None,
None,
Some((n * 7.0).trunc() as i64),
None,
sign,
))
}
"durday" => {
let (n, sign) = number(s)?;
let days = n.trunc();
let hours = ((n - days) * 24.0).trunc();
Some(duration_value(
None,
None,
Some(days as i64),
Some(hours as i64),
sign,
))
}
"durhour" => {
let (n, sign) = number(s)?;
Some(duration_value(
None,
None,
None,
Some(n.trunc() as i64),
sign,
))
}
"datequarterend" => quarter_end(s),
"numinf" => Some("INF".into()),
"numneginf" => Some("-INF".into()),
"numnan" => Some("NaN".into()),
"numwordsen" => num_words(s),
"durwordsen" => dur_words(s),
"boolballotbox" => ballot(s).map(|b| if b { "true" } else { "false" }.to_string()),
"yesnoballotbox" => ballot(s).map(|b| if b { "Yes" } else { "No" }.to_string()),
"countrynameen" => table(0, s),
"stateprovnameen" => table(1, s),
"edgarprovcountryen" => table(2, s),
"exchnameen" => table(3, s),
"entityfilercategoryen" => table(4, s),
_ => None,
}
}
fn is_ws(c: char) -> bool {
matches!(c, ' ' | '\t' | '\n' | '\r')
}
fn number(s: &str) -> Option<(f64, &'static str)> {
let t = s.trim_matches(is_ws);
let body = t.strip_prefix(['+', '-']).unwrap_or(t);
let (int, frac) = match body.split_once('.') {
Some((i, f)) => (i, Some(f)),
None => (body, None),
};
let digits = |x: &str| x.chars().all(|c| c.is_ascii_digit());
let ok = match frac {
None => !int.is_empty() && digits(int),
Some(f) => digits(int) && digits(f) && (!int.is_empty() || !f.is_empty()),
};
if !ok || (int.is_empty() && frac.map(|f| f.is_empty()).unwrap_or(true)) {
return None;
}
let n: f64 = t.parse().ok().or_else(|| format!("{}0", t).parse().ok())?;
Some(if n < 0.0 { (-n, "-") } else { (n, "") })
}
fn duration_value(
y: Option<i64>,
mut m: Option<i64>,
mut d: Option<i64>,
mut h: Option<i64>,
mut sign: &str,
) -> String {
let z = |v: Option<i64>| v.map(|x| x == 0).unwrap_or(true);
if z(y) && z(m) && z(d) && z(h) {
sign = "";
let mut hit = y == Some(0);
if m == Some(0) {
if hit {
m = None
} else {
hit = true
}
}
if d == Some(0) {
if hit {
d = None
} else {
hit = true
}
}
if h == Some(0) && hit {
h = None
}
}
let mut out = format!("{}P", sign);
if let Some(y) = y {
out.push_str(&format!("{}Y", y));
}
if let Some(m) = m {
if m != 0 || y.is_none() {
out.push_str(&format!("{}M", m));
}
}
if let Some(d) = d {
if d != 0 || (y.is_none() && m.is_none()) {
out.push_str(&format!("{}D", d));
}
}
if let Some(h) = h {
if h != 0 || (y.is_none() && m.is_none() && d.is_none()) {
out.push_str(&format!("T{}H", h));
}
}
out
}
fn quarter_end(s: &str) -> Option<String> {
static RE: OnceLock<Regex> = OnceLock::new();
let re = RE.get_or_init(|| {
let q = r"(1|[Ff]irst|2|[Ss]econd|3|[Tt]hird|4|[Ff]ourth|[Ll]ast)";
Regex::new(&format!(
r"^[ \t\n\r]*(?:(?:(?:[^\W\d]|\d)[^0-9]*)?{q}[^0-9]*([0-9]{{4}})|([0-9]{{4}})[^0-9]*{q}(?:[^\W0-9]|[^0-9].*\w)?)[ \t\n\r]*$"
))
.expect("quarter end pattern")
});
let c = re.captures(s)?;
let year: i32 = c.get(2).or(c.get(3))?.as_str().parse().ok()?;
let q = c.get(1).or(c.get(4))?.as_str().to_lowercase();
let md = match q.as_str() {
"first" | "1" => "03-31",
"second" | "2" => "06-30",
"third" | "3" => "09-30",
_ => "12-31",
};
Some(format!("{:04}-{}", year, md))
}
const SMALL: &[(&str, u64)] = &[
("zero", 0),
("one", 1),
("two", 2),
("three", 3),
("four", 4),
("five", 5),
("six", 6),
("seven", 7),
("eight", 8),
("nine", 9),
("ten", 10),
("eleven", 11),
("twelve", 12),
("thirteen", 13),
("fourteen", 14),
("fifteen", 15),
("sixteen", 16),
("seventeen", 17),
("eighteen", 18),
("nineteen", 19),
("twenty", 20),
("thirty", 30),
("forty", 40),
("fifty", 50),
("sixty", 60),
("seventy", 70),
("eighty", 80),
("ninety", 90),
];
const MAGNITUDE: &[(&str, u128)] = &[
("thousand", 1_000),
("million", 1_000_000),
("billion", 1_000_000_000),
("trillion", 1_000_000_000_000),
("quadrillion", 1_000_000_000_000_000),
("quintillion", 1_000_000_000_000_000_000),
];
fn is_dash(c: char) -> bool {
matches!(
c,
'-' | '\u{058A}'
| '\u{05BE}'
| '\u{2010}'
| '\u{2011}'
| '\u{2012}'
| '\u{2013}'
| '\u{2014}'
| '\u{2015}'
| '\u{FE58}'
| '\u{FE63}'
| '\u{FF0D}'
)
}
fn word_case_ok(w: &str) -> bool {
w.chars().skip(1).all(|c| !c.is_uppercase())
}
fn text2num(words: &[&str]) -> Option<u128> {
let (mut n, mut g): (u128, u128) = (0, 0);
if words.is_empty() {
return None;
}
for w in words {
if let Some((_, v)) = SMALL.iter().find(|(k, _)| k == w) {
g += *v as u128;
} else if *w == "hundred" && g != 0 {
g *= 100;
} else if let Some((_, v)) = MAGNITUDE.iter().find(|(k, _)| k == w) {
n += g * v;
g = 0;
} else {
return None;
}
}
Some(n + g)
}
fn num_words(s: &str) -> Option<String> {
let t = s.trim_matches(is_ws);
if t.is_empty() {
return None;
}
if matches!(t, "No" | "no" | "None" | "none" | "Nil" | "nil") {
return Some("0".into());
}
let words: Vec<&str> = t
.split(|c: char| c.is_whitespace() || c == ',' || is_dash(c))
.filter(|w| !w.is_empty())
.collect();
if words.iter().any(|w| !word_case_ok(w)) {
return None;
}
let lower: Vec<String> = words
.iter()
.map(|w| w.to_lowercase())
.filter(|w| w != "and")
.collect();
let refs: Vec<&str> = lower.iter().map(|s| s.as_str()).collect();
if refs.first() == Some(&"zero") && refs.len() > 1 {
return None;
}
text2num(&refs).map(|n| n.to_string())
}
fn dur_words(s: &str) -> Option<String> {
let t = s.trim_matches(is_ws);
if t.is_empty() {
return None;
}
let words: Vec<&str> = t
.split(|c: char| c.is_whitespace() || c == ',' || is_dash(c))
.filter(|w| !w.is_empty())
.collect();
let mut out = String::from("P");
let mut pending: Vec<String> = Vec::new();
let mut next_unit = 0; for w in words {
let lw = w.to_lowercase();
let unit = match lw.as_str() {
"year" | "years" => Some(0),
"month" | "months" => Some(1),
"day" | "days" => Some(2),
_ => None,
};
match unit {
None => {
if lw == "and" && pending.is_empty() {
continue;
}
if !word_case_ok(w) {
return None;
}
pending.push(lw);
}
Some(u) => {
if u < next_unit || pending.is_empty() || !word_case_ok(w) {
return None;
}
next_unit = u + 1;
let part = std::mem::take(&mut pending);
let value = if part.len() == 1 && matches!(part[0].as_str(), "zero" | "no") {
None
} else if part.len() == 1 && part[0].chars().all(|c| c.is_ascii_digit()) {
if part[0].len() > 4 {
return None;
}
Some(part[0].clone())
} else {
let refs: Vec<&str> = part
.iter()
.map(|s| s.as_str())
.filter(|s| *s != "and")
.collect();
let n = text2num(&refs)?;
if n > 999 || refs.contains(&"zero") {
return None;
}
Some(n.to_string())
};
if let Some(v) = value {
out.push_str(&v);
out.push(['Y', 'M', 'D'][u]);
}
}
}
}
if !pending.is_empty() {
return None;
}
Some(if out.len() > 1 { out } else { "P0D".into() })
}
fn ballot(s: &str) -> Option<bool> {
let t = s.trim_matches(is_ws);
match t {
"\u{2610}" => Some(false),
"\u{2611}" | "\u{2612}" => Some(true),
_ => None,
}
}
struct Table {
set: RegexSet,
codes: Vec<&'static str>,
}
fn table(which: usize, s: &str) -> Option<String> {
static TABLES: OnceLock<Vec<Table>> = OnceLock::new();
let tables = TABLES.get_or_init(|| {
[
data::COUNTRY_NAME_EN,
data::STATE_PROV_NAME_EN,
data::EDGAR_PROV_COUNTRY_EN,
data::EXCH_NAME_EN,
data::ENTITY_FILER_CATEGORY_EN,
]
.iter()
.map(|t| Table {
set: RegexSet::new(
t.iter()
.map(|(p, _)| format!(r"^[ \t\n\r]*(?:{})[ \t\n\r]*$", p)),
)
.expect("SEC name table pattern"),
codes: t.iter().map(|(_, c)| *c).collect(),
})
.collect()
});
let t = &tables[which];
if s.trim_matches(is_ws).is_empty() {
return None;
}
t.set
.matches(s)
.iter()
.next()
.map(|i| t.codes[i].to_string())
}
#[cfg(test)]
mod tests {
use super::*;
fn ok(f: &str, s: &str, want: &str) {
assert_eq!(apply(f, s).as_deref(), Some(want), "{} {:?}", f, s);
}
fn bad(f: &str, s: &str) {
assert_eq!(apply(f, s), None, "{} {:?} should be invalid", f, s);
}
#[test]
fn durations_spill_like_the_sec_plugin() {
ok("duryear", "1.5", "P1Y6M");
ok("duryear", "5", "P5Y");
ok("duryear", "0", "P0Y");
ok("duryear", "-2", "-P2Y");
ok("duryear", "2.25", "P2Y3M");
ok("durmonth", "18", "P18M");
ok("durmonth", "0.5", "P0M15D");
ok("durweek", "2", "P14D");
ok("durday", "1.5", "P1DT12H");
ok("durday", "30", "P30D");
ok("durhour", "36", "PT36H");
bad("duryear", "five");
bad("duryear", "");
bad("duryear", "1.2.3");
ok("duryear", ".5", "P0Y6M");
}
#[test]
fn words() {
ok("numwordsen", "Twelve", "12");
ok("numwordsen", "no", "0");
ok("numwordsen", "None", "0");
ok("numwordsen", "zero", "0");
ok("numwordsen", "one hundred and five", "105");
ok("numwordsen", "twenty-one thousand, three hundred", "21300");
bad("numwordsen", "lots");
bad("numwordsen", "TWELVE");
ok("durwordsen", "five-year", "P5Y");
ok("durwordsen", "two years and six months", "P2Y6M");
ok("durwordsen", "18 months", "P18M");
ok(
"durwordsen",
"one year, three months and ten days",
"P1Y3M10D",
);
ok("durwordsen", "zero years", "P0D");
ok("durwordsen", "thirty-day", "P30D");
bad("durwordsen", "a while");
bad("durwordsen", "six months two years");
bad("durwordsen", "two weeks");
}
#[test]
fn ballots_and_quarters() {
ok("boolballotbox", "☒", "true");
ok("boolballotbox", " ☐ ", "false");
ok("yesnoballotbox", "☑", "Yes");
bad("boolballotbox", "x");
ok("datequarterend", "Q3 2024", "2024-09-30");
ok("datequarterend", "third quarter 2024", "2024-09-30");
ok("datequarterend", "2024 first quarter", "2024-03-31");
ok("datequarterend", "fourth quarter of 2023", "2023-12-31");
bad("datequarterend", "sometime");
}
#[test]
fn name_tables() {
ok("stateprovnameen", "Washington", "WA");
ok("stateprovnameen", "Delaware", "DE");
ok("countrynameen", "United States", "US");
ok("countrynameen", "Cayman Islands", "KY");
ok("exchnameen", "Nasdaq Global Select Market", "NASDAQ");
ok("exchnameen", "New York Stock Exchange", "NYSE");
ok(
"entityfilercategoryen",
"Large accelerated filer",
"Large Accelerated Filer",
);
ok(
"entityfilercategoryen",
"Non-accelerated Filer",
"Non-accelerated Filer",
);
ok("edgarprovcountryen", "Ontario, Canada", "A6");
bad("stateprovnameen", "Atlantis");
bad("countrynameen", "");
for f in FORMATS {
let _ = apply(f, "\u{0}");
}
}
}