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",
356 DanglingReference => "CIM0006",
358 MissingRequired => "CIM0007",
360 CardinalityExceeded => "CIM0008",
363 WrongReferenceTarget => "CIM0009",
365 AttributeNotInProfile => "CIM0010",
367 AbstractInstantiated => "CIM0011",
369 Deprecated => "CIM0012",
371 MalformedHeader => "CIM0013",
373 UnsatisfiedDependency => "CIM0014",
376 Structure => "CIM0015",
378 DatatypeMismatch => "CIM0016",
383 FixedValueMismatch => "CIM0017",
385 ConflictingValue => "CIM0018",
393 IllegalXmlCharacter => "CIM0019",
399 UnreadableFile => "CIM0022",
404 WrongVintage => "CIM0021",
409 UnserializableIdentifier => "CIM0020",
415}
416
417impl fmt::Display for Rule {
418 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419 f.write_str(self.code())
420 }
421}
422
423#[derive(Clone, Debug)]
428pub struct Diagnostic {
429 pub severity: Severity,
430 pub rule: Rule,
431 pub object: Option<crate::mrid::Mrid>,
433 pub class: Option<&'static str>,
435 pub attribute: Option<&'static str>,
437 pub source: Option<String>,
439 pub position: Option<u64>,
444 pub related_position: Option<u64>,
447 pub message: String,
448}
449
450pub fn line_and_column(source: &str, position: u64) -> (u64, u64) {
455 let upto = &source.as_bytes()[..(position as usize).min(source.len())];
456 let line = upto.iter().filter(|&&b| b == b'\n').count() as u64 + 1;
457 let col = match upto.iter().rposition(|&b| b == b'\n') {
458 Some(i) => (upto.len() - i) as u64,
459 None => upto.len() as u64 + 1,
460 };
461 (line, col)
462}
463
464impl Diagnostic {
465 pub fn new(severity: Severity, rule: Rule, message: impl Into<String>) -> Diagnostic {
466 Diagnostic {
467 severity,
468 rule,
469 object: None,
470 class: None,
471 attribute: None,
472 source: None,
473 position: None,
474 related_position: None,
475 message: message.into(),
476 }
477 }
478
479 pub fn error(rule: Rule, message: impl Into<String>) -> Diagnostic {
480 Diagnostic::new(Severity::Error, rule, message)
481 }
482 pub fn warning(rule: Rule, message: impl Into<String>) -> Diagnostic {
483 Diagnostic::new(Severity::Warning, rule, message)
484 }
485 pub fn info(rule: Rule, message: impl Into<String>) -> Diagnostic {
486 Diagnostic::new(Severity::Info, rule, message)
487 }
488
489 pub fn with_object(mut self, mrid: impl Into<crate::mrid::Mrid>) -> Diagnostic {
490 self.object = Some(mrid.into());
491 self
492 }
493 pub fn with_class(mut self, class: &'static str) -> Diagnostic {
494 self.class = Some(class);
495 self
496 }
497 pub fn with_attribute(mut self, attr: &'static str) -> Diagnostic {
498 self.attribute = Some(attr);
499 self
500 }
501 pub fn with_source(mut self, source: impl Into<String>) -> Diagnostic {
502 self.source = Some(source.into());
503 self
504 }
505 pub fn with_position(mut self, position: u64) -> Diagnostic {
507 self.position = Some(position);
508 self
509 }
510 pub fn with_related_position(mut self, position: u64) -> Diagnostic {
512 self.related_position = Some(position);
513 self
514 }
515}
516
517impl fmt::Display for Diagnostic {
518 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
519 write!(f, "{}[{}]", self.severity, self.rule.code())?;
520 if let Some(src) = &self.source {
521 write!(f, " {src}")?;
522 }
523 if let Some(pos) = self.position {
524 let gap = if self.source.is_some() { "" } else { " " };
526 write!(f, "{gap}@{pos}")?;
527 }
528 write!(f, ": {}", self.message)?;
529 if let Some(class) = self.class {
530 write!(f, " [{class}")?;
531 match &self.object {
532 Some(o) => write!(f, " {o}]")?,
533 None => write!(f, "]")?,
534 }
535 } else if let Some(o) = &self.object {
536 write!(f, " [{o}]")?;
537 }
538 Ok(())
539 }
540}
541
542#[derive(Clone, Debug, Default)]
544pub struct Report {
545 pub diagnostics: Vec<Diagnostic>,
546}
547
548impl Report {
549 pub fn push(&mut self, d: Diagnostic) {
550 self.diagnostics.push(d);
551 }
552
553 pub fn extend(&mut self, other: Report) {
554 self.diagnostics.extend(other.diagnostics);
555 }
556
557 pub fn is_empty(&self) -> bool {
558 self.diagnostics.is_empty()
559 }
560
561 pub fn len(&self) -> usize {
562 self.diagnostics.len()
563 }
564
565 pub fn count(&self, severity: Severity) -> usize {
566 self.diagnostics
567 .iter()
568 .filter(|d| d.severity == severity)
569 .count()
570 }
571
572 pub fn has_errors(&self) -> bool {
574 self.diagnostics
575 .iter()
576 .any(|d| d.severity == Severity::Error)
577 }
578
579 pub fn iter(&self) -> std::slice::Iter<'_, Diagnostic> {
580 self.diagnostics.iter()
581 }
582
583 pub fn by_rule(&self, rule: Rule) -> impl Iterator<Item = &Diagnostic> {
584 self.diagnostics.iter().filter(move |d| d.rule == rule)
585 }
586
587 pub fn summary(&self) -> Vec<(Rule, usize)> {
589 let mut counts: Vec<(Rule, usize)> = Vec::new();
590 for d in &self.diagnostics {
591 match counts.iter_mut().find(|(r, _)| *r == d.rule) {
592 Some((_, n)) => *n += 1,
593 None => counts.push((d.rule, 1)),
594 }
595 }
596 counts.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
597 counts
598 }
599}
600
601impl IntoIterator for Report {
602 type Item = Diagnostic;
603 type IntoIter = std::vec::IntoIter<Diagnostic>;
604 fn into_iter(self) -> Self::IntoIter {
605 self.diagnostics.into_iter()
606 }
607}
608
609impl fmt::Display for Report {
610 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
611 for d in &self.diagnostics {
612 writeln!(f, "{d}")?;
613 }
614 Ok(())
615 }
616}
617
618#[cfg(test)]
619mod tests {
620 use super::*;
621
622 #[test]
623 fn byte_counts_read_the_way_a_budget_was_written() {
624 assert_eq!(human_bytes(2 << 30), "2 GiB");
625 assert_eq!(human_bytes(512 << 10), "512 KiB");
626 assert_eq!(human_bytes(17), "17 B");
627 assert_eq!(human_bytes((1 << 20) + 1), "1.0 MiB");
628 assert_eq!(human_bytes(1536 << 20), "1536 MiB");
629 }
630
631 #[test]
632 fn rule_codes_are_unique() {
633 let mut codes: Vec<&str> = Rule::ALL.iter().map(|r| r.code()).collect();
634 codes.sort_unstable();
635 let n = codes.len();
636 codes.dedup();
637 assert_eq!(codes.len(), n, "duplicate rule codes");
638
639 let expected: Vec<String> = (1..=n).map(|i| format!("CIM{i:04}")).collect();
643 assert_eq!(
644 codes, expected,
645 "the rule codes are not contiguous from CIM0001"
646 );
647 }
648
649 #[test]
650 fn byte_offsets_convert_to_lines_and_columns() {
651 let src = "one\ntwo\nthree";
652 assert_eq!(line_and_column(src, 0), (1, 1));
653 assert_eq!(line_and_column(src, 4), (2, 1));
654 assert_eq!(line_and_column(src, 6), (2, 3));
655 assert_eq!(line_and_column(src, 9_999).0, 3);
657 }
658
659 #[test]
660 fn report_summarizes_by_rule() {
661 let mut r = Report::default();
662 r.push(Diagnostic::error(Rule::MissingRequired, "a"));
663 r.push(Diagnostic::error(Rule::MissingRequired, "b"));
664 r.push(Diagnostic::warning(Rule::Deprecated, "c"));
665 assert!(r.has_errors());
666 assert_eq!(r.count(Severity::Error), 2);
667 assert_eq!(
668 r.summary(),
669 vec![(Rule::MissingRequired, 2), (Rule::Deprecated, 1)]
670 );
671 }
672
673 #[test]
674 fn diagnostic_display_includes_location_and_code() {
675 let d = Diagnostic::error(Rule::MissingRequired, "missing name")
676 .with_class("ACLineSegment")
677 .with_object("abc")
678 .with_source("EQ.xml")
679 .with_position(1234);
680 let s = d.to_string();
681 assert!(s.contains("error[CIM0007]"), "{s}");
682 assert!(s.contains("EQ.xml@1234"), "{s}");
683 assert!(s.contains("[ACLineSegment abc]"), "{s}");
684
685 let d = Diagnostic::warning(Rule::Structure, "x").with_position(7);
687 assert_eq!(d.to_string(), "warning[CIM0015] @7: x");
688 }
689
690 #[test]
691 fn document_errors_say_where() {
692 let e = Error::xml("expected `</rdf:RDF>`").locate(Some("EQ.xml"), 120);
693 assert_eq!(e.position(), Some(120));
694 assert_eq!(
695 e.to_string(),
696 "malformed XML in EQ.xml at byte 120: expected `</rdf:RDF>`"
697 );
698 let e = Error::xml("x").locate(None, 5).locate(Some("a"), 9);
700 assert_eq!(e.position(), Some(5));
701 let t = Error::Truncated {
702 open: Some("cim:Terminal".into()),
703 source: None,
704 position: 40,
705 };
706 assert_eq!(t.position(), Some(40));
707 assert!(
708 t.to_string()
709 .contains("inside <cim:Terminal>, unfinished from byte 40")
710 );
711 }
712}