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 {
20 message: String,
21 source: Option<String>,
23 position: Option<u64>,
25 },
26 Truncated {
31 open: Option<String>,
33 source: Option<String>,
34 position: u64,
37 },
38 NotCimXml {
42 message: String,
43 source: Option<String>,
44 position: Option<u64>,
45 },
46 DanglingReference {
48 object: String,
49 attribute: &'static str,
50 target: String,
51 total: usize,
53 },
54 SchemaMismatch {
59 left: &'static str,
60 right: &'static str,
61 },
62 UnknownVintage {
66 path: String,
67 known: Vec<&'static str>,
69 },
70 #[cfg(feature = "zip")]
72 Zip(String),
73 InputTooLarge {
79 limit: u64,
81 read: u64,
83 source: Option<String>,
85 },
86}
87
88impl Error {
89 pub fn position(&self) -> Option<u64> {
91 match self {
92 Error::Xml { position, .. } | Error::NotCimXml { position, .. } => *position,
93 Error::Truncated { position, .. } => Some(*position),
94 _ => None,
95 }
96 }
97
98 pub(crate) fn xml(message: impl Into<String>) -> Error {
99 Error::Xml {
100 message: message.into(),
101 source: None,
102 position: None,
103 }
104 }
105
106 pub(crate) fn not_cim(message: impl Into<String>) -> Error {
107 Error::NotCimXml {
108 message: message.into(),
109 source: None,
110 position: None,
111 }
112 }
113
114 pub(crate) fn locate(mut self, at_source: Option<&str>, at: u64) -> Error {
116 if let Error::Xml {
117 source, position, ..
118 }
119 | Error::NotCimXml {
120 source, position, ..
121 } = &mut self
122 {
123 position.get_or_insert(at);
124 if source.is_none() {
125 *source = at_source.map(str::to_owned);
126 }
127 }
128 if let Error::Truncated { source, .. } = &mut self
129 && source.is_none()
130 {
131 *source = at_source.map(str::to_owned);
132 }
133 self
134 }
135
136 pub(crate) fn detail(&self) -> String {
139 match self {
140 Error::Xml { message, .. } => format!("malformed XML: {message}"),
141 Error::NotCimXml { message, .. } => format!("not a CIM/XML document: {message}"),
142 Error::Truncated { open, .. } => match open {
143 Some(open) => format!("truncated: the input ends inside <{open}>"),
144 None => "truncated: the input ends inside markup".to_owned(),
145 },
146 other => other.to_string(),
147 }
148 }
149}
150
151fn write_location(
153 f: &mut fmt::Formatter<'_>,
154 source: Option<&str>,
155 position: Option<u64>,
156) -> fmt::Result {
157 if let Some(s) = source {
158 write!(f, " in {s}")?;
159 }
160 if let Some(p) = position {
161 write!(f, " at byte {p}")?;
162 }
163 Ok(())
164}
165
166impl fmt::Display for Error {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 match self {
169 Error::Io(e) => write!(f, "i/o error: {e}"),
170 Error::Xml {
171 message,
172 source,
173 position,
174 } => {
175 f.write_str("malformed XML")?;
176 write_location(f, source.as_deref(), *position)?;
177 write!(f, ": {message}")
178 }
179 Error::NotCimXml {
180 message,
181 source,
182 position,
183 } => {
184 f.write_str("not a CIM/XML document")?;
185 write_location(f, source.as_deref(), *position)?;
186 write!(f, ": {message}")
187 }
188 Error::Truncated {
189 open,
190 source,
191 position,
192 } => {
193 f.write_str("truncated document")?;
194 if let Some(s) = source {
195 write!(f, " {s}")?;
196 }
197 match open {
198 Some(open) => write!(
199 f,
200 ": the input ends inside <{open}>, unfinished from byte {position}"
201 )?,
202 None => write!(f, ": the input ends inside markup at byte {position}")?,
203 }
204 f.write_str("; was the transfer interrupted?")
205 }
206 Error::DanglingReference {
207 object,
208 attribute,
209 target,
210 total,
211 } => write!(
212 f,
213 "unresolved reference {object}.{attribute} -> {target} \
214 ({total} unresolved in total); load the missing profile or \
215 use LinkPolicy::Lenient"
216 ),
217 Error::SchemaMismatch { left, right } => write!(
218 f,
219 "cannot combine a {left} model with a {right} one: class and attribute \
220 identifiers belong to one vintage's tables"
221 ),
222 Error::UnknownVintage { path, known } => write!(
223 f,
224 "no CIM vintage recognised in {path}: not a CIM/XML input, or a vocabulary \
225 this build has no feature for (it has {known:?})"
226 ),
227 #[cfg(feature = "zip")]
228 Error::Zip(m) => write!(f, "zip archive error: {m}"),
229 Error::InputTooLarge {
230 limit,
231 read,
232 source,
233 } => {
234 write!(
235 f,
236 "input exceeds the {} input budget after reading {}",
237 human_bytes(*limit),
238 human_bytes(*read)
239 )?;
240 if let Some(source) = source {
241 write!(f, " (while reading {source})")?;
242 }
243 write!(
244 f,
245 "; raise it with ReadOptions::with_max_input_bytes, or pass 0 for no limit"
246 )
247 }
248 }
249 }
250}
251
252pub(crate) fn human_bytes(n: u64) -> String {
256 const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
257 let mut unit = 0;
258 let mut value = n;
259 while unit + 1 < UNITS.len() && value >= 1024 && value.is_multiple_of(1024) {
260 value /= 1024;
261 unit += 1;
262 }
263 if unit > 0 || n < 1024 {
264 return format!("{value} {}", UNITS[unit]);
265 }
266 #[allow(clippy::cast_precision_loss)] let mut f = n as f64;
268 let mut unit = 0;
269 while unit + 1 < UNITS.len() && f >= 1024.0 {
270 f /= 1024.0;
271 unit += 1;
272 }
273 format!("{f:.1} {}", UNITS[unit])
274}
275
276impl std::error::Error for Error {
277 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
278 match self {
279 Error::Io(e) => Some(e),
280 _ => None,
281 }
282 }
283}
284
285impl From<std::io::Error> for Error {
286 fn from(e: std::io::Error) -> Error {
287 Error::Io(e)
288 }
289}
290
291impl From<quick_xml::events::attributes::AttrError> for Error {
292 fn from(e: quick_xml::events::attributes::AttrError) -> Error {
293 Error::xml(e.to_string())
294 }
295}
296
297#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
299pub enum Severity {
300 Error,
302 Warning,
304 Info,
306}
307
308impl fmt::Display for Severity {
309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310 f.write_str(match self {
311 Severity::Error => "error",
312 Severity::Warning => "warning",
313 Severity::Info => "info",
314 })
315 }
316}
317
318macro_rules! rules {
325 ($($(#[$doc:meta])* $name:ident => $code:literal,)*) => {
326 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
327 pub enum Rule {
328 $($(#[$doc])* $name,)*
329 }
330
331 impl Rule {
332 pub const fn code(self) -> &'static str {
334 match self {
335 $(Rule::$name => $code,)*
336 }
337 }
338
339 pub const ALL: &'static [Rule] = &[$(Rule::$name,)*];
341 }
342 };
343}
344
345rules! {
346 UnknownClass => "CIM0001",
348 UnknownAttribute => "CIM0002",
350 InvalidValue => "CIM0003",
352 NonConformingMrid => "CIM0004",
354 DuplicateMrid => "CIM0005",
359 DanglingReference => "CIM0006",
361 MissingRequired => "CIM0007",
363 CardinalityExceeded => "CIM0008",
366 WrongReferenceTarget => "CIM0009",
368 AttributeNotInProfile => "CIM0010",
370 AbstractInstantiated => "CIM0011",
372 Deprecated => "CIM0012",
374 MalformedHeader => "CIM0013",
376 UnsatisfiedDependency => "CIM0014",
379 Structure => "CIM0015",
381 DatatypeMismatch => "CIM0016",
386 FixedValueMismatch => "CIM0017",
388 ConflictingValue => "CIM0018",
397 IllegalXmlCharacter => "CIM0019",
403 UnreadableFile => "CIM0022",
408 WrongVintage => "CIM0021",
413 UnserializableIdentifier => "CIM0020",
419}
420
421impl fmt::Display for Rule {
422 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423 f.write_str(self.code())
424 }
425}
426
427#[derive(Clone, Debug)]
432pub struct Diagnostic {
433 pub severity: Severity,
434 pub rule: Rule,
435 pub object: Option<crate::mrid::Mrid>,
437 pub class: Option<&'static str>,
439 pub attribute: Option<&'static str>,
441 pub source: Option<String>,
443 pub position: Option<u64>,
448 pub related_position: Option<u64>,
451 pub message: String,
452}
453
454pub fn line_and_column(source: &str, position: u64) -> (u64, u64) {
459 let upto = &source.as_bytes()[..(position as usize).min(source.len())];
460 let line = upto.iter().filter(|&&b| b == b'\n').count() as u64 + 1;
461 let col = match upto.iter().rposition(|&b| b == b'\n') {
462 Some(i) => (upto.len() - i) as u64,
463 None => upto.len() as u64 + 1,
464 };
465 (line, col)
466}
467
468impl Diagnostic {
469 pub fn new(severity: Severity, rule: Rule, message: impl Into<String>) -> Diagnostic {
470 Diagnostic {
471 severity,
472 rule,
473 object: None,
474 class: None,
475 attribute: None,
476 source: None,
477 position: None,
478 related_position: None,
479 message: message.into(),
480 }
481 }
482
483 pub fn error(rule: Rule, message: impl Into<String>) -> Diagnostic {
484 Diagnostic::new(Severity::Error, rule, message)
485 }
486 pub fn warning(rule: Rule, message: impl Into<String>) -> Diagnostic {
487 Diagnostic::new(Severity::Warning, rule, message)
488 }
489 pub fn info(rule: Rule, message: impl Into<String>) -> Diagnostic {
490 Diagnostic::new(Severity::Info, rule, message)
491 }
492
493 pub fn with_object(mut self, mrid: impl Into<crate::mrid::Mrid>) -> Diagnostic {
494 self.object = Some(mrid.into());
495 self
496 }
497 pub fn with_class(mut self, class: &'static str) -> Diagnostic {
498 self.class = Some(class);
499 self
500 }
501 pub fn with_attribute(mut self, attr: &'static str) -> Diagnostic {
502 self.attribute = Some(attr);
503 self
504 }
505 pub fn with_source(mut self, source: impl Into<String>) -> Diagnostic {
506 self.source = Some(source.into());
507 self
508 }
509 pub fn with_position(mut self, position: u64) -> Diagnostic {
511 self.position = Some(position);
512 self
513 }
514 pub fn with_related_position(mut self, position: u64) -> Diagnostic {
516 self.related_position = Some(position);
517 self
518 }
519}
520
521impl fmt::Display for Diagnostic {
522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523 write!(f, "{}[{}]", self.severity, self.rule.code())?;
524 if let Some(src) = &self.source {
525 write!(f, " {src}")?;
526 }
527 if let Some(pos) = self.position {
528 let gap = if self.source.is_some() { "" } else { " " };
530 write!(f, "{gap}@{pos}")?;
531 }
532 write!(f, ": {}", self.message)?;
533 if let Some(class) = self.class {
534 write!(f, " [{class}")?;
535 match &self.object {
536 Some(o) => write!(f, " {o}]")?,
537 None => write!(f, "]")?,
538 }
539 } else if let Some(o) = &self.object {
540 write!(f, " [{o}]")?;
541 }
542 Ok(())
543 }
544}
545
546#[derive(Clone, Debug, Default)]
548pub struct Report {
549 pub diagnostics: Vec<Diagnostic>,
550}
551
552impl Report {
553 pub fn push(&mut self, d: Diagnostic) {
554 self.diagnostics.push(d);
555 }
556
557 pub fn extend(&mut self, other: Report) {
558 self.diagnostics.extend(other.diagnostics);
559 }
560
561 pub fn is_empty(&self) -> bool {
562 self.diagnostics.is_empty()
563 }
564
565 pub fn len(&self) -> usize {
566 self.diagnostics.len()
567 }
568
569 pub fn count(&self, severity: Severity) -> usize {
570 self.diagnostics
571 .iter()
572 .filter(|d| d.severity == severity)
573 .count()
574 }
575
576 pub fn has_errors(&self) -> bool {
578 self.diagnostics
579 .iter()
580 .any(|d| d.severity == Severity::Error)
581 }
582
583 pub fn iter(&self) -> std::slice::Iter<'_, Diagnostic> {
584 self.diagnostics.iter()
585 }
586
587 pub fn by_rule(&self, rule: Rule) -> impl Iterator<Item = &Diagnostic> {
588 self.diagnostics.iter().filter(move |d| d.rule == rule)
589 }
590
591 pub fn summary(&self) -> Vec<(Rule, usize)> {
593 let mut counts: Vec<(Rule, usize)> = Vec::new();
594 for d in &self.diagnostics {
595 match counts.iter_mut().find(|(r, _)| *r == d.rule) {
596 Some((_, n)) => *n += 1,
597 None => counts.push((d.rule, 1)),
598 }
599 }
600 counts.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
601 counts
602 }
603}
604
605impl IntoIterator for Report {
606 type Item = Diagnostic;
607 type IntoIter = std::vec::IntoIter<Diagnostic>;
608 fn into_iter(self) -> Self::IntoIter {
609 self.diagnostics.into_iter()
610 }
611}
612
613impl fmt::Display for Report {
614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
615 for d in &self.diagnostics {
616 writeln!(f, "{d}")?;
617 }
618 Ok(())
619 }
620}
621
622#[cfg(test)]
623mod tests {
624 use super::*;
625
626 #[test]
627 fn byte_counts_read_the_way_a_budget_was_written() {
628 assert_eq!(human_bytes(2 << 30), "2 GiB");
629 assert_eq!(human_bytes(512 << 10), "512 KiB");
630 assert_eq!(human_bytes(17), "17 B");
631 assert_eq!(human_bytes((1 << 20) + 1), "1.0 MiB");
632 assert_eq!(human_bytes(1536 << 20), "1536 MiB");
633 }
634
635 #[test]
636 fn rule_codes_are_unique() {
637 let mut codes: Vec<&str> = Rule::ALL.iter().map(|r| r.code()).collect();
638 codes.sort_unstable();
639 let n = codes.len();
640 codes.dedup();
641 assert_eq!(codes.len(), n, "duplicate rule codes");
642
643 let expected: Vec<String> = (1..=n).map(|i| format!("CIM{i:04}")).collect();
647 assert_eq!(
648 codes, expected,
649 "the rule codes are not contiguous from CIM0001"
650 );
651 }
652
653 #[test]
654 fn byte_offsets_convert_to_lines_and_columns() {
655 let src = "one\ntwo\nthree";
656 assert_eq!(line_and_column(src, 0), (1, 1));
657 assert_eq!(line_and_column(src, 4), (2, 1));
658 assert_eq!(line_and_column(src, 6), (2, 3));
659 assert_eq!(line_and_column(src, 9_999).0, 3);
661 }
662
663 #[test]
664 fn report_summarizes_by_rule() {
665 let mut r = Report::default();
666 r.push(Diagnostic::error(Rule::MissingRequired, "a"));
667 r.push(Diagnostic::error(Rule::MissingRequired, "b"));
668 r.push(Diagnostic::warning(Rule::Deprecated, "c"));
669 assert!(r.has_errors());
670 assert_eq!(r.count(Severity::Error), 2);
671 assert_eq!(
672 r.summary(),
673 vec![(Rule::MissingRequired, 2), (Rule::Deprecated, 1)]
674 );
675 }
676
677 #[test]
678 fn diagnostic_display_includes_location_and_code() {
679 let d = Diagnostic::error(Rule::MissingRequired, "missing name")
680 .with_class("ACLineSegment")
681 .with_object("abc")
682 .with_source("EQ.xml")
683 .with_position(1234);
684 let s = d.to_string();
685 assert!(s.contains("error[CIM0007]"), "{s}");
686 assert!(s.contains("EQ.xml@1234"), "{s}");
687 assert!(s.contains("[ACLineSegment abc]"), "{s}");
688
689 let d = Diagnostic::warning(Rule::Structure, "x").with_position(7);
691 assert_eq!(d.to_string(), "warning[CIM0015] @7: x");
692 }
693
694 #[test]
695 fn document_errors_say_where() {
696 let e = Error::xml("expected `</rdf:RDF>`").locate(Some("EQ.xml"), 120);
697 assert_eq!(e.position(), Some(120));
698 assert_eq!(
699 e.to_string(),
700 "malformed XML in EQ.xml at byte 120: expected `</rdf:RDF>`"
701 );
702 let e = Error::xml("x").locate(None, 5).locate(Some("a"), 9);
704 assert_eq!(e.position(), Some(5));
705 let t = Error::Truncated {
706 open: Some("cim:Terminal".into()),
707 source: None,
708 position: 40,
709 };
710 assert_eq!(t.position(), Some(40));
711 assert!(
712 t.to_string()
713 .contains("inside <cim:Terminal>, unfinished from byte 40")
714 );
715 }
716}