Skip to main content

cim_kit/
error.rs

1//! Errors and structured diagnostics.
2
3use std::fmt;
4
5pub type Result<T> = std::result::Result<T, Error>;
6
7/// A hard failure: the operation could not be completed.
8///
9/// Problems that leave the data usable (an unknown class, an unresolved reference in
10/// lenient mode) are [`Diagnostic`]s instead.
11///
12/// `#[non_exhaustive]`: match with a wildcard arm.
13#[derive(Debug)]
14#[non_exhaustive]
15pub enum Error {
16    Io(std::io::Error),
17    /// The document is not well-formed XML: an end tag that does not match, a second
18    /// document element, text outside it, a broken attribute.
19    Xml {
20        message: String,
21        /// The document being read: a file name or an archive entry.
22        source: Option<String>,
23        /// Byte offset of the offending markup.
24        position: Option<u64>,
25    },
26    /// The input ended before the document did — typically an interrupted transfer.
27    ///
28    /// Distinct from [`Error::Xml`] so a pipeline can fetch the file again rather than
29    /// reject its producer.
30    Truncated {
31        /// The innermost element still open, as written (`cim:ACLineSegment`).
32        open: Option<String>,
33        source: Option<String>,
34        /// Byte offset where the unfinished construct starts: the open element's `<`, or
35        /// the `<` or `&` of markup the input cut through.
36        position: u64,
37    },
38    /// The document is well-formed XML but not a CIM/XML document (or, under
39    /// [`Strictness::Strict`](crate::reader::Strictness::Strict), names something the
40    /// schema does not define).
41    NotCimXml {
42        message: String,
43        source: Option<String>,
44        position: Option<u64>,
45    },
46    /// A reference could not be resolved and the link policy is strict.
47    DanglingReference {
48        object: String,
49        attribute: &'static str,
50        target: String,
51        /// Total number of unresolved references found.
52        total: usize,
53    },
54    /// Two models built from different CIM vintages cannot be combined.
55    ///
56    /// Class and attribute identifiers index one vintage's tables and mean something else
57    /// in another.
58    SchemaMismatch {
59        left: &'static str,
60        right: &'static str,
61    },
62    /// No file under the given path declares a CIM vocabulary this build recognises.
63    ///
64    /// Either the input is not CIM/XML, or it is a vintage this build has no feature for.
65    UnknownVintage {
66        path: String,
67        /// The vintages that *are* compiled in.
68        known: Vec<&'static str>,
69    },
70    /// A zip archive could not be read.
71    #[cfg(feature = "zip")]
72    Zip(String),
73    /// The input exceeded [`ReadOptions::max_input_bytes`](crate::reader::ReadOptions::max_input_bytes).
74    ///
75    /// The budget covers one load call, every file and decompressed archive entry of it.
76    /// Never downgraded to a diagnostic by lenient reading: the dataset is incomplete and
77    /// should be discarded.
78    InputTooLarge {
79        /// The budget in force, in bytes.
80        limit: u64,
81        /// Bytes accepted, across the whole load call, when the budget was exceeded.
82        read: u64,
83        /// The document being read: a file name or an archive entry.
84        source: Option<String>,
85    },
86}
87
88impl Error {
89    /// The byte offset in the source document this error concerns, when it has one.
90    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    /// Fill in where a document error happened, keeping what is already known.
115    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    /// What went wrong, without the source and position, for a [`Diagnostic`] that
137    /// carries both as fields.
138    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
151/// ` in EQ.xml at byte 120`, from whatever is known.
152fn 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
252/// A byte count the way a person reads one: `2 GiB`, `512 KiB`, `17 B`.
253///
254/// Exact multiples print as integers, everything else to one decimal.
255pub(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)] // one decimal of a human-facing figure
267    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/// How much a diagnostic matters.
298#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
299pub enum Severity {
300    /// Violates the standard; the model is not conforming.
301    Error,
302    /// Legal but suspect, or a tolerated deviation.
303    Warning,
304    /// Informational, e.g. a deprecated attribute in use.
305    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
318/// A stable identifier for the rule that produced a diagnostic.
319///
320/// Rule codes let a pipeline filter, suppress or fail on specific classes of problem
321/// without matching message text.
322///
323/// One macro declares the variants, their codes and [`Rule::ALL`], so they cannot drift.
324macro_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            /// Short stable code, e.g. `CIM0007`, suitable for CI filters.
333            pub const fn code(self) -> &'static str {
334                match self {
335                    $(Rule::$name => $code,)*
336                }
337            }
338
339            /// Every rule, so tooling can enumerate the catalogue.
340            pub const ALL: &'static [Rule] = &[$(Rule::$name,)*];
341        }
342    };
343}
344
345rules! {
346    /// An element names a class the schema does not define.
347    UnknownClass => "CIM0001",
348    /// An element names an attribute the schema does not define for its class.
349    UnknownAttribute => "CIM0002",
350    /// An attribute value could not be parsed as its declared type.
351    InvalidValue => "CIM0003",
352    /// An identifier is not a UUID, as IEC 61970-552 requires.
353    NonConformingMrid => "CIM0004",
354    /// An identifier is used where it must be unique: by objects of unrelated classes,
355    /// defined twice with `rdf:ID` in one document, or — with
356    /// [`ReadOptions::single_description`](crate::reader::ReadOptions::single_description)
357    /// — described twice in one document.
358    DuplicateMrid => "CIM0005",
359    /// A reference points at an object not present in the dataset.
360    DanglingReference => "CIM0006",
361    /// A required attribute is missing.
362    MissingRequired => "CIM0007",
363    /// An attribute occurs more often than its multiplicity permits; from the reader, a
364    /// single-valued one given again with the same value.
365    CardinalityExceeded => "CIM0008",
366    /// A reference points at an object of the wrong class.
367    WrongReferenceTarget => "CIM0009",
368    /// An attribute is used outside the profiles that declare it.
369    AttributeNotInProfile => "CIM0010",
370    /// An abstract class was instantiated.
371    AbstractInstantiated => "CIM0011",
372    /// A deprecated element is in use.
373    Deprecated => "CIM0012",
374    /// The file header is missing or incomplete.
375    MalformedHeader => "CIM0013",
376    /// A header declares a dependency that was not loaded; or a change set's base or
377    /// precondition is not satisfied, and it was not applied.
378    UnsatisfiedDependency => "CIM0014",
379    /// A structural problem in the document that did not prevent reading.
380    Structure => "CIM0015",
381    /// A stored value does not have the shape its attribute declares.
382    ///
383    /// CIM/XML carries no datatype information, so this is only detectable against the
384    /// schema (e.g. text where a float is declared, or another enumeration's literal).
385    DatatypeMismatch => "CIM0016",
386    /// An attribute the schema pins with `cims:isFixed` carries a different value.
387    FixedValueMismatch => "CIM0017",
388    /// One single-valued attribute was given two different values.
389    ///
390    /// By two loaded files: merging keeps the later and discards the other; see
391    /// [`Dataset::merge_conflicts`]. Twice in one document, in one element or in two
392    /// descriptions of the object: the reader keeps the later and reports an error with
393    /// [`Diagnostic::related_position`] at the first.
394    ///
395    /// [`Dataset::merge_conflicts`]: crate::Dataset::merge_conflicts
396    ConflictingValue => "CIM0018",
397    /// A value, identifier or reference holds a character XML 1.0 cannot represent.
398    ///
399    /// XML's `Char` production excludes most of the C0 range, even as a character
400    /// reference, so it cannot be written at all. The reader strips such characters and
401    /// reports them; validation also flags values set through the API.
402    IllegalXmlCharacter => "CIM0019",
403    /// A file or archive entry in the model set could not be read; it contributes nothing.
404    ///
405    /// Under [`Strictness::Lenient`](crate::reader::Strictness::Lenient) the load records
406    /// this and reads the remaining files; under `Strict` it is an [`Error`].
407    UnreadableFile => "CIM0022",
408    /// The document is written against a different schema vintage than the one reading it.
409    ///
410    /// Detected from the root's namespaces (`…/CIM100#` for CGMES 3.0,
411    /// `…/CIM-schema-cim16#` for 2.4.15), reported once instead of one `CIM0001` per element.
412    WrongVintage => "CIM0021",
413    /// An identifier has no valid RDF/XML serialization.
414    ///
415    /// `rdf:ID` is an XML `NCName` and `rdf:about` an IRI reference; every UUID is fine.
416    /// An identifier that is neither (one containing a space, say) is still written, but
417    /// the document is not valid RDF/XML, though it is well-formed XML.
418    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/// A structured finding, usable by CI and tooling rather than only printable.
428///
429/// The object and attribute fields hold the identifier and the schema's name, not
430/// rendered text, so callers can group or look up findings without parsing messages.
431#[derive(Clone, Debug)]
432pub struct Diagnostic {
433    pub severity: Severity,
434    pub rule: Rule,
435    /// Identifier of the object concerned, when the finding is object-scoped.
436    pub object: Option<crate::mrid::Mrid>,
437    /// Class name of that object.
438    pub class: Option<&'static str>,
439    /// Qualified attribute name, when the finding is attribute-scoped.
440    pub attribute: Option<&'static str>,
441    /// Source file the finding came from.
442    pub source: Option<String>,
443    /// Byte offset in the source document, when the finding came from parsing.
444    ///
445    /// An offset, not a line, because the reader streams; [`line_and_column`] converts.
446    /// The reader records the start of the element concerned: its `<`.
447    pub position: Option<u64>,
448    /// Byte offset of an earlier occurrence the finding refers to, such as the first of
449    /// two conflicting values.
450    pub related_position: Option<u64>,
451    pub message: String,
452}
453
454/// Convert a byte offset in `source` to a 1-based line and column.
455///
456/// Pairs with [`Diagnostic::position`], which the streaming reader records instead of a
457/// line number. Reads `source` up to `position` only.
458pub 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    /// Record the byte offset in the source document the finding came from.
510    pub fn with_position(mut self, position: u64) -> Diagnostic {
511        self.position = Some(position);
512        self
513    }
514    /// Record the byte offset of an earlier occurrence the finding refers to.
515    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            // `@` rather than `:` so the number is not mistaken for a line.
529            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/// A collection of diagnostics with convenience queries.
547#[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    /// Whether any diagnostic is an error, i.e. the model is non-conforming.
577    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    /// Number of findings per rule, most frequent first — a useful CI summary.
592    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        // Contiguous from CIM0001, because the codes are a published catalogue and a hole
644        // in it means a rule was removed and every citation after it now means something
645        // else — the same reasoning the `concepts/` registers are held to.
646        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        // Past the end clamps rather than panicking.
660        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        // A read given no source name still says where.
690        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        // A position already known is kept.
703        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}