cim-kit 0.5.1

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
//! Writer for CIM/XML instance documents (IEC 61970-552).
//!
//! Output is deterministic: objects in ascending mRID order, attributes in schema order,
//! so an unchanged model re-writes byte-identically.

use std::io::Write;

use crate::dataset::Dataset;
use crate::error::{Error, Result};
use crate::header::{
    DM_NS, DifferenceModel, HeaderValue, MD_NS, ModelHeader, ModelKind, Statement, StatementValue,
};
use crate::mrid::Mrid;
use crate::object::Object;
use crate::schema::{AttrKind, ClassDef, ClassId, NsId, Primitive, ProfileId, ProfileMask, Schema};
use crate::value::Value;

const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";

/// How to identify objects in the output.
///
/// IEC 61970-552 distinguishes the file that *introduces* an object (`rdf:ID`) from one
/// that adds to it (`rdf:about`); the RDFS marks a class a profile only refers to with
/// `cims:stereotype Description`.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum IdStyle {
    /// Decide per object from the schema (the default).
    ///
    /// `rdf:ID` when some profile in the write set *defines* the class
    /// ([`ClassDef::defined_in`](crate::schema::ClassDef::defined_in)), `rdf:about`
    /// otherwise. Per class, not per file: a Topology file writes `TopologicalNode` with
    /// `rdf:ID` and `Terminal` with `rdf:about`.
    #[default]
    Auto,
    /// Force `rdf:ID="_<uuid>"` for every object.
    RdfId,
    /// Force `rdf:about="#_<uuid>"` for every object.
    RdfAbout,
}

/// Where a document's `md:FullModel` header comes from.
///
/// IEC 61970-552 gives every instance file a header declaring its profiles and
/// dependencies, so deriving one is the default.
#[derive(Clone, Debug, Default)]
pub enum HeaderSource {
    /// Derive one from the dataset: identified by its content, declaring the profiles
    /// actually written.
    ///
    /// Deterministic and clock-free: the identifier is an RFC 4122 v5 UUID over the
    /// model's content.
    #[default]
    Derive,
    /// Write this header, which is how a model is written back as the file set it came
    /// from. An identifier is filled in from the model's content if it has none.
    ///
    /// Boxed: a `ModelHeader` is large and this enum sits in every `WriteOptions`.
    Given(Box<ModelHeader>),
    /// Write no header. Not a conforming instance file.
    Omit,
}

/// Options controlling serialization.
#[derive(Clone, Debug)]
pub struct WriteOptions {
    /// Write only attributes belonging to these profiles; zero means "everything".
    ///
    /// A set, because one file often serves several (e.g. Equipment, Operation and
    /// ShortCircuit together).
    pub profiles: ProfileMask,
    pub id_style: IdStyle,
    /// Indent nested elements. Off produces smaller files.
    pub pretty: bool,
    /// Where the document's `md:FullModel` comes from.
    pub header: HeaderSource,
    /// Emit the XML declaration.
    pub xml_declaration: bool,
}

impl Default for WriteOptions {
    fn default() -> Self {
        WriteOptions {
            profiles: 0,
            id_style: IdStyle::Auto,
            pretty: true,
            header: HeaderSource::default(),
            xml_declaration: true,
        }
    }
}

impl WriteOptions {
    /// Write one profile's attributes, as a conforming instance file.
    pub fn profile(profile: ProfileId) -> WriteOptions {
        WriteOptions::profiles(profile.mask())
    }

    /// Write the attributes of every profile in `profiles`.
    pub fn profiles(profiles: ProfileMask) -> WriteOptions {
        WriteOptions {
            profiles,
            ..Default::default()
        }
    }

    /// Write `header` rather than a derived one.
    pub fn with_header(mut self, header: ModelHeader) -> Self {
        self.header = HeaderSource::Given(Box::new(header));
        self
    }

    /// Write no header at all.
    ///
    /// The result is not a conforming instance file. Use it for a fragment, or where the
    /// caller assembles the document itself.
    pub fn headerless(mut self) -> Self {
        self.header = HeaderSource::Omit;
        self
    }
    pub fn with_id_style(mut self, style: IdStyle) -> Self {
        self.id_style = style;
        self
    }
    pub fn compact(mut self) -> Self {
        self.pretty = false;
        self
    }
}

/// Write every object of `dataset` as one CIM/XML document.
pub fn write<W: Write>(dataset: &Dataset, out: W, options: &WriteOptions) -> Result<()> {
    let ids: Vec<_> = dataset.iter().map(|(id, _)| id).collect();
    write_objects(dataset, ids.into_iter(), out, options)
}

/// Write a chosen subset of objects as one CIM/XML document.
pub fn write_objects<W: Write, I>(
    dataset: &Dataset,
    objects: I,
    out: W,
    options: &WriteOptions,
) -> Result<()>
where
    I: Iterator<Item = crate::dataset::ObjectId>,
{
    let schema = dataset.schema();
    let mut w = Writer::new(out, schema, options.pretty);

    // Deterministic order: sort by mRID so output does not depend on load order.
    let mut list: Vec<&Object> = objects.filter_map(|id| dataset.get(id)).collect();
    list.sort_by(|a, b| a.mrid().cmp(b.mrid()));

    w.start_document(options)?;
    // 552 requires `md:FullModel rdf:about`; a hand-built header without one gets the
    // model's content identifier.
    match &options.header {
        HeaderSource::Omit => {}
        HeaderSource::Given(h) if h.id.is_some() => w.header(h)?,
        HeaderSource::Given(h) => {
            let mut h = h.clone();
            h.id = Some(dataset.content_id());
            w.header(&h)?;
        }
        HeaderSource::Derive => w.header(&derive_header(dataset, options.profiles))?,
    }
    for obj in list {
        w.object(obj, options)?;
    }
    w.end_document()
}

/// Write one profile's slice of a dataset.
pub fn write_profile<W: Write>(
    dataset: &Dataset,
    profile: ProfileId,
    out: W,
    options: &WriteOptions,
) -> Result<()> {
    write_profiles(dataset, profile.mask(), out, options)
}

/// Write the slice of a dataset belonging to a set of profiles.
///
/// E.g. an Equipment file that declared Equipment, Operation and ShortCircuit is rebuilt
/// by passing all three.
pub fn write_profiles<W: Write>(
    dataset: &Dataset,
    profiles: ProfileMask,
    out: W,
    options: &WriteOptions,
) -> Result<()> {
    let schema = dataset.schema();
    let mut opts = options.clone();
    opts.profiles = profiles;

    let ids: Vec<_> = dataset
        .iter()
        .filter(|(_, o)| object_in_profiles(schema, o, profiles))
        .map(|(id, _)| id)
        .collect();
    write_objects(dataset, ids.into_iter(), out, &opts)
}

/// Write a difference model (IEC 61970-552 `dm:DifferenceModel`).
///
/// The counterpart of [`read_difference`](crate::reader::read_difference). Statements
/// are grouped by subject; preconditions, then reverse, then forward differences.
///
/// The difference's own header is used unless `options` supplies one.
pub fn write_difference<W: Write>(
    schema: &'static Schema,
    diff: &DifferenceModel,
    out: W,
    options: &WriteOptions,
) -> Result<()> {
    let mut header = match &options.header {
        HeaderSource::Given(h) => (**h).clone(),
        // `Derive` and `Omit` both use the difference's own header: there is no data to
        // derive from, and `dm:DifferenceModel` is the document's content.
        _ => diff.header.clone(),
    };
    header.kind = ModelKind::Difference;

    let mut w = Writer::new(out, schema, options.pretty);
    // Predicates may use namespaces outside the schema (vendor extensions); bind them
    // before the root element.
    for s in diff.reverse.iter().chain(&diff.forward) {
        w.bind_statement_namespaces(s);
    }
    let mut opts = options.clone();
    opts.header = HeaderSource::Given(Box::new(header.clone()));
    w.start_document(&opts)?;

    w.header_open(&header)?;
    w.header_body(&header)?;
    // Published order: what must hold, what goes, what comes.
    w.statements("preconditions", &diff.preconditions)?;
    w.statements("reverseDifferences", &diff.reverse)?;
    w.statements("forwardDifferences", &diff.forward)?;
    w.header_close(&header)?;
    w.end_document()
}

/// Whether a stored value belongs in an instance file serving `profiles`.
///
/// See [`Schema::effective_profiles`] for the rule. A zero mask means "no filtering".
#[inline]
fn slot_belongs_to(schema: &Schema, slot: &crate::object::Slot, profiles: ProfileMask) -> bool {
    profiles == 0 || schema.effective_profiles(slot.attr, slot.profiles) & profiles != 0
}

/// Whether an object would serialize any attribute in `profiles`.
pub fn object_has_content_in(schema: &Schema, obj: &Object, profiles: ProfileMask) -> bool {
    obj.slots()
        .iter()
        .any(|s| slot_belongs_to(schema, s, profiles))
}

/// Whether an object belongs in a file serving `profiles` — which is not the same question
/// as whether it has anything to *say* there.
///
/// An object also belongs where a profile *introduces* its class and the reader saw it
/// there, even with no values: e.g. `<cim:ConnectivityNode rdf:ID="_x"/>` in Equipment
/// Boundary (D55).
pub fn object_in_profiles(schema: &Schema, obj: &Object, profiles: ProfileMask) -> bool {
    object_has_content_in(schema, obj, profiles)
        || (obj.profiles() & profiles != 0 && schema.class(obj.class()).defined_in & profiles != 0)
}

/// The prefix bindings of one output document.
///
/// Resolved once, up front, so each prefix is declared exactly once (a duplicate `xmlns:md`
/// is not well-formed) and exists before use (a header property read from a default
/// namespace has no prefix). A prefix is minted where the preferred one is taken.
#[derive(Debug, Default)]
struct Namespaces {
    /// `(prefix, IRI)` in declaration order.
    decls: Vec<(String, String)>,
    /// Prefix chosen for each [`NsId`] of the schema.
    by_ns: Vec<usize>,
}

impl Namespaces {
    /// Bind `iri`, preferring `want` as its prefix, and return the binding's index.
    ///
    /// An IRI already bound keeps its existing prefix.
    fn bind(&mut self, want: &str, iri: &str) -> usize {
        if let Some(i) = self.decls.iter().position(|(_, n)| n == iri) {
            return i;
        }
        // `xml`/`xmlns` are reserved and an empty prefix is unusable: generate a name.
        let base = match want {
            "" | "xml" | "xmlns" => "ns",
            other => other,
        };
        let mut prefix = base.to_owned();
        let mut n = 1;
        while self.decls.iter().any(|(p, _)| *p == prefix) {
            n += 1;
            prefix = format!("{base}{n}");
        }
        self.decls.push((prefix, iri.to_owned()));
        self.decls.len() - 1
    }

    /// Bindings for a document written against `schema`.
    ///
    /// Declares the schema's full namespace set, used or not, so output is stable.
    fn for_schema(schema: &Schema) -> Namespaces {
        let mut ns = Namespaces::default();
        // `rdf` first and by that name: the one prefix 552 fixes.
        ns.bind("rdf", RDF_NS);
        ns.by_ns = schema
            .namespaces
            .iter()
            .map(|n| ns.bind(n.prefix, n.iri))
            .collect();
        ns
    }

    fn prefix(&self, ns: NsId) -> &str {
        self.by_ns
            .get(ns.index())
            .map_or("ns", |&i| self.decls[i].0.as_str())
    }

    fn prefix_at(&self, index: usize) -> &str {
        &self.decls[index].0
    }

    /// The prefix bound to `iri`, if the document declares it.
    fn prefix_of_iri(&self, iri: &str) -> Option<&str> {
        self.decls
            .iter()
            .find(|(_, n)| n == iri)
            .map(|(p, _)| p.as_str())
    }
}

struct Writer<W: Write> {
    out: W,
    schema: &'static Schema,
    pretty: bool,
    ns: Namespaces,
    /// Prefix index for each entry of the header's `extra` list, in order.
    extra_prefixes: Vec<usize>,
}

impl<W: Write> Writer<W> {
    fn new(out: W, schema: &'static Schema, pretty: bool) -> Writer<W> {
        Writer {
            out,
            schema,
            pretty,
            ns: Namespaces::for_schema(schema),
            extra_prefixes: Vec::new(),
        }
    }

    /// Register the namespaces a difference statement mentions.
    fn bind_statement_namespaces(&mut self, s: &Statement) {
        if let Some(q) = &s.class {
            self.ns.bind(suggest_prefix(&q.ns), &q.ns);
        }
        self.ns
            .bind(suggest_prefix(&s.predicate_ns), &s.predicate_ns);
    }

    /// The prefix under which the model-description vocabulary is written here.
    fn md(&self) -> String {
        self.ns.prefix_of_iri(MD_NS).unwrap_or("md").to_owned()
    }
    /// The prefix under which the difference-model vocabulary is written here.
    fn dm(&self) -> String {
        self.ns.prefix_of_iri(DM_NS).unwrap_or("dm").to_owned()
    }

    fn start_document(&mut self, options: &WriteOptions) -> Result<()> {
        // Resolve every prefix before writing anything.
        self.ns.bind("md", MD_NS);
        self.ns.bind("dm", DM_NS);
        // A given header may carry vendor properties in namespaces the schema knows
        // nothing about; a derived one never does.
        self.extra_prefixes = match &options.header {
            HeaderSource::Given(h) => h
                .extra
                .iter()
                .map(|p| self.ns.bind(&p.prefix, &p.ns))
                .collect(),
            _ => Vec::new(),
        };

        if options.xml_declaration {
            self.out
                .write_all(b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")?;
        }
        // `rdf` is bound first, so the literal `rdf:` prefix used below is correct.
        self.out.write_all(b"<rdf:RDF")?;
        let decls = std::mem::take(&mut self.ns.decls);
        for (prefix, iri) in &decls {
            write!(self.out, " xmlns:{prefix}=\"").map_err(Error::Io)?;
            self.escape_attr(iri)?;
            self.out.write_all(b"\"")?;
        }
        self.ns.decls = decls;
        self.out.write_all(b">\n")?;
        Ok(())
    }

    fn end_document(&mut self) -> Result<()> {
        self.out.write_all(b"</rdf:RDF>\n")?;
        self.out.flush()?;
        Ok(())
    }

    fn header(&mut self, h: &ModelHeader) -> Result<()> {
        self.header_open(h)?;
        self.header_body(h)?;
        self.header_close(h)
    }

    fn header_element(&self, h: &ModelHeader) -> (String, &'static str) {
        match h.kind {
            ModelKind::Full => (self.md(), "FullModel"),
            ModelKind::Difference => (self.dm(), "DifferenceModel"),
        }
    }

    /// Open the header element.
    ///
    /// Callers normally fill in a missing identifier first; the nil UUID is the last
    /// resort, since `validate` reports it and an absent `rdf:about` is unreadable.
    fn header_open(&mut self, h: &ModelHeader) -> Result<()> {
        let (prefix, elem) = self.header_element(h);
        let about =
            h.id.as_ref()
                .map(Mrid::to_urn)
                .unwrap_or_else(|| Mrid::nil().to_urn());
        self.indent(1)?;
        write!(self.out, "<{prefix}:{elem} rdf:about=\"").map_err(Error::Io)?;
        self.escape_attr(&about)?;
        self.out.write_all(b"\">\n")?;
        Ok(())
    }

    fn header_close(&mut self, h: &ModelHeader) -> Result<()> {
        let (prefix, elem) = self.header_element(h);
        self.indent(1)?;
        writeln!(self.out, "</{prefix}:{elem}>").map_err(Error::Io)?;
        Ok(())
    }

    fn header_body(&mut self, h: &ModelHeader) -> Result<()> {
        // Fixed order so headers are diffable across writes.
        self.header_text(h.created.as_deref(), "Model.created")?;
        self.header_text(h.scenario_time.as_deref(), "Model.scenarioTime")?;
        self.header_text(h.description.as_deref(), "Model.description")?;
        self.header_text(h.version.as_deref(), "Model.version")?;
        self.header_text(
            h.modeling_authority_set.as_deref(),
            "Model.modelingAuthoritySet",
        )?;
        for p in &h.profiles {
            self.header_text(Some(p), "Model.profile")?;
        }
        for d in &h.dependent_on {
            self.header_resource(&d.to_urn(), "Model.DependentOn")?;
        }
        for s in &h.supersedes {
            self.header_resource(&s.to_urn(), "Model.Supersedes")?;
        }
        // Prefixes resolved at `start_document`; the schema may not know them.
        let prefixes: Vec<String> = self
            .extra_prefixes
            .iter()
            .map(|&i| self.ns.prefix_at(i).to_owned())
            .collect();
        for (p, prefix) in h.extra.iter().zip(&prefixes) {
            match &p.value {
                HeaderValue::Text(v) => self.header_prop_text(prefix, &p.local, v)?,
                HeaderValue::Resource(v) => self.header_prop_resource(prefix, &p.local, v)?,
            }
        }
        Ok(())
    }

    /// Write one `dm:preconditions` / `dm:reverseDifferences` / `dm:forwardDifferences`
    /// statement set.
    ///
    /// Statements about one subject share an element; a group that named a class keeps it,
    /// since that is how a difference reclassifies an object.
    fn statements(&mut self, local: &str, statements: &[Statement]) -> Result<()> {
        if statements.is_empty() {
            return Ok(());
        }
        let dm = self.dm();
        self.indent(2)?;
        writeln!(self.out, "<{dm}:{local} rdf:parseType=\"Statements\">").map_err(Error::Io)?;

        let mut i = 0;
        while i < statements.len() {
            let subject = &statements[i].subject;
            let class = &statements[i].class;
            let defines = statements[i].defines_subject;
            let mut j = i;
            while j < statements.len()
                && statements[j].subject == *subject
                && statements[j].class == *class
            {
                j += 1;
            }

            // Bound before the root, so a vendor predicate keeps its own namespace.
            let (prefix, name) = match class {
                Some(q) => (
                    self.ns.prefix_of_iri(&q.ns).unwrap_or("ns").to_owned(),
                    q.local.clone(),
                ),
                None => ("rdf".to_owned(), "Description".to_owned()),
            };
            self.indent(3)?;
            // As for objects: an absolute-IRI identifier has no `rdf:ID` form.
            if defines && subject.form_in_xml() != crate::xml::IdentifierForm::Iri {
                write!(self.out, "<{prefix}:{name} rdf:ID=\"").map_err(Error::Io)?;
                self.escape_attr(&subject.to_rdf_id())?;
            } else {
                write!(self.out, "<{prefix}:{name} rdf:about=\"").map_err(Error::Io)?;
                self.escape_attr(&subject.to_rdf_reference())?;
            }
            self.out.write_all(b"\">\n")?;

            for s in &statements[i..j] {
                let p = self
                    .ns
                    .prefix_of_iri(&s.predicate_ns)
                    .unwrap_or("ns")
                    .to_owned();
                let predicate = &s.predicate;
                self.indent(4)?;
                match &s.value {
                    StatementValue::Resource(iri) => {
                        write!(self.out, "<{p}:{predicate} rdf:resource=\"").map_err(Error::Io)?;
                        self.escape_attr(iri)?;
                        self.out.write_all(b"\"/>\n")?;
                    }
                    StatementValue::Literal(text) => {
                        write!(self.out, "<{p}:{predicate}>").map_err(Error::Io)?;
                        self.escape_text(text)?;
                        writeln!(self.out, "</{p}:{predicate}>").map_err(Error::Io)?;
                    }
                }
            }

            self.indent(3)?;
            writeln!(self.out, "</{prefix}:{name}>").map_err(Error::Io)?;
            i = j;
        }

        self.indent(2)?;
        writeln!(self.out, "</{dm}:{local}>").map_err(Error::Io)?;
        Ok(())
    }

    fn header_text(&mut self, value: Option<&str>, local: &str) -> Result<()> {
        let Some(v) = value else { return Ok(()) };
        let md = self.md();
        self.header_prop_text(&md, local, v)
    }

    fn header_resource(&mut self, value: &str, local: &str) -> Result<()> {
        let md = self.md();
        self.header_prop_resource(&md, local, value)
    }

    fn header_prop_text(&mut self, prefix: &str, local: &str, value: &str) -> Result<()> {
        self.indent(2)?;
        write!(self.out, "<{prefix}:{local}>").map_err(Error::Io)?;
        self.escape_text(value)?;
        writeln!(self.out, "</{prefix}:{local}>").map_err(Error::Io)?;
        Ok(())
    }

    fn header_prop_resource(&mut self, prefix: &str, local: &str, value: &str) -> Result<()> {
        self.indent(2)?;
        write!(self.out, "<{prefix}:{local} rdf:resource=\"").map_err(Error::Io)?;
        self.escape_attr(value)?;
        self.out.write_all(b"\"/>\n")?;
        Ok(())
    }

    /// Write one object element.
    ///
    /// Fields are destructured so prefixes can be borrowed while the sink is mutable,
    /// avoiding an allocation per attribute.
    fn object(&mut self, obj: &Object, options: &WriteOptions) -> Result<()> {
        let Writer {
            out,
            schema,
            pretty,
            ns,
            ..
        } = self;
        let pretty = *pretty;
        let all_attrs = schema.class(obj.class()).all_attrs;
        let class = schema.class(element_class(schema, obj, obj.class(), options.profiles));
        let prefix = ns.prefix(class.ns);

        indent(out, pretty, 1)?;
        write!(out, "<{}:{}", prefix, class.name).map_err(Error::Io)?;
        // An absolute-IRI identifier has no `rdf:ID` (`NCName`) form: use `rdf:about`.
        let mrid = obj.mrid();
        match (
            resolve_id_style(options, class),
            mrid.form_in_xml() == crate::xml::IdentifierForm::Iri,
        ) {
            (_, true) | (IdStyle::RdfAbout, false) => {
                out.write_all(b" rdf:about=\"")?;
                escape_attr(out, &mrid.to_rdf_reference())?;
            }
            // `Auto` is resolved above; anything left is the explicit `rdf:ID` form.
            _ => {
                out.write_all(b" rdf:ID=\"")?;
                escape_attr(out, &mrid.to_rdf_id())?;
            }
        }
        // Iterate the object's slots, not the class's attributes: far fewer.
        if !object_has_content_in(schema, obj, options.profiles) {
            out.write_all(b"\"/>\n")?;
            return Ok(());
        }
        out.write_all(b"\">\n")?;

        // Schema order, from the object's own class rather than the element's (an SSH
        // file writes `<cim:Equipment>` for an `ACLineSegment`).
        for attr_id in all_attrs {
            let def = schema.attr(*attr_id);
            let attr_prefix = ns.prefix(def.ns);
            let prim = lexical_primitive(schema, def.kind);
            for slot in obj.get_all(*attr_id) {
                if !slot_belongs_to(schema, slot, options.profiles) {
                    continue;
                }
                property(
                    out,
                    schema,
                    ns,
                    pretty,
                    attr_prefix,
                    def.name,
                    &slot.value,
                    prim,
                    2,
                )?;
            }
        }

        indent(out, pretty, 1)?;
        writeln!(out, "</{}:{}>", prefix, class.name).map_err(Error::Io)?;
        Ok(())
    }

    fn indent(&mut self, level: usize) -> Result<()> {
        indent(&mut self.out, self.pretty, level)
    }

    fn escape_text(&mut self, s: &str) -> Result<()> {
        escape_text(&mut self.out, s)
    }

    fn escape_attr(&mut self, s: &str) -> Result<()> {
        escape_attr(&mut self.out, s)
    }
}

/// Write one property element, recursing into compounds.
///
/// `prim` is the primitive the schema gives the attribute, which decides the lexical
/// form: `Decimal` has no exponent notation, `Float` does.
#[allow(clippy::too_many_arguments)]
fn property<W: Write>(
    out: &mut W,
    schema: &'static Schema,
    ns: &Namespaces,
    pretty: bool,
    prefix: &str,
    name: &str,
    value: &Value,
    prim: Primitive,
    depth: usize,
) -> Result<()> {
    indent(out, pretty, depth)?;
    match value {
        Value::Reference(m) => {
            write!(out, "<{prefix}:{name} rdf:resource=\"").map_err(Error::Io)?;
            escape_attr(out, &m.to_rdf_reference())?;
            out.write_all(b"\"/>\n")?;
        }
        Value::Enum(e) => {
            let ev = schema.enum_value(*e);
            write!(out, "<{prefix}:{name} rdf:resource=\"").map_err(Error::Io)?;
            escape_attr(out, schema.namespace(ev.ns).iri)?;
            escape_attr(out, ev.name)?;
            out.write_all(b"\"/>\n")?;
        }
        // A compound is written inline as a blank node (`rdf:parseType="Resource"`).
        Value::Compound(c) => {
            if c.is_empty() {
                writeln!(out, "<{prefix}:{name} rdf:parseType=\"Resource\"/>")
                    .map_err(Error::Io)?;
                return Ok(());
            }
            writeln!(out, "<{prefix}:{name} rdf:parseType=\"Resource\">").map_err(Error::Io)?;
            for (attr, v) in c.values() {
                let def = schema.attr(*attr);
                property(
                    out,
                    schema,
                    ns,
                    pretty,
                    ns.prefix(def.ns),
                    def.name,
                    v,
                    lexical_primitive(schema, def.kind),
                    depth + 1,
                )?;
            }
            indent(out, pretty, depth)?;
            writeln!(out, "</{prefix}:{name}>").map_err(Error::Io)?;
        }
        other => {
            write!(out, "<{prefix}:{name}>").map_err(Error::Io)?;
            if let Some(text) = other.to_lexical_as(prim) {
                escape_text(out, &text)?;
            }
            writeln!(out, "</{prefix}:{name}>").map_err(Error::Io)?;
        }
    }
    Ok(())
}

fn indent<W: Write>(out: &mut W, pretty: bool, level: usize) -> Result<()> {
    if pretty {
        for _ in 0..level {
            out.write_all(b"  ")?;
        }
    }
    Ok(())
}

/// Escape a value for element content.
///
/// Escapes `&`, `<` and `>` (so `]]>` cannot occur); quotes are left alone. CR is escaped
/// numerically, since parsers normalize a literal CR to LF.
fn escape_text<W: Write>(out: &mut W, s: &str) -> Result<()> {
    escape(out, s, |b| match b {
        b'&' => Some(b"&amp;".as_slice()),
        b'<' => Some(b"&lt;"),
        b'>' => Some(b"&gt;"),
        b'\r' => Some(b"&#13;"),
        _ => None,
    })
}

/// Escape a value for a double-quoted attribute.
///
/// Tab, LF and CR are escaped numerically too, since attribute-value normalization would
/// turn them into spaces.
fn escape_attr<W: Write>(out: &mut W, s: &str) -> Result<()> {
    escape(out, s, |b| match b {
        b'&' => Some(b"&amp;".as_slice()),
        b'<' => Some(b"&lt;"),
        b'>' => Some(b"&gt;"),
        b'"' => Some(b"&quot;"),
        b'\t' => Some(b"&#9;"),
        b'\n' => Some(b"&#10;"),
        b'\r' => Some(b"&#13;"),
        _ => None,
    })
}

/// Copy `s`, replacing the bytes `rep` names, and dropping what XML cannot represent.
///
/// Replaced bytes are all ASCII, so multi-byte characters are untouched. Characters
/// outside XML 1.0's `Char` (most of C0) have no representation even as a reference, so
/// they are dropped; [`Rule::IllegalXmlCharacter`] reports them on read and in validation.
///
/// [`Rule::IllegalXmlCharacter`]: crate::Rule::IllegalXmlCharacter
fn escape<W: Write>(out: &mut W, s: &str, rep: fn(u8) -> Option<&'static [u8]>) -> Result<()> {
    // One byte test per byte on the common path, and no allocation unless it fires.
    let cleaned = crate::xml::strip_illegal(s);
    let bytes = cleaned.as_bytes();
    let mut start = 0;
    for (i, &b) in bytes.iter().enumerate() {
        let Some(r) = rep(b) else { continue };
        out.write_all(&bytes[start..i])?;
        out.write_all(r)?;
        start = i + 1;
    }
    out.write_all(&bytes[start..])?;
    Ok(())
}

/// The primitive an attribute's values are written as.
///
/// A datatype such as `Money` serializes as the primitive it wraps; enumerations,
/// references and compounds never reach the text path, so `String` stands in.
fn lexical_primitive(schema: &Schema, kind: AttrKind) -> Primitive {
    match kind {
        AttrKind::Primitive(p) => p,
        AttrKind::Datatype(d) => schema.datatype(d).value,
        _ => Primitive::String,
    }
}

/// A prefix to suggest for a namespace the schema does not know, derived from its IRI.
///
/// `http://example.com/vendor#` yields `vendor`; anything unusable yields `ns`, which
/// [`Namespaces::bind`] then makes unique.
fn suggest_prefix(iri: &str) -> &str {
    let trimmed = iri.trim_end_matches(['#', '/']);
    let last = trimmed.rsplit(['#', '/', ':']).next().unwrap_or_default();
    let usable = !last.is_empty()
        && last.starts_with(|c: char| c.is_ascii_alphabetic())
        && last
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
    if usable { last } else { "ns" }
}

/// The class an object is written as in a file serving `profiles`.
///
/// The most specific class (the object's own or an ancestor) that the profiles declare and
/// whose mandatory attributes the model supplies.
/// An SSH file thus writes `<cim:Equipment rdf:about="…">` for an
/// `ACLineSegment` (SSH does not declare `ACLineSegment`); the most specific class would
/// fail the profile's SHACL shapes. Falls back to the object's own class.
pub fn element_class(
    schema: &Schema,
    obj: &Object,
    class: ClassId,
    profiles: ProfileMask,
) -> ClassId {
    // Writing everything into one document imposes no profile, so the real class stands.
    if profiles == 0 {
        return class;
    }
    let declared = |c: ClassId| {
        let d = schema.class(c);
        d.concrete && !d.compound && d.profiles & profiles != 0
    };
    // Mandatory attributes must be supplied by the *model* (`obj.has(a)`), not by this
    // file: published SSH files omit the mandatory `IdentifiedObject.mRID`, so the
    // stricter rule would reject every candidate.
    let complete = |c: ClassId| {
        schema.class(c).all_attrs.iter().all(|&a| {
            let def = schema.attr(a);
            !(def.mult.is_required() && def.used_in & profiles != 0) || obj.has(a)
        })
    };
    std::iter::once(class)
        .chain(schema.class(class).ancestors.iter().copied())
        .find(|&c| declared(c) && complete(c))
        .unwrap_or(class)
}

/// The header a document gets when the caller supplies none.
///
/// Adjust it (modelling authority set, scenario time, ...) and pass it back through
/// [`WriteOptions::with_header`].
///
/// Declares exactly the profiles being written: the mask when one is given, otherwise
/// every profile the data covers. The identifier is an RFC 4122 v5 UUID over the vintage,
/// those profiles and the model's content identifier. `Model.created` is left out, since
/// this crate reads no clock.
pub fn derive_header(dataset: &Dataset, profiles: ProfileMask) -> ModelHeader {
    derive_header_with(
        dataset.schema(),
        if profiles == 0 {
            dataset.profiles()
        } else {
            profiles
        },
        &dataset.content_id(),
    )
}

/// The same, from an already-computed content identifier.
///
/// `Dataset::content_id` walks the whole model, so a multi-file export computes it once.
pub(crate) fn derive_header_with(
    schema: &'static Schema,
    covered: ProfileMask,
    content: &Mrid,
) -> ModelHeader {
    let iris: Vec<String> = schema
        .profiles
        .iter()
        .enumerate()
        .filter(|(i, _)| covered & (1u64 << i) != 0)
        .map(|(_, p)| p.version_iri.to_owned())
        .collect();

    let mut name = format!("{}\u{1e}", schema.vintage);
    for iri in &iris {
        name.push_str(iri);
        name.push('\u{1e}');
    }
    name.push_str(&content.to_string());

    ModelHeader {
        kind: ModelKind::Full,
        id: Some(Mrid::new_v5(&Dataset::DERIVED_NS, name.as_bytes())),
        profiles: iris,
        version: Some("1".to_owned()),
        ..Default::default()
    }
}

/// How an object of `class` is identified in a file serving `options.profiles`.
///
/// Exposed so tooling can predict the output without rendering it.
pub fn id_style_for(schema: &Schema, class: ClassId, profiles: ProfileMask) -> IdStyle {
    resolve_id_style(
        &WriteOptions {
            profiles,
            ..Default::default()
        },
        schema.class(class),
    )
}

fn resolve_id_style(options: &WriteOptions, class: &ClassDef) -> IdStyle {
    match options.id_style {
        IdStyle::Auto => {
            // Writing everything into one document makes that document the definition.
            if options.profiles == 0 || class.defined_in & options.profiles != 0 {
                IdStyle::RdfId
            } else if class.profiles & options.profiles == 0 {
                // No profile this file serves mentions the class (an under-declaring
                // header), so this file must introduce it (D57).
                IdStyle::RdfId
            } else {
                IdStyle::RdfAbout
            }
        }
        forced => forced,
    }
}

/// Classes that a profile may contain, for callers building per-profile exports.
pub fn classes_in_profile(
    schema: &Schema,
    profile: ProfileId,
) -> impl Iterator<Item = ClassId> + '_ {
    let mask = profile.mask();
    schema
        .classes
        .iter()
        .enumerate()
        .filter(move |(_, c)| c.concrete && !c.compound && c.profiles & mask != 0)
        .map(|(i, _)| ClassId(i as u16))
}