crossfoot-instance 0.3.0

XBRL 2.1 instance loading and validation (Crossfoot)
Documentation
//! Extensible Enumerations 1.0 (2014): taxonomy constraints on `enum:enumerationItemType`
//! concepts (`enumte:*`) and fact values that must be usable members of the concept's domain
//! (`enumie:InvalidFactValue`). Owned by the versioning/taxonomy workstream (enumeration checks
//! only).

use std::collections::HashSet;

use crossfoot_core::{
    arcrole, ns, Concept, ConceptKind, Diagnostic, Dts, Endpoint, FactKind, Instance, QName,
};

pub const ENUM_2014: &str = "http://xbrl.org/2014/extensible-enumerations";

/// The enumeration attributes of a concept whose type derives from `enum:enumerationItemType`
/// (directly, by restriction, or through its substitution group head's type).
fn is_enum_concept(dts: &Dts, c: &Concept) -> bool {
    let target = QName::new(ENUM_2014, "enumerationItemType");
    let mut cur = Some(c);
    let mut guard = 0;
    while let Some(k) = cur {
        if let Some(t) = &k.type_name {
            return *t == target || dts.schemas.derives_from(t, &target);
        }
        guard += 1;
        if guard > 16 {
            return false;
        }
        cur = k
            .substitution_group
            .as_ref()
            .and_then(|h| dts.concepts.get(h));
    }
    false
}

fn enum_attr<'a>(c: &'a Concept, local: &str) -> Option<&'a str> {
    c.attrs
        .iter()
        .find(|(q, _)| q.is(ENUM_2014, local))
        .map(|(_, v)| v.trim())
}

fn domain_of(dts: &Dts, c: &Concept) -> Option<QName> {
    let v = enum_attr(c, "domain")?;
    dts.concept_node(c).resolve_qname(v, true)
}

/// Taxonomy checks (`enumte:MissingDomainError`, `InvalidDomainError`, `MissingLinkRoleError`).
pub fn validate_dts(dts: &Dts) -> Vec<Diagnostic> {
    let mut out = Vec::new();
    for c in dts.concepts.values() {
        if c.kind != ConceptKind::Item || !is_enum_concept(dts, c) {
            continue;
        }
        let node = dts.concept_node(c);
        match enum_attr(c, "domain") {
            None => out.push(
                Diagnostic::error(
                    "enumte:MissingDomainError",
                    format!("enumeration concept {} has no enum:domain", c.qname.clark()),
                )
                .at(node),
            ),
            Some(_) => {
                let ok = domain_of(dts, c)
                    .and_then(|q| dts.concepts.get(&q))
                    .map(|d| d.kind == ConceptKind::Item)
                    .unwrap_or(false);
                if !ok {
                    out.push(
                        Diagnostic::error(
                            "enumte:InvalidDomainError",
                            format!(
                                "enum:domain of {} is not a domain member item (dimension, hypercube, tuple or undefined)",
                                c.qname.clark()
                            ),
                        )
                        .at(node),
                    );
                }
            }
        }
        if enum_attr(c, "linkrole").is_none() {
            out.push(
                Diagnostic::error(
                    "enumte:MissingLinkRoleError",
                    format!(
                        "enumeration concept {} has no enum:linkrole",
                        c.qname.clark()
                    ),
                )
                .at(node),
            );
        }
    }
    out
}

/// Usable members of a domain: the head when `enum:headUsable` is true, then the
/// domain-member descendants in the link role (consecutive relationships follow
/// `xbrldt:targetRole`), except members whose relationship has `xbrldt:usable="false"`.
pub fn usable_members(
    dts: &Dts,
    head: &QName,
    linkrole: &str,
    head_usable: bool,
) -> HashSet<QName> {
    let mut usable = HashSet::new();
    let mut unusable = HashSet::new();
    if head_usable {
        usable.insert(head.clone());
    } else {
        unusable.insert(head.clone());
    }
    let mut stack: Vec<(QName, String)> = vec![(head.clone(), linkrole.to_string())];
    let mut seen: HashSet<(QName, String)> = HashSet::new();
    while let Some((q, lr)) = stack.pop() {
        if !seen.insert((q.clone(), lr.clone())) {
            continue;
        }
        let from = Endpoint::Concept(q);
        for (id, r) in dts.from_rels(&from, arcrole::DOMAIN_MEMBER, Some(&lr)) {
            let Endpoint::Concept(t) = &r.to else {
                continue;
            };
            let arc = dts.arc_node(id);
            if arc
                .attr(ns::XBRLDT, "usable")
                .map(|v| v.trim() == "false" || v.trim() == "0")
                .unwrap_or(false)
            {
                unusable.insert(t.clone());
            } else {
                usable.insert(t.clone());
            }
            let next = arc
                .attr(ns::XBRLDT, "targetRole")
                .map(|s| s.trim().to_string())
                .unwrap_or_else(|| lr.clone());
            stack.push((t.clone(), next));
        }
    }
    usable.retain(|q| !unusable.contains(q));
    usable
}

/// Fact checks: the value of an enumeration fact must be a usable member of its domain.
pub fn validate_facts(dts: &Dts, inst: &Instance) -> Vec<Diagnostic> {
    let mut out = Vec::new();
    let mut cache: std::collections::HashMap<QName, Option<HashSet<QName>>> = Default::default();
    for f in &inst.facts {
        if f.kind != FactKind::Item || f.is_nil {
            continue;
        }
        let Some(c) = dts.concepts.get(&f.concept) else {
            continue;
        };
        if !is_enum_concept(dts, c) {
            continue;
        }
        let allowed = cache
            .entry(c.qname.clone())
            .or_insert_with(|| {
                let head = domain_of(dts, c)?;
                let lr = enum_attr(c, "linkrole")?;
                let hu = matches!(enum_attr(c, "headUsable"), Some("true") | Some("1"));
                Some(usable_members(dts, &head, lr, hu))
            })
            .clone();
        let Some(allowed) = allowed else { continue };
        let Some(v) = f.value.as_deref() else {
            continue;
        };
        let value = match f.node {
            Some(fr) => inst.node(fr).resolve_qname(v.trim(), true),
            None => None,
        };
        let ok = value.map(|q| allowed.contains(&q)).unwrap_or(false);
        if !ok {
            let mut d = Diagnostic::error(
                "enumie:InvalidFactValue",
                format!(
                    "value {} of {} is not a usable member of its enumeration domain",
                    v.trim(),
                    f.concept.clark()
                ),
            );
            if let Some(fr) = f.node {
                d = d.at(inst.node(fr));
            }
            out.push(d);
        }
    }
    out
}