cim_kit/writer.rs
1//! Writer for CIM/XML instance documents (IEC 61970-552).
2//!
3//! Output is deterministic: objects are emitted in ascending mRID order and attributes
4//! in schema order, so re-writing an unchanged model yields byte-identical output and
5//! diffs between model versions stay readable.
6
7use std::io::Write;
8
9use crate::dataset::Dataset;
10use crate::error::{Error, Result};
11use crate::header::{
12 DM_NS, DifferenceModel, HeaderValue, MD_NS, ModelHeader, ModelKind, Statement, StatementValue,
13};
14use crate::mrid::Mrid;
15use crate::object::Object;
16use crate::schema::{AttrKind, ClassDef, ClassId, NsId, Primitive, ProfileId, ProfileMask, Schema};
17use crate::value::Value;
18
19const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
20
21/// How to identify objects in the output.
22///
23/// IEC 61970-552 distinguishes the file that *introduces* an object from a file that adds
24/// to one defined elsewhere, and the RDFS records which is which per class per profile:
25/// a class a profile only refers to carries `cims:stereotype Description`.
26#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
27pub enum IdStyle {
28 /// Decide per object from the schema — the correct behaviour, and the default.
29 ///
30 /// An object is written with `rdf:ID` when some profile in the write set *defines*
31 /// its class ([`ClassDef::defined_in`](crate::schema::ClassDef::defined_in)), and with
32 /// `rdf:about` otherwise. This is not a per-file choice: a Topology file identifies
33 /// `TopologicalNode` with `rdf:ID` because Topology introduces it, and `Terminal` with
34 /// `rdf:about` because Equipment did. A single profile keyword cannot express that,
35 /// and assuming one silently rewrote 49,255 `rdf:ID`s as `rdf:about` in the published
36 /// `RealGrid` State Variables file.
37 #[default]
38 Auto,
39 /// Force `rdf:ID="_<uuid>"` for every object.
40 RdfId,
41 /// Force `rdf:about="#_<uuid>"` for every object.
42 RdfAbout,
43}
44
45/// Options controlling serialization.
46/// Where a document's `md:FullModel` header comes from.
47///
48/// IEC 61970-552 gives every instance file a header, and a consumer needs it: it is what
49/// says which profiles the file serves and which models it depends on. Deriving one is
50/// therefore the default, so that the obvious call produces a document another
51/// implementation will accept — writing none has to be asked for.
52///
53/// The derivation belongs here rather than in the callers: two entry points that each
54/// decide for themselves produce two behaviours, and only one of them ends up documented.
55#[derive(Clone, Debug, Default)]
56pub enum HeaderSource {
57 /// Derive one from the dataset: identified by its content, declaring the profiles
58 /// actually written.
59 ///
60 /// Deterministic and clock-free — the identifier is an RFC 4122 v5 UUID over the
61 /// model's content, so the same model exports to the same header twice.
62 #[default]
63 Derive,
64 /// Write this header, which is how a model is written back as the file set it came
65 /// from. An identifier is filled in from the model's content if it has none.
66 ///
67 /// Boxed because a `ModelHeader` is large next to the other two answers, and this
68 /// enum is copied into every `WriteOptions`.
69 Given(Box<ModelHeader>),
70 /// Write no header. Not a conforming instance file.
71 Omit,
72}
73
74#[derive(Clone, Debug)]
75pub struct WriteOptions {
76 /// Write only attributes belonging to these profiles; zero means "everything".
77 ///
78 /// This is a *set*, not a single profile, because one instance file routinely serves
79 /// several: CGMES normally exchanges Equipment, Operation and ShortCircuit together,
80 /// and a file that declared only one of them would not reproduce its input.
81 pub profiles: ProfileMask,
82 pub id_style: IdStyle,
83 /// Indent nested elements. Off produces smaller files.
84 pub pretty: bool,
85 /// Where the document's `md:FullModel` comes from.
86 pub header: HeaderSource,
87 /// Emit the XML declaration.
88 pub xml_declaration: bool,
89}
90
91impl Default for WriteOptions {
92 fn default() -> Self {
93 WriteOptions {
94 profiles: 0,
95 id_style: IdStyle::Auto,
96 pretty: true,
97 header: HeaderSource::default(),
98 xml_declaration: true,
99 }
100 }
101}
102
103impl WriteOptions {
104 /// Write one profile's attributes, as a conforming instance file.
105 pub fn profile(profile: ProfileId) -> WriteOptions {
106 WriteOptions::profiles(profile.mask())
107 }
108
109 /// Write the attributes of every profile in `profiles`.
110 pub fn profiles(profiles: ProfileMask) -> WriteOptions {
111 WriteOptions {
112 profiles,
113 ..Default::default()
114 }
115 }
116
117 /// Write `header` rather than a derived one.
118 pub fn with_header(mut self, header: ModelHeader) -> Self {
119 self.header = HeaderSource::Given(Box::new(header));
120 self
121 }
122
123 /// Write no header at all.
124 ///
125 /// The result is not a conforming instance file. Use it for a fragment, or where the
126 /// caller assembles the document itself.
127 pub fn headerless(mut self) -> Self {
128 self.header = HeaderSource::Omit;
129 self
130 }
131 pub fn with_id_style(mut self, style: IdStyle) -> Self {
132 self.id_style = style;
133 self
134 }
135 pub fn compact(mut self) -> Self {
136 self.pretty = false;
137 self
138 }
139}
140
141/// Write every object of `dataset` as one CIM/XML document.
142pub fn write<W: Write>(dataset: &Dataset, out: W, options: &WriteOptions) -> Result<()> {
143 let ids: Vec<_> = dataset.iter().map(|(id, _)| id).collect();
144 write_objects(dataset, ids.into_iter(), out, options)
145}
146
147/// Write a chosen subset of objects as one CIM/XML document.
148pub fn write_objects<W: Write, I>(
149 dataset: &Dataset,
150 objects: I,
151 out: W,
152 options: &WriteOptions,
153) -> Result<()>
154where
155 I: Iterator<Item = crate::dataset::ObjectId>,
156{
157 let schema = dataset.schema();
158 let mut w = Writer::new(out, schema, options.pretty);
159
160 // Deterministic order: sort by mRID so output does not depend on load order.
161 let mut list: Vec<&Object> = objects.filter_map(|id| dataset.get(id)).collect();
162 list.sort_by(|a, b| a.mrid().cmp(b.mrid()));
163
164 w.start_document(options)?;
165 // IEC 61970-552 requires `md:FullModel rdf:about`, and a header a caller built by hand
166 // may not have one. The model's content identifier stands in: deterministic, distinct
167 // per model, and derived rather than invented — where the nil UUID would be a document
168 // this crate's own validator rejects.
169 match &options.header {
170 HeaderSource::Omit => {}
171 HeaderSource::Given(h) if h.id.is_some() => w.header(h)?,
172 HeaderSource::Given(h) => {
173 let mut h = h.clone();
174 h.id = Some(dataset.content_id());
175 w.header(&h)?;
176 }
177 HeaderSource::Derive => w.header(&derive_header(dataset, options.profiles))?,
178 }
179 for obj in list {
180 w.object(obj, options)?;
181 }
182 w.end_document()
183}
184
185/// Write one profile's slice of a dataset.
186pub fn write_profile<W: Write>(
187 dataset: &Dataset,
188 profile: ProfileId,
189 out: W,
190 options: &WriteOptions,
191) -> Result<()> {
192 write_profiles(dataset, profile.mask(), out, options)
193}
194
195/// Write the slice of a dataset belonging to a set of profiles.
196///
197/// This is how a multi-profile model is exported back to the file set it came from: a
198/// CGMES Equipment file that declared Equipment, Operation and ShortCircuit is rebuilt by
199/// passing all three, rather than being split into three files.
200pub fn write_profiles<W: Write>(
201 dataset: &Dataset,
202 profiles: ProfileMask,
203 out: W,
204 options: &WriteOptions,
205) -> Result<()> {
206 let schema = dataset.schema();
207 let mut opts = options.clone();
208 opts.profiles = profiles;
209
210 let ids: Vec<_> = dataset
211 .iter()
212 .filter(|(_, o)| object_in_profiles(schema, o, profiles))
213 .map(|(id, _)| id)
214 .collect();
215 write_objects(dataset, ids.into_iter(), out, &opts)
216}
217
218/// Write a difference model (IEC 61970-552 `dm:DifferenceModel`).
219///
220/// The counterpart of [`read_difference`](crate::reader::read_difference): a change file
221/// read in can be written back out. Statements are grouped by subject, reverse before
222/// forward, matching the published conformity change sets.
223///
224/// The difference's own header is used unless `options` supplies one.
225pub fn write_difference<W: Write>(
226 schema: &'static Schema,
227 diff: &DifferenceModel,
228 out: W,
229 options: &WriteOptions,
230) -> Result<()> {
231 let mut header = match &options.header {
232 HeaderSource::Given(h) => (**h).clone(),
233 // A change set is *about* a model, so a derived header cannot be built from data
234 // this function does not have. The difference's own header is the answer to both
235 // `Derive` and `Omit`: a `dm:DifferenceModel` element is the document's root
236 // content, not decoration that can be left out.
237 _ => diff.header.clone(),
238 };
239 header.kind = ModelKind::Difference;
240
241 let mut w = Writer::new(out, schema, options.pretty);
242 // Statement predicates may name namespaces outside the schema's own set — a difference
243 // can carry a vendor extension — so they are bound before the root element is written.
244 for s in diff.reverse.iter().chain(&diff.forward) {
245 w.bind_statement_namespaces(s);
246 }
247 let mut opts = options.clone();
248 opts.header = HeaderSource::Given(Box::new(header.clone()));
249 w.start_document(&opts)?;
250
251 w.header_open(&header)?;
252 w.header_body(&header)?;
253 // 61970-552 lists what is being replaced before what replaces it.
254 // In the published order: what must hold, what goes, what comes.
255 w.statements("preconditions", &diff.preconditions)?;
256 w.statements("reverseDifferences", &diff.reverse)?;
257 w.statements("forwardDifferences", &diff.forward)?;
258 w.header_close(&header)?;
259 w.end_document()
260}
261
262/// Whether a stored value belongs in an instance file serving `profiles`.
263///
264/// See [`Schema::effective_profiles`] for the rule. A zero mask means "no filtering".
265#[inline]
266fn slot_belongs_to(schema: &Schema, slot: &crate::object::Slot, profiles: ProfileMask) -> bool {
267 profiles == 0 || schema.effective_profiles(slot.attr, slot.profiles) & profiles != 0
268}
269
270/// Whether an object would serialize any attribute in `profiles`.
271pub fn object_has_content_in(schema: &Schema, obj: &Object, profiles: ProfileMask) -> bool {
272 obj.slots()
273 .iter()
274 .any(|s| slot_belongs_to(schema, s, profiles))
275}
276
277/// Whether an object belongs in a file serving `profiles` — which is not the same question
278/// as whether it has anything to *say* there.
279///
280/// A boundary set introduces a node and says nothing else about it:
281/// `<cim:ConnectivityNode rdf:ID="_x"/>` in Equipment Boundary, with Topology Boundary
282/// supplying the one attribute it has. Selecting by content alone drops that element, and
283/// the result is a file set whose Topology Boundary document points `rdf:about` at a
284/// definition no document contains. So an object also belongs where the profile both
285/// *introduces* its class and has seen it — which is a fact the reader recorded, not an
286/// inference (D55).
287pub fn object_in_profiles(schema: &Schema, obj: &Object, profiles: ProfileMask) -> bool {
288 object_has_content_in(schema, obj, profiles)
289 || (obj.profiles() & profiles != 0 && schema.class(obj.class()).defined_in & profiles != 0)
290}
291
292/// The prefix bindings of one output document.
293///
294/// A document's `xmlns:` declarations have to satisfy two constraints that writing them
295/// from several independent places violates easily, and both produce output that is not
296/// well-formed XML rather than output that is merely ugly:
297///
298/// * **Each prefix may be declared at most once on an element.** The schema's namespace
299/// table already contains `md` and `dm`, so emitting them again for the header is a
300/// duplicate attribute — which no CIM-tolerant reader notices and every XML parser
301/// rejects outright.
302/// * **A prefix must exist before it is used.** A header property read from a document
303/// that bound the *default* namespace has no prefix at all, and `<:Model.x>` is not a
304/// name.
305///
306/// Bindings are therefore resolved once, up front: every namespace the document can
307/// mention is registered here, a prefix is minted where the preferred one is taken by a
308/// different IRI, and the writer asks this type for the prefix of everything it emits.
309#[derive(Debug, Default)]
310struct Namespaces {
311 /// `(prefix, IRI)` in declaration order.
312 decls: Vec<(String, String)>,
313 /// Prefix chosen for each [`NsId`] of the schema.
314 by_ns: Vec<usize>,
315}
316
317impl Namespaces {
318 /// Bind `iri`, preferring `want` as its prefix, and return the binding's index.
319 ///
320 /// An IRI already bound keeps its existing prefix — that is what makes the schema's
321 /// `md` entry and the header's `md` requirement the same declaration instead of two.
322 fn bind(&mut self, want: &str, iri: &str) -> usize {
323 if let Some(i) = self.decls.iter().position(|(_, n)| n == iri) {
324 return i;
325 }
326 // `xml` and `xmlns` are reserved by the XML Namespaces recommendation, and an
327 // empty prefix cannot name an element in a document that uses no default
328 // namespace, so both fall back to a generated name.
329 let base = match want {
330 "" | "xml" | "xmlns" => "ns",
331 other => other,
332 };
333 let mut prefix = base.to_owned();
334 let mut n = 1;
335 while self.decls.iter().any(|(p, _)| *p == prefix) {
336 n += 1;
337 prefix = format!("{base}{n}");
338 }
339 self.decls.push((prefix, iri.to_owned()));
340 self.decls.len() - 1
341 }
342
343 /// Bindings for a document written against `schema`.
344 ///
345 /// The schema's full namespace set is declared whether or not a given document uses
346 /// all of it, so that output is stable across models and matches the published files.
347 fn for_schema(schema: &Schema) -> Namespaces {
348 let mut ns = Namespaces::default();
349 // `rdf` first and by that name: it is the one prefix IEC 61970-552 fixes, and the
350 // vocabularies themselves sometimes bind it under a generated name.
351 ns.bind("rdf", RDF_NS);
352 ns.by_ns = schema
353 .namespaces
354 .iter()
355 .map(|n| ns.bind(n.prefix, n.iri))
356 .collect();
357 ns
358 }
359
360 fn prefix(&self, ns: NsId) -> &str {
361 self.by_ns
362 .get(ns.index())
363 .map_or("ns", |&i| self.decls[i].0.as_str())
364 }
365
366 fn prefix_at(&self, index: usize) -> &str {
367 &self.decls[index].0
368 }
369
370 /// The prefix bound to `iri`, if the document declares it.
371 fn prefix_of_iri(&self, iri: &str) -> Option<&str> {
372 self.decls
373 .iter()
374 .find(|(_, n)| n == iri)
375 .map(|(p, _)| p.as_str())
376 }
377}
378
379struct Writer<W: Write> {
380 out: W,
381 schema: &'static Schema,
382 pretty: bool,
383 ns: Namespaces,
384 /// Prefix index for each entry of the header's `extra` list, in order.
385 extra_prefixes: Vec<usize>,
386}
387
388impl<W: Write> Writer<W> {
389 fn new(out: W, schema: &'static Schema, pretty: bool) -> Writer<W> {
390 Writer {
391 out,
392 schema,
393 pretty,
394 ns: Namespaces::for_schema(schema),
395 extra_prefixes: Vec::new(),
396 }
397 }
398
399 /// Register the namespaces a difference statement mentions.
400 fn bind_statement_namespaces(&mut self, s: &Statement) {
401 if let Some(q) = &s.class {
402 self.ns.bind(suggest_prefix(&q.ns), &q.ns);
403 }
404 self.ns
405 .bind(suggest_prefix(&s.predicate_ns), &s.predicate_ns);
406 }
407
408 /// The prefix under which the model-description vocabulary is written here.
409 fn md(&self) -> String {
410 self.ns.prefix_of_iri(MD_NS).unwrap_or("md").to_owned()
411 }
412 /// The prefix under which the difference-model vocabulary is written here.
413 fn dm(&self) -> String {
414 self.ns.prefix_of_iri(DM_NS).unwrap_or("dm").to_owned()
415 }
416
417 fn start_document(&mut self, options: &WriteOptions) -> Result<()> {
418 // Every prefix the document can use is resolved before anything is written, so a
419 // prefix is declared exactly once and always before its first use.
420 self.ns.bind("md", MD_NS);
421 self.ns.bind("dm", DM_NS);
422 // A given header may carry vendor properties in namespaces the schema knows
423 // nothing about; a derived one never does.
424 self.extra_prefixes = match &options.header {
425 HeaderSource::Given(h) => h
426 .extra
427 .iter()
428 .map(|p| self.ns.bind(&p.prefix, &p.ns))
429 .collect(),
430 _ => Vec::new(),
431 };
432
433 if options.xml_declaration {
434 self.out
435 .write_all(b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")?;
436 }
437 // `rdf` is bound first and to the RDF namespace, so the literal prefix used for
438 // `rdf:RDF`, `rdf:ID`, `rdf:resource` and `rdf:parseType` is always correct.
439 self.out.write_all(b"<rdf:RDF")?;
440 let decls = std::mem::take(&mut self.ns.decls);
441 for (prefix, iri) in &decls {
442 write!(self.out, " xmlns:{prefix}=\"").map_err(Error::Io)?;
443 self.escape_attr(iri)?;
444 self.out.write_all(b"\"")?;
445 }
446 self.ns.decls = decls;
447 self.out.write_all(b">\n")?;
448 Ok(())
449 }
450
451 fn end_document(&mut self) -> Result<()> {
452 self.out.write_all(b"</rdf:RDF>\n")?;
453 self.out.flush()?;
454 Ok(())
455 }
456
457 fn header(&mut self, h: &ModelHeader) -> Result<()> {
458 self.header_open(h)?;
459 self.header_body(h)?;
460 self.header_close(h)
461 }
462
463 fn header_element(&self, h: &ModelHeader) -> (String, &'static str) {
464 match h.kind {
465 ModelKind::Full => (self.md(), "FullModel"),
466 ModelKind::Difference => (self.dm(), "DifferenceModel"),
467 }
468 }
469
470 /// Open the header element.
471 ///
472 /// `write_objects` fills in a missing identifier from the model's content before
473 /// reaching here; a difference model derives one of its own. The nil UUID is the last
474 /// resort for a caller that reached the writer some other way, and it is deliberately
475 /// the *conforming-looking* wrong answer rather than an omitted attribute, because
476 /// `validate` reports it and an absent `rdf:about` would make the document unreadable.
477 fn header_open(&mut self, h: &ModelHeader) -> Result<()> {
478 let (prefix, elem) = self.header_element(h);
479 let about =
480 h.id.as_ref()
481 .map(Mrid::to_urn)
482 .unwrap_or_else(|| Mrid::nil().to_urn());
483 self.indent(1)?;
484 write!(self.out, "<{prefix}:{elem} rdf:about=\"").map_err(Error::Io)?;
485 self.escape_attr(&about)?;
486 self.out.write_all(b"\">\n")?;
487 Ok(())
488 }
489
490 fn header_close(&mut self, h: &ModelHeader) -> Result<()> {
491 let (prefix, elem) = self.header_element(h);
492 self.indent(1)?;
493 writeln!(self.out, "</{prefix}:{elem}>").map_err(Error::Io)?;
494 Ok(())
495 }
496
497 fn header_body(&mut self, h: &ModelHeader) -> Result<()> {
498 // Fixed order so headers are diffable across writes.
499 self.header_text(h.created.as_deref(), "Model.created")?;
500 self.header_text(h.scenario_time.as_deref(), "Model.scenarioTime")?;
501 self.header_text(h.description.as_deref(), "Model.description")?;
502 self.header_text(h.version.as_deref(), "Model.version")?;
503 self.header_text(
504 h.modeling_authority_set.as_deref(),
505 "Model.modelingAuthoritySet",
506 )?;
507 for p in &h.profiles {
508 self.header_text(Some(p), "Model.profile")?;
509 }
510 for d in &h.dependent_on {
511 self.header_resource(&d.to_urn(), "Model.DependentOn")?;
512 }
513 for s in &h.supersedes {
514 self.header_resource(&s.to_urn(), "Model.Supersedes")?;
515 }
516 // Prefixes for these were resolved at `start_document`, because a header property
517 // may use a prefix the schema does not know, or none at all.
518 let prefixes: Vec<String> = self
519 .extra_prefixes
520 .iter()
521 .map(|&i| self.ns.prefix_at(i).to_owned())
522 .collect();
523 for (p, prefix) in h.extra.iter().zip(&prefixes) {
524 match &p.value {
525 HeaderValue::Text(v) => self.header_prop_text(prefix, &p.local, v)?,
526 HeaderValue::Resource(v) => self.header_prop_resource(prefix, &p.local, v)?,
527 }
528 }
529 Ok(())
530 }
531
532 /// Write one `dm:preconditions` / `dm:reverseDifferences` / `dm:forwardDifferences`
533 /// statement set.
534 ///
535 /// Statements about the same subject share one `rdf:Description`, and a statement group
536 /// that named a class keeps it: a difference may reclassify an object, and the class
537 /// element is how it says so.
538 fn statements(&mut self, local: &str, statements: &[Statement]) -> Result<()> {
539 if statements.is_empty() {
540 return Ok(());
541 }
542 let dm = self.dm();
543 self.indent(2)?;
544 writeln!(self.out, "<{dm}:{local} rdf:parseType=\"Statements\">").map_err(Error::Io)?;
545
546 let mut i = 0;
547 while i < statements.len() {
548 let subject = &statements[i].subject;
549 let class = &statements[i].class;
550 let defines = statements[i].defines_subject;
551 let mut j = i;
552 while j < statements.len()
553 && statements[j].subject == *subject
554 && statements[j].class == *class
555 {
556 j += 1;
557 }
558
559 // The namespaces were bound before the root element was written, so a
560 // statement about a vendor extension keeps its own namespace instead of being
561 // relabelled `cim:` — which would have changed what the statement says.
562 let (prefix, name) = match class {
563 Some(q) => (
564 self.ns.prefix_of_iri(&q.ns).unwrap_or("ns").to_owned(),
565 q.local.clone(),
566 ),
567 None => ("rdf".to_owned(), "Description".to_owned()),
568 };
569 self.indent(3)?;
570 // The same override as an object element: an identifier that is an absolute
571 // IRI has no `rdf:ID` form, so the statement group names it with `rdf:about`.
572 if defines && subject.form_in_xml() != crate::xml::IdentifierForm::Iri {
573 write!(self.out, "<{prefix}:{name} rdf:ID=\"").map_err(Error::Io)?;
574 self.escape_attr(&subject.to_rdf_id())?;
575 } else {
576 write!(self.out, "<{prefix}:{name} rdf:about=\"").map_err(Error::Io)?;
577 self.escape_attr(&subject.to_rdf_reference())?;
578 }
579 self.out.write_all(b"\">\n")?;
580
581 for s in &statements[i..j] {
582 let p = self
583 .ns
584 .prefix_of_iri(&s.predicate_ns)
585 .unwrap_or("ns")
586 .to_owned();
587 let predicate = &s.predicate;
588 self.indent(4)?;
589 match &s.value {
590 StatementValue::Resource(iri) => {
591 write!(self.out, "<{p}:{predicate} rdf:resource=\"").map_err(Error::Io)?;
592 self.escape_attr(iri)?;
593 self.out.write_all(b"\"/>\n")?;
594 }
595 StatementValue::Literal(text) => {
596 write!(self.out, "<{p}:{predicate}>").map_err(Error::Io)?;
597 self.escape_text(text)?;
598 writeln!(self.out, "</{p}:{predicate}>").map_err(Error::Io)?;
599 }
600 }
601 }
602
603 self.indent(3)?;
604 writeln!(self.out, "</{prefix}:{name}>").map_err(Error::Io)?;
605 i = j;
606 }
607
608 self.indent(2)?;
609 writeln!(self.out, "</{dm}:{local}>").map_err(Error::Io)?;
610 Ok(())
611 }
612
613 fn header_text(&mut self, value: Option<&str>, local: &str) -> Result<()> {
614 let Some(v) = value else { return Ok(()) };
615 let md = self.md();
616 self.header_prop_text(&md, local, v)
617 }
618
619 fn header_resource(&mut self, value: &str, local: &str) -> Result<()> {
620 let md = self.md();
621 self.header_prop_resource(&md, local, value)
622 }
623
624 fn header_prop_text(&mut self, prefix: &str, local: &str, value: &str) -> Result<()> {
625 self.indent(2)?;
626 write!(self.out, "<{prefix}:{local}>").map_err(Error::Io)?;
627 self.escape_text(value)?;
628 writeln!(self.out, "</{prefix}:{local}>").map_err(Error::Io)?;
629 Ok(())
630 }
631
632 fn header_prop_resource(&mut self, prefix: &str, local: &str, value: &str) -> Result<()> {
633 self.indent(2)?;
634 write!(self.out, "<{prefix}:{local} rdf:resource=\"").map_err(Error::Io)?;
635 self.escape_attr(value)?;
636 self.out.write_all(b"\"/>\n")?;
637 Ok(())
638 }
639
640 /// Write one object element.
641 ///
642 /// The prefix table is borrowed from `self.ns` while the sink is borrowed mutably, so
643 /// the fields are destructured rather than reached through `self`. Doing it the other
644 /// way meant copying each prefix into a fresh `String` — one allocation per attribute
645 /// occurrence, over a million of them on a nation-scale model.
646 fn object(&mut self, obj: &Object, options: &WriteOptions) -> Result<()> {
647 let Writer {
648 out,
649 schema,
650 pretty,
651 ns,
652 ..
653 } = self;
654 let pretty = *pretty;
655 let all_attrs = schema.class(obj.class()).all_attrs;
656 let class = schema.class(element_class(schema, obj, obj.class(), options.profiles));
657 let prefix = ns.prefix(class.ns);
658
659 indent(out, pretty, 1)?;
660 write!(out, "<{}:{}", prefix, class.name).map_err(Error::Io)?;
661 // An identifier that is an absolute IRI has no `rdf:ID` form — `rdf:ID` is an XML
662 // `NCName` — so the choice the profile would make is overruled by what the syntax
663 // permits. `rdf:about` with the IRI itself is both valid and exactly what the
664 // document that supplied such an identifier said.
665 let mrid = obj.mrid();
666 match (
667 resolve_id_style(options, class),
668 mrid.form_in_xml() == crate::xml::IdentifierForm::Iri,
669 ) {
670 (_, true) | (IdStyle::RdfAbout, false) => {
671 out.write_all(b" rdf:about=\"")?;
672 escape_attr(out, &mrid.to_rdf_reference())?;
673 }
674 // `Auto` is resolved above; anything left is the explicit `rdf:ID` form.
675 _ => {
676 out.write_all(b" rdf:ID=\"")?;
677 escape_attr(out, &mrid.to_rdf_id())?;
678 }
679 }
680 // Asked of the object's own slots rather than of every attribute the class could
681 // have: an object carries four values on average against twenty-one possible ones.
682 if !object_has_content_in(schema, obj, options.profiles) {
683 out.write_all(b"\"/>\n")?;
684 return Ok(());
685 }
686 out.write_all(b"\">\n")?;
687
688 // Attributes are emitted in schema order, and taken from the object's own class
689 // rather than the element's: a Steady State Hypothesis file writes
690 // `<cim:Equipment>` but the value it carries is still declared where the real
691 // class declares it.
692 for attr_id in all_attrs {
693 let def = schema.attr(*attr_id);
694 let attr_prefix = ns.prefix(def.ns);
695 let prim = lexical_primitive(schema, def.kind);
696 for slot in obj.get_all(*attr_id) {
697 if !slot_belongs_to(schema, slot, options.profiles) {
698 continue;
699 }
700 property(
701 out,
702 schema,
703 ns,
704 pretty,
705 attr_prefix,
706 def.name,
707 &slot.value,
708 prim,
709 2,
710 )?;
711 }
712 }
713
714 indent(out, pretty, 1)?;
715 writeln!(out, "</{}:{}>", prefix, class.name).map_err(Error::Io)?;
716 Ok(())
717 }
718
719 fn indent(&mut self, level: usize) -> Result<()> {
720 indent(&mut self.out, self.pretty, level)
721 }
722
723 fn escape_text(&mut self, s: &str) -> Result<()> {
724 escape_text(&mut self.out, s)
725 }
726
727 fn escape_attr(&mut self, s: &str) -> Result<()> {
728 escape_attr(&mut self.out, s)
729 }
730}
731
732/// Write one property element, recursing into compounds.
733///
734/// `prim` is the primitive the schema gives the attribute, which decides the lexical
735/// form: `Decimal` has no exponent notation, `Float` does.
736#[allow(clippy::too_many_arguments)]
737fn property<W: Write>(
738 out: &mut W,
739 schema: &'static Schema,
740 ns: &Namespaces,
741 pretty: bool,
742 prefix: &str,
743 name: &str,
744 value: &Value,
745 prim: Primitive,
746 depth: usize,
747) -> Result<()> {
748 indent(out, pretty, depth)?;
749 match value {
750 Value::Reference(m) => {
751 write!(out, "<{prefix}:{name} rdf:resource=\"").map_err(Error::Io)?;
752 escape_attr(out, &m.to_rdf_reference())?;
753 out.write_all(b"\"/>\n")?;
754 }
755 Value::Enum(e) => {
756 let ev = schema.enum_value(*e);
757 write!(out, "<{prefix}:{name} rdf:resource=\"").map_err(Error::Io)?;
758 escape_attr(out, schema.namespace(ev.ns).iri)?;
759 escape_attr(out, ev.name)?;
760 out.write_all(b"\"/>\n")?;
761 }
762 // A compound has no identity, so it is written inline rather than referenced.
763 // `rdf:parseType="Resource"` is what makes the nested element a blank node.
764 Value::Compound(c) => {
765 if c.is_empty() {
766 writeln!(out, "<{prefix}:{name} rdf:parseType=\"Resource\"/>")
767 .map_err(Error::Io)?;
768 return Ok(());
769 }
770 writeln!(out, "<{prefix}:{name} rdf:parseType=\"Resource\">").map_err(Error::Io)?;
771 for (attr, v) in c.values() {
772 let def = schema.attr(*attr);
773 property(
774 out,
775 schema,
776 ns,
777 pretty,
778 ns.prefix(def.ns),
779 def.name,
780 v,
781 lexical_primitive(schema, def.kind),
782 depth + 1,
783 )?;
784 }
785 indent(out, pretty, depth)?;
786 writeln!(out, "</{prefix}:{name}>").map_err(Error::Io)?;
787 }
788 other => {
789 write!(out, "<{prefix}:{name}>").map_err(Error::Io)?;
790 if let Some(text) = other.to_lexical_as(prim) {
791 escape_text(out, &text)?;
792 }
793 writeln!(out, "</{prefix}:{name}>").map_err(Error::Io)?;
794 }
795 }
796 Ok(())
797}
798
799fn indent<W: Write>(out: &mut W, pretty: bool, level: usize) -> Result<()> {
800 if pretty {
801 for _ in 0..level {
802 out.write_all(b" ")?;
803 }
804 }
805 Ok(())
806}
807
808/// Escape a value for element content.
809///
810/// Only `&` and `<` have to be escaped in character data; `>` is escaped as well because a
811/// bare `]]>` is forbidden and escaping every `>` is the cheap way to be sure. Quotes are
812/// left alone — a name containing an apostrophe is written as the producer wrote it rather
813/// than as `'`.
814///
815/// Carriage return is escaped numerically. It has to be: an XML parser normalizes literal
816/// CR and CRLF in content to LF, so a value carrying one would come back different from
817/// the value that was written.
818fn escape_text<W: Write>(out: &mut W, s: &str) -> Result<()> {
819 escape(out, s, |b| match b {
820 b'&' => Some(b"&".as_slice()),
821 b'<' => Some(b"<"),
822 b'>' => Some(b">"),
823 b'\r' => Some(b" "),
824 _ => None,
825 })
826}
827
828/// Escape a value for a double-quoted attribute.
829///
830/// Beyond the markup characters, every whitespace control character is escaped
831/// numerically, because attribute-value normalization replaces a literal tab, newline or
832/// carriage return with a space before an application ever sees it — silently changing the
833/// value.
834fn escape_attr<W: Write>(out: &mut W, s: &str) -> Result<()> {
835 escape(out, s, |b| match b {
836 b'&' => Some(b"&".as_slice()),
837 b'<' => Some(b"<"),
838 b'>' => Some(b">"),
839 b'"' => Some(b"""),
840 b'\t' => Some(b"	"),
841 b'\n' => Some(b" "),
842 b'\r' => Some(b" "),
843 _ => None,
844 })
845}
846
847/// Copy `s`, replacing the bytes `rep` names, and dropping what XML cannot represent.
848///
849/// Multi-byte characters are untouched by the replacement table because every replaced
850/// byte is ASCII and so never part of one.
851///
852/// The removal is the part that is not decoration. XML 1.0's `Char` production excludes
853/// most of the C0 range *and* forbids a numeric character reference to it, so a value
854/// carrying a NUL has no representation at all and a document containing one is refused by
855/// every conforming parser at that byte, and `quick-xml` enforces neither end of this.
856/// Dropping the character is the only alternative to writing an unreadable document; it is
857/// not silent, because [`Rule::IllegalXmlCharacter`] fires where the value enters and again
858/// for any value still holding one in the store.
859///
860/// [`Rule::IllegalXmlCharacter`]: crate::Rule::IllegalXmlCharacter
861fn escape<W: Write>(out: &mut W, s: &str, rep: fn(u8) -> Option<&'static [u8]>) -> Result<()> {
862 // One byte test per byte on the common path, and no allocation unless it fires.
863 let cleaned = crate::xml::strip_illegal(s);
864 let bytes = cleaned.as_bytes();
865 let mut start = 0;
866 for (i, &b) in bytes.iter().enumerate() {
867 let Some(r) = rep(b) else { continue };
868 out.write_all(&bytes[start..i])?;
869 out.write_all(r)?;
870 start = i + 1;
871 }
872 out.write_all(&bytes[start..])?;
873 Ok(())
874}
875
876/// The primitive an attribute's values are written as.
877///
878/// A CIM datatype such as `Money` serializes as the primitive it wraps; anything with a
879/// serialization of its own — an enumeration, a reference, a compound — never reaches the
880/// text path, so `String` is a harmless stand-in.
881fn lexical_primitive(schema: &Schema, kind: AttrKind) -> Primitive {
882 match kind {
883 AttrKind::Primitive(p) => p,
884 AttrKind::Datatype(d) => schema.datatype(d).value,
885 _ => Primitive::String,
886 }
887}
888
889/// A prefix to suggest for a namespace the schema does not know, derived from its IRI.
890///
891/// `http://example.com/vendor#` yields `vendor`; anything unusable yields `ns`, which
892/// [`Namespaces::bind`] then makes unique.
893fn suggest_prefix(iri: &str) -> &str {
894 let trimmed = iri.trim_end_matches(['#', '/']);
895 let last = trimmed.rsplit(['#', '/', ':']).next().unwrap_or_default();
896 let usable = !last.is_empty()
897 && last.starts_with(|c: char| c.is_ascii_alphabetic())
898 && last
899 .chars()
900 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
901 if usable { last } else { "ns" }
902}
903
904/// The class an object is written as in a file serving `profiles`.
905///
906/// An instance file may only name classes its own profiles declare, and may only name one
907/// whose mandatory attributes it actually carries. A Steady State Hypothesis file
908/// therefore writes `<cim:Equipment rdf:about="…">` for an `ACLineSegment` — SSH declares
909/// `Equipment` but not `ACLineSegment` — and re-reading it merges the value back onto the
910/// object the Equipment file defined. Emitting the most specific class instead produces a
911/// document that fails the profile's own SHACL shapes.
912///
913/// Both conditions are load-bearing, and the published models show each. FullGrid's SSH
914/// file writes 61 objects as `cim:Equipment` because SSH declares none of their classes,
915/// and writes one `Cut` that way too: SSH declares `Cut`'s parent `Switch`, but `Switch`
916/// requires `open`, which that object has no value for, so the generic carrier is the only
917/// class the data supports.
918///
919/// The object's own class is kept when nothing better applies, rather than losing it.
920pub fn element_class(
921 schema: &Schema,
922 obj: &Object,
923 class: ClassId,
924 profiles: ProfileMask,
925) -> ClassId {
926 // Writing everything into one document imposes no profile, so the real class stands.
927 if profiles == 0 {
928 return class;
929 }
930 let declared = |c: ClassId| {
931 let d = schema.class(c);
932 d.concrete && !d.compound && d.profiles & profiles != 0
933 };
934 // Every mandatory attribute this profile expects of the class must be supplied by the
935 // *model*, or the document would claim more than the data supports.
936 //
937 // The model, not this file — `obj.has(a)` rather than "is `a` written here". The
938 // stricter reading looks more correct and is not: `IdentifiedObject.mRID` is mandatory
939 // in ten of eleven CGMES 3.0 profiles, and the published Steady State Hypothesis files
940 // do not carry it (which is the one finding ENTSO-E's own shapes report against their
941 // own models). Under the stricter rule no class is ever complete for SSH, every
942 // candidate fails, and the fallback writes the *most specific* class — the exact
943 // opposite of what this function exists to do, and what a corpus census catches.
944 let complete = |c: ClassId| {
945 schema.class(c).all_attrs.iter().all(|&a| {
946 let def = schema.attr(a);
947 !(def.mult.is_required() && def.used_in & profiles != 0) || obj.has(a)
948 })
949 };
950 std::iter::once(class)
951 .chain(schema.class(class).ancestors.iter().copied())
952 .find(|&c| declared(c) && complete(c))
953 .unwrap_or(class)
954}
955
956/// The header a document gets when the caller supplies none.
957///
958/// Public so a caller can derive one, adjust it — a modelling authority set, a scenario
959/// time — and pass it back through [`WriteOptions::with_header`].
960///
961/// Declares exactly the profiles being written — the mask when one is given, otherwise
962/// every profile the data actually covers — because `md:Model.profile` is how a consumer
963/// decides what a file is, and claiming a profile the file says nothing about is worse
964/// than claiming none.
965///
966/// The identifier is an RFC 4122 v5 UUID over the vintage, those profiles and the model's
967/// content identifier: deterministic, distinct per model, and needing no clock and no
968/// dependency. `Model.created` is deliberately absent rather than invented — this crate
969/// reads no clock, and a timestamp that is not when the model was made is worse than an
970/// absent one.
971pub fn derive_header(dataset: &Dataset, profiles: ProfileMask) -> ModelHeader {
972 derive_header_with(
973 dataset.schema(),
974 if profiles == 0 {
975 dataset.profiles()
976 } else {
977 profiles
978 },
979 &dataset.content_id(),
980 )
981}
982
983/// The same, from an already-computed content identifier.
984///
985/// Split out because `Dataset::content_id` walks the whole model — 88 ms on the 112 MiB
986/// `RealGrid` — and an export that writes eleven profile files would otherwise walk it
987/// eleven times to derive eleven headers that all name the same model.
988pub(crate) fn derive_header_with(
989 schema: &'static Schema,
990 covered: ProfileMask,
991 content: &Mrid,
992) -> ModelHeader {
993 let iris: Vec<String> = schema
994 .profiles
995 .iter()
996 .enumerate()
997 .filter(|(i, _)| covered & (1u64 << i) != 0)
998 .map(|(_, p)| p.version_iri.to_owned())
999 .collect();
1000
1001 let mut name = format!("{}\u{1e}", schema.vintage);
1002 for iri in &iris {
1003 name.push_str(iri);
1004 name.push('\u{1e}');
1005 }
1006 name.push_str(&content.to_string());
1007
1008 ModelHeader {
1009 kind: ModelKind::Full,
1010 id: Some(Mrid::new_v5(&Dataset::DERIVED_NS, name.as_bytes())),
1011 profiles: iris,
1012 version: Some("1".to_owned()),
1013 ..Default::default()
1014 }
1015}
1016
1017/// How an object of `class` is identified in a file serving `options.profiles`.
1018///
1019/// Exposed so tooling can predict the output without rendering it.
1020pub fn id_style_for(schema: &Schema, class: ClassId, profiles: ProfileMask) -> IdStyle {
1021 resolve_id_style(
1022 &WriteOptions {
1023 profiles,
1024 ..Default::default()
1025 },
1026 schema.class(class),
1027 )
1028}
1029
1030fn resolve_id_style(options: &WriteOptions, class: &ClassDef) -> IdStyle {
1031 match options.id_style {
1032 IdStyle::Auto => {
1033 // Writing everything into one document makes that document the definition.
1034 if options.profiles == 0 || class.defined_in & options.profiles != 0 {
1035 IdStyle::RdfId
1036 } else if class.profiles & options.profiles == 0 {
1037 // No profile this file serves mentions the class at all, so `rdf:about`
1038 // would name a definition no file in the set contains. Real headers reach
1039 // this by under-declaring — Equipment naming only `EquipmentCore/3/1` while
1040 // carrying `LoadArea` — and the file carrying the object is then the only
1041 // thing that can introduce it. The header is a claim, the data is evidence,
1042 // which is D7's rule for values applied to identity (D57).
1043 //
1044 // Imprecise in one unobserved case: two files that both under-declare and
1045 // both carry the object would each introduce it. Recovering that needs each
1046 // document's form carried rather than re-derived (D2), and neither corpus
1047 // contains it.
1048 IdStyle::RdfId
1049 } else {
1050 IdStyle::RdfAbout
1051 }
1052 }
1053 forced => forced,
1054 }
1055}
1056
1057/// Classes that a profile may contain, for callers building per-profile exports.
1058pub fn classes_in_profile(
1059 schema: &Schema,
1060 profile: ProfileId,
1061) -> impl Iterator<Item = ClassId> + '_ {
1062 let mask = profile.mask();
1063 schema
1064 .classes
1065 .iter()
1066 .enumerate()
1067 .filter(move |(_, c)| c.concrete && !c.compound && c.profiles & mask != 0)
1068 .map(|(i, _)| ClassId(i as u16))
1069}