Skip to main content

crossfoot_instance/
equal.rs

1//! XBRL 2.1 §4.10 equality predicates: s-equal contexts (with typed segment / scenario
2//! content), u-equal units, v-equal values. Contexts and units reduce to comparable keys.
3
4use crossfoot_core::xml::Node;
5use crossfoot_core::{ns, Context, Dts, Fact, Instance, Period, QName, Unit};
6
7use crossfoot_dts::schema_util::{attribute_info, type_attributes, value_key};
8
9/// Typed s-equality key of an element subtree (segment / scenario content). `None` when a
10/// NaN value makes the content unequal to everything, itself included.
11pub fn element_key(dts: &Dts, n: Node<'_>, out: &mut String) -> Option<()> {
12    out.push('<');
13    out.push_str(&n.name().clark());
14    let decl = dts.schemas.element(n.name());
15    let ty = decl.and_then(|d| d.type_name.clone());
16    let mut attrs: Vec<(String, String)> = Vec::new();
17    for a in n.attributes() {
18        let an = &a.name;
19        if &*an.ns == ns::XSI
20            && matches!(&*an.local, "schemaLocation" | "noNamespaceSchemaLocation")
21        {
22            continue;
23        }
24        let aq = QName::new(&an.ns, &an.local);
25        let at = ty
26            .as_ref()
27            .and_then(|t| attribute_info(dts, t, &aq))
28            .and_then(|i| i.type_name)
29            .or_else(|| {
30                if an.ns.is_empty() {
31                    None
32                } else {
33                    dts.schemas.attribute(&aq).and_then(|g| g.type_name.clone())
34                }
35            });
36        let v = match at.and_then(|t| dts.schemas.validate_simple(&t, &a.value, Some(n)).ok()) {
37            Some(val) => value_key(&val)?,
38            None => format!("s:{}", a.value.trim()),
39        };
40        attrs.push((aq.clark(), v));
41    }
42    // PSVI: declared default / fixed attributes that are absent
43    if let Some(t) = ty.as_ref() {
44        for (aq, info) in type_attributes(dts, t) {
45            let Some(dv) = info.default.as_ref().or(info.fixed.as_ref()) else {
46                continue;
47            };
48            let k = aq.clark();
49            if attrs.iter().any(|(x, _)| *x == k) {
50                continue;
51            }
52            let v = match info
53                .type_name
54                .as_ref()
55                .and_then(|at| dts.schemas.validate_simple(at, dv, Some(n)).ok())
56            {
57                Some(val) => value_key(&val)?,
58                None => format!("s:{}", dv.trim()),
59            };
60            attrs.push((k, v));
61        }
62    }
63    attrs.sort();
64    for (k, v) in attrs {
65        out.push(' ');
66        out.push_str(&k);
67        out.push('=');
68        out.push_str(&v);
69    }
70    out.push('>');
71    let kids: Vec<Node<'_>> = n.elements().collect();
72    if kids.is_empty() {
73        let mut text = n.string_value();
74        if text.is_empty() {
75            // PSVI: an empty element takes its declared default / fixed value
76            if let Some(dv) = decl.and_then(|d| d.default.as_ref().or(d.fixed.as_ref())) {
77                text = dv.to_string();
78            }
79        }
80        let v = match ty
81            .as_ref()
82            .and_then(|t| dts.schemas.validate_simple(t, &text, Some(n)).ok())
83        {
84            Some(val) => value_key(&val)?,
85            None => format!("s:{}", text.trim()),
86        };
87        out.push_str(&v);
88    } else {
89        for k in kids {
90            element_key(dts, k, out)?;
91        }
92    }
93    out.push_str("</>");
94    Some(())
95}
96
97fn period_key(p: &Period) -> String {
98    match p {
99        Period::Instant(i) => format!("i{}", i.canonical()),
100        Period::Duration { start, end } => format!("d{}/{}", start.canonical(), end.canonical()),
101        Period::Forever => "f".into(),
102    }
103}
104
105/// A key equal for s-equal contexts (§4.10, non-dimensional: segment and scenario content
106/// compared as XML with typed values, in order).
107pub fn context_key(dts: &Dts, inst: &Instance, c: &Context) -> String {
108    let mut k = String::new();
109    k.push_str(c.entity_scheme.trim());
110    k.push('|');
111    k.push_str(&c.entity_id.split_whitespace().collect::<Vec<_>>().join(" "));
112    k.push('|');
113    k.push_str(&period_key(&c.period));
114    let mut nan = false;
115    for (tag, part) in [("|S", c.segment), ("|C", c.scenario)] {
116        k.push_str(tag);
117        if let Some(f) = part {
118            if (f.doc as usize) < inst.docs.len() {
119                let n = inst.node(f);
120                for ch in n.elements() {
121                    if element_key(dts, ch, &mut k).is_none() {
122                        nan = true;
123                    }
124                }
125            }
126        }
127    }
128    if nan {
129        k.push_str("|#nan#");
130        k.push_str(&c.id);
131    }
132    k
133}
134
135/// u-equal key of a unit.
136pub fn unit_key(u: &Unit) -> String {
137    u.key()
138}
139
140/// The typed value of a fact for v-equality (or its trimmed text when untyped).
141pub fn fact_value_key(dts: &Dts, inst: &Instance, f: &Fact) -> Option<String> {
142    let v = f.value.as_deref()?;
143    let c = dts.concept(&f.concept)?;
144    if let Some(t) = &c.type_name {
145        let node = f
146            .node
147            .filter(|fr| (fr.doc as usize) < inst.docs.len())
148            .map(|fr| inst.node(fr));
149        if let Ok(val) = dts.schemas.validate_simple(t, v, node) {
150            return value_key(&val);
151        }
152    }
153    Some(format!("s:{}", v.trim()))
154}