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