use crate::error::{Result, XbrlError};
use crate::instance::{Context, Instance, RawFact, Unit, XbrlValue};
use crate::parser;
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::cmp::{Ordering, Reverse};
use std::collections::{BTreeSet, HashMap, HashSet};
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Span {
pub end: String,
pub start: Option<String>,
}
impl Span {
pub fn instant(date: impl Into<String>) -> Self {
Span {
end: date.into(),
start: None,
}
}
pub fn duration(start: impl Into<String>, end: impl Into<String>) -> Self {
Span {
end: end.into(),
start: Some(start.into()),
}
}
pub fn is_instant(&self) -> bool {
self.start.is_none()
}
fn of(context: &Context) -> Option<Span> {
let period = &context.period;
let end = period.end_date.as_ref().or(period.instant.as_ref())?;
let end = end.trim();
if end.is_empty() {
return None;
}
Some(Span {
end: end.to_string(),
start: period.start_date.as_ref().map(|s| s.trim().to_string()),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PeriodKind {
Any,
Instant,
Duration,
}
impl PeriodKind {
fn admits(self, span: &Span) -> bool {
match self {
PeriodKind::Any => true,
PeriodKind::Instant => span.is_instant(),
PeriodKind::Duration => !span.is_instant(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Dimension {
pub axis: String,
pub member: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Fact<T> {
pub value: T,
pub period_start: Option<String>,
pub period_end: Option<String>,
pub unit: Option<String>,
pub decimals: Option<i32>,
#[serde(default)]
pub dimensions: Vec<Dimension>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum PeriodMatch {
Unknown,
AfterReport,
BeforeReport,
EndsOnReportDate,
RequiredContext,
}
impl PeriodMatch {
fn of(span: Option<&Span>, report: Option<&Span>) -> Self {
let Some(span) = span else {
return PeriodMatch::Unknown;
};
let Some(report) = report else {
return PeriodMatch::BeforeReport;
};
match span.end.cmp(&report.end) {
Ordering::Greater => PeriodMatch::AfterReport,
Ordering::Less => PeriodMatch::BeforeReport,
Ordering::Equal => match (&span.start, &report.start) {
(None, _) => PeriodMatch::RequiredContext,
(Some(start), Some(report_start)) if start == report_start => {
PeriodMatch::RequiredContext
}
(Some(_), None) => PeriodMatch::RequiredContext,
(Some(_), Some(_)) => PeriodMatch::EndsOnReportDate,
},
}
}
}
struct Candidate<'a> {
preference: usize,
fact: &'a RawFact,
context: Option<&'a Context>,
span: Option<Span>,
members: usize,
}
fn precision(fact: &RawFact) -> i64 {
match fact.decimals.as_deref().map(str::trim) {
Some(decimals) if decimals.eq_ignore_ascii_case("INF") => i64::MAX,
Some(decimals) => decimals.parse().unwrap_or(i64::MIN),
None => i64::MIN,
}
}
impl<'a> Candidate<'a> {
fn duplicate_key(&self) -> (&'a str, Option<&'a str>) {
(
self.fact.full_name.as_str(),
self.fact.context_ref.as_deref(),
)
}
}
fn member_count(context: &Context) -> usize {
context.explicit_members().count() + context.typed_members().count()
}
fn dimensions_of(context: &Context) -> Vec<Dimension> {
let explicit = context.explicit_members().map(|m| (&m.dimension, &m.value));
let typed = context.typed_members().map(|m| (&m.dimension, &m.value));
explicit
.chain(typed)
.map(|(axis, member)| Dimension {
axis: axis.trim().to_string(),
member: member.trim().to_string(),
})
.collect()
}
fn without_namespace(measure: &str) -> &str {
let measure = measure.trim();
measure.rsplit_once(':').map_or(measure, |(_, local)| local)
}
fn unit_label(unit: &Unit) -> String {
match (&unit.measure, &unit.divide) {
(Some(measure), _) => without_namespace(measure).to_string(),
(None, Some(divide)) => format!(
"{}/{}",
without_namespace(÷.unit_numerator.measure),
without_namespace(÷.unit_denominator.measure)
),
(None, None) => unit.id.clone(),
}
}
fn is_iso_date(s: &str) -> bool {
let bytes = s.as_bytes();
bytes.len() == 10
&& bytes[4] == b'-'
&& bytes[7] == b'-'
&& bytes
.iter()
.enumerate()
.all(|(i, b)| i == 4 || i == 7 || b.is_ascii_digit())
}
pub struct Document {
instance: Instance,
by_full_name: HashMap<String, Vec<usize>>,
by_local_name: HashMap<String, Vec<usize>>,
contexts: HashMap<String, usize>,
units: HashMap<String, String>,
reporting_period: Option<Span>,
}
impl Document {
pub fn parse(content: &str) -> Result<Self> {
match parser::is_xml_instance(content) {
true => Self::from_xml(content),
false => Self::from_ixbrl(content),
}
}
pub fn from_ixbrl(html: &str) -> Result<Self> {
parser::parse_ixbrl(html).map(Self::new)
}
pub fn from_xml(xml: &str) -> Result<Self> {
parser::parse_xml(xml).map(Self::new)
}
pub fn new(xbrl: Instance) -> Self {
let mut by_full_name = HashMap::<String, Vec<usize>>::new();
let mut by_local_name = HashMap::<String, Vec<usize>>::new();
for (i, fact) in xbrl.facts.iter().enumerate() {
by_full_name
.entry(fact.full_name.clone())
.or_default()
.push(i);
by_local_name
.entry(fact.local_name.clone())
.or_default()
.push(i);
}
let contexts = xbrl
.contexts
.iter()
.enumerate()
.map(|(i, c)| (c.id.clone(), i))
.collect();
let units = xbrl
.units
.iter()
.map(|u| (u.id.clone(), unit_label(u)))
.collect();
let mut data = Document {
instance: xbrl,
by_full_name,
by_local_name,
contexts,
units,
reporting_period: None,
};
data.reporting_period = data.resolve_reporting_period();
data
}
pub fn instance(&self) -> &Instance {
&self.instance
}
pub fn into_instance(self) -> Instance {
self.instance
}
pub fn facts(&self) -> &[RawFact] {
&self.instance.facts
}
pub fn contexts(&self) -> &[Context] {
&self.instance.contexts
}
pub fn units(&self) -> &[Unit] {
&self.instance.units
}
pub fn reporting_period(&self) -> Option<&Span> {
self.reporting_period.as_ref()
}
fn resolve_reporting_period(&self) -> Option<Span> {
let fact = self
.facts_named("dei:DocumentPeriodEndDate")
.next()
.or_else(|| self.facts_named("DocumentPeriodEndDate").next())?;
let context_span = self.context_of(fact).and_then(Span::of);
let end = match &fact.value {
XbrlValue::String(s) if is_iso_date(s.trim()) => Some(s.trim().to_string()),
_ => None,
}
.or_else(|| {
context_span
.as_ref()
.map(|s| s.end.clone())
.filter(|d| is_iso_date(d))
})?;
Some(Span {
end,
start: context_span.and_then(|s| s.start),
})
}
fn facts_named<'a>(&'a self, concept: &str) -> impl Iterator<Item = &'a RawFact> + use<'a> {
let index = if concept.contains(':') {
&self.by_full_name
} else {
&self.by_local_name
};
index
.get(concept)
.into_iter()
.flatten()
.map(|&i| &self.instance.facts[i])
}
fn context_of(&self, fact: &RawFact) -> Option<&Context> {
let id = fact.context_ref.as_deref()?;
self.contexts.get(id).map(|&i| &self.instance.contexts[i])
}
fn candidates<'a>(&'a self, concepts: &[&str]) -> Vec<Candidate<'a>> {
let mut candidates = Vec::new();
for (preference, concept) in concepts.iter().enumerate() {
for fact in self.facts_named(concept) {
let context = self.context_of(fact);
candidates.push(Candidate {
preference,
fact,
context,
span: context.and_then(Span::of),
members: context.map_or(0, member_count),
});
}
}
let mut most_exact: HashMap<(&str, Option<&str>), i64> = HashMap::new();
for candidate in &candidates {
let exact = most_exact
.entry(candidate.duplicate_key())
.or_insert(i64::MIN);
*exact = (*exact).max(precision(candidate.fact));
}
candidates.retain(|c| precision(c.fact) == most_exact[&c.duplicate_key()]);
candidates
}
fn rank(&self, a: &Candidate<'_>, b: &Candidate<'_>) -> Ordering {
let report = self.reporting_period.as_ref();
let class_a = PeriodMatch::of(a.span.as_ref(), report);
let class_b = PeriodMatch::of(b.span.as_ref(), report);
a.context
.is_some()
.cmp(&b.context.is_some())
.then_with(|| class_a.cmp(&class_b))
.then_with(|| b.preference.cmp(&a.preference))
.then_with(|| {
let end_a = a.span.as_ref().map_or("", |s| s.end.as_str());
let end_b = b.span.as_ref().map_or("", |s| s.end.as_str());
match class_a {
PeriodMatch::AfterReport => end_b.cmp(end_a),
_ => end_a.cmp(end_b),
}
})
.then_with(|| b.members.cmp(&a.members))
}
pub fn get<T: FromFacts>(&self, concepts: &[&str]) -> T {
let problems = RefCell::new(Vec::new());
let scope = Scope {
data: self,
period: None,
problems: &problems,
};
T::from_facts(
&scope,
concepts,
concepts.first().copied().unwrap_or_default(),
)
}
pub fn extract<T: FromXbrl>(&self) -> Result<T> {
let (value, mut problems) = self.extract_lenient::<T>();
match problems.is_empty() {
true => Ok(value),
false => Err(problems.remove(0)),
}
}
pub fn extract_lenient<T: FromXbrl>(&self) -> (T, Vec<XbrlError>) {
self.read(None)
}
pub fn extract_for<T: FromXbrl>(&self, period: &Span) -> (T, Vec<XbrlError>) {
self.read(Some(period.clone()))
}
pub fn extract_each_period<T: FromXbrl>(&self) -> (Vec<T>, Vec<XbrlError>) {
let problems = RefCell::new(Vec::new());
let scope = Scope {
data: self,
period: None,
problems: &problems,
};
let value = each_period(&scope);
(value, problems.into_inner())
}
fn read<T: FromXbrl>(&self, period: Option<Span>) -> (T, Vec<XbrlError>) {
let problems = RefCell::new(Vec::new());
let scope = Scope {
data: self,
period,
problems: &problems,
};
let value = T::from_xbrl(&scope);
(value, problems.into_inner())
}
}
pub struct Scope<'a> {
data: &'a Document,
period: Option<Span>,
problems: &'a RefCell<Vec<XbrlError>>,
}
impl<'a> Scope<'a> {
pub fn period_start(&self) -> Option<String> {
self.period.as_ref().and_then(|p| p.start.clone())
}
pub fn period_end(&self) -> Option<String> {
self.period.as_ref().map(|p| p.end.clone())
}
fn pick(&self, concepts: &[&str]) -> Option<Candidate<'a>> {
let candidates = self.data.candidates(concepts);
match &self.period {
Some(period) => candidates
.into_iter()
.rev()
.filter(|c| c.members == 0 && c.span.as_ref() == Some(period))
.min_by_key(|c| c.preference),
None => candidates.into_iter().max_by(|a, b| self.data.rank(a, b)),
}
}
fn all(&self, concepts: &[&str]) -> Vec<Candidate<'a>> {
let mut seen = HashSet::new();
let mut facts: Vec<Candidate<'a>> = self
.data
.candidates(concepts)
.into_iter()
.filter(|c| c.fact.value != XbrlValue::Nil && c.span.is_some())
.filter(|c| self.period.is_none() || c.span == self.period)
.filter(|c| {
seen.insert((
c.fact.full_name.as_str(),
c.fact.context_ref.as_deref(),
c.fact.value_key(),
))
})
.collect();
facts.sort_by(|a, b| {
Reverse(&a.span)
.cmp(&Reverse(&b.span))
.then_with(|| a.members.cmp(&b.members))
.then_with(|| a.preference.cmp(&b.preference))
});
facts
}
fn convert<T: FactValue>(&self, fact: &RawFact, field: &str) -> Option<T> {
let XbrlValue::String(raw) = &fact.value else {
return None;
};
let converted = T::from_fact_value(raw);
if converted.is_none() {
self.problems.borrow_mut().push(XbrlError::ValueConversion {
field: field.to_string(),
concept: fact.full_name.clone(),
value: raw.chars().take(80).collect(),
target_type: T::TYPE_NAME,
});
}
converted
}
fn with_context<T: FactValue>(
&self,
candidate: &Candidate<'a>,
field: &str,
) -> Option<Fact<T>> {
let value = self.convert(candidate.fact, field)?;
let fact = candidate.fact;
Some(Fact {
value,
period_start: candidate.span.as_ref().and_then(|s| s.start.clone()),
period_end: candidate.span.as_ref().map(|s| s.end.clone()),
unit: fact
.unit_ref
.as_deref()
.and_then(|id| self.data.units.get(id).cloned()),
decimals: fact.decimals.as_deref().and_then(|d| d.trim().parse().ok()),
dimensions: candidate.context.map(dimensions_of).unwrap_or_default(),
})
}
}
impl RawFact {
fn value_key(&self) -> &str {
match &self.value {
XbrlValue::String(s) => s.as_str(),
XbrlValue::Nil => "",
}
}
}
pub trait FactValue: Sized {
const TYPE_NAME: &'static str;
fn from_fact_value(raw: &str) -> Option<Self>;
}
impl FactValue for String {
const TYPE_NAME: &'static str = "String";
fn from_fact_value(raw: &str) -> Option<Self> {
Some(raw.to_string())
}
}
impl FactValue for f64 {
const TYPE_NAME: &'static str = "f64";
fn from_fact_value(raw: &str) -> Option<Self> {
raw.trim().replace(',', "").parse().ok()
}
}
impl FactValue for bool {
const TYPE_NAME: &'static str = "bool";
fn from_fact_value(raw: &str) -> Option<Self> {
let raw = raw.trim();
if raw.eq_ignore_ascii_case("true") || raw.eq_ignore_ascii_case("yes") {
Some(true)
} else if raw.eq_ignore_ascii_case("false") || raw.eq_ignore_ascii_case("no") {
Some(false)
} else {
None
}
}
}
macro_rules! integer_fact_value {
($($ty:ty),*) => {$(
impl FactValue for $ty {
const TYPE_NAME: &'static str = stringify!($ty);
fn from_fact_value(raw: &str) -> Option<Self> {
let raw = raw.trim().replace(',', "");
let whole = match raw.split_once('.') {
Some((whole, frac)) if frac.bytes().all(|b| b == b'0') => whole,
Some(_) => return None,
None => raw.as_str(),
};
whole.parse().ok()
}
}
)*};
}
integer_fact_value!(i32, i64, u32, u64);
pub trait FromFacts: Sized {
fn from_facts(scope: &Scope<'_>, concepts: &[&str], field: &str) -> Self;
}
impl<T: FactValue> FromFacts for Option<T> {
fn from_facts(scope: &Scope<'_>, concepts: &[&str], field: &str) -> Self {
scope
.pick(concepts)
.and_then(|c| scope.convert(c.fact, field))
}
}
impl<T: FactValue> FromFacts for Option<Fact<T>> {
fn from_facts(scope: &Scope<'_>, concepts: &[&str], field: &str) -> Self {
scope
.pick(concepts)
.and_then(|c| scope.with_context(&c, field))
}
}
impl<T: FactValue> FromFacts for Vec<Fact<T>> {
fn from_facts(scope: &Scope<'_>, concepts: &[&str], field: &str) -> Self {
scope
.all(concepts)
.iter()
.filter_map(|c| scope.with_context(c, field))
.collect()
}
}
pub trait FromXbrl: Sized {
const PERIOD_KIND: PeriodKind = PeriodKind::Any;
fn concepts(out: &mut Vec<&'static str>);
fn from_xbrl(scope: &Scope<'_>) -> Self;
}
pub fn each_period<T: FromXbrl>(scope: &Scope<'_>) -> Vec<T> {
let mut concepts = Vec::new();
T::concepts(&mut concepts);
let periods: BTreeSet<Span> = scope
.data
.candidates(&concepts)
.into_iter()
.filter(|c| c.members == 0 && c.fact.value != XbrlValue::Nil)
.filter_map(|c| c.span)
.filter(|span| T::PERIOD_KIND.admits(span))
.filter(|span| scope.period.as_ref().is_none_or(|p| p == span))
.collect();
periods
.into_iter()
.rev()
.map(|period| {
T::from_xbrl(&Scope {
data: scope.data,
period: Some(period),
problems: scope.problems,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::instance::{Entity, ExplicitMember, Identifier, Period, Segment};
fn context(id: &str, period: Period) -> Context {
Context {
id: id.to_string(),
entity: Entity {
identifier: Identifier {
scheme: "cik".to_string(),
value: "123".to_string(),
},
segment: None,
},
period,
scenario: None,
}
}
fn instant(id: &str, date: &str) -> Context {
context(
id,
Period {
instant: Some(date.to_string()),
start_date: None,
end_date: None,
},
)
}
fn duration(id: &str, start: &str, end: &str) -> Context {
context(
id,
Period {
instant: None,
start_date: Some(start.to_string()),
end_date: Some(end.to_string()),
},
)
}
fn with_member(mut context: Context, axis: &str, member: &str) -> Context {
context.entity.segment = Some(Segment {
explicit_members: vec![ExplicitMember {
dimension: axis.to_string(),
value: member.to_string(),
}],
typed_members: Vec::new(),
});
context
}
fn fact(name: &str, context: &str, value: &str) -> RawFact {
RawFact {
full_name: name.to_string(),
local_name: name.rsplit(':').next().unwrap().to_string(),
context_ref: Some(context.to_string()),
value: XbrlValue::String(value.to_string()),
..Default::default()
}
}
fn q3_document(mut facts: Vec<RawFact>, mut contexts: Vec<Context>) -> Document {
contexts.push(duration("ytd", "2024-01-01", "2024-09-30"));
contexts.push(duration("q3", "2024-07-01", "2024-09-30"));
contexts.push(duration("prior_ytd", "2023-01-01", "2023-09-30"));
contexts.push(instant("now", "2024-09-30"));
contexts.push(instant("year_end", "2023-12-31"));
contexts.push(instant("cover", "2024-11-12"));
facts.push(fact("dei:DocumentPeriodEndDate", "ytd", "2024-09-30"));
Document::new(Instance {
contexts,
units: Vec::new(),
facts,
})
}
fn one<T: FromFacts>(data: &Document, period: Option<Span>, concepts: &[&str]) -> T {
let problems = RefCell::new(Vec::new());
let scope = Scope {
data,
period,
problems: &problems,
};
T::from_facts(&scope, concepts, "field")
}
#[test]
fn reporting_period_is_the_required_context() {
let data = q3_document(Vec::new(), Vec::new());
assert_eq!(
data.reporting_period(),
Some(&Span::duration("2024-01-01", "2024-09-30"))
);
}
#[test]
fn period_match_classification() {
let report = Span::duration("2025-01-01", "2025-03-31");
let class = |span: Span| PeriodMatch::of(Some(&span), Some(&report));
assert_eq!(
class(Span::instant("2025-03-31")),
PeriodMatch::RequiredContext
);
assert_eq!(
class(Span::instant("2024-12-31")),
PeriodMatch::BeforeReport
);
assert_eq!(class(Span::instant("2025-05-12")), PeriodMatch::AfterReport);
assert_eq!(
class(Span::duration("2025-02-01", "2025-03-31")),
PeriodMatch::EndsOnReportDate
);
assert_eq!(PeriodMatch::of(None, Some(&report)), PeriodMatch::Unknown);
}
#[test]
fn balance_sheet_date_beats_prior_year_end_and_cover_page() {
let data = q3_document(
vec![
fact("us-gaap:Assets", "cover", "3"),
fact("us-gaap:Assets", "now", "1"),
fact("us-gaap:Assets", "year_end", "2"),
],
Vec::new(),
);
assert_eq!(
one::<Option<f64>>(&data, None, &["us-gaap:Assets"]),
Some(1.0)
);
}
#[test]
fn required_context_beats_shorter_span_with_same_end() {
let data = q3_document(
vec![
fact("us-gaap:OperatingExpenses", "ytd", "900"),
fact("us-gaap:OperatingExpenses", "q3", "300"),
],
Vec::new(),
);
assert_eq!(
one::<Option<f64>>(&data, None, &["us-gaap:OperatingExpenses"]),
Some(900.0)
);
}
#[test]
fn consolidated_beats_dimensional_within_same_period() {
let class_a = with_member(
instant("now_a", "2024-09-30"),
"us-gaap:StatementClassOfStockAxis",
"us-gaap:CommonClassAMember",
);
let data = q3_document(
vec![
fact("us-gaap:StockholdersEquity", "now", "10"),
fact("us-gaap:StockholdersEquity", "now_a", "4"),
],
vec![class_a],
);
assert_eq!(
one::<Option<f64>>(&data, None, &["us-gaap:StockholdersEquity"]),
Some(10.0)
);
}
#[test]
fn the_exact_figure_beats_its_rounded_restatement() {
let stated = |value: &str, decimals: &str| RawFact {
decimals: Some(decimals.to_string()),
..fact("us-gaap:AssetsHeldInTrustNoncurrent", "now", value)
};
let data = q3_document(
vec![stated("276012327", "0"), stated("276000000", "-5")],
Vec::new(),
);
let concepts = ["us-gaap:AssetsHeldInTrustNoncurrent"];
assert_eq!(
one::<Option<f64>>(&data, None, &concepts),
Some(276012327.0)
);
assert_eq!(
one::<Option<f64>>(&data, Some(Span::instant("2024-09-30")), &concepts),
Some(276012327.0)
);
assert_eq!(one::<Vec<Fact<f64>>>(&data, None, &concepts).len(), 1);
}
#[test]
fn precision_does_not_choose_between_contexts() {
let class = |id: &str, member: &str| {
with_member(
instant(id, "2024-09-30"),
"us-gaap:StatementClassOfStockAxis",
member,
)
};
let stated = |context: &str, value: &str, decimals: &str| RawFact {
decimals: Some(decimals.to_string()),
..fact("us-gaap:CommonStockSharesOutstanding", context, value)
};
let data = q3_document(
vec![stated("a", "0", "INF"), stated("b", "7906250", "0")],
vec![
class("a", "us-gaap:CommonClassAMember"),
class("b", "us-gaap:CommonClassBMember"),
],
);
assert_eq!(
one::<Option<f64>>(&data, None, &["us-gaap:CommonStockSharesOutstanding"]),
Some(7906250.0)
);
}
#[test]
fn without_a_reporting_period_the_most_recent_wins() {
let data = Document::new(Instance {
contexts: vec![instant("old", "2023-03-31"), instant("new", "2024-03-31")],
units: Vec::new(),
facts: vec![
fact("us-gaap:Assets", "new", "2"),
fact("us-gaap:Assets", "old", "1"),
],
});
assert_eq!(
one::<Option<f64>>(&data, None, &["us-gaap:Assets"]),
Some(2.0)
);
}
#[test]
fn alias_is_a_fallback_in_the_order_written() {
let both = q3_document(
vec![
fact("us-gaap:AssetsHeldInTrust", "now", "2"),
fact("us-gaap:AssetsHeldInTrustNoncurrent", "now", "1"),
],
Vec::new(),
);
let concepts = [
"us-gaap:AssetsHeldInTrustNoncurrent",
"us-gaap:AssetsHeldInTrust",
];
assert_eq!(one::<Option<f64>>(&both, None, &concepts), Some(1.0));
let only_alias = q3_document(
vec![fact("us-gaap:AssetsHeldInTrust", "now", "2")],
Vec::new(),
);
assert_eq!(one::<Option<f64>>(&only_alias, None, &concepts), Some(2.0));
}
#[test]
fn an_alias_for_this_period_beats_the_concept_for_last_year() {
let data = q3_document(
vec![
fact("us-gaap:AssetsHeldInTrustNoncurrent", "year_end", "1"),
fact("us-gaap:AssetsHeldInTrust", "now", "2"),
],
Vec::new(),
);
let concepts = [
"us-gaap:AssetsHeldInTrustNoncurrent",
"us-gaap:AssetsHeldInTrust",
];
assert_eq!(one::<Option<f64>>(&data, None, &concepts), Some(2.0));
}
#[test]
fn a_pinned_scope_reads_only_its_own_period() {
let class_a = with_member(
duration("q3_a", "2024-07-01", "2024-09-30"),
"us-gaap:StatementClassOfStockAxis",
"us-gaap:CommonClassAMember",
);
let data = q3_document(
vec![
fact("us-gaap:OperatingExpenses", "ytd", "900"),
fact("us-gaap:OperatingExpenses", "q3", "300"),
fact("us-gaap:NetIncomeLoss", "ytd", "-50"),
fact("us-gaap:EarningsPerShareBasic", "q3_a", "0.02"),
],
vec![class_a],
);
let q3 = Some(Span::duration("2024-07-01", "2024-09-30"));
assert_eq!(
one::<Option<f64>>(&data, q3.clone(), &["us-gaap:OperatingExpenses"]),
Some(300.0)
);
assert_eq!(
one::<Option<f64>>(&data, q3.clone(), &["us-gaap:NetIncomeLoss"]),
None
);
assert_eq!(
one::<Option<f64>>(&data, q3, &["us-gaap:EarningsPerShareBasic"]),
None
);
}
#[test]
fn a_vec_of_facts_holds_every_period_and_member() {
let class_a = with_member(
instant("cover_a", "2024-11-12"),
"us-gaap:StatementClassOfStockAxis",
"us-gaap:CommonClassAMember",
);
let class_b = with_member(
instant("cover_b", "2024-11-12"),
"us-gaap:StatementClassOfStockAxis",
"us-gaap:CommonClassBMember",
);
let concept = "dei:EntityCommonStockSharesOutstanding";
let data = q3_document(
vec![
fact(concept, "cover_a", "23000000"),
fact(concept, "cover_b", "5750000"),
fact(concept, "cover_b", "5750000"),
],
vec![class_a, class_b],
);
let by_class = one::<Vec<Fact<f64>>>(&data, None, &[concept]);
let seen: Vec<(f64, &str)> = by_class
.iter()
.map(|f| (f.value, f.dimensions[0].member.as_str()))
.collect();
assert_eq!(
seen,
vec![
(23000000.0, "us-gaap:CommonClassAMember"),
(5750000.0, "us-gaap:CommonClassBMember"),
]
);
assert_eq!(by_class[0].period_end.as_deref(), Some("2024-11-12"));
assert_eq!(by_class[0].period_start, None);
}
#[test]
fn a_value_that_does_not_convert_is_reported_and_left_empty() {
let data = q3_document(
vec![
fact("us-gaap:Assets", "now", "N/A"),
fact("us-gaap:Liabilities", "now", "1,250"),
],
Vec::new(),
);
let problems = RefCell::new(Vec::new());
let scope = Scope {
data: &data,
period: None,
problems: &problems,
};
assert_eq!(
<Option<f64>>::from_facts(&scope, &["us-gaap:Assets"], "assets"),
None
);
assert_eq!(
<Option<f64>>::from_facts(&scope, &["us-gaap:Liabilities"], "liabilities"),
Some(1250.0)
);
let problems = problems.into_inner();
assert_eq!(problems.len(), 1);
assert!(
problems[0]
.to_string()
.contains("`assets` (us-gaap:Assets)")
);
}
#[test]
fn integers_accept_a_whole_number_however_it_is_written() {
assert_eq!(i64::from_fact_value("6,900,000"), Some(6_900_000));
assert_eq!(i32::from_fact_value("1.0"), Some(1));
assert_eq!(i32::from_fact_value("1.5"), None);
assert_eq!(bool::from_fact_value("Yes"), Some(true));
assert_eq!(bool::from_fact_value("maybe"), None);
}
}