1use std::fmt;
4
5pub type Result<T> = std::result::Result<T, Error>;
6
7#[derive(Debug)]
14#[non_exhaustive]
15pub enum Error {
16 Io(std::io::Error),
17 Xml(String),
19 NotCimXml(String),
21 DanglingReference {
23 object: String,
24 attribute: &'static str,
25 target: String,
26 total: usize,
28 },
29 SchemaMismatch {
34 left: &'static str,
35 right: &'static str,
36 },
37 UnknownVintage {
41 path: String,
42 known: Vec<&'static str>,
44 },
45 #[cfg(feature = "zip")]
47 Zip(String),
48 InputTooLarge {
54 limit: u64,
56 read: u64,
58 source: Option<String>,
60 },
61}
62
63impl fmt::Display for Error {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 match self {
66 Error::Io(e) => write!(f, "i/o error: {e}"),
67 Error::Xml(m) => write!(f, "malformed XML: {m}"),
68 Error::NotCimXml(m) => write!(f, "not a CIM/XML document: {m}"),
69 Error::DanglingReference {
70 object,
71 attribute,
72 target,
73 total,
74 } => write!(
75 f,
76 "unresolved reference {object}.{attribute} -> {target} \
77 ({total} unresolved in total); load the missing profile or \
78 use LinkPolicy::Lenient"
79 ),
80 Error::SchemaMismatch { left, right } => write!(
81 f,
82 "cannot combine a {left} model with a {right} one: class and attribute \
83 identifiers belong to one vintage's tables"
84 ),
85 Error::UnknownVintage { path, known } => write!(
86 f,
87 "no CIM vintage recognised in {path}: not a CIM/XML input, or a vocabulary \
88 this build has no feature for (it has {known:?})"
89 ),
90 #[cfg(feature = "zip")]
91 Error::Zip(m) => write!(f, "zip archive error: {m}"),
92 Error::InputTooLarge {
93 limit,
94 read,
95 source,
96 } => {
97 write!(
98 f,
99 "input exceeds the {} input budget after reading {}",
100 human_bytes(*limit),
101 human_bytes(*read)
102 )?;
103 if let Some(source) = source {
104 write!(f, " (while reading {source})")?;
105 }
106 write!(
107 f,
108 "; raise it with ReadOptions::with_max_input_bytes, or pass 0 for no limit"
109 )
110 }
111 }
112 }
113}
114
115pub(crate) fn human_bytes(n: u64) -> String {
119 const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
120 let mut unit = 0;
121 let mut value = n;
122 while unit + 1 < UNITS.len() && value >= 1024 && value.is_multiple_of(1024) {
123 value /= 1024;
124 unit += 1;
125 }
126 if unit > 0 || n < 1024 {
127 return format!("{value} {}", UNITS[unit]);
128 }
129 #[allow(clippy::cast_precision_loss)] let mut f = n as f64;
131 let mut unit = 0;
132 while unit + 1 < UNITS.len() && f >= 1024.0 {
133 f /= 1024.0;
134 unit += 1;
135 }
136 format!("{f:.1} {}", UNITS[unit])
137}
138
139impl std::error::Error for Error {
140 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
141 match self {
142 Error::Io(e) => Some(e),
143 _ => None,
144 }
145 }
146}
147
148impl From<std::io::Error> for Error {
149 fn from(e: std::io::Error) -> Error {
150 Error::Io(e)
151 }
152}
153
154impl From<quick_xml::Error> for Error {
155 fn from(e: quick_xml::Error) -> Error {
156 Error::Xml(e.to_string())
157 }
158}
159
160impl From<quick_xml::events::attributes::AttrError> for Error {
161 fn from(e: quick_xml::events::attributes::AttrError) -> Error {
162 Error::Xml(e.to_string())
163 }
164}
165
166#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
168pub enum Severity {
169 Error,
171 Warning,
173 Info,
175}
176
177impl fmt::Display for Severity {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 f.write_str(match self {
180 Severity::Error => "error",
181 Severity::Warning => "warning",
182 Severity::Info => "info",
183 })
184 }
185}
186
187macro_rules! rules {
194 ($($(#[$doc:meta])* $name:ident => $code:literal,)*) => {
195 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
196 pub enum Rule {
197 $($(#[$doc])* $name,)*
198 }
199
200 impl Rule {
201 pub const fn code(self) -> &'static str {
203 match self {
204 $(Rule::$name => $code,)*
205 }
206 }
207
208 pub const ALL: &'static [Rule] = &[$(Rule::$name,)*];
210 }
211 };
212}
213
214rules! {
215 UnknownClass => "CIM0001",
217 UnknownAttribute => "CIM0002",
219 InvalidValue => "CIM0003",
221 NonConformingMrid => "CIM0004",
223 DuplicateMrid => "CIM0005",
225 DanglingReference => "CIM0006",
227 MissingRequired => "CIM0007",
229 CardinalityExceeded => "CIM0008",
231 WrongReferenceTarget => "CIM0009",
233 AttributeNotInProfile => "CIM0010",
235 AbstractInstantiated => "CIM0011",
237 Deprecated => "CIM0012",
239 MalformedHeader => "CIM0013",
241 UnsatisfiedDependency => "CIM0014",
244 Structure => "CIM0015",
246 DatatypeMismatch => "CIM0016",
251 FixedValueMismatch => "CIM0017",
253 ConflictingValue => "CIM0018",
259 IllegalXmlCharacter => "CIM0019",
265 UnreadableFile => "CIM0022",
270 WrongVintage => "CIM0021",
275 UnserializableIdentifier => "CIM0020",
281}
282
283impl fmt::Display for Rule {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285 f.write_str(self.code())
286 }
287}
288
289#[derive(Clone, Debug)]
294pub struct Diagnostic {
295 pub severity: Severity,
296 pub rule: Rule,
297 pub object: Option<crate::mrid::Mrid>,
299 pub class: Option<&'static str>,
301 pub attribute: Option<&'static str>,
303 pub source: Option<String>,
305 pub position: Option<u64>,
309 pub message: String,
310}
311
312pub fn line_and_column(source: &str, position: u64) -> (u64, u64) {
317 let upto = &source.as_bytes()[..(position as usize).min(source.len())];
318 let line = upto.iter().filter(|&&b| b == b'\n').count() as u64 + 1;
319 let col = match upto.iter().rposition(|&b| b == b'\n') {
320 Some(i) => (upto.len() - i) as u64,
321 None => upto.len() as u64 + 1,
322 };
323 (line, col)
324}
325
326impl Diagnostic {
327 pub fn new(severity: Severity, rule: Rule, message: impl Into<String>) -> Diagnostic {
328 Diagnostic {
329 severity,
330 rule,
331 object: None,
332 class: None,
333 attribute: None,
334 source: None,
335 position: None,
336 message: message.into(),
337 }
338 }
339
340 pub fn error(rule: Rule, message: impl Into<String>) -> Diagnostic {
341 Diagnostic::new(Severity::Error, rule, message)
342 }
343 pub fn warning(rule: Rule, message: impl Into<String>) -> Diagnostic {
344 Diagnostic::new(Severity::Warning, rule, message)
345 }
346 pub fn info(rule: Rule, message: impl Into<String>) -> Diagnostic {
347 Diagnostic::new(Severity::Info, rule, message)
348 }
349
350 pub fn with_object(mut self, mrid: impl Into<crate::mrid::Mrid>) -> Diagnostic {
351 self.object = Some(mrid.into());
352 self
353 }
354 pub fn with_class(mut self, class: &'static str) -> Diagnostic {
355 self.class = Some(class);
356 self
357 }
358 pub fn with_attribute(mut self, attr: &'static str) -> Diagnostic {
359 self.attribute = Some(attr);
360 self
361 }
362 pub fn with_source(mut self, source: impl Into<String>) -> Diagnostic {
363 self.source = Some(source.into());
364 self
365 }
366 pub fn with_position(mut self, position: u64) -> Diagnostic {
368 self.position = Some(position);
369 self
370 }
371}
372
373impl fmt::Display for Diagnostic {
374 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375 write!(f, "{}[{}]", self.severity, self.rule.code())?;
376 if let Some(src) = &self.source {
377 write!(f, " {src}")?;
378 if let Some(pos) = self.position {
379 write!(f, "@{pos}")?;
381 }
382 }
383 write!(f, ": {}", self.message)?;
384 if let Some(class) = self.class {
385 write!(f, " [{class}")?;
386 match &self.object {
387 Some(o) => write!(f, " {o}]")?,
388 None => write!(f, "]")?,
389 }
390 } else if let Some(o) = &self.object {
391 write!(f, " [{o}]")?;
392 }
393 Ok(())
394 }
395}
396
397#[derive(Clone, Debug, Default)]
399pub struct Report {
400 pub diagnostics: Vec<Diagnostic>,
401}
402
403impl Report {
404 pub fn push(&mut self, d: Diagnostic) {
405 self.diagnostics.push(d);
406 }
407
408 pub fn extend(&mut self, other: Report) {
409 self.diagnostics.extend(other.diagnostics);
410 }
411
412 pub fn is_empty(&self) -> bool {
413 self.diagnostics.is_empty()
414 }
415
416 pub fn len(&self) -> usize {
417 self.diagnostics.len()
418 }
419
420 pub fn count(&self, severity: Severity) -> usize {
421 self.diagnostics
422 .iter()
423 .filter(|d| d.severity == severity)
424 .count()
425 }
426
427 pub fn has_errors(&self) -> bool {
429 self.diagnostics
430 .iter()
431 .any(|d| d.severity == Severity::Error)
432 }
433
434 pub fn iter(&self) -> std::slice::Iter<'_, Diagnostic> {
435 self.diagnostics.iter()
436 }
437
438 pub fn by_rule(&self, rule: Rule) -> impl Iterator<Item = &Diagnostic> {
439 self.diagnostics.iter().filter(move |d| d.rule == rule)
440 }
441
442 pub fn summary(&self) -> Vec<(Rule, usize)> {
444 let mut counts: Vec<(Rule, usize)> = Vec::new();
445 for d in &self.diagnostics {
446 match counts.iter_mut().find(|(r, _)| *r == d.rule) {
447 Some((_, n)) => *n += 1,
448 None => counts.push((d.rule, 1)),
449 }
450 }
451 counts.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
452 counts
453 }
454}
455
456impl IntoIterator for Report {
457 type Item = Diagnostic;
458 type IntoIter = std::vec::IntoIter<Diagnostic>;
459 fn into_iter(self) -> Self::IntoIter {
460 self.diagnostics.into_iter()
461 }
462}
463
464impl fmt::Display for Report {
465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466 for d in &self.diagnostics {
467 writeln!(f, "{d}")?;
468 }
469 Ok(())
470 }
471}
472
473#[cfg(test)]
474mod tests {
475 use super::*;
476
477 #[test]
478 fn byte_counts_read_the_way_a_budget_was_written() {
479 assert_eq!(human_bytes(2 << 30), "2 GiB");
480 assert_eq!(human_bytes(512 << 10), "512 KiB");
481 assert_eq!(human_bytes(17), "17 B");
482 assert_eq!(human_bytes((1 << 20) + 1), "1.0 MiB");
483 assert_eq!(human_bytes(1536 << 20), "1536 MiB");
484 }
485
486 #[test]
487 fn rule_codes_are_unique() {
488 let mut codes: Vec<&str> = Rule::ALL.iter().map(|r| r.code()).collect();
489 codes.sort_unstable();
490 let n = codes.len();
491 codes.dedup();
492 assert_eq!(codes.len(), n, "duplicate rule codes");
493
494 let expected: Vec<String> = (1..=n).map(|i| format!("CIM{i:04}")).collect();
498 assert_eq!(
499 codes, expected,
500 "the rule codes are not contiguous from CIM0001"
501 );
502 }
503
504 #[test]
505 fn byte_offsets_convert_to_lines_and_columns() {
506 let src = "one\ntwo\nthree";
507 assert_eq!(line_and_column(src, 0), (1, 1));
508 assert_eq!(line_and_column(src, 4), (2, 1));
509 assert_eq!(line_and_column(src, 6), (2, 3));
510 assert_eq!(line_and_column(src, 9_999).0, 3);
512 }
513
514 #[test]
515 fn report_summarizes_by_rule() {
516 let mut r = Report::default();
517 r.push(Diagnostic::error(Rule::MissingRequired, "a"));
518 r.push(Diagnostic::error(Rule::MissingRequired, "b"));
519 r.push(Diagnostic::warning(Rule::Deprecated, "c"));
520 assert!(r.has_errors());
521 assert_eq!(r.count(Severity::Error), 2);
522 assert_eq!(
523 r.summary(),
524 vec![(Rule::MissingRequired, 2), (Rule::Deprecated, 1)]
525 );
526 }
527
528 #[test]
529 fn diagnostic_display_includes_location_and_code() {
530 let d = Diagnostic::error(Rule::MissingRequired, "missing name")
531 .with_class("ACLineSegment")
532 .with_object("abc")
533 .with_source("EQ.xml")
534 .with_position(1234);
535 let s = d.to_string();
536 assert!(s.contains("error[CIM0007]"), "{s}");
537 assert!(s.contains("EQ.xml@1234"), "{s}");
538 assert!(s.contains("[ACLineSegment abc]"), "{s}");
539 }
540}