Skip to main content

openbim_ifc_binding_core/
selector.rs

1//! Selectors and values by path (#464): the facade's `ifc::selector`.
2//!
3//! [`IfcModel::select`] filters the model with a selector such as
4//! `IfcWall, Pset_WallCommon.IsExternal=TRUE` (grammar
5//! [`SELECTOR_GRAMMAR_VERSION`]); [`IfcModel::get_value`] reads a value by
6//! path (`type.Name`, `Pset_WallCommon.FireRating`) and
7//! [`IfcModel::set_value`] writes one, from a plain host value coerced as
8//! [`IfcModel::set_attribute_by_name_plain`] coerces it for an attribute,
9//! or wrapped in the type of the property already stated for a property.
10//!
11//! A selector or path that does not parse, and a class or attribute the
12//! declared release does not declare, are refused with
13//! `invalid-selector`, whose [`BindingError::span`] is the byte range of
14//! the offending text in the UTF-8 query. Property facets and paths read
15//! with feature `properties`, property writes need `properties-write`;
16//! without them they refuse with `feature-disabled`.
17
18use ifc::selector::{
19    ParseError, SelectedValue, Selector, SelectorError, SelectorIndex, SetTarget, ValuePath,
20};
21use ifc::EntityId;
22
23use crate::attribute::refused;
24use crate::coerce::Plain;
25use crate::value::Tagged;
26use crate::{BindingError, IfcModel};
27
28/// The version of the selector grammar the bindings parse.
29pub const SELECTOR_GRAMMAR_VERSION: &str = ifc::selector::GRAMMAR_VERSION;
30
31/// A value read by path, for a host: a scalar, a list, or a property set's
32/// named values.
33#[derive(Debug, Clone, PartialEq)]
34pub enum Selected {
35    /// A scalar, a reference or `$`; never a `list`.
36    Value(Tagged),
37    /// Several values.
38    List(Vec<Selected>),
39    /// A property set, complex property or bounded value: each member's
40    /// name and value, in order.
41    Properties(Vec<(String, Selected)>),
42}
43
44impl Selected {
45    fn from_selected(value: SelectedValue) -> Self {
46        match value {
47            SelectedValue::Null => Self::Value(Tagged::Null),
48            SelectedValue::Derived => Self::Value(Tagged::Derived),
49            SelectedValue::Bool(b) => Self::Value(Tagged::Bool(b)),
50            SelectedValue::Unknown => Self::Value(Tagged::Unknown),
51            SelectedValue::Integer(i) => Self::Value(Tagged::Integer(i)),
52            SelectedValue::Real(r) => Self::Value(Tagged::Real(r)),
53            SelectedValue::Text(text) => Self::Value(Tagged::Text(text)),
54            SelectedValue::Binary(digits) => Self::Value(Tagged::Binary(digits)),
55            SelectedValue::Enum(item) => Self::Value(Tagged::Enum(item)),
56            SelectedValue::Entity(EntityId(id)) => Self::Value(Tagged::Ref(id)),
57            SelectedValue::List(items) => {
58                Self::List(items.into_iter().map(Self::from_selected).collect())
59            }
60            SelectedValue::Properties(members) => Self::Properties(
61                members
62                    .into_iter()
63                    .map(|(name, value)| (name, Self::from_selected(value)))
64                    .collect(),
65            ),
66            // `SelectedValue` is non-exhaustive; a new form is reported,
67            // never dropped, until it earns a form of its own.
68            other => Self::Value(Tagged::Text(format!("{other:?}"))),
69        }
70    }
71
72    /// The tagged form the C binding writes to its tape: a list as a
73    /// `list`, a property set as a `list` of two-item `list`s, each the
74    /// member's name (`text`) and its value.
75    pub fn to_tagged(&self) -> Tagged {
76        match self {
77            Self::Value(value) => value.clone(),
78            Self::List(items) => Tagged::List(items.iter().map(Self::to_tagged).collect()),
79            Self::Properties(members) => Tagged::List(
80                members
81                    .iter()
82                    .map(|(name, value)| {
83                        Tagged::List(vec![Tagged::Text(name.clone()), value.to_tagged()])
84                    })
85                    .collect(),
86            ),
87        }
88    }
89}
90
91/// `query` parsed, in the canonical form the grammar writes: spacing,
92/// quoting and aliases normalised. Refused with `invalid-selector`.
93pub fn canonical_selector(query: &str) -> Result<String, BindingError> {
94    Selector::parse(query)
95        .map(|selector| selector.to_string())
96        .map_err(parse_error)
97}
98
99impl IfcModel {
100    /// The entities `query` selects, in ascending id order.
101    ///
102    /// Refused with `invalid-selector` for a query that does not parse or
103    /// names a class or attribute the declared release does not declare,
104    /// `unsupported-schema`, `invalid-model` for an ambiguous or malformed
105    /// relationship or a duplicated `GlobalId` an instance facet names,
106    /// `missing-reference`, and the property refusals of
107    /// [`Self::property_sets`].
108    pub fn select(&self, query: &str) -> Result<Vec<u64>, BindingError> {
109        let selector = Selector::parse(query).map_err(parse_error)?;
110        let schema = self.declared_schema()?;
111        SelectorIndex::new(&self.inner, schema)
112            .select(&selector)
113            .map(raw)
114            .map_err(selector_error)
115    }
116
117    /// The entities `query` selects from `base` alone, in ascending id
118    /// order. Refused as [`Self::select`], and with `missing-entity` for an
119    /// id of `base` the model lacks.
120    pub fn select_from(&self, query: &str, base: &[u64]) -> Result<Vec<u64>, BindingError> {
121        let selector = Selector::parse(query).map_err(parse_error)?;
122        let schema = self.declared_schema()?;
123        let base: Vec<EntityId> = base.iter().copied().map(EntityId).collect();
124        SelectorIndex::new(&self.inner, schema)
125            .select_from(&selector, &base)
126            .map(raw)
127            .map_err(selector_error)
128    }
129
130    /// The value `path` reads from entity `id`. Refused with
131    /// `invalid-selector` for a path that does not parse, `missing-entity`,
132    /// and as [`Self::select`].
133    pub fn get_value(&self, id: u64, path: &str) -> Result<Selected, BindingError> {
134        let path = ValuePath::parse(path).map_err(parse_error)?;
135        let schema = self.declared_schema()?;
136        SelectorIndex::new(&self.inner, schema)
137            .value(EntityId(id), &path)
138            .map(Selected::from_selected)
139            .map_err(selector_error)
140    }
141
142    /// Write `value` at `path` of entity `id`, as one transaction: an
143    /// attribute (`Name`, `type.Name`, `materials.Category`) from a plain
144    /// value coerced against its declared type, or a property
145    /// (`Pset_WallCommon.FireRating`, `type.Pset_WallCommon.FireRating`)
146    /// from a typed value, or a plain one the property already states the
147    /// type of. Every check runs first: a refusal changes nothing.
148    ///
149    /// Refused with `invalid-value` for a path that names no single value
150    /// (a pattern, `count`, a prefix reaching no entity), `unknown-attribute`,
151    /// `derived-attribute`, `type-mismatch` (also for a plain value no
152    /// stated property types), `ambiguous-value`, and the property edit's
153    /// refusals. Also `unsupported` when the build or host has no random
154    /// source for the seed (as [`crate::relations::new_guid`]); that is
155    /// checked first, before `feature-disabled` for a property write.
156    pub fn set_value(&mut self, id: u64, path: &str, value: Plain) -> Result<(), BindingError> {
157        let seed = crate::relations::fresh_seed()?;
158        self.tracked(|this| this.set_value_seeded(id, path, value, seed))
159    }
160
161    /// [`Self::set_value`]
162    /// with the seed the `GlobalId`s of new sets and relationships derive
163    /// from: a host with entropy of its own (the browser) passes it. The
164    /// seed names the batch: a fixed seed reproduces its `GlobalId`s, also
165    /// after a write/read cycle; reusing it where the model holds one it
166    /// derives is refused (`invalid-value`).
167    pub fn set_value_seeded(
168        &mut self,
169        id: u64,
170        path: &str,
171        value: Plain,
172        seed: u128,
173    ) -> Result<(), BindingError> {
174        let path = ValuePath::parse(path).map_err(parse_error)?;
175        let schema = self.declared_schema()?;
176        let targets = SelectorIndex::new(&self.inner, schema)
177            .set_targets(EntityId(id), &path)
178            .map_err(selector_error)?;
179        match targets.first() {
180            Some(SetTarget::Attribute { entity, name }) => {
181                let value = self.coerce_attribute(entity.0, name, value)?.into_value()?;
182                let transaction = SelectorIndex::new(&self.inner, schema)
183                    .stage_attributes(&targets, &value)
184                    .map_err(selector_error)?;
185                self.tracked(|this| transaction.commit(&mut this.inner))
186                    .map(|_| ())
187                    .map_err(|conflicts| BindingError::InvalidModel(format!("{conflicts:?}")))
188            }
189            Some(_) => self.tracked(|this| {
190                write_properties(this, &targets, plain_tagged(value)?.into_value()?, seed)
191            }),
192            None => Err(BindingError::InvalidValue(format!(
193                "{path} names no value to write"
194            ))),
195        }
196    }
197}
198
199#[cfg(feature = "properties-write")]
200fn write_properties(
201    model: &mut IfcModel,
202    targets: &[SetTarget],
203    value: ifc::Value,
204    seed: u128,
205) -> Result<(), BindingError> {
206    let schema = model.declared_schema()?;
207    let edits = SelectorIndex::new(&model.inner, schema)
208        .property_edits(targets, &value)
209        .map_err(selector_error)?;
210    ifc::apply_property_edits(&mut model.inner, &edits, seed)
211        .map(|_| ())
212        .map_err(crate::property_edit::write::edit_error)
213}
214
215#[cfg(not(feature = "properties-write"))]
216fn write_properties(
217    _model: &mut IfcModel,
218    _targets: &[SetTarget],
219    _value: ifc::Value,
220    _seed: u128,
221) -> Result<(), BindingError> {
222    Err(BindingError::FeatureDisabled("properties-write"))
223}
224
225/// A plain host value as the tagged value a property edit takes: a typed
226/// value as given, a bare one to be wrapped in the stated type.
227fn plain_tagged(value: Plain) -> Result<Tagged, BindingError> {
228    Ok(match value {
229        Plain::Null => Tagged::Null,
230        Plain::Bool(b) => Tagged::Bool(b),
231        Plain::Integer(i) => Tagged::Integer(i),
232        Plain::Real(r) => Tagged::Real(r),
233        Plain::Text(text) => Tagged::Text(text),
234        Plain::Ref(id) => Tagged::Ref(id),
235        Plain::List(items) => Tagged::List(
236            items
237                .into_iter()
238                .map(plain_tagged)
239                .collect::<Result<_, _>>()?,
240        ),
241        Plain::Exact(tagged) => tagged,
242    })
243}
244
245fn raw(ids: Vec<EntityId>) -> Vec<u64> {
246    ids.into_iter().map(|EntityId(id)| id).collect()
247}
248
249pub(crate) fn parse_error(error: ParseError) -> BindingError {
250    BindingError::InvalidSelector {
251        detail: error.kind.to_string(),
252        span: (error.span.start, error.span.end),
253    }
254}
255
256pub(crate) fn selector_error(error: SelectorError) -> BindingError {
257    let detail = error.to_string();
258    match error {
259        SelectorError::UnknownClass { span, .. } | SelectorError::UnknownAttribute { span, .. } => {
260            BindingError::InvalidSelector {
261                detail,
262                span: (span.start, span.end),
263            }
264        }
265        SelectorError::MissingEntity(EntityId(id)) => BindingError::MissingEntity(id),
266        SelectorError::MissingReference { .. } => BindingError::MissingReference(detail),
267        SelectorError::FeatureDisabled(feature) => BindingError::FeatureDisabled(feature),
268        SelectorError::UnsupportedValue { .. } => BindingError::Unsupported(detail),
269        SelectorError::NotSettable { .. } | SelectorError::ConflictingWrite { .. } => {
270            BindingError::InvalidValue(detail)
271        }
272        SelectorError::Attribute(error) => refused(error),
273        SelectorError::TypeMismatch { .. }
274        | SelectorError::UntypedValue { .. }
275        | SelectorError::InvalidText { .. } => BindingError::TypeMismatch(detail),
276        #[cfg(feature = "properties")]
277        SelectorError::Property { error, .. } => crate::properties::read::property_error(error),
278        #[cfg(feature = "properties-write")]
279        SelectorError::PropertyEdit(error) => crate::property_edit::write::edit_error(error),
280        // Ambiguous and malformed relationships, a duplicated GlobalId, a
281        // conflict, and any refusal added after this binding.
282        _ => BindingError::InvalidModel(detail),
283    }
284}