Skip to main content

cim_kit/
rdf.rs

1//! Standard RDF output: the profile-enriched graph, in N-Triples or Turtle.
2//!
3//! # Why this exists
4//!
5//! CIM/XML looks like RDF/XML and is not. IEC 61970-552 predates the W3C RDF/XML
6//! recommendation, and the two disagree in ways that matter: `rdf:parseType="Statements"`
7//! is not RDF syntax at all, and `rdf:ID="_<uuid>"` denotes `urn:uuid:<uuid>` rather than
8//! a fragment of the document. ENTSO-E's own interoperability reporting says so — the
9//! int:net IOP report calls CIMXML's differences from "RDFXML *defined by W3C*" gaps, and
10//! the CGMES documentation's claim that CIMXML "can be read by available RDF
11//! de-serialization software" does not hold.
12//!
13//! The second gap is larger. **CIM/XML exchanges no datatype information at all.** Every
14//! value is element text, so a reader without the profile cannot tell `1` (an integer)
15//! from `1` (a float) from `1` (a string) — and ENTSO-E's SHACL shapes constrain 3,137
16//! properties by `sh:datatype`. The 2024 int:net report puts it plainly: *"There are no
17//! open libraries to natively enhance the data based on the profile definitions"*, and
18//! lists providing one as one of three ways out.
19//!
20//! This module is that step. It writes the model as ordinary RDF with every literal
21//! carrying the XSD type the profile assigns it, so the result can be loaded by any RDF
22//! toolchain and validated directly against the SHACL shapes ENTSO-E publishes alongside
23//! the RDFS this crate is generated from.
24//!
25// An example has to name a vintage, and a vintage is a feature. See `Dataset::view`.
26#![cfg_attr(
27    feature = "cgmes3",
28    doc = r#"
29```no_run
30use cim_kit::prelude::*;
31use cim_kit::cgmes3::SCHEMA;
32use cim_kit::rdf::{RdfOptions, Syntax};
33
34# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
35let ds = Dataset::load(SCHEMA, ["model_EQ.xml", "model_SSH.xml"])?;
36let out = std::fs::File::create("model.ttl")?;
37cim_kit::rdf::write(&ds, out, &RdfOptions::new(Syntax::Turtle))?;
38# Ok(())
39# }
40```
41"#
42)]
43//!
44//! # The mapping
45//!
46//! | CIM | RDF |
47//! |---|---|
48//! | object with a UUID identifier | IRI `urn:uuid:<uuid>` (IEC 61970-552 §identification) |
49//! | object with a non-conforming identifier | blank node, or an IRI under [`RdfOptions::base`] |
50//! | class | `rdf:type <namespace><ClassName>` |
51//! | attribute | predicate `<namespace><Class.attr>` |
52//! | primitive value | literal typed by [`Primitive::xsd_datatype`] |
53//! | CIM datatype (`Resistance`, …) | literal of the primitive it serializes as |
54//! | enumeration | IRI `<namespace><Enum.literal>` |
55//! | association | IRI of the target object |
56//! | compound (`rdf:parseType="Resource"`) | blank node, typed, with its fields |
57//! | `md:FullModel` header | a resource with its `md:Model.*` properties |
58//!
59//! # What this is not
60//!
61//! Not an RDF store, and not a SHACL engine. It writes a graph; validating it against
62//! shapes is a job for a tool that already does that well. The structural checks this
63//! crate performs itself are in [`validate`](mod@crate::validate) and cover what the RDFS
64//! justifies without shapes.
65
66use std::io::Write;
67
68use crate::dataset::Dataset;
69use crate::error::{Error, Result};
70use crate::header::{HeaderValue, MD_NS, ModelHeader};
71use crate::mrid::Mrid;
72use crate::object::{Compound, Object};
73use crate::schema::{AttrId, AttrKind, ClassId, Primitive, ProfileMask, Schema};
74use crate::value::Value;
75
76const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
77const XSD_NS: &str = "http://www.w3.org/2001/XMLSchema#";
78/// `rdf:type`, spelled out once. Written on every object and every compound, so it is a
79/// constant rather than a `format!` of `RDF_NS` — building it per triple allocated over a
80/// million times on a nation-scale model, twice each: once to write it and once to
81/// recognise it as the one predicate Turtle abbreviates to `a`.
82const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
83
84/// Which RDF syntax to write.
85#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
86pub enum Syntax {
87    /// One triple per line, no prefixes. The line-based interchange syntax every RDF
88    /// tool reads, and the one to pipe into a validator.
89    #[default]
90    NTriples,
91    /// Prefixed and grouped by subject. The same graph, for a person to read.
92    Turtle,
93}
94
95/// Options controlling RDF output.
96#[derive(Clone, Debug)]
97pub struct RdfOptions {
98    pub syntax: Syntax,
99    /// Write only values belonging to these profiles; zero means "everything".
100    ///
101    /// Filtering follows the same rule as the CIM/XML writer
102    /// ([`Schema::effective_profiles`]), so validating one profile's graph against that
103    /// profile's shapes sees exactly what an export of it would contain.
104    pub profiles: ProfileMask,
105    /// Emit `rdf:type` for every object and compound.
106    ///
107    /// On by default: SHACL shapes select their targets with `sh:targetClass`, so a graph
108    /// without types is a graph nothing applies to.
109    pub types: bool,
110    /// Emit the loaded files' `md:FullModel` headers as resources.
111    ///
112    /// Restricted by [`RdfOptions::profiles`] exactly as the objects are: a graph for one
113    /// profile carries the headers of the files that *serve* it and no others, because that
114    /// is what the profile's instance file carries.
115    pub headers: bool,
116    /// Base IRI for identifiers that are not UUIDs.
117    ///
118    /// IEC 61970-552 requires a UUID and this crate keeps non-conforming identifiers
119    /// verbatim, reporting them as
120    /// [`Rule::NonConformingMrid`](crate::Rule::NonConformingMrid). Such an identifier has
121    /// no `urn:uuid:` form, and inventing one would be a lie about what the document said.
122    /// With a base set the identifier becomes `{base}{identifier}`; without one it becomes
123    /// a **blank node**, which keeps the graph's shape and its joins but gives the object
124    /// no global name.
125    pub base: Option<String>,
126}
127
128impl Default for RdfOptions {
129    fn default() -> Self {
130        RdfOptions {
131            syntax: Syntax::default(),
132            profiles: 0,
133            types: true,
134            headers: true,
135            base: None,
136        }
137    }
138}
139
140impl RdfOptions {
141    pub fn new(syntax: Syntax) -> RdfOptions {
142        RdfOptions {
143            syntax,
144            ..Default::default()
145        }
146    }
147
148    /// Restrict output to a set of profiles.
149    pub fn profiles(mut self, profiles: ProfileMask) -> Self {
150        self.profiles = profiles;
151        self
152    }
153
154    /// Name non-conforming identifiers under `base` instead of emitting blank nodes.
155    pub fn with_base(mut self, base: impl Into<String>) -> Self {
156        self.base = Some(base.into());
157        self
158    }
159}
160
161/// Write `dataset` as RDF.
162pub fn write<W: Write>(dataset: &Dataset, out: W, options: &RdfOptions) -> Result<()> {
163    let schema = dataset.schema();
164    let mut w = RdfWriter {
165        out,
166        schema,
167        options,
168        prefixes: turtle_prefixes(schema),
169        blank: 0,
170        subject_open: false,
171    };
172    w.prologue()?;
173    if options.headers {
174        for h in dataset.headers() {
175            if header_serves(schema, h, options.profiles) {
176                w.header(h)?;
177            }
178        }
179    }
180    // ObjectId order, which is load order: deterministic, and cheaper than sorting a
181    // nation-scale model when RDF itself defines no order over a graph.
182    for (_, obj) in dataset.iter() {
183        w.object(obj)?;
184    }
185    w.close_subject()?;
186    w.out.flush()?;
187    Ok(())
188}
189
190/// Write `dataset` as RDF into a string.
191pub fn to_string(dataset: &Dataset, options: &RdfOptions) -> Result<String> {
192    let mut buf = Vec::new();
193    write(dataset, &mut buf, options)?;
194    String::from_utf8(buf).map_err(|e| Error::NotCimXml(e.to_string()))
195}
196
197/// Whether a file's header belongs in a graph restricted to `profiles`.
198///
199/// The same question the CIM/XML export asks of a file: does this header declare a profile
200/// the export serves. A zero mask is the whole model, where every header belongs.
201fn header_serves(schema: &Schema, header: &ModelHeader, profiles: ProfileMask) -> bool {
202    profiles == 0
203        || header
204            .profiles
205            .iter()
206            .filter_map(|iri| schema.profile_by_iri(iri))
207            .any(|p| p.mask() & profiles != 0)
208}
209
210/// Whether an export restricted to `profiles` would describe any object at all.
211///
212/// Lets a caller distinguish "this profile is absent from the model" from "this profile
213/// conforms" — which a check on the graph's *size* cannot, since a graph of nothing but
214/// headers runs to hundreds of lines.
215///
216/// Deliberately about objects rather than headers: a file may declare Equipment, Operation
217/// and ShortCircuit and carry no Operation attribute at all, and a header on its own is not
218/// an export of that profile.
219pub fn has_content(dataset: &Dataset, profiles: ProfileMask) -> bool {
220    let schema = dataset.schema();
221    dataset
222        .iter()
223        .any(|(_, o)| crate::writer::object_has_content_in(schema, o, profiles))
224}
225
226/// One of the three things a triple's object can be.
227enum Term<'a> {
228    Iri(String),
229    Blank(String),
230    /// Lexical form and datatype IRI; an empty datatype means a plain string literal.
231    Literal(String, &'a str),
232}
233
234struct RdfWriter<'a, W: Write> {
235    out: W,
236    schema: &'static Schema,
237    options: &'a RdfOptions,
238    /// Prefix to abbreviate each schema namespace with, or `None` where abbreviating it
239    /// would be wrong. Resolved once, for the reason [`turtle_prefixes`] explains.
240    prefixes: Vec<Option<&'static str>>,
241    /// Counter for the blank nodes compounds need.
242    blank: u64,
243    /// Turtle groups triples by subject, so a subject stays open until the next one.
244    subject_open: bool,
245}
246
247/// Which of a schema's namespaces may be abbreviated in Turtle, and under what name.
248///
249/// A `@prefix` declaration is global to the document and the last one wins, so a prefix
250/// that names two different namespaces silently changes what every abbreviated name after
251/// it denotes — output that parses cleanly and means something else, which is the worst
252/// kind. Two ways that can happen, and both are live rather than theoretical once
253/// third-party profiles are generated as the design promises:
254///
255/// * a schema namespace whose conventional prefix is `rdf`, `xsd` or `md`, which this
256///   writer has already bound to the vocabularies it needs itself;
257/// * two schema namespaces that share a prefix, which the generator's fallback naming
258///   makes unlikely but does not prevent.
259///
260/// Either way the namespace is simply not abbreviated: a full IRI is always correct, and a
261/// wrong prefixed name never is.
262fn turtle_prefixes(schema: &Schema) -> Vec<Option<&'static str>> {
263    const RESERVED: [&str; 3] = ["rdf", "xsd", "md"];
264    let mut out: Vec<Option<&'static str>> = Vec::with_capacity(schema.namespaces.len());
265    for (i, ns) in schema.namespaces.iter().enumerate() {
266        // The vocabularies this writer declares itself keep their canonical prefixes and
267        // are not re-declared from the table.
268        if matches!(ns.iri, RDF_NS | MD_NS) {
269            out.push(None);
270            continue;
271        }
272        let clashes = RESERVED.contains(&ns.prefix)
273            || schema.namespaces[..i]
274                .iter()
275                .any(|earlier| earlier.prefix == ns.prefix && earlier.iri != ns.iri);
276        out.push((!clashes).then_some(ns.prefix));
277    }
278    out
279}
280
281impl<W: Write> RdfWriter<'_, W> {
282    fn turtle(&self) -> bool {
283        self.options.syntax == Syntax::Turtle
284    }
285
286    /// Turtle's prefix declarations. N-Triples has none and needs none.
287    fn prologue(&mut self) -> Result<()> {
288        if !self.turtle() {
289            return Ok(());
290        }
291        writeln!(self.out, "@prefix rdf: <{RDF_NS}> .").map_err(Error::Io)?;
292        writeln!(self.out, "@prefix xsd: <{XSD_NS}> .").map_err(Error::Io)?;
293        writeln!(self.out, "@prefix md: <{MD_NS}> .").map_err(Error::Io)?;
294        // Exactly the namespaces `write_abbreviated` will use, so the document never
295        // declares a prefix it does not need or one that would shadow another.
296        for (ns, prefix) in self.schema.namespaces.iter().zip(&self.prefixes) {
297            let Some(prefix) = prefix else { continue };
298            writeln!(self.out, "@prefix {}: <{}> .", prefix, ns.iri).map_err(Error::Io)?;
299        }
300        self.out.write_all(b"\n")?;
301        Ok(())
302    }
303
304    // -- header ------------------------------------------------------------
305
306    fn header(&mut self, h: &ModelHeader) -> Result<()> {
307        let Some(id) = h.id.as_ref() else {
308            // A header with no identifier has no subject to hang its properties on.
309            return Ok(());
310        };
311        let subject = self.term_for(id);
312        self.close_subject()?;
313        if self.options.types {
314            let kind = match h.kind {
315                crate::header::ModelKind::Full => "FullModel",
316                crate::header::ModelKind::Difference => "DifferenceModel",
317            };
318            let ty = Term::Iri(format!("{MD_NS}{kind}"));
319            self.triple(&subject, RDF_TYPE, &ty)?;
320        }
321        for (local, value) in [
322            ("Model.created", h.created.as_deref()),
323            ("Model.scenarioTime", h.scenario_time.as_deref()),
324            ("Model.description", h.description.as_deref()),
325            ("Model.version", h.version.as_deref()),
326            (
327                "Model.modelingAuthoritySet",
328                h.modeling_authority_set.as_deref(),
329            ),
330        ] {
331            if let Some(v) = value {
332                let term = self.header_literal(local, v);
333                self.triple(&subject, &format!("{MD_NS}{local}"), &term)?;
334            }
335        }
336        for p in &h.profiles {
337            let term = self.header_literal("Model.profile", p);
338            self.triple(&subject, &format!("{MD_NS}Model.profile"), &term)?;
339        }
340        for (local, ids) in [
341            ("Model.DependentOn", &h.dependent_on),
342            ("Model.Supersedes", &h.supersedes),
343        ] {
344            for m in ids {
345                let target = self.term_for(m);
346                self.triple(&subject, &format!("{MD_NS}{local}"), &target)?;
347            }
348        }
349        for p in &h.extra {
350            let term = match &p.value {
351                HeaderValue::Text(v) => Term::Literal(v.clone(), ""),
352                HeaderValue::Resource(v) => Term::Iri(v.clone()),
353            };
354            self.triple(&subject, &format!("{}{}", p.ns, p.local), &term)?;
355        }
356        self.close_subject()
357    }
358
359    /// Type a header value from the header profile's own vocabulary.
360    ///
361    /// The exchange header is a profile like any other — CGMES 3.0 publishes a Header AP
362    /// RDFS, and the generator reads it — so `md:Model.created` is a `DateTime`,
363    /// `md:Model.version` an `Integer` and `md:Model.profile` a `URI`, and ENTSO-E's
364    /// header shapes constrain each with the matching `sh:datatype`. Emitting them all as
365    /// plain strings, which is what hand-writing the header amounts to, fails those shapes
366    /// on every file. The schema is the single place that knows, so it is asked.
367    fn header_literal(&self, local: &str, text: &str) -> Term<'static> {
368        let prim = self
369            .schema
370            .find_attr(MD_NS, local)
371            .map(|a| match self.schema.attr(a).kind {
372                AttrKind::Primitive(p) => p,
373                AttrKind::Datatype(d) => self.schema.datatype(d).value,
374                _ => Primitive::String,
375            })
376            .unwrap_or(Primitive::String);
377        Term::Literal(text.to_owned(), prim.xsd_datatype())
378    }
379
380    // -- objects -----------------------------------------------------------
381
382    fn object(&mut self, obj: &Object) -> Result<()> {
383        let profiles = self.options.profiles;
384        let keep = |s: &crate::object::Slot| {
385            profiles == 0 || self.schema.effective_profiles(s.attr, s.profiles) & profiles != 0
386        };
387        // A profile's graph holds the objects that profile describes and no others.
388        // Emitting a bare `rdf:type` for an object with nothing to say in this profile
389        // would assert something the corresponding instance file never claims — and
390        // ENTSO-E's shapes check exactly that, since a profile constrains a reference's
391        // target to the classes *it* declares.
392        if profiles != 0 && !obj.slots().iter().any(keep) {
393            return Ok(());
394        }
395
396        let subject = self.term_for(obj.mrid());
397        self.close_subject()?;
398
399        if self.options.types {
400            // The same rule the CIM/XML writer uses to pick an element's class: a Steady
401            // State Hypothesis graph types an `ACLineSegment` as `cim:Equipment`, because
402            // that is the class SSH declares and the only one its shapes expect.
403            let class = crate::writer::element_class(self.schema, obj, obj.class(), profiles);
404            let ty = Term::Iri(self.class_iri(class));
405            self.triple(&subject, RDF_TYPE, &ty)?;
406        }
407        for slot in obj.slots() {
408            if !keep(slot) {
409                continue;
410            }
411            self.property(&subject, slot.attr, &slot.value)?;
412        }
413        self.close_subject()
414    }
415
416    /// Emit one attribute occurrence, recursing into compounds.
417    fn property(&mut self, subject: &Term<'_>, attr: AttrId, value: &Value) -> Result<()> {
418        let def = self.schema.attr(attr);
419        let predicate = format!("{}{}", self.schema.namespace(def.ns).iri, def.name);
420
421        // A compound has no identifier, which is exactly what a blank node is for. Its
422        // triples are written after the property that points at it, so the subject
423        // currently open has to be closed first.
424        if let Value::Compound(c) = value {
425            self.blank += 1;
426            let node = Term::Blank(format!("_:c{}", self.blank));
427            self.triple(subject, &predicate, &node)?;
428            self.close_subject()?;
429            self.compound(&node, c)?;
430            self.close_subject()?;
431            return Ok(());
432        }
433
434        let term = self.term_for_value(def.kind, value);
435        self.triple(subject, &predicate, &term)
436    }
437
438    fn compound(&mut self, subject: &Term<'_>, c: &Compound) -> Result<()> {
439        if self.options.types {
440            let ty = Term::Iri(self.class_iri(c.class()));
441            self.triple(subject, RDF_TYPE, &ty)?;
442        }
443        for (attr, v) in c.values() {
444            self.property(subject, *attr, v)?;
445        }
446        Ok(())
447    }
448
449    // -- terms -------------------------------------------------------------
450
451    fn class_iri(&self, class: ClassId) -> String {
452        let def = self.schema.class(class);
453        format!("{}{}", self.schema.namespace(def.ns).iri, def.name)
454    }
455
456    /// The subject or object term denoting `mrid`.
457    fn term_for(&self, mrid: &Mrid) -> Term<'static> {
458        if mrid.is_uuid() {
459            return Term::Iri(mrid.to_urn());
460        }
461        match &self.options.base {
462            Some(base) => Term::Iri(format!("{base}{}", mrid.canonical())),
463            None => Term::Blank(blank_label(&mrid.canonical())),
464        }
465    }
466
467    fn term_for_value(&self, kind: AttrKind, value: &Value) -> Term<'static> {
468        // The declared kind decides the datatype, and the stored value decides the
469        // lexical form. They can disagree — a malformed document is why `validate` has a
470        // datatype check — in which case the value is written as what it actually is,
471        // rather than being labelled with a type it does not have.
472        match (kind, value) {
473            (_, Value::Reference(m)) => self.term_for(m),
474            (_, Value::Enum(e)) => {
475                let ev = self.schema.enum_value(*e);
476                Term::Iri(format!("{}{}", self.schema.namespace(ev.ns).iri, ev.name))
477            }
478            (AttrKind::Primitive(p), _) => self.literal(p, value),
479            (AttrKind::Datatype(dt), _) => self.literal(self.schema.datatype(dt).value, value),
480            // Compounds are handled before this point; anything else left here is a
481            // malformed value kept as text.
482            _ => self.literal(Primitive::String, value),
483        }
484    }
485
486    fn literal(&self, declared: Primitive, value: &Value) -> Term<'static> {
487        // Normally the profile decides the type — that is the whole purpose here. But a
488        // document can carry something the profile does not declare (which is what
489        // `validate`'s datatype check reports), and labelling that with the declared type
490        // would assert something false. Such a value is written as what it actually is.
491        let effective = if value.fits(declared) {
492            declared
493        } else {
494            match value {
495                Value::Boolean(_) => Primitive::Boolean,
496                Value::Integer(_) => Primitive::Integer,
497                Value::Float(_) => Primitive::Float,
498                _ => Primitive::String,
499            }
500        };
501        let lexical = value.to_lexical_as(effective).unwrap_or_default();
502        Term::Literal(lexical, effective.xsd_datatype())
503    }
504
505    // -- syntax ------------------------------------------------------------
506
507    fn triple(&mut self, subject: &Term<'_>, predicate: &str, object: &Term<'_>) -> Result<()> {
508        if self.turtle() {
509            if self.subject_open {
510                self.out.write_all(b" ;\n    ")?;
511            } else {
512                self.write_term(subject)?;
513                self.out.write_all(b"\n    ")?;
514                self.subject_open = true;
515            }
516            // `a` is Turtle's keyword for rdf:type, and the one abbreviation every reader
517            // of RDF expects to see.
518            if predicate == RDF_TYPE {
519                self.out.write_all(b"a")?;
520            } else {
521                self.write_abbreviated(predicate)?;
522            }
523            self.out.write_all(b" ")?;
524            self.write_term(object)?;
525            return Ok(());
526        }
527        self.write_term(subject)?;
528        self.out.write_all(b" ")?;
529        self.write_iri(predicate)?;
530        self.out.write_all(b" ")?;
531        self.write_term(object)?;
532        self.out.write_all(b" .\n")?;
533        Ok(())
534    }
535
536    fn close_subject(&mut self) -> Result<()> {
537        if self.subject_open {
538            self.out.write_all(b" .\n")?;
539            self.subject_open = false;
540        }
541        Ok(())
542    }
543
544    /// Write an IRI as a prefixed name where the schema knows its namespace.
545    fn write_abbreviated(&mut self, iri: &str) -> Result<()> {
546        if let Some((ns, local)) = split_iri(iri)
547            && is_turtle_local_name(local)
548            && let Some(prefix) = self.prefix_for(ns)
549        {
550            return write!(self.out, "{prefix}:{local}").map_err(Error::Io);
551        }
552        self.write_iri(iri)
553    }
554
555    fn prefix_for(&self, ns: &str) -> Option<&'static str> {
556        match ns {
557            RDF_NS => Some("rdf"),
558            MD_NS => Some("md"),
559            XSD_NS => Some("xsd"),
560            _ => self
561                .schema
562                .namespaces
563                .iter()
564                .position(|n| n.iri == ns)
565                .and_then(|i| self.prefixes[i]),
566        }
567    }
568
569    fn write_term(&mut self, term: &Term<'_>) -> Result<()> {
570        match term {
571            Term::Iri(iri) if self.turtle() => self.write_abbreviated(iri),
572            Term::Iri(iri) => self.write_iri(iri),
573            Term::Blank(label) => self.out.write_all(label.as_bytes()).map_err(Error::Io),
574            Term::Literal(lexical, datatype) => {
575                self.out.write_all(b"\"")?;
576                self.write_escaped_literal(lexical)?;
577                self.out.write_all(b"\"")?;
578                if datatype.is_empty() {
579                    // RDF 1.1: a literal with no datatype *is* an `xsd:string`.
580                    return Ok(());
581                }
582                if self.turtle()
583                    && let Some(local) = datatype.strip_prefix(XSD_NS)
584                {
585                    return write!(self.out, "^^xsd:{local}").map_err(Error::Io);
586                }
587                self.out.write_all(b"^^")?;
588                self.write_iri(datatype)
589            }
590        }
591    }
592
593    /// An IRI reference. The characters an IRIREF may not contain are escaped numerically
594    /// rather than dropped, so a non-conforming value cannot break the syntax.
595    fn write_iri(&mut self, iri: &str) -> Result<()> {
596        self.out.write_all(b"<")?;
597        for c in iri.chars() {
598            match c {
599                '<' | '>' | '"' | '{' | '}' | '|' | '^' | '`' | '\\' => {
600                    write!(self.out, "\\u{:04X}", c as u32).map_err(Error::Io)?
601                }
602                c if (c as u32) <= 0x20 => {
603                    write!(self.out, "\\u{:04X}", c as u32).map_err(Error::Io)?
604                }
605                c => {
606                    let mut b = [0u8; 4];
607                    self.out.write_all(c.encode_utf8(&mut b).as_bytes())?;
608                }
609            }
610        }
611        self.out.write_all(b">")?;
612        Ok(())
613    }
614
615    fn write_escaped_literal(&mut self, s: &str) -> Result<()> {
616        let bytes = s.as_bytes();
617        let mut start = 0;
618        for (i, &b) in bytes.iter().enumerate() {
619            let rep: &[u8] = match b {
620                b'\\' => b"\\\\",
621                b'"' => b"\\\"",
622                b'\n' => b"\\n",
623                b'\r' => b"\\r",
624                b'\t' => b"\\t",
625                _ => continue,
626            };
627            self.out.write_all(&bytes[start..i])?;
628            self.out.write_all(rep)?;
629            start = i + 1;
630        }
631        self.out.write_all(&bytes[start..])?;
632        Ok(())
633    }
634}
635
636/// Split an IRI into `(namespace, local name)` at its last `#` or `/`.
637fn split_iri(iri: &str) -> Option<(&str, &str)> {
638    let at = iri.rfind(['#', '/'])?;
639    Some((&iri[..=at], &iri[at + 1..]))
640}
641
642/// Whether `local` can be written after a Turtle prefix without escaping.
643///
644/// Deliberately narrower than Turtle's `PN_LOCAL`: CIM's property names are
645/// `Class.attribute`, so an interior dot must be allowed, but a trailing one would end the
646/// statement instead.
647fn is_turtle_local_name(local: &str) -> bool {
648    !local.is_empty()
649        && !local.ends_with('.')
650        && local.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
651        && local
652            .chars()
653            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
654}
655
656/// A stable blank-node label for a non-conforming identifier.
657///
658/// It has to be stable rather than merely unique: every reference to the object has to
659/// produce the same label, or the graph falls apart into unconnected fragments.
660fn blank_label(id: &str) -> String {
661    let plain = !id.is_empty()
662        && id.starts_with(|c: char| c.is_ascii_alphanumeric())
663        && id
664            .chars()
665            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'));
666    if plain {
667        return format!("_:id{id}");
668    }
669    let mut out = String::with_capacity(id.len() * 2 + 4);
670    out.push_str("_:x");
671    for b in id.bytes() {
672        out.push(char::from_digit((b >> 4) as u32, 16).unwrap_or('0'));
673        out.push(char::from_digit((b & 0xf) as u32, 16).unwrap_or('0'));
674    }
675    out
676}
677
678#[cfg(test)]
679mod tests {
680    use super::*;
681
682    #[test]
683    fn blank_labels_are_stable_and_syntactically_valid() {
684        // The same identifier must always give the same label, or references stop joining.
685        let id = "c1d5c14b8f8011e08e4d00247eb1f55e";
686        assert_eq!(blank_label(id), blank_label(id));
687        assert_eq!(blank_label(id), format!("_:id{id}"));
688        // Anything that is not a plain name is hex-encoded rather than passed through.
689        for weird in ["a b", "é", "_lead", "-lead", ""] {
690            let label = blank_label(weird);
691            assert!(label.starts_with("_:"), "{weird:?} -> {label}");
692            assert!(
693                label[2..]
694                    .chars()
695                    .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
696                "{weird:?} -> {label}"
697            );
698        }
699    }
700
701    #[test]
702    fn cim_property_names_survive_turtle_abbreviation() {
703        // `Class.attribute` is a valid Turtle local name because the dot is interior.
704        assert!(is_turtle_local_name("ACLineSegment.r"));
705        assert!(is_turtle_local_name("IdentifiedObject.mRID"));
706        assert!(is_turtle_local_name("PhaseCode.ABC"));
707        // A trailing dot would end the statement.
708        assert!(!is_turtle_local_name("Trailing."));
709        assert!(!is_turtle_local_name("9leading"));
710        assert!(!is_turtle_local_name(""));
711    }
712
713    #[test]
714    fn iris_split_at_the_last_separator() {
715        assert_eq!(
716            split_iri("http://iec.ch/TC57/CIM100#ACLineSegment.r"),
717            Some(("http://iec.ch/TC57/CIM100#", "ACLineSegment.r"))
718        );
719        assert_eq!(split_iri("urn:uuid:abc"), None);
720    }
721}