Skip to main content

crossfoot_instance/
load.rs

1//! Loading an XBRL instance document into the shared model.
2
3use std::sync::Arc;
4
5use crossfoot_core::datetime::XDateTime;
6use crossfoot_core::xml::{resolve_uri, Node};
7use crossfoot_core::{
8    ns, Atom, ConceptKind, Context, Decimals, Diagnostic, DimContainer, DimValue, Document, Dts,
9    Fact, FactId, FactKind, Footnote, FootnoteRel, FootnoteTarget, Frag, Instance, InstanceSource,
10    Period, QName, Unit,
11};
12
13fn frag(doc: u32, n: Node<'_>) -> Frag {
14    Frag { doc, node: n.id }
15}
16
17/// Parse an `xbrli:context` element. `doc` is the index of its document in `Instance::docs`.
18pub fn parse_context(n: Node<'_>, doc: u32) -> Result<Context, Diagnostic> {
19    let id = Atom::from(n.att("id").unwrap_or("").trim());
20    let entity = n.first_element_named(ns::XBRLI, "entity").ok_or_else(|| {
21        Diagnostic::error("xbrl.4.7.3:entity", format!("context {} has no entity", id)).at(n)
22    })?;
23    let ident = entity
24        .first_element_named(ns::XBRLI, "identifier")
25        .ok_or_else(|| {
26            Diagnostic::error(
27                "xbrl.4.7.3.1:identifier",
28                format!("context {} has no identifier", id),
29            )
30            .at(entity)
31        })?;
32    let scheme = Atom::from(ident.att("scheme").unwrap_or("").trim());
33    let entity_id = Atom::from(ident.string_value().trim());
34    let segment = entity.first_element_named(ns::XBRLI, "segment");
35    let period_el = n.first_element_named(ns::XBRLI, "period").ok_or_else(|| {
36        Diagnostic::error("xbrl.4.7.2:period", format!("context {} has no period", id)).at(n)
37    })?;
38    let period = parse_period(period_el).ok_or_else(|| {
39        Diagnostic::error(
40            "xbrl.4.7.2:periodValue",
41            format!("context {} has an invalid period", id),
42        )
43        .at(period_el)
44    })?;
45    let scenario = n.first_element_named(ns::XBRLI, "scenario");
46    let mut dims = Vec::new();
47    for (container, el) in [
48        (DimContainer::Segment, segment),
49        (DimContainer::Scenario, scenario),
50    ] {
51        let Some(el) = el else { continue };
52        for m in el.elements() {
53            if m.ns() != ns::XBRLDI {
54                continue;
55            }
56            let Some(dim) = m.att("dimension").and_then(|d| m.resolve_qname(d, false)) else {
57                continue;
58            };
59            match m.local() {
60                "explicitMember" => {
61                    if let Some(mem) = m.resolve_qname(&m.string_value(), true) {
62                        dims.push(DimValue::Explicit {
63                            dimension: dim,
64                            member: mem,
65                            container,
66                        });
67                    }
68                }
69                "typedMember" => {
70                    let canonical = m
71                        .elements()
72                        .next()
73                        .map(|c| c.string_value().trim().to_string())
74                        .unwrap_or_default();
75                    dims.push(DimValue::Typed {
76                        dimension: dim,
77                        value: frag(doc, m),
78                        canonical,
79                        container,
80                    });
81                }
82                _ => {}
83            }
84        }
85    }
86    Ok(Context {
87        id,
88        entity_scheme: scheme,
89        entity_id,
90        period,
91        segment: segment.map(|s| frag(doc, s)),
92        scenario: scenario.map(|s| frag(doc, s)),
93        dims,
94        node: Some(frag(doc, n)),
95    })
96}
97
98fn parse_period(p: Node<'_>) -> Option<Period> {
99    if p.first_element_named(ns::XBRLI, "forever").is_some() {
100        return Some(Period::Forever);
101    }
102    if let Some(i) = p.first_element_named(ns::XBRLI, "instant") {
103        return XDateTime::parse(&i.string_value(), true).map(Period::Instant);
104    }
105    let s = p.first_element_named(ns::XBRLI, "startDate")?;
106    let e = p.first_element_named(ns::XBRLI, "endDate")?;
107    Some(Period::Duration {
108        start: XDateTime::parse(&s.string_value(), false)?,
109        end: XDateTime::parse(&e.string_value(), true)?,
110    })
111}
112
113/// Parse an `xbrli:unit` element.
114pub fn parse_unit(n: Node<'_>, doc: u32) -> Result<Unit, Diagnostic> {
115    let id = Atom::from(n.att("id").unwrap_or("").trim());
116    let measures = |el: Node<'_>| -> Vec<QName> {
117        let mut v: Vec<QName> = el
118            .elements_named(ns::XBRLI, "measure")
119            .filter_map(|m| m.resolve_qname(&m.string_value(), true))
120            .collect();
121        v.sort();
122        v
123    };
124    let (numerator, denominator) = match n.first_element_named(ns::XBRLI, "divide") {
125        Some(d) => {
126            let num = d
127                .first_element_named(ns::XBRLI, "unitNumerator")
128                .map(measures)
129                .unwrap_or_default();
130            let den = d
131                .first_element_named(ns::XBRLI, "unitDenominator")
132                .map(measures)
133                .unwrap_or_default();
134            (num, den)
135        }
136        None => (measures(n), Vec::new()),
137    };
138    Ok(Unit {
139        id,
140        numerator,
141        denominator,
142        node: Some(frag(doc, n)),
143    })
144}
145
146pub(crate) fn parse_decimals(v: Option<&str>) -> Option<Decimals> {
147    let v = v?.trim();
148    if v == "INF" {
149        Some(Decimals::Inf)
150    } else {
151        v.parse().ok().map(Decimals::N)
152    }
153}
154
155fn is_nil(n: Node<'_>) -> bool {
156    matches!(
157        n.attr(ns::XSI, "nil").map(|v| v.trim()),
158        Some("true") | Some("1")
159    )
160}
161
162type DefaultCache = std::collections::HashMap<QName, (Option<Decimals>, Option<Decimals>)>;
163
164/// decimals / precision defaulted or fixed by an item type (PSVI).
165fn type_accuracy_defaults(
166    dts: &Dts,
167    ty: &QName,
168    cache: &mut DefaultCache,
169) -> (Option<Decimals>, Option<Decimals>) {
170    if let Some(v) = cache.get(ty) {
171        return *v;
172    }
173    let get = |a: &str| {
174        crossfoot_dts::schema_util::attribute_info(dts, ty, &QName::new("", a))
175            .and_then(|i| i.fixed.or(i.default))
176            .and_then(|v| parse_decimals(Some(&v)))
177    };
178    let v = (get("decimals"), get("precision"));
179    cache.insert(ty.clone(), v);
180    v
181}
182
183fn load_fact(
184    inst: &mut Instance,
185    dts: &Dts,
186    n: Node<'_>,
187    parent: Option<FactId>,
188    _diags: &mut Vec<Diagnostic>,
189    cache: &mut DefaultCache,
190) -> FactId {
191    let concept = n.name().clone();
192    let c = dts.concept(&concept);
193    let kind = match c.map(|c| c.kind) {
194        Some(ConceptKind::Tuple) => FactKind::Tuple,
195        Some(_) => FactKind::Item,
196        None => {
197            // undeclared: guess from shape
198            if n.att("contextRef").is_some() {
199                FactKind::Item
200            } else {
201                FactKind::Tuple
202            }
203        }
204    };
205    let id = FactId(inst.facts.len() as u32);
206    let nil = is_nil(n);
207    let (value, fraction) = if kind == FactKind::Item && !nil {
208        if c.map(|c| c.is_fraction).unwrap_or(false) {
209            let num = n
210                .first_element_named(ns::XBRLI, "numerator")
211                .map(|x| x.string_value().trim().to_string())
212                .unwrap_or_default();
213            let den = n
214                .first_element_named(ns::XBRLI, "denominator")
215                .map(|x| x.string_value().trim().to_string())
216                .unwrap_or_default();
217            (Some(format!("{}/{}", num, den)), Some((num, den)))
218        } else if n.elements().next().is_some() {
219            // mixed content (e.g. XHTML in a text item) — keep serialized children
220            let mut s = String::new();
221            for ch in n.children() {
222                if ch.is_text() {
223                    crossfoot_core::xml::escape_text(ch.text().unwrap_or(""), &mut s);
224                } else if ch.is_element() {
225                    s.push_str(&ch.to_xml());
226                }
227            }
228            (Some(s), None)
229        } else {
230            let mut v = n.string_value();
231            if v.is_empty() {
232                // PSVI: an empty element takes its declared default / fixed value
233                if let Some(dv) = dts
234                    .schemas
235                    .element(&concept)
236                    .and_then(|d| d.default.as_ref().or(d.fixed.as_ref()))
237                {
238                    v = dv.to_string();
239                }
240            }
241            (Some(v), None)
242        }
243    } else {
244        (None, None)
245    };
246    let mut decimals = parse_decimals(n.att("decimals"));
247    let mut precision = parse_decimals(n.att("precision"));
248    if kind == FactKind::Item && !nil && n.att("decimals").is_none() && n.att("precision").is_none()
249    {
250        if let Some(c) = c.filter(|c| c.is_numeric && !c.is_fraction) {
251            if let Some(t) = &c.type_name {
252                let (d, p) = type_accuracy_defaults(dts, t, cache);
253                decimals = d;
254                precision = p;
255            }
256        }
257    }
258    inst.facts.push(Fact {
259        id: n.attr_atom("", "id").cloned(),
260        concept,
261        kind,
262        context: n.attr_atom("", "contextRef").map(|s| Atom::from(s.trim())),
263        unit: n.attr_atom("", "unitRef").map(|s| Atom::from(s.trim())),
264        value,
265        is_nil: nil,
266        decimals,
267        precision,
268        lang: n.lang().map(Atom::from),
269        parent,
270        children: Vec::new(),
271        node: Some(frag(0, n)),
272        inline: None,
273        fraction,
274    });
275    if kind == FactKind::Tuple {
276        let mut kids = Vec::new();
277        for ch in n.elements() {
278            kids.push(load_fact(inst, dts, ch, Some(id), _diags, cache));
279        }
280        inst.facts[id.0 as usize].children = kids;
281    }
282    id
283}
284
285/// Load an XBRL instance (the DTS must already be discovered from its references).
286pub fn load_instance(doc: Arc<Document>, dts: &Dts) -> (Instance, Vec<Diagnostic>) {
287    let mut diags = Vec::new();
288    let mut inst = Instance::new(&doc.uri, InstanceSource::Xml);
289    inst.docs.push(doc.clone());
290    let Some(root) = doc.document_element() else {
291        return (inst, diags);
292    };
293    if !root.is(ns::XBRLI, "xbrl") {
294        diags.push(
295            Diagnostic::error("xbrl.4.1:root", "document element is not xbrli:xbrl").at(root),
296        );
297        return (inst, diags);
298    }
299    let mut footnote_links = Vec::new();
300    let mut cache = DefaultCache::new();
301    for n in root.elements() {
302        match (n.ns(), n.local()) {
303            (ns::LINK, "schemaRef") => {
304                if let Some(h) = n.attr(ns::XLINK, "href") {
305                    inst.schema_refs
306                        .push(Atom::from(resolve_uri(&n.base_uri(), h).as_str()));
307                }
308            }
309            (ns::LINK, "linkbaseRef") => {
310                if let Some(h) = n.attr(ns::XLINK, "href") {
311                    inst.linkbase_refs
312                        .push(Atom::from(resolve_uri(&n.base_uri(), h).as_str()));
313                }
314            }
315            (ns::LINK, "roleRef") => {
316                inst.role_refs.push((
317                    Atom::from(n.att("roleURI").unwrap_or("")),
318                    Atom::from(n.attr(ns::XLINK, "href").unwrap_or("")),
319                ));
320            }
321            (ns::LINK, "arcroleRef") => {
322                inst.arcrole_refs.push((
323                    Atom::from(n.att("arcroleURI").unwrap_or("")),
324                    Atom::from(n.attr(ns::XLINK, "href").unwrap_or("")),
325                ));
326            }
327            (ns::XBRLI, "context") => match parse_context(n, 0) {
328                Ok(c) => {
329                    if inst.contexts.contains_key(&c.id) {
330                        diags.push(
331                            Diagnostic::error(
332                                "xmlSchema:duplicateId",
333                                format!("duplicate context id {}", c.id),
334                            )
335                            .at(n),
336                        );
337                    } else {
338                        inst.contexts.insert(c.id.clone(), c);
339                    }
340                }
341                Err(d) => diags.push(d),
342            },
343            (ns::XBRLI, "unit") => match parse_unit(n, 0) {
344                Ok(u) => {
345                    inst.units.insert(u.id.clone(), u);
346                }
347                Err(d) => diags.push(d),
348            },
349            (ns::LINK, "footnoteLink") => footnote_links.push(n),
350            _ => {
351                let id = load_fact(&mut inst, dts, n, None, &mut diags, &mut cache);
352                inst.top_level.push(id);
353            }
354        }
355    }
356    // footnote links
357    for link in footnote_links {
358        let link_role = Atom::from(link.attr(ns::XLINK, "role").unwrap_or(""));
359        let mut labels: std::collections::HashMap<&str, Vec<FootnoteTarget>> =
360            std::collections::HashMap::new();
361        for c in link.elements() {
362            match c.attr(ns::XLINK, "type") {
363                Some("locator") => {
364                    let (Some(l), Some(h)) =
365                        (c.attr(ns::XLINK, "label"), c.attr(ns::XLINK, "href"))
366                    else {
367                        continue;
368                    };
369                    let frag_id = h.split('#').nth(1).unwrap_or("");
370                    if let Some(fid) = inst
371                        .facts
372                        .iter()
373                        .position(|f| f.id.as_deref() == Some(frag_id))
374                    {
375                        labels
376                            .entry(l)
377                            .or_default()
378                            .push(FootnoteTarget::Fact(FactId(fid as u32)));
379                    }
380                }
381                Some("resource") => {
382                    let Some(l) = c.attr(ns::XLINK, "label") else {
383                        continue;
384                    };
385                    let mut content = String::new();
386                    for ch in c.children() {
387                        if ch.is_text() {
388                            crossfoot_core::xml::escape_text(ch.text().unwrap_or(""), &mut content);
389                        } else if ch.is_element() {
390                            content.push_str(&ch.to_xml());
391                        }
392                    }
393                    let idx = inst.footnotes.len();
394                    inst.footnotes.push(Footnote {
395                        id: c.attr_atom("", "id").cloned(),
396                        role: c.attr_atom(ns::XLINK, "role").cloned(),
397                        lang: c.lang().map(Atom::from),
398                        content,
399                        node: Some(frag(0, c)),
400                    });
401                    labels
402                        .entry(l)
403                        .or_default()
404                        .push(FootnoteTarget::Footnote(idx));
405                }
406                _ => {}
407            }
408        }
409        for arc in link.elements() {
410            if arc.attr(ns::XLINK, "type") != Some("arc") {
411                continue;
412            }
413            let arcrole = Atom::from(arc.attr(ns::XLINK, "arcrole").unwrap_or(""));
414            let (Some(f), Some(t)) = (arc.attr(ns::XLINK, "from"), arc.attr(ns::XLINK, "to"))
415            else {
416                continue;
417            };
418            let froms: Vec<FactId> = labels
419                .get(f)
420                .map(|v| {
421                    v.iter()
422                        .filter_map(|x| {
423                            if let FootnoteTarget::Fact(id) = x {
424                                Some(*id)
425                            } else {
426                                None
427                            }
428                        })
429                        .collect()
430                })
431                .unwrap_or_default();
432            if let Some(tos) = labels.get(t) {
433                for from in &froms {
434                    for to in tos {
435                        inst.footnote_rels.push(FootnoteRel {
436                            arcrole: arcrole.clone(),
437                            link_role: link_role.clone(),
438                            from: *from,
439                            to: to.clone(),
440                        });
441                    }
442                }
443            }
444        }
445    }
446    (inst, diags)
447}