xbrl-rs 0.3.0

XBRL parser and validation
Documentation
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
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
use crate::{
    NamespacePrefix, NamespaceUri, QName, XbrlError,
    xml::{self, ArcroleRef, RoleRef, SchemaRef, parse_qname},
};
use quick_xml::{
    Reader,
    events::{BytesStart, Event, attributes::Attributes},
};
use std::{
    collections::HashMap,
    fs::File,
    io::{BufRead, BufReader},
    path::{Path, PathBuf},
};

/// An `xbrli:context` element as parsed from the instance document.
#[derive(Debug, PartialEq, Eq)]
pub struct RawContext {
    /// Id attribute of the context.
    pub id: String,
    /// Entity definition for the context.
    pub entity: RawEntity,
    /// Period definition for the context.
    pub period: RawPeriod,
    /// Scenario dimensions for the context.
    pub scenario_dimensions: Vec<RawDimension>,
}

/// An `xbrli:entity` element as parsed from the instance document.
#[derive(Debug, PartialEq, Eq)]
pub struct RawEntity {
    /// Identifier for the entity, typically a legal entity identifier (LEI).
    pub identifier: String,
    /// Scheme for the entity identifier, typically a URI that defines the
    /// syntax and semantics of the identifier (e.g.
    /// "http://standards.iso.org/iso/17442" for LEIs).
    pub scheme: String,
    /// Segment dimensions for the entity.
    pub segment_dimensions: Vec<RawDimension>,
}

/// An `xbrli:period` element as parsed from the instance document.
#[derive(Debug, PartialEq, Eq)]
pub enum RawPeriod {
    Instant(String),
    Duration {
        start_date: String,
        end_date: String,
    },
    Forever,
}

/// A dimension defined in a `scenario` or `segment` element.
#[derive(Debug, PartialEq, Eq)]
pub struct RawDimension {
    /// QName of the dimension
    pub dimension: QName,
    /// QName of the member
    pub member: QName,
}

#[derive(Debug, PartialEq, Eq)]
pub struct RawUnit {
    /// Unique ID of the unit as specified in the instance document.
    pub id: String,
    /// For a simple unit, this will be the only measure. For a divide unit,
    /// this is the numerator.
    pub numerator: Vec<QName>,
    /// For a simple unit, this will be empty. For a divide unit, this is the
    /// denominator.
    pub denominator: Vec<QName>,
}

/// A fact in the instance document, which can be either an item or a tuple.
#[derive(Debug, PartialEq, Eq)]
pub enum RawFact {
    Item(RawItemFact),
    Tuple(RawTupleFact),
}

#[derive(Debug, PartialEq, Eq)]
pub struct RawItemFact {
    /// QName of the corresponding concept
    pub name: QName,
    /// Raw text value
    pub value: String,
    /// contextRef attribute
    pub context_ref: String,
    /// unitRef attribute
    pub unit_ref: Option<String>,
    /// decimals attribute
    pub decimals: Option<String>,
    /// precision attribute
    pub precision: Option<String>,
    /// id attribute
    pub id: Option<String>,
    /// xsi:nil attribute
    pub is_nil: bool,
}

#[derive(Debug, PartialEq, Eq)]
pub struct RawTupleFact {
    /// QName of the corresponding concept
    pub name: QName,
    /// id attribute
    pub id: Option<String>,
    /// xsi:nil attribute
    pub is_nil: bool,
    /// Child facts (items or nested tuples)
    pub children: Vec<RawFact>,
}

/// A locator in a footnote link, usually a `link:loc` element.
#[derive(Debug, PartialEq, Eq)]
pub struct Locator {
    /// Local name of the locator element (e.g. `loc` or a custom element).
    pub label: String,
    /// Optional `xlink:href` target, typically a same-document fragment.
    pub href: String,
}

#[derive(Debug, PartialEq, Eq)]
pub struct RawFootnoteLink {
    pub role: String,
    pub locators: Vec<Locator>,
    pub arcs: Vec<FootnoteArc>,
    pub footnotes: Vec<FootnoteResource>,
}

#[derive(Debug, PartialEq, Eq)]
pub struct FootnoteArc {
    pub from: String,
    pub to: String,
}

#[derive(Debug, PartialEq, Eq)]
pub struct FootnoteResource {
    pub label: String,
    pub lang: Option<String>,
    pub text: String,
}

#[derive(Debug, PartialEq, Eq, Default)]
pub struct RawInstance {
    /// Namespace declarations (prefix -> URI)
    pub namespaces: HashMap<NamespacePrefix, NamespaceUri>,
    /// Schema references
    pub schema_refs: Vec<SchemaRef>,
    /// Role references
    ///
    /// Usually defined in the linkbase document, but can also be present in the
    /// instance document.
    pub role_refs: Vec<RoleRef>,
    /// Arcrole references
    ///
    /// Usually defined in the linkbase document, but can also be present in the
    /// instance document.
    pub arcrole_refs: Vec<ArcroleRef>,
    /// Context definitions
    pub contexts: Vec<RawContext>,
    /// Unit definitions
    pub units: Vec<RawUnit>,
    /// All facts
    pub facts: Vec<RawFact>,
    /// Optional footnote links
    pub footnote_links: Vec<RawFootnoteLink>,
}

impl RawInstance {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        namespaces: HashMap<NamespacePrefix, NamespaceUri>,
        schema_refs: Vec<SchemaRef>,
        role_refs: Vec<RoleRef>,
        arcrole_refs: Vec<ArcroleRef>,
        contexts: Vec<RawContext>,
        units: Vec<RawUnit>,
        facts: Vec<RawFact>,
        footnote_links: Vec<RawFootnoteLink>,
    ) -> Self {
        Self {
            namespaces,
            schema_refs,
            role_refs,
            arcrole_refs,
            contexts,
            units,
            facts,
            footnote_links,
        }
    }
}

/// The parser for XBRL instance documents.
pub struct InstanceParser<R> {
    /// The XML reader for the instance document.
    reader: Reader<R>,
    /// Path of the currently parsed instance file if available. Used for error
    /// reporting.
    path: Option<PathBuf>,
    /// Flag to indicate if the root element is an XBRL instance element.
    is_xbrl_root: bool,
}

impl InstanceParser<BufReader<File>> {
    /// Creates a new `InstanceParser` from the given file path.
    pub fn from_file(path: &Path) -> Result<Self, XbrlError> {
        let file = File::open(path).map_err(|err| XbrlError::FileOpen {
            path: path.to_path_buf(),
            source: err,
        })?;
        let reader = Reader::from_reader(BufReader::new(file));

        Ok(Self {
            path: Some(path.to_path_buf()),
            reader,
            is_xbrl_root: false,
        })
    }
}

impl<R: BufRead> InstanceParser<R> {
    /// Creates a new `InstanceParser` with the given reader and file path.
    pub fn new(reader: Reader<R>, path: Option<PathBuf>, is_xbrl_root: bool) -> Self {
        Self {
            reader,
            path,
            is_xbrl_root,
        }
    }

    /// Sets whether the parser enforces `<xbrli:xbrl>` as the document root.
    /// When `true`, any element encountered before `<xbrli:xbrl>` is an error.
    /// When `false` (default), non-XBRL wrapper elements are silently skipped.
    pub fn xbrl_root(mut self, is_xbrl_root: bool) -> Self {
        self.is_xbrl_root = is_xbrl_root;
        self
    }

    /// Creates a new `InstanceParser` from the given reader.
    pub fn from_reader(reader: R) -> Self {
        let mut reader = Reader::from_reader(reader);
        reader.config_mut().trim_text_start = true;
        reader.config_mut().trim_text_end = true;
        Self::new(reader, None, false)
    }

    /// Parses an XBRL instance document from the reader. Path is used for error
    /// reporting.
    pub fn parse(&mut self) -> Result<RawInstance, XbrlError> {
        let mut instance = RawInstance::default();
        let mut has_instance_root = false;
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf) {
                Ok(Event::Start(ref event)) => {
                    let event_name = event.name();
                    let local_name = event_name.local_name();
                    let attributes = event.attributes();

                    match local_name.as_ref() {
                        b"xbrl" => {
                            has_instance_root = true;
                            self.parse_instance_root(&mut instance, attributes)?;
                        }
                        _ if !has_instance_root && self.is_xbrl_root => {
                            return Err(XbrlError::InvalidInstanceDocument {
                                path: self.path.clone(),
                                reason: "expected <xbrli:xbrl> as root element".to_string(),
                            });
                        }
                        b"schemaRef" => self.parse_schema_ref(&mut instance, attributes)?,
                        b"roleRef" => self.parse_role_ref(&mut instance, attributes)?,
                        b"arcroleRef" => self.parse_arcrole_ref(&mut instance, attributes)?,
                        b"context" => self.parse_context(&mut instance, attributes)?,
                        b"unit" => self.parse_unit(&mut instance, attributes)?,
                        b"footnoteLink" => self.parse_footnote_link(&mut instance, attributes)?,
                        _ if has_instance_root && Self::is_fact_element(local_name.as_ref()) => {
                            self.parse_fact(&mut instance, event)?;
                        }
                        _ => {}
                    }
                }
                Ok(Event::Empty(ref event)) => {
                    let local_name = event.name().local_name();
                    let attributes = event.attributes();

                    match local_name.as_ref() {
                        b"xbrl" => {
                            has_instance_root = true;
                            self.parse_instance_root(&mut instance, attributes)?;
                        }
                        _ if !has_instance_root && self.is_xbrl_root => {
                            return Err(XbrlError::InvalidInstanceDocument {
                                path: self.path.clone(),
                                reason: "expected <xbrli:xbrl> as root element".to_string(),
                            });
                        }
                        b"schemaRef" => self.parse_schema_ref(&mut instance, attributes)?,
                        b"roleRef" => self.parse_role_ref(&mut instance, attributes)?,
                        b"arcroleRef" => self.parse_arcrole_ref(&mut instance, attributes)?,
                        _ if has_instance_root && Self::is_fact_element(local_name.as_ref()) => {
                            let fact = self.parse_empty_fact(event)?;
                            instance.facts.push(fact);
                        }
                        _ => {}
                    }
                }
                Ok(Event::End(ref event)) if event.name().local_name().as_ref() == b"xbrl" => {
                    break;
                }
                Ok(Event::End(_)) => {}
                Ok(Event::Text(_)) => {}
                Ok(Event::Eof) => break,
                Err(err) => {
                    return Err(XbrlError::XmlParse {
                        path: self.path.clone(),
                        position: self.reader.buffer_position(),
                        element: Some("schema".to_string()),
                        source: err,
                    });
                }
                _ => {}
            }
        }

        if !has_instance_root {
            return Err(XbrlError::InvalidInstanceDocument {
                path: self.path.clone(),
                reason: "missing <xbrli:xbrl> root element".to_string(),
            });
        }

        Ok(instance)
    }

    /// Parses the root <xbrli:xbrl> element to extract namespace declarations.
    fn parse_instance_root(
        &mut self,
        instance: &mut RawInstance,
        attributes: Attributes,
    ) -> Result<(), XbrlError> {
        for attribute in attributes {
            let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                path: self.path.clone(),
                position: self.reader.buffer_position(),
                element: Some("xbrl".to_string()),
                source: err.into(),
            })?;
            let key = attribute.key;

            if let Some(prefix) = key.prefix()
                && prefix.as_ref() == b"xmlns"
            {
                let local = key.local_name();
                let namespace_prefix = str::from_utf8(local.as_ref())?;
                let uri = attribute.decode_and_unescape_value(self.reader.decoder())?;
                instance.namespaces.insert(
                    NamespacePrefix::from(namespace_prefix),
                    NamespaceUri::from(uri.into_owned()),
                );
            }
        }

        Ok(())
    }

    /// Parse the `link:schemaRef` element to extract the schema reference.
    fn parse_schema_ref(
        &mut self,
        instance: &mut RawInstance,
        attributes: Attributes,
    ) -> Result<(), XbrlError> {
        for attribute in attributes {
            let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                path: self.path.clone(),
                position: self.reader.buffer_position(),
                element: Some("schemaRef".to_string()),
                source: err.into(),
            })?;

            if attribute.key.local_name().as_ref() == b"href" {
                let value = attribute.decode_and_unescape_value(self.reader.decoder())?;
                instance.schema_refs.push(SchemaRef {
                    href: value.into_owned(),
                });
                return Ok(());
            }
        }

        Err(XbrlError::InvalidInstanceDocument {
            path: self.path.clone(),
            reason: "missing xlink:href in link:schemaRef".to_string(),
        })
    }

    /// Parse the `link:roleRef` element to extract the role reference.
    fn parse_role_ref(
        &mut self,
        instance: &mut RawInstance,
        attributes: Attributes,
    ) -> Result<(), XbrlError> {
        let mut role_uri = None;
        let mut href = None;

        for attribute in attributes {
            let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                path: self.path.clone(),
                position: self.reader.buffer_position(),
                element: Some("roleRef".to_string()),
                source: err.into(),
            })?;
            let local_name = attribute.key.local_name();
            let value = attribute.decode_and_unescape_value(self.reader.decoder())?;

            match local_name.as_ref() {
                b"roleURI" => role_uri = Some(value.into_owned()),
                b"href" => href = Some(value.into_owned()),
                _ => {}
            }
        }

        instance.role_refs.push(RoleRef {
            role_uri: role_uri.ok_or_else(|| XbrlError::InvalidInstanceDocument {
                path: self.path.clone(),
                reason: "missing roleURI in link:roleRef".to_string(),
            })?,
            href: href.ok_or_else(|| XbrlError::InvalidInstanceDocument {
                path: self.path.clone(),
                reason: "missing xlink:href in link:roleRef".to_string(),
            })?,
        });

        Ok(())
    }

    /// Parse the `link:arcroleRef` element to extract the arcrole reference.
    fn parse_arcrole_ref(
        &mut self,
        instance: &mut RawInstance,
        attributes: Attributes,
    ) -> Result<(), XbrlError> {
        let mut arcrole_uri = None;
        let mut href = None;

        for attribute in attributes {
            let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                path: self.path.clone(),
                position: self.reader.buffer_position(),
                element: Some("arcroleRef".to_string()),
                source: err.into(),
            })?;
            let local_name = attribute.key.local_name();
            let value = attribute.decode_and_unescape_value(self.reader.decoder())?;

            match local_name.as_ref() {
                b"arcroleURI" => arcrole_uri = Some(value.into_owned()),
                b"href" => href = Some(value.into_owned()),
                _ => {}
            }
        }

        instance.arcrole_refs.push(ArcroleRef {
            arcrole_uri: arcrole_uri.ok_or_else(|| XbrlError::InvalidInstanceDocument {
                path: self.path.clone(),
                reason: "missing arcroleURI in link:arcroleRef".to_string(),
            })?,
            href: href.ok_or_else(|| XbrlError::InvalidInstanceDocument {
                path: self.path.clone(),
                reason: "missing xlink:href in link:arcroleRef".to_string(),
            })?,
        });

        Ok(())
    }

    /// Parse the `xbrli:context` element to extract the context definition.
    ///
    /// `xbrli:segment` and `xbrli:scenario` elements are parsed as dimensional
    /// containers. `xbrli:segment` is always a child of `xbrli:entity`, while
    /// `xbrli:scenario` is a direct child of `xbrli:context`.
    fn parse_context(
        &mut self,
        instance: &mut RawInstance,
        attributes: Attributes,
    ) -> Result<(), XbrlError> {
        let mut id = None;

        for attribute in attributes {
            let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                path: self.path.clone(),
                position: self.reader.buffer_position(),
                element: Some("context".to_string()),
                source: err.into(),
            })?;

            if attribute.key.local_name().as_ref() == b"id" {
                let value = attribute.decode_and_unescape_value(self.reader.decoder())?;
                id = Some(value.into_owned());
            }
        }

        let id = id.ok_or_else(|| XbrlError::InvalidInstanceDocument {
            path: self.path.clone(),
            reason: "missing id in xbrli:context".to_string(),
        })?;

        let mut entity = None;
        let mut period = None;
        let mut scenario_dimensions = Vec::new();
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf)? {
                Event::Start(ref event) => match event.local_name().as_ref() {
                    b"entity" => {
                        entity = Some(self.parse_entity()?);
                    }
                    b"period" => {
                        period = Some(self.parse_period()?);
                    }
                    b"scenario" => {
                        self.parse_dimensional_container(&mut scenario_dimensions)?;
                    }
                    _ => {}
                },
                Event::End(ref event) if event.local_name().as_ref() == b"context" => break,
                Event::Eof => break,
                _ => {}
            }
            buf.clear();
        }

        instance.contexts.push(RawContext {
            id,
            entity: entity.ok_or_else(|| XbrlError::InvalidInstanceDocument {
                path: self.path.clone(),
                reason: "missing entity in xbrli:context".to_string(),
            })?,
            period: period.ok_or_else(|| XbrlError::InvalidInstanceDocument {
                path: self.path.clone(),
                reason: "missing period in xbrli:context".to_string(),
            })?,
            scenario_dimensions,
        });

        Ok(())
    }

    /// Parse the `xbrli:entity` element to extract the entity identifier and
    /// scheme.
    fn parse_entity(&mut self) -> Result<RawEntity, XbrlError> {
        let mut identifier = None;
        let mut scheme = None;
        let mut segment_dimensions = Vec::new();
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf)? {
                Event::Start(ref event) => match event.local_name().as_ref() {
                    b"identifier" => {
                        for attribute in event.attributes() {
                            let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                                path: self.path.clone(),
                                position: self.reader.buffer_position(),
                                element: Some("identifier".to_string()),
                                source: err.into(),
                            })?;

                            if attribute.key.local_name().as_ref() == b"scheme" {
                                let value =
                                    attribute.decode_and_unescape_value(self.reader.decoder())?;
                                scheme = Some(value.into_owned());
                            }
                        }
                    }
                    b"segment" => {
                        self.parse_dimensional_container(&mut segment_dimensions)?;
                    }
                    _ => {}
                },
                Event::Text(ref text) if identifier.is_none() => {
                    let value = text.xml_content().map_err(quick_xml::Error::from)?;
                    identifier = Some(value.into_owned());
                }
                Event::End(ref event) if event.local_name().as_ref() == b"entity" => break,
                Event::Eof => break,
                _ => {}
            }
            buf.clear();
        }

        Ok(RawEntity {
            // Keep parsing tolerant and report missing identifier/scheme during
            // validation as spec-level errors.
            identifier: identifier.unwrap_or_default(),
            scheme: scheme.unwrap_or_default(),
            segment_dimensions,
        })
    }

    /// Parse the `xbrli:period` element to extract the period definition.
    fn parse_period(&mut self) -> Result<RawPeriod, XbrlError> {
        let mut instant = None;
        let mut start_date = None;
        let mut end_date = None;
        let mut is_forever = false;
        let mut current_tag: Option<String> = None;
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf)? {
                Event::Start(ref event) | Event::Empty(ref event) => {
                    match event.local_name().as_ref() {
                        b"instant" => current_tag = Some("instant".to_string()),
                        b"startDate" => current_tag = Some("startDate".to_string()),
                        b"endDate" => current_tag = Some("endDate".to_string()),
                        b"forever" => is_forever = true,
                        _ => {}
                    }
                }
                Event::Text(ref text) => {
                    let value = text
                        .xml_content()
                        .map_err(quick_xml::Error::from)?
                        .into_owned();
                    match current_tag.as_deref() {
                        Some("instant") => instant = Some(value),
                        Some("startDate") => start_date = Some(value),
                        Some("endDate") => end_date = Some(value),
                        _ => {}
                    }
                }
                Event::End(ref event) => match event.local_name().as_ref() {
                    b"period" => break,
                    _ => current_tag = None,
                },
                Event::Eof => break,
                _ => {}
            }
            buf.clear();
        }

        if is_forever {
            Ok(RawPeriod::Forever)
        } else if let Some(instant) = instant {
            Ok(RawPeriod::Instant(instant))
        } else if let (Some(start_date), Some(end_date)) = (start_date, end_date) {
            Ok(RawPeriod::Duration {
                start_date,
                end_date,
            })
        } else {
            Err(XbrlError::InvalidInstanceDocument {
                path: self.path.clone(),
                reason: "invalid period in xbrli:context".to_string(),
            })
        }
    }

    /// Parse the dimensions defined in a `scenario` or `segment` element.
    fn parse_dimensional_container(
        &mut self,
        dimensions: &mut Vec<RawDimension>,
    ) -> Result<(), XbrlError> {
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf)? {
                Event::Start(ref event) | Event::Empty(ref event)
                    if event.local_name().as_ref() == b"explicitMember" =>
                {
                    let mut dimension = None;

                    for attribute in event.attributes() {
                        let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                            path: self.path.clone(),
                            position: self.reader.buffer_position(),
                            element: Some("explicitMember".to_string()),
                            source: err.into(),
                        })?;

                        if attribute.key.local_name().as_ref() == b"dimension" {
                            let value =
                                attribute.decode_and_unescape_value(self.reader.decoder())?;
                            dimension = Some(parse_qname(&value));
                        }
                    }

                    if let Some(dimension) = dimension {
                        let mut member_buf = Vec::new();

                        if let Event::Text(ref text) =
                            self.reader.read_event_into(&mut member_buf)?
                        {
                            let member = text.xml_content().map_err(quick_xml::Error::from)?;
                            let member = parse_qname(member.trim());
                            dimensions.push(RawDimension { dimension, member });
                        }
                    }
                }
                Event::End(ref event)
                    if matches!(event.local_name().as_ref(), b"scenario" | b"segment") =>
                {
                    break;
                }
                Event::Eof => break,
                _ => {}
            }
            buf.clear();
        }

        Ok(())
    }

    /// Parse the `xbrli:unit` element to extract the unit definition, including
    /// measures and divide units.
    fn parse_unit(
        &mut self,
        instance: &mut RawInstance,
        attributes: Attributes,
    ) -> Result<(), XbrlError> {
        let mut id = None;

        for attribute in attributes {
            let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                path: self.path.clone(),
                position: self.reader.buffer_position(),
                element: Some("unit".to_string()),
                source: err.into(),
            })?;

            if attribute.key.local_name().as_ref() == b"id" {
                let value = attribute.decode_and_unescape_value(self.reader.decoder())?;
                id = Some(value.into_owned());
            }
        }

        let id = id.ok_or_else(|| XbrlError::InvalidInstanceDocument {
            path: self.path.clone(),
            reason: "missing id in xbrli:unit".to_string(),
        })?;
        let mut numerator = Vec::new();
        let mut denominator = Vec::new();
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf)? {
                Event::Start(ref event) => match event.local_name().as_ref() {
                    b"measure" => {
                        let mut text_buf = Vec::new();
                        if let Event::Text(ref text) = self.reader.read_event_into(&mut text_buf)? {
                            let value = text.xml_content().map_err(quick_xml::Error::from)?;
                            let qname = xml::parse_qname(&value);
                            numerator.push(qname);
                        }
                    }
                    b"divide" => {
                        self.parse_unit_divide(&mut numerator, &mut denominator)?;
                    }
                    _ => {}
                },
                Event::End(ref event) if event.local_name().as_ref() == b"unit" => break,
                Event::Eof => break,
                _ => {}
            }
            buf.clear();
        }

        instance.units.push(RawUnit {
            id,
            numerator,
            denominator,
        });

        Ok(())
    }

    /// Parse the `divide` element inside a `unit` to extract the numerator and
    /// denominator measures.
    fn parse_unit_divide(
        &mut self,
        numerator: &mut Vec<QName>,
        denominator: &mut Vec<QName>,
    ) -> Result<(), XbrlError> {
        let mut in_numerator = false;
        let mut in_denominator = false;
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf)? {
                Event::Start(ref event) => match event.local_name().as_ref() {
                    b"unitNumerator" => in_numerator = true,
                    b"unitDenominator" => in_denominator = true,
                    b"measure" => {
                        let mut text_buf = Vec::new();
                        if let Event::Text(ref text) = self.reader.read_event_into(&mut text_buf)? {
                            let value = text.xml_content().map_err(quick_xml::Error::from)?;
                            let qname = xml::parse_qname(&value);
                            if in_numerator {
                                numerator.push(qname);
                            } else if in_denominator {
                                denominator.push(qname);
                            }
                        }
                    }
                    _ => {}
                },
                Event::End(ref event) => match event.local_name().as_ref() {
                    b"unitNumerator" => in_numerator = false,
                    b"unitDenominator" => in_denominator = false,
                    b"divide" => break,
                    _ => {}
                },
                Event::Eof => break,
                _ => {}
            }
            buf.clear();
        }

        Ok(())
    }

    /// Check if a local element name represents a fact (as opposed to a
    /// structural XBRL element like context, unit, schemaRef, etc.).
    fn is_fact_element(local_name: &[u8]) -> bool {
        !matches!(
            local_name,
            b"xbrl"
                | b"context"
                | b"unit"
                | b"schemaRef"
                | b"roleRef"
                | b"arcroleRef"
                | b"identifier"
                | b"entity"
                | b"period"
                | b"instant"
                | b"startDate"
                | b"endDate"
                | b"scenario"
                | b"segment"
                | b"explicitMember"
                | b"measure"
                | b"footnoteLink"
                | b"footnote"
                | b"footnoteArc"
                | b"loc"
                | b"forever"
                | b"unitNumerator"
                | b"unitDenominator"
                | b"divide"
        )
    }

    /// Parse a fact element (item or tuple).
    ///
    /// If `contextRef` is present the element is an item fact; otherwise it is
    /// a tuple fact whose children are parsed recursively.
    fn parse_fact(
        &mut self,
        instance: &mut RawInstance,
        event: &BytesStart,
    ) -> Result<(), XbrlError> {
        let fact = self.parse_fact_recursive(event)?;

        if let Some(fact) = fact {
            instance.facts.push(fact);
        }

        Ok(())
    }

    /// Recursively parse a single fact element, returning `None` for
    /// self-closing elements without `contextRef` that have no children
    /// (empty tuples are still returned).
    fn parse_fact_recursive(&mut self, event: &BytesStart) -> Result<Option<RawFact>, XbrlError> {
        let name = parse_qname(std::str::from_utf8(event.name().as_ref())?);

        let mut context_ref = None;
        let mut unit_ref = None;
        let mut decimals = None;
        let mut precision = None;
        let mut id = None;
        let mut is_nil = false;

        for attribute in event.attributes() {
            let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                path: self.path.clone(),
                position: self.reader.buffer_position(),
                element: Some(name.to_string()),
                source: err.into(),
            })?;
            let local_name = attribute.key.local_name();
            let value = attribute.decode_and_unescape_value(self.reader.decoder())?;

            match local_name.as_ref() {
                b"contextRef" => context_ref = Some(value.into_owned()),
                b"unitRef" => unit_ref = Some(value.into_owned()),
                b"decimals" => decimals = Some(value.into_owned()),
                b"precision" => precision = Some(value.into_owned()),
                b"id" => id = Some(value.into_owned()),
                b"nil" => is_nil = value.as_ref() == "true",
                _ => {}
            }
        }

        if let Some(context_ref) = context_ref {
            let mut value = String::new();
            let mut buf = Vec::new();

            // Item fact: read text value until closing tag
            loop {
                match self.reader.read_event_into(&mut buf)? {
                    Event::Text(ref text) => {
                        let decoded = text.xml_content().map_err(quick_xml::Error::from)?;
                        value.push_str(&decoded);
                    }
                    Event::End(ref end) if end.name().as_ref() == event.name().as_ref() => break,
                    Event::Eof => break,
                    _ => {}
                }
                buf.clear();
            }

            // Normalize line breaks and collapse repeated whitespace
            let value = value.replace(['\n', '\r'], "");
            let value = value.split_whitespace().collect::<Vec<_>>().join(" ");

            Ok(Some(RawFact::Item(RawItemFact {
                name,
                value,
                context_ref,
                unit_ref,
                decimals,
                precision,
                id,
                is_nil,
            })))
        } else {
            let mut children = Vec::new();
            let mut buf = Vec::new();

            // Tuple fact: recursively parse child facts until closing tag
            loop {
                match self.reader.read_event_into(&mut buf)? {
                    Event::Start(ref child_event)
                        if Self::is_fact_element(child_event.name().local_name().as_ref()) =>
                    {
                        if let Some(child) = self.parse_fact_recursive(child_event)? {
                            children.push(child);
                        }
                    }
                    Event::Empty(ref child_event)
                        if Self::is_fact_element(child_event.name().local_name().as_ref()) =>
                    {
                        children.push(self.parse_empty_fact(child_event)?);
                    }
                    Event::End(ref end) if end.name().as_ref() == event.name().as_ref() => break,
                    Event::Eof => break,
                    _ => {}
                }
                buf.clear();
            }

            Ok(Some(RawFact::Tuple(RawTupleFact {
                name,
                id,
                is_nil,
                children,
            })))
        }
    }

    /// Parse a self-closing (empty) fact element.
    fn parse_empty_fact(&mut self, event: &BytesStart) -> Result<RawFact, XbrlError> {
        let name = parse_qname(std::str::from_utf8(event.name().as_ref())?);

        let mut context_ref = None;
        let mut unit_ref = None;
        let mut decimals = None;
        let mut precision = None;
        let mut id = None;
        let mut is_nil = false;

        for attribute in event.attributes() {
            let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                path: self.path.clone(),
                position: self.reader.buffer_position(),
                element: Some(name.to_string()),
                source: err.into(),
            })?;
            let local_name = attribute.key.local_name();
            let value = attribute.decode_and_unescape_value(self.reader.decoder())?;

            match local_name.as_ref() {
                b"contextRef" => context_ref = Some(value.into_owned()),
                b"unitRef" => unit_ref = Some(value.into_owned()),
                b"decimals" => decimals = Some(value.into_owned()),
                b"precision" => precision = Some(value.into_owned()),
                b"id" => id = Some(value.into_owned()),
                b"nil" => is_nil = value.as_ref() == "true",
                _ => {}
            }
        }

        if let Some(context_ref) = context_ref {
            Ok(RawFact::Item(RawItemFact {
                name,
                value: String::new(),
                context_ref,
                unit_ref,
                decimals,
                precision,
                id,
                is_nil,
            }))
        } else {
            Ok(RawFact::Tuple(RawTupleFact {
                name,
                id,
                is_nil,
                children: Vec::new(),
            }))
        }
    }

    /// Parse the `link:footnoteLink` element to extract the footnote link.
    fn parse_footnote_link(
        &mut self,
        instance: &mut RawInstance,
        attributes: Attributes,
    ) -> Result<(), XbrlError> {
        let mut role = String::new();

        for attribute in attributes {
            let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                path: self.path.clone(),
                position: self.reader.buffer_position(),
                element: Some("footnoteLink".to_string()),
                source: err.into(),
            })?;

            if attribute.key.local_name().as_ref() == b"role" {
                let value = attribute.decode_and_unescape_value(self.reader.decoder())?;
                role = value.into_owned();
            }
        }

        let mut locators = Vec::new();
        let mut arcs = Vec::new();
        let mut footnotes = Vec::new();
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf)? {
                Event::Start(ref event) | Event::Empty(ref event) => {
                    match event.local_name().as_ref() {
                        b"loc" => {
                            let mut label = None;
                            let mut href = None;

                            for attribute in event.attributes() {
                                let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                                    path: self.path.clone(),
                                    position: self.reader.buffer_position(),
                                    element: Some("loc".to_string()),
                                    source: err.into(),
                                })?;
                                let local_name = attribute.key.local_name();
                                let value =
                                    attribute.decode_and_unescape_value(self.reader.decoder())?;

                                match local_name.as_ref() {
                                    b"label" => label = Some(value.into_owned()),
                                    b"href" => href = Some(value.into_owned()),
                                    _ => {}
                                }
                            }

                            if let (Some(label), Some(href)) = (label, href) {
                                locators.push(Locator { label, href });
                            }
                        }
                        b"footnoteArc" => {
                            let mut from = None;
                            let mut to = None;

                            for attribute in event.attributes() {
                                let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                                    path: self.path.clone(),
                                    position: self.reader.buffer_position(),
                                    element: Some("footnoteArc".to_string()),
                                    source: err.into(),
                                })?;
                                let local_name = attribute.key.local_name();
                                let value =
                                    attribute.decode_and_unescape_value(self.reader.decoder())?;

                                match local_name.as_ref() {
                                    b"from" => from = Some(value.into_owned()),
                                    b"to" => to = Some(value.into_owned()),
                                    _ => {}
                                }
                            }

                            if let (Some(from), Some(to)) = (from, to) {
                                arcs.push(FootnoteArc { from, to });
                            }
                        }
                        b"footnote" => {
                            let mut label = None;
                            let mut lang = None;

                            for attribute in event.attributes() {
                                let attribute = attribute.map_err(|err| XbrlError::XmlParse {
                                    path: self.path.clone(),
                                    position: self.reader.buffer_position(),
                                    element: Some("footnote".to_string()),
                                    source: err.into(),
                                })?;
                                let local_name = attribute.key.local_name();
                                let value =
                                    attribute.decode_and_unescape_value(self.reader.decoder())?;

                                match local_name.as_ref() {
                                    b"label" => label = Some(value.into_owned()),
                                    b"lang" => lang = Some(value.into_owned()),
                                    _ => {}
                                }
                            }

                            // Read footnote text content
                            let mut text = String::new();
                            let mut text_buf = Vec::new();
                            loop {
                                match self.reader.read_event_into(&mut text_buf)? {
                                    Event::Text(ref t) => {
                                        let decoded =
                                            t.xml_content().map_err(quick_xml::Error::from)?;
                                        text.push_str(&decoded);
                                    }
                                    Event::End(ref e) if e.local_name().as_ref() == b"footnote" => {
                                        break;
                                    }
                                    Event::Eof => break,
                                    _ => {}
                                }
                                text_buf.clear();
                            }

                            if let Some(label) = label {
                                footnotes.push(FootnoteResource {
                                    label,
                                    lang,
                                    text: text.trim().to_string(),
                                });
                            }
                        }
                        _ => {}
                    }
                }
                Event::End(ref event) if event.local_name().as_ref() == b"footnoteLink" => {
                    break;
                }
                Event::Eof => break,
                _ => {}
            }
            buf.clear();
        }

        instance.footnote_links.push(RawFootnoteLink {
            role,
            locators,
            arcs,
            footnotes,
        });

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_matches::assert_matches;
    use std::str::FromStr;

    #[test]
    fn test_parse_non_instance_root() {
        let xml = r#"<root>
                                <xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                                    xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                                </xbrli:xbrl>
                            </root>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.namespaces.len(), 2);
        assert_eq!(
            instance
                .namespaces
                .get(&NamespacePrefix::from("xbrli"))
                .unwrap(),
            &NamespaceUri::from("http://www.xbrl.org/2003/instance")
        );
        assert_eq!(
            instance
                .namespaces
                .get(&NamespacePrefix::from("ifrs"))
                .unwrap(),
            &NamespaceUri::from("http://xbrl.ifrs.org/taxonomy/2023")
        );
    }

    #[test]
    fn test_parse_non_instance_root_strict() {
        let xml = r#"<root>
                                <xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                                    xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                                </xbrli:xbrl>
                            </root>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes()).xbrl_root(true);
        let res = parser.parse();

        assert_matches!(res, Err(XbrlError::InvalidInstanceDocument { reason, .. }) if reason == "expected <xbrli:xbrl> as root element");
    }

    #[test]
    fn test_parse_instance_root() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                            xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                        </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.namespaces.len(), 2);
        assert_eq!(
            instance
                .namespaces
                .get(&NamespacePrefix::from("xbrli"))
                .unwrap(),
            &NamespaceUri::from("http://www.xbrl.org/2003/instance")
        );
        assert_eq!(
            instance
                .namespaces
                .get(&NamespacePrefix::from("ifrs"))
                .unwrap(),
            &NamespaceUri::from("http://xbrl.ifrs.org/taxonomy/2023")
        );
    }

    #[test]
    fn test_parse_schema_ref() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                            xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                            <link:schemaRef xlink:href="ifrs.xsd" />
                        </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.schema_refs.len(), 1);
        assert_eq!(instance.schema_refs[0].href, "ifrs.xsd");
    }

    #[test]
    fn test_parse_role_ref() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                            xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                            <link:roleRef roleURI="http://example.com/role" xlink:href="role.xml" />
                        </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.role_refs.len(), 1);
        assert_eq!(instance.role_refs[0].role_uri, "http://example.com/role");
        assert_eq!(instance.role_refs[0].href, "role.xml");
    }

    #[test]
    fn test_parse_arcrole_ref() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                            xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                            <link:arcroleRef arcroleURI="http://example.com/arcrole" xlink:href="arcrole.xml" />
                        </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.arcrole_refs.len(), 1);
        assert_eq!(
            instance.arcrole_refs[0].arcrole_uri,
            "http://example.com/arcrole"
        );
        assert_eq!(instance.arcrole_refs[0].href, "arcrole.xml");
    }

    #[test]
    fn test_parse_context() {
        let xml = r#"<xbrli:xbrl
                                xmlns:xbrli="http://www.xbrl.org/2003/instance"
                                xmlns:xbrldi="http://xbrl.org/2006/xbrldi"
                                xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                                <context id="c1">
                                    <entity>
                                        <identifier scheme="http://example.com">ABC</identifier>
                                        <segment>
                                            <xbrldi:explicitMember dimension="ifrs:OperatingSegmentsAxis">
                                                ifrs:EuropeSegmentMember
                                            </xbrldi:explicitMember>
                                        </segment>
                                    </entity>
                                    <period>
                                        <instant>2024-12-31</instant>
                                    </period>
                                    <scenario>
                                        <xbrldi:explicitMember dimension="ifrs:ProductsAndServicesAxis">
                                            ifrs:SoftwareMember
                                        </xbrldi:explicitMember>
                                    </scenario>
                                </context>
                            </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.contexts.len(), 1);
        let context = &instance.contexts[0];
        assert_eq!(
            context,
            &RawContext {
                id: "c1".to_string(),
                entity: RawEntity {
                    identifier: "ABC".to_string(),
                    scheme: "http://example.com".to_string(),
                    segment_dimensions: vec![RawDimension {
                        dimension: QName::from_str("ifrs:OperatingSegmentsAxis").unwrap(),
                        member: QName::from_str("ifrs:EuropeSegmentMember").unwrap(),
                    }],
                },
                period: RawPeriod::Instant("2024-12-31".to_string()),
                scenario_dimensions: vec![RawDimension {
                    dimension: QName::from_str("ifrs:ProductsAndServicesAxis").unwrap(),
                    member: QName::from_str("ifrs:SoftwareMember").unwrap(),
                }],
            }
        );
    }

    #[test]
    fn test_parse_context_missing_identifier_is_tolerated() {
        let xml = r#"<xbrli:xbrl
                                xmlns:xbrli="http://www.xbrl.org/2003/instance"
                                xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                                <context id="c1">
                                    <entity>
                                        <identifier scheme="http://example.com"></identifier>
                                    </entity>
                                    <period>
                                        <instant>2024-12-31</instant>
                                    </period>
                                </context>
                            </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.contexts.len(), 1);
        let context = &instance.contexts[0];
        assert_eq!(context.entity.identifier, "");
        assert_eq!(context.entity.scheme, "http://example.com");
    }

    #[test]
    fn test_parse_unit() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                            xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                            <unit id="u1">
                                <measure>iso4217:EUR</measure>
                            </unit>
                        </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.units.len(), 1);
        let unit = &instance.units[0];
        assert_eq!(
            unit,
            &RawUnit {
                id: "u1".to_string(),
                numerator: vec![QName::from_str("iso4217:EUR").unwrap()],
                denominator: vec![],
            }
        );
    }

    #[test]
    fn test_parse_unit_divide() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                                xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                                <xbrli:unit id="USD_per_share">
                                    <xbrli:divide>
                                        <xbrli:unitNumerator>
                                            <xbrli:measure>iso4217:USD</xbrli:measure>
                                        </xbrli:unitNumerator>
                                        <xbrli:unitDenominator>
                                            <xbrli:measure>xbrli:shares</xbrli:measure>
                                        </xbrli:unitDenominator>
                                    </xbrli:divide>
                                </xbrli:unit>
                            </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.units.len(), 1);
        let unit = &instance.units[0];
        assert_eq!(
            unit,
            &RawUnit {
                id: "USD_per_share".to_string(),
                numerator: vec![QName::from_str("iso4217:USD").unwrap()],
                denominator: vec![QName::from_str("xbrli:shares").unwrap()],
            }
        );
    }

    #[test]
    fn test_parse_item_fact() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                            xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                            <ifrs:Revenue contextRef="c1" unitRef="u1" decimals="-3">
                                1200000
                            </ifrs:Revenue>
                        </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.facts.len(), 1);
        let fact = &instance.facts[0];
        assert_matches!(fact, RawFact::Item(fact) => {
            assert_eq!(fact.name.to_string(), "ifrs:Revenue");
            assert_eq!(fact.value, "1200000");
            assert_eq!(fact.context_ref, "c1");
            assert_eq!(fact.unit_ref.as_deref(), Some("u1"));
            assert_eq!(fact.decimals.as_deref(), Some("-3"));
            assert!(!fact.is_nil);
        });
    }

    #[test]
    fn test_parse_item_fact_embedded_newlines() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                            xmlns:t="http://example.com/taxonomy">
                            <t:Description contextRef="c1">
                                Revenue 
                                for 
                                the period
                            </t:Description>
                        </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.facts.len(), 1);
        assert_matches!(&instance.facts[0], RawFact::Item(fact) => {
            assert_eq!(fact.name.to_string(), "t:Description");
            assert_eq!(fact.value, "Revenue for the period");
        });
    }

    #[test]
    fn test_parse_tuple_fact() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                                xmlns:t="http://example.com/taxonomy">
                                <t:Address>
                                    <t:Street contextRef="c1">Main Street</t:Street>
                                    <t:City contextRef="c1">Berlin</t:City>
                                </t:Address>
                            </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.facts.len(), 1);
        let fact = &instance.facts[0];
        assert_matches!(fact, RawFact::Tuple(tuple) => {
            assert_eq!(tuple.name.to_string(), "t:Address");
            assert!(!tuple.is_nil);
            assert_eq!(tuple.children.len(), 2);

            assert_matches!(&tuple.children[0], RawFact::Item(item) => {
                assert_eq!(item.name.to_string(), "t:Street");
                assert_eq!(item.value, "Main Street");
                assert_eq!(item.context_ref, "c1");
            });
            assert_matches!(&tuple.children[1], RawFact::Item(item) => {
                assert_eq!(item.name.to_string(), "t:City");
                assert_eq!(item.value, "Berlin");
                assert_eq!(item.context_ref, "c1");
            });
        });
    }

    #[test]
    fn test_parse_nested_tuple() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                                xmlns:t="http://example.com/taxonomy">
                                <t:Outer>
                                    <t:Inner>
                                        <t:Value contextRef="c1">42</t:Value>
                                    </t:Inner>
                                </t:Outer>
                            </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.facts.len(), 1);
        let fact = &instance.facts[0];
        assert_matches!(fact, RawFact::Tuple(outer) => {
            assert_eq!(outer.name.to_string(), "t:Outer");
            assert!(!outer.is_nil);
            assert_eq!(outer.children.len(), 1);

            assert_matches!(&outer.children[0], RawFact::Tuple(inner) => {
                assert_eq!(inner.name.to_string(), "t:Inner");
                assert!(!inner.is_nil);
                assert_eq!(inner.children.len(), 1);

                assert_matches!(&inner.children[0], RawFact::Item(item) => {
                    assert_eq!(item.name.to_string(), "t:Value");
                    assert_eq!(item.value, "42");
                    assert_eq!(item.context_ref, "c1");
                });
            });
        });
    }

    #[test]
    fn test_parse_nil_item_fact() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                            xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                            <ifrs:Revenue contextRef="c1" xsi:nil="true" />
                        </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.facts.len(), 1);
        match &instance.facts[0] {
            RawFact::Item(fact) => {
                assert_eq!(fact.name.to_string(), "ifrs:Revenue");
                assert!(fact.is_nil);
                assert_eq!(fact.value, "");
                assert_eq!(fact.context_ref, "c1");
            }
            RawFact::Tuple(_) => panic!("expected item fact"),
        }
    }

    #[test]
    fn test_parse_empty_tuple() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                            xmlns:t="http://example.com/taxonomy">
                            <t:Address xsi:nil="true" />
                        </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.facts.len(), 1);
        match &instance.facts[0] {
            RawFact::Tuple(tuple) => {
                assert_eq!(tuple.name.to_string(), "t:Address");
                assert!(tuple.is_nil);
                assert!(tuple.children.is_empty());
            }
            RawFact::Item(_) => panic!("expected tuple fact"),
        }
    }

    #[test]
    fn test_parse_footnote_link() {
        let xml = r##"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                            xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                            <link:footnoteLink role="http://example.com/footnote">
                                <link:loc xlink:label="loc1" xlink:href="#c1" />
                                <link:footnote xlink:label="fn1" xml:lang="en">
                                    This is a footnote.
                                </link:footnote>
                                <link:footnoteArc xlink:from="loc1" xlink:to="fn1" />
                            </link:footnoteLink>
                        </xbrli:xbrl>"##;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.footnote_links.len(), 1);
        let footnote_link = &instance.footnote_links[0];
        assert_eq!(
            footnote_link,
            &RawFootnoteLink {
                role: "http://example.com/footnote".to_string(),
                locators: vec![Locator {
                    label: "loc1".to_string(),
                    href: "#c1".to_string(),
                }],
                arcs: vec![FootnoteArc {
                    from: "loc1".to_string(),
                    to: "fn1".to_string(),
                }],
                footnotes: vec![FootnoteResource {
                    label: "fn1".to_string(),
                    lang: Some("en".to_string()),
                    text: "This is a footnote.".to_string(),
                }],
            }
        );
    }

    #[test]
    fn test_parse_instance() {
        let xml = r#"<xbrli:xbrl xmlns:xbrli="http://www.xbrl.org/2003/instance"
                            xmlns:ifrs="http://xbrl.ifrs.org/taxonomy/2023">
                            <link:schemaRef xlink:href="ifrs.xsd" />
                            <context id="c1">
                                <entity>
                                    <identifier scheme="http://example.com">ABC</identifier>
                                </entity>
                                <period>
                                    <instant>2024-12-31</instant>
                                </period>
                            </context>
                            <unit id="u1">
                                <measure>iso4217:EUR</measure>
                            </unit>
                            <ifrs:Revenue contextRef="c1" unitRef="u1" decimals="-3">
                                1200000
                            </ifrs:Revenue>
                        </xbrli:xbrl>"#;
        let mut parser = InstanceParser::from_reader(xml.as_bytes());
        let instance = parser.parse().unwrap();

        assert_eq!(instance.contexts.len(), 1);
        assert_eq!(instance.units.len(), 1);
        assert_eq!(instance.facts.len(), 1);

        assert_eq!(
            instance,
            RawInstance {
                namespaces: {
                    let mut namespaces = HashMap::new();
                    namespaces.insert("xbrli".into(), "http://www.xbrl.org/2003/instance".into());
                    namespaces.insert("ifrs".into(), "http://xbrl.ifrs.org/taxonomy/2023".into());
                    namespaces
                },
                schema_refs: vec![SchemaRef {
                    href: "ifrs.xsd".to_string(),
                }],
                role_refs: vec![],
                arcrole_refs: vec![],
                contexts: vec![RawContext {
                    id: "c1".to_string(),
                    entity: RawEntity {
                        identifier: "ABC".to_string(),
                        scheme: "http://example.com".to_string(),
                        segment_dimensions: vec![],
                    },
                    period: RawPeriod::Instant("2024-12-31".to_string()),
                    scenario_dimensions: vec![],
                }],
                units: vec![RawUnit {
                    id: "u1".to_string(),
                    numerator: vec![QName::from_str("iso4217:EUR").unwrap()],
                    denominator: vec![],
                }],
                facts: vec![RawFact::Item(RawItemFact {
                    name: QName::from_str("ifrs:Revenue").unwrap(),
                    value: "1200000".to_string(),
                    context_ref: "c1".to_string(),
                    unit_ref: Some("u1".to_string()),
                    decimals: Some("-3".to_string()),
                    precision: None,
                    id: None,
                    is_nil: false,
                })],
                footnote_links: vec![],
            }
        );
    }
}