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