Skip to main content

crossfoot_instance/
enumerations.rs

1//! Extensible Enumerations 1.0 (2014): taxonomy constraints on `enum:enumerationItemType`
2//! concepts (`enumte:*`) and fact values that must be usable members of the concept's domain
3//! (`enumie:InvalidFactValue`). Owned by the versioning/taxonomy workstream (enumeration checks
4//! only).
5
6use std::collections::HashSet;
7
8use crossfoot_core::{
9    arcrole, ns, Concept, ConceptKind, Diagnostic, Dts, Endpoint, FactKind, Instance, QName,
10};
11
12pub const ENUM_2014: &str = "http://xbrl.org/2014/extensible-enumerations";
13
14/// The enumeration attributes of a concept whose type derives from `enum:enumerationItemType`
15/// (directly, by restriction, or through its substitution group head's type).
16fn is_enum_concept(dts: &Dts, c: &Concept) -> bool {
17    let target = QName::new(ENUM_2014, "enumerationItemType");
18    let mut cur = Some(c);
19    let mut guard = 0;
20    while let Some(k) = cur {
21        if let Some(t) = &k.type_name {
22            return *t == target || dts.schemas.derives_from(t, &target);
23        }
24        guard += 1;
25        if guard > 16 {
26            return false;
27        }
28        cur = k
29            .substitution_group
30            .as_ref()
31            .and_then(|h| dts.concepts.get(h));
32    }
33    false
34}
35
36fn enum_attr<'a>(c: &'a Concept, local: &str) -> Option<&'a str> {
37    c.attrs
38        .iter()
39        .find(|(q, _)| q.is(ENUM_2014, local))
40        .map(|(_, v)| v.trim())
41}
42
43fn domain_of(dts: &Dts, c: &Concept) -> Option<QName> {
44    let v = enum_attr(c, "domain")?;
45    dts.concept_node(c).resolve_qname(v, true)
46}
47
48/// Taxonomy checks (`enumte:MissingDomainError`, `InvalidDomainError`, `MissingLinkRoleError`).
49pub fn validate_dts(dts: &Dts) -> Vec<Diagnostic> {
50    let mut out = Vec::new();
51    for c in dts.concepts.values() {
52        if c.kind != ConceptKind::Item || !is_enum_concept(dts, c) {
53            continue;
54        }
55        let node = dts.concept_node(c);
56        match enum_attr(c, "domain") {
57            None => out.push(
58                Diagnostic::error(
59                    "enumte:MissingDomainError",
60                    format!("enumeration concept {} has no enum:domain", c.qname.clark()),
61                )
62                .at(node),
63            ),
64            Some(_) => {
65                let ok = domain_of(dts, c)
66                    .and_then(|q| dts.concepts.get(&q))
67                    .map(|d| d.kind == ConceptKind::Item)
68                    .unwrap_or(false);
69                if !ok {
70                    out.push(
71                        Diagnostic::error(
72                            "enumte:InvalidDomainError",
73                            format!(
74                                "enum:domain of {} is not a domain member item (dimension, hypercube, tuple or undefined)",
75                                c.qname.clark()
76                            ),
77                        )
78                        .at(node),
79                    );
80                }
81            }
82        }
83        if enum_attr(c, "linkrole").is_none() {
84            out.push(
85                Diagnostic::error(
86                    "enumte:MissingLinkRoleError",
87                    format!(
88                        "enumeration concept {} has no enum:linkrole",
89                        c.qname.clark()
90                    ),
91                )
92                .at(node),
93            );
94        }
95    }
96    out
97}
98
99/// Usable members of a domain: the head when `enum:headUsable` is true, then the
100/// domain-member descendants in the link role (consecutive relationships follow
101/// `xbrldt:targetRole`), except members whose relationship has `xbrldt:usable="false"`.
102pub fn usable_members(
103    dts: &Dts,
104    head: &QName,
105    linkrole: &str,
106    head_usable: bool,
107) -> HashSet<QName> {
108    let mut usable = HashSet::new();
109    let mut unusable = HashSet::new();
110    if head_usable {
111        usable.insert(head.clone());
112    } else {
113        unusable.insert(head.clone());
114    }
115    let mut stack: Vec<(QName, String)> = vec![(head.clone(), linkrole.to_string())];
116    let mut seen: HashSet<(QName, String)> = HashSet::new();
117    while let Some((q, lr)) = stack.pop() {
118        if !seen.insert((q.clone(), lr.clone())) {
119            continue;
120        }
121        let from = Endpoint::Concept(q);
122        for (id, r) in dts.from_rels(&from, arcrole::DOMAIN_MEMBER, Some(&lr)) {
123            let Endpoint::Concept(t) = &r.to else {
124                continue;
125            };
126            let arc = dts.arc_node(id);
127            if arc
128                .attr(ns::XBRLDT, "usable")
129                .map(|v| v.trim() == "false" || v.trim() == "0")
130                .unwrap_or(false)
131            {
132                unusable.insert(t.clone());
133            } else {
134                usable.insert(t.clone());
135            }
136            let next = arc
137                .attr(ns::XBRLDT, "targetRole")
138                .map(|s| s.trim().to_string())
139                .unwrap_or_else(|| lr.clone());
140            stack.push((t.clone(), next));
141        }
142    }
143    usable.retain(|q| !unusable.contains(q));
144    usable
145}
146
147/// Fact checks: the value of an enumeration fact must be a usable member of its domain.
148pub fn validate_facts(dts: &Dts, inst: &Instance) -> Vec<Diagnostic> {
149    let mut out = Vec::new();
150    let mut cache: std::collections::HashMap<QName, Option<HashSet<QName>>> = Default::default();
151    for f in &inst.facts {
152        if f.kind != FactKind::Item || f.is_nil {
153            continue;
154        }
155        let Some(c) = dts.concepts.get(&f.concept) else {
156            continue;
157        };
158        if !is_enum_concept(dts, c) {
159            continue;
160        }
161        let allowed = cache
162            .entry(c.qname.clone())
163            .or_insert_with(|| {
164                let head = domain_of(dts, c)?;
165                let lr = enum_attr(c, "linkrole")?;
166                let hu = matches!(enum_attr(c, "headUsable"), Some("true") | Some("1"));
167                Some(usable_members(dts, &head, lr, hu))
168            })
169            .clone();
170        let Some(allowed) = allowed else { continue };
171        let Some(v) = f.value.as_deref() else {
172            continue;
173        };
174        let value = match f.node {
175            Some(fr) => inst.node(fr).resolve_qname(v.trim(), true),
176            None => None,
177        };
178        let ok = value.map(|q| allowed.contains(&q)).unwrap_or(false);
179        if !ok {
180            let mut d = Diagnostic::error(
181                "enumie:InvalidFactValue",
182                format!(
183                    "value {} of {} is not a usable member of its enumeration domain",
184                    v.trim(),
185                    f.concept.clark()
186                ),
187            );
188            if let Some(fr) = f.node {
189                d = d.at(inst.node(fr));
190            }
191            out.push(d);
192        }
193    }
194    out
195}