Skip to main content

ifc_material/
release.rs

1//! The IFC release a model's material records are read and written against.
2//!
3//! Every slot position comes from the bundled table of one release, so an
4//! IFC2X3 record is never decoded or authored with IFC4 positions.
5//!
6//! Binding, from `FILE_SCHEMA`:
7//! - one recognised declaration (`IFC2X3`, `IFC4`, `IFC4X3`/`IFC4X3_ADD2`)
8//!   binds that release's own table;
9//! - one unrecognised declaration fails closed with
10//!   [`MaterialError::UnsupportedSchema`];
11//! - several declarations fail closed with [`MaterialError::MultipleSchemas`];
12//! - no declaration at all (an in-memory [`Model::new`]) binds IFC4, the
13//!   0.2.0 behaviour, as `ifc-classification` does since #51.
14
15use ifc_model::{Entity, EntityId, Model, Value};
16use ifc_schema::{for_version, Attribute, Schema, SchemaVersion};
17
18use crate::{MaterialError, MaterialResult};
19
20/// Every attribute this crate reads or writes, per entity, under its IFC4
21/// ADD2 TC1 name and in IFC4 positional order (inherited attributes first).
22///
23/// This is the IFC4 layout the crate was written against. Accessors never
24/// index it: they ask the bound release for the attribute's position by
25/// name. `release_layout` tests pin it against the three bundled tables.
26pub(crate) const IFC4_LAYOUT: &[(&str, &[&str])] = &[
27    ("IFCMATERIAL", &["Name", "Description", "Category"]),
28    (
29        "IFCMATERIALCLASSIFICATIONRELATIONSHIP",
30        &["MaterialClassifications", "ClassifiedMaterial"],
31    ),
32    (
33        "IFCMATERIALCONSTITUENT",
34        &["Name", "Description", "Material", "Fraction", "Category"],
35    ),
36    (
37        "IFCMATERIALCONSTITUENTSET",
38        &["Name", "Description", "MaterialConstituents"],
39    ),
40    (
41        "IFCMATERIALDEFINITIONREPRESENTATION",
42        &[
43            "Name",
44            "Description",
45            "Representations",
46            "RepresentedMaterial",
47        ],
48    ),
49    ("IFCMATERIALLAYER", LAYER),
50    (
51        "IFCMATERIALLAYERSET",
52        &["MaterialLayers", "LayerSetName", "Description"],
53    ),
54    (
55        "IFCMATERIALLAYERSETUSAGE",
56        &[
57            "ForLayerSet",
58            "LayerSetDirection",
59            "DirectionSense",
60            "OffsetFromReferenceLine",
61            "ReferenceExtent",
62        ],
63    ),
64    (
65        "IFCMATERIALLAYERWITHOFFSETS",
66        &[
67            "Material",
68            "LayerThickness",
69            "IsVentilated",
70            "Name",
71            "Description",
72            "Category",
73            "Priority",
74            "OffsetDirection",
75            "OffsetValues",
76        ],
77    ),
78    ("IFCMATERIALLIST", &["Materials"]),
79    ("IFCMATERIALPROFILE", PROFILE),
80    (
81        "IFCMATERIALPROFILESET",
82        &[
83            "Name",
84            "Description",
85            "MaterialProfiles",
86            "CompositeProfile",
87        ],
88    ),
89    ("IFCMATERIALPROFILESETUSAGE", PROFILE_USAGE),
90    (
91        "IFCMATERIALPROFILESETUSAGETAPERING",
92        &[
93            "ForProfileSet",
94            "CardinalPoint",
95            "ReferenceExtent",
96            "ForProfileEndSet",
97            "CardinalEndPoint",
98        ],
99    ),
100    (
101        "IFCMATERIALPROFILEWITHOFFSETS",
102        &[
103            "Name",
104            "Description",
105            "Material",
106            "Profile",
107            "Priority",
108            "Category",
109            "OffsetValues",
110        ],
111    ),
112    (
113        "IFCMATERIALPROPERTIES",
114        &["Name", "Description", "Properties", "Material"],
115    ),
116    (
117        "IFCMATERIALRELATIONSHIP",
118        &[
119            "Name",
120            "Description",
121            "RelatingMaterial",
122            "RelatedMaterials",
123            "Expression",
124        ],
125    ),
126    ("IFCRELASSOCIATESMATERIAL", ROOT_RELATION_MATERIAL),
127    ("IFCRELDEFINESBYTYPE", ROOT_RELATION_TYPE),
128];
129
130const LAYER: &[&str] = &[
131    "Material",
132    "LayerThickness",
133    "IsVentilated",
134    "Name",
135    "Description",
136    "Category",
137    "Priority",
138];
139const PROFILE: &[&str] = &[
140    "Name",
141    "Description",
142    "Material",
143    "Profile",
144    "Priority",
145    "Category",
146];
147const PROFILE_USAGE: &[&str] = &["ForProfileSet", "CardinalPoint", "ReferenceExtent"];
148const ROOT_RELATION_MATERIAL: &[&str] = &[
149    "GlobalId",
150    "OwnerHistory",
151    "Name",
152    "Description",
153    "RelatedObjects",
154    "RelatingMaterial",
155];
156const ROOT_RELATION_TYPE: &[&str] = &[
157    "GlobalId",
158    "OwnerHistory",
159    "Name",
160    "Description",
161    "RelatedObjects",
162    "RelatingType",
163];
164
165/// The release a projection or authoring call binds to, or why none could be.
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub(crate) enum Release<'m> {
168    /// Reads and writes resolve against this release's bundled table.
169    Bound(SchemaVersion),
170    /// The header declares this many schemas.
171    Multiple(usize),
172    /// The header declares one schema this crate has no table for.
173    Unsupported(&'m str),
174}
175
176/// Releases this crate's layouts are proven against.
177///
178/// `ifc-schema` also bundles IFC4X1 and IFC4X2, but nothing here is verified
179/// against their tables, so a header declaring either is refused with the
180/// unsupported-schema error rather than read through a neighbour's layout.
181const fn proven(version: SchemaVersion) -> bool {
182    matches!(
183        version,
184        SchemaVersion::Ifc2x3 | SchemaVersion::Ifc4 | SchemaVersion::Ifc4x3
185    )
186}
187
188impl<'m> Release<'m> {
189    /// The binding of projections built without a model (`try_new`) and of
190    /// a model whose header declares no schema.
191    pub(crate) const LEGACY: Release<'static> = Release::Bound(SchemaVersion::Ifc4);
192
193    /// The release `model`'s header binds.
194    pub(crate) fn of(model: &'m Model) -> Self {
195        match model.header().schema.as_slice() {
196            [] => Release::LEGACY,
197            [token] => SchemaVersion::from_header_token(token)
198                .filter(|version| proven(*version))
199                .map_or(Self::Unsupported(token.as_str()), Self::Bound),
200            tokens => Self::Multiple(tokens.len()),
201        }
202    }
203
204    /// The bound version and its bundled table.
205    ///
206    /// A release whose table this build leaves out (its release feature is
207    /// off, #306) is refused as unsupported.
208    pub(crate) fn bound(self) -> MaterialResult<(SchemaVersion, &'static Schema)> {
209        match self {
210            Self::Bound(version) => match for_version(version) {
211                Ok(schema) => Ok((version, schema)),
212                Err(_) => Err(MaterialError::UnsupportedSchema {
213                    schema: version.header_tokens()[0].to_owned(),
214                }),
215            },
216            Self::Multiple(schemas) => Err(MaterialError::MultipleSchemas { schemas }),
217            Self::Unsupported(schema) => Err(MaterialError::UnsupportedSchema {
218                schema: schema.to_owned(),
219            }),
220        }
221    }
222
223    /// Whether the bound release declares `entity` as an instantiable
224    /// (non-abstract) entity. `false` when no release is bound.
225    pub(crate) fn instantiates(self, entity: &str) -> bool {
226        self.bound()
227            .is_ok_and(|(_, schema)| instantiable(schema, entity))
228    }
229
230    /// Fail with [`MaterialError::EntityNotInSchema`] unless the bound
231    /// release can instantiate `entity`.
232    pub(crate) fn require_entity(
233        self,
234        entity: &'static str,
235        id: Option<EntityId>,
236    ) -> MaterialResult<(SchemaVersion, &'static Schema)> {
237        let (version, schema) = self.bound()?;
238        if instantiable(schema, entity) {
239            Ok((version, schema))
240        } else {
241            Err(MaterialError::EntityNotInSchema {
242                entity,
243                id,
244                schema: version,
245            })
246        }
247    }
248
249    /// Position and declaration of `attribute` (IFC4 name) on `entity` in
250    /// the bound release.
251    ///
252    /// A record type the release cannot instantiate is `EntityNotInSchema`;
253    /// an attribute it does not declare is `NotInSchema`. Neither is ever a
254    /// silent `None` read from a slot the release gives another meaning.
255    pub(crate) fn attribute(
256        self,
257        entity: &'static str,
258        id: EntityId,
259        attribute: &'static str,
260    ) -> MaterialResult<(usize, &'static Attribute)> {
261        debug_assert!(
262            in_ifc4_layout(entity, attribute),
263            "{entity}.{attribute} is read but missing from IFC4_LAYOUT"
264        );
265        let (version, schema) = self.require_entity(entity, Some(id))?;
266        position(schema, version, entity, attribute).ok_or(MaterialError::NotInSchema {
267            entity,
268            id,
269            attribute,
270            schema: version,
271        })
272    }
273
274    /// Position of `attribute` (IFC4 name) on `entity` in the bound release.
275    pub(crate) fn slot(
276        self,
277        entity: &'static str,
278        id: EntityId,
279        attribute: &'static str,
280    ) -> MaterialResult<usize> {
281        self.attribute(entity, id, attribute).map(|(slot, _)| slot)
282    }
283
284    /// Whether `candidate` is a legal value type of `attribute` on `entity`
285    /// in the bound release (entity inheritance and SELECTs included), and
286    /// instantiable there.
287    pub(crate) fn accepts(
288        self,
289        entity: &'static str,
290        attribute: &'static str,
291        candidate: &str,
292    ) -> MaterialResult<(bool, &'static str)> {
293        let (_, schema) = self.bound()?;
294        let declared = self.declared(entity, attribute)?.type_name.as_str();
295        Ok((
296            instantiable(schema, candidate) && schema.accepts_type(declared, candidate),
297            declared,
298        ))
299    }
300
301    /// The bound release's declaration of `attribute` (IFC4 name) on
302    /// `entity`, for authoring: `EntityNotInSchema` or
303    /// `AuthoringNotInSchema` when the release lacks either.
304    pub(crate) fn declared(
305        self,
306        entity: &'static str,
307        attribute: &'static str,
308    ) -> MaterialResult<&'static Attribute> {
309        let (version, schema) = self.require_entity(entity, None)?;
310        position(schema, version, entity, attribute)
311            .map(|(_, declared)| declared)
312            .ok_or(MaterialError::AuthoringNotInSchema {
313                entity,
314                attribute,
315                schema: version,
316            })
317    }
318
319    /// Build `entity`'s record in the bound release's layout from values
320    /// named by their IFC4 attribute names.
321    ///
322    /// A non-null value for an attribute the release does not declare is
323    /// refused with `AuthoringNotInSchema` rather than dropped; a null for
324    /// an attribute the release requires is refused with
325    /// `AuthoringRequired`.
326    pub(crate) fn record(
327        self,
328        entity: &'static str,
329        values: Vec<(&'static str, Value)>,
330    ) -> MaterialResult<Entity> {
331        let (version, schema) = self.require_entity(entity, None)?;
332        let declared = schema.attributes(entity);
333        let mut slots = vec![None; declared.len()];
334        for (attribute, value) in values {
335            debug_assert!(
336                in_ifc4_layout(entity, attribute),
337                "{entity}.{attribute} is written but missing from IFC4_LAYOUT"
338            );
339            match position(schema, version, entity, attribute) {
340                Some((slot, _)) => slots[slot] = Some(value),
341                None if value == Value::Null => {}
342                None => {
343                    return Err(MaterialError::AuthoringNotInSchema {
344                        entity,
345                        attribute,
346                        schema: version,
347                    })
348                }
349            }
350        }
351        let mut attributes = Vec::with_capacity(slots.len());
352        for (slot, value) in slots.into_iter().enumerate() {
353            let declaration = declared[slot];
354            match value.unwrap_or(Value::Null) {
355                Value::Null if !declaration.optional => {
356                    return Err(MaterialError::AuthoringRequired {
357                        entity,
358                        attribute: declaration.name.as_str(),
359                        schema: version,
360                    })
361                }
362                value => attributes.push(value),
363            }
364        }
365        Ok(Entity::new(entity, attributes))
366    }
367}
368
369fn instantiable(schema: &Schema, entity: &str) -> bool {
370    schema
371        .entity(entity)
372        .is_some_and(|declaration| !declaration.abstract_)
373}
374
375fn position(
376    schema: &'static Schema,
377    version: SchemaVersion,
378    entity: &str,
379    attribute: &'static str,
380) -> Option<(usize, &'static Attribute)> {
381    let name = release_name(version, entity, attribute);
382    schema
383        .attributes(entity)
384        .into_iter()
385        .enumerate()
386        .find(|(_, declared)| declared.name.eq_ignore_ascii_case(name))
387}
388
389fn in_ifc4_layout(entity: &str, attribute: &str) -> bool {
390    IFC4_LAYOUT.iter().any(|(declared, attributes)| {
391        declared.eq_ignore_ascii_case(entity) && attributes.contains(&attribute)
392    })
393}
394
395/// The name `release` gives the attribute this crate knows by its IFC4 name.
396///
397/// IFC4X3 ADD2 renamed `IfcMaterialRelationship.Expression` to
398/// `MaterialExpression`; it keeps its position (5th, after the two inherited
399/// `IfcResourceLevelRelationship` attributes) and meaning. No other material
400/// attribute is renamed between IFC2X3 TC1, IFC4 ADD2 TC1 and IFC4X3 ADD2.
401pub(crate) fn release_name(
402    release: SchemaVersion,
403    entity: &str,
404    attribute: &'static str,
405) -> &'static str {
406    match (release, attribute) {
407        (SchemaVersion::Ifc4x3, "Expression")
408            if entity.eq_ignore_ascii_case("IFCMATERIALRELATIONSHIP") =>
409        {
410            "MaterialExpression"
411        }
412        _ => attribute,
413    }
414}
415
416/// Whether `entity` is an instantiable `IfcTypeObject` in the bound
417/// release, the only legal `IfcRelDefinesByType.RelatingType`.
418///
419/// Read from the release's table: IFC4X3 removed `IfcDoorStyle` and
420/// `IfcWindowStyle`, and IFC2X3 has no `IfcTypeProcess` branch.
421pub(crate) fn is_type_object(release: Release<'_>, entity: &str) -> MaterialResult<bool> {
422    let (_, schema) = release.bound()?;
423    Ok(instantiable(schema, entity) && schema.is_a(entity, "IFCTYPEOBJECT"))
424}
425
426/// The IFC release `model`'s material records are read and written against.
427///
428/// A consumer binds its own vocabulary with this answer instead of
429/// re-parsing the header. A header with no declaration binds IFC4 (an
430/// in-memory model; the 0.2.0 behaviour).
431///
432/// # Errors
433///
434/// [`MaterialError::MultipleSchemas`] when the header declares several
435/// schemas, and [`MaterialError::UnsupportedSchema`] when it declares one
436/// this crate is not verified for (including IFC4X1 and IFC4X2).
437pub fn material_schema(model: &Model) -> MaterialResult<SchemaVersion> {
438    Release::of(model).bound().map(|(version, _)| version)
439}
440
441#[cfg(test)]
442mod tests;
443
444#[cfg(test)]
445mod intermediate_release_tests {
446    use super::*;
447
448    /// IFC4X1 and IFC4X2 have bundled tables but no verified layout here:
449    /// refused with the unsupported-schema error, never read as IFC4/IFC4X3.
450    #[test]
451    fn ifc4x1_and_ifc4x2_are_refused_not_aliased() {
452        for token in ["IFC4X1", "IFC4X2"] {
453            let mut model = Model::new();
454            model.header_mut().schema = vec![token.to_owned()];
455            assert!(
456                matches!(Release::of(&model).bound(), Err(MaterialError::UnsupportedSchema { schema }) if schema == token),
457                "{token} must be refused"
458            );
459        }
460    }
461}