Skip to main content

ifc_properties/exact/
index.rs

1//! A whole-model scan of property assignments, shared by many queries
2//! (#352).
3//!
4//! Every exact query validates every `IfcRelDefinesByProperties` and
5//! `IfcRelDefinesByType` of the file, because a malformed one could hide an
6//! assignment. Asked once per object, that makes "every property of every
7//! object" quadratic: objects times relationships. [`PropertyIndex`] runs
8//! the validation once and records which objects each relationship relates,
9//! so each query afterwards costs only its own object's sets.
10
11use std::fmt;
12
13use ifc_model::{EntityId, Model};
14use ifc_schema::SchemaVersion;
15
16use super::assignment::{Relations, Scope};
17use super::enumerate::{properties_where_in, property_sets_where_in};
18use super::predefined::predefined_sets_in;
19use super::release::{validate_model, Release};
20use super::{
21    property_in, ExactPredefinedSet, ExactPropertyEntry, ExactPropertyError, ExactPropertySetEntry,
22    ExactResolution,
23};
24
25/// The exact resolver's view of one model, scanned once for many queries.
26///
27/// Answers exactly what the free functions answer, results and errors
28/// alike: [`Self::exact_property`] is [`exact_property`](super::exact_property),
29/// [`Self::exact_properties`] is [`exact_properties`](super::exact_properties),
30/// and so on, for every object of the model. The difference is cost. A free
31/// function validates every property relationship in the file on each
32/// call; the index validates them once, in [`Self::build`], and records the
33/// sets each object is assigned. A loop resolving every object is then
34/// linear in objects plus relationships instead of their product.
35///
36/// ```
37/// # use ifc_model::{EntityId, Model};
38/// # use ifc_properties::{exact_property, PropertyIndex};
39/// # fn every_object(model: &Model, objects: &[EntityId]) {
40/// let index = PropertyIndex::build(model);
41/// for &object in objects {
42///     assert_eq!(
43///         index.exact_property(object, Some("Pset_WallCommon"), "IsExternal"),
44///         exact_property(model, object, Some("Pset_WallCommon"), "IsExternal"),
45///     );
46/// }
47/// # }
48/// ```
49///
50/// # It cannot go stale
51///
52/// The index is a borrowed view (ADR 0003): it holds `&Model` for its
53/// whole life, so the model cannot be mutated, by a
54/// [`Transaction`](ifc_model::Transaction) or otherwise, while the index
55/// exists. To read after an edit, drop the index, commit, and build a new
56/// one from the edited model.
57///
58/// # Refusals
59///
60/// A model the exact resolver refuses as a whole (diagnostics, no or
61/// several schemas, an unsupported release) still builds; every query then
62/// returns that refusal, as every free function would. A malformed
63/// relationship is likewise reported by each query it would have refused.
64#[derive(Clone)]
65pub struct PropertyIndex<'m> {
66    model: &'m Model,
67    bound: Result<(Release, Relations), ExactPropertyError>,
68}
69
70impl fmt::Debug for PropertyIndex<'_> {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        let mut out = f.debug_struct("PropertyIndex");
73        match &self.bound {
74            Ok((release, relations)) => out
75                .field("schema", &release.version)
76                .field("objects", &relations.objects()),
77            Err(error) => out.field("refused", error),
78        };
79        out.finish_non_exhaustive()
80    }
81}
82
83impl<'m> PropertyIndex<'m> {
84    /// Bind `model` to its declared release and validate every property
85    /// relationship once.
86    ///
87    /// Linear in the model's `IfcRelDefinesByProperties` and
88    /// `IfcRelDefinesByType` and the objects they relate. Never fails: a
89    /// refusal is kept and returned by every query.
90    #[must_use]
91    pub fn build(model: &'m Model) -> Self {
92        let bound = validate_model(model)
93            .map(|release| (release, Relations::scan(model, release, Scope::All)));
94        Self { model, bound }
95    }
96
97    /// The model this index was built from.
98    #[must_use]
99    pub fn model(&self) -> &'m Model {
100        self.model
101    }
102
103    /// The release every query resolves against, as
104    /// [`exact_schema`](super::exact_schema) answers.
105    ///
106    /// # Errors
107    ///
108    /// The model-level refusal [`exact_schema`](super::exact_schema) returns.
109    pub fn schema(&self) -> Result<SchemaVersion, ExactPropertyError> {
110        self.bound
111            .as_ref()
112            .map(|(release, _)| release.version)
113            .map_err(Clone::clone)
114    }
115
116    fn bound(&self) -> Result<(Release, &Relations), ExactPropertyError> {
117        self.bound
118            .as_ref()
119            .map(|(release, relations)| (*release, relations))
120            .map_err(Clone::clone)
121    }
122
123    /// [`exact_property`](super::exact_property) of `object`.
124    ///
125    /// # Errors
126    ///
127    /// As for [`exact_property`](super::exact_property).
128    pub fn exact_property(
129        &self,
130        object: EntityId,
131        set_name: Option<&str>,
132        property_name: &str,
133    ) -> Result<ExactResolution, ExactPropertyError> {
134        let (release, relations) = self.bound()?;
135        property_in(
136            self.model,
137            release,
138            Some(relations),
139            object,
140            set_name,
141            property_name,
142        )
143    }
144
145    /// [`exact_properties`](super::exact_properties) of `object`.
146    ///
147    /// # Errors
148    ///
149    /// As for [`exact_properties`](super::exact_properties).
150    pub fn exact_properties(
151        &self,
152        object: EntityId,
153    ) -> Result<Vec<ExactPropertyEntry>, ExactPropertyError> {
154        self.exact_properties_where(object, |_| true, |_| true)
155    }
156
157    /// [`exact_properties_where`](super::exact_properties_where) of
158    /// `object`.
159    ///
160    /// # Errors
161    ///
162    /// As for [`exact_properties_where`](super::exact_properties_where).
163    pub fn exact_properties_where<S, P>(
164        &self,
165        object: EntityId,
166        mut select_set: S,
167        mut select_property: P,
168    ) -> Result<Vec<ExactPropertyEntry>, ExactPropertyError>
169    where
170        S: FnMut(&str) -> bool,
171        P: FnMut(&str) -> bool,
172    {
173        let (release, relations) = self.bound()?;
174        properties_where_in(
175            self.model,
176            release,
177            Some(relations),
178            object,
179            &mut select_set,
180            &mut select_property,
181        )
182    }
183
184    /// [`exact_property_sets_where`](super::exact_property_sets_where) of
185    /// `object`.
186    ///
187    /// # Errors
188    ///
189    /// As for [`exact_property_sets_where`](super::exact_property_sets_where).
190    pub fn exact_property_sets_where<S>(
191        &self,
192        object: EntityId,
193        mut select_set: S,
194    ) -> Result<Vec<ExactPropertySetEntry>, ExactPropertyError>
195    where
196        S: FnMut(&str) -> bool,
197    {
198        let (release, relations) = self.bound()?;
199        property_sets_where_in(
200            self.model,
201            release,
202            Some(relations),
203            object,
204            &mut select_set,
205        )
206    }
207
208    /// [`exact_predefined_sets`](super::exact_predefined_sets) of `object`.
209    ///
210    /// # Errors
211    ///
212    /// As for [`exact_predefined_sets`](super::exact_predefined_sets).
213    pub fn exact_predefined_sets(
214        &self,
215        object: EntityId,
216        entity: &str,
217    ) -> Result<Vec<ExactPredefinedSet>, ExactPropertyError> {
218        let (release, relations) = self.bound()?;
219        predefined_sets_in(self.model, release, Some(relations), object, entity)
220    }
221}