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;
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#";
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,
}
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,
}
}
}
impl ReadOptions {
pub const DEFAULT_MAX_DIAGNOSTICS: usize = 10_000;
pub const DEFAULT_MAX_INPUT_BYTES: u64 = 2 << 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
}
}
#[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(e.to_string())),
};
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>,
objects_read: usize,
object: Option<Object>,
compounds: Vec<(AttrId, Compound)>,
pending: Option<PendingText>,
profile_mask: ProfileMask,
diff_subject: Option<(Mrid, Option<QualifiedName>, bool)>,
diff_set: DiffSet,
source: Option<usize>,
header_registered: bool,
placeholder_slot: Option<usize>,
}
struct Parser<'a> {
schema: &'static Schema,
options: &'a ReadOptions,
source: Option<String>,
report: Report,
header_only: bool,
truncated: bool,
ns: HashMap<Vec<u8>, String>,
cache: HashMap<Vec<u8>, Resolved>,
undefined_entities: RefCell<Vec<String>>,
}
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: HashMap::new(),
cache: HashMap::new(),
undefined_entities: RefCell::new(Vec::new()),
}
}
#[inline]
fn flush_undefined_entities(&mut self, pos: u64) {
if !self.undefined_entities.get_mut().is_empty() {
self.report_undefined_entities(pos);
}
}
#[cold]
#[inline(never)]
fn report_undefined_entities(&mut self, pos: u64) {
let names = std::mem::take(self.undefined_entities.get_mut());
for name in names {
self.diag(undefined_entity(&name), pos);
}
}
fn 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),
};
let ns = self.ns.get(prefix.as_bytes())?;
Some((ns.as_str(), local))
}
fn resolve(&mut self, qname: &str) -> Resolved {
if let Some(r) = self.cache.get(qname.as_bytes()) {
return *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 => Resolved::Unknown,
};
self.cache.insert(qname.as_bytes().to_vec(), resolved);
resolved
}
fn run<R: BufRead>(
&mut self,
input: R,
mut 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 = false;
let mut buf = Vec::new();
let mut ctx = Ctx::Outside;
let mut stack: Vec<Ctx> = Vec::with_capacity(8);
let mut st = State {
profile_mask: self.options.assume_profile.map_or(0, |p| p.mask()),
..Default::default()
};
loop {
let ev = reader.read_event_into(&mut buf).map_err(parse_error)?;
let pos = reader.buffer_position();
match ev {
Event::Eof => break,
Event::Start(e) => {
let next = self.on_open(&e, false, ctx, &mut st, pos)?;
self.flush_undefined_entities(pos);
stack.push(ctx);
ctx = next;
}
Event::Empty(e) => {
let saved = ctx;
let entered = self.on_open(&e, true, ctx, &mut st, pos)?;
self.flush_undefined_entities(pos);
match entered {
Ctx::Object => {
if let Some(o) = st.object.take() {
self.ensure_source(&mut st, &mut dataset);
self.commit(o, &st, &mut dataset, pos);
st.objects_read += 1;
}
}
Ctx::Compound => self.close_compound(&mut st),
Ctx::DiffSubject => st.diff_subject = None,
Ctx::Header => self.register_header(&mut st, &mut dataset),
_ => {}
}
ctx = saved;
}
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(_) => {
if ctx == Ctx::Header {
self.register_header(&mut st, &mut dataset);
}
match ctx {
Ctx::Text => {
if let Some(p) = st.pending.take() {
self.finish_text(p, &mut st, pos);
}
}
Ctx::Object => {
if let Some(o) = st.object.take() {
self.ensure_source(&mut st, &mut dataset);
self.commit(o, &st, &mut dataset, pos);
st.objects_read += 1;
}
}
Ctx::Compound => self.close_compound(&mut st),
Ctx::DiffSubject => st.diff_subject = None,
_ => {}
}
ctx = stack.pop().unwrap_or(Ctx::Outside);
}
_ => {}
}
buf.clear();
if self.header_only && st.header.is_some() && ctx == Ctx::Body {
break;
}
}
if !st.saw_root {
return Err(Error::NotCimXml("no rdf:RDF root element found".to_owned()));
}
if !st.header_registered
&& let Some(ds) = dataset.as_mut()
{
ds.push_header(self.placeholder_header());
}
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();
}
if let (Some(d), Some(ds)) = (difference.as_ref(), dataset.as_mut()) {
ds.push_difference(d.clone());
}
Ok(ReadOutcome {
header,
difference,
report: std::mem::take(&mut self.report),
objects_read: st.objects_read,
})
}
fn check_vintage(&mut self, pos: u64) {
let declared: Vec<&str> = self.ns.values().map(String::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 placeholder_header(&self) -> ModelHeader {
let mut h = ModelHeader::new(ModelKind::Full);
h.source = self.source.clone();
if let Some(p) = self.options.assume_profile {
h.profiles
.push(self.schema.profile(p).version_iri.to_owned());
}
h
}
fn ensure_source(&mut self, st: &mut State, dataset: &mut Option<&mut Dataset>) {
if st.header_registered || st.source.is_some() {
return;
}
st.header_registered = true;
if let Some(ds) = dataset.as_mut() {
let slot = ds.push_header(self.placeholder_header());
st.placeholder_slot = Some(slot);
st.source = Some(slot);
}
}
fn register_header(&mut self, st: &mut State, dataset: &mut Option<&mut Dataset>) {
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;
}
if let Some(slot) = st.placeholder_slot.take()
&& let Some(ds) = dataset.as_mut()
{
let mut h = h.clone();
if h.source.is_none() {
h.source = self.source.clone();
}
ds.set_header(slot, h);
return;
}
if st.header_registered {
return;
}
st.header_registered = true;
if let Some(ds) = dataset.as_mut() {
let mut h = h.clone();
if h.source.is_none() {
h.source = self.source.clone();
}
if h.profiles.is_empty()
&& let Some(p) = self.options.assume_profile
{
h.profiles
.push(self.schema.profile(p).version_iri.to_owned());
}
st.source = Some(ds.push_header(h));
}
}
fn close_compound(&mut self, st: &mut State) {
let Some((attr, compound)) = st.compounds.pop() else {
return;
};
let value = Value::Compound(Box::new(compound));
let many = self.schema.attr(attr).mult.is_many();
match st.compounds.last_mut() {
Some((_, parent)) => {
if many {
parent.push(attr, value)
} else {
parent.set(attr, value)
}
}
None => {
if let Some(obj) = st.object.as_mut() {
if many {
obj.push_in(st.profile_mask, attr, value);
} else {
obj.set_in(st.profile_mask, attr, value);
}
}
}
}
}
fn commit(
&mut self,
mut object: Object,
st: &State,
dataset: &mut Option<&mut Dataset>,
pos: u64,
) {
object.mark_profile(st.profile_mask);
object.from_file = true;
object.shrink_for_load();
let Some(ds) = dataset.as_mut() else { return };
if let Some(existing) = ds.by_mrid(object.mrid()) {
let incoming = object.class();
let held = 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, pos);
}
}
if let Some(ds) = dataset.as_mut() {
let id = ds.insert(object);
if let Some(source) = st.source {
ds.record_source(source, id);
}
}
}
fn on_open(
&mut self,
e: &BytesStart<'_>,
self_closing: bool,
ctx: Ctx,
st: &mut State,
pos: u64,
) -> Result<Ctx> {
let qname = e.name();
let qname = qname.as_ref();
if !st.saw_root || declares_namespace(e) {
self.collect_namespaces(e)?;
}
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) => {
let obj = st.object.as_mut().expect("object present");
if self.schema.attr(attr).mult.is_many() {
obj.push_in(st.profile_mask, attr, value);
} else {
obj.set_in(st.profile_mask, attr, value);
}
Ok(Ctx::Skip)
}
Prop::Enter(attr, class) => {
st.compounds.push((attr, Compound::new(class)));
Ok(Ctx::Compound)
}
Prop::Text(attr) => {
st.pending = Some(PendingText {
target: TextTarget::Attr(attr),
text: String::new(),
});
Ok(Ctx::Text)
}
Prop::Skip => Ok(Ctx::Skip),
}
}
Ctx::Compound => {
let Some((_, top)) = st.compounds.last() else {
return Ok(Ctx::Skip);
};
let class = top.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) => {
let (_, top) = st.compounds.last_mut().expect("compound present");
if self.schema.attr(attr).mult.is_many() {
top.push(attr, value);
} else {
top.set(attr, value);
}
Ok(Ctx::Skip)
}
Prop::Enter(attr, class) => {
st.compounds.push((attr, Compound::new(class)));
Ok(Ctx::Compound)
}
Prop::Text(attr) => {
st.pending = Some(PendingText {
target: TextTarget::Compound(attr),
text: String::new(),
});
Ok(Ctx::Text)
}
Prop::Skip => Ok(Ctx::Skip),
}
}
Ctx::Header => self.open_in_header(e, qname, self_closing, st),
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(),
});
Ok(Ctx::Text)
}
Ctx::Text => {
let name = qname.to_owned();
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 = self.object_identity(e, def.name, pos)?;
let mut o = Object::new(class, mrid);
o.mark_profile(st.profile_mask);
st.object = Some(o);
Ok(Ctx::Object)
}
Resolved::Attr(_) | Resolved::Unknown => {
let name = qname.to_owned();
if self.options.strictness == Strictness::Strict {
return Err(Error::NotCimXml(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,
) -> 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(),
});
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 = qname.to_owned();
if self.options.strictness == Strictness::Strict {
return Err(Error::NotCimXml(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> {
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);
}
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))
}
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, pos: u64) {
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) {
let obj = st.object.as_mut().expect("object present");
if self.schema.attr(attr).mult.is_many() {
obj.push_in(st.profile_mask, attr, v);
} else {
obj.set_in(st.profile_mask, attr, v);
}
}
}
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)
&& let Some((_, top)) = st.compounds.last_mut()
{
if self.schema.attr(attr).mult.is_many() {
top.push(attr, v);
} else {
top.set(attr, v);
}
}
}
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
}
}
}
fn collect_namespaces(&mut self, e: &BytesStart<'_>) -> Result<()> {
for attr in e.attributes().with_checks(false) {
let attr = attr?;
let key = attr.key.as_ref();
let value = self.attr_value(&attr)?.into_owned();
if let Some(prefix) = key.strip_prefix("xmlns:") {
self.ns.insert(prefix.as_bytes().to_vec(), value);
} else if key == "xmlns" {
self.ns.insert(Vec::new(), value);
}
}
Ok(())
}
fn attr<'e>(
&self,
e: &'e BytesStart<'_>,
ns: &str,
local: &str,
) -> Result<Option<Cow<'e, str>>> {
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.ns.get(prefix.as_bytes()).map(String::as_str) != Some(ns) {
continue;
}
return Ok(Some(self.attr_value(&attr)?));
}
Ok(None)
}
}
fn parse_error(e: quick_xml::Error) -> Error {
match e {
quick_xml::Error::Io(io) => Error::Io(io::Error::new(io.kind(), io.to_string())),
other => Error::Xml(other.to_string()),
}
}
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)
}
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,
}
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,
},
}