use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::io::{self, BufRead, Read};
use quick_xml::Reader;
use quick_xml::events::{BytesStart, Event};
use crate::dataset::{Dataset, ObjectId};
use crate::error::{Diagnostic, Error, Report, Result, Rule};
use crate::header::{
DM_NS, DifferenceModel, HeaderProperty, MD_NS, ModelHeader, ModelKind, QualifiedName,
Statement, StatementValue,
};
use crate::mrid::Mrid;
use crate::object::{Compound, Object};
use crate::schema::{AttrId, AttrKind, ClassId, Primitive, ProfileId, ProfileMask, Schema};
use crate::value::Value;
const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
static UNKNOWN_MRID: Mrid = Mrid::nil();
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Strictness {
#[default]
Lenient,
Strict,
}
#[derive(Clone, Debug)]
pub struct ReadOptions {
pub strictness: Strictness,
pub assume_profile: Option<ProfileId>,
pub report_deprecated: bool,
pub report_non_conforming_mrids: bool,
pub max_diagnostics: usize,
pub max_input_bytes: u64,
pub single_description: bool,
}
impl Default for ReadOptions {
fn default() -> Self {
ReadOptions {
strictness: Strictness::Lenient,
assume_profile: None,
report_deprecated: false,
report_non_conforming_mrids: false,
max_diagnostics: ReadOptions::DEFAULT_MAX_DIAGNOSTICS,
max_input_bytes: ReadOptions::DEFAULT_MAX_INPUT_BYTES,
single_description: false,
}
}
}
impl ReadOptions {
pub const DEFAULT_MAX_DIAGNOSTICS: usize = 10_000;
pub const DEFAULT_MAX_INPUT_BYTES: u64 = 8 << 30;
pub fn lenient() -> ReadOptions {
ReadOptions::default()
}
pub fn strict() -> ReadOptions {
ReadOptions {
strictness: Strictness::Strict,
report_deprecated: true,
report_non_conforming_mrids: true,
..ReadOptions::default()
}
}
pub fn with_profile(mut self, profile: ProfileId) -> Self {
self.assume_profile = Some(profile);
self
}
pub fn with_max_diagnostics(mut self, max: usize) -> Self {
self.max_diagnostics = max;
self
}
pub fn with_max_input_bytes(mut self, max: u64) -> Self {
self.max_input_bytes = max;
self
}
pub fn with_single_description(mut self, on: bool) -> Self {
self.single_description = on;
self
}
}
#[derive(Debug)]
pub(crate) struct Budget {
limit: u64,
used: Cell<u64>,
tripped: Cell<bool>,
}
impl Budget {
pub(crate) fn new(options: &ReadOptions) -> Budget {
Budget {
limit: options.max_input_bytes,
used: Cell::new(0),
tripped: Cell::new(false),
}
}
pub(crate) fn meter<R: BufRead>(&self, input: R) -> Metered<'_, R> {
Metered {
inner: input,
used: self.used.get(),
limit: if self.limit == 0 {
u64::MAX
} else {
self.limit
},
budget: self,
}
}
pub(crate) fn check<T>(&self, result: Result<T>, source: Option<&str>) -> Result<T> {
match result {
Err(_) if self.tripped.get() => Err(Error::InputTooLarge {
limit: self.limit,
read: self.used.get(),
source: source.map(str::to_owned),
}),
other => other,
}
}
pub(crate) fn tripped(&self) -> bool {
self.tripped.get()
}
}
pub(crate) struct Metered<'a, R> {
inner: R,
used: u64,
limit: u64,
budget: &'a Budget,
}
impl<R> Drop for Metered<'_, R> {
fn drop(&mut self) {
self.budget.used.set(self.used);
}
}
impl<R: BufRead> Read for Metered<'_, R> {
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
let available = self.fill_buf()?;
let n = available.len().min(out.len());
out[..n].copy_from_slice(&available[..n]);
self.consume(n);
Ok(n)
}
}
impl<R: BufRead> BufRead for Metered<'_, R> {
#[inline]
fn fill_buf(&mut self) -> io::Result<&[u8]> {
if self.used > self.limit {
self.budget.tripped.set(true);
self.budget.used.set(self.used);
return Err(io::Error::other("input budget exceeded"));
}
let room = self.limit - self.used;
let buf = self.inner.fill_buf()?;
Ok(match usize::try_from(room) {
Ok(room) if room < buf.len() => &buf[..=room],
_ => buf,
})
}
#[inline]
fn consume(&mut self, amt: usize) {
self.used = self.used.saturating_add(amt as u64);
self.inner.consume(amt);
}
}
const SNIFF_PREFIX: u64 = 1 << 20;
#[derive(Debug)]
pub struct ReadOutcome {
pub header: Option<ModelHeader>,
pub difference: Option<DifferenceModel>,
pub report: Report,
pub objects_read: usize,
}
pub fn read_into<R: BufRead>(
dataset: &mut Dataset,
input: R,
source: Option<&str>,
options: &ReadOptions,
) -> Result<ReadOutcome> {
let budget = Budget::new(options);
read_into_within(dataset, input, source, options, &budget)
}
pub(crate) fn read_into_within<R: BufRead>(
dataset: &mut Dataset,
input: R,
source: Option<&str>,
options: &ReadOptions,
budget: &Budget,
) -> Result<ReadOutcome> {
let schema = dataset.schema();
let mut parser = Parser::new(schema, source, options, false);
let outcome = parser.run(budget.meter(input), Some(dataset));
budget.check(outcome, source)
}
pub fn read_header<R: BufRead>(
schema: &'static Schema,
input: R,
source: Option<&str>,
) -> Result<Option<ModelHeader>> {
let options = ReadOptions::default();
let budget = Budget::new(&options);
let mut parser = Parser::new(schema, source, &options, true);
let outcome = parser.run(budget.meter(input), None);
Ok(budget.check(outcome, source)?.header)
}
pub fn sniff<R: BufRead>(input: R) -> Result<Option<&'static Schema>> {
let mut reader = Reader::from_reader(input.take(SNIFF_PREFIX));
reader.config_mut().check_end_names = false;
let mut buf = Vec::new();
loop {
let ev = match reader.read_event_into(&mut buf) {
Ok(ev) => ev,
Err(_) if reader.get_ref().limit() == 0 => return Ok(None),
Err(e) => {
return Err(Error::xml(shown(&e.to_string())).locate(None, reader.error_position()));
}
};
let e = match ev {
Event::Eof => return Ok(None),
Event::Start(e) | Event::Empty(e) => e,
_ => {
buf.clear();
continue;
}
};
let mut iris: Vec<String> = Vec::new();
for attr in e.attributes().with_checks(false) {
let attr = attr?;
let key = attr.key.as_ref();
if key == "xmlns" || key.starts_with("xmlns:") {
iris.push(attr.value.into_owned());
}
}
if let Some(schema) = Schema::detect(iris.iter().map(String::as_str)) {
return Ok(Some(schema));
}
buf.clear();
}
}
pub fn read_difference<R: BufRead>(
schema: &'static Schema,
input: R,
source: Option<&str>,
options: &ReadOptions,
) -> Result<Option<DifferenceModel>> {
let budget = Budget::new(options);
let mut parser = Parser::new(schema, source, options, false);
let outcome = parser.run(budget.meter(input), None);
Ok(budget.check(outcome, source)?.difference)
}
#[derive(Clone, Copy)]
enum Resolved {
Class(ClassId),
Attr(AttrId),
Unknown,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Ctx {
Outside,
Body,
Header,
Object,
Compound,
DiffSet,
DiffSubject,
Text,
Skip,
}
enum Prop {
Value(AttrId, Value),
Enter(AttrId, ClassId),
Text(AttrId),
Skip,
}
#[derive(Default)]
struct State {
saw_root: bool,
header: Option<ModelHeader>,
difference: Option<DifferenceModel>,
staged: Vec<Staged>,
staged_seen: Vec<(AttrId, u64)>,
object: Option<Object>,
object_start: u64,
object_defined: bool,
seen: Vec<(AttrId, u64)>,
compounds: Vec<Frame>,
pending: Option<PendingText>,
profile_mask: ProfileMask,
diff_subject: Option<(Mrid, Option<QualifiedName>, bool)>,
diff_set: DiffSet,
}
struct Staged {
object: Object,
start: u64,
defined: bool,
seen: std::ops::Range<u32>,
}
struct Described {
start: u64,
defined: bool,
seen: std::ops::Range<u32>,
more: Vec<(AttrId, u64)>,
}
impl Described {
fn new(s: &Staged) -> Described {
Described {
start: s.start,
defined: s.defined,
seen: s.seen.clone(),
more: Vec::new(),
}
}
}
struct DocumentObjects {
base: usize,
created: Vec<Described>,
merged: HashMap<u32, Described>,
}
impl DocumentObjects {
fn get_mut(&mut self, id: ObjectId) -> Option<&mut Described> {
match id.index().checked_sub(self.base) {
Some(i) => self.created.get_mut(i),
None => self.merged.get_mut(&(id.index() as u32)),
}
}
}
struct Frame {
attr: AttrId,
compound: Compound,
start: u64,
seen: Vec<(AttrId, u64)>,
}
impl Frame {
fn new(attr: AttrId, class: ClassId, start: u64) -> Frame {
Frame {
attr,
compound: Compound::new(class),
start,
seen: Vec::new(),
}
}
}
#[derive(Default)]
struct OpenElements {
names: String,
open: Vec<(usize, u64)>,
}
impl OpenElements {
fn push(&mut self, qname: &str, start: u64) {
self.open.push((self.names.len(), start));
self.names.push_str(qname);
}
fn pop(&mut self) {
if let Some((at, _)) = self.open.pop() {
self.names.truncate(at);
}
}
fn innermost(&self) -> Option<(String, u64)> {
let &(at, start) = self.open.last()?;
Some((shown(&self.names[at..]).into_owned(), start))
}
}
struct Parser<'a> {
schema: &'static Schema,
options: &'a ReadOptions,
source: Option<String>,
report: Report,
header_only: bool,
truncated: bool,
ns: Vec<(usize, Box<str>, String)>,
rdf_spans: Cell<[(u32, u32); 3]>,
cache: HashMap<Vec<u8>, Resolved>,
undefined_entities: RefCell<Vec<String>>,
illegal_in_attribute: Cell<Option<char>>,
}
impl<'a> Parser<'a> {
fn new(
schema: &'static Schema,
source: Option<&str>,
options: &'a ReadOptions,
header_only: bool,
) -> Parser<'a> {
Parser {
schema,
options,
source: source.map(str::to_owned),
report: Report::default(),
header_only,
truncated: false,
ns: Vec::new(),
rdf_spans: Cell::new([(0, 0); 3]),
cache: HashMap::new(),
undefined_entities: RefCell::new(Vec::new()),
illegal_in_attribute: Cell::new(None),
}
}
#[inline]
fn flush_attribute_findings(&mut self, pos: u64) {
if !self.undefined_entities.get_mut().is_empty()
|| self.illegal_in_attribute.get().is_some()
{
self.report_attribute_findings(pos);
}
}
#[cold]
#[inline(never)]
fn report_attribute_findings(&mut self, pos: u64) {
let names = std::mem::take(self.undefined_entities.get_mut());
for name in names {
self.diag(undefined_entity(&name), pos);
}
if let Some(c) = self.illegal_in_attribute.take() {
self.diag(
Diagnostic::warning(
Rule::IllegalXmlCharacter,
format!(
"an attribute value holds {}, which XML 1.0 cannot represent in any \
form; removed",
crate::xml::describe_char(c)
),
),
pos,
);
}
}
fn attr_value<'e>(
&self,
attr: &quick_xml::events::attributes::Attribute<'e>,
) -> Result<Cow<'e, str>> {
let value = self.normalized_attr_value(attr)?;
match crate::xml::find_illegal(&value) {
None => Ok(value),
Some((_, c)) => {
if self.illegal_in_attribute.get().is_none() {
self.illegal_in_attribute.set(Some(c));
}
Ok(Cow::Owned(crate::xml::strip_illegal(&value).into_owned()))
}
}
}
fn normalized_attr_value<'e>(
&self,
attr: &quick_xml::events::attributes::Attribute<'e>,
) -> Result<Cow<'e, str>> {
use quick_xml::escape::EscapeError;
match attr.normalized_value(quick_xml::XmlVersion::Explicit1_0) {
Ok(v) => Ok(v),
Err(quick_xml::Error::Escape(EscapeError::UnrecognizedEntity(..))) => {
let (escaped, names) = escape_undefined_entities(&attr.value);
self.undefined_entities.borrow_mut().extend(names);
let rewritten = quick_xml::events::attributes::Attribute {
key: attr.key,
value: Cow::Owned(escaped),
};
let value = rewritten
.normalized_value(quick_xml::XmlVersion::Explicit1_0)
.map_err(|e| Error::xml(e.to_string()))?;
Ok(Cow::Owned(value.into_owned()))
}
Err(e) => Err(Error::xml(e.to_string())),
}
}
fn diag(&mut self, d: Diagnostic, pos: u64) {
let max = self.options.max_diagnostics;
if max != 0 && self.report.len() >= max {
if !self.truncated {
self.truncated = true;
self.report.push(Diagnostic::warning(
Rule::Structure,
format!(
"stopped recording after {max} diagnostics; reading continued \
(raise ReadOptions::max_diagnostics to see the rest)"
),
));
}
return;
}
let mut d = d.with_position(pos);
if let Some(s) = &self.source {
d = d.with_source(s.clone());
}
self.report.push(d);
}
fn expand<'q>(&self, qname: &'q str) -> Option<(&str, &'q str)> {
let (prefix, local) = match qname.split_once(':') {
Some((prefix, local)) => (prefix, local),
None => ("", qname),
};
Some((self.namespace(prefix)?, local))
}
fn resolve(&mut self, qname: &str) -> Result<Resolved> {
if let Some(r) = self.cache.get(qname.as_bytes()) {
return Ok(*r);
}
let resolved = match self.expand(qname) {
Some((ns, local)) if local.contains('.') => match self.schema.find_attr(ns, local) {
Some(a) => Resolved::Attr(a),
None => Resolved::Unknown,
},
Some((ns, local)) => match self.schema.find_class(ns, local) {
Some(c) => Resolved::Class(c),
None => Resolved::Unknown,
},
None => {
self.check_prefix(qname, qname)?;
Resolved::Unknown
}
};
self.cache.insert(qname.as_bytes().to_vec(), resolved);
Ok(resolved)
}
fn run<R: BufRead>(&mut self, input: R, dataset: Option<&mut Dataset>) -> Result<ReadOutcome> {
let mut reader = Reader::from_reader(input);
reader.config_mut().trim_text(false);
reader.config_mut().expand_empty_elements = false;
reader.config_mut().check_end_names = true;
let source = self.source.clone();
let mut buf = Vec::new();
let mut ctx = Ctx::Outside;
let mut stack: Vec<Ctx> = Vec::with_capacity(8);
let mut open = OpenElements::default();
let mut root_closed = false;
let mut st = State {
profile_mask: self.options.assume_profile.map_or(0, |p| p.mask()),
..Default::default()
};
loop {
let pos = reader.buffer_position();
let ev = match reader.read_event_into(&mut buf) {
Ok(ev) => ev,
Err(e) => {
let at_end = reader.get_mut().fill_buf().is_ok_and(<[u8]>::is_empty);
return Err(parse_error(
e,
reader.error_position(),
at_end,
&open,
&source,
));
}
};
if stack.is_empty()
&& let Some(problem) = outside_document(&ev, root_closed)
{
return Err(Error::xml(problem).locate(source.as_deref(), pos));
}
match ev {
Event::Eof => break,
Event::Start(e) => {
let next = self
.on_open(&e, false, ctx, &mut st, pos, stack.len())
.map_err(|err| err.locate(source.as_deref(), pos))?;
self.flush_attribute_findings(pos);
open.push(e.name().as_ref(), pos);
stack.push(ctx);
ctx = next;
}
Event::Empty(e) => {
let saved = ctx;
let entered = self
.on_open(&e, true, ctx, &mut st, pos, stack.len())
.map_err(|err| err.locate(source.as_deref(), pos))?;
self.flush_attribute_findings(pos);
self.close_scope(stack.len());
match entered {
Ctx::Object => self.stage(&mut st),
Ctx::Compound => self.close_compound(&mut st),
Ctx::DiffSubject => st.diff_subject = None,
Ctx::Header => self.adopt_header(&mut st),
_ => {}
}
ctx = saved;
root_closed |= stack.is_empty();
}
Event::Text(t) if ctx == Ctx::Text => {
if let Some(p) = st.pending.as_mut() {
let text = t.xml10_content();
p.text.push_str(&text);
}
}
Event::GeneralRef(r) if ctx == Ctx::Text => {
let mut undefined = None;
if let Some(p) = st.pending.as_mut() {
match r.resolve_char_ref() {
Ok(Some(c)) => p.text.push(c),
Ok(None) | Err(_) => {
let name = r.as_ref();
match quick_xml::escape::resolve_predefined_entity(name) {
Some(text) => p.text.push_str(text),
None => {
p.text.push('&');
p.text.push_str(name);
p.text.push(';');
undefined = Some(name.to_owned());
}
}
}
}
}
if let Some(name) = undefined {
self.diag(undefined_entity(&name), pos);
}
}
Event::CData(t) if ctx == Ctx::Text => {
if let Some(p) = st.pending.as_mut() {
p.text.push_str(&t);
}
}
Event::End(_) => {
match ctx {
Ctx::Header => self.adopt_header(&mut st),
Ctx::Text => {
if let Some(p) = st.pending.take() {
self.finish_text(p, &mut st);
}
}
Ctx::Object => self.stage(&mut st),
Ctx::Compound => self.close_compound(&mut st),
Ctx::DiffSubject => st.diff_subject = None,
_ => {}
}
ctx = stack.pop().unwrap_or(Ctx::Outside);
self.close_scope(stack.len());
open.pop();
root_closed |= stack.is_empty();
}
_ => {}
}
buf.clear();
if self.header_only && st.header.is_some() && ctx == Ctx::Body {
break;
}
}
if !self.header_only
&& let Some((name, start)) = open.innermost()
{
return Err(Error::Truncated {
open: Some(name),
source,
position: start,
});
}
if !st.saw_root {
return Err(Error::NotCimXml {
message: "no rdf:RDF root element found".to_owned(),
source,
position: None,
});
}
let mut header = st.header;
let mut difference = st.difference;
if let Some(d) = difference.as_mut()
&& let Some(h) = header.clone()
{
d.header = h;
}
if let Some(h) = header.as_mut()
&& h.source.is_none()
{
h.source = self.source.clone();
}
let objects_read = st.staged.len();
if let Some(ds) = dataset {
let slot = ds.push_header(self.slot_header(header.as_ref()));
let mut doc = DocumentObjects {
base: ds.slot_count(),
created: Vec::with_capacity(st.staged.len()),
merged: HashMap::new(),
};
for s in st.staged {
self.commit(s, &mut st.staged_seen, &mut doc, slot, ds);
}
if let Some(d) = difference.as_ref() {
ds.push_difference(d.clone());
}
}
Ok(ReadOutcome {
header,
difference,
report: std::mem::take(&mut self.report),
objects_read,
})
}
fn check_vintage(&mut self, pos: u64) {
let declared: Vec<&str> = self.ns.iter().map(|(.., iri)| iri.as_str()).collect();
let Some(actual) = Schema::detect(declared.iter().copied()) else {
return;
};
if std::ptr::eq(actual, self.schema) {
return;
}
self.diag(
Diagnostic::error(
Rule::WrongVintage,
format!(
"this document is {} and is being read as {}; nothing in it will \
resolve. Use `{}::SCHEMA`, or `reader::sniff` to detect it",
actual.vintage, self.schema.vintage, actual.vintage
),
),
pos,
);
}
fn slot_header(&self, header: Option<&ModelHeader>) -> ModelHeader {
let mut h = header.cloned().unwrap_or_else(|| {
let mut h = ModelHeader::new(ModelKind::Full);
h.source = self.source.clone();
h
});
if h.profiles.is_empty()
&& let Some(p) = self.options.assume_profile
{
h.profiles
.push(self.schema.profile(p).version_iri.to_owned());
}
h
}
fn adopt_header(&mut self, st: &mut State) {
let Some(h) = st.header.as_ref() else { return };
let declared = h
.profiles
.iter()
.filter_map(|iri| self.schema.profile_by_iri(iri))
.fold(0, |acc, p| acc | p.mask());
if declared != 0 {
st.profile_mask = declared;
}
}
fn stage(&mut self, st: &mut State) {
let Some(mut object) = st.object.take() else {
return;
};
object.mark_profile(st.profile_mask);
let from = st.staged_seen.len() as u32;
st.staged_seen.extend_from_slice(&st.seen);
st.staged.push(Staged {
object,
start: st.object_start,
defined: st.object_defined,
seen: from..st.staged_seen.len() as u32,
});
}
fn close_compound(&mut self, st: &mut State) {
let Some(frame) = st.compounds.pop() else {
return;
};
let value = Value::Compound(Box::new(frame.compound));
self.store(st, frame.attr, value, frame.start);
}
fn store(&mut self, st: &mut State, attr: AttrId, value: Value, pos: u64) {
let many = self.schema.attr(attr).mult.is_many();
if !many {
let seen = match st.compounds.last_mut() {
Some(frame) => &mut frame.seen,
None => &mut st.seen,
};
match seen.iter().find(|(a, _)| *a == attr) {
Some(&(_, first)) => self.report_repeat(st, attr, &value, first, pos),
None => seen.push((attr, pos)),
}
}
let mask = st.profile_mask;
match st.compounds.last_mut() {
Some(frame) if many => frame.compound.push(attr, value),
Some(frame) => frame.compound.set(attr, value),
None => {
if let Some(obj) = st.object.as_mut() {
if many {
obj.push_in(mask, attr, value);
} else {
obj.set_in(mask, attr, value);
}
}
}
}
}
#[cold]
fn report_repeat(&mut self, st: &State, attr: AttrId, value: &Value, first: u64, pos: u64) {
let earlier = match st.compounds.last() {
Some(frame) => frame.compound.get(attr),
None => st.object.as_ref().and_then(|o| o.get(attr)),
};
let Some(earlier) = earlier else { return };
let schema = self.schema;
let mut d = repeat_finding(schema, attr, earlier, value, first);
if let Some(o) = st.object.as_ref() {
d = d
.with_class(schema.class(o.class()).name)
.with_object(o.mrid().clone());
}
self.diag(d, pos);
}
fn commit(
&mut self,
s: Staged,
seen: &mut [(AttrId, u64)],
doc: &mut DocumentObjects,
slot: usize,
ds: &mut Dataset,
) {
let Some(id) = ds.find(s.object.mrid()) else {
doc.created.push(Described::new(&s));
let mut object = s.object;
object.from_file = true;
object.shrink_for_load();
let id = ds.insert_new(object);
ds.record_source(slot, id);
return;
};
if let Some(held) = doc.get_mut(id) {
self.redescribe(ds, id, held, s, seen);
return;
}
let described = Described::new(&s);
let mut object = s.object;
object.from_file = true;
object.shrink_for_load();
if let Some(existing) = ds.get(id) {
let (incoming, held) = (object.class(), existing.class());
if !self.schema.is_a(incoming, held) && !self.schema.is_a(held, incoming) {
let d = Diagnostic::error(
Rule::DuplicateMrid,
format!(
"identifier {} is used by both {} and {}, which are unrelated classes",
object.mrid().canonical(),
self.schema.class(held).name,
self.schema.class(incoming).name
),
)
.with_class(self.schema.class(incoming).name)
.with_object(object.mrid().clone());
self.diag(d, s.start);
}
}
for c in ds.absorb(id, object) {
ds.record_conflict(c);
}
doc.merged.insert(id.index() as u32, described);
ds.record_source(slot, id);
}
#[cold]
fn redescribe(
&mut self,
ds: &mut Dataset,
id: ObjectId,
held: &mut Described,
s: Staged,
seen: &mut [(AttrId, u64)],
) {
let schema = self.schema;
let Some(current) = ds.get(id) else { return };
let (held_class, class) = (current.class(), s.object.class());
let name = schema.class(class).name;
let mrid = s.object.mrid();
let first = held.start;
let twice = if s.defined && held.defined {
Some(format!(
"{} is defined again with rdf:ID; first defined at byte {first}",
mrid.canonical()
))
} else if !schema.is_a(class, held_class) && !schema.is_a(held_class, class) {
Some(format!(
"{} is described as {} at byte {first} and again as {name}, which are \
unrelated classes",
mrid.canonical(),
schema.class(held_class).name
))
} else if self.options.single_description {
Some(format!(
"{} is described again; first described at byte {first}",
mrid.canonical()
))
} else {
None
};
if let Some(message) = twice {
let d = Diagnostic::error(Rule::DuplicateMrid, message)
.with_class(name)
.with_object(mrid.clone())
.with_related_position(first);
self.diag(d, s.start);
}
let mut reported = Vec::new();
for k in s.seen.clone() {
let (attr, pos) = seen[k as usize];
let (first_seen, more) = (
&mut seen[held.seen.start as usize..held.seen.end as usize],
&mut held.more,
);
let Some(entry) = first_seen
.iter_mut()
.chain(more.iter_mut())
.find(|(a, _)| *a == attr)
else {
held.more.push((attr, pos));
continue;
};
if let (Some(earlier), Some(later)) = (current.get(attr), s.object.get(attr)) {
let d = repeat_finding(schema, attr, earlier, later, entry.1)
.with_class(name)
.with_object(mrid.clone());
self.diag(d, pos);
reported.push(attr);
}
entry.1 = pos;
}
held.defined |= s.defined;
for c in ds.absorb(id, s.object) {
if !reported.contains(&c.attr) {
ds.record_conflict(c);
}
}
}
fn on_open(
&mut self,
e: &BytesStart<'_>,
self_closing: bool,
ctx: Ctx,
st: &mut State,
pos: u64,
depth: usize,
) -> Result<Ctx> {
let qname = e.name();
let qname = qname.as_ref();
if !st.saw_root || declares_namespace(e) {
self.collect_namespaces(e, depth)?;
}
let resolves = st.saw_root
&& !self.header_only
&& match ctx {
Ctx::Body => true,
Ctx::Object => st.object.is_some(),
Ctx::Compound => !st.compounds.is_empty(),
_ => false,
};
if !resolves {
self.check_prefix(qname, qname)?;
}
self.check_attribute_prefixes(e, qname)?;
if !st.saw_root {
if let Some((ns, local)) = self.expand(qname)
&& ns == RDF_NS
&& local == "RDF"
{
st.saw_root = true;
self.check_vintage(pos);
return Ok(Ctx::Body);
}
return Ok(ctx);
}
match ctx {
Ctx::Body => self.open_in_body(e, qname, st, pos),
Ctx::Object => {
let Some(obj) = st.object.as_ref() else {
return Ok(Ctx::Skip);
};
let (class, mrid) = (obj.class(), obj.mrid());
match self.property(e, self_closing, class, mrid, pos)? {
Prop::Value(attr, value) => {
self.store(st, attr, value, pos);
Ok(Ctx::Skip)
}
Prop::Enter(attr, class) => {
st.compounds.push(Frame::new(attr, class, pos));
Ok(Ctx::Compound)
}
Prop::Text(attr) => {
st.pending = Some(PendingText {
target: TextTarget::Attr(attr),
text: String::new(),
start: pos,
});
Ok(Ctx::Text)
}
Prop::Skip => Ok(Ctx::Skip),
}
}
Ctx::Compound => {
let Some(top) = st.compounds.last() else {
return Ok(Ctx::Skip);
};
let class = top.compound.class();
let mrid = st.object.as_ref().map_or(&UNKNOWN_MRID, |o| o.mrid());
match self.property(e, self_closing, class, mrid, pos)? {
Prop::Value(attr, value) => {
self.store(st, attr, value, pos);
Ok(Ctx::Skip)
}
Prop::Enter(attr, class) => {
st.compounds.push(Frame::new(attr, class, pos));
Ok(Ctx::Compound)
}
Prop::Text(attr) => {
st.pending = Some(PendingText {
target: TextTarget::Compound(attr),
text: String::new(),
start: pos,
});
Ok(Ctx::Text)
}
Prop::Skip => Ok(Ctx::Skip),
}
}
Ctx::Header => self.open_in_header(e, qname, self_closing, st, pos),
Ctx::DiffSet => {
let about = self.attr(e, RDF_NS, "about")?;
let defines = about.is_none();
if let Some(raw) = about.or(self.attr(e, RDF_NS, "ID")?) {
let class = self.expand(qname).and_then(|(ns, local)| {
(!(ns == RDF_NS && local == "Description")).then(|| QualifiedName {
ns: ns.to_owned(),
local: local.to_owned(),
})
});
st.diff_subject = Some((Mrid::parse(raw.trim()), class, defines));
return Ok(Ctx::DiffSubject);
}
Ok(Ctx::Skip)
}
Ctx::DiffSubject => {
let Some((ns, local)) = self
.expand(qname)
.map(|(n, l)| (n.to_owned(), l.to_owned()))
else {
return Ok(Ctx::Skip);
};
let Some((subject, class, defines_subject)) = st.diff_subject.clone() else {
return Ok(Ctx::Skip);
};
if let Some(res) = self.attr(e, RDF_NS, "resource")? {
let res = res.trim().to_owned();
push_statement(
&mut st.difference,
st.diff_set,
Statement {
subject,
class,
defines_subject,
predicate_ns: ns,
predicate: local,
value: StatementValue::Resource(res),
},
);
return Ok(Ctx::Skip);
}
if self_closing {
return Ok(Ctx::Skip);
}
st.pending = Some(PendingText {
target: TextTarget::Statement {
subject,
class,
defines_subject,
ns,
local,
set: st.diff_set,
},
text: String::new(),
start: pos,
});
Ok(Ctx::Text)
}
Ctx::Text => {
let name = shown(qname);
self.diag(
Diagnostic::warning(
Rule::Structure,
format!("unexpected element <{name}> inside a value; skipped"),
),
pos,
);
Ok(Ctx::Skip)
}
Ctx::Skip | Ctx::Outside => Ok(Ctx::Skip),
}
}
fn open_in_body(
&mut self,
e: &BytesStart<'_>,
qname: &str,
st: &mut State,
pos: u64,
) -> Result<Ctx> {
if let Some((ns, local)) = self.expand(qname)
&& ((ns == MD_NS && local == "FullModel")
|| (ns == DM_NS && local == "DifferenceModel"))
{
let kind = if ns == DM_NS {
ModelKind::Difference
} else {
ModelKind::Full
};
let mut h = ModelHeader::new(kind);
h.id = self
.attr(e, RDF_NS, "about")?
.map(|s| Mrid::parse(s.trim()));
h.source = self.source.clone();
st.header = Some(h);
if kind == ModelKind::Difference {
st.difference = Some(DifferenceModel::default());
}
return Ok(Ctx::Header);
}
if self.header_only {
return Ok(Ctx::Skip);
}
match self.resolve(qname)? {
Resolved::Class(class) => {
let def = self.schema.class(class);
if def.compound {
self.diag(
Diagnostic::error(
Rule::Structure,
format!(
"compound type {} has no identity and cannot be a top-level object",
def.name
),
)
.with_class(def.name),
pos,
);
return Ok(Ctx::Skip);
}
if !def.concrete {
self.diag(
Diagnostic::error(
Rule::AbstractInstantiated,
format!("abstract class {} instantiated", def.name),
)
.with_class(def.name),
pos,
);
}
if self.options.report_deprecated && def.deprecated {
self.diag(
Diagnostic::info(
Rule::Deprecated,
format!("deprecated class {}", def.name),
)
.with_class(def.name),
pos,
);
}
let (mrid, defined) = self.object_identity(e, def.name, pos)?;
let mut o = Object::new(class, mrid);
o.mark_profile(st.profile_mask);
st.object = Some(o);
st.object_start = pos;
st.object_defined = defined;
st.seen.clear();
Ok(Ctx::Object)
}
Resolved::Attr(_) | Resolved::Unknown => {
let name = shown(qname);
if self.options.strictness == Strictness::Strict {
return Err(Error::not_cim(format!("unknown class element <{name}>")));
}
self.diag(
Diagnostic::warning(
Rule::UnknownClass,
format!("unknown class element <{name}>, skipped"),
),
pos,
);
Ok(Ctx::Skip)
}
}
}
fn open_in_header(
&mut self,
e: &BytesStart<'_>,
qname: &str,
self_closing: bool,
st: &mut State,
pos: u64,
) -> Result<Ctx> {
let Some((ns, local)) = self
.expand(qname)
.map(|(n, l)| (n.to_owned(), l.to_owned()))
else {
return Ok(Ctx::Skip);
};
let set = match (ns == DM_NS, local.as_str()) {
(true, "forwardDifferences") => Some(DiffSet::Forward),
(true, "reverseDifferences") => Some(DiffSet::Reverse),
(true, "preconditions") => Some(DiffSet::Preconditions),
_ => None,
};
if let Some(set) = set {
st.diff_set = set;
if st.difference.is_none() {
st.difference = Some(DifferenceModel::default());
}
return Ok(Ctx::DiffSet);
}
let prefix = prefix_of(qname);
if let Some(res) = self.attr(e, RDF_NS, "resource")? {
let res = res.trim().to_owned();
apply_header_resource(&mut st.header, &prefix, &ns, &local, res);
return Ok(Ctx::Skip);
}
if self_closing {
return Ok(Ctx::Skip);
}
st.pending = Some(PendingText {
target: TextTarget::Header { prefix, ns, local },
text: String::new(),
start: pos,
});
Ok(Ctx::Text)
}
fn property(
&mut self,
e: &BytesStart<'_>,
self_closing: bool,
class: ClassId,
owner: &Mrid,
pos: u64,
) -> Result<Prop> {
let qname = e.name();
let qname = qname.as_ref();
let Resolved::Attr(attr) = self.resolve(qname)? else {
let name = shown(qname);
if self.options.strictness == Strictness::Strict {
return Err(Error::not_cim(format!("unknown property element <{name}>")));
}
self.diag(
Diagnostic::warning(
Rule::UnknownAttribute,
format!("unknown property <{name}>, skipped"),
)
.with_object(owner.clone()),
pos,
);
return Ok(Prop::Skip);
};
let def = self.schema.attr(attr);
if !self.schema.is_a(class, def.owner) {
self.diag(
Diagnostic::warning(
Rule::UnknownAttribute,
format!(
"{} does not apply to class {}",
def.name,
self.schema.class(class).name
),
)
.with_attribute(def.name)
.with_object(owner.clone()),
pos,
);
return Ok(Prop::Skip);
}
if self.options.report_deprecated && def.deprecated {
self.diag(
Diagnostic::info(
Rule::Deprecated,
format!("deprecated attribute {}", def.name),
)
.with_attribute(def.name),
pos,
);
}
if let AttrKind::Compound(target) = def.kind {
if self.attr(e, RDF_NS, "resource")?.is_some() {
self.diag(
Diagnostic::error(
Rule::InvalidValue,
format!(
"{} holds a compound, which has no identity, but is written as \
a reference",
def.name
),
)
.with_attribute(def.name)
.with_object(owner.clone()),
pos,
);
return Ok(Prop::Skip);
}
return Ok(Prop::Enter(attr, target));
}
if let Some(res) = self.attr(e, RDF_NS, "resource")? {
let res = res.trim();
return Ok(match self.resource_value(attr, res, owner, pos) {
Some(v) => Prop::Value(attr, v),
None => Prop::Skip,
});
}
if self_closing {
if matches!(def.kind, AttrKind::Primitive(Primitive::String)) {
return Ok(Prop::Value(attr, Value::Text("".into())));
}
return Ok(Prop::Skip);
}
Ok(Prop::Text(attr))
}
fn object_identity(
&mut self,
e: &BytesStart<'_>,
class: &'static str,
pos: u64,
) -> Result<(Mrid, bool)> {
for (name, raw) in [
("rdf:ID", self.attr(e, RDF_NS, "ID")?),
("rdf:about", self.attr(e, RDF_NS, "about")?),
] {
let Some(raw) = raw else { continue };
let raw = raw.trim();
let m = Mrid::parse(raw);
let unwritable_id = name == "rdf:ID" && !crate::xml::is_ncname(raw);
if unwritable_id || (self.options.report_non_conforming_mrids && !m.is_conforming()) {
let complaint = if unwritable_id {
format!(
"is not an XML NCName and so cannot be written back as one; repaired to {:?}",
m.to_rdf_id()
)
} else if m.is_uuid() {
format!(
"is a UUID written without hyphens; IEC 61970-552 requires {:?}",
m.canonical()
)
} else {
"is not a UUID as IEC 61970-552 requires".to_owned()
};
self.diag(
Diagnostic::warning(
Rule::NonConformingMrid,
format!("{name} {raw:?} {complaint}"),
)
.with_class(class),
pos,
);
}
return Ok((m, name == "rdf:ID"));
}
let placeholder = match &self.source {
Some(src) => format!("no-identifier-{src}-{pos}"),
None => format!("no-identifier-{pos}"),
};
self.diag(
Diagnostic::error(
Rule::Structure,
format!("<{class}> has neither rdf:ID nor rdf:about; kept as {placeholder:?}"),
)
.with_class(class),
pos,
);
Ok((Mrid::parse(&placeholder), false))
}
fn resource_value(&mut self, attr: AttrId, res: &str, owner: &Mrid, pos: u64) -> Option<Value> {
let def = self.schema.attr(attr);
let AttrKind::Enumeration(_) = def.kind else {
return Some(Value::Reference(Mrid::parse(res)));
};
let Some((ns, local)) = res.rsplit_once('#') else {
self.diag(
Diagnostic::error(
Rule::InvalidValue,
format!("enumeration value {res:?} is not an IRI"),
)
.with_attribute(def.name),
pos,
);
return None;
};
if let Some(v) = self.schema.find_enum_value(&format!("{ns}#"), local) {
return Some(Value::Enum(v));
}
match self.schema.find_enum_value_any_ns(local) {
Some(v) => {
let correct = self.schema.namespace(self.schema.enum_value(v).ns).iri;
self.diag(
Diagnostic::warning(
Rule::InvalidValue,
format!(
"enumeration literal {local} is written in namespace {ns}# but is \
declared in {correct}; value recovered"
),
)
.with_attribute(def.name)
.with_object(owner.clone()),
pos,
);
Some(Value::Enum(v))
}
None => {
self.diag(
Diagnostic::error(
Rule::InvalidValue,
format!("unknown enumeration literal {res:?}"),
)
.with_attribute(def.name)
.with_object(owner.clone()),
pos,
);
None
}
}
}
fn finish_text(&mut self, mut p: PendingText, st: &mut State) {
let pos = p.start;
if let Some((offset, c)) = crate::xml::find_illegal(&p.text) {
self.diag(
Diagnostic::warning(
Rule::IllegalXmlCharacter,
format!(
"value holds {}, which XML 1.0 cannot represent in any form; \
removed (first at byte {offset} of the value)",
crate::xml::describe_char(c)
),
),
pos,
);
p.text = crate::xml::strip_illegal(&p.text).into_owned();
}
match p.target {
TextTarget::Attr(attr) => {
let Some(obj) = st.object.as_ref() else {
return;
};
if let Some(v) = self.parse_text(attr, &p.text, obj.mrid(), pos) {
self.store(st, attr, v, pos);
}
}
TextTarget::Compound(attr) => {
let mrid = st.object.as_ref().map_or(&UNKNOWN_MRID, |o| o.mrid());
if let Some(v) = self.parse_text(attr, &p.text, mrid, pos)
&& !st.compounds.is_empty()
{
self.store(st, attr, v, pos);
}
}
TextTarget::Header { prefix, ns, local } => {
apply_header_text(&mut st.header, &prefix, &ns, &local, p.text);
}
TextTarget::Statement {
subject,
class,
defines_subject,
ns,
local,
set,
} => push_statement(
&mut st.difference,
set,
Statement {
subject,
class,
defines_subject,
predicate_ns: ns,
predicate: local,
value: StatementValue::Literal(p.text),
},
),
}
}
fn parse_text(&mut self, attr: AttrId, text: &str, owner: &Mrid, pos: u64) -> Option<Value> {
let def = self.schema.attr(attr);
let prim = match def.kind {
AttrKind::Primitive(prim) => prim,
AttrKind::Datatype(dt) => self.schema.datatype(dt).value,
AttrKind::Enumeration(_) | AttrKind::Association { .. } | AttrKind::Compound(_) => {
Primitive::String
}
};
match Value::parse_primitive(prim, text) {
Ok(v) => Some(v),
Err(e) => {
let name = def.name;
self.diag(
Diagnostic::error(Rule::InvalidValue, e.to_string())
.with_attribute(name)
.with_object(owner.clone()),
pos,
);
None
}
}
}
#[inline]
fn namespace(&self, prefix: &str) -> Option<&str> {
match self.ns.iter().rev().find(|(_, p, _)| **p == *prefix) {
Some((.., iri)) => Some(iri),
None => (prefix == "xml").then_some(XML_NS),
}
}
fn collect_namespaces(&mut self, e: &BytesStart<'_>, depth: usize) -> Result<()> {
for attr in e.attributes().with_checks(false) {
let attr = attr?;
let key = attr.key.as_ref();
let prefix = match key.strip_prefix("xmlns:") {
Some(prefix) => prefix,
None if key == "xmlns" => "",
None => continue,
};
let value = self.attr_value(&attr)?.into_owned();
check_binding(prefix, &value)?;
self.ns.push((depth, prefix.into(), value));
self.cache.clear();
}
Ok(())
}
#[inline]
fn close_scope(&mut self, depth: usize) {
if self.ns.last().is_some_and(|(d, ..)| *d >= depth) {
self.end_scope(depth);
}
}
#[cold]
fn end_scope(&mut self, depth: usize) {
let keep = self.ns.partition_point(|(d, ..)| *d < depth);
self.ns.truncate(keep);
self.cache.clear();
}
#[inline]
fn check_attribute_prefixes(&self, e: &BytesStart<'_>, qname: &str) -> Result<()> {
let tag: &str = e;
let mut spans = [(0, 0); 3];
for attr in e.attributes().with_checks(false) {
let attr = attr?;
let key = attr.key.as_ref();
let Some((prefix, local)) = key.split_once(':') else {
continue;
};
if prefix == "xmlns" {
continue;
}
match self.namespace(prefix) {
Some(RDF_NS) => {
if let (Some(i), Cow::Borrowed(value)) = (rdf_slot(local), &attr.value) {
if spans[i] == (0, 0) {
let at = value.as_ptr() as usize - tag.as_ptr() as usize;
spans[i] = (at as u32, (at + value.len()) as u32 + 1);
}
}
}
Some(_) => {}
None => return Err(unbound_prefix(prefix, key, qname)),
}
}
self.rdf_spans.set(spans);
Ok(())
}
#[inline]
fn check_prefix(&self, name: &str, element: &str) -> Result<()> {
match name.split_once(':') {
Some((prefix, _)) if self.namespace(prefix).is_none() => {
Err(unbound_prefix(prefix, name, element))
}
_ => Ok(()),
}
}
fn attr<'e>(
&self,
e: &'e BytesStart<'_>,
ns: &str,
local: &str,
) -> Result<Option<Cow<'e, str>>> {
if ns == RDF_NS
&& let Some(i) = rdf_slot(local)
{
let (start, end) = self.rdf_spans.get()[i];
if end == 0 {
return Ok(None);
}
let tag: &'e str = e;
let attr = quick_xml::events::attributes::Attribute {
key: quick_xml::name::QName(["rdf:ID", "rdf:about", "rdf:resource"][i]),
value: Cow::Borrowed(&tag[start as usize..end as usize - 1]),
};
return self.attr_value(&attr).map(Some);
}
for attr in e.attributes().with_checks(false) {
let attr = attr?;
let key = attr.key.as_ref();
let Some((prefix, name)) = key.split_once(':') else {
continue;
};
if name != local {
continue;
}
if self.namespace(prefix) != Some(ns) {
continue;
}
return Ok(Some(self.attr_value(&attr)?));
}
Ok(None)
}
}
fn parse_error(
e: quick_xml::Error,
at: u64,
at_end: bool,
open: &OpenElements,
source: &Option<String>,
) -> Error {
use quick_xml::errors::{IllFormedError, SyntaxError};
match e {
quick_xml::Error::Io(io) => Error::Io(io::Error::new(io.kind(), io.to_string())),
quick_xml::Error::Syntax(s) if !matches!(s, SyntaxError::InvalidBangMarkup) => {
Error::Truncated {
open: open.innermost().map(|(name, _)| name),
source: source.clone(),
position: at,
}
}
quick_xml::Error::IllFormed(IllFormedError::UnclosedReference) if at_end => {
Error::Truncated {
open: open.innermost().map(|(name, _)| name),
source: source.clone(),
position: at,
}
}
quick_xml::Error::IllFormed(IllFormedError::UnclosedReference) => Error::xml(
"a `&` that starts no entity or character reference; a literal ampersand is \
written `&`",
)
.locate(source.as_deref(), at),
quick_xml::Error::IllFormed(e) => {
Error::xml(shown(&e.to_string())).locate(source.as_deref(), at)
}
other => Error::xml(shown(&other.to_string())).locate(source.as_deref(), at),
}
}
fn outside_document(ev: &Event<'_>, root_closed: bool) -> Option<&'static str> {
match ev {
Event::Start(_) | Event::Empty(_) if root_closed => {
Some("a second document element; XML allows exactly one")
}
Event::Text(t)
if !t
.as_ref()
.bytes()
.all(|b| matches!(b, b' ' | b'\t' | b'\r' | b'\n')) =>
{
Some("text outside the document element")
}
Event::CData(_) | Event::GeneralRef(_) => Some("text outside the document element"),
_ => None,
}
}
fn shown(text: &str) -> Cow<'_, str> {
if text.chars().any(char::is_control) {
Cow::Owned(
text.chars()
.map(|c| {
if c.is_control() {
c.escape_default().to_string()
} else {
c.to_string()
}
})
.collect(),
)
} else {
Cow::Borrowed(text)
}
}
fn undefined_entity(name: &str) -> Diagnostic {
Diagnostic::warning(
Rule::InvalidValue,
format!(
"undefined entity &{name}; kept as text: CIM/XML documents declare no DTD, so \
only the five predefined entities and character references are expanded"
),
)
}
fn escape_undefined_entities(raw: &str) -> (String, Vec<String>) {
let mut out = String::with_capacity(raw.len() + 8);
let mut names = Vec::new();
let mut rest = raw;
while let Some(at) = rest.find('&') {
out.push_str(&rest[..at]);
let after = &rest[at + 1..];
let name = after.split_once(';').map(|(n, _)| n);
match name {
Some(n)
if !n.starts_with('#')
&& quick_xml::escape::resolve_predefined_entity(n).is_none() =>
{
out.push_str("&");
names.push(n.to_owned());
}
_ => out.push('&'),
}
rest = after;
}
out.push_str(rest);
(out, names)
}
#[inline]
fn rdf_slot(local: &str) -> Option<usize> {
match local {
"ID" => Some(0),
"about" => Some(1),
"resource" => Some(2),
_ => None,
}
}
#[cold]
fn unbound_prefix(prefix: &str, name: &str, element: &str) -> Error {
let what = if name == element {
String::new()
} else {
format!(" of attribute {}", shown(name))
};
Error::xml(format!(
"prefix {}{what} on <{}> is not declared",
shown(prefix),
shown(element)
))
}
fn check_binding(prefix: &str, iri: &str) -> Result<()> {
let problem = if prefix == "xmlns" {
"the prefix xmlns cannot be declared"
} else if prefix == "xml" && iri != XML_NS {
"the prefix xml cannot be bound to another namespace"
} else if prefix != "xml" && iri == XML_NS {
"only the prefix xml can be bound to the XML namespace"
} else if iri == XMLNS_NS {
"the xmlns namespace cannot be bound"
} else if !prefix.is_empty() && iri.is_empty() {
"a prefixed namespace declaration cannot be empty"
} else {
return Ok(());
};
let attr = if prefix.is_empty() {
"xmlns".to_owned()
} else {
format!("xmlns:{}", shown(prefix))
};
Err(Error::xml(format!("{attr}: {problem}")))
}
fn repeat_finding(
schema: &Schema,
attr: AttrId,
earlier: &Value,
later: &Value,
first: u64,
) -> Diagnostic {
let def = schema.attr(attr);
let shown = |v| crate::value::display_value(schema, v);
let d = if earlier == later {
Diagnostic::warning(
Rule::CardinalityExceeded,
format!(
"{} is given again with the same value {}, first at byte {first}; it permits one",
def.name,
shown(later)
),
)
} else {
Diagnostic::error(
Rule::ConflictingValue,
format!(
"{} is given twice: {} at byte {first}, then {}; the later is kept",
def.name,
shown(earlier),
shown(later)
),
)
};
d.with_attribute(def.name).with_related_position(first)
}
fn declares_namespace(e: &BytesStart<'_>) -> bool {
e.as_ref().contains("xmlns")
}
fn prefix_of(qname: &str) -> String {
match qname.split_once(':') {
Some((prefix, _)) => prefix.to_owned(),
None => String::new(),
}
}
fn apply_header_resource(
header: &mut Option<ModelHeader>,
prefix: &str,
ns: &str,
local: &str,
res: String,
) {
let Some(h) = header.as_mut() else { return };
match (ns, local) {
(MD_NS, "Model.DependentOn") => h.dependent_on.push(Mrid::parse(&res)),
(MD_NS, "Model.Supersedes") => h.supersedes.push(Mrid::parse(&res)),
(MD_NS, "Model.profile") => h.profiles.push(res),
_ => h
.extra
.push(HeaderProperty::resource(prefix, ns, local, res)),
}
}
fn apply_header_text(
header: &mut Option<ModelHeader>,
prefix: &str,
ns: &str,
local: &str,
text: String,
) {
let Some(h) = header.as_mut() else { return };
if ns != MD_NS {
h.extra.push(HeaderProperty::text(prefix, ns, local, text));
return;
}
match local {
"Model.created" => h.created = Some(text),
"Model.scenarioTime" => h.scenario_time = Some(text),
"Model.description" => h.description = Some(text),
"Model.version" => h.version = Some(text),
"Model.modelingAuthoritySet" => h.modeling_authority_set = Some(text),
"Model.profile" => h.profiles.push(text),
"Model.DependentOn" => h.dependent_on.push(Mrid::parse(&text)),
"Model.Supersedes" => h.supersedes.push(Mrid::parse(&text)),
_ => h.extra.push(HeaderProperty::text(prefix, ns, local, text)),
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum DiffSet {
Preconditions,
#[default]
Reverse,
Forward,
}
fn push_statement(difference: &mut Option<DifferenceModel>, set: DiffSet, s: Statement) {
let d = difference.get_or_insert_with(DifferenceModel::default);
match set {
DiffSet::Preconditions => d.preconditions.push(s),
DiffSet::Reverse => d.reverse.push(s),
DiffSet::Forward => d.forward.push(s),
}
}
struct PendingText {
target: TextTarget,
text: String,
start: u64,
}
enum TextTarget {
Attr(AttrId),
Compound(AttrId),
Header {
prefix: String,
ns: String,
local: String,
},
Statement {
subject: Mrid,
class: Option<QualifiedName>,
defines_subject: bool,
ns: String,
local: String,
set: DiffSet,
},
}