Skip to main content

cim_kit/
writer.rs

1//! Writer for CIM/XML instance documents (IEC 61970-552).
2//!
3//! Output is deterministic: objects in ascending mRID order, attributes in schema order,
4//! so an unchanged model re-writes byte-identically.
5
6use std::io::Write;
7
8use crate::dataset::Dataset;
9use crate::error::{Error, Result};
10use crate::header::{
11    DM_NS, DifferenceModel, HeaderValue, MD_NS, ModelHeader, ModelKind, Statement, StatementValue,
12};
13use crate::mrid::Mrid;
14use crate::object::Object;
15use crate::schema::{AttrKind, ClassDef, ClassId, NsId, Primitive, ProfileId, ProfileMask, Schema};
16use crate::value::Value;
17
18const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
19
20/// How to identify objects in the output.
21///
22/// IEC 61970-552 distinguishes the file that *introduces* an object (`rdf:ID`) from one
23/// that adds to it (`rdf:about`); the RDFS marks a class a profile only refers to with
24/// `cims:stereotype Description`.
25#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
26pub enum IdStyle {
27    /// Decide per object from the schema (the default).
28    ///
29    /// `rdf:ID` when some profile in the write set *defines* the class
30    /// ([`ClassDef::defined_in`](crate::schema::ClassDef::defined_in)), `rdf:about`
31    /// otherwise. Per class, not per file: a Topology file writes `TopologicalNode` with
32    /// `rdf:ID` and `Terminal` with `rdf:about`.
33    #[default]
34    Auto,
35    /// Force `rdf:ID="_<uuid>"` for every object.
36    RdfId,
37    /// Force `rdf:about="#_<uuid>"` for every object.
38    RdfAbout,
39}
40
41/// Where a document's `md:FullModel` header comes from.
42///
43/// IEC 61970-552 gives every instance file a header declaring its profiles and
44/// dependencies, so deriving one is the default.
45#[derive(Clone, Debug, Default)]
46pub enum HeaderSource {
47    /// Derive one from the dataset: identified by its content, declaring the profiles
48    /// actually written.
49    ///
50    /// Deterministic and clock-free: the identifier is an RFC 4122 v5 UUID over the
51    /// model's content.
52    #[default]
53    Derive,
54    /// Write this header, which is how a model is written back as the file set it came
55    /// from. An identifier is filled in from the model's content if it has none.
56    ///
57    /// Boxed: a `ModelHeader` is large and this enum sits in every `WriteOptions`.
58    Given(Box<ModelHeader>),
59    /// Write no header. Not a conforming instance file.
60    Omit,
61}
62
63/// Options controlling serialization.
64#[derive(Clone, Debug)]
65pub struct WriteOptions {
66    /// Write only attributes belonging to these profiles; zero means "everything".
67    ///
68    /// A set, because one file often serves several (e.g. Equipment, Operation and
69    /// ShortCircuit together).
70    pub profiles: ProfileMask,
71    pub id_style: IdStyle,
72    /// Indent nested elements. Off produces smaller files.
73    pub pretty: bool,
74    /// Where the document's `md:FullModel` comes from.
75    pub header: HeaderSource,
76    /// Emit the XML declaration.
77    pub xml_declaration: bool,
78}
79
80impl Default for WriteOptions {
81    fn default() -> Self {
82        WriteOptions {
83            profiles: 0,
84            id_style: IdStyle::Auto,
85            pretty: true,
86            header: HeaderSource::default(),
87            xml_declaration: true,
88        }
89    }
90}
91
92impl WriteOptions {
93    /// Write one profile's attributes, as a conforming instance file.
94    pub fn profile(profile: ProfileId) -> WriteOptions {
95        WriteOptions::profiles(profile.mask())
96    }
97
98    /// Write the attributes of every profile in `profiles`.
99    pub fn profiles(profiles: ProfileMask) -> WriteOptions {
100        WriteOptions {
101            profiles,
102            ..Default::default()
103        }
104    }
105
106    /// Write `header` rather than a derived one.
107    pub fn with_header(mut self, header: ModelHeader) -> Self {
108        self.header = HeaderSource::Given(Box::new(header));
109        self
110    }
111
112    /// Write no header at all.
113    ///
114    /// The result is not a conforming instance file. Use it for a fragment, or where the
115    /// caller assembles the document itself.
116    pub fn headerless(mut self) -> Self {
117        self.header = HeaderSource::Omit;
118        self
119    }
120    pub fn with_id_style(mut self, style: IdStyle) -> Self {
121        self.id_style = style;
122        self
123    }
124    pub fn compact(mut self) -> Self {
125        self.pretty = false;
126        self
127    }
128}
129
130/// Write every object of `dataset` as one CIM/XML document.
131pub fn write<W: Write>(dataset: &Dataset, out: W, options: &WriteOptions) -> Result<()> {
132    let ids: Vec<_> = dataset.iter().map(|(id, _)| id).collect();
133    write_objects(dataset, ids.into_iter(), out, options)
134}
135
136/// Write a chosen subset of objects as one CIM/XML document.
137pub fn write_objects<W: Write, I>(
138    dataset: &Dataset,
139    objects: I,
140    out: W,
141    options: &WriteOptions,
142) -> Result<()>
143where
144    I: Iterator<Item = crate::dataset::ObjectId>,
145{
146    let schema = dataset.schema();
147    let mut w = Writer::new(out, schema, options.pretty);
148
149    // Deterministic order: sort by mRID so output does not depend on load order.
150    let mut list: Vec<&Object> = objects.filter_map(|id| dataset.get(id)).collect();
151    list.sort_by(|a, b| a.mrid().cmp(b.mrid()));
152
153    w.start_document(options)?;
154    // 552 requires `md:FullModel rdf:about`; a hand-built header without one gets the
155    // model's content identifier.
156    match &options.header {
157        HeaderSource::Omit => {}
158        HeaderSource::Given(h) if h.id.is_some() => w.header(h)?,
159        HeaderSource::Given(h) => {
160            let mut h = h.clone();
161            h.id = Some(dataset.content_id());
162            w.header(&h)?;
163        }
164        HeaderSource::Derive => w.header(&derive_header(dataset, options.profiles))?,
165    }
166    for obj in list {
167        w.object(obj, options)?;
168    }
169    w.end_document()
170}
171
172/// Write one profile's slice of a dataset.
173pub fn write_profile<W: Write>(
174    dataset: &Dataset,
175    profile: ProfileId,
176    out: W,
177    options: &WriteOptions,
178) -> Result<()> {
179    write_profiles(dataset, profile.mask(), out, options)
180}
181
182/// Write the slice of a dataset belonging to a set of profiles.
183///
184/// E.g. an Equipment file that declared Equipment, Operation and ShortCircuit is rebuilt
185/// by passing all three.
186pub fn write_profiles<W: Write>(
187    dataset: &Dataset,
188    profiles: ProfileMask,
189    out: W,
190    options: &WriteOptions,
191) -> Result<()> {
192    let schema = dataset.schema();
193    let mut opts = options.clone();
194    opts.profiles = profiles;
195
196    let ids: Vec<_> = dataset
197        .iter()
198        .filter(|(_, o)| object_in_profiles(schema, o, profiles))
199        .map(|(id, _)| id)
200        .collect();
201    write_objects(dataset, ids.into_iter(), out, &opts)
202}
203
204/// Write a difference model (IEC 61970-552 `dm:DifferenceModel`).
205///
206/// The counterpart of [`read_difference`](crate::reader::read_difference). Statements
207/// are grouped by subject; preconditions, then reverse, then forward differences.
208///
209/// The difference's own header is used unless `options` supplies one.
210pub fn write_difference<W: Write>(
211    schema: &'static Schema,
212    diff: &DifferenceModel,
213    out: W,
214    options: &WriteOptions,
215) -> Result<()> {
216    let mut header = match &options.header {
217        HeaderSource::Given(h) => (**h).clone(),
218        // `Derive` and `Omit` both use the difference's own header: there is no data to
219        // derive from, and `dm:DifferenceModel` is the document's content.
220        _ => diff.header.clone(),
221    };
222    header.kind = ModelKind::Difference;
223
224    let mut w = Writer::new(out, schema, options.pretty);
225    // Predicates may use namespaces outside the schema (vendor extensions); bind them
226    // before the root element.
227    for s in diff.reverse.iter().chain(&diff.forward) {
228        w.bind_statement_namespaces(s);
229    }
230    let mut opts = options.clone();
231    opts.header = HeaderSource::Given(Box::new(header.clone()));
232    w.start_document(&opts)?;
233
234    w.header_open(&header)?;
235    w.header_body(&header)?;
236    // Published order: what must hold, what goes, what comes.
237    w.statements("preconditions", &diff.preconditions)?;
238    w.statements("reverseDifferences", &diff.reverse)?;
239    w.statements("forwardDifferences", &diff.forward)?;
240    w.header_close(&header)?;
241    w.end_document()
242}
243
244/// Whether a stored value belongs in an instance file serving `profiles`.
245///
246/// See [`Schema::effective_profiles`] for the rule. A zero mask means "no filtering".
247#[inline]
248fn slot_belongs_to(schema: &Schema, slot: &crate::object::Slot, profiles: ProfileMask) -> bool {
249    profiles == 0 || schema.effective_profiles(slot.attr, slot.profiles) & profiles != 0
250}
251
252/// Whether an object would serialize any attribute in `profiles`.
253pub fn object_has_content_in(schema: &Schema, obj: &Object, profiles: ProfileMask) -> bool {
254    obj.slots()
255        .iter()
256        .any(|s| slot_belongs_to(schema, s, profiles))
257}
258
259/// Whether an object belongs in a file serving `profiles` — which is not the same question
260/// as whether it has anything to *say* there.
261///
262/// An object also belongs where a profile *introduces* its class and the reader saw it
263/// there, even with no values: e.g. `<cim:ConnectivityNode rdf:ID="_x"/>` in Equipment
264/// Boundary (D55).
265pub fn object_in_profiles(schema: &Schema, obj: &Object, profiles: ProfileMask) -> bool {
266    object_has_content_in(schema, obj, profiles)
267        || (obj.profiles() & profiles != 0 && schema.class(obj.class()).defined_in & profiles != 0)
268}
269
270/// The prefix bindings of one output document.
271///
272/// Resolved once, up front, so each prefix is declared exactly once (a duplicate `xmlns:md`
273/// is not well-formed) and exists before use (a header property read from a default
274/// namespace has no prefix). A prefix is minted where the preferred one is taken.
275#[derive(Debug, Default)]
276struct Namespaces {
277    /// `(prefix, IRI)` in declaration order.
278    decls: Vec<(String, String)>,
279    /// Prefix chosen for each [`NsId`] of the schema.
280    by_ns: Vec<usize>,
281}
282
283impl Namespaces {
284    /// Bind `iri`, preferring `want` as its prefix, and return the binding's index.
285    ///
286    /// An IRI already bound keeps its existing prefix.
287    fn bind(&mut self, want: &str, iri: &str) -> usize {
288        if let Some(i) = self.decls.iter().position(|(_, n)| n == iri) {
289            return i;
290        }
291        // `xml`/`xmlns` are reserved and an empty prefix is unusable: generate a name.
292        let base = match want {
293            "" | "xml" | "xmlns" => "ns",
294            other => other,
295        };
296        let mut prefix = base.to_owned();
297        let mut n = 1;
298        while self.decls.iter().any(|(p, _)| *p == prefix) {
299            n += 1;
300            prefix = format!("{base}{n}");
301        }
302        self.decls.push((prefix, iri.to_owned()));
303        self.decls.len() - 1
304    }
305
306    /// Bindings for a document written against `schema`.
307    ///
308    /// Declares the schema's full namespace set, used or not, so output is stable.
309    fn for_schema(schema: &Schema) -> Namespaces {
310        let mut ns = Namespaces::default();
311        // `rdf` first and by that name: the one prefix 552 fixes.
312        ns.bind("rdf", RDF_NS);
313        ns.by_ns = schema
314            .namespaces
315            .iter()
316            .map(|n| ns.bind(n.prefix, n.iri))
317            .collect();
318        ns
319    }
320
321    fn prefix(&self, ns: NsId) -> &str {
322        self.by_ns
323            .get(ns.index())
324            .map_or("ns", |&i| self.decls[i].0.as_str())
325    }
326
327    fn prefix_at(&self, index: usize) -> &str {
328        &self.decls[index].0
329    }
330
331    /// The prefix bound to `iri`, if the document declares it.
332    fn prefix_of_iri(&self, iri: &str) -> Option<&str> {
333        self.decls
334            .iter()
335            .find(|(_, n)| n == iri)
336            .map(|(p, _)| p.as_str())
337    }
338}
339
340struct Writer<W: Write> {
341    out: W,
342    schema: &'static Schema,
343    pretty: bool,
344    ns: Namespaces,
345    /// Prefix index for each entry of the header's `extra` list, in order.
346    extra_prefixes: Vec<usize>,
347}
348
349impl<W: Write> Writer<W> {
350    fn new(out: W, schema: &'static Schema, pretty: bool) -> Writer<W> {
351        Writer {
352            out,
353            schema,
354            pretty,
355            ns: Namespaces::for_schema(schema),
356            extra_prefixes: Vec::new(),
357        }
358    }
359
360    /// Register the namespaces a difference statement mentions.
361    fn bind_statement_namespaces(&mut self, s: &Statement) {
362        if let Some(q) = &s.class {
363            self.ns.bind(suggest_prefix(&q.ns), &q.ns);
364        }
365        self.ns
366            .bind(suggest_prefix(&s.predicate_ns), &s.predicate_ns);
367    }
368
369    /// The prefix under which the model-description vocabulary is written here.
370    fn md(&self) -> String {
371        self.ns.prefix_of_iri(MD_NS).unwrap_or("md").to_owned()
372    }
373    /// The prefix under which the difference-model vocabulary is written here.
374    fn dm(&self) -> String {
375        self.ns.prefix_of_iri(DM_NS).unwrap_or("dm").to_owned()
376    }
377
378    fn start_document(&mut self, options: &WriteOptions) -> Result<()> {
379        // Resolve every prefix before writing anything.
380        self.ns.bind("md", MD_NS);
381        self.ns.bind("dm", DM_NS);
382        // A given header may carry vendor properties in namespaces the schema knows
383        // nothing about; a derived one never does.
384        self.extra_prefixes = match &options.header {
385            HeaderSource::Given(h) => h
386                .extra
387                .iter()
388                .map(|p| self.ns.bind(&p.prefix, &p.ns))
389                .collect(),
390            _ => Vec::new(),
391        };
392
393        if options.xml_declaration {
394            self.out
395                .write_all(b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")?;
396        }
397        // `rdf` is bound first, so the literal `rdf:` prefix used below is correct.
398        self.out.write_all(b"<rdf:RDF")?;
399        let decls = std::mem::take(&mut self.ns.decls);
400        for (prefix, iri) in &decls {
401            write!(self.out, " xmlns:{prefix}=\"").map_err(Error::Io)?;
402            self.escape_attr(iri)?;
403            self.out.write_all(b"\"")?;
404        }
405        self.ns.decls = decls;
406        self.out.write_all(b">\n")?;
407        Ok(())
408    }
409
410    fn end_document(&mut self) -> Result<()> {
411        self.out.write_all(b"</rdf:RDF>\n")?;
412        self.out.flush()?;
413        Ok(())
414    }
415
416    fn header(&mut self, h: &ModelHeader) -> Result<()> {
417        self.header_open(h)?;
418        self.header_body(h)?;
419        self.header_close(h)
420    }
421
422    fn header_element(&self, h: &ModelHeader) -> (String, &'static str) {
423        match h.kind {
424            ModelKind::Full => (self.md(), "FullModel"),
425            ModelKind::Difference => (self.dm(), "DifferenceModel"),
426        }
427    }
428
429    /// Open the header element.
430    ///
431    /// Callers normally fill in a missing identifier first; the nil UUID is the last
432    /// resort, since `validate` reports it and an absent `rdf:about` is unreadable.
433    fn header_open(&mut self, h: &ModelHeader) -> Result<()> {
434        let (prefix, elem) = self.header_element(h);
435        let about =
436            h.id.as_ref()
437                .map(Mrid::to_urn)
438                .unwrap_or_else(|| Mrid::nil().to_urn());
439        self.indent(1)?;
440        write!(self.out, "<{prefix}:{elem} rdf:about=\"").map_err(Error::Io)?;
441        self.escape_attr(&about)?;
442        self.out.write_all(b"\">\n")?;
443        Ok(())
444    }
445
446    fn header_close(&mut self, h: &ModelHeader) -> Result<()> {
447        let (prefix, elem) = self.header_element(h);
448        self.indent(1)?;
449        writeln!(self.out, "</{prefix}:{elem}>").map_err(Error::Io)?;
450        Ok(())
451    }
452
453    fn header_body(&mut self, h: &ModelHeader) -> Result<()> {
454        // Fixed order so headers are diffable across writes.
455        self.header_text(h.created.as_deref(), "Model.created")?;
456        self.header_text(h.scenario_time.as_deref(), "Model.scenarioTime")?;
457        self.header_text(h.description.as_deref(), "Model.description")?;
458        self.header_text(h.version.as_deref(), "Model.version")?;
459        self.header_text(
460            h.modeling_authority_set.as_deref(),
461            "Model.modelingAuthoritySet",
462        )?;
463        for p in &h.profiles {
464            self.header_text(Some(p), "Model.profile")?;
465        }
466        for d in &h.dependent_on {
467            self.header_resource(&d.to_urn(), "Model.DependentOn")?;
468        }
469        for s in &h.supersedes {
470            self.header_resource(&s.to_urn(), "Model.Supersedes")?;
471        }
472        // Prefixes resolved at `start_document`; the schema may not know them.
473        let prefixes: Vec<String> = self
474            .extra_prefixes
475            .iter()
476            .map(|&i| self.ns.prefix_at(i).to_owned())
477            .collect();
478        for (p, prefix) in h.extra.iter().zip(&prefixes) {
479            match &p.value {
480                HeaderValue::Text(v) => self.header_prop_text(prefix, &p.local, v)?,
481                HeaderValue::Resource(v) => self.header_prop_resource(prefix, &p.local, v)?,
482            }
483        }
484        Ok(())
485    }
486
487    /// Write one `dm:preconditions` / `dm:reverseDifferences` / `dm:forwardDifferences`
488    /// statement set.
489    ///
490    /// Statements about one subject share an element; a group that named a class keeps it,
491    /// since that is how a difference reclassifies an object.
492    fn statements(&mut self, local: &str, statements: &[Statement]) -> Result<()> {
493        if statements.is_empty() {
494            return Ok(());
495        }
496        let dm = self.dm();
497        self.indent(2)?;
498        writeln!(self.out, "<{dm}:{local} rdf:parseType=\"Statements\">").map_err(Error::Io)?;
499
500        let mut i = 0;
501        while i < statements.len() {
502            let subject = &statements[i].subject;
503            let class = &statements[i].class;
504            let defines = statements[i].defines_subject;
505            let mut j = i;
506            while j < statements.len()
507                && statements[j].subject == *subject
508                && statements[j].class == *class
509            {
510                j += 1;
511            }
512
513            // Bound before the root, so a vendor predicate keeps its own namespace.
514            let (prefix, name) = match class {
515                Some(q) => (
516                    self.ns.prefix_of_iri(&q.ns).unwrap_or("ns").to_owned(),
517                    q.local.clone(),
518                ),
519                None => ("rdf".to_owned(), "Description".to_owned()),
520            };
521            self.indent(3)?;
522            // As for objects: an absolute-IRI identifier has no `rdf:ID` form.
523            if defines && subject.form_in_xml() != crate::xml::IdentifierForm::Iri {
524                write!(self.out, "<{prefix}:{name} rdf:ID=\"").map_err(Error::Io)?;
525                self.escape_attr(&subject.to_rdf_id())?;
526            } else {
527                write!(self.out, "<{prefix}:{name} rdf:about=\"").map_err(Error::Io)?;
528                self.escape_attr(&subject.to_rdf_reference())?;
529            }
530            self.out.write_all(b"\">\n")?;
531
532            for s in &statements[i..j] {
533                let p = self
534                    .ns
535                    .prefix_of_iri(&s.predicate_ns)
536                    .unwrap_or("ns")
537                    .to_owned();
538                let predicate = &s.predicate;
539                self.indent(4)?;
540                match &s.value {
541                    StatementValue::Resource(iri) => {
542                        write!(self.out, "<{p}:{predicate} rdf:resource=\"").map_err(Error::Io)?;
543                        self.escape_attr(iri)?;
544                        self.out.write_all(b"\"/>\n")?;
545                    }
546                    StatementValue::Literal(text) => {
547                        write!(self.out, "<{p}:{predicate}>").map_err(Error::Io)?;
548                        self.escape_text(text)?;
549                        writeln!(self.out, "</{p}:{predicate}>").map_err(Error::Io)?;
550                    }
551                }
552            }
553
554            self.indent(3)?;
555            writeln!(self.out, "</{prefix}:{name}>").map_err(Error::Io)?;
556            i = j;
557        }
558
559        self.indent(2)?;
560        writeln!(self.out, "</{dm}:{local}>").map_err(Error::Io)?;
561        Ok(())
562    }
563
564    fn header_text(&mut self, value: Option<&str>, local: &str) -> Result<()> {
565        let Some(v) = value else { return Ok(()) };
566        let md = self.md();
567        self.header_prop_text(&md, local, v)
568    }
569
570    fn header_resource(&mut self, value: &str, local: &str) -> Result<()> {
571        let md = self.md();
572        self.header_prop_resource(&md, local, value)
573    }
574
575    fn header_prop_text(&mut self, prefix: &str, local: &str, value: &str) -> Result<()> {
576        self.indent(2)?;
577        write!(self.out, "<{prefix}:{local}>").map_err(Error::Io)?;
578        self.escape_text(value)?;
579        writeln!(self.out, "</{prefix}:{local}>").map_err(Error::Io)?;
580        Ok(())
581    }
582
583    fn header_prop_resource(&mut self, prefix: &str, local: &str, value: &str) -> Result<()> {
584        self.indent(2)?;
585        write!(self.out, "<{prefix}:{local} rdf:resource=\"").map_err(Error::Io)?;
586        self.escape_attr(value)?;
587        self.out.write_all(b"\"/>\n")?;
588        Ok(())
589    }
590
591    /// Write one object element.
592    ///
593    /// Fields are destructured so prefixes can be borrowed while the sink is mutable,
594    /// avoiding an allocation per attribute.
595    fn object(&mut self, obj: &Object, options: &WriteOptions) -> Result<()> {
596        let Writer {
597            out,
598            schema,
599            pretty,
600            ns,
601            ..
602        } = self;
603        let pretty = *pretty;
604        let all_attrs = schema.class(obj.class()).all_attrs;
605        let class = schema.class(element_class(schema, obj, obj.class(), options.profiles));
606        let prefix = ns.prefix(class.ns);
607
608        indent(out, pretty, 1)?;
609        write!(out, "<{}:{}", prefix, class.name).map_err(Error::Io)?;
610        // An absolute-IRI identifier has no `rdf:ID` (`NCName`) form: use `rdf:about`.
611        let mrid = obj.mrid();
612        match (
613            resolve_id_style(options, class),
614            mrid.form_in_xml() == crate::xml::IdentifierForm::Iri,
615        ) {
616            (_, true) | (IdStyle::RdfAbout, false) => {
617                out.write_all(b" rdf:about=\"")?;
618                escape_attr(out, &mrid.to_rdf_reference())?;
619            }
620            // `Auto` is resolved above; anything left is the explicit `rdf:ID` form.
621            _ => {
622                out.write_all(b" rdf:ID=\"")?;
623                escape_attr(out, &mrid.to_rdf_id())?;
624            }
625        }
626        // Iterate the object's slots, not the class's attributes: far fewer.
627        if !object_has_content_in(schema, obj, options.profiles) {
628            out.write_all(b"\"/>\n")?;
629            return Ok(());
630        }
631        out.write_all(b"\">\n")?;
632
633        // Schema order, from the object's own class rather than the element's (an SSH
634        // file writes `<cim:Equipment>` for an `ACLineSegment`).
635        for attr_id in all_attrs {
636            let def = schema.attr(*attr_id);
637            let attr_prefix = ns.prefix(def.ns);
638            let prim = lexical_primitive(schema, def.kind);
639            for slot in obj.get_all(*attr_id) {
640                if !slot_belongs_to(schema, slot, options.profiles) {
641                    continue;
642                }
643                property(
644                    out,
645                    schema,
646                    ns,
647                    pretty,
648                    attr_prefix,
649                    def.name,
650                    &slot.value,
651                    prim,
652                    2,
653                )?;
654            }
655        }
656
657        indent(out, pretty, 1)?;
658        writeln!(out, "</{}:{}>", prefix, class.name).map_err(Error::Io)?;
659        Ok(())
660    }
661
662    fn indent(&mut self, level: usize) -> Result<()> {
663        indent(&mut self.out, self.pretty, level)
664    }
665
666    fn escape_text(&mut self, s: &str) -> Result<()> {
667        escape_text(&mut self.out, s)
668    }
669
670    fn escape_attr(&mut self, s: &str) -> Result<()> {
671        escape_attr(&mut self.out, s)
672    }
673}
674
675/// Write one property element, recursing into compounds.
676///
677/// `prim` is the primitive the schema gives the attribute, which decides the lexical
678/// form: `Decimal` has no exponent notation, `Float` does.
679#[allow(clippy::too_many_arguments)]
680fn property<W: Write>(
681    out: &mut W,
682    schema: &'static Schema,
683    ns: &Namespaces,
684    pretty: bool,
685    prefix: &str,
686    name: &str,
687    value: &Value,
688    prim: Primitive,
689    depth: usize,
690) -> Result<()> {
691    indent(out, pretty, depth)?;
692    match value {
693        Value::Reference(m) => {
694            write!(out, "<{prefix}:{name} rdf:resource=\"").map_err(Error::Io)?;
695            escape_attr(out, &m.to_rdf_reference())?;
696            out.write_all(b"\"/>\n")?;
697        }
698        Value::Enum(e) => {
699            let ev = schema.enum_value(*e);
700            write!(out, "<{prefix}:{name} rdf:resource=\"").map_err(Error::Io)?;
701            escape_attr(out, schema.namespace(ev.ns).iri)?;
702            escape_attr(out, ev.name)?;
703            out.write_all(b"\"/>\n")?;
704        }
705        // A compound is written inline as a blank node (`rdf:parseType="Resource"`).
706        Value::Compound(c) => {
707            if c.is_empty() {
708                writeln!(out, "<{prefix}:{name} rdf:parseType=\"Resource\"/>")
709                    .map_err(Error::Io)?;
710                return Ok(());
711            }
712            writeln!(out, "<{prefix}:{name} rdf:parseType=\"Resource\">").map_err(Error::Io)?;
713            for (attr, v) in c.values() {
714                let def = schema.attr(*attr);
715                property(
716                    out,
717                    schema,
718                    ns,
719                    pretty,
720                    ns.prefix(def.ns),
721                    def.name,
722                    v,
723                    lexical_primitive(schema, def.kind),
724                    depth + 1,
725                )?;
726            }
727            indent(out, pretty, depth)?;
728            writeln!(out, "</{prefix}:{name}>").map_err(Error::Io)?;
729        }
730        other => {
731            write!(out, "<{prefix}:{name}>").map_err(Error::Io)?;
732            if let Some(text) = other.to_lexical_as(prim) {
733                escape_text(out, &text)?;
734            }
735            writeln!(out, "</{prefix}:{name}>").map_err(Error::Io)?;
736        }
737    }
738    Ok(())
739}
740
741fn indent<W: Write>(out: &mut W, pretty: bool, level: usize) -> Result<()> {
742    if pretty {
743        for _ in 0..level {
744            out.write_all(b"  ")?;
745        }
746    }
747    Ok(())
748}
749
750/// Escape a value for element content.
751///
752/// Escapes `&`, `<` and `>` (so `]]>` cannot occur); quotes are left alone. CR is escaped
753/// numerically, since parsers normalize a literal CR to LF.
754fn escape_text<W: Write>(out: &mut W, s: &str) -> Result<()> {
755    escape(out, s, |b| match b {
756        b'&' => Some(b"&amp;".as_slice()),
757        b'<' => Some(b"&lt;"),
758        b'>' => Some(b"&gt;"),
759        b'\r' => Some(b"&#13;"),
760        _ => None,
761    })
762}
763
764/// Escape a value for a double-quoted attribute.
765///
766/// Tab, LF and CR are escaped numerically too, since attribute-value normalization would
767/// turn them into spaces.
768fn escape_attr<W: Write>(out: &mut W, s: &str) -> Result<()> {
769    escape(out, s, |b| match b {
770        b'&' => Some(b"&amp;".as_slice()),
771        b'<' => Some(b"&lt;"),
772        b'>' => Some(b"&gt;"),
773        b'"' => Some(b"&quot;"),
774        b'\t' => Some(b"&#9;"),
775        b'\n' => Some(b"&#10;"),
776        b'\r' => Some(b"&#13;"),
777        _ => None,
778    })
779}
780
781/// Copy `s`, replacing the bytes `rep` names, and dropping what XML cannot represent.
782///
783/// Replaced bytes are all ASCII, so multi-byte characters are untouched. Characters
784/// outside XML 1.0's `Char` (most of C0) have no representation even as a reference, so
785/// they are dropped; [`Rule::IllegalXmlCharacter`] reports them on read and in validation.
786///
787/// [`Rule::IllegalXmlCharacter`]: crate::Rule::IllegalXmlCharacter
788fn escape<W: Write>(out: &mut W, s: &str, rep: fn(u8) -> Option<&'static [u8]>) -> Result<()> {
789    // One byte test per byte on the common path, and no allocation unless it fires.
790    let cleaned = crate::xml::strip_illegal(s);
791    let bytes = cleaned.as_bytes();
792    let mut start = 0;
793    for (i, &b) in bytes.iter().enumerate() {
794        let Some(r) = rep(b) else { continue };
795        out.write_all(&bytes[start..i])?;
796        out.write_all(r)?;
797        start = i + 1;
798    }
799    out.write_all(&bytes[start..])?;
800    Ok(())
801}
802
803/// The primitive an attribute's values are written as.
804///
805/// A datatype such as `Money` serializes as the primitive it wraps; enumerations,
806/// references and compounds never reach the text path, so `String` stands in.
807fn lexical_primitive(schema: &Schema, kind: AttrKind) -> Primitive {
808    match kind {
809        AttrKind::Primitive(p) => p,
810        AttrKind::Datatype(d) => schema.datatype(d).value,
811        _ => Primitive::String,
812    }
813}
814
815/// A prefix to suggest for a namespace the schema does not know, derived from its IRI.
816///
817/// `http://example.com/vendor#` yields `vendor`; anything unusable yields `ns`, which
818/// [`Namespaces::bind`] then makes unique.
819fn suggest_prefix(iri: &str) -> &str {
820    let trimmed = iri.trim_end_matches(['#', '/']);
821    let last = trimmed.rsplit(['#', '/', ':']).next().unwrap_or_default();
822    let usable = !last.is_empty()
823        && last.starts_with(|c: char| c.is_ascii_alphabetic())
824        && last
825            .chars()
826            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
827    if usable { last } else { "ns" }
828}
829
830/// The class an object is written as in a file serving `profiles`.
831///
832/// The most specific class (the object's own or an ancestor) that the profiles declare and
833/// whose mandatory attributes the model supplies.
834/// An SSH file thus writes `<cim:Equipment rdf:about="…">` for an
835/// `ACLineSegment` (SSH does not declare `ACLineSegment`); the most specific class would
836/// fail the profile's SHACL shapes. Falls back to the object's own class.
837pub fn element_class(
838    schema: &Schema,
839    obj: &Object,
840    class: ClassId,
841    profiles: ProfileMask,
842) -> ClassId {
843    // Writing everything into one document imposes no profile, so the real class stands.
844    if profiles == 0 {
845        return class;
846    }
847    let declared = |c: ClassId| {
848        let d = schema.class(c);
849        d.concrete && !d.compound && d.profiles & profiles != 0
850    };
851    // Mandatory attributes must be supplied by the *model* (`obj.has(a)`), not by this
852    // file: published SSH files omit the mandatory `IdentifiedObject.mRID`, so the
853    // stricter rule would reject every candidate.
854    let complete = |c: ClassId| {
855        schema.class(c).all_attrs.iter().all(|&a| {
856            let def = schema.attr(a);
857            !(def.mult.is_required() && def.used_in & profiles != 0) || obj.has(a)
858        })
859    };
860    std::iter::once(class)
861        .chain(schema.class(class).ancestors.iter().copied())
862        .find(|&c| declared(c) && complete(c))
863        .unwrap_or(class)
864}
865
866/// The header a document gets when the caller supplies none.
867///
868/// Adjust it (modelling authority set, scenario time, ...) and pass it back through
869/// [`WriteOptions::with_header`].
870///
871/// Declares exactly the profiles being written: the mask when one is given, otherwise
872/// every profile the data covers. The identifier is an RFC 4122 v5 UUID over the vintage,
873/// those profiles and the model's content identifier. `Model.created` is left out, since
874/// this crate reads no clock.
875pub fn derive_header(dataset: &Dataset, profiles: ProfileMask) -> ModelHeader {
876    derive_header_with(
877        dataset.schema(),
878        if profiles == 0 {
879            dataset.profiles()
880        } else {
881            profiles
882        },
883        &dataset.content_id(),
884    )
885}
886
887/// The same, from an already-computed content identifier.
888///
889/// `Dataset::content_id` walks the whole model, so a multi-file export computes it once.
890pub(crate) fn derive_header_with(
891    schema: &'static Schema,
892    covered: ProfileMask,
893    content: &Mrid,
894) -> ModelHeader {
895    let iris: Vec<String> = schema
896        .profiles
897        .iter()
898        .enumerate()
899        .filter(|(i, _)| covered & (1u64 << i) != 0)
900        .map(|(_, p)| p.version_iri.to_owned())
901        .collect();
902
903    let mut name = format!("{}\u{1e}", schema.vintage);
904    for iri in &iris {
905        name.push_str(iri);
906        name.push('\u{1e}');
907    }
908    name.push_str(&content.to_string());
909
910    ModelHeader {
911        kind: ModelKind::Full,
912        id: Some(Mrid::new_v5(&Dataset::DERIVED_NS, name.as_bytes())),
913        profiles: iris,
914        version: Some("1".to_owned()),
915        ..Default::default()
916    }
917}
918
919/// How an object of `class` is identified in a file serving `options.profiles`.
920///
921/// Exposed so tooling can predict the output without rendering it.
922pub fn id_style_for(schema: &Schema, class: ClassId, profiles: ProfileMask) -> IdStyle {
923    resolve_id_style(
924        &WriteOptions {
925            profiles,
926            ..Default::default()
927        },
928        schema.class(class),
929    )
930}
931
932fn resolve_id_style(options: &WriteOptions, class: &ClassDef) -> IdStyle {
933    match options.id_style {
934        IdStyle::Auto => {
935            // Writing everything into one document makes that document the definition.
936            if options.profiles == 0 || class.defined_in & options.profiles != 0 {
937                IdStyle::RdfId
938            } else if class.profiles & options.profiles == 0 {
939                // No profile this file serves mentions the class (an under-declaring
940                // header), so this file must introduce it (D57).
941                IdStyle::RdfId
942            } else {
943                IdStyle::RdfAbout
944            }
945        }
946        forced => forced,
947    }
948}
949
950/// Classes that a profile may contain, for callers building per-profile exports.
951pub fn classes_in_profile(
952    schema: &Schema,
953    profile: ProfileId,
954) -> impl Iterator<Item = ClassId> + '_ {
955    let mask = profile.mask();
956    schema
957        .classes
958        .iter()
959        .enumerate()
960        .filter(move |(_, c)| c.concrete && !c.compound && c.profiles & mask != 0)
961        .map(|(i, _)| ClassId(i as u16))
962}