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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
//! XBRL instance document representation
mod context;
mod fact;
mod footnote;
mod parser;
mod resolver;
mod template;
mod typed;
mod unit;
mod view;
mod writer;
use crate::{
ExpandedName, NamespacePrefix, NamespaceUri, RoleUri, TaxonomySet,
error::Result,
validation::{self, ValidationResult},
};
pub use context::{Context, ContextId, EntityIdentifier, Period};
pub use fact::{Decimals, Fact, ItemFact, TupleFact};
pub use footnote::{FootnoteArc, FootnoteLink, FootnoteLocator, FootnoteResource};
pub use parser::InstanceParser;
use quick_xml::{Reader, Writer};
pub use resolver::resolve_instance;
use std::{collections::HashMap, fs::File, io, path::Path};
pub use typed::{FactValue, TypedFact, TypedInstanceDocument, TypedItemFact, TypedTupleFact};
pub use unit::{Unit, UnitId};
pub use view::{DocumentView, SectionView, TreeNode};
pub use writer::InstanceWriter;
/// Supported mutable attributes for item facts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FactAttribute {
Id(String),
UnitRef(String),
Decimals(Decimals),
Precision(Decimals),
}
/// Names of removable item-fact attributes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FactAttributeName {
Id,
UnitRef,
Decimals,
Precision,
}
/// Represents a complete XBRL instance document
#[derive(Debug, Default, Clone)]
pub struct InstanceDocument {
/// Namespace prefixes used in the document (e.g. "xbrli" ->
/// "http://www.xbrl.org/2003/instance")
namespaces: HashMap<NamespacePrefix, NamespaceUri>,
/// Schema references (xlink:href values from link:schemaRef elements)
schema_refs: Vec<String>,
/// roleURI values from roleRef elements in the instance.
role_refs: Vec<String>,
/// arcroleURI values from arcroleRef elements in the instance.
arcrole_refs: Vec<String>,
/// All contexts in the instance
contexts: HashMap<ContextId, Context>,
/// All units in the instance
units: HashMap<UnitId, Unit>,
/// Top-level facts in the instance (item and tuple facts)
facts: Vec<Fact>,
/// Footnote links found in the instance.
footnote_links: Vec<FootnoteLink>,
}
impl InstanceDocument {
#[allow(clippy::too_many_arguments)]
pub fn new(
schema_refs: Vec<String>,
contexts: HashMap<ContextId, Context>,
units: HashMap<UnitId, Unit>,
facts: Vec<Fact>,
namespaces: HashMap<NamespacePrefix, NamespaceUri>,
footnote_links: Vec<FootnoteLink>,
) -> Self {
Self {
schema_refs,
role_refs: Vec::new(),
arcrole_refs: Vec::new(),
contexts,
units,
facts,
namespaces,
footnote_links,
}
}
/// Parse an XBRL instance document from the file at the given path.
///
/// Automatically extracts the `<xbrli:xbrl>` element if the input
/// contains a wrapper around it.
pub fn from_file(path: &Path) -> Result<Self> {
let mut parser = InstanceParser::from_file(path)?;
let instance = parser.parse()?;
let doc = resolver::resolve_instance(instance)?;
Ok(doc)
}
/// Parse an XBRL instance document from the reader.
///
/// Automatically extracts the `<xbrli:xbrl>` element if the input
/// contains a wrapper around it.
pub fn from_reader<R>(reader: R) -> Result<Self>
where
R: io::BufRead,
{
let mut parser = InstanceParser::from_reader(reader);
let instance = parser.parse()?;
let doc = resolver::resolve_instance(instance)?;
Ok(doc)
}
/// Parse an XBRL instance document from the XML reader.
///
/// Automatically extracts the `<xbrli:xbrl>` element if the input
/// contains a wrapper around it.
pub fn from_xml_reader<R>(reader: Reader<R>) -> Result<Self>
where
R: io::BufRead,
{
let mut parser = InstanceParser::new(reader, None, false);
let instance = parser.parse()?;
let doc = resolver::resolve_instance(instance)?;
Ok(doc)
}
/// Builds a template instance document based on the taxonomy structure.
///
/// - Registers all schema refs and role refs from the taxonomy
/// - Adds both contexts and all provided units
/// - Pre-populates nil facts for concepts in taxonomy schemas, preserving
/// tuple nesting and child order from XSD content models
/// - For tuples with an exclusive single-choice content model, emits the
/// tuple as `xsi:nil=true` (without pre-populated choice children)
/// - Assigns each fact the correct `unitRef` based on its XSD type:
/// monetary → first currency unit, shares → first shares unit, other
/// numeric → first pure unit, non-numeric → no unitRef
/// - Emits concepts that participate in dimensional hypercube base sets
/// only when matching dimensional contexts are provided.
///
/// Build the [`DocumentView`] once after this call, then fill values
/// in-place via [`set_fact_value`] without rebuilding the view.
pub fn from_taxonomy(
taxonomy: &TaxonomySet,
namespaces: HashMap<NamespacePrefix, NamespaceUri>,
instant_context: Context,
duration_context: Context,
dimensional_instant_contexts: Vec<Context>,
dimensional_duration_contexts: Vec<Context>,
units: &[Unit],
) -> Self {
template::build_instance(
taxonomy,
namespaces,
instant_context,
duration_context,
dimensional_instant_contexts,
dimensional_duration_contexts,
units,
)
}
/// Builds a template instance document restricted to the given presentation
/// roles, in presentation-arc order. Concepts not covered by any of the
/// specified roles are omitted. Tuple subtrees are populated from the
/// schema content model. Hypercube-related concepts are emitted only when
/// matching dimensional contexts are provided.
///
/// `dimensional_hypercubes` narrows which hypercubes' members are assigned
/// the dimensional contexts. When non-empty, only facts that are domain
/// members of at least one of the listed hypercube concepts receive
/// dimensional context refs; facts from other hypercubes are omitted.
/// Pass an empty slice to apply
/// dimensional contexts to members of all hypercubes.
#[allow(clippy::too_many_arguments)]
pub fn from_sections(
taxonomy: &TaxonomySet,
roles: &[RoleUri],
namespaces: HashMap<NamespacePrefix, NamespaceUri>,
instant_context: Context,
duration_context: Context,
dimensional_instant_contexts: Vec<Context>,
dimensional_duration_contexts: Vec<Context>,
units: &[Unit],
dimensional_hypercubes: &[ExpandedName],
) -> Self {
template::build_instance_from_sections(
taxonomy,
roles,
namespaces,
instant_context,
duration_context,
dimensional_instant_contexts,
dimensional_duration_contexts,
units,
dimensional_hypercubes,
)
}
/// Validate this instance against a taxonomy.
pub fn validate(&self, taxonomy: &TaxonomySet) -> ValidationResult {
validation::validate_all(self, taxonomy)
}
/// Convert this instance into a typed instance document.
pub fn type_instance(self, taxonomy: &TaxonomySet) -> Result<TypedInstanceDocument> {
TypedInstanceDocument::from_instance(self, taxonomy)
}
/// Convenience wrapper for [`DocumentView::build`] using this instance's
/// full fact tree.
///
/// The returned view is item-indexed (`fact_indices`) and keeps tuple
/// concepts visible when corresponding tuple facts are present.
pub fn view<'a>(&self, taxonomy: &'a TaxonomySet) -> DocumentView<'a> {
DocumentView::build(self.facts(), taxonomy)
}
/// Serialize this instance to an XML file at the given path.
pub fn to_file(&self, path: &Path) -> Result<()> {
let file = File::create(path)?;
self.to_writer(file)?;
Ok(())
}
/// Serialize this instance to an XBRL XML document using a writer.
pub fn to_writer<W>(&self, writer: W) -> Result<()>
where
W: io::Write,
{
let mut writer = InstanceWriter::new(Writer::new(writer), false);
writer.write(self)
}
/// Add a schema reference (xlink:href from a link:schemaRef element)
pub fn add_schema_ref(&mut self, href: String) {
self.schema_refs.push(href);
}
/// Get all schema references declared in the instance document.
pub fn schema_refs(&self) -> &[String] {
&self.schema_refs
}
/// Add a role reference URI from a roleRef element.
pub fn add_role_ref(&mut self, role_uri: String) {
self.role_refs.push(role_uri);
}
/// Get all role reference URIs declared in the instance document.
pub fn role_refs(&self) -> &[String] {
&self.role_refs
}
/// Add an arcrole reference URI from an arcroleRef element.
pub fn add_arcrole_ref(&mut self, arcrole_uri: String) {
self.arcrole_refs.push(arcrole_uri);
}
/// Get all arcrole reference URIs declared in the instance document.
pub fn arcrole_refs(&self) -> &[String] {
&self.arcrole_refs
}
/// Extract relative path suffixes from schema reference URLs.
///
/// Strips the URL scheme, host, and leading `/taxonomies/` segment to
/// produce paths suitable for joining with a local taxonomy directory.
///
/// For example:
/// `http://www.xbrl.de/taxonomies/de-gcd-2020-04-01/de-gcd-2020-04-01-shell.xsd`
/// becomes `de-gcd-2020-04-01/de-gcd-2020-04-01-shell.xsd`.
pub fn schema_ref_paths(&self) -> Vec<&str> {
self.schema_refs
.iter()
.map(|href| {
// Find the path portion after "://" + host
let path = href
.find("://")
.and_then(|i| href[i + 3..].find('/'))
.map(|i| &href[href.find("://").unwrap() + 3 + i..])
.unwrap_or(href);
// Strip leading "/taxonomies/" if present
path.strip_prefix("/taxonomies/")
.or_else(|| path.strip_prefix("/"))
.unwrap_or(path)
})
.collect()
}
/// Add a context to the instance
pub fn add_context(&mut self, context: Context) {
self.contexts.insert(context.id.clone(), context);
}
/// Get a context by ID
pub fn get_context(&self, id: &str) -> Option<&Context> {
self.contexts.get(id)
}
/// Add a unit to the instance
pub fn add_unit(&mut self, unit: Unit) {
self.units.insert(unit.id.clone(), unit);
}
/// Get a unit by ID
pub fn get_unit(&self, id: &str) -> Option<&Unit> {
self.units.get(id)
}
/// Add a fact to the instance
pub fn add_fact(&mut self, fact: Fact) {
self.facts.push(fact);
}
/// Get all top-level facts.
pub fn facts(&self) -> &[Fact] {
&self.facts
}
/// Get all top-level facts mutably.
pub fn facts_mut(&mut self) -> &mut [Fact] {
&mut self.facts
}
/// Get all item facts in depth-first order.
pub fn item_facts(&self) -> Vec<&ItemFact> {
let mut out = Vec::new();
for fact in &self.facts {
fact.walk_items(&mut out);
}
out
}
/// Number of item facts in the instance (including nested tuple descendants).
pub fn item_fact_count(&self) -> usize {
self.facts.iter().map(|fact| fact.count_items()).sum()
}
/// Set the value of a fact by its index (from [`DocumentView`] fact_indices).
/// Clears nil status.
///
/// # Panics
/// Panics if `index` is out of bounds.
pub fn set_fact_value(&mut self, index: usize, value: String) {
let mut current_index = 0usize;
for fact in &mut self.facts {
if Self::set_item_value_by_index(fact, index, &value, &mut current_index) {
return;
}
}
panic!("fact index out of bounds: {index}");
}
/// Set the nil status of a fact by its index (from [`DocumentView`] fact_indices).
/// When setting nil=true, also clears the value.
///
/// # Panics
/// Panics if `index` is out of bounds.
pub fn set_fact_nil(&mut self, index: usize, is_nil: bool) {
let mut current_index = 0usize;
for fact in &mut self.facts {
if Self::set_item_nil_by_index(fact, index, is_nil, &mut current_index) {
return;
}
}
panic!("fact index out of bounds: {index}");
}
/// Set an item-fact attribute by its index (from [`DocumentView`]
/// `fact_indices`).
///
/// When setting `decimals` or `precision`, the counterpart is cleared to
/// keep attributes mutually exclusive.
///
/// # Panics
/// Panics if `index` is out of bounds.
pub fn set_fact_attribute(&mut self, index: usize, attribute: FactAttribute) {
let mut current_index = 0usize;
for fact in &mut self.facts {
if Self::set_item_attribute_by_index(fact, index, &attribute, &mut current_index) {
return;
}
}
panic!("fact index out of bounds: {index}");
}
/// Remove an optional item-fact attribute by its index (from
/// [`DocumentView`] `fact_indices`).
///
/// # Panics
/// Panics if `index` is out of bounds.
pub fn clear_fact_attribute(&mut self, index: usize, attribute: FactAttributeName) {
let mut current_index = 0usize;
for fact in &mut self.facts {
if Self::clear_item_attribute_by_index(fact, index, attribute, &mut current_index) {
return;
}
}
panic!("fact index out of bounds: {index}");
}
/// Sets `xsi:nil` on a tuple fact within all matching tuple instances.
///
/// This is a mutation-only helper. It does not check taxonomy/schema
/// compatibility; call [`validate`] explicitly after mutation.
///
/// Returns the number of tuple instances that were mutated.
pub fn set_tuple_fact_nil(&mut self, tuple_local_name: &str, is_nil: bool) -> Result<usize> {
let mut changed = 0usize;
for fact in &mut self.facts {
changed += Self::set_tuple_fact_nil_in_fact(fact, tuple_local_name, is_nil);
}
Ok(changed)
}
/// Adds one tuple child within all matching tuple instances.
///
/// Behavior:
/// - if the child already exists, no change is made
/// - if it does not exist, a new child is added using `child_fact`
/// - if the tuple itself is nil and a child is added, it is set to non-nil
///
/// This is a mutation-only helper. It does not check taxonomy/schema
/// compatibility; call [`validate`] explicitly after mutation.
///
/// Returns the number of tuple instances that were mutated.
pub fn add_tuple_child(
&mut self,
tuple_local_name: &str,
child_fact: &ItemFact,
) -> Result<usize> {
let mut changed = 0usize;
for fact in &mut self.facts {
changed += Self::add_tuple_child_in_fact(fact, tuple_local_name, child_fact);
}
Ok(changed)
}
/// Removes one tuple child within all matching tuple instances.
///
/// Behavior:
/// - removes all item children whose local name matches
/// `child_local_name`
/// - leaves all other children unchanged
///
/// This is a mutation-only helper. It does not check taxonomy/schema
/// compatibility; call [`validate`] explicitly after mutation.
///
/// Returns the number of tuple instances that were mutated.
pub fn remove_tuple_child(
&mut self,
tuple_local_name: &str,
child_local_name: &str,
) -> Result<usize> {
let mut changed = 0usize;
for fact in &mut self.facts {
changed += Self::remove_tuple_child_in_fact(fact, tuple_local_name, child_local_name);
}
Ok(changed)
}
/// Sets `xsi:nil` on a tuple child within all matching tuple instances.
///
/// This is a mutation-only helper. It does not check taxonomy/schema
/// compatibility; call [`validate`] explicitly after mutation.
///
/// Returns the number of tuple instances that were mutated.
pub fn set_tuple_child_nil(
&mut self,
tuple_local_name: &str,
child_local_name: &str,
is_nil: bool,
) -> Result<usize> {
let mut changed = 0usize;
for fact in &mut self.facts {
changed +=
Self::set_tuple_child_nil_in_fact(fact, tuple_local_name, child_local_name, is_nil);
}
Ok(changed)
}
/// Add a namespace prefix mapping
pub fn add_namespace(&mut self, prefix: NamespacePrefix, uri: NamespaceUri) {
self.namespaces.insert(prefix, uri);
}
/// Get namespace URI for a prefix
pub fn get_namespace(&self, prefix: &str) -> Option<&str> {
self.namespaces.get(prefix).map(|s| s.as_str())
}
/// Get all namespace prefix mappings
pub fn namespaces(&self) -> &HashMap<NamespacePrefix, NamespaceUri> {
&self.namespaces
}
/// Add a footnote link to the instance.
pub fn add_footnote_link(&mut self, footnote_link: FootnoteLink) {
self.footnote_links.push(footnote_link);
}
/// Get all footnote links in the instance.
pub fn footnote_links(&self) -> &[FootnoteLink] {
&self.footnote_links
}
/// Get all contexts.
pub fn contexts(&self) -> &HashMap<ContextId, Context> {
&self.contexts
}
/// Get a mutable reference to all contexts.
pub fn contexts_mut(&mut self) -> &mut HashMap<ContextId, Context> {
&mut self.contexts
}
/// Get all units.
pub fn units(&self) -> &HashMap<UnitId, Unit> {
&self.units
}
/// Get a mutable reference to all units.
pub fn units_mut(&mut self) -> &mut HashMap<UnitId, Unit> {
&mut self.units
}
/// Set the value of a fact by its index (from [`DocumentView`]
/// fact_indices).
fn set_item_nil_by_index(
fact: &mut Fact,
target_index: usize,
is_nil: bool,
current_index: &mut usize,
) -> bool {
match fact {
Fact::Item(item) => {
if *current_index == target_index {
item.set_nil(is_nil);
if is_nil {
item.set_value(String::new());
}
true
} else {
*current_index += 1;
false
}
}
Fact::Tuple(tuple) => {
for child in tuple.children_mut() {
if Self::set_item_nil_by_index(child, target_index, is_nil, current_index) {
return true;
}
}
false
}
}
}
fn set_item_value_by_index(
fact: &mut Fact,
target_index: usize,
value: &str,
current_index: &mut usize,
) -> bool {
match fact {
Fact::Item(item) => {
if *current_index == target_index {
item.set_value(value.to_owned());
item.set_nil(false);
true
} else {
*current_index += 1;
false
}
}
Fact::Tuple(tuple) => {
for child in tuple.children_mut() {
if Self::set_item_value_by_index(child, target_index, value, current_index) {
return true;
}
}
false
}
}
}
fn set_item_attribute_by_index(
fact: &mut Fact,
target_index: usize,
attribute: &FactAttribute,
current_index: &mut usize,
) -> bool {
match fact {
Fact::Item(item) => {
if *current_index == target_index {
match attribute {
FactAttribute::Id(id) => item.set_id(id.clone()),
FactAttribute::UnitRef(unit_ref) => {
item.set_unit_ref(Some(unit_ref.clone()))
}
FactAttribute::Decimals(decimals) => {
item.set_decimals(decimals.clone());
item.clear_precision();
}
FactAttribute::Precision(precision) => {
item.set_precision(precision.clone());
item.clear_decimals();
}
}
true
} else {
*current_index += 1;
false
}
}
Fact::Tuple(tuple) => {
for child in tuple.children_mut() {
if Self::set_item_attribute_by_index(
child,
target_index,
attribute,
current_index,
) {
return true;
}
}
false
}
}
}
fn clear_item_attribute_by_index(
fact: &mut Fact,
target_index: usize,
attribute: FactAttributeName,
current_index: &mut usize,
) -> bool {
match fact {
Fact::Item(item) => {
if *current_index == target_index {
match attribute {
FactAttributeName::Id => item.clear_id(),
FactAttributeName::UnitRef => item.set_unit_ref(None),
FactAttributeName::Decimals => item.clear_decimals(),
FactAttributeName::Precision => item.clear_precision(),
}
true
} else {
*current_index += 1;
false
}
}
Fact::Tuple(tuple) => {
for child in tuple.children_mut() {
if Self::clear_item_attribute_by_index(
child,
target_index,
attribute,
current_index,
) {
return true;
}
}
false
}
}
}
/// Sets `xsi:nil` on a tuple fact within a fact.
///
/// This is a mutation-only helper. It does not check taxonomy/schema
/// compatibility; call [`validate`] explicitly after mutation.
///
/// Returns the number of tuple instances that were mutated.
fn set_tuple_fact_nil_in_fact(fact: &mut Fact, tuple_local_name: &str, is_nil: bool) -> usize {
match fact {
Fact::Item(_) => 0,
Fact::Tuple(tuple) => {
let mut changed = 0usize;
if tuple.concept_name().local_name == tuple_local_name {
tuple.set_nil(is_nil);
changed += 1;
}
for child in tuple.children_mut() {
changed += Self::set_tuple_fact_nil_in_fact(child, tuple_local_name, is_nil);
}
changed
}
}
}
/// Adds one tuple child within a fact.
///
/// This is a mutation-only helper. It does not check taxonomy/schema
/// compatibility; call [`validate`] explicitly after mutation.
///
/// Returns the number of tuple instances that were mutated.
fn add_tuple_child_in_fact(
fact: &mut Fact,
tuple_local_name: &str,
child_fact: &ItemFact,
) -> usize {
match fact {
Fact::Item(_) => 0,
Fact::Tuple(tuple) => {
let mut changed = 0usize;
if tuple.concept_name().local_name == tuple_local_name
&& Self::add_tuple_child_in_tuple(tuple, child_fact)
{
changed += 1;
}
for child in tuple.children_mut() {
changed += Self::add_tuple_child_in_fact(child, tuple_local_name, child_fact);
}
changed
}
}
}
/// Adds one tuple child within a tuple fact.
fn add_tuple_child_in_tuple(tuple: &mut TupleFact, child_fact: &ItemFact) -> bool {
let child_local_name = child_fact.concept_name().local_name.as_str();
let has_matching_child = tuple.children().iter().any(|fact| {
matches!(fact, Fact::Item(item) if item.concept_name().local_name == child_local_name)
});
// Explicit no-op when the child already exists.
if has_matching_child {
return false;
}
// A nil tuple has no active content. Adding a child makes it non-nil again.
if tuple.is_nil() {
tuple.set_nil(false);
}
let children = tuple.children_mut();
let mut added = child_fact.clone();
added.set_nil(false);
children.push(Fact::Item(added));
true
}
/// Removes one tuple child within a fact.
///
/// This is a mutation-only helper. It does not check taxonomy/schema
/// compatibility; call [`validate`] explicitly after mutation.
///
/// Returns the number of tuple instances that were mutated.
fn remove_tuple_child_in_fact(
fact: &mut Fact,
tuple_local_name: &str,
child_local_name: &str,
) -> usize {
match fact {
Fact::Item(_) => 0,
Fact::Tuple(tuple) => {
let mut changed = 0usize;
if tuple.concept_name().local_name == tuple_local_name
&& Self::remove_tuple_child_in_tuple(tuple, child_local_name)
{
changed += 1;
}
for child in tuple.children_mut() {
changed +=
Self::remove_tuple_child_in_fact(child, tuple_local_name, child_local_name);
}
changed
}
}
}
/// Removes all matching tuple item children within a tuple fact.
fn remove_tuple_child_in_tuple(tuple: &mut TupleFact, child_local_name: &str) -> bool {
let children = tuple.children_mut();
let original_len = children.len();
children.retain(|fact| {
!matches!(fact, Fact::Item(item) if item.concept_name().local_name == child_local_name)
});
original_len != children.len()
}
/// Sets `xsi:nil` on a tuple child within a tuple fact.
///
/// This is a mutation-only helper. It does not check taxonomy/schema
/// compatibility; call [`validate`] explicitly after mutation.
///
/// Returns true if the fact was mutated.
///
/// Note: this only sets nil on existing children; it does not add new nil
/// children if the target child does not already exist.
///
/// If the same child appears multiple times within the same tuple, all
/// occurrences will be updated.
fn set_tuple_child_nil_in_fact(
fact: &mut Fact,
tuple_local_name: &str,
child_local_name: &str,
is_nil: bool,
) -> usize {
match fact {
Fact::Item(_) => 0,
Fact::Tuple(tuple) => {
let mut changed = 0usize;
if tuple.concept_name().local_name == tuple_local_name
&& Self::set_tuple_child_nil_in_tuple(tuple, child_local_name, is_nil)
{
changed += 1;
}
for child in tuple.children_mut() {
changed += Self::set_tuple_child_nil_in_fact(
child,
tuple_local_name,
child_local_name,
is_nil,
);
}
changed
}
}
}
/// Sets `xsi:nil` on a tuple child within a tuple fact.
fn set_tuple_child_nil_in_tuple(
tuple: &mut TupleFact,
child_local_name: &str,
is_nil: bool,
) -> bool {
let mut touched = false;
for fact in tuple.children_mut() {
if let Fact::Item(item) = fact
&& item.concept_name().local_name == child_local_name
{
item.set_nil(is_nil);
if is_nil {
item.set_value(String::new());
}
touched = true;
}
}
touched
}
}
#[cfg(test)]
mod tests {
use super::{
Decimals, Fact, FactAttribute, FactAttributeName, InstanceDocument, ItemFact, TaxonomySet,
TupleFact,
};
use crate::{ExpandedName, NamespaceUri};
fn expanded_name(local_name: &str) -> ExpandedName {
ExpandedName::new(
NamespaceUri::from("http://example.com/ns"),
local_name.to_owned(),
)
}
fn item(local_name: &str, value: &str, is_nil: bool) -> Fact {
Fact::Item(ItemFact::new(
None,
expanded_name(local_name),
"D-2020".to_owned(),
None,
value.to_owned(),
is_nil,
None,
None,
))
}
fn tuple(local_name: &str, children: Vec<Fact>) -> Fact {
let mut tuple = TupleFact::new(expanded_name(local_name));
for child in children {
tuple.add_child(child);
}
Fact::Tuple(tuple)
}
#[test]
fn type_instance_fails_for_unknown_concept() {
let taxonomy = TaxonomySet::default();
let mut instance = InstanceDocument::default();
instance.add_fact(item("unknownConcept", "1", false));
let result = instance.type_instance(&taxonomy);
assert!(result.is_err());
}
#[test]
fn from_xml_parses_basic_instance() {
let xml = r#"
<xbrli:xbrl
xmlns:xbrli="http://www.xbrl.org/2003/instance"
xmlns:link="http://www.xbrl.org/2003/linkbase"
xmlns:xlink="http://www.w3.org/1999/xlink">
<link:schemaRef
xlink:type="simple"
xlink:href="http://www.xbrl.de/taxonomies/de-gcd-2020-04-01/de-gcd-2020-04-01-shell.xsd"/>
</xbrli:xbrl>
"#;
let instance =
InstanceDocument::from_reader(xml.as_bytes()).expect("instance should parse");
assert_eq!(instance.schema_refs().len(), 1);
assert!(instance.contexts().is_empty());
assert!(instance.units().is_empty());
assert!(instance.facts().is_empty());
}
#[test]
fn validate_reports_duplicate_role_refs() {
let taxonomy = TaxonomySet::default();
let mut instance = InstanceDocument::default();
let role_uri = "http://www.xbrl.org/2003/role/link".to_string();
instance.add_role_ref(role_uri.clone());
instance.add_role_ref(role_uri);
let result = instance.validate(&taxonomy);
assert!(!result.is_valid());
assert!(
result
.errors()
.iter()
.any(|message| message.code == "spec.duplicate_role_ref")
);
}
#[test]
fn validate_reports_duplicate_arcrole_refs() {
let taxonomy = TaxonomySet::default();
let mut instance = InstanceDocument::default();
let arcrole_uri = "http://www.xbrl.org/2003/arcrole/fact-footnote".to_string();
instance.add_arcrole_ref(arcrole_uri.clone());
instance.add_arcrole_ref(arcrole_uri);
let result = instance.validate(&taxonomy);
assert!(!result.is_valid());
assert!(
result
.errors()
.iter()
.any(|message| message.code == "spec.duplicate_arcrole_ref")
);
}
#[test]
fn validate_accepts_unique_refs() {
let taxonomy = TaxonomySet::default();
let mut instance = InstanceDocument::default();
instance.add_role_ref("http://www.xbrl.org/2003/role/link".to_string());
instance.add_arcrole_ref("http://www.xbrl.org/2003/arcrole/fact-footnote".to_string());
let result = instance.validate(&taxonomy);
assert!(
result.is_valid(),
"unexpected errors: {:#?}",
result.errors()
);
assert!(result.errors().is_empty());
}
#[test]
fn from_xml_parses_role_and_arcrole_refs() {
let xml = r#"
<xbrli:xbrl
xmlns:xbrli="http://www.xbrl.org/2003/instance"
xmlns:link="http://www.xbrl.org/2003/linkbase"
xmlns:xlink="http://www.w3.org/1999/xlink">
<link:roleRef
roleURI="http://www.xbrl.org/2003/role/link"
xlink:type="simple"
xlink:href="dummy.xsd#role_link"/>
<link:arcroleRef
arcroleURI="http://www.xbrl.org/2003/arcrole/fact-footnote"
xlink:type="simple"
xlink:href="dummy.xsd#arcrole_fact_footnote"/>
</xbrli:xbrl>
"#;
let instance =
InstanceDocument::from_reader(xml.as_bytes()).expect("instance should parse");
assert_eq!(instance.role_refs(), ["http://www.xbrl.org/2003/role/link"]);
assert_eq!(
instance.arcrole_refs(),
["http://www.xbrl.org/2003/arcrole/fact-footnote"]
);
}
#[test]
fn validate_reports_both_duplicate_role_and_arcrole_refs() {
let taxonomy = TaxonomySet::default();
let mut instance = InstanceDocument::default();
instance.add_role_ref("http://www.xbrl.org/2003/role/link".to_string());
instance.add_role_ref("http://www.xbrl.org/2003/role/link".to_string());
instance.add_arcrole_ref("http://www.xbrl.org/2003/arcrole/fact-footnote".to_string());
instance.add_arcrole_ref("http://www.xbrl.org/2003/arcrole/fact-footnote".to_string());
let result = instance.validate(&taxonomy);
assert!(!result.is_valid());
assert!(
result
.errors()
.iter()
.any(|message| message.code == "spec.duplicate_role_ref")
);
assert!(
result
.errors()
.iter()
.any(|message| message.code == "spec.duplicate_arcrole_ref")
);
}
#[test]
fn remove_tuple_child_removes_existing_child() {
let mut instance = InstanceDocument::default();
instance.add_fact(tuple(
"genInfo.report.id.specialAccountingStandard",
vec![
item("genInfo.report.id.specialAccountingStandard.K", "", false),
item("genInfo.report.id.specialAccountingStandard.RKV", "", true),
],
));
let changed = instance
.remove_tuple_child(
"genInfo.report.id.specialAccountingStandard",
"genInfo.report.id.specialAccountingStandard.RKV",
)
.expect("remove should succeed");
assert_eq!(changed, 1);
let facts = instance.item_facts();
assert_eq!(facts.len(), 1);
assert!(facts.iter().any(|fact| {
fact.concept_name().local_name == "genInfo.report.id.specialAccountingStandard.K"
}));
assert!(!facts.iter().any(|fact| {
fact.concept_name().local_name == "genInfo.report.id.specialAccountingStandard.RKV"
}));
}
#[test]
fn add_tuple_child_adds_new_child_when_missing() {
let mut instance = InstanceDocument::default();
instance.add_fact(tuple(
"genInfo.report.id.specialAccountingStandard",
vec![item(
"genInfo.report.id.specialAccountingStandard.K",
"",
false,
)],
));
let changed = instance
.add_tuple_child(
"genInfo.report.id.specialAccountingStandard",
&ItemFact::new(
None,
expanded_name("genInfo.report.id.specialAccountingStandard.RKV"),
"D-2020".to_owned(),
None,
String::new(),
false,
None,
None,
),
)
.expect("add should succeed");
assert_eq!(changed, 1);
let facts = instance.item_facts();
assert_eq!(facts.len(), 2);
assert!(facts.iter().any(|fact| {
fact.concept_name().local_name == "genInfo.report.id.specialAccountingStandard.RKV"
&& !fact.is_nil()
}));
assert!(facts.iter().any(|fact| {
fact.concept_name().local_name == "genInfo.report.id.specialAccountingStandard.K"
&& !fact.is_nil()
}));
}
#[test]
fn add_tuple_child_does_nothing_when_child_exists() {
let mut instance = InstanceDocument::default();
instance.add_fact(tuple(
"genInfo.report.id.specialAccountingStandard",
vec![
item("genInfo.report.id.specialAccountingStandard.K", "", false),
item("genInfo.report.id.specialAccountingStandard.RKV", "", true),
],
));
let changed = instance
.add_tuple_child(
"genInfo.report.id.specialAccountingStandard",
&ItemFact::new(
None,
expanded_name("genInfo.report.id.specialAccountingStandard.RKV"),
"D-2020".to_owned(),
None,
String::new(),
false,
None,
None,
),
)
.expect("add should succeed");
assert_eq!(changed, 0);
let facts = instance.item_facts();
assert_eq!(facts.len(), 2);
let rkv = facts
.iter()
.find(|fact| {
fact.concept_name().local_name == "genInfo.report.id.specialAccountingStandard.RKV"
})
.expect("RKV child should exist");
assert!(rkv.is_nil());
}
#[test]
fn set_tuple_child_nil_sets_nil_and_clears_value() {
let mut instance = InstanceDocument::default();
instance.add_fact(tuple(
"genInfo.report.id.reportElement",
vec![item(
"genInfo.report.id.reportElement.reportElements.BVV",
"present",
false,
)],
));
let changed = instance
.set_tuple_child_nil(
"genInfo.report.id.reportElement",
"genInfo.report.id.reportElement.reportElements.BVV",
true,
)
.expect("nil update should succeed");
assert_eq!(changed, 1);
let facts = instance.item_facts();
let bvv = facts
.iter()
.find(|fact| {
fact.concept_name().local_name
== "genInfo.report.id.reportElement.reportElements.BVV"
})
.expect("BVV child should exist");
assert!(bvv.is_nil());
assert_eq!(bvv.value(), "");
}
#[test]
fn set_tuple_fact_nil() {
let mut instance = InstanceDocument::default();
instance.add_fact(tuple(
"genInfo.report.id.reportType",
vec![item(
"genInfo.report.id.reportType.reportType.JA",
"",
false,
)],
));
let changed = instance
.set_tuple_fact_nil("genInfo.report.id.reportType", true)
.expect("tuple nil update should succeed");
assert_eq!(changed, 1);
let tuple_fact = match &instance.facts()[0] {
Fact::Tuple(tuple) => tuple,
_ => panic!("expected tuple fact"),
};
assert!(tuple_fact.is_nil());
}
#[test]
fn set_fact_attribute_sets_and_replaces_numeric_accuracy() {
let mut instance = InstanceDocument::default();
instance.add_fact(item("metric", "1", false));
instance.set_fact_attribute(0, FactAttribute::Decimals(Decimals::Finite(2)));
let fact = &instance.item_facts()[0];
assert_eq!(fact.decimals(), Some(&Decimals::Finite(2)));
assert_eq!(fact.precision(), None);
instance.set_fact_attribute(0, FactAttribute::Precision(Decimals::Finite(5)));
let fact = &instance.item_facts()[0];
assert_eq!(fact.decimals(), None);
assert_eq!(fact.precision(), Some(&Decimals::Finite(5)));
}
#[test]
fn remove_fact_attribute_clears_optional_attributes() {
let mut instance = InstanceDocument::default();
let mut item = ItemFact::new(
None,
expanded_name("metric"),
"D-2020".to_owned(),
Some("u1".to_owned()),
"1".to_owned(),
false,
Some(Decimals::Finite(0)),
None,
);
item.set_id("id-1".to_owned());
instance.add_fact(Fact::Item(item));
instance.clear_fact_attribute(0, FactAttributeName::Id);
instance.clear_fact_attribute(0, FactAttributeName::UnitRef);
instance.clear_fact_attribute(0, FactAttributeName::Decimals);
let fact = &instance.item_facts()[0];
assert_eq!(fact.id(), None);
assert_eq!(fact.unit_ref(), None);
assert_eq!(fact.decimals(), None);
}
}