Skip to main content

crossfoot_instance/
validate.rs

1//! XBRL 2.1 instance validation (§4). Owned by the XBRL 2.1 workstream.
2
3use std::collections::{HashMap, HashSet};
4
5use crossfoot_core::xml::Node;
6use crossfoot_core::{
7    arcrole, ns, ConceptKind, Diagnostic, Dts, Endpoint, FactId, FactKind, Instance,
8    InstanceSource, Period, QName,
9};
10
11use crate::equal::{context_key, fact_value_key, unit_key};
12use crossfoot_dts::schema_util::attribute_info;
13
14fn at(d: Diagnostic, n: Option<Node<'_>>) -> Diagnostic {
15    match n {
16        Some(n) => d.at(n),
17        None => d,
18    }
19}
20
21fn is_decimals_lexical(v: &str) -> bool {
22    let v = v.trim();
23    if v == "INF" {
24        return true;
25    }
26    let b = v.strip_prefix(['-', '+']).unwrap_or(v);
27    !b.is_empty() && b.bytes().all(|c| c.is_ascii_digit())
28}
29
30fn is_precision_lexical(v: &str) -> bool {
31    let v = v.trim();
32    if v == "INF" {
33        return true;
34    }
35    let b = v.strip_prefix('+').unwrap_or(v);
36    !b.is_empty() && b.bytes().all(|c| c.is_ascii_digit())
37}
38
39/// Validate an instance against its DTS under XBRL 2.1 (contexts, units, item/tuple
40/// constraints, periodType, decimals/precision, footnotes, required elements...).
41pub fn validate(dts: &Dts, inst: &Instance) -> Vec<Diagnostic> {
42    let mut out = Vec::new();
43    let is_xml = matches!(inst.source, InstanceSource::Xml);
44    if is_xml {
45        if let Some(root) = inst.docs.first().and_then(|d| d.document_element()) {
46            if root.is(ns::XBRLI, "xbrl") {
47                check_root(dts, root, &mut out);
48            }
49        }
50    }
51    check_contexts(dts, inst, is_xml, &mut out);
52    check_units(inst, &mut out);
53    check_facts(dts, inst, is_xml, &mut out);
54    check_essence_alias(dts, inst, &mut out);
55    check_requires_element(dts, inst, &mut out);
56    check_explicit_member_values(inst, &mut out);
57    out
58}
59
60/// `xbrldi:explicitMember` content and `@dimension` are xs:QName: an empty or unresolvable
61/// value is a schema value error (checked for every context, used or not, as Arelle does).
62fn check_explicit_member_values(inst: &Instance, out: &mut Vec<Diagnostic>) {
63    let mut seen = std::collections::HashSet::new();
64    for ctx in inst.contexts.values() {
65        for fr in [ctx.segment, ctx.scenario].into_iter().flatten() {
66            if !seen.insert((fr.doc, fr.node)) {
67                continue;
68            }
69            let el = inst.node(fr);
70            for m in el.elements() {
71                if !m.is(ns::XBRLDI, "explicitMember") {
72                    continue;
73                }
74                let v = m.string_value();
75                if m.resolve_qname(v.trim(), true).is_none() {
76                    out.push(
77                        Diagnostic::error(
78                            "xmlSchema:valueError",
79                            format!("xbrldi:explicitMember value '{}' is not a valid QName (context {})", v.trim(), ctx.id),
80                        )
81                        .at(m),
82                    );
83                }
84            }
85        }
86    }
87}
88
89fn check_root(dts: &Dts, root: Node<'_>, out: &mut Vec<Diagnostic>) {
90    // §4.7 element order: schemaRef, linkbaseRef, roleRef, arcroleRef, then the rest
91    let mut order = 0;
92    let mut schema_refs = 0;
93    for n in root.elements() {
94        let seq = if n.ns() == ns::LINK {
95            match n.local() {
96                "schemaRef" => 1,
97                "linkbaseRef" => 2,
98                "roleRef" => 3,
99                "arcroleRef" => 4,
100                _ => 9,
101            }
102        } else {
103            9
104        };
105        if seq == 1 {
106            schema_refs += 1;
107        }
108        if seq < order {
109            out.push(
110                Diagnostic::error(
111                    "xbrl.4.7:instanceElementOrder",
112                    format!("element {} is out of order", n.name().lexical()),
113                )
114                .at(n),
115            );
116        } else {
117            order = seq;
118        }
119    }
120    if schema_refs == 0 {
121        out.push(
122            Diagnostic::error(
123                "xbrl.4.2:schemaRefMissing",
124                "instance has no link:schemaRef",
125            )
126            .at(root),
127        );
128    }
129    out.extend(crossfoot_dts::links::check_instance_links(dts, root));
130    // id uniqueness across the instance document
131    let mut seen: HashSet<&str> = HashSet::new();
132    for n in root.descendant_elements() {
133        for (code, msg) in crossfoot_dts::schema_util::lax_attribute_errors(dts, n) {
134            out.push(Diagnostic::error(&code, msg).at(n));
135        }
136        if n.ns() != ns::XBRLI
137            && n.ns() != ns::XBRLDI
138            && n.ancestors()
139                .any(|a| a.is(ns::XBRLI, "segment") || a.is(ns::XBRLI, "scenario"))
140        {
141            if let Some((code, msg)) = crossfoot_dts::schema_util::lax_element_error(dts, n) {
142                out.push(Diagnostic::error(&code, msg).at(n));
143            }
144        }
145        if let Some(id) = n.att("id") {
146            if !seen.insert(id.trim()) {
147                out.push(
148                    Diagnostic::error(
149                        "xmlSchema:duplicateId",
150                        format!("id {} is not unique in the instance", id),
151                    )
152                    .at(n),
153                );
154            }
155        }
156    }
157    // full schema validity of the instance (XML Schema stream)
158    for e in dts.schemas.validate_element(root, None) {
159        out.push(crate::xsd_diag(e));
160    }
161}
162
163fn check_segment_content(
164    dts: &Dts,
165    el: Node<'_>,
166    ctx_id: &str,
167    which: &str,
168    sect: &str,
169    out: &mut Vec<Diagnostic>,
170) {
171    let mut any = false;
172    for c in el.elements() {
173        any = true;
174        for n in std::iter::once(c).chain(c.descendant_elements()) {
175            if n.ns() == ns::XBRLI {
176                out.push(
177                    Diagnostic::error(
178                        &format!("xbrl.{}:{}XbrliElement", sect, which),
179                        format!(
180                            "context {} {} contains xbrli element {}",
181                            ctx_id,
182                            which,
183                            n.name().lexical()
184                        ),
185                    )
186                    .at(n),
187                );
188            } else if let Some(c) = dts.concept(n.name()) {
189                if matches!(
190                    c.kind,
191                    ConceptKind::Item
192                        | ConceptKind::Tuple
193                        | ConceptKind::Hypercube
194                        | ConceptKind::Dimension
195                ) {
196                    out.push(
197                        Diagnostic::error(
198                            &format!("xbrl.{}:{}ItemOrTuple", sect, which),
199                            format!(
200                                "context {} {} contains item or tuple {}",
201                                ctx_id,
202                                which,
203                                n.name().lexical()
204                            ),
205                        )
206                        .at(n),
207                    );
208                }
209            }
210        }
211    }
212    if !any {
213        out.push(
214            Diagnostic::error(
215                &format!("xbrl.{}:{}Empty", sect, which),
216                format!("context {} {} is empty", ctx_id, which),
217            )
218            .at(el),
219        );
220    }
221}
222
223fn check_contexts(dts: &Dts, inst: &Instance, _is_xml: bool, out: &mut Vec<Diagnostic>) {
224    for c in inst.contexts.values() {
225        let node = c
226            .node
227            .filter(|f| (f.doc as usize) < inst.docs.len())
228            .map(|f| inst.node(f));
229        if let Period::Duration { start, end } = &c.period {
230            if (start.secs, start.nanos) >= (end.secs, end.nanos) {
231                out.push(at(
232                    Diagnostic::error(
233                        "xbrl.4.7.2:periodStartBeforeEnd",
234                        format!("context {} startDate is not before endDate", c.id),
235                    ),
236                    node,
237                ));
238            }
239        }
240        if c.entity_scheme.trim().is_empty() {
241            out.push(at(
242                Diagnostic::error(
243                    "xbrl.4.7.3.1:identifierScheme",
244                    format!("context {} identifier has an empty scheme", c.id),
245                ),
246                node,
247            ));
248        }
249        if let Some(f) = c.segment {
250            if (f.doc as usize) < inst.docs.len() {
251                check_segment_content(dts, inst.node(f), &c.id, "segment", "4.7.3.2", out);
252            }
253        }
254        if let Some(f) = c.scenario {
255            if (f.doc as usize) < inst.docs.len() {
256                check_segment_content(dts, inst.node(f), &c.id, "scenario", "4.7.4", out);
257            }
258        }
259    }
260}
261
262fn check_units(inst: &Instance, out: &mut Vec<Diagnostic>) {
263    for u in inst.units.values() {
264        let node = u
265            .node
266            .filter(|f| (f.doc as usize) < inst.docs.len())
267            .map(|f| inst.node(f));
268        for m in u.numerator.iter().chain(u.denominator.iter()) {
269            if &*m.ns == ns::XBRLI && !matches!(&*m.local, "pure" | "shares") {
270                out.push(at(
271                    Diagnostic::error(
272                        "xbrl.4.8.2:measureElement",
273                        format!("unit {} has illegal measure {}", u.id, m.lexical()),
274                    ),
275                    node,
276                ));
277            }
278        }
279        for m in &u.numerator {
280            if u.denominator.contains(m) {
281                out.push(at(
282                    Diagnostic::error(
283                        "xbrl.4.8.4:measureBothNumDenom",
284                        format!(
285                            "unit {} measure {} is both numerator and denominator",
286                            u.id,
287                            m.lexical()
288                        ),
289                    ),
290                    node,
291                ));
292            }
293        }
294        if let Some(n) = node {
295            for m in n
296                .descendant_elements()
297                .filter(|m| m.is(ns::XBRLI, "measure"))
298            {
299                let txt = m.string_value();
300                if m.resolve_qname(&txt, true).is_none() {
301                    out.push(
302                        Diagnostic::error(
303                            "xmlSchema:valueError",
304                            format!("unit {} measure {} is not a valid QName", u.id, txt.trim()),
305                        )
306                        .at(m),
307                    );
308                }
309            }
310            if let Some(d) = n.first_element_named(ns::XBRLI, "divide") {
311                for part in ["unitNumerator", "unitDenominator"] {
312                    let has = d
313                        .first_element_named(ns::XBRLI, part)
314                        .map(|p| p.elements_named(ns::XBRLI, "measure").next().is_some())
315                        .unwrap_or(false);
316                    if !has {
317                        out.push(
318                            Diagnostic::error(
319                                "xmlSchema:elementMissing",
320                                format!("unit {} divide has no {} measure", u.id, part),
321                            )
322                            .at(d),
323                        );
324                    }
325                }
326            } else if u.numerator.is_empty()
327                && n.elements_named(ns::XBRLI, "measure").next().is_none()
328            {
329                out.push(
330                    Diagnostic::error(
331                        "xmlSchema:elementMissing",
332                        format!("unit {} has no measure", u.id),
333                    )
334                    .at(n),
335                );
336            }
337        }
338    }
339}
340
341fn is_iso4217_code(l: &str) -> bool {
342    l.len() == 3 && l.bytes().all(|b| b.is_ascii_uppercase())
343}
344
345fn check_facts(dts: &Dts, inst: &Instance, is_xml: bool, out: &mut Vec<Diagnostic>) {
346    let top: HashSet<FactId> = inst.top_level.iter().copied().collect();
347    let xbrl_attr_ns = [ns::XBRLI, ns::LINK, ns::XLINK, ns::XL];
348    for (i, f) in inst.facts.iter().enumerate() {
349        let id = FactId(i as u32);
350        let node = f
351            .node
352            .filter(|fr| (fr.doc as usize) < inst.docs.len())
353            .map(|fr| inst.node(fr));
354        let xml_node = if is_xml { node } else { None };
355        let name = f.concept.lexical();
356        let Some(c) = dts.concept(&f.concept) else {
357            out.push(at(
358                Diagnostic::error(
359                    "xbrl.4.6:undeclaredElement",
360                    format!("{} is not declared in the DTS", f.concept),
361                ),
362                node,
363            ));
364            continue;
365        };
366        if c.kind == ConceptKind::Other {
367            if top.contains(&id) || f.parent.is_some() {
368                out.push(at(
369                    Diagnostic::error(
370                        "xbrl.4.6:notItemOrTuple",
371                        format!("{} is not an item or tuple", name),
372                    ),
373                    node,
374                ));
375            }
376            continue;
377        }
378        if c.is_abstract {
379            out.push(at(
380                Diagnostic::error(
381                    "xmlSchema:abstractElement",
382                    format!("{} is abstract and cannot appear in an instance", name),
383                ),
384                node,
385            ));
386        }
387        if f.is_nil && !c.nillable {
388            out.push(at(
389                Diagnostic::error(
390                    "xmlSchema:nilNotAllowed",
391                    format!("{} is not nillable", name),
392                ),
393                node,
394            ));
395        }
396        // raw attributes (XML instance) or the parsed ones (inline)
397        let raw_dec = xml_node.and_then(|n| n.att("decimals"));
398        let raw_prec = xml_node.and_then(|n| n.att("precision"));
399        if let Some(d) = raw_dec {
400            if !is_decimals_lexical(d) {
401                out.push(at(
402                    Diagnostic::error(
403                        "xbrl.4.6.5:decimals",
404                        format!("fact {} decimals {} is invalid", name, d),
405                    ),
406                    node,
407                ));
408            }
409        }
410        if let Some(p) = raw_prec {
411            if !is_precision_lexical(p) {
412                out.push(at(
413                    Diagnostic::error(
414                        "xbrl.4.6.4:precision",
415                        format!("fact {} precision {} is invalid", name, p),
416                    ),
417                    node,
418                ));
419            }
420        }
421        match f.kind {
422            FactKind::Tuple => {
423                if let Some(n) = xml_node {
424                    if n.att("contextRef").is_some() {
425                        out.push(
426                            Diagnostic::error(
427                                "xbrl.4.6.1:tupleContextRef",
428                                format!("tuple {} must not have a contextRef", name),
429                            )
430                            .at(n),
431                        );
432                    }
433                    if n.att("unitRef").is_some() {
434                        out.push(
435                            Diagnostic::error(
436                                "xbrl.4.6.2:tupleUnitRef",
437                                format!("tuple {} must not have a unitRef", name),
438                            )
439                            .at(n),
440                        );
441                    }
442                    if raw_dec.is_some() || raw_prec.is_some() {
443                        out.push(
444                            Diagnostic::error(
445                                "xbrl.4.6.3:tuplePrecisionDecimals",
446                                format!("tuple {} must not have decimals or precision", name),
447                            )
448                            .at(n),
449                        );
450                    }
451                    for a in n.attributes() {
452                        if xbrl_attr_ns.contains(&&*a.name.ns) {
453                            out.push(
454                                Diagnostic::error(
455                                    "xbrl.4.9:tupleAttribute",
456                                    format!(
457                                        "tuple {} must not have attribute {}",
458                                        name,
459                                        a.name.lexical()
460                                    ),
461                                )
462                                .at(n),
463                            );
464                        }
465                    }
466                    if f.is_nil && n.elements().next().is_some() {
467                        out.push(
468                            Diagnostic::error(
469                                "xmlSchema:nilContent",
470                                format!("nil tuple {} has content", name),
471                            )
472                            .at(n),
473                        );
474                    }
475                }
476            }
477            FactKind::Item => {
478                // context
479                let ctx = match &f.context {
480                    None => {
481                        out.push(at(
482                            Diagnostic::error(
483                                "xbrl.4.6.1:itemContextRef",
484                                format!("item {} has no contextRef", name),
485                            ),
486                            node,
487                        ));
488                        None
489                    }
490                    Some(cr) => match inst.contexts.get(cr) {
491                        Some(ctx) => Some(ctx),
492                        None => {
493                            out.push(at(
494                                Diagnostic::error(
495                                    "xbrl.4.6.1:itemContextRef",
496                                    format!("item {} refers to missing context {}", name, cr),
497                                ),
498                                node,
499                            ));
500                            None
501                        }
502                    },
503                };
504                if let (Some(ctx), Some(pt)) = (ctx, c.period_type) {
505                    let ok = matches!(
506                        (pt, &ctx.period),
507                        (crossfoot_core::PeriodType::Instant, Period::Instant(_))
508                            | (
509                                crossfoot_core::PeriodType::Duration,
510                                Period::Duration { .. } | Period::Forever
511                            )
512                    );
513                    if !ok {
514                        out.push(at(
515                            Diagnostic::error(
516                                "xbrl.4.7.2:contextPeriodType",
517                                format!(
518                                    "item {} periodType conflicts with context {}",
519                                    name, ctx.id
520                                ),
521                            ),
522                            node,
523                        ));
524                    }
525                }
526                // unit
527                if c.is_numeric {
528                    match f.unit.as_ref().map(|u| (u, inst.units.get(u))) {
529                        None => out.push(at(
530                            Diagnostic::error(
531                                "xbrl.4.6.2:numericUnit",
532                                format!("numeric item {} has no unitRef", name),
533                            ),
534                            node,
535                        )),
536                        Some((u, None)) => out.push(at(
537                            Diagnostic::error(
538                                "xbrl.4.6.2:numericUnit",
539                                format!("numeric item {} refers to missing unit {}", name, u),
540                            ),
541                            node,
542                        )),
543                        Some((_, Some(unit))) => {
544                            if c.is_monetary {
545                                if unit.numerator.len() != 1 || !unit.denominator.is_empty() {
546                                    out.push(at(Diagnostic::error("xbrl.4.8.2:monetaryFactUnit-notSingleMeasure", format!("monetary item {} unit {} must be a single currency measure", name, unit.id)), node));
547                                } else if &*unit.numerator[0].ns != ns::ISO4217
548                                    || !is_iso4217_code(&unit.numerator[0].local)
549                                {
550                                    out.push(at(Diagnostic::error("xbrl.4.8.2:monetaryFactUnit-notMonetaryMeasure", format!("monetary item {} unit {} is not an ISO 4217 currency", name, unit.id)), node));
551                                }
552                            } else if c.is_shares {
553                                if unit.numerator.len() != 1 || !unit.denominator.is_empty() {
554                                    out.push(at(Diagnostic::error("xbrl.4.8.2:sharesFactUnit-notSingleMeasure", format!("shares item {} unit {} must be a single xbrli:shares measure", name, unit.id)), node));
555                                } else if !unit.numerator[0].is(ns::XBRLI, "shares") {
556                                    out.push(at(
557                                        Diagnostic::error(
558                                            "xbrl.4.8.2:sharesFactUnit-notSharesMeasure",
559                                            format!(
560                                                "shares item {} unit {} is not xbrli:shares",
561                                                name, unit.id
562                                            ),
563                                        ),
564                                        node,
565                                    ));
566                                }
567                            }
568                        }
569                    }
570                } else if f.unit.is_some() {
571                    out.push(at(
572                        Diagnostic::error(
573                            "xbrl.4.6.2:nonNumericUnit",
574                            format!("non-numeric item {} must not have a unitRef", name),
575                        ),
576                        node,
577                    ));
578                }
579                // decimals / precision (§4.6.3), including fixed/default values from the type
580                let ty = c.type_name.as_ref();
581                let type_has = |attr: &str| -> bool {
582                    ty.and_then(|t| attribute_info(dts, t, &QName::new("", attr)))
583                        .map(|i| i.fixed.is_some() || i.default.is_some())
584                        .unwrap_or(false)
585                };
586                let has_dec = if is_xml {
587                    raw_dec.is_some()
588                } else {
589                    f.decimals.is_some()
590                };
591                let has_prec = if is_xml {
592                    raw_prec.is_some()
593                } else {
594                    f.precision.is_some()
595                };
596                let eff_dec = has_dec || (c.is_numeric && type_has("decimals"));
597                let eff_prec = has_prec || (c.is_numeric && type_has("precision"));
598                if has_dec && has_prec {
599                    out.push(at(
600                        Diagnostic::error(
601                            "xbrl.4.6.3:bothPrecisionAndDecimals",
602                            format!("item {} has both precision and decimals", name),
603                        ),
604                        node,
605                    ));
606                }
607                if f.is_nil {
608                    if eff_dec || eff_prec {
609                        out.push(at(
610                            Diagnostic::error(
611                                "xbrl.4.6.3:nilPrecisionDecimals",
612                                format!("nil item {} must not have precision or decimals", name),
613                            ),
614                            node,
615                        ));
616                    }
617                } else if c.is_fraction {
618                    if has_dec || has_prec {
619                        out.push(at(
620                            Diagnostic::error(
621                                "xbrl.4.6.3:fractionPrecisionDecimals",
622                                format!(
623                                    "fraction item {} must not have precision or decimals",
624                                    name
625                                ),
626                            ),
627                            node,
628                        ));
629                    }
630                    if let Some((num, den)) = f.fraction.as_ref() {
631                        let nd = crossfoot_core::Decimal::parse_sci(den);
632                        if crossfoot_core::Decimal::parse_sci(num).is_none() && num.trim() != "INF"
633                        {
634                            out.push(at(
635                                Diagnostic::error(
636                                    "xbrl.5.1.1:fractionPrecisionDecimals",
637                                    format!(
638                                        "fraction item {} has an invalid numerator {}",
639                                        name, num
640                                    ),
641                                ),
642                                node,
643                            ));
644                        }
645                        if nd.map(|d| d.is_zero()).unwrap_or(true) {
646                            out.push(at(
647                                Diagnostic::error(
648                                    "xbrl.5.1.1:fractionPrecisionDecimals",
649                                    format!(
650                                        "fraction item {} has an invalid denominator {}",
651                                        name, den
652                                    ),
653                                ),
654                                node,
655                            ));
656                        }
657                    }
658                } else if c.is_numeric {
659                    if !eff_dec && !eff_prec {
660                        out.push(at(
661                            Diagnostic::error(
662                                "xbrl.4.6.3:missingPrecisionDecimals",
663                                format!("numeric item {} must have precision or decimals", name),
664                            ),
665                            node,
666                        ));
667                    }
668                } else if has_dec || has_prec {
669                    out.push(at(
670                        Diagnostic::error(
671                            "xbrl.4.6.3:extraneousPrecisionDecimals",
672                            format!(
673                                "non-numeric item {} must not have precision or decimals",
674                                name
675                            ),
676                        ),
677                        node,
678                    ));
679                }
680                if let Some(n) = xml_node {
681                    if !c.is_fraction {
682                        if let Some(ch) = n.elements().next() {
683                            out.push(
684                                Diagnostic::error(
685                                    "xbrl.5.1.1:itemMixedContent",
686                                    format!(
687                                        "item {} must not have child element {}",
688                                        name,
689                                        ch.name().lexical()
690                                    ),
691                                )
692                                .at(n),
693                            );
694                        }
695                    }
696                    if f.is_nil && !n.string_value().trim().is_empty() {
697                        out.push(
698                            Diagnostic::error(
699                                "xmlSchema:nilContent",
700                                format!("nil item {} has content", name),
701                            )
702                            .at(n),
703                        );
704                    }
705                }
706                // value validity against the item type
707                if !f.is_nil && !c.is_fraction {
708                    if let (Some(t), Some(v)) = (ty, f.value.as_deref()) {
709                        let simple = xml_node
710                            .map(|n| n.elements().next().is_none())
711                            .unwrap_or(true);
712                        if simple {
713                            if let Err(e) = dts.schemas.validate_simple(t, v, node) {
714                                out.push(at(
715                                    Diagnostic::error(
716                                        &e.code,
717                                        format!(
718                                            "item {} value {:?} is not valid for {}: {}",
719                                            name,
720                                            truncate(v),
721                                            t.lexical(),
722                                            e.message
723                                        ),
724                                    ),
725                                    node,
726                                ));
727                            }
728                        }
729                    }
730                }
731            }
732        }
733    }
734}
735
736fn truncate(s: &str) -> String {
737    let s = s.trim();
738    if s.chars().count() > 60 {
739        format!("{}…", s.chars().take(60).collect::<String>())
740    } else {
741        s.to_string()
742    }
743}
744
745/// §5.2.6.2.2: essence and alias facts that are c-equal and p-equal must be u-equal and
746/// v-equal.
747fn check_essence_alias(dts: &Dts, inst: &Instance, out: &mut Vec<Diagnostic>) {
748    let rels: Vec<(&QName, &QName, &str)> = dts
749        .relationships(arcrole::ESSENCE_ALIAS, None)
750        .filter_map(|(_, r)| match (&r.from, &r.to) {
751            (Endpoint::Concept(a), Endpoint::Concept(b)) => Some((a, b, &*r.link_role)),
752            _ => None,
753        })
754        .collect();
755    if rels.is_empty() {
756        return;
757    }
758    let involved: HashSet<&QName> = rels.iter().flat_map(|(a, b, _)| [*a, *b]).collect();
759    let mut ctx_keys: HashMap<&str, String> = HashMap::new();
760    // (concept, parent, context key) -> facts
761    let mut by_key: HashMap<(&QName, Option<FactId>, String), Vec<FactId>> = HashMap::new();
762    for (i, f) in inst.facts.iter().enumerate() {
763        if f.is_nil || f.kind != FactKind::Item || !involved.contains(&f.concept) {
764            continue;
765        }
766        let Some(cid) = f.context.as_deref() else {
767            continue;
768        };
769        let Some(ctx) = inst.contexts.get(cid) else {
770            continue;
771        };
772        let ck = ctx_keys
773            .entry(cid)
774            .or_insert_with(|| context_key(dts, inst, ctx))
775            .clone();
776        by_key
777            .entry((&f.concept, f.parent, ck))
778            .or_default()
779            .push(FactId(i as u32));
780    }
781    let mut reported: HashSet<(FactId, FactId)> = HashSet::new();
782    for (e, a, lr) in rels {
783        for ((c, parent, ck), efs) in by_key.iter() {
784            if *c != e {
785                continue;
786            }
787            let Some(afs) = by_key.get(&(a, *parent, ck.clone())) else {
788                continue;
789            };
790            for &ef in efs {
791                for &af in afs {
792                    if !reported.insert((ef, af)) {
793                        continue;
794                    }
795                    let (fe, fa) = (inst.fact(ef), inst.fact(af));
796                    let ue = inst.unit_of(fe).map(unit_key);
797                    let ua = inst.unit_of(fa).map(unit_key);
798                    let node = fe
799                        .node
800                        .filter(|fr| (fr.doc as usize) < inst.docs.len())
801                        .map(|fr| inst.node(fr));
802                    if ue != ua {
803                        out.push(at(Diagnostic::inconsistency("xbrl.5.2.6.2.2:essenceAliasUnitsInconsistency", format!("essence-alias facts {} and {} have different units (link role {})", e.lexical(), a.lexical(), lr)), node));
804                        continue;
805                    }
806                    let ve = fact_value_key(dts, inst, fe);
807                    let va = fact_value_key(dts, inst, fa);
808                    if ve.is_none() || ve != va {
809                        out.push(at(Diagnostic::inconsistency("xbrl.5.2.6.2.2:essenceAliasUnitsInconsistency", format!("essence-alias facts {} and {} have different values (link role {})", e.lexical(), a.lexical(), lr)), node));
810                    }
811                }
812            }
813        }
814    }
815}
816
817/// §5.2.6.2.4: a fact of the source concept requires at least one fact of the target.
818fn check_requires_element(dts: &Dts, inst: &Instance, out: &mut Vec<Diagnostic>) {
819    let present: HashSet<&QName> = inst.facts.iter().map(|f| &f.concept).collect();
820    let mut done: HashSet<(&QName, &QName)> = HashSet::new();
821    for (_, r) in dts.relationships(arcrole::REQUIRES_ELEMENT, None) {
822        let (Endpoint::Concept(a), Endpoint::Concept(b)) = (&r.from, &r.to) else {
823            continue;
824        };
825        if present.contains(a) && !present.contains(b) && done.insert((a, b)) {
826            out.push(Diagnostic::inconsistency(
827                "xbrl.5.2.6.2.4:requiresElementInconsistency",
828                format!(
829                    "{} requires a fact of {} which is missing (link role {})",
830                    a.lexical(),
831                    b.lexical(),
832                    r.link_role
833                ),
834            ));
835        }
836    }
837}
838
839#[cfg(test)]
840mod tests {
841    use super::*;
842    #[test]
843    fn lexical() {
844        assert!(is_decimals_lexical("-2"));
845        assert!(is_decimals_lexical("INF"));
846        assert!(!is_decimals_lexical("2.0"));
847        assert!(is_precision_lexical("0"));
848        assert!(!is_precision_lexical("-1"));
849    }
850}