Skip to main content

ifc_constraint/
view.rs

1//! Shared borrowed model view and strict by-name decoders.
2
3use std::collections::HashSet;
4
5use ifc_model::{Entity, EntityId, Model, Value};
6
7use crate::release::{Binding, Layout};
8use crate::{ConstraintError, ConstraintResult};
9
10/// Borrowed entry point for constraint projections and inverse-style queries.
11///
12/// Every projection reads against the release the model's header declares
13/// (IFC2X3, IFC4 or IFC4X3; none reads as IFC4). A header this crate cannot
14/// bind surfaces as [`ConstraintError::UnsupportedSchema`] or
15/// [`ConstraintError::MultipleSchemas`] from the first lookup.
16#[derive(Debug, Clone, Copy)]
17pub struct ConstraintView<'m> {
18    model: &'m Model,
19    binding: Binding<'m>,
20}
21
22impl<'m> ConstraintView<'m> {
23    /// Borrow constraint semantics from a model snapshot.
24    #[must_use]
25    pub fn new(model: &'m Model) -> Self {
26        Self {
27            model,
28            binding: Binding::of(model),
29        }
30    }
31
32    pub(crate) const fn model(self) -> &'m Model {
33        self.model
34    }
35
36    /// The bound release, or why none could be bound.
37    pub(crate) fn layout(self) -> ConstraintResult<Layout> {
38        self.binding.layout()
39    }
40}
41
42pub(crate) fn wrong(expected: &'static str, entity: &Entity) -> ConstraintError {
43    ConstraintError::WrongEntityType {
44        expected,
45        actual: entity.type_name.to_string(),
46    }
47}
48
49pub(crate) fn invalid(
50    kind: &'static str,
51    id: EntityId,
52    attribute: &'static str,
53    value: &Value,
54) -> ConstraintError {
55    ConstraintError::InvalidValue {
56        entity: kind,
57        id,
58        attribute,
59        value: format!("{value:?}"),
60    }
61}
62
63/// One record read against its release.
64#[derive(Debug, Clone, Copy)]
65pub(crate) struct Record<'m> {
66    pub(crate) kind: &'static str,
67    pub(crate) id: EntityId,
68    pub(crate) entity: &'m Entity,
69    pub(crate) layout: Layout,
70}
71
72impl<'m> Record<'m> {
73    /// The value of `attribute` (IFC4 name): `NotInSchema` when the release
74    /// does not declare it, `None` when the record leaves it `$` or ends
75    /// before it.
76    pub(crate) fn value(self, attribute: &'static str) -> ConstraintResult<Option<&'m Value>> {
77        let (slot, _) =
78            self.layout
79                .declared(self.kind, attribute)
80                .ok_or(ConstraintError::NotInSchema {
81                    entity: self.kind,
82                    id: self.id,
83                    attribute,
84                    schema: self.layout.version(),
85                })?;
86        Ok(match self.entity.attribute(slot) {
87            None | Some(Value::Null) => None,
88            Some(value) => Some(value),
89        })
90    }
91
92    /// Whether the release declares `attribute` (IFC4 name).
93    pub(crate) fn declares(self, attribute: &'static str) -> bool {
94        self.layout.declared(self.kind, attribute).is_some()
95    }
96
97    /// Whether the release types `attribute` as an entity record (or a
98    /// SELECT reaching one), such as IFC2X3's `IfcDateTimeSelect`.
99    pub(crate) fn admits_record(self, attribute: &'static str) -> bool {
100        self.layout
101            .declared(self.kind, attribute)
102            .is_some_and(|(_, declared)| self.layout.admits_entity(&declared.type_name, 8))
103    }
104
105    /// Whether the release declares `attribute` as an aggregate.
106    pub(crate) fn aggregate(self, attribute: &'static str) -> bool {
107        self.layout
108            .declared(self.kind, attribute)
109            .is_some_and(|(_, declared)| declared.aggregate)
110    }
111
112    /// The (element) type the release declares for `attribute`, or `""`.
113    pub(crate) fn declared_type(self, attribute: &'static str) -> &'static str {
114        self.layout
115            .declared(self.kind, attribute)
116            .map_or("", |(_, declared)| declared.type_name.as_str())
117    }
118
119    /// Whether the release requires `attribute`.
120    pub(crate) fn requires(self, attribute: &'static str) -> bool {
121        self.layout
122            .declared(self.kind, attribute)
123            .is_some_and(|(_, declared)| !declared.optional)
124    }
125
126    pub(crate) fn optional_text(
127        self,
128        attribute: &'static str,
129    ) -> ConstraintResult<Option<&'m str>> {
130        match self.value(attribute)? {
131            None => Ok(None),
132            Some(Value::Ref(target)) if self.admits_record(attribute) => {
133                Err(ConstraintError::StructuredValue {
134                    entity: self.kind,
135                    id: self.id,
136                    attribute,
137                    target: *target,
138                })
139            }
140            Some(value) => value
141                .unwrap_typed()
142                .as_text()
143                .map(Some)
144                .ok_or_else(|| invalid(self.kind, self.id, attribute, value)),
145        }
146    }
147
148    pub(crate) fn required_text(self, attribute: &'static str) -> ConstraintResult<&'m str> {
149        self.optional_text(attribute)?
150            .ok_or(ConstraintError::MissingAttribute {
151                entity: self.kind,
152                id: self.id,
153                attribute,
154            })
155    }
156
157    pub(crate) fn optional_ref(
158        self,
159        attribute: &'static str,
160    ) -> ConstraintResult<Option<EntityId>> {
161        match self.value(attribute)? {
162            None => Ok(None),
163            Some(Value::Ref(target)) => Ok(Some(*target)),
164            Some(value) => Err(invalid(self.kind, self.id, attribute, value)),
165        }
166    }
167
168    pub(crate) fn required_ref(self, attribute: &'static str) -> ConstraintResult<EntityId> {
169        self.optional_ref(attribute)?
170            .ok_or(ConstraintError::MissingAttribute {
171                entity: self.kind,
172                id: self.id,
173                attribute,
174            })
175    }
176
177    /// A non-empty, duplicate-free set of references. Where the release
178    /// declares a single reference, that one reference is the set.
179    pub(crate) fn required_refs(self, attribute: &'static str) -> ConstraintResult<Vec<EntityId>> {
180        let value = self
181            .value(attribute)?
182            .ok_or(ConstraintError::MissingAttribute {
183                entity: self.kind,
184                id: self.id,
185                attribute,
186            })?;
187        let single = self
188            .layout
189            .declared(self.kind, attribute)
190            .is_some_and(|(_, declared)| !declared.aggregate);
191        let values = match value {
192            Value::Ref(target) if single => return Ok(vec![*target]),
193            Value::List(values) if !single && !values.is_empty() => values,
194            _ => return Err(invalid(self.kind, self.id, attribute, value)),
195        };
196        let mut seen = HashSet::new();
197        let mut out = Vec::with_capacity(values.len());
198        for item in values {
199            let Value::Ref(target) = item else {
200                return Err(invalid(self.kind, self.id, attribute, item));
201            };
202            if !seen.insert(*target) {
203                return Err(ConstraintError::InvalidValue {
204                    entity: self.kind,
205                    id: self.id,
206                    attribute,
207                    value: format!("duplicate {target}"),
208                });
209            }
210            out.push(*target);
211        }
212        Ok(out)
213    }
214
215    /// Fail unless `target` resolves to a type the release accepts as
216    /// `expected`.
217    pub(crate) fn validate_target(
218        self,
219        model: &Model,
220        attribute: &'static str,
221        target: EntityId,
222        expected: &'static str,
223    ) -> ConstraintResult<()> {
224        let actual = model
225            .get(target)
226            .ok_or(ConstraintError::DanglingReference {
227                entity: self.kind,
228                id: self.id,
229                attribute,
230                target,
231            })?;
232        let accepted = if expected == "IfcDefinitionSelect" {
233            self.layout.is_definition(&actual.type_name)
234        } else {
235            self.layout
236                .schema()
237                .accepts_type(expected, &actual.type_name)
238        };
239        if accepted {
240            Ok(())
241        } else {
242            Err(ConstraintError::ReferenceType {
243                entity: self.kind,
244                id: self.id,
245                attribute,
246                target,
247                expected,
248                actual: actual.type_name.to_string(),
249            })
250        }
251    }
252}