Skip to main content

openbim_ifc_binding_core/
relations.rs

1//! Entities by `GlobalId`, new `GlobalId`s, and an object's type, a type's
2//! occurrences and the openings and fillings of elements (#463).
3//!
4//! Every operation reads against the release the header declares and is
5//! refused with `unsupported-schema` when it names no bundled release.
6//!
7//! [`IfcModel::by_guid`] keeps the facade's `GlobalIdIndex` beside the
8//! model, built on the first lookup and again only after the model or its
9//! header changes, so a host looking up many `GlobalId`s pays one pass. A
10//! `GlobalId` several entities carry is refused with `invalid-model`
11//! naming all of them, never answered with one;
12//! [`IfcModel::duplicate_global_ids`] lists every such `GlobalId`.
13//!
14//! The relation queries refuse an id the model lacks (`missing-entity`),
15//! an entity of a type the query does not accept (`wrong-entity-type`), a
16//! malformed relationship or several answers where the schema allows one
17//! (`invalid-model`), and an answer the model lacks (`missing-reference`).
18
19use std::sync::Mutex;
20
21use ifc::{EntityId, GlobalIdIndex, Guid, GuidError, ObjectRelationError};
22
23use crate::value::Tagged;
24use crate::{BindingError, IfcModel};
25
26/// One `GlobalId` several entities carry.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct DuplicateGlobalId {
29    /// The shared `GlobalId`.
30    pub global_id: String,
31    /// Every entity that carries it, in file order.
32    pub ids: Vec<u64>,
33}
34
35/// The facade's index, and the model state it was built from.
36#[derive(Debug)]
37pub(crate) struct CachedIndex {
38    revision: u64,
39    schema: Option<String>,
40    index: GlobalIdIndex,
41}
42
43/// The cache slot [`IfcModel`] carries.
44#[derive(Debug, Default)]
45pub(crate) struct GuidCache(Mutex<Option<CachedIndex>>);
46
47impl IfcModel {
48    /// The entity whose `GlobalId` is `global_id`, or `None` when none.
49    ///
50    /// Refused with `invalid-value` when `global_id` is not 22 characters
51    /// of IFC's alphabet, and with `invalid-model` when several entities
52    /// carry it.
53    pub fn by_guid(&self, global_id: &str) -> Result<Option<u64>, BindingError> {
54        let guid = parse_guid(global_id)?;
55        self.with_index(|index| {
56            index
57                .get(&guid)
58                .map(|found| found.map(|EntityId(id)| id))
59                .map_err(|duplicate| BindingError::InvalidModel(duplicate.to_string()))
60        })
61    }
62
63    /// Every `GlobalId` several entities carry, in `GlobalId` order, each
64    /// with its holders in file order. Empty for a conformant file.
65    pub fn duplicate_global_ids(&self) -> Result<Vec<DuplicateGlobalId>, BindingError> {
66        self.with_index(|index| {
67            Ok(index
68                .duplicates()
69                .map(|(guid, ids)| DuplicateGlobalId {
70                    global_id: guid.to_string(),
71                    ids: ids.iter().map(|EntityId(id)| *id).collect(),
72                })
73                .collect())
74        })
75    }
76
77    /// The type object of `occurrence` (`IfcRelDefinesByType`), or `None`.
78    pub fn type_object(&self, occurrence: u64) -> Result<Option<u64>, BindingError> {
79        let schema = self.declared_schema()?;
80        ifc::type_of(&self.inner, schema, EntityId(occurrence))
81            .map(|found| found.map(|EntityId(id)| id))
82            .map_err(relation_error)
83    }
84
85    /// Every object `type_object` types, in file order.
86    pub fn occurrences_of(&self, type_object: u64) -> Result<Vec<u64>, BindingError> {
87        let schema = self.declared_schema()?;
88        ifc::occurrences_of(&self.inner, schema, EntityId(type_object))
89            .map(raw)
90            .map_err(relation_error)
91    }
92
93    /// Every opening voiding `element` (`IfcRelVoidsElement`), in file
94    /// order.
95    pub fn openings_of(&self, element: u64) -> Result<Vec<u64>, BindingError> {
96        let schema = self.declared_schema()?;
97        ifc::openings_of(&self.inner, schema, EntityId(element))
98            .map(raw)
99            .map_err(relation_error)
100    }
101
102    /// Every element filling `opening` (`IfcRelFillsElement`), in file
103    /// order.
104    pub fn fillings_of(&self, opening: u64) -> Result<Vec<u64>, BindingError> {
105        let schema = self.declared_schema()?;
106        ifc::fillings_of(&self.inner, schema, EntityId(opening))
107            .map(raw)
108            .map_err(relation_error)
109    }
110
111    /// The element `opening` voids (`IfcRelVoidsElement`), or `None`.
112    pub fn voided_element_of(&self, opening: u64) -> Result<Option<u64>, BindingError> {
113        let schema = self.declared_schema()?;
114        ifc::voided_element_of(&self.inner, schema, EntityId(opening))
115            .map(|found| found.map(|EntityId(id)| id))
116            .map_err(relation_error)
117    }
118
119    /// Run `answer` against the cached index, rebuilding it first when the
120    /// model or its declared release changed since it was built.
121    fn with_index<T>(
122        &self,
123        answer: impl FnOnce(&GlobalIdIndex) -> Result<T, BindingError>,
124    ) -> Result<T, BindingError> {
125        let schema = self.declared_schema()?;
126        let revision = self.inner.revision();
127        let token = self.schema().map(str::to_owned);
128        // A poisoned lock only means another thread panicked mid-build; the
129        // slot is rebuilt below whatever it holds.
130        let mut slot = self
131            .guid_index
132            .0
133            .lock()
134            .unwrap_or_else(std::sync::PoisonError::into_inner);
135        let current = slot
136            .as_ref()
137            .is_some_and(|cached| cached.revision == revision && cached.schema == token);
138        if !current {
139            *slot = Some(CachedIndex {
140                revision,
141                schema: token,
142                index: GlobalIdIndex::build(&self.inner, schema),
143            });
144        }
145        answer(&slot.as_ref().expect("built above").index)
146    }
147}
148
149/// A new random `GlobalId` (RFC 9562 version 4) in IFC's 22-character
150/// form.
151///
152/// Refused with `unsupported` when the build or host has no random source:
153/// a WebAssembly build without the facade's `js-random` feature, or a
154/// JavaScript host without `crypto.getRandomValues` (Node 18).
155pub fn new_guid() -> Result<String, BindingError> {
156    ifc::new_guid()
157        .map(|guid| guid.to_string())
158        .map_err(|error: GuidError| BindingError::Unsupported(error.to_string()))
159}
160
161/// A fresh seed for one unseeded batch.
162///
163/// Refused with `unsupported` when the build or host has no random source,
164/// as [`new_guid`] is.
165pub(crate) fn fresh_seed() -> Result<u128, BindingError> {
166    ifc::fresh_seed().map_err(|error: GuidError| BindingError::Unsupported(error.to_string()))
167}
168
169/// The `GlobalId` named by `parts` (RFC 9562 version 8): the same parts
170/// give the same `GlobalId` in every host and release.
171pub fn name_based_guid<S: AsRef<str>>(parts: &[S]) -> String {
172    let parts: Vec<&str> = parts.iter().map(AsRef::as_ref).collect();
173    ifc::name_based_guid(&parts).to_string()
174}
175
176/// The duplicates as one tagged `list`, each a `list` of the `GlobalId`
177/// (text) and its holders (`list` of `ref`). The C binding's tape form.
178pub fn duplicates_to_tagged(duplicates: &[DuplicateGlobalId]) -> Tagged {
179    Tagged::List(
180        duplicates
181            .iter()
182            .map(|duplicate| {
183                Tagged::List(vec![
184                    Tagged::Text(duplicate.global_id.clone()),
185                    Tagged::List(duplicate.ids.iter().copied().map(Tagged::Ref).collect()),
186                ])
187            })
188            .collect(),
189    )
190}
191
192fn parse_guid(text: &str) -> Result<Guid, BindingError> {
193    Guid::parse(text).ok_or_else(|| {
194        BindingError::InvalidValue(format!(
195            "{text:?} is not a GlobalId: 22 characters of 0-9, A-Z, a-z, _ and $, the first 0-3"
196        ))
197    })
198}
199
200fn raw(ids: Vec<EntityId>) -> Vec<u64> {
201    ids.into_iter().map(|EntityId(id)| id).collect()
202}
203
204fn relation_error(error: ObjectRelationError) -> BindingError {
205    match error {
206        ObjectRelationError::MissingEntity(EntityId(id)) => BindingError::MissingEntity(id),
207        ObjectRelationError::WrongEntityType { .. } => {
208            BindingError::WrongEntityType(error.to_string())
209        }
210        ObjectRelationError::MissingReference { .. } => {
211            BindingError::MissingReference(error.to_string())
212        }
213        // Malformed, ambiguous, and any refusal added after this binding.
214        _ => BindingError::InvalidModel(error.to_string()),
215    }
216}