openbim_ifc_binding_core/validation.rs
1//! Schema validation as plain records (feature `validate`).
2//!
3//! Runs the facade's validator against the schema the file declares and
4//! flattens its report into records every host can carry: strings, ids and
5//! counts, in the report's stable sorted order. Without the feature the
6//! records still exist, so every host keeps one surface, and
7//! [`IfcModel::validate`] refuses with `feature-disabled`.
8
9use crate::{BindingError, IfcModel};
10
11/// One finding: what is wrong, and where.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct ValidationFinding {
14 /// `error`, `evaluation-error`, `warning`, `indeterminate` or
15 /// `unsupported`, as the validator spells them. `error` and
16 /// `evaluation-error` make a file non-conformant; `indeterminate` is an
17 /// EXPRESS rule that evaluated to UNKNOWN; `unsupported` is a rule this
18 /// validator does not check.
19 pub severity: String,
20 /// Stable id of the check, e.g. `structure.reference.dangling`.
21 pub rule: String,
22 /// The entity the finding is about; `None` for the file as a whole.
23 pub entity: Option<u64>,
24 /// The zero-based attribute slot, when the finding is about one.
25 pub attribute_index: Option<usize>,
26 /// The attribute's schema name, when the schema declares one.
27 pub attribute_name: Option<String>,
28 /// The location as text: `<file>`, `#12` or `#12.Name`.
29 pub path: String,
30 /// What is wrong, in one sentence.
31 pub message: String,
32}
33
34/// Counts by severity.
35#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
36pub struct ValidationSummary {
37 /// Schema violations.
38 pub errors: usize,
39 /// Implemented rules that could not be decided for an instance.
40 pub evaluation_errors: usize,
41 /// Legal but suspicious conditions.
42 pub warnings: usize,
43 /// EXPRESS rules that evaluated to UNKNOWN for an instance (#538); always
44 /// 0 without EXPRESS rules.
45 pub indeterminate: usize,
46 /// Rules this validator does not evaluate.
47 pub unsupported: usize,
48}
49
50/// Everything one validation run found.
51#[derive(Debug, Clone, Default, PartialEq, Eq)]
52pub struct ValidationReport {
53 /// No errors and no evaluation errors among the recorded findings.
54 /// Unsupported rules do not count against it.
55 pub conformant: bool,
56 /// The run hit its finding budget: the counts are lower bounds and a
57 /// conformant verdict is not final.
58 pub truncated: bool,
59 /// Counts by severity over the recorded findings.
60 pub summary: ValidationSummary,
61 /// Every recorded finding, sorted by severity, rule, entity and slot.
62 pub findings: Vec<ValidationFinding>,
63}
64
65impl IfcModel {
66 /// Validate against the schema the header declares.
67 ///
68 /// `max_findings` caps how many findings are recorded (the validator's
69 /// default budget, 10,000, when `None`); hitting it sets
70 /// [`ValidationReport::truncated`]. Refused with `unsupported-schema`
71 /// when the header names no bundled schema, and with `feature-disabled`
72 /// in a build without the `validate` feature.
73 pub fn validate(&self, max_findings: Option<usize>) -> Result<ValidationReport, BindingError> {
74 #[cfg(feature = "validate")]
75 {
76 run(self, max_findings)
77 }
78 #[cfg(not(feature = "validate"))]
79 {
80 let _ = max_findings;
81 Err(BindingError::FeatureDisabled("validate"))
82 }
83 }
84
85 /// Validate with the EXPRESS rules of the declared release, read from
86 /// `express`, the text of that release's `.exp` file (#538).
87 ///
88 /// Every WHERE, type and global rule is evaluated, and INVERSE
89 /// cardinality is checked. The text is parsed on each call against the
90 /// declared release's tables; it is never bundled (the schemas are
91 /// CC BY-ND). Refused with `express-mismatch` when the text declares
92 /// another schema or disagrees with the tables, with `invalid-express`
93 /// when it does not parse, with `unsupported-schema` when the header
94 /// names no bundled schema, and with `feature-disabled` in a build
95 /// without the `validate-express` feature.
96 pub fn validate_express(
97 &self,
98 express: &str,
99 max_findings: Option<usize>,
100 ) -> Result<ValidationReport, BindingError> {
101 #[cfg(feature = "validate-express")]
102 {
103 run_express(self, express, max_findings)
104 }
105 #[cfg(not(feature = "validate-express"))]
106 {
107 let _ = (express, max_findings);
108 Err(BindingError::FeatureDisabled("validate-express"))
109 }
110 }
111}
112
113#[cfg(feature = "validate")]
114fn run(model: &IfcModel, max_findings: Option<usize>) -> Result<ValidationReport, BindingError> {
115 use ifc::validate::{validate_with, Budget};
116
117 let schema = model.declared_schema()?;
118 let budget = max_findings.map_or(Budget::DEFAULT, |max_findings| Budget { max_findings });
119 Ok(flatten(&validate_with(&model.inner, schema, budget)))
120}
121
122#[cfg(feature = "validate-express")]
123fn run_express(
124 model: &IfcModel,
125 express: &str,
126 max_findings: Option<usize>,
127) -> Result<ValidationReport, BindingError> {
128 use ifc::validate::express::{ExpressError, ExpressRules};
129 use ifc::validate::{validate_with_options, Budget, ValidateOptions};
130
131 let schema = model.declared_schema()?;
132 let rules = ExpressRules::parse(express, schema).map_err(|error| match error {
133 ExpressError::SchemaMismatch { .. } | ExpressError::TableMismatch { .. } => {
134 BindingError::ExpressMismatch(error.to_string())
135 }
136 // Syntax, Unresolved, and any error added after this binding.
137 _ => BindingError::InvalidExpress(error.to_string()),
138 })?;
139 let budget = max_findings.map_or(Budget::DEFAULT, |max_findings| Budget { max_findings });
140 let options = ValidateOptions::new().budget(budget).express(&rules);
141 Ok(flatten(&validate_with_options(
142 &model.inner,
143 schema,
144 &options,
145 )))
146}
147
148/// The validator's report as plain records.
149#[cfg(feature = "validate")]
150fn flatten(report: &ifc::validate::Report) -> ValidationReport {
151 use ifc::validate::Path;
152
153 let summary = report.summary();
154 let findings = report
155 .sorted()
156 .into_iter()
157 .map(|finding| {
158 let (entity, attribute_index, attribute_name) = match &finding.path {
159 Path::File => (None, None, None),
160 Path::Entity(id) => (Some(id.0), None, None),
161 Path::Attribute {
162 entity,
163 index,
164 name,
165 } => (Some(entity.0), Some(*index), name.clone()),
166 // A path kind added after this binding: `path` still says
167 // where, as text.
168 _ => (None, None, None),
169 };
170 ValidationFinding {
171 severity: finding.severity.to_string(),
172 rule: finding.rule.clone(),
173 entity,
174 attribute_index,
175 attribute_name,
176 path: finding.path.to_string(),
177 message: finding.message.clone(),
178 }
179 })
180 .collect();
181 ValidationReport {
182 conformant: report.is_conformant(),
183 truncated: report.is_truncated(),
184 summary: ValidationSummary {
185 errors: summary.errors,
186 evaluation_errors: summary.evaluation_errors,
187 warnings: summary.warnings,
188 indeterminate: summary.indeterminate,
189 unsupported: summary.unsupported,
190 },
191 findings,
192 }
193}
194
195/// The report as one tagged `list` of findings, each a `list` of seven
196/// values: severity (text), rule (text), entity (`ref`, or `null` for the
197/// file), attribute index (`integer` or `null`), attribute name (`text` or
198/// `null`), path (text), message (text). The C binding's tape form.
199pub fn findings_to_tagged(findings: &[ValidationFinding]) -> crate::value::Tagged {
200 use crate::value::Tagged;
201 let optional = |value: Option<Tagged>| value.unwrap_or(Tagged::Null);
202 Tagged::List(
203 findings
204 .iter()
205 .map(|finding| {
206 Tagged::List(vec![
207 Tagged::Text(finding.severity.clone()),
208 Tagged::Text(finding.rule.clone()),
209 optional(finding.entity.map(Tagged::Ref)),
210 optional(
211 finding
212 .attribute_index
213 // A slot index is far below i64::MAX.
214 .map(|index| Tagged::Integer(i64::try_from(index).unwrap_or(i64::MAX))),
215 ),
216 optional(finding.attribute_name.clone().map(Tagged::Text)),
217 Tagged::Text(finding.path.clone()),
218 Tagged::Text(finding.message.clone()),
219 ])
220 })
221 .collect(),
222 )
223}