Skip to main content

cim_kit/
rdf.rs

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