use std::fmt;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Io(std::io::Error),
Xml(String),
NotCimXml(String),
DanglingReference {
object: String,
attribute: &'static str,
target: String,
total: usize,
},
SchemaMismatch {
left: &'static str,
right: &'static str,
},
UnknownVintage {
path: String,
known: Vec<&'static str>,
},
#[cfg(feature = "zip")]
Zip(String),
InputTooLarge {
limit: u64,
read: u64,
source: Option<String>,
},
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Io(e) => write!(f, "i/o error: {e}"),
Error::Xml(m) => write!(f, "malformed XML: {m}"),
Error::NotCimXml(m) => write!(f, "not a CIM/XML document: {m}"),
Error::DanglingReference {
object,
attribute,
target,
total,
} => write!(
f,
"unresolved reference {object}.{attribute} -> {target} \
({total} unresolved in total); load the missing profile or \
use LinkPolicy::Lenient"
),
Error::SchemaMismatch { left, right } => write!(
f,
"cannot combine a {left} model with a {right} one: class and attribute \
identifiers belong to one vintage's tables"
),
Error::UnknownVintage { path, known } => write!(
f,
"no CIM vintage recognised in {path}: not a CIM/XML input, or a vocabulary \
this build has no feature for (it has {known:?})"
),
#[cfg(feature = "zip")]
Error::Zip(m) => write!(f, "zip archive error: {m}"),
Error::InputTooLarge {
limit,
read,
source,
} => {
write!(
f,
"input exceeds the {} input budget after reading {}",
human_bytes(*limit),
human_bytes(*read)
)?;
if let Some(source) = source {
write!(f, " (while reading {source})")?;
}
write!(
f,
"; raise it with ReadOptions::with_max_input_bytes, or pass 0 for no limit"
)
}
}
}
}
pub(crate) fn human_bytes(n: u64) -> String {
const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
let mut unit = 0;
let mut value = n;
while unit + 1 < UNITS.len() && value >= 1024 && value.is_multiple_of(1024) {
value /= 1024;
unit += 1;
}
if unit > 0 || n < 1024 {
return format!("{value} {}", UNITS[unit]);
}
#[allow(clippy::cast_precision_loss)] let mut f = n as f64;
let mut unit = 0;
while unit + 1 < UNITS.len() && f >= 1024.0 {
f /= 1024.0;
unit += 1;
}
format!("{f:.1} {}", UNITS[unit])
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io(e) => Some(e),
_ => None,
}
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Error {
Error::Io(e)
}
}
impl From<quick_xml::Error> for Error {
fn from(e: quick_xml::Error) -> Error {
Error::Xml(e.to_string())
}
}
impl From<quick_xml::events::attributes::AttrError> for Error {
fn from(e: quick_xml::events::attributes::AttrError) -> Error {
Error::Xml(e.to_string())
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Severity {
Error,
Warning,
Info,
}
impl fmt::Display for Severity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Severity::Error => "error",
Severity::Warning => "warning",
Severity::Info => "info",
})
}
}
macro_rules! rules {
($($(#[$doc:meta])* $name:ident => $code:literal,)*) => {
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Rule {
$($(#[$doc])* $name,)*
}
impl Rule {
pub const fn code(self) -> &'static str {
match self {
$(Rule::$name => $code,)*
}
}
pub const ALL: &'static [Rule] = &[$(Rule::$name,)*];
}
};
}
rules! {
UnknownClass => "CIM0001",
UnknownAttribute => "CIM0002",
InvalidValue => "CIM0003",
NonConformingMrid => "CIM0004",
DuplicateMrid => "CIM0005",
DanglingReference => "CIM0006",
MissingRequired => "CIM0007",
CardinalityExceeded => "CIM0008",
WrongReferenceTarget => "CIM0009",
AttributeNotInProfile => "CIM0010",
AbstractInstantiated => "CIM0011",
Deprecated => "CIM0012",
MalformedHeader => "CIM0013",
UnsatisfiedDependency => "CIM0014",
Structure => "CIM0015",
DatatypeMismatch => "CIM0016",
FixedValueMismatch => "CIM0017",
ConflictingValue => "CIM0018",
IllegalXmlCharacter => "CIM0019",
UnreadableFile => "CIM0022",
WrongVintage => "CIM0021",
UnserializableIdentifier => "CIM0020",
}
impl fmt::Display for Rule {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.code())
}
}
#[derive(Clone, Debug)]
pub struct Diagnostic {
pub severity: Severity,
pub rule: Rule,
pub object: Option<crate::mrid::Mrid>,
pub class: Option<&'static str>,
pub attribute: Option<&'static str>,
pub source: Option<String>,
pub position: Option<u64>,
pub message: String,
}
pub fn line_and_column(source: &str, position: u64) -> (u64, u64) {
let upto = &source.as_bytes()[..(position as usize).min(source.len())];
let line = upto.iter().filter(|&&b| b == b'\n').count() as u64 + 1;
let col = match upto.iter().rposition(|&b| b == b'\n') {
Some(i) => (upto.len() - i) as u64,
None => upto.len() as u64 + 1,
};
(line, col)
}
impl Diagnostic {
pub fn new(severity: Severity, rule: Rule, message: impl Into<String>) -> Diagnostic {
Diagnostic {
severity,
rule,
object: None,
class: None,
attribute: None,
source: None,
position: None,
message: message.into(),
}
}
pub fn error(rule: Rule, message: impl Into<String>) -> Diagnostic {
Diagnostic::new(Severity::Error, rule, message)
}
pub fn warning(rule: Rule, message: impl Into<String>) -> Diagnostic {
Diagnostic::new(Severity::Warning, rule, message)
}
pub fn info(rule: Rule, message: impl Into<String>) -> Diagnostic {
Diagnostic::new(Severity::Info, rule, message)
}
pub fn with_object(mut self, mrid: impl Into<crate::mrid::Mrid>) -> Diagnostic {
self.object = Some(mrid.into());
self
}
pub fn with_class(mut self, class: &'static str) -> Diagnostic {
self.class = Some(class);
self
}
pub fn with_attribute(mut self, attr: &'static str) -> Diagnostic {
self.attribute = Some(attr);
self
}
pub fn with_source(mut self, source: impl Into<String>) -> Diagnostic {
self.source = Some(source.into());
self
}
pub fn with_position(mut self, position: u64) -> Diagnostic {
self.position = Some(position);
self
}
}
impl fmt::Display for Diagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}[{}]", self.severity, self.rule.code())?;
if let Some(src) = &self.source {
write!(f, " {src}")?;
if let Some(pos) = self.position {
write!(f, "@{pos}")?;
}
}
write!(f, ": {}", self.message)?;
if let Some(class) = self.class {
write!(f, " [{class}")?;
match &self.object {
Some(o) => write!(f, " {o}]")?,
None => write!(f, "]")?,
}
} else if let Some(o) = &self.object {
write!(f, " [{o}]")?;
}
Ok(())
}
}
#[derive(Clone, Debug, Default)]
pub struct Report {
pub diagnostics: Vec<Diagnostic>,
}
impl Report {
pub fn push(&mut self, d: Diagnostic) {
self.diagnostics.push(d);
}
pub fn extend(&mut self, other: Report) {
self.diagnostics.extend(other.diagnostics);
}
pub fn is_empty(&self) -> bool {
self.diagnostics.is_empty()
}
pub fn len(&self) -> usize {
self.diagnostics.len()
}
pub fn count(&self, severity: Severity) -> usize {
self.diagnostics
.iter()
.filter(|d| d.severity == severity)
.count()
}
pub fn has_errors(&self) -> bool {
self.diagnostics
.iter()
.any(|d| d.severity == Severity::Error)
}
pub fn iter(&self) -> std::slice::Iter<'_, Diagnostic> {
self.diagnostics.iter()
}
pub fn by_rule(&self, rule: Rule) -> impl Iterator<Item = &Diagnostic> {
self.diagnostics.iter().filter(move |d| d.rule == rule)
}
pub fn summary(&self) -> Vec<(Rule, usize)> {
let mut counts: Vec<(Rule, usize)> = Vec::new();
for d in &self.diagnostics {
match counts.iter_mut().find(|(r, _)| *r == d.rule) {
Some((_, n)) => *n += 1,
None => counts.push((d.rule, 1)),
}
}
counts.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
counts
}
}
impl IntoIterator for Report {
type Item = Diagnostic;
type IntoIter = std::vec::IntoIter<Diagnostic>;
fn into_iter(self) -> Self::IntoIter {
self.diagnostics.into_iter()
}
}
impl fmt::Display for Report {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for d in &self.diagnostics {
writeln!(f, "{d}")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn byte_counts_read_the_way_a_budget_was_written() {
assert_eq!(human_bytes(2 << 30), "2 GiB");
assert_eq!(human_bytes(512 << 10), "512 KiB");
assert_eq!(human_bytes(17), "17 B");
assert_eq!(human_bytes((1 << 20) + 1), "1.0 MiB");
assert_eq!(human_bytes(1536 << 20), "1536 MiB");
}
#[test]
fn rule_codes_are_unique() {
let mut codes: Vec<&str> = Rule::ALL.iter().map(|r| r.code()).collect();
codes.sort_unstable();
let n = codes.len();
codes.dedup();
assert_eq!(codes.len(), n, "duplicate rule codes");
let expected: Vec<String> = (1..=n).map(|i| format!("CIM{i:04}")).collect();
assert_eq!(
codes, expected,
"the rule codes are not contiguous from CIM0001"
);
}
#[test]
fn byte_offsets_convert_to_lines_and_columns() {
let src = "one\ntwo\nthree";
assert_eq!(line_and_column(src, 0), (1, 1));
assert_eq!(line_and_column(src, 4), (2, 1));
assert_eq!(line_and_column(src, 6), (2, 3));
assert_eq!(line_and_column(src, 9_999).0, 3);
}
#[test]
fn report_summarizes_by_rule() {
let mut r = Report::default();
r.push(Diagnostic::error(Rule::MissingRequired, "a"));
r.push(Diagnostic::error(Rule::MissingRequired, "b"));
r.push(Diagnostic::warning(Rule::Deprecated, "c"));
assert!(r.has_errors());
assert_eq!(r.count(Severity::Error), 2);
assert_eq!(
r.summary(),
vec![(Rule::MissingRequired, 2), (Rule::Deprecated, 1)]
);
}
#[test]
fn diagnostic_display_includes_location_and_code() {
let d = Diagnostic::error(Rule::MissingRequired, "missing name")
.with_class("ACLineSegment")
.with_object("abc")
.with_source("EQ.xml")
.with_position(1234);
let s = d.to_string();
assert!(s.contains("error[CIM0007]"), "{s}");
assert!(s.contains("EQ.xml@1234"), "{s}");
assert!(s.contains("[ACLineSegment abc]"), "{s}");
}
}