ifc_lite_core/slot.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Typed attribute slots: the named, kind-checked replacement for a literal
6//! attribute index (F3e-0b, #7780).
7//!
8//! ```
9//! use ifc_lite_core::{slot, EntityDecoder};
10//!
11//! let content = "#1=IFCPROJECT('guid',$,'P',$,$,$,$,$,#9);";
12//! let mut decoder = EntityDecoder::new(content);
13//! let project = decoder.decode_by_id(1).unwrap();
14//! assert_eq!(project.string_at(slot::IfcProject::NAME), Some("P"));
15//! assert_eq!(project.ref_at(slot::IfcProject::UNITS_IN_CONTEXT), Some(9));
16//! ```
17//!
18//! There is one zero-sized struct per entity ([`IfcProject`] and the other
19//! 1,000 in [`crate::generated::slots`]), with the supertype's attributes
20//! flattened in, so `slot::IfcWall::OBJECT_PLACEMENT` exists. Each const names
21//! one attribute and carries the kind of value it holds ([`kind`]).
22//!
23//! * [`Slot`] has the same position in every bundled schema that declares the
24//! entity (a "trailing" slot is one past the end of the older schemas'
25//! records, which reads as `None` either way). It converts to its index at
26//! compile time, so a read is the same instruction as the literal it
27//! replaces.
28//! * [`SchemaSlot`] moves between schemas (or names something else). It has
29//! no `index()`: it can only be read after it is resolved against a
30//! [`SchemaVersion`], by [`SchemaSlot::at`] with an explicit pin or by
31//! [`crate::EntityDecoder::slot`] with the source's own schema. Resolve it
32//! once, outside any per-entity loop.
33//!
34//! The typed accessors on [`DecodedEntity`] take `impl Into<SlotIx<K>>`: a
35//! `Slot<K>` of the matching kind (a `Slot<Select>` fits any kind), or a
36//! computed `usize` for generic walkers. The old `get_*(usize)` readers stay.
37//! The generated positions are checked against the registries by tests, and in
38//! debug builds every typed accessor asserts that the entity is the slot's
39//! owner or one of its subtypes.
40
41use crate::generated::{IfcType, SchemaVersion};
42use crate::schema_gen::{AttributeValue, DecodedEntity};
43use std::fmt;
44use std::marker::PhantomData;
45
46pub use crate::generated::slots::*;
47
48/// Value kinds a [`Slot`] can carry. Mirrors [`crate::AttrKind`].
49pub mod kind {
50 macro_rules! kinds {
51 ($($(#[$doc:meta])* $name:ident),* $(,)?) => {
52 $($(#[$doc])* #[derive(Debug, Clone, Copy)] pub struct $name;)*
53 };
54 }
55 kinds! {
56 /// An entity reference (or a select of entities only).
57 Ref,
58 /// A list of entity references.
59 RefList,
60 /// Any other aggregate.
61 List,
62 /// REAL or NUMBER.
63 Real,
64 /// INTEGER.
65 Int,
66 /// STRING.
67 Text,
68 /// An ENUMERATION.
69 Enum,
70 /// BOOLEAN or LOGICAL.
71 Logical,
72 /// BINARY.
73 Binary,
74 /// A select mixing entities with value types, or an attribute whose
75 /// kind differs between schemas. Fits every typed accessor.
76 Select,
77 }
78}
79
80use kind::{Binary, Enum, Int, List, Logical, Real, Ref, RefList, Select, Text};
81
82/// `by_schema` entry for a schema that does not declare the entity or the
83/// attribute.
84pub const ABSENT: u8 = u8::MAX;
85
86/// A named attribute position that is the same in every bundled schema.
87pub struct Slot<K> {
88 index: u8,
89 #[cfg(debug_assertions)]
90 owner: u32,
91 _kind: PhantomData<fn() -> K>,
92}
93
94impl<K> Slot<K> {
95 /// Used by the generated slot tables: the STEP record position and the
96 /// CRC32 id of the entity the slot belongs to.
97 #[doc(hidden)]
98 pub const fn new(index: u8, owner: u32) -> Self {
99 #[cfg(not(debug_assertions))]
100 let _ = owner;
101 Self {
102 index,
103 #[cfg(debug_assertions)]
104 owner,
105 _kind: PhantomData,
106 }
107 }
108
109 /// The position in the STEP record, as `DecodedEntity::get` indexes it.
110 pub const fn index(self) -> usize {
111 self.index as usize
112 }
113}
114
115/// A named attribute position that moves between schemas. Resolve it with
116/// [`SchemaSlot::at`] (an explicit pin) or [`crate::EntityDecoder::slot`]
117/// (the source's own schema); there is deliberately no `index()`.
118pub struct SchemaSlot<K> {
119 by_schema: [u8; 5],
120 owner: u32,
121 _kind: PhantomData<fn() -> K>,
122}
123
124impl<K> SchemaSlot<K> {
125 /// Used by the generated slot tables: the position per schema in
126 /// [`SchemaVersion`] declaration order ([`ABSENT`] when the schema has no
127 /// such attribute) and the CRC32 id of the owning entity.
128 #[doc(hidden)]
129 pub const fn new(by_schema: [u8; 5], owner: u32) -> Self {
130 Self {
131 by_schema,
132 owner,
133 _kind: PhantomData,
134 }
135 }
136
137 /// Whether `schema` declares the entity this slot belongs to at all,
138 /// whether or not the entity has this attribute there (`IfcLinearPlacement`
139 /// is declared from IFC4X1 on; `IfcAlignment` too).
140 pub fn entity_declared_in(self, schema: SchemaVersion) -> bool {
141 IfcType::from_id(self.owner).is_some_and(|owner| schema.attribute_names(owner.as_str()).is_some())
142 }
143
144 /// The slot as `schema` lays it out, or `None` when that schema has no
145 /// such attribute (for example `IfcSpace.InteriorOrExteriorSpace` after
146 /// IFC2X3). Pin a schema explicitly only where the entity exists in
147 /// that family alone, and say why in a comment.
148 pub const fn at(self, schema: SchemaVersion) -> Option<Slot<K>> {
149 let index = self.by_schema[schema_ordinal(schema)];
150 if index == ABSENT {
151 None
152 } else {
153 Some(Slot::new(index, self.owner))
154 }
155 }
156}
157
158/// `by_schema` position of `schema`: [`SchemaVersion`] declaration order.
159const fn schema_ordinal(schema: SchemaVersion) -> usize {
160 match schema {
161 SchemaVersion::Ifc2x3 => 0,
162 SchemaVersion::Ifc4 => 1,
163 SchemaVersion::Ifc4x1 => 2,
164 SchemaVersion::Ifc4x2 => 3,
165 // A newer schema (the enum is non-exhaustive) reads as the newest
166 // bundled layout, like an undeclared FILE_SCHEMA does.
167 _ => 4,
168 }
169}
170
171/// A position the typed accessors read: a [`Slot`] of kind `K` (or
172/// [`Select`]), or a computed `usize`.
173pub struct SlotIx<K> {
174 index: usize,
175 #[cfg(debug_assertions)]
176 owner: u32,
177 _kind: PhantomData<fn() -> K>,
178}
179
180impl<K> SlotIx<K> {
181 #[inline(always)]
182 fn of_slot<S>(slot: Slot<S>) -> Self {
183 Self {
184 index: slot.index(),
185 #[cfg(debug_assertions)]
186 owner: slot.owner,
187 _kind: PhantomData,
188 }
189 }
190
191 /// Resolve against `entity`; debug builds check the slot's owner.
192 #[inline(always)]
193 fn at(self, entity: &DecodedEntity) -> usize {
194 #[cfg(debug_assertions)]
195 assert_owner(entity, self.owner, self.index);
196 #[cfg(not(debug_assertions))]
197 let _ = entity;
198 self.index
199 }
200}
201
202impl<K> From<usize> for SlotIx<K> {
203 #[inline(always)]
204 fn from(index: usize) -> Self {
205 Self {
206 index,
207 #[cfg(debug_assertions)]
208 owner: 0,
209 _kind: PhantomData,
210 }
211 }
212}
213
214macro_rules! slot_kinds {
215 ($($k:ident),* $(,)?) => {$(
216 impl From<Slot<$k>> for SlotIx<$k> {
217 #[inline(always)]
218 fn from(slot: Slot<$k>) -> Self { Self::of_slot(slot) }
219 }
220 impl From<Slot<Select>> for SlotIx<$k> {
221 #[inline(always)]
222 fn from(slot: Slot<Select>) -> Self { Self::of_slot(slot) }
223 }
224 )*};
225}
226slot_kinds!(Ref, RefList, List, Real, Int, Text, Enum, Logical, Binary);
227
228impl From<Slot<Select>> for SlotIx<Select> {
229 #[inline(always)]
230 fn from(slot: Slot<Select>) -> Self {
231 Self::of_slot(slot)
232 }
233}
234
235/// Any position [`DecodedEntity::attr`] reads, whatever its kind: a
236/// [`Slot`] of any kind, or a computed `usize`.
237pub trait AnySlot {
238 /// This position without its kind.
239 fn into_any(self) -> SlotIx<Select>;
240}
241
242impl AnySlot for usize {
243 #[inline(always)]
244 fn into_any(self) -> SlotIx<Select> {
245 self.into()
246 }
247}
248
249impl<K> AnySlot for Slot<K> {
250 #[inline(always)]
251 fn into_any(self) -> SlotIx<Select> {
252 SlotIx::of_slot(self)
253 }
254}
255
256impl<K> Clone for Slot<K> {
257 fn clone(&self) -> Self {
258 *self
259 }
260}
261impl<K> Copy for Slot<K> {}
262
263impl<K> fmt::Debug for Slot<K> {
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 write!(f, "Slot({})", self.index)
266 }
267}
268
269impl<K> PartialEq for Slot<K> {
270 fn eq(&self, other: &Self) -> bool {
271 self.index == other.index
272 }
273}
274impl<K> Eq for Slot<K> {}
275
276impl<K> Clone for SchemaSlot<K> {
277 fn clone(&self) -> Self {
278 *self
279 }
280}
281impl<K> Copy for SchemaSlot<K> {}
282
283impl<K> fmt::Debug for SchemaSlot<K> {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285 write!(f, "SchemaSlot({:?})", self.by_schema)
286 }
287}
288
289/// Debug builds only: the entity must be the slot's owner or a subtype of it,
290/// in at least one bundled schema's hierarchy. The whole test suite therefore
291/// checks that each migrated slot belongs to the record it reads.
292#[cfg(debug_assertions)]
293fn assert_owner(entity: &DecodedEntity, owner: u32, index: usize) {
294 let Some(owner_type) = IfcType::from_id(owner) else {
295 return;
296 };
297 // An unknown keyword has no hierarchy to check.
298 if matches!(entity.ifc_type, IfcType::Unknown(_)) || entity.ifc_type == owner_type {
299 return;
300 }
301 let (child, parent) = (entity.ifc_type.as_str(), owner_type.as_str());
302 const ALL: [SchemaVersion; 5] = [
303 SchemaVersion::Ifc2x3,
304 SchemaVersion::Ifc4,
305 SchemaVersion::Ifc4x1,
306 SchemaVersion::Ifc4x2,
307 SchemaVersion::Ifc4x3,
308 ];
309 assert!(
310 ALL.iter().any(|schema| schema.is_subtype_of(child, parent)),
311 "slot {index} belongs to {parent} but was read from #{} {child}",
312 entity.id
313 );
314}
315
316impl DecodedEntity {
317 /// The raw value at a slot or computed position.
318 #[inline]
319 pub fn attr(&self, slot: impl AnySlot) -> Option<&AttributeValue> {
320 self.get(slot.into_any().at(self))
321 }
322
323 /// An entity reference (`$` and wrong shapes read as `None`).
324 #[inline]
325 pub fn ref_at(&self, slot: impl Into<SlotIx<Ref>>) -> Option<u32> {
326 self.get(slot.into().at(self)).and_then(AttributeValue::as_entity_ref)
327 }
328
329 /// Reference members of a list, with [`DecodedEntity::get_refs`]
330 /// semantics: a bare reference is a one-element list, an
331 /// `IfcPropertySetDefinitionSet` typed parameter is its set, non-reference
332 /// members are skipped, and an empty result is `None`.
333 #[inline]
334 pub fn ref_list_at(&self, slot: impl Into<SlotIx<RefList>>) -> Option<Vec<u32>> {
335 self.get_refs(slot.into().at(self))
336 }
337
338 /// A REAL (an INTEGER widens, a typed wrapper such as
339 /// `IFCLENGTHMEASURE(2.)` is seen through), as [`AttributeValue::as_float`].
340 #[inline]
341 pub fn real_at(&self, slot: impl Into<SlotIx<Real>>) -> Option<f64> {
342 self.get_float(slot.into().at(self))
343 }
344
345 /// An INTEGER, as [`AttributeValue::as_int`].
346 #[inline]
347 pub fn int_at(&self, slot: impl Into<SlotIx<Int>>) -> Option<i64> {
348 self.get(slot.into().at(self)).and_then(AttributeValue::as_int)
349 }
350
351 /// A STRING, its STEP escapes already decoded (as [`DecodedEntity::get_string`]).
352 #[inline]
353 pub fn string_at(&self, slot: impl Into<SlotIx<Text>>) -> Option<&str> {
354 self.get_string(slot.into().at(self))
355 }
356
357 /// An enumeration literal without its dots (`.ELEMENT.` reads `ELEMENT`).
358 #[inline]
359 pub fn enum_at(&self, slot: impl Into<SlotIx<Enum>>) -> Option<&str> {
360 self.get(slot.into().at(self)).and_then(AttributeValue::as_enum)
361 }
362
363 /// A BOOLEAN or LOGICAL as a definite boolean, with
364 /// [`DecodedEntity::get_bool`] semantics (one meaning, F3c): `.T.` is
365 /// `true`, `.F.` is `false`, `.U.` (unknown), `$` and anything else are
366 /// `None`.
367 #[inline]
368 pub fn logical_at(&self, slot: impl Into<SlotIx<Logical>>) -> Option<bool> {
369 self.get_bool(slot.into().at(self))
370 }
371
372 /// A BINARY literal's raw content, undecoded (see
373 /// [`crate::decode_step_binary`]).
374 #[inline]
375 pub fn binary_at(&self, slot: impl Into<SlotIx<Binary>>) -> Option<&str> {
376 self.get(slot.into().at(self)).and_then(AttributeValue::as_binary_hex)
377 }
378
379 /// An aggregate's members.
380 #[inline]
381 pub fn list_at(&self, slot: impl Into<SlotIx<List>>) -> Option<&[AttributeValue]> {
382 self.get_list(slot.into().at(self))
383 }
384}
385
386#[cfg(test)]
387#[path = "slot_tests.rs"]
388pub(crate) mod tests;