Skip to main content

ifc_systems/
release.rs

1//! The release a read binds to.
2//!
3//! Every accessor in this crate — `systems`, `zones`, `ports`, `flow::of`,
4//! `connectivity::build` — must interpret entities against the IFC release
5//! the file actually declares, not against a hard-wired one (issue #52), and
6//! refuses a file that binds no verified release instead of reading it as
7//! IFC4.
8//! `IfcZone` is a subtype of `IfcSystem` in IFC4 but of `IfcGroup` in
9//! IFC2X3; reading an IFC2X3 file under the IFC4 table therefore
10//! misclassifies zones as systems and vice versa for `IfcElectricalCircuit`.
11//!
12//! This module resolves that release once per read and hands out a small
13//! [`Release`] carrying both the version tag (for error reporting) and the
14//! bundled [`Schema`] table (for `is_a`/`attributes` lookups), mirroring the
15//! pattern `ifc-properties::exact::release` established for issue #48.
16
17use ifc_model::Model;
18use ifc_schema::{for_version, Schema, SchemaVersion};
19
20use crate::error::SchemaResolutionError;
21
22/// The release a read runs against: its version tag and bundled table.
23///
24/// Crate-private: callers get a [`SchemaVersion`] from [`schema_of`] and
25/// the crate's public accessors resolve their own `Release` internally, so
26/// this type never needs to appear in a public signature.
27#[derive(Clone, Copy)]
28pub(crate) struct Release {
29    pub(crate) version: SchemaVersion,
30    pub(crate) schema: &'static Schema,
31}
32
33impl Release {
34    /// Whether `candidate` (a declared entity type name) is `ancestor` or a
35    /// subtype of it, under this release's table.
36    pub(crate) fn is_a(self, candidate: &str, ancestor: &str) -> bool {
37        self.schema.is_a(candidate, ancestor)
38    }
39
40    /// Position of `attribute` on `entity` in this release, by name; `None`
41    /// when the release does not declare it.
42    ///
43    /// Used to tell "the file left this attribute empty" apart from "this
44    /// release does not have this attribute" (e.g. IFC2X3 `IfcZone` has no
45    /// `LongName`).
46    pub(crate) fn slot(self, entity: &str, attribute: &str) -> Option<usize> {
47        self.schema
48            .attribute_names(entity)
49            .iter()
50            .position(|name| name.eq_ignore_ascii_case(attribute))
51    }
52
53    fn bind(version: SchemaVersion) -> Result<Self, SchemaResolutionError> {
54        let schema =
55            for_version(version).map_err(|_| SchemaResolutionError::UnsupportedSchema {
56                schema: version.release_id().to_owned(),
57            })?;
58        Ok(Self { version, schema })
59    }
60}
61
62/// Releases every reader in this crate is verified against its own table.
63///
64/// IFC2X3 and IFC4 since #52; IFC4X3 since #215: the zone readers in #194,
65/// the system, port, connectivity and flow readers by `tests/ifc4x3.rs`,
66/// which round-trips each through STEP text, and by `slots_hold_in_every_verified_release`
67/// below, which pins every fixed slot against each table. IFC4X1 and IFC4X2
68/// are bundled but unverified here, so they are refused.
69const VERIFIED: &[SchemaVersion] = &[
70    SchemaVersion::Ifc2x3,
71    SchemaVersion::Ifc4,
72    SchemaVersion::Ifc4x3,
73];
74
75/// Resolve the IFC release a model declares, from its `FILE_SCHEMA` header.
76///
77/// This is the seam every read in this crate goes through: [`crate::systems`],
78/// [`crate::ports`], [`crate::zones`], [`crate::ConnectionGraph::build`],
79/// [`crate::ElementRole::of`], [`crate::role_inconsistencies`] and
80/// [`crate::spatial_placements`] all refuse exactly what this refuses, with
81/// the same error. Nothing is read against a release the file did not
82/// declare.
83///
84/// # Errors
85///
86/// [`SchemaResolutionError`] when the header names no schema, more than one,
87/// or a release this crate has not verified (anything but IFC2X3, IFC4 and
88/// IFC4X3), or one this build does not bundle.
89pub fn schema_of(model: &Model) -> Result<SchemaVersion, SchemaResolutionError> {
90    resolve(model).map(|release| release.version)
91}
92
93/// Internal resolution: version tag plus the bundled table to read against.
94pub(crate) fn resolve(model: &Model) -> Result<Release, SchemaResolutionError> {
95    match model.header().schema.as_slice() {
96        [] => Err(SchemaResolutionError::MissingSchema),
97        [token] => match SchemaVersion::from_header_token(token) {
98            Some(version) if VERIFIED.contains(&version) => Release::bind(version),
99            _ => Err(SchemaResolutionError::UnsupportedSchema {
100                schema: token.clone(),
101            }),
102        },
103        schemas => Err(SchemaResolutionError::MultipleSchemas {
104            schemas: schemas.len(),
105        }),
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112
113    /// Every fixed slot position these readers use, by entity and attribute,
114    /// holds in each verified release's own table. A release whose layout
115    /// moved one of them must fail here before it is added to `VERIFIED`.
116    #[test]
117    fn slots_hold_in_every_verified_release() {
118        use crate::connectivity::relation::slot as connects;
119        use crate::port::definition::slot as port;
120        use crate::system::group::slot as group;
121        use crate::system::services::slot as services;
122        use crate::zone::spatial_group::slot as spatial;
123        let pinned = [
124            (
125                "IFCRELASSIGNSTOGROUP",
126                "RelatedObjects",
127                group::ASSIGNS_RELATED,
128            ),
129            (
130                "IFCRELASSIGNSTOGROUP",
131                "RelatingGroup",
132                group::ASSIGNS_GROUP,
133            ),
134            ("IFCRELCONNECTSPORTS", "RelatingPort", connects::RELATING),
135            ("IFCRELCONNECTSPORTS", "RelatedPort", connects::RELATED),
136            (
137                "IFCRELCONNECTSPORTS",
138                "RealizingElement",
139                connects::REALIZING,
140            ),
141            ("IFCRELNESTS", "RelatingObject", port::NESTS_PARENT),
142            ("IFCRELNESTS", "RelatedObjects", port::NESTS_CHILDREN),
143            (
144                "IFCRELCONNECTSPORTTOELEMENT",
145                "RelatingPort",
146                port::PORT_TO_ELEMENT_PORT,
147            ),
148            (
149                "IFCRELCONNECTSPORTTOELEMENT",
150                "RelatedElement",
151                port::PORT_TO_ELEMENT_ELEMENT,
152            ),
153            ("IFCDISTRIBUTIONPORT", "FlowDirection", port::FLOW_DIRECTION),
154            (
155                "IFCRELCONTAINEDINSPATIALSTRUCTURE",
156                "RelatedElements",
157                spatial::RELATED_ELEMENTS,
158            ),
159            (
160                "IFCRELCONTAINEDINSPATIALSTRUCTURE",
161                "RelatingStructure",
162                spatial::RELATING_STRUCTURE,
163            ),
164            (
165                "IFCRELREFERENCEDINSPATIALSTRUCTURE",
166                "RelatedElements",
167                spatial::RELATED_ELEMENTS,
168            ),
169            (
170                "IFCRELREFERENCEDINSPATIALSTRUCTURE",
171                "RelatingStructure",
172                spatial::RELATING_STRUCTURE,
173            ),
174            (
175                "IFCRELSERVICESBUILDINGS",
176                "RelatingSystem",
177                services::RELATING_SYSTEM,
178            ),
179            (
180                "IFCRELSERVICESBUILDINGS",
181                "RelatedBuildings",
182                services::RELATED_BUILDINGS,
183            ),
184            ("IFCSYSTEM", "Name", group::NAME),
185            ("IFCDISTRIBUTIONPORT", "Name", port::NAME),
186        ];
187        let mut checked = 0;
188        for &version in VERIFIED {
189            let release = Release::bind(version).expect("verified releases are bundled");
190            for (entity, attribute, slot) in pinned {
191                assert_eq!(
192                    release.slot(entity, attribute),
193                    Some(slot),
194                    "{version:?} {entity}.{attribute}"
195                );
196                checked += 1;
197            }
198        }
199        assert_eq!(checked, 3 * pinned.len());
200    }
201
202    #[test]
203    fn unbound_and_unverified_headers_are_refused() {
204        let mut model = Model::new();
205        assert!(matches!(
206            resolve(&model),
207            Err(SchemaResolutionError::MissingSchema)
208        ));
209        for token in ["IFC4X1", "IFC4X2", "IFC9"] {
210            model.header_mut().schema = vec![token.to_owned()];
211            assert!(
212                matches!(resolve(&model), Err(SchemaResolutionError::UnsupportedSchema { ref schema }) if schema == token),
213                "{token}"
214            );
215        }
216        model.header_mut().schema = vec!["IFC4".into(), "IFC2X3".into()];
217        assert!(matches!(
218            resolve(&model),
219            Err(SchemaResolutionError::MultipleSchemas { schemas: 2 })
220        ));
221        model.header_mut().schema = vec!["IFC4X3_ADD2".into()];
222        assert_eq!(schema_of(&model), Ok(SchemaVersion::Ifc4x3));
223    }
224}