use std::sync::Arc;
use crossfoot_core::datetime::XDateTime;
use crossfoot_core::xml::{resolve_uri, Node};
use crossfoot_core::{
ns, Atom, ConceptKind, Context, Decimals, Diagnostic, DimContainer, DimValue, Document, Dts,
Fact, FactId, FactKind, Footnote, FootnoteRel, FootnoteTarget, Frag, Instance, InstanceSource,
Period, QName, Unit,
};
fn frag(doc: u32, n: Node<'_>) -> Frag {
Frag { doc, node: n.id }
}
pub fn parse_context(n: Node<'_>, doc: u32) -> Result<Context, Diagnostic> {
let id = Atom::from(n.att("id").unwrap_or("").trim());
let entity = n.first_element_named(ns::XBRLI, "entity").ok_or_else(|| {
Diagnostic::error("xbrl.4.7.3:entity", format!("context {} has no entity", id)).at(n)
})?;
let ident = entity
.first_element_named(ns::XBRLI, "identifier")
.ok_or_else(|| {
Diagnostic::error(
"xbrl.4.7.3.1:identifier",
format!("context {} has no identifier", id),
)
.at(entity)
})?;
let scheme = Atom::from(ident.att("scheme").unwrap_or("").trim());
let entity_id = Atom::from(ident.string_value().trim());
let segment = entity.first_element_named(ns::XBRLI, "segment");
let period_el = n.first_element_named(ns::XBRLI, "period").ok_or_else(|| {
Diagnostic::error("xbrl.4.7.2:period", format!("context {} has no period", id)).at(n)
})?;
let period = parse_period(period_el).ok_or_else(|| {
Diagnostic::error(
"xbrl.4.7.2:periodValue",
format!("context {} has an invalid period", id),
)
.at(period_el)
})?;
let scenario = n.first_element_named(ns::XBRLI, "scenario");
let mut dims = Vec::new();
for (container, el) in [
(DimContainer::Segment, segment),
(DimContainer::Scenario, scenario),
] {
let Some(el) = el else { continue };
for m in el.elements() {
if m.ns() != ns::XBRLDI {
continue;
}
let Some(dim) = m.att("dimension").and_then(|d| m.resolve_qname(d, false)) else {
continue;
};
match m.local() {
"explicitMember" => {
if let Some(mem) = m.resolve_qname(&m.string_value(), true) {
dims.push(DimValue::Explicit {
dimension: dim,
member: mem,
container,
});
}
}
"typedMember" => {
let canonical = m
.elements()
.next()
.map(|c| c.string_value().trim().to_string())
.unwrap_or_default();
dims.push(DimValue::Typed {
dimension: dim,
value: frag(doc, m),
canonical,
container,
});
}
_ => {}
}
}
}
Ok(Context {
id,
entity_scheme: scheme,
entity_id,
period,
segment: segment.map(|s| frag(doc, s)),
scenario: scenario.map(|s| frag(doc, s)),
dims,
node: Some(frag(doc, n)),
})
}
fn parse_period(p: Node<'_>) -> Option<Period> {
if p.first_element_named(ns::XBRLI, "forever").is_some() {
return Some(Period::Forever);
}
if let Some(i) = p.first_element_named(ns::XBRLI, "instant") {
return XDateTime::parse(&i.string_value(), true).map(Period::Instant);
}
let s = p.first_element_named(ns::XBRLI, "startDate")?;
let e = p.first_element_named(ns::XBRLI, "endDate")?;
Some(Period::Duration {
start: XDateTime::parse(&s.string_value(), false)?,
end: XDateTime::parse(&e.string_value(), true)?,
})
}
pub fn parse_unit(n: Node<'_>, doc: u32) -> Result<Unit, Diagnostic> {
let id = Atom::from(n.att("id").unwrap_or("").trim());
let measures = |el: Node<'_>| -> Vec<QName> {
let mut v: Vec<QName> = el
.elements_named(ns::XBRLI, "measure")
.filter_map(|m| m.resolve_qname(&m.string_value(), true))
.collect();
v.sort();
v
};
let (numerator, denominator) = match n.first_element_named(ns::XBRLI, "divide") {
Some(d) => {
let num = d
.first_element_named(ns::XBRLI, "unitNumerator")
.map(measures)
.unwrap_or_default();
let den = d
.first_element_named(ns::XBRLI, "unitDenominator")
.map(measures)
.unwrap_or_default();
(num, den)
}
None => (measures(n), Vec::new()),
};
Ok(Unit {
id,
numerator,
denominator,
node: Some(frag(doc, n)),
})
}
pub(crate) fn parse_decimals(v: Option<&str>) -> Option<Decimals> {
let v = v?.trim();
if v == "INF" {
Some(Decimals::Inf)
} else {
v.parse().ok().map(Decimals::N)
}
}
fn is_nil(n: Node<'_>) -> bool {
matches!(
n.attr(ns::XSI, "nil").map(|v| v.trim()),
Some("true") | Some("1")
)
}
type DefaultCache = std::collections::HashMap<QName, (Option<Decimals>, Option<Decimals>)>;
fn type_accuracy_defaults(
dts: &Dts,
ty: &QName,
cache: &mut DefaultCache,
) -> (Option<Decimals>, Option<Decimals>) {
if let Some(v) = cache.get(ty) {
return *v;
}
let get = |a: &str| {
crossfoot_dts::schema_util::attribute_info(dts, ty, &QName::new("", a))
.and_then(|i| i.fixed.or(i.default))
.and_then(|v| parse_decimals(Some(&v)))
};
let v = (get("decimals"), get("precision"));
cache.insert(ty.clone(), v);
v
}
fn load_fact(
inst: &mut Instance,
dts: &Dts,
n: Node<'_>,
parent: Option<FactId>,
_diags: &mut Vec<Diagnostic>,
cache: &mut DefaultCache,
) -> FactId {
let concept = n.name().clone();
let c = dts.concept(&concept);
let kind = match c.map(|c| c.kind) {
Some(ConceptKind::Tuple) => FactKind::Tuple,
Some(_) => FactKind::Item,
None => {
if n.att("contextRef").is_some() {
FactKind::Item
} else {
FactKind::Tuple
}
}
};
let id = FactId(inst.facts.len() as u32);
let nil = is_nil(n);
let (value, fraction) = if kind == FactKind::Item && !nil {
if c.map(|c| c.is_fraction).unwrap_or(false) {
let num = n
.first_element_named(ns::XBRLI, "numerator")
.map(|x| x.string_value().trim().to_string())
.unwrap_or_default();
let den = n
.first_element_named(ns::XBRLI, "denominator")
.map(|x| x.string_value().trim().to_string())
.unwrap_or_default();
(Some(format!("{}/{}", num, den)), Some((num, den)))
} else if n.elements().next().is_some() {
let mut s = String::new();
for ch in n.children() {
if ch.is_text() {
crossfoot_core::xml::escape_text(ch.text().unwrap_or(""), &mut s);
} else if ch.is_element() {
s.push_str(&ch.to_xml());
}
}
(Some(s), None)
} else {
let mut v = n.string_value();
if v.is_empty() {
if let Some(dv) = dts
.schemas
.element(&concept)
.and_then(|d| d.default.as_ref().or(d.fixed.as_ref()))
{
v = dv.to_string();
}
}
(Some(v), None)
}
} else {
(None, None)
};
let mut decimals = parse_decimals(n.att("decimals"));
let mut precision = parse_decimals(n.att("precision"));
if kind == FactKind::Item && !nil && n.att("decimals").is_none() && n.att("precision").is_none()
{
if let Some(c) = c.filter(|c| c.is_numeric && !c.is_fraction) {
if let Some(t) = &c.type_name {
let (d, p) = type_accuracy_defaults(dts, t, cache);
decimals = d;
precision = p;
}
}
}
inst.facts.push(Fact {
id: n.attr_atom("", "id").cloned(),
concept,
kind,
context: n.attr_atom("", "contextRef").map(|s| Atom::from(s.trim())),
unit: n.attr_atom("", "unitRef").map(|s| Atom::from(s.trim())),
value,
is_nil: nil,
decimals,
precision,
lang: n.lang().map(Atom::from),
parent,
children: Vec::new(),
node: Some(frag(0, n)),
inline: None,
fraction,
});
if kind == FactKind::Tuple {
let mut kids = Vec::new();
for ch in n.elements() {
kids.push(load_fact(inst, dts, ch, Some(id), _diags, cache));
}
inst.facts[id.0 as usize].children = kids;
}
id
}
pub fn load_instance(doc: Arc<Document>, dts: &Dts) -> (Instance, Vec<Diagnostic>) {
let mut diags = Vec::new();
let mut inst = Instance::new(&doc.uri, InstanceSource::Xml);
inst.docs.push(doc.clone());
let Some(root) = doc.document_element() else {
return (inst, diags);
};
if !root.is(ns::XBRLI, "xbrl") {
diags.push(
Diagnostic::error("xbrl.4.1:root", "document element is not xbrli:xbrl").at(root),
);
return (inst, diags);
}
let mut footnote_links = Vec::new();
let mut cache = DefaultCache::new();
for n in root.elements() {
match (n.ns(), n.local()) {
(ns::LINK, "schemaRef") => {
if let Some(h) = n.attr(ns::XLINK, "href") {
inst.schema_refs
.push(Atom::from(resolve_uri(&n.base_uri(), h).as_str()));
}
}
(ns::LINK, "linkbaseRef") => {
if let Some(h) = n.attr(ns::XLINK, "href") {
inst.linkbase_refs
.push(Atom::from(resolve_uri(&n.base_uri(), h).as_str()));
}
}
(ns::LINK, "roleRef") => {
inst.role_refs.push((
Atom::from(n.att("roleURI").unwrap_or("")),
Atom::from(n.attr(ns::XLINK, "href").unwrap_or("")),
));
}
(ns::LINK, "arcroleRef") => {
inst.arcrole_refs.push((
Atom::from(n.att("arcroleURI").unwrap_or("")),
Atom::from(n.attr(ns::XLINK, "href").unwrap_or("")),
));
}
(ns::XBRLI, "context") => match parse_context(n, 0) {
Ok(c) => {
if inst.contexts.contains_key(&c.id) {
diags.push(
Diagnostic::error(
"xmlSchema:duplicateId",
format!("duplicate context id {}", c.id),
)
.at(n),
);
} else {
inst.contexts.insert(c.id.clone(), c);
}
}
Err(d) => diags.push(d),
},
(ns::XBRLI, "unit") => match parse_unit(n, 0) {
Ok(u) => {
inst.units.insert(u.id.clone(), u);
}
Err(d) => diags.push(d),
},
(ns::LINK, "footnoteLink") => footnote_links.push(n),
_ => {
let id = load_fact(&mut inst, dts, n, None, &mut diags, &mut cache);
inst.top_level.push(id);
}
}
}
for link in footnote_links {
let link_role = Atom::from(link.attr(ns::XLINK, "role").unwrap_or(""));
let mut labels: std::collections::HashMap<&str, Vec<FootnoteTarget>> =
std::collections::HashMap::new();
for c in link.elements() {
match c.attr(ns::XLINK, "type") {
Some("locator") => {
let (Some(l), Some(h)) =
(c.attr(ns::XLINK, "label"), c.attr(ns::XLINK, "href"))
else {
continue;
};
let frag_id = h.split('#').nth(1).unwrap_or("");
if let Some(fid) = inst
.facts
.iter()
.position(|f| f.id.as_deref() == Some(frag_id))
{
labels
.entry(l)
.or_default()
.push(FootnoteTarget::Fact(FactId(fid as u32)));
}
}
Some("resource") => {
let Some(l) = c.attr(ns::XLINK, "label") else {
continue;
};
let mut content = String::new();
for ch in c.children() {
if ch.is_text() {
crossfoot_core::xml::escape_text(ch.text().unwrap_or(""), &mut content);
} else if ch.is_element() {
content.push_str(&ch.to_xml());
}
}
let idx = inst.footnotes.len();
inst.footnotes.push(Footnote {
id: c.attr_atom("", "id").cloned(),
role: c.attr_atom(ns::XLINK, "role").cloned(),
lang: c.lang().map(Atom::from),
content,
node: Some(frag(0, c)),
});
labels
.entry(l)
.or_default()
.push(FootnoteTarget::Footnote(idx));
}
_ => {}
}
}
for arc in link.elements() {
if arc.attr(ns::XLINK, "type") != Some("arc") {
continue;
}
let arcrole = Atom::from(arc.attr(ns::XLINK, "arcrole").unwrap_or(""));
let (Some(f), Some(t)) = (arc.attr(ns::XLINK, "from"), arc.attr(ns::XLINK, "to"))
else {
continue;
};
let froms: Vec<FactId> = labels
.get(f)
.map(|v| {
v.iter()
.filter_map(|x| {
if let FootnoteTarget::Fact(id) = x {
Some(*id)
} else {
None
}
})
.collect()
})
.unwrap_or_default();
if let Some(tos) = labels.get(t) {
for from in &froms {
for to in tos {
inst.footnote_rels.push(FootnoteRel {
arcrole: arcrole.clone(),
link_role: link_role.clone(),
from: *from,
to: to.clone(),
});
}
}
}
}
}
(inst, diags)
}