Skip to main content

ifc_validate/report/
summary.rs

1//! Deterministic counts and the assembled report.
2
3use std::fmt;
4
5use super::finding::{Finding, Severity};
6use super::path::path_key;
7
8/// Counts by severity, for a one-line verdict.
9///
10/// Non-exhaustive: it is produced by [`Report::summary`], and a new severity
11/// must be able to add its count without breaking callers.
12#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
13#[non_exhaustive]
14pub struct Summary {
15    /// How many schema violations.
16    pub errors: usize,
17    /// How many implemented rules could not be decided for an instance.
18    pub evaluation_errors: usize,
19    /// How many suspicious-but-legal findings.
20    pub warnings: usize,
21    /// How many EXPRESS rule results were UNKNOWN or `?`.
22    pub indeterminate: usize,
23    /// How many rules went unevaluated.
24    pub unsupported: usize,
25}
26
27impl Summary {
28    /// Whether the file violated nothing this validator checked, and every
29    /// implemented rule could be decided.
30    ///
31    /// Deliberately ignores [`Severity::Unsupported`]: an unchecked rule is a
32    /// statement about the validator, not about the file. Callers that want
33    /// "clean *and* fully checked" must also test [`Summary::unsupported`],
34    /// and the distinction is the point.
35    ///
36    /// Does *not* ignore [`Severity::EvaluationError`]: that is an implemented
37    /// rule this particular instance defeated, and reading it as a pass would
38    /// be exactly the silent skip this crate refuses to make.
39    #[must_use]
40    pub const fn is_conformant(&self) -> bool {
41        self.errors == 0 && self.evaluation_errors == 0
42    }
43}
44
45impl fmt::Display for Summary {
46    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(
48            formatter,
49            "{} errors, {} evaluation errors, {} warnings, {} indeterminate, {} unsupported",
50            self.errors,
51            self.evaluation_errors,
52            self.warnings,
53            self.indeterminate,
54            self.unsupported
55        )
56    }
57}
58
59/// Everything a validation run produced.
60#[derive(Debug, Clone)]
61pub struct Report {
62    findings: Vec<Finding>,
63    truncated: bool,
64    max_findings: usize,
65}
66
67impl Default for Report {
68    fn default() -> Self {
69        Self {
70            findings: Vec::new(),
71            truncated: false,
72            max_findings: usize::MAX,
73        }
74    }
75}
76
77impl PartialEq for Report {
78    fn eq(&self, other: &Self) -> bool {
79        self.findings == other.findings && self.truncated == other.truncated
80    }
81}
82
83impl Eq for Report {}
84
85impl Report {
86    /// An empty report.
87    #[must_use]
88    pub fn new() -> Self {
89        Self::default()
90    }
91
92    /// An empty report that stores at most `max_findings` entries.
93    pub(crate) fn with_max_findings(max_findings: usize) -> Self {
94        Self {
95            max_findings,
96            ..Self::default()
97        }
98    }
99
100    /// Records a finding, or marks the report truncated when its cap is full.
101    pub fn push(&mut self, finding: Finding) {
102        if self.findings.len() >= self.max_findings {
103            self.truncated = true;
104            return;
105        }
106        self.findings.push(finding);
107    }
108
109    /// Records that the run stopped early because it hit its finding budget.
110    ///
111    /// A report that silently stops at N findings claims the file has N
112    /// problems. This flag is what keeps that claim honest.
113    pub fn mark_truncated(&mut self) {
114        self.truncated = true;
115    }
116
117    /// Whether the run stopped before checking everything.
118    #[must_use]
119    pub const fn is_truncated(&self) -> bool {
120        self.truncated
121    }
122
123    /// Every finding, in the order produced.
124    ///
125    /// Callers wanting a stable order across runs should use
126    /// [`Report::sorted`]: production order follows traversal, which is
127    /// deterministic for a given model but not meaningful.
128    #[must_use]
129    pub fn findings(&self) -> &[Finding] {
130        &self.findings
131    }
132
133    /// How many findings of each severity.
134    #[must_use]
135    pub fn summary(&self) -> Summary {
136        let mut summary = Summary::default();
137        for finding in &self.findings {
138            match finding.severity {
139                Severity::Error => summary.errors += 1,
140                Severity::EvaluationError => summary.evaluation_errors += 1,
141                Severity::Warning => summary.warnings += 1,
142                Severity::Indeterminate => summary.indeterminate += 1,
143                Severity::Unsupported => summary.unsupported += 1,
144            }
145        }
146        summary
147    }
148
149    /// Findings in a stable, explicitly defined order.
150    ///
151    /// Sorted by severity, then rule id, then entity id, then slot. Two runs
152    /// over the same file always produce byte-identical output, which is what
153    /// makes a report diffable in CI.
154    #[must_use]
155    pub fn sorted(&self) -> Vec<&Finding> {
156        let mut sorted: Vec<&Finding> = self.findings.iter().collect();
157        sorted.sort_by(|left, right| {
158            left.severity
159                .cmp(&right.severity)
160                .then_with(|| left.rule.cmp(&right.rule))
161                .then_with(|| path_key(&left.path).cmp(&path_key(&right.path)))
162                .then_with(|| left.message.cmp(&right.message))
163        });
164        sorted
165    }
166
167    /// Merges another report into this one, preserving the truncation flag.
168    pub fn extend(&mut self, other: Self) {
169        let other_truncated = other.truncated;
170        for finding in other.findings {
171            self.push(finding);
172        }
173        self.truncated |= other_truncated;
174    }
175
176    /// Whether anything this validator checked was violated.
177    #[must_use]
178    pub fn is_conformant(&self) -> bool {
179        self.summary().is_conformant()
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186    use crate::report::Path;
187    use ifc_model::EntityId;
188
189    #[test]
190    fn unsupported_rules_do_not_make_a_file_non_conformant() {
191        let mut report = Report::new();
192        report.push(Finding::unsupported(
193            "where.IfcRoot.WR1",
194            Path::File,
195            "not implemented",
196        ));
197        assert!(
198            report.is_conformant(),
199            "an unchecked rule is a fact about the validator"
200        );
201        assert_eq!(report.summary().unsupported, 1);
202    }
203
204    /// A rule that could not be decided is not a pass.
205    #[test]
206    fn an_evaluation_error_makes_a_file_non_conformant() {
207        let mut report = Report::new();
208        report.push(Finding::evaluation_error(
209            "IfcMaterialLayer.NormalizedPriority",
210            Path::Entity(EntityId(1)),
211            "Priority is a string, not an integer",
212        ));
213        let summary = report.summary();
214        assert_eq!(summary.evaluation_errors, 1);
215        assert_eq!(summary.errors, 0, "counted separately from violations");
216        assert!(!report.is_conformant());
217        assert!(summary.to_string().contains("1 evaluation errors"));
218    }
219
220    #[test]
221    fn sorting_is_total_and_stable() {
222        let mut report = Report::new();
223        report.push(Finding::warning("b.rule", Path::Entity(EntityId(9)), "w"));
224        report.push(Finding::error("a.rule", Path::Entity(EntityId(2)), "e"));
225        report.push(Finding::error("a.rule", Path::Entity(EntityId(1)), "e"));
226        let order: Vec<String> = report
227            .sorted()
228            .iter()
229            .map(|finding| finding.path.to_string())
230            .collect();
231        assert_eq!(order, ["#1", "#2", "#9"], "errors first, then by entity");
232    }
233
234    /// A capped report cannot be overfilled through a merge.
235    #[test]
236    fn extend_honors_the_storage_cap() {
237        let mut target = Report::with_max_findings(1);
238        let mut source = Report::new();
239        source.push(Finding::error("a", Path::File, "first"));
240        source.push(Finding::error("b", Path::File, "second"));
241
242        target.extend(source);
243
244        assert_eq!(target.findings().len(), 1);
245        assert!(target.is_truncated());
246    }
247
248    /// A truncated report says so, rather than implying the file is clean.
249    #[test]
250    fn truncation_survives_a_merge() {
251        let mut left = Report::new();
252        let mut right = Report::new();
253        right.mark_truncated();
254        left.extend(right);
255        assert!(left.is_truncated());
256    }
257}