Skip to main content

ifc_validate/report/
finding.rs

1//! What a validator says when something is wrong.
2//!
3//! # Severity is about conformance, not about how annoyed you should be
4//!
5//! [`Severity::Error`] means the file violates the schema: a required
6//! attribute is absent, a reference points at nothing, a GUID is duplicated.
7//! [`Severity::Warning`] means the file is legal but suspicious.
8//! [`Severity::Unsupported`] means *this validator did not check* -- the rule
9//! exists in the schema and is not implemented here.
10//! [`Severity::EvaluationError`] means an implemented rule applied to an
11//! instance and *could not be decided* for it: an operand has a shape the rule
12//! cannot read, names a target the file does not contain, or is missing from
13//! the schema tables the rule was written against.
14//!
15//! [`Severity::Indeterminate`] means an EXPRESS rule evaluated to UNKNOWN
16//! or `?` for an instance: the data could not decide it. ISO 10303-11 does
17//! not count that as a violation, so it leaves conformance alone, but it
18//! is reported rather than read as a pass.
19//!
20//! `Unsupported` and `EvaluationError` are the important ones. A validator that silently
21//! skips what it cannot evaluate reports a clean file and is worse than
22//! useless, because a clean report is exactly what a user acts on. Counting
23//! the unchecked rules is what makes "no errors" mean something.
24//!
25//! They differ in what they say about the file. `Unsupported` is a fact about
26//! this validator for every file alike, so it leaves conformance alone. An
27//! `EvaluationError` is about *this* instance: the rule may well be violated
28//! there, so a report carrying one is not conformant.
29
30use std::fmt;
31
32use super::detail::FindingDetail;
33use super::path::Path;
34
35/// How serious a finding is.
36///
37/// Declaration order is the report's sort order, most actionable first.
38/// Non-exhaustive: a new category of finding must not break every match.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
40#[non_exhaustive]
41pub enum Severity {
42    /// The file violates the schema.
43    Error,
44    /// An implemented rule applies to this instance but could not be
45    /// decided for it. Makes the report non-conformant, because "could not
46    /// check" is not "passed".
47    EvaluationError,
48    /// Legal, but very likely a mistake.
49    Warning,
50    /// An EXPRESS rule evaluated to UNKNOWN or `?` for an instance: neither
51    /// satisfied nor violated. Not a verdict against the file.
52    Indeterminate,
53    /// A rule this validator does not implement. Not a verdict on the file.
54    Unsupported,
55}
56
57impl fmt::Display for Severity {
58    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
59        let text = match self {
60            Self::Error => "error",
61            Self::EvaluationError => "evaluation-error",
62            Self::Warning => "warning",
63            Self::Indeterminate => "indeterminate",
64            Self::Unsupported => "unsupported",
65        };
66        formatter.write_str(text)
67    }
68}
69
70/// One thing a validator has to say about a file.
71#[derive(Debug, Clone, PartialEq, Eq)]
72#[non_exhaustive]
73pub struct Finding {
74    /// How serious it is.
75    pub severity: Severity,
76    /// A stable identifier for the check that produced this, e.g.
77    /// `structure.reference.dangling` or `where.IfcRoot.WR1`. Callers filter
78    /// and suppress on this, so it is part of the contract.
79    pub rule: String,
80    /// Where the problem is.
81    pub path: Path,
82    /// What is wrong, in one sentence, without restating the rule id.
83    pub message: String,
84    /// Typed detail, when the check provides it: an EXPRESS rule's scope,
85    /// label and outcome, or a reserved set name.
86    pub detail: Option<FindingDetail>,
87}
88
89impl Finding {
90    /// A schema violation.
91    #[must_use]
92    pub fn error(rule: impl Into<String>, path: Path, message: impl Into<String>) -> Self {
93        Self {
94            severity: Severity::Error,
95            rule: rule.into(),
96            path,
97            message: message.into(),
98            detail: None,
99        }
100    }
101
102    /// A legal but suspicious condition.
103    #[must_use]
104    pub fn warning(rule: impl Into<String>, path: Path, message: impl Into<String>) -> Self {
105        Self {
106            severity: Severity::Warning,
107            rule: rule.into(),
108            path,
109            message: message.into(),
110            detail: None,
111        }
112    }
113
114    /// An implemented rule that could not be decided for one instance.
115    ///
116    /// `rule` is the rule's own id, so a caller filtering on it sees both
117    /// verdicts; the severity says which one this is.
118    #[must_use]
119    pub fn evaluation_error(
120        rule: impl Into<String>,
121        path: Path,
122        message: impl Into<String>,
123    ) -> Self {
124        Self {
125            severity: Severity::EvaluationError,
126            rule: rule.into(),
127            path,
128            message: message.into(),
129            detail: None,
130        }
131    }
132
133    /// A rule this validator did not evaluate.
134    #[must_use]
135    pub fn unsupported(rule: impl Into<String>, path: Path, message: impl Into<String>) -> Self {
136        Self {
137            severity: Severity::Unsupported,
138            rule: rule.into(),
139            path,
140            message: message.into(),
141            detail: None,
142        }
143    }
144}
145
146impl Finding {
147    /// A rule this validator evaluated that could decide nothing for the
148    /// instance: UNKNOWN or `?`.
149    #[must_use]
150    pub fn indeterminate(rule: impl Into<String>, path: Path, message: impl Into<String>) -> Self {
151        Self {
152            severity: Severity::Indeterminate,
153            rule: rule.into(),
154            path,
155            message: message.into(),
156            detail: None,
157        }
158    }
159
160    /// The same finding, carrying typed detail.
161    #[must_use]
162    pub fn with_detail(mut self, detail: FindingDetail) -> Self {
163        self.detail = Some(detail);
164        self
165    }
166}
167
168impl fmt::Display for Finding {
169    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
170        write!(
171            formatter,
172            "{}: {} at {}: {}",
173            self.severity, self.rule, self.path, self.message
174        )
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181    use ifc_model::EntityId;
182
183    /// Severity ordering is what report sorting relies on.
184    #[test]
185    fn errors_sort_before_warnings_before_unsupported() {
186        let mut severities = [
187            Severity::Unsupported,
188            Severity::Indeterminate,
189            Severity::Warning,
190            Severity::EvaluationError,
191            Severity::Error,
192        ];
193        severities.sort();
194        assert_eq!(
195            severities,
196            [
197                Severity::Error,
198                Severity::EvaluationError,
199                Severity::Warning,
200                Severity::Indeterminate,
201                Severity::Unsupported
202            ]
203        );
204    }
205
206    /// Each severity renders distinctly, so a printed report cannot
207    /// conflate "violated" with "could not decide".
208    #[test]
209    fn every_severity_renders_distinctly() {
210        let rendered: Vec<String> = [
211            Severity::Error,
212            Severity::EvaluationError,
213            Severity::Warning,
214            Severity::Indeterminate,
215            Severity::Unsupported,
216        ]
217        .iter()
218        .map(ToString::to_string)
219        .collect();
220        let mut unique = rendered.clone();
221        unique.sort();
222        unique.dedup();
223        assert_eq!(unique.len(), rendered.len(), "{rendered:?}");
224    }
225
226    /// A finding renders its path so a reader can find the entity.
227    #[test]
228    fn a_finding_names_where_it_applies() {
229        let finding = Finding::error(
230            "structure.dangling",
231            Path::Attribute {
232                entity: EntityId(12),
233                index: 3,
234                name: Some("Representation".into()),
235            },
236            "points at #99, which does not exist",
237        );
238        assert_eq!(finding.path.to_string(), "#12.Representation");
239        assert_eq!(finding.severity, Severity::Error);
240    }
241}