cim-kit 0.4.0

IEC CIM/CGMES for power systems: CIM/XML I/O that reproduces the file set, profile-aware validation, typed RDF export
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
//! Loading and saving whole models.
//!
//! A CGMES model is a set of profile files, so the convenient unit of work is "load
//! these files into one dataset" rather than "parse this document". This module provides
//! that, plus difference-model application and per-profile export.

use std::fs::File;
use std::io::{BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};

use crate::dataset::Dataset;
use crate::error::{Diagnostic, Report, Result, Rule};
use crate::header::{DifferenceModel, ModelHeader, ModelKind, Statement, StatementValue};
use crate::mrid::Mrid;
use crate::object::Object;
use crate::reader::{Budget, ReadOptions, Strictness, read_header, read_into_within};
use crate::schema::{AttrKind, Primitive, ProfileId, Schema};
use crate::value::Value;
use crate::writer::{WriteOptions, write_profile};

/// Outcome of loading one or more files.
#[derive(Debug, Default)]
pub struct LoadReport {
    pub report: Report,
    /// Files loaded, in order, with the header each carried.
    pub files: Vec<(PathBuf, Option<ModelHeader>)>,
    /// Files that could not be read, each also reported as `CIM0022`.
    ///
    /// Non-empty means the model is missing whatever they held: it is assembled from what
    /// could be read, which is the useful answer, but it is not the model the caller named.
    pub failed: Vec<PathBuf>,
    pub objects_read: usize,
}

impl LoadReport {
    pub fn has_errors(&self) -> bool {
        self.report.has_errors()
    }
}

impl Dataset {
    /// Load a set of instance files into a new dataset.
    ///
    /// Files may be given in any order: objects are merged by mRID, so an SSH file read
    /// before its EQ file produces the same result.
    pub fn load<I, P>(schema: &'static Schema, paths: I) -> Result<Dataset>
    where
        I: IntoIterator<Item = P>,
        P: AsRef<Path>,
    {
        let mut ds = Dataset::new(schema);
        ds.load_files(paths, &ReadOptions::lenient())?;
        Ok(ds)
    }

    /// Load files into an existing dataset.
    ///
    /// The files share one input budget ([`ReadOptions::max_input_bytes`]): a model set is
    /// one load, however many files and archive entries it arrives as.
    ///
    /// # Errors
    ///
    /// [`Error::InputTooLarge`](crate::Error::InputTooLarge) under either strictness once
    /// the budget is spent — the dataset then holds part of the model and must be
    /// discarded. Under [`Strictness::Strict`], the first file that cannot be read.
    pub fn load_files<I, P>(&mut self, paths: I, options: &ReadOptions) -> Result<LoadReport>
    where
        I: IntoIterator<Item = P>,
        P: AsRef<Path>,
    {
        let budget = Budget::new(options);
        let mut out = LoadReport::default();
        for path in paths {
            let path = path.as_ref();
            // A model set is several files and one of them being unreadable says nothing
            // about the rest. ENTSO-E's own quality-check corpus contains exactly that
            // case — a six-file set whose Equipment archive holds the text `nonxmlfile` —
            // and aborting the load answered it with a single message that did not even
            // name the file, while the other five were never looked at. Reading is
            // tolerant by default and this is the same rule one level up: record it, name
            // it, carry on. `Strictness::Strict` still refuses.
            match self.load_file_within(path, options, &budget) {
                Ok(one) => {
                    out.report.extend(one.report);
                    out.files.extend(one.files);
                    out.objects_read += one.objects_read;
                }
                // Not the budget, though: a load that stopped there holds part of the model,
                // and recording it as one more unreadable file would hand that part back
                // as a success.
                Err(e) if options.strictness == Strictness::Lenient && !budget.tripped() => {
                    out.failed.push(path.to_path_buf());
                    out.report.push(
                        Diagnostic::error(Rule::UnreadableFile, e.to_string()).with_source(
                            path.file_name()
                                .map(|n| n.to_string_lossy().into_owned())
                                .unwrap_or_else(|| path.display().to_string()),
                        ),
                    );
                }
                Err(e) => return Err(e),
            }
        }
        self.shrink_to_fit();
        Ok(out)
    }

    /// Load one instance file, or every instance file inside a zip archive.
    pub fn load_file(&mut self, path: &Path, options: &ReadOptions) -> Result<LoadReport> {
        self.load_file_within(path, options, &Budget::new(options))
    }

    fn load_file_within(
        &mut self,
        path: &Path,
        options: &ReadOptions,
        budget: &Budget,
    ) -> Result<LoadReport> {
        if path
            .extension()
            .is_some_and(|e| e.eq_ignore_ascii_case("zip"))
        {
            #[cfg(feature = "zip")]
            {
                return self.load_zip_within(path, options, budget);
            }
            #[cfg(not(feature = "zip"))]
            {
                return Err(crate::error::Error::NotCimXml(format!(
                    "{} is a zip archive; enable the `zip` feature to read it",
                    path.display()
                )));
            }
        }

        let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
        let file = File::open(path)?;
        let outcome = read_into_within(
            self,
            BufReader::with_capacity(1 << 16, file),
            name.as_deref(),
            options,
            budget,
        )?;

        let mut report = LoadReport {
            report: outcome.report,
            objects_read: outcome.objects_read,
            files: vec![(path.to_path_buf(), outcome.header.clone())],
            failed: Vec::new(),
        };
        // The reader registers the header itself, so that each object records the file it
        // came from while it is being read.
        if outcome.header.is_none() {
            report.report.push(
                Diagnostic::warning(Rule::MalformedHeader, "file has no md:FullModel header")
                    .with_source(name.unwrap_or_default()),
            );
        }
        Ok(report)
    }

    /// Load every instance file under a directory, in sorted order.
    ///
    /// A CGMES model set is a directory, not a list — that is how the conformity models,
    /// the QoCDC models and every real exchange are shipped — so this is the call most
    /// programs actually want. Naming the files individually is [`Dataset::load`].
    pub fn load_dir(schema: &'static Schema, dir: impl AsRef<Path>) -> Result<Dataset> {
        let mut ds = Dataset::new(schema);
        ds.load_files(instance_files(dir.as_ref()), &ReadOptions::lenient())?;
        Ok(ds)
    }

    /// Load a model set, reading its vintage out of the files themselves.
    ///
    /// The call most programs want. `path` is a directory, a zip archive or a single
    /// instance file; the schema comes from the first document's namespace declarations, so
    /// the caller does not have to know — or hard-code — whether a model is CGMES 3.0 or
    /// 2.4.15.
    ///
    /// Use [`Dataset::load_dir`] or [`Dataset::load`] to state the vintage explicitly, which
    /// is what a program that only ever handles one of them should do.
    ///
    /// # Errors
    ///
    /// [`Error::UnknownVintage`](crate::Error::UnknownVintage) when no file under `path`
    /// declares a vocabulary this build
    /// has a feature for — including when `path` holds no CIM input at all.
    ///
    // An example has to name a vintage only when it names a schema; this one does not, so
    // it compiles under any feature set.
    /// ```no_run
    /// # fn main() -> cim_kit::Result<()> {
    /// let grid = cim_kit::Dataset::open("MicroGrid-BE")?;
    /// println!("{} objects", grid.len());
    /// # Ok(()) }
    /// ```
    pub fn open(path: impl AsRef<Path>) -> Result<Dataset> {
        let path = path.as_ref();
        let files = instance_files(path);
        let schema = detect_vintage(&files).ok_or_else(|| crate::error::Error::UnknownVintage {
            path: path.display().to_string(),
            known: crate::VINTAGES.iter().map(|s| s.vintage).collect(),
        })?;
        let mut ds = Dataset::new(schema);
        ds.load_files(&files, &ReadOptions::lenient())?;
        Ok(ds)
    }

    /// Read only the headers of a set of files, without loading their objects.
    ///
    /// Useful for deciding what to load: headers declare profiles and dependencies.
    pub fn peek_headers<I, P>(
        schema: &'static Schema,
        paths: I,
    ) -> Result<Vec<(PathBuf, Option<ModelHeader>)>>
    where
        I: IntoIterator<Item = P>,
        P: AsRef<Path>,
    {
        let mut out = Vec::new();
        for path in paths {
            let path = path.as_ref();
            let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
            let file = File::open(path)?;
            let header = read_header(schema, BufReader::new(file), name.as_deref())?;
            out.push((path.to_path_buf(), header));
        }
        Ok(out)
    }

    /// Apply a difference model (IEC 61970-552): check it applies to this model, remove
    /// reverse statements, then assert forward statements.
    ///
    /// A change set is a statement about one model state, so it is refused — the report
    /// holds one `CIM0014` error and the dataset is left unchanged — when a model its
    /// `md:Model.Supersedes` names is neither loaded here nor an earlier change set applied
    /// here (compared as identifiers, so spelling does not matter), or when one of its
    /// `dm:preconditions` does not hold. A dataset with no header identifiers, or a change
    /// set naming no base, has nothing to compare and is not checked. A caller who knows
    /// better clears `diff.header.supersedes` or `diff.preconditions`.
    ///
    /// Past that gate, statements naming objects or properties the schema does not know are
    /// reported and skipped rather than aborting the whole application, and a retraction
    /// that does not hold is a warning: published change sets reconcile files that
    /// disagree, so it is evidence rather than grounds to refuse.
    pub fn apply_difference(&mut self, diff: &DifferenceModel) -> Report {
        let schema = self.schema();
        let mut report = Report::default();
        if let Some(refusal) = self.refusal(diff) {
            report.push(refusal);
            return report;
        }
        // Values a difference asserts belong to the profiles its own header declares,
        // exactly as if they had arrived in an instance file. Without that, an export
        // would fall back to the attribute's declaration and could file the change under
        // a profile the change set never claimed.
        let profiles = diff
            .header
            .profiles
            .iter()
            .filter_map(|iri| schema.profile_by_iri(iri))
            .fold(0, |acc, p| acc | p.mask());

        // Retract, then re-type, then assert. The order matters and is the standard's own:
        // a reverse statement talks about the object as it *was*, so it has to be applied
        // while the object still has its old class, and a forward statement talks about
        // what it becomes. The published conformity change sets replace a
        // `LinearShuntCompensator` with a `NonlinearShuntCompensator` under one identifier
        // and then set attributes only the new class has — which is exactly the case that
        // re-typing last would get wrong.
        for s in &diff.reverse {
            self.apply_statement(s, false, profiles, &mut report);
        }
        self.apply_reclassifications(diff, &mut report);
        for s in &diff.forward {
            self.apply_statement(s, true, profiles, &mut report);
        }
        self.record_applied(diff.header.id.clone(), &diff.header.supersedes);
        report
    }

    /// Why `diff` must not be applied to this dataset, if it must not.
    fn refusal(&self, diff: &DifferenceModel) -> Option<Diagnostic> {
        let loaded: Vec<&Mrid> = self.model_ids().collect();
        if !loaded.is_empty()
            && let Some(missing) = diff
                .header
                .supersedes
                .iter()
                .find(|id| !loaded.contains(id))
        {
            let mut held: Vec<String> = loaded.iter().map(|m| m.canonical()).collect();
            held.sort();
            return Some(Diagnostic::error(
                Rule::UnsatisfiedDependency,
                format!(
                    "change set not applied: it supersedes model {}, which is not loaded \
                     (this dataset holds {}); it was computed against another model",
                    missing.canonical(),
                    held.join(", ")
                ),
            ));
        }
        for s in &diff.preconditions {
            let mut scratch = Report::default();
            let holds = self
                .statement_value(s, &mut scratch)
                .is_some_and(|(attr, value)| {
                    self.find(&s.subject)
                        .and_then(|id| self.get(id))
                        .is_some_and(|o| o.values().any(|(a, v)| a == attr && *v == value))
                });
            if !holds {
                return Some(
                    Diagnostic::error(
                        Rule::UnsatisfiedDependency,
                        format!(
                            "change set not applied: its precondition {} {} does not hold",
                            s.predicate,
                            match &s.value {
                                StatementValue::Resource(r) => r.as_str(),
                                StatementValue::Literal(t) => t.as_str(),
                            }
                        ),
                    )
                    .with_object(s.subject.clone()),
                );
            }
        }
        None
    }

    /// Apply class changes named by a difference's forward statements.
    ///
    /// IEC 61970-552 treats an object's type as a statement like any other, so a
    /// difference may replace an object's class. The published CGMES conformity tests do
    /// exactly this, turning a `LinearShuntCompensator` into a `NonlinearShuntCompensator`
    /// under the same identifier; the reverse statements retract the old class's
    /// attributes and the forward ones assert the new class's.
    fn apply_reclassifications(&mut self, diff: &DifferenceModel, report: &mut Report) {
        let schema = self.schema();
        let mut seen: Vec<Mrid> = Vec::new();

        for s in &diff.forward {
            let Some(qname) = &s.class else { continue };
            if seen.contains(&s.subject) {
                continue;
            }
            seen.push(s.subject.clone());

            let Some(target) = schema.find_class(&qname.ns, &qname.local) else {
                report.push(
                    Diagnostic::warning(
                        Rule::UnknownClass,
                        format!("difference names unknown class {}", qname.local),
                    )
                    .with_object(s.subject.clone()),
                );
                continue;
            };
            let Some(id) = self.find(&s.subject) else {
                continue;
            };
            let Some(current) = self.get(id).map(|o| o.class()) else {
                continue;
            };
            if current == target {
                continue;
            }
            // Only a genuine change is applied. Narrowing to a subclass is a refinement
            // and is accepted; anything else is a reclassification worth recording.
            if !schema.is_a(target, current) {
                report.push(
                    Diagnostic::info(
                        Rule::Structure,
                        format!(
                            "difference reclassifies {} from {} to {}",
                            s.subject.canonical(),
                            schema.class(current).name,
                            schema.class(target).name
                        ),
                    )
                    .with_object(s.subject.clone())
                    .with_class(schema.class(target).name),
                );
            }
            // A sideways reclassification leaves the old class's own attributes with
            // nowhere to live. The dataset sheds them so the model stays consistent; what
            // went is reported here, because it is data the change set's author chose to
            // discard and a consumer should be able to see that it happened.
            for slot in self.reclassify(id, target) {
                let def = schema.attr(slot.attr);
                report.push(
                    Diagnostic::warning(
                        Rule::Structure,
                        format!(
                            "{} was dropped: {} does not have it, and the difference \
                             reclassified this object",
                            def.name,
                            schema.class(target).name
                        ),
                    )
                    .with_class(schema.class(target).name)
                    .with_object(s.subject.clone())
                    .with_attribute(def.name),
                );
            }
        }
    }

    /// The attribute and value a difference statement names, resolved against the schema
    /// — one implementation for applying a statement and for checking a precondition.
    fn statement_value(
        &self,
        s: &Statement,
        report: &mut Report,
    ) -> Option<(crate::schema::AttrId, Value)> {
        let schema = self.schema();
        let Some(attr) = schema.find_attr(&s.predicate_ns, &s.predicate) else {
            report.push(
                Diagnostic::warning(
                    Rule::UnknownAttribute,
                    format!(
                        "difference statement names unknown property {}",
                        s.predicate
                    ),
                )
                .with_object(s.subject.clone()),
            );
            return None;
        };
        let def = schema.attr(attr);

        let value = match &s.value {
            StatementValue::Resource(iri) => match def.kind {
                AttrKind::Enumeration(_) => {
                    let Some((ns, local)) = iri.rsplit_once('#') else {
                        report.push(
                            Diagnostic::error(
                                Rule::InvalidValue,
                                format!("enumeration value {iri} is not an IRI"),
                            )
                            .with_attribute(def.name),
                        );
                        return None;
                    };
                    match schema
                        .find_enum_value(&format!("{ns}#"), local)
                        // As in the reader: a misplaced namespace is recoverable.
                        .or_else(|| schema.find_enum_value_any_ns(local))
                    {
                        Some(v) => Value::Enum(v),
                        None => {
                            report.push(
                                Diagnostic::error(
                                    Rule::InvalidValue,
                                    format!("unknown enumeration literal {iri}"),
                                )
                                .with_attribute(def.name)
                                .with_object(s.subject.clone()),
                            );
                            return None;
                        }
                    }
                }
                _ => Value::Reference(Mrid::parse(iri)),
            },
            StatementValue::Literal(text) => {
                let prim = match def.kind {
                    AttrKind::Primitive(p) => p,
                    AttrKind::Datatype(d) => schema.datatype(d).value,
                    _ => Primitive::String,
                };
                match Value::parse_primitive(prim, text) {
                    Ok(v) => v,
                    Err(e) => {
                        report.push(
                            Diagnostic::error(Rule::InvalidValue, e.to_string())
                                .with_attribute(def.name)
                                .with_object(s.subject.clone()),
                        );
                        return None;
                    }
                }
            }
        };
        Some((attr, value))
    }

    fn apply_statement(
        &mut self,
        s: &Statement,
        assert: bool,
        profiles: crate::schema::ProfileMask,
        report: &mut Report,
    ) {
        let schema = self.schema();
        let Some((attr, value)) = self.statement_value(s, report) else {
            return;
        };
        let def = schema.attr(attr);

        // Asserting into an absent object creates it, which a forward difference may
        // legitimately do when it introduces a new object.
        let id = match self.find(&s.subject) {
            Some(id) => id,
            None if assert => {
                let class = s
                    .class
                    .as_ref()
                    .and_then(|c| schema.find_class(&c.ns, &c.local))
                    .unwrap_or(def.owner);
                self.insert(Object::new(class, s.subject.clone()))
            }
            None => {
                report.push(
                    Diagnostic::warning(
                        Rule::DanglingReference,
                        format!(
                            "difference removes from {} which is not in the dataset",
                            s.subject.canonical()
                        ),
                    )
                    .with_attribute(def.name),
                );
                return;
            }
        };

        // The same guard the reader applies to a property element, for the same reason: a
        // value stored under an attribute the object's class does not have is invisible
        // afterwards — the writer emits a class's own attributes and validation checks
        // them, so neither would ever look at it — and it would be dropped without a word
        // on the next export. A difference statement is not more trustworthy than a
        // document just because it arrived as a change set.
        //
        // Assertions only. A *retraction* of such a value is exactly how the model gets
        // rid of one, and refusing it would strand the value it was sent to remove: the
        // published CGMES 2.4.15 Type 4 archive has an object its Equipment file calls a
        // `LinearShuntCompensator` and its Steady State Hypothesis file a
        // `NonlinearShuntCompensator`, and the change set that reconciles them opens by
        // retracting the linear attributes from what is, by then, a nonlinear object.
        let class = self.get(id).map(|o| o.class());
        if assert
            && let Some(class) = class
            && !schema.is_a(class, def.owner)
        {
            report.push(
                Diagnostic::warning(
                    Rule::UnknownAttribute,
                    format!(
                        "difference statement sets {} on {}, which does not have it",
                        def.name,
                        schema.class(class).name
                    ),
                )
                .with_class(schema.class(class).name)
                .with_object(s.subject.clone())
                .with_attribute(def.name),
            );
            return;
        }

        let Some(obj) = self.get_mut(id) else { return };
        if assert {
            if def.mult.is_many() {
                obj.push_in(profiles, attr, value);
            } else {
                obj.set_in(profiles, attr, value);
            }
            obj.mark_profile(profiles);
        } else if !obj.remove_value(attr, &value) {
            report.push(
                Diagnostic::info(
                    Rule::Structure,
                    format!("difference removes {} which was not present", def.name),
                )
                .with_object(s.subject.clone()),
            );
        }
    }

    /// Write one profile of this dataset to a file.
    pub fn save_profile(
        &self,
        path: &Path,
        profile: ProfileId,
        header: Option<ModelHeader>,
    ) -> Result<()> {
        // `IdStyle::Auto` decides per class whether this profile defines the object or
        // only adds to it, which is what IEC 61970-552 means by rdf:ID versus rdf:about.
        // A caller's header wins; without one the writer derives a conforming one.
        let options = match header {
            Some(h) => WriteOptions::default().with_header(h),
            None => WriteOptions::default(),
        };
        let file = File::create(path)?;
        write_profile(
            self,
            profile,
            BufWriter::with_capacity(1 << 16, file),
            &options,
        )
    }

    /// Write every profile the dataset carries data for, into `dir`, one file each.
    ///
    /// Files are named `<stem>_<KEYWORD>.xml`. Use [`Dataset::save_as_loaded`] instead
    /// when the goal is to reproduce the file set the model was read from.
    pub fn save_all_profiles(&self, dir: &Path, stem: &str) -> Result<Vec<PathBuf>> {
        std::fs::create_dir_all(dir)?;
        let mut written = Vec::new();
        // Once for the export, not once per profile: deriving a header needs the model's
        // content identifier, and computing that walks the whole model.
        let content = self.content_id();
        for cov in crate::validate::profile_coverage(self) {
            if cov.objects == 0 {
                continue;
            }
            let path = dir.join(format!("{stem}_{}.xml", cov.keyword));
            let header =
                crate::writer::derive_header_with(self.schema(), cov.profile.mask(), &content);
            self.save_profile(&path, cov.profile, Some(header))?;
            written.push(path);
        }
        Ok(written)
    }

    /// Write the model back out as the file set it was read from.
    ///
    /// One output file per loaded header, carrying that header, the profiles it declared
    /// and the objects that came from it. CGMES normally exchanges Equipment, Operation
    /// and ShortCircuit in a single file; splitting them apart would be legal but would
    /// not reproduce the input, so this is the faithful export.
    ///
    /// Selecting by profile alone is not enough for a merged common grid model, where two
    /// modelling authorities each contribute an Equipment file: every object would then
    /// land in both. The dataset therefore records which file contributed each object —
    /// see [`Dataset::objects_from`] — and each header writes its own. Objects built
    /// programmatically belong to no file and go with the first header whose profiles can
    /// carry them, rather than being dropped.
    ///
    /// Returns the paths written. A header without a resolvable profile is skipped and
    /// named in the report, and the objects that came only from it are counted in
    /// [`SaveReport::unwritten`] — this is a faithful reproduction of a file set, so where
    /// there is no file to reproduce, nothing is invented. [`Dataset::save_all_profiles`]
    /// is the export that always writes something.
    pub fn save_as_loaded(&self, dir: &Path) -> Result<SaveReport> {
        std::fs::create_dir_all(dir)?;
        let schema = self.schema();
        let mut out = SaveReport::default();

        // Objects built programmatically belong to no file; they go with the first file
        // whose profiles can carry them, rather than being dropped.
        let unsourced: Vec<crate::dataset::ObjectId> = self
            .iter()
            .filter(|(_, o)| !o.from_file())
            .map(|(id, _)| id)
            .collect();
        let mut unsourced_placed = false;
        let mut used_names: Vec<String> = Vec::new();
        // Which objects reached a file. A header this schema cannot resolve a profile for
        // writes nothing, and its objects would otherwise leave in silence — the failure
        // this counts is a whole model exporting as an empty directory and a success.
        let mut covered = vec![false; self.len()];
        let mark = |ids: &[crate::dataset::ObjectId], covered: &mut Vec<bool>| {
            for id in ids {
                if let Some(slot) = covered.get_mut(id.index()) {
                    *slot = true;
                }
            }
        };

        for (i, header) in self.headers().iter().enumerate() {
            let profiles = header
                .profiles
                .iter()
                .filter_map(|iri| schema.profile_by_iri(iri))
                .fold(0, |acc, p| acc | p.mask());
            if profiles == 0 {
                out.skipped.push(
                    header
                        .source
                        .clone()
                        .unwrap_or_else(|| format!("header {i}")),
                );
                continue;
            }

            // Reuse the source file name so a directory can be regenerated in place —
            // unless another header already claimed it. Two headers can want the same
            // name: `save_as_loaded` keeps only the final path component (a zip entry
            // name is chosen by whoever built the archive), so a merged model assembled
            // from `BE/EQ.xml` and `NL/EQ.xml` would otherwise write one file, silently
            // lose an authority's equipment, and report the same path twice as written.
            let name = unique_name(
                header
                    .source
                    .as_deref()
                    .and_then(output_file_name)
                    .unwrap_or_else(|| format!("model_{i}.xml")),
                &mut used_names,
            );
            let path = dir.join(&name);
            let file = File::create(&path)?;
            let sink = BufWriter::with_capacity(1 << 16, file);
            let options = WriteOptions {
                profiles,
                header: crate::writer::HeaderSource::Given(Box::new(header.clone())),
                ..Default::default()
            };

            if header.kind == ModelKind::Difference {
                // A change file holds statements, not objects, so the statements have to be
                // matched to the header: by identifier, or failing that by the document both
                // were read from — a `dm:DifferenceModel` with no `rdf:about` has no
                // identifier to match on.
                let diff = self
                    .differences()
                    .iter()
                    .find(|d| d.header.id.is_some() && d.header.id == header.id)
                    .or_else(|| {
                        self.differences()
                            .iter()
                            .find(|d| d.header.source.is_some() && d.header.source == header.source)
                    });
                match diff {
                    Some(d) => crate::writer::write_difference(schema, d, sink, &options)?,
                    None => {
                        out.skipped
                            .push(format!("{name}: difference statements were not retained"));
                        continue;
                    }
                }
                out.written.push(path);
                continue;
            }

            // Everything the file carried, whether or not it said anything about it.
            // Membership is recorded when the element is read; whether the object has a
            // value in this file's profiles is an inference, and it is wrong for a shape
            // boundary sets use constantly — `<cim:ConnectivityNode rdf:ID="_x"/>` with no
            // property children, introduced here and described by Topology Boundary (D55).
            let mut ids: Vec<_> = self.objects_from(i).collect();
            if !unsourced_placed && !unsourced.is_empty() {
                let before = ids.len();
                ids.extend(unsourced.iter().copied().filter(|&id| {
                    self.get(id)
                        .is_some_and(|o| crate::writer::object_has_content_in(schema, o, profiles))
                }));
                unsourced_placed = ids.len() > before;
            }

            mark(&ids, &mut covered);
            crate::writer::write_objects(self, ids.into_iter(), sink, &options)?;
            out.written.push(path);
        }

        out.unwritten = self
            .iter()
            .filter(|(id, _)| !covered.get(id.index()).copied().unwrap_or(false))
            .count();
        Ok(out)
    }
}

/// The schema vintage a set of inputs declares, taken from the first file that answers.
///
/// The first file is not necessarily the one that can be read: ENTSO-E's quality-check
/// corpus has a six-file set whose *Equipment* archive is deliberately not XML, and taking
/// only the first answer there means reading five CGMES 2.4.15 files as CGMES 3.0 — 211
/// unknown-class warnings and an empty model, which is what `CIM0021` exists to prevent.
///
/// One function rather than one per caller, because [`Dataset::open`] walked the whole list
/// and the `cim` tool looked at exactly one, and the difference was invisible until a file
/// that could not be read happened to come first.
pub fn detect_vintage<I, P>(paths: I) -> Option<&'static Schema>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    paths.into_iter().find_map(|p| detect_file(p.as_ref()))
}

/// The schema vintage a file declares, or `None` if it cannot be read or is unrecognised.
///
/// A zip archive is opened for its first CIM/XML entry, since a model set often arrives as
/// one. Unreadable is not an error here: [`Dataset::open`] moves on to the next file.
pub fn detect_file(path: &Path) -> Option<&'static Schema> {
    #[cfg(feature = "zip")]
    if path
        .extension()
        .is_some_and(|e| e.eq_ignore_ascii_case("zip"))
    {
        let file = File::open(path).ok()?;
        let mut zip = zip::ZipArchive::new(BufReader::new(file)).ok()?;
        // Only looking for one readable document here; an undecodable name is reported
        // by the load that reads the archive.
        let mut names: Vec<String> = zip
            .file_names()
            .filter_map(|n| n.ok())
            .filter(|n| n.to_ascii_lowercase().ends_with(".xml"))
            .map(|n| n.into_owned())
            .collect();
        names.sort();
        let entry = zip.by_name(names.first()?).ok()?;
        return crate::reader::sniff(BufReader::new(entry)).ok().flatten();
    }
    let file = File::open(path).ok()?;
    crate::reader::sniff(BufReader::new(file)).ok().flatten()
}

/// Every CIM input under `path`, sorted so that a load is reproducible.
///
/// A plain file is returned as itself whatever its name; a directory is walked recursively
/// and the files that look like CIM inputs are kept — `.xml`, and `.zip` when the `zip`
/// feature is on, since without it an archive can only produce an error.
///
/// Exposed because every program that touches a model set needs it and the answer is not
/// quite obvious: models arrive as directories, the directories nest, and the order files
/// are read in has to be fixed for a load to be reproducible even though merging makes it
/// otherwise immaterial.
pub fn instance_files(path: impl AsRef<Path>) -> Vec<PathBuf> {
    let path = path.as_ref();
    fn looks_like_input(path: &Path) -> bool {
        let Some(ext) = path.extension() else {
            return false;
        };
        ext.eq_ignore_ascii_case("xml")
            || (cfg!(feature = "zip") && ext.eq_ignore_ascii_case("zip"))
    }
    fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for e in entries.flatten() {
            let p = e.path();
            if p.is_dir() {
                walk(&p, out);
            } else if looks_like_input(&p) {
                out.push(p);
            }
        }
    }

    let mut out = Vec::new();
    if path.is_dir() {
        walk(path, &mut out);
        out.sort();
    } else if path.is_file() {
        out.push(path.to_path_buf());
    }
    out
}

/// Outcome of writing a model back to disk.
#[derive(Debug, Default)]
pub struct SaveReport {
    pub written: Vec<PathBuf>,
    /// Headers that declared no profile this schema recognises.
    pub skipped: Vec<String>,
    /// Objects no output file covers.
    ///
    /// Non-zero means the export is not the model: an object belongs to a file whose
    /// header declares no profile — a document with no `md:FullModel` at all, for
    /// instance — and there is nothing to reproduce it into. Reported as a number rather
    /// than left to be inferred from an empty `written`, because a *partly* exported model
    /// is the case that looks like success.
    pub unwritten: usize,
}

/// The file name to write a header's model back to, confined to the output directory.
///
/// A header's `source` is whatever named the document it was read from, and that is not
/// always a plain file name: reading a zip archive records the *entry* name, which the
/// archive's author chose and which may contain directory separators or `..`. Joining that
/// onto an output directory would let an archive decide where this process writes — the
/// classic zip-slip. Only the final component is kept, and only when it is an ordinary
/// name.
fn output_file_name(source: &str) -> Option<String> {
    let candidate = Path::new(source).file_name()?.to_str()?;
    let plain = !candidate.is_empty()
        && candidate != "."
        && candidate != ".."
        && !candidate.contains(['/', '\\', '\0']);
    plain.then(|| candidate.to_owned())
}

/// Give `name` a suffix if `used` already holds it, and record the result.
///
/// Not a nicety: without it a second file wanting the same name overwrites the first, and
/// the caller is told both were written.
fn unique_name(name: String, used: &mut Vec<String>) -> String {
    let mut candidate = name.clone();
    let (stem, ext) = match name.rsplit_once('.') {
        Some((s, e)) if !s.is_empty() => (s, format!(".{e}")),
        _ => (name.as_str(), String::new()),
    };
    let mut n = 1;
    while used.contains(&candidate) {
        n += 1;
        candidate = format!("{stem}_{n}{ext}");
    }
    used.push(candidate.clone());
    candidate
}

/// Write a dataset to any sink, as a single document.
pub fn write_to<W: Write>(dataset: &Dataset, out: W, options: &WriteOptions) -> Result<()> {
    crate::writer::write(dataset, out, options)
}

// ---------------------------------------------------------------------------
// Zip archives
// ---------------------------------------------------------------------------

#[cfg(feature = "zip")]
impl Dataset {
    /// Load every CIM/XML entry in a zip archive.
    ///
    /// CGMES model sets are routinely distributed as archives, sometimes with one
    /// instance file per archive and sometimes with a whole model set inside one.
    pub fn load_zip(&mut self, path: &Path, options: &ReadOptions) -> Result<LoadReport> {
        self.load_zip_within(path, options, &Budget::new(options))
    }

    fn load_zip_within(
        &mut self,
        path: &Path,
        options: &ReadOptions,
        budget: &Budget,
    ) -> Result<LoadReport> {
        use crate::error::Error;

        let file = File::open(path)?;
        let mut archive = zip::ZipArchive::new(BufReader::new(file))
            .map_err(|e| Error::Zip(format!("{}: {e}", path.display())))?;

        // Read entries in name order so a load is reproducible.
        let mut out = LoadReport::default();
        let mut names: Vec<String> = Vec::new();
        for name in archive.file_names() {
            match name {
                Ok(n) if n.to_ascii_lowercase().ends_with(".xml") => names.push(n.into_owned()),
                Ok(_) => {}
                // An entry whose name the archive cannot decode is an entry this load does
                // not read, and that is said rather than skipped.
                Err(e) => out.report.push(
                    Diagnostic::error(
                        Rule::UnreadableFile,
                        format!("an entry name could not be decoded: {e}"),
                    )
                    .with_source(path.display().to_string()),
                ),
            }
        }
        names.sort();

        for name in names {
            let entry = archive
                .by_name(&name)
                .map_err(|e| Error::Zip(format!("{name}: {e}")))?;
            // The entry's decompressed bytes, counted as the parser takes them: the
            // archive's own size fields are the attacker's to write.
            // A read failure inside an entry is the archive's — zip refuses an entry that
            // inflates past the size it declares — so it is reported as one, named.
            let outcome = read_into_within(
                self,
                BufReader::with_capacity(1 << 16, entry),
                Some(&name),
                options,
                budget,
            )
            .map_err(|e| match e {
                Error::Io(io) => Error::Zip(format!("{}: {name}: {io}", path.display())),
                other => other,
            })?;
            out.report.extend(outcome.report);
            out.objects_read += outcome.objects_read;
            out.files
                .push((PathBuf::from(&name), outcome.header.clone()));
        }
        Ok(out)
    }

    /// Write every populated profile into one zip archive.
    pub fn save_zip(&self, path: &Path, stem: &str) -> Result<Vec<String>> {
        use crate::error::Error;
        use zip::write::SimpleFileOptions;

        let file = File::create(path)?;
        let mut zw = zip::ZipWriter::new(BufWriter::new(file));
        let mut written = Vec::new();
        // Once for the archive, not once per profile: see `save_all_profiles`.
        let content = self.content_id();

        for cov in crate::validate::profile_coverage(self) {
            if cov.objects == 0 {
                continue;
            }
            let name = format!("{stem}_{}.xml", cov.keyword);
            zw.start_file(&name, SimpleFileOptions::default())
                .map_err(|e| Error::Zip(e.to_string()))?;
            let header =
                crate::writer::derive_header_with(self.schema(), cov.profile.mask(), &content);
            write_profile(
                self,
                cov.profile,
                &mut zw,
                &WriteOptions::default().with_header(header),
            )?;
            written.push(name);
        }
        zw.finish().map_err(|e| Error::Zip(e.to_string()))?;
        Ok(written)
    }
}

#[cfg(test)]
mod tests {
    use super::{output_file_name, unique_name};

    #[test]
    fn two_files_wanting_one_name_get_two_files() {
        // A merged common grid model assembled from `BE/EQ.xml` and `NL/EQ.xml`: only the
        // final component survives the traversal guard, so both headers ask for `EQ.xml`.
        let mut used = Vec::new();
        assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ.xml");
        assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ_2.xml");
        assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ_3.xml");
        assert_eq!(unique_name("SSH.xml".into(), &mut used), "SSH.xml");
        // A name without an extension still gets a distinct one.
        assert_eq!(unique_name("model".into(), &mut used), "model");
        assert_eq!(unique_name("model".into(), &mut used), "model_2");
        // And a collision with an already-suffixed name keeps counting rather than looping.
        assert_eq!(unique_name("EQ_2.xml".into(), &mut used), "EQ_2_2.xml");
    }

    #[test]
    fn an_export_never_escapes_its_output_directory() {
        // A header's source is the name of the document it was read from, and for a zip
        // archive that name is chosen by whoever built the archive.
        assert_eq!(output_file_name("EQ.xml").as_deref(), Some("EQ.xml"));
        assert_eq!(
            output_file_name("model/EQ.xml").as_deref(),
            Some("EQ.xml"),
            "a nested archive entry keeps only its file name"
        );
        assert_eq!(
            output_file_name("../../../etc/cron.d/pwn").as_deref(),
            Some("pwn")
        );
        assert_eq!(output_file_name("/etc/passwd").as_deref(), Some("passwd"));
        for hostile in ["..", ".", "", "/", "..\\..\\evil.xml", "a\0b"] {
            assert_eq!(output_file_name(hostile), None, "{hostile:?}");
        }
    }
}