Skip to main content

ifc_approval/
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::{ApprovalError, ApprovalResult};
9
10/// Borrowed entry point for approval 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 [`ApprovalError::UnsupportedSchema`] or
15/// [`ApprovalError::MultipleSchemas`] from the first lookup.
16#[derive(Debug, Clone, Copy)]
17pub struct ApprovalView<'m> {
18    model: &'m Model,
19    binding: Binding<'m>,
20}
21
22impl<'m> ApprovalView<'m> {
23    /// Borrow approval 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) -> ApprovalResult<Layout> {
38        self.binding.layout()
39    }
40}
41
42pub(crate) fn wrong(expected: &'static str, entity: &Entity) -> ApprovalError {
43    ApprovalError::WrongEntityType {
44        expected,
45        actual: entity.type_name.to_string(),
46    }
47}
48
49fn invalid(
50    kind: &'static str,
51    id: EntityId,
52    attribute: &'static str,
53    value: &Value,
54) -> ApprovalError {
55    ApprovalError::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    fn value(self, attribute: &'static str) -> ApprovalResult<Option<&'m Value>> {
77        let (slot, _) =
78            self.layout
79                .declared(self.kind, attribute)
80                .ok_or(ApprovalError::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    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 requires `attribute`.
106    pub(crate) fn requires(self, attribute: &'static str) -> bool {
107        self.layout
108            .declared(self.kind, attribute)
109            .is_some_and(|(_, declared)| !declared.optional)
110    }
111
112    pub(crate) fn optional_text(self, attribute: &'static str) -> ApprovalResult<Option<&'m str>> {
113        match self.value(attribute)? {
114            None => Ok(None),
115            Some(Value::Ref(target)) if self.admits_record(attribute) => {
116                Err(ApprovalError::StructuredValue {
117                    entity: self.kind,
118                    id: self.id,
119                    attribute,
120                    target: *target,
121                })
122            }
123            Some(value) => value
124                .unwrap_typed()
125                .as_text()
126                .map(Some)
127                .ok_or_else(|| invalid(self.kind, self.id, attribute, value)),
128        }
129    }
130
131    pub(crate) fn required_text(self, attribute: &'static str) -> ApprovalResult<&'m str> {
132        self.optional_text(attribute)?
133            .ok_or(ApprovalError::MissingAttribute {
134                entity: self.kind,
135                id: self.id,
136                attribute,
137            })
138    }
139
140    pub(crate) fn optional_ref(self, attribute: &'static str) -> ApprovalResult<Option<EntityId>> {
141        match self.value(attribute)? {
142            None => Ok(None),
143            Some(Value::Ref(target)) => Ok(Some(*target)),
144            Some(value) => Err(invalid(self.kind, self.id, attribute, value)),
145        }
146    }
147
148    pub(crate) fn required_ref(self, attribute: &'static str) -> ApprovalResult<EntityId> {
149        self.optional_ref(attribute)?
150            .ok_or(ApprovalError::MissingAttribute {
151                entity: self.kind,
152                id: self.id,
153                attribute,
154            })
155    }
156
157    /// A non-empty, duplicate-free set of references. Where the release
158    /// declares a single reference (IFC2X3 `RelatedApproval`), that one
159    /// reference is the set.
160    pub(crate) fn required_refs(self, attribute: &'static str) -> ApprovalResult<Vec<EntityId>> {
161        let value = self
162            .value(attribute)?
163            .ok_or(ApprovalError::MissingAttribute {
164                entity: self.kind,
165                id: self.id,
166                attribute,
167            })?;
168        let single = self
169            .layout
170            .declared(self.kind, attribute)
171            .is_some_and(|(_, declared)| !declared.aggregate);
172        let values = match value {
173            Value::Ref(target) if single => return Ok(vec![*target]),
174            Value::List(values) if !single && !values.is_empty() => values,
175            _ => return Err(invalid(self.kind, self.id, attribute, value)),
176        };
177        let mut seen = HashSet::new();
178        let mut out = Vec::with_capacity(values.len());
179        for item in values {
180            let Value::Ref(target) = item else {
181                return Err(invalid(self.kind, self.id, attribute, item));
182            };
183            if !seen.insert(*target) {
184                return Err(ApprovalError::InvalidValue {
185                    entity: self.kind,
186                    id: self.id,
187                    attribute,
188                    value: format!("duplicate {target}"),
189                });
190            }
191            out.push(*target);
192        }
193        Ok(out)
194    }
195
196    /// Fail unless `target` resolves to a type the release accepts as
197    /// `expected`.
198    pub(crate) fn validate_target(
199        self,
200        model: &Model,
201        attribute: &'static str,
202        target: EntityId,
203        expected: &'static str,
204    ) -> ApprovalResult<()> {
205        let actual = model.get(target).ok_or(ApprovalError::DanglingReference {
206            entity: self.kind,
207            id: self.id,
208            attribute,
209            target,
210        })?;
211        let accepted = if expected == "IfcDefinitionSelect" {
212            self.layout.is_definition(&actual.type_name)
213        } else {
214            self.layout
215                .schema()
216                .accepts_type(expected, &actual.type_name)
217        };
218        if accepted {
219            Ok(())
220        } else {
221            Err(ApprovalError::ReferenceType {
222                entity: self.kind,
223                id: self.id,
224                attribute,
225                target,
226                expected,
227                actual: actual.type_name.to_string(),
228            })
229        }
230    }
231}