Skip to main content

openbim_ifc_binding_core/
inverse.rs

1//! `INVERSE` attributes by name and the entities referencing one (#462).
2//!
3//! [`IfcModel::attribute_by_name`] resolves an `INVERSE` name
4//! (`IsDefinedBy`) through the facade's reverse index, with the `FOR`
5//! clause of the release the header declares: IFC2X3's `IsDefinedBy` holds
6//! type and property relationships, IFC4's only property ones beside a
7//! separate `IsTypedBy`. The value has the declared shape:
8//!
9//! - a `SET` or `BAG` inverse, `SET [0:1]` included (`ContainedInStructure`,
10//!   `Decomposes`), is a `list` of `ref`s in ascending id order, empty when
11//!   nothing references the entity: an optional single inverse is a list of
12//!   zero or one, never unwrapped;
13//! - a non-aggregate inverse (`VoidsElements`, IFC2X3's
14//!   `IfcGroup.IsGroupedBy`) is one `ref`, or `null` when nothing
15//!   references the entity; two or more are refused with `invalid-model`.
16//!
17//! [`IfcModel::inverse_attribute_names`] lists the declarations,
18//! [`IfcModel::inverse_references`] every entity referencing one with the
19//! attribute index it references through (IfcOpenShell's `get_inverse`
20//! with indices), and [`IfcModel::total_inverses`] counts the distinct
21//! referrers (`get_total_inverses`).
22//!
23//! The index is built on the first such read and again only after the
24//! model changes, so a host reading many inverses pays one pass. An
25//! `INVERSE` name holds no slot: a write to one is refused with
26//! `inverse-attribute`.
27
28use std::sync::{Arc, Mutex};
29
30use ifc::{AttributeValue, EntityId, InverseValue, NamedAttributeError, ReverseIndex};
31
32use crate::attribute::refused;
33use crate::record::{Field, Record, ToRecord};
34use crate::value::Tagged;
35use crate::{BindingError, IfcModel};
36
37/// One `INVERSE` attribute of an entity, as its declared release defines
38/// it.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct InverseAttributeInfo {
41    /// The declared name, in the schema's spelling (`IsDefinedBy`).
42    pub name: String,
43    /// The referencing entity type named before `FOR`; its subtypes count.
44    pub entity: String,
45    /// The attribute of `entity` named after `FOR` (`RelatedObjects`).
46    pub for_attribute: String,
47    /// Whether the inverse is a `SET` or `BAG` (read as a `list`) rather
48    /// than a single entity (read as a `ref` or `null`).
49    pub aggregate: bool,
50    /// The declared lower bound; `1` for a non-aggregate inverse.
51    pub lower: u64,
52    /// The declared upper bound, `None` for `?`; `Some(1)` for a
53    /// non-aggregate inverse.
54    pub upper: Option<u64>,
55    /// The entity whose declaration introduces the inverse.
56    pub declared_by: String,
57}
58
59impl ToRecord for InverseAttributeInfo {
60    fn to_record(&self) -> Record {
61        Record::new(
62            "InverseAttributeInfo",
63            vec![
64                ("name", Field::Text(self.name.clone())),
65                ("entity", Field::Text(self.entity.clone())),
66                ("for_attribute", Field::Text(self.for_attribute.clone())),
67                ("aggregate", Field::Bool(self.aggregate)),
68                ("lower", Field::Count(count(self.lower))),
69                (
70                    "upper",
71                    self.upper
72                        .map_or(Field::Null, |upper| Field::Count(count(upper))),
73                ),
74                ("declared_by", Field::Text(self.declared_by.clone())),
75            ],
76        )
77    }
78}
79
80/// One reference to an entity: who holds it and in which attribute.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct InverseReference {
83    /// The referencing entity.
84    pub id: u64,
85    /// The zero-based attribute index (STEP slot) of `id` holding the
86    /// reference, directly or inside an aggregate or typed value.
87    pub index: usize,
88}
89
90impl ToRecord for InverseReference {
91    fn to_record(&self) -> Record {
92        Record::new(
93            "InverseReference",
94            vec![
95                ("id", Field::Id(self.id)),
96                ("index", Field::Count(self.index)),
97            ],
98        )
99    }
100}
101
102/// The facade's reverse index, and the model revision it was built from.
103#[derive(Debug, Default)]
104pub(crate) struct ReverseCache(Mutex<Option<(u64, Arc<ReverseIndex>)>>);
105
106impl IfcModel {
107    /// Every `INVERSE` attribute of entity `id`, inherited ones first,
108    /// resolved against the declared release.
109    pub fn inverse_attribute_names(
110        &self,
111        id: u64,
112    ) -> Result<Vec<InverseAttributeInfo>, BindingError> {
113        let schema = self.declared_schema()?;
114        let type_name = &self.entity(id)?.type_name;
115        Ok(ifc::inverse_slots(schema, type_name)
116            .map_err(refused)?
117            .into_iter()
118            .map(|slot| InverseAttributeInfo {
119                name: slot.name.to_owned(),
120                entity: slot.entity.to_owned(),
121                for_attribute: slot.for_attribute.to_owned(),
122                aggregate: slot.is_aggregate(),
123                lower: slot.lower(),
124                upper: slot.upper(),
125                declared_by: slot.declared_by.to_owned(),
126            })
127            .collect())
128    }
129
130    /// Every reference to entity `id`, in ascending `(id, index)` order:
131    /// one per referencing entity and attribute, whatever the attribute
132    /// (IfcOpenShell's `get_inverse(.., with_attribute_indices=True)`).
133    /// Needs no schema.
134    pub fn inverse_references(&self, id: u64) -> Result<Vec<InverseReference>, BindingError> {
135        self.entity(id)?;
136        let reverse = self.reverse_index();
137        Ok(reverse
138            .referrers(EntityId(id))
139            .iter()
140            .map(|referrer| InverseReference {
141                id: referrer.from.0,
142                index: referrer.slot,
143            })
144            .collect())
145    }
146
147    /// How many distinct entities reference entity `id`, through any
148    /// attribute (IfcOpenShell's `get_total_inverses`). Needs no schema.
149    pub fn total_inverses(&self, id: u64) -> Result<usize, BindingError> {
150        self.entity(id)?;
151        Ok(ifc::total_inverses(&self.reverse_index(), EntityId(id)))
152    }
153
154    /// The `INVERSE` attribute `name` of `id`, after the slot lookup named
155    /// it one.
156    pub(crate) fn inverse_by_name(&self, id: u64, name: &str) -> Result<Tagged, BindingError> {
157        let schema = self.declared_schema()?;
158        let reverse = self.reverse_index();
159        match ifc::attribute_value_by_name(&self.inner, schema, &reverse, EntityId(id), name)
160            .map_err(inverse_refused)?
161        {
162            AttributeValue::Inverse(value) => Ok(to_tagged(&value)),
163            AttributeValue::Explicit(value) => Ok(value.map_or(Tagged::Null, Tagged::from_value)),
164            // `AttributeValue` is non-exhaustive.
165            other => Err(BindingError::InvalidModel(format!(
166                "unexpected read {other:?}"
167            ))),
168        }
169    }
170
171    /// The reverse index of the model as it is now, rebuilt first when an
172    /// edit changed it since the last build.
173    fn reverse_index(&self) -> Arc<ReverseIndex> {
174        let revision = self.inner.revision();
175        // A poisoned lock only means another thread panicked mid-build; the
176        // slot is rebuilt below whatever it holds.
177        let mut slot = self
178            .reverse_index
179            .0
180            .lock()
181            .unwrap_or_else(std::sync::PoisonError::into_inner);
182        match slot.as_ref() {
183            Some((built, index)) if *built == revision => Arc::clone(index),
184            _ => {
185                let index = Arc::new(ReverseIndex::build(&self.inner));
186                *slot = Some((revision, Arc::clone(&index)));
187                index
188            }
189        }
190    }
191}
192
193/// A single-valued inverse more than one entity references is a model
194/// contradicting its schema; every other refusal is the slot lookup's.
195fn inverse_refused(error: NamedAttributeError) -> BindingError {
196    match error {
197        NamedAttributeError::InverseCardinality { .. } => {
198            BindingError::InvalidModel(error.to_string())
199        }
200        other => refused(other),
201    }
202}
203
204fn to_tagged(value: &InverseValue) -> Tagged {
205    match value {
206        InverseValue::Single(found) => found.map_or(Tagged::Null, |EntityId(id)| Tagged::Ref(id)),
207        InverseValue::Aggregate(ids) => {
208            Tagged::List(ids.iter().map(|EntityId(id)| Tagged::Ref(*id)).collect())
209        }
210        // `InverseValue` is non-exhaustive: every shape lists its ids.
211        other => Tagged::List(
212            other
213                .ids()
214                .iter()
215                .map(|EntityId(id)| Tagged::Ref(*id))
216                .collect(),
217        ),
218    }
219}
220
221fn count(bound: u64) -> usize {
222    usize::try_from(bound).unwrap_or(usize::MAX)
223}