Skip to main content

ifc_validate/where_rule/
registry.rs

1//! Which WHERE rules this validator actually evaluates.
2//!
3//! # The honesty problem this solves
4//!
5//! IFC4 declares hundreds of `WHERE` rules as EXPRESS expressions. This
6//! validator does not have an EXPRESS expression evaluator, so it cannot
7//! check most of them. The tempting design is to check the ones it can and
8//! stay quiet about the rest -- which produces a clean report for a file
9//! nobody fully checked, and a user who believes it.
10//!
11//! Instead every rule is registered with an explicit state. Supported rules
12//! are evaluated; unsupported ones are *reported* as unsupported. A caller
13//! can therefore distinguish "this file is conformant" from "this file did
14//! not trip the subset we implement".
15//!
16//! # Why a registry rather than a list of implemented functions
17//!
18//! Rules get implemented over time. If support were implicit in which
19//! functions exist, nothing would tell a reader which rules are missing --
20//! the absence of code is invisible. The registry makes the gap a data
21//! structure that can be counted, printed, and tested against.
22
23use ifc_schema::{Schema, SchemaVersion};
24
25/// Whether this validator evaluates a given rule.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27#[non_exhaustive]
28pub enum Support {
29    /// Implemented and evaluated on every run.
30    Implemented,
31    /// Declared by the schema, not evaluated here.
32    ///
33    /// Carries why, so the report can say something better than "no".
34    Unsupported(&'static str),
35}
36
37/// One registered rule.
38///
39/// The entry is the rule's whole scope: it applies to instances of
40/// [`Self::entity`] *and of its subtypes*, and only under the
41/// [`Self::releases`] whose EXPRESS declares it under this id. The engine
42/// reads both from here, so a rule cannot run on a narrower set of
43/// instances, or under more releases, than its entry states.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct RuleEntry {
46    /// Stable rule id: `<declaring entity>.<label>` exactly as the schema
47    /// writes it (e.g. `IfcExternalReference.WR1`), or `global.<name>` for a
48    /// file-wide rule.
49    pub id: &'static str,
50    /// The entity declaring the rule, or `None` for a global rule.
51    ///
52    /// Instances of its subtypes are constrained too: EXPRESS WHERE rules
53    /// are inherited.
54    pub entity: Option<&'static str>,
55    /// The releases whose EXPRESS declares this rule under [`Self::id`].
56    pub releases: &'static [SchemaVersion],
57    /// Whether it is evaluated.
58    pub support: Support,
59}
60
61impl RuleEntry {
62    /// Whether `schema` is a release that declares this rule.
63    ///
64    /// Tables of no recognised release declare none of the registered
65    /// rules: a rule is never carried across versions, nor onto an unknown
66    /// one.
67    #[must_use]
68    pub fn applies_to(&self, schema: &Schema) -> bool {
69        schema
70            .version()
71            .is_some_and(|version| self.releases.contains(&version))
72    }
73}
74
75/// Reason strings, shared so the same gap reads identically everywhere.
76const NEEDS_EXPRESSIONS: &str = "requires an EXPRESS expression evaluator";
77const NEEDS_INVERSES: &str =
78    "not implemented uniformly: IFC2X3 requires INVERSE relationship semantics, which validation does not derive";
79const NEEDS_GEOMETRY: &str = "requires geometric evaluation, which validation does not perform";
80
81/// Every release the registry is verified against (`tests/registry_scope.rs`).
82/// IFC4X1 and IFC4X2 are bundled but not yet scoped: no WHERE rule applies
83/// to them natively (their EXPRESS rules run through `crate::express`).
84const ALL: &[SchemaVersion] = &[
85    SchemaVersion::Ifc2x3,
86    SchemaVersion::Ifc4,
87    SchemaVersion::Ifc4x3,
88];
89/// Every bundled release: for the file-wide `IfcRoot.UR1` check, which
90/// needs no WHERE-rule label and holds in every release alike.
91const EVERY_RELEASE: &[SchemaVersion] = &[
92    SchemaVersion::Ifc2x3,
93    SchemaVersion::Ifc4,
94    SchemaVersion::Ifc4x1,
95    SchemaVersion::Ifc4x2,
96    SchemaVersion::Ifc4x3,
97];
98/// The id of the `IfcRoot.UR1` check: a UNIQUE clause, not a WHERE rule.
99pub(crate) const UNIQUE_GLOBAL_ID: &str = "global.UniqueGlobalId";
100/// IFC2X3 alone: IFC4 renamed most of its `WRnn` labels.
101const IFC2X3: &[SchemaVersion] = &[SchemaVersion::Ifc2x3];
102/// IFC4 and IFC4X3, which share their rule labels.
103const IFC4_FAMILY: &[SchemaVersion] = &[SchemaVersion::Ifc4, SchemaVersion::Ifc4x3];
104
105/// Every rule this validator knows about, implemented or not.
106///
107/// Deliberately not exhaustive over every bundled IFC release: claiming to
108/// enumerate all rules would be its own dishonesty. It covers selected
109/// high-value predicates plus representative unsupported categories.
110///
111/// Every entity-scoped entry's id, entity and releases are checked against
112/// the normative EXPRESS by `tests/registry_scope.rs`.
113pub const RULES: &[RuleEntry] = &[
114    RuleEntry {
115        id: "global.IfcSingleProjectInstance",
116        entity: None,
117        releases: ALL,
118        support: Support::Implemented,
119    },
120    // IfcRoot constrains GlobalId with `UNIQUE UR1`, not a WHERE rule. It is
121    // registered here under its global id rather than as `IfcRoot.UR1`: the
122    // check is file-wide, and two entries for one check would double-report.
123    RuleEntry {
124        id: UNIQUE_GLOBAL_ID,
125        entity: None,
126        releases: EVERY_RELEASE,
127        support: Support::Implemented,
128    },
129    RuleEntry {
130        id: "IfcRelDefinesByProperties.NoRelatedTypeObject",
131        entity: Some("IfcRelDefinesByProperties"),
132        releases: IFC4_FAMILY,
133        support: Support::Implemented,
134    },
135    RuleEntry {
136        id: "IfcExternalReference.WR1",
137        entity: Some("IfcExternalReference"),
138        releases: ALL,
139        support: Support::Implemented,
140    },
141    // One predicate under two labels: IFC2X3 `WR1`, IFC4 on
142    // `AvoidInconsistentSequence`.
143    RuleEntry {
144        id: "IfcRelSequence.WR1",
145        entity: Some("IfcRelSequence"),
146        releases: IFC2X3,
147        support: Support::Implemented,
148    },
149    RuleEntry {
150        id: "IfcRelSequence.AvoidInconsistentSequence",
151        entity: Some("IfcRelSequence"),
152        releases: IFC4_FAMILY,
153        support: Support::Implemented,
154    },
155    // IFC2X3 states these on the abstract IfcRelDecomposes as `WR31`, and
156    // the assignment ones below as `WR1`; neither label is registered yet.
157    RuleEntry {
158        id: "IfcRelAggregates.NoSelfReference",
159        entity: Some("IfcRelAggregates"),
160        releases: IFC4_FAMILY,
161        support: Support::Implemented,
162    },
163    RuleEntry {
164        id: "IfcRelNests.NoSelfReference",
165        entity: Some("IfcRelNests"),
166        releases: IFC4_FAMILY,
167        support: Support::Implemented,
168    },
169    RuleEntry {
170        id: "IfcMaterialLayer.NormalizedPriority",
171        entity: Some("IfcMaterialLayer"),
172        releases: IFC4_FAMILY,
173        support: Support::Implemented,
174    },
175    RuleEntry {
176        id: "IfcRelAssignsToActor.NoSelfReference",
177        entity: Some("IfcRelAssignsToActor"),
178        releases: IFC4_FAMILY,
179        support: Support::Implemented,
180    },
181    RuleEntry {
182        id: "IfcRelAssignsToProcess.NoSelfReference",
183        entity: Some("IfcRelAssignsToProcess"),
184        releases: IFC4_FAMILY,
185        support: Support::Implemented,
186    },
187    RuleEntry {
188        id: "IfcRelAssignsToProduct.NoSelfReference",
189        entity: Some("IfcRelAssignsToProduct"),
190        releases: IFC4_FAMILY,
191        support: Support::Implemented,
192    },
193    // Declared on IfcRelAssignsToGroup, so IfcRelAssignsToGroupByFactor
194    // inherits it rather than declaring its own.
195    RuleEntry {
196        id: "IfcRelAssignsToGroup.NoSelfReference",
197        entity: Some("IfcRelAssignsToGroup"),
198        releases: IFC4_FAMILY,
199        support: Support::Implemented,
200    },
201    RuleEntry {
202        id: "IfcRelConnectsPathElements.NormalizedRelatingPriorities",
203        entity: Some("IfcRelConnectsPathElements"),
204        releases: IFC4_FAMILY,
205        support: Support::Implemented,
206    },
207    RuleEntry {
208        id: "IfcRelConnectsPathElements.NormalizedRelatedPriorities",
209        entity: Some("IfcRelConnectsPathElements"),
210        releases: IFC4_FAMILY,
211        support: Support::Implemented,
212    },
213    RuleEntry {
214        id: "IfcRelSpaceBoundary.CorrectPhysOrVirt",
215        entity: Some("IfcRelSpaceBoundary"),
216        releases: IFC4_FAMILY,
217        support: Support::Implemented,
218    },
219    // `IfcUniqueDefinitionNames` / `IfcUniquePropertySetNames`; IFC2X3
220    // states no such rule.
221    RuleEntry {
222        id: "IfcObject.UniquePropertySetNames",
223        entity: Some("IfcObject"),
224        releases: IFC4_FAMILY,
225        support: Support::Implemented,
226    },
227    RuleEntry {
228        id: "IfcTypeObject.UniquePropertySetNames",
229        entity: Some("IfcTypeObject"),
230        releases: IFC4_FAMILY,
231        support: Support::Implemented,
232    },
233    // One predicate under two labels: IFC2X3 `WR41` over `ObjectTypeOf`,
234    // IFC4 on `ApplicableOccurrence` over `Types`.
235    RuleEntry {
236        id: "IfcTypeProduct.WR41",
237        entity: Some("IfcTypeProduct"),
238        releases: IFC2X3,
239        support: Support::Implemented,
240    },
241    RuleEntry {
242        id: "IfcTypeProduct.ApplicableOccurrence",
243        entity: Some("IfcTypeProduct"),
244        releases: IFC4_FAMILY,
245        support: Support::Implemented,
246    },
247    RuleEntry {
248        id: "IfcDocumentReference.WR1",
249        entity: Some("IfcDocumentReference"),
250        releases: ALL,
251        support: Support::Unsupported(NEEDS_INVERSES),
252    },
253    RuleEntry {
254        id: "IfcRepresentationContextSameWCS",
255        entity: None,
256        releases: ALL,
257        support: Support::Unsupported(NEEDS_GEOMETRY),
258    },
259    // One predicate under two labels: IFC2X3 `WR21`, IFC4 on
260    // `AllPointsSameDim`.
261    RuleEntry {
262        id: "IfcPolyLoop.WR21",
263        entity: Some("IfcPolyLoop"),
264        releases: IFC2X3,
265        support: Support::Unsupported(NEEDS_EXPRESSIONS),
266    },
267    RuleEntry {
268        id: "IfcPolyLoop.AllPointsSameDim",
269        entity: Some("IfcPolyLoop"),
270        releases: IFC4_FAMILY,
271        support: Support::Unsupported(NEEDS_EXPRESSIONS),
272    },
273    RuleEntry {
274        id: "IfcQuantityLength.WR21",
275        entity: Some("IfcQuantityLength"),
276        releases: ALL,
277        support: Support::Unsupported(NEEDS_EXPRESSIONS),
278    },
279    RuleEntry {
280        id: "IfcZone.WR1",
281        entity: Some("IfcZone"),
282        releases: ALL,
283        support: Support::Unsupported(NEEDS_EXPRESSIONS),
284    },
285];
286
287/// The registered entry for `id`, if there is one.
288#[must_use]
289pub fn lookup(id: &str) -> Option<&'static RuleEntry> {
290    RULES.iter().find(|entry| entry.id == id)
291}
292
293/// Every rule this validator does not evaluate.
294pub fn unsupported() -> impl Iterator<Item = &'static RuleEntry> {
295    RULES
296        .iter()
297        .filter(|entry| matches!(entry.support, Support::Unsupported(_)))
298}
299
300/// Every rule this validator does evaluate.
301pub fn implemented() -> impl Iterator<Item = &'static RuleEntry> {
302    RULES
303        .iter()
304        .filter(|entry| matches!(entry.support, Support::Implemented))
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    /// Rule ids must be unique: they are what callers suppress on.
312    #[test]
313    fn rule_ids_are_unique() {
314        let mut ids: Vec<&str> = RULES.iter().map(|entry| entry.id).collect();
315        ids.sort_unstable();
316        let count = ids.len();
317        ids.dedup();
318        assert_eq!(ids.len(), count, "duplicate rule id in the registry");
319    }
320
321    /// The registry must actually contain unevaluated rules.
322    ///
323    /// If this ever reports zero, either every IFC4 rule is implemented -- it
324    /// is not -- or rules are being dropped from the registry instead of
325    /// being marked unsupported, which is exactly the dishonesty the registry
326    /// exists to prevent.
327    #[test]
328    fn the_registry_admits_what_it_cannot_check() {
329        assert!(
330            unsupported().count() > 0,
331            "a validator claiming full WHERE-rule coverage is lying"
332        );
333    }
334
335    /// An entity-scoped id names its declaring entity, and that entity
336    /// exists in every release the entry claims.
337    ///
338    /// `IfcRelAssignsToGroupByFactor.NoSelfReference` once named a subtype
339    /// that declares nothing; `tests/registry_scope.rs` additionally checks
340    /// each label against the normative EXPRESS.
341    #[test]
342    fn entity_ids_name_their_declaring_entity_in_every_claimed_release() {
343        for entry in RULES {
344            assert!(!entry.releases.is_empty(), "{} applies nowhere", entry.id);
345            let Some(entity) = entry.entity else {
346                continue;
347            };
348            assert!(
349                entry.id.starts_with(&format!("{entity}.")),
350                "{} is not `{entity}.<label>`",
351                entry.id
352            );
353            for version in entry.releases {
354                let schema = ifc_schema::for_version(*version).expect("bundled tables");
355                assert!(
356                    schema.entity(entity).is_some(),
357                    "{} claims {version:?}, which declares no {entity}",
358                    entry.id
359                );
360            }
361        }
362    }
363
364    /// Tables of an unrecognised release run no registered rule.
365    #[test]
366    fn an_unknown_release_declares_no_registered_rule() {
367        let schema = Schema::from_express("SCHEMA IFC9;\nEND_SCHEMA;\n");
368        assert!(RULES.iter().all(|entry| !entry.applies_to(&schema)));
369    }
370
371    #[test]
372    fn unsupported_boundaries_remain_explicit() {
373        let reasons: Vec<_> = unsupported()
374            .filter_map(|entry| match entry.support {
375                Support::Unsupported(reason) => Some(reason),
376                Support::Implemented => None,
377            })
378            .collect();
379        // Aggregate bounds are checked since #111 (`structure::bounds`), so no
380        // rule may still claim to need them.
381        assert!(
382            reasons
383                .iter()
384                .all(|reason| !reason.contains("aggregate bounds")),
385            "{reasons:?}"
386        );
387        for required in ["EXPRESS expression", "INVERSE"] {
388            assert!(
389                reasons.iter().any(|reason| reason.contains(required)),
390                "missing explicit unsupported boundary for {required}: {reasons:?}"
391            );
392        }
393    }
394}