Skip to main content

ifc_material/
view.rs

1//! Shared borrowed-view mechanics and strict IFC slot decoders.
2
3use ifc_model::{Entity, EntityId, Model, ReverseIndex, Value};
4
5use crate::release::Release;
6use crate::{LogicalValue, MaterialError, MaterialResult, SchemaVersion};
7
8const MAX_TYPED_WRAPPERS: usize = 8;
9
10/// Borrowed MaterialResource interpretation of a model.
11///
12/// Every projection the view hands out reads against the release the
13/// model's header declares (see [`crate::material_schema`]): slot positions
14/// come from that release's bundled table, never from IFC4 by assumption.
15#[derive(Debug, Clone, Copy)]
16pub struct MaterialView<'m> {
17    model: &'m Model,
18    release: Release<'m>,
19}
20
21impl<'m> MaterialView<'m> {
22    /// Wraps a model reference for MaterialResource projection, bound to the
23    /// release its header declares.
24    pub fn new(model: &'m Model) -> Self {
25        Self {
26            model,
27            release: Release::of(model),
28        }
29    }
30
31    /// Returns the underlying model this view borrows from.
32    pub fn model(self) -> &'m Model {
33        self.model
34    }
35
36    /// The release this view's projections read against.
37    ///
38    /// # Errors
39    ///
40    /// [`MaterialError::MultipleSchemas`] or
41    /// [`MaterialError::UnsupportedSchema`] when the header binds none.
42    pub fn schema(self) -> MaterialResult<SchemaVersion> {
43        self.release.bound().map(|(version, _)| version)
44    }
45
46    pub(crate) fn release(self) -> Release<'m> {
47        self.release
48    }
49
50    /// The `entity` records whose `attribute` references `object`, ascending
51    /// by id (#608): the only records a lookup about `object` needs to
52    /// project. A record that names `object` in another attribute, or not at
53    /// all, is not read, so a malformed one elsewhere cannot refuse it.
54    ///
55    /// Through the model's reverse index when something built it, else one
56    /// pass over the `entity` records; neither leaves an index behind. Both
57    /// raise the release's slot error when a record references `object`.
58    pub(crate) fn naming(
59        self,
60        referrers: Option<&ReverseIndex>,
61        entity: &'static str,
62        attribute: &'static str,
63        object: EntityId,
64    ) -> MaterialResult<Vec<(EntityId, &'m Entity)>> {
65        let mut found = Vec::new();
66        if let Some(index) = referrers {
67            for referrer in index.referrers(object) {
68                let Some(record) = self.model.get(referrer.from) else {
69                    continue;
70                };
71                if record.type_name.eq_ignore_ascii_case(entity)
72                    && self.release.slot(entity, referrer.from, attribute)? == referrer.slot
73                {
74                    found.push((referrer.from, record));
75                }
76            }
77        } else {
78            let references = |value: &Value| {
79                let mut hit = false;
80                value.for_each_ref(&mut |target| hit |= target == object);
81                hit
82            };
83            for &id in self.model.ids_of_type(entity) {
84                let Some(record) = self.model.get(id) else {
85                    continue;
86                };
87                if !record.attributes.iter().any(references) {
88                    continue;
89                }
90                let slot = self.release.slot(entity, id, attribute)?;
91                if record.attributes.get(slot).is_some_and(references) {
92                    found.push((id, record));
93                }
94            }
95            found.sort_unstable_by_key(|(id, _)| *id);
96        }
97        Ok(found)
98    }
99
100    pub(crate) fn entity(self, source: EntityId, target: EntityId) -> MaterialResult<&'m Entity> {
101        self.model
102            .get(target)
103            .ok_or(MaterialError::DanglingReference {
104                source_id: source,
105                target,
106            })
107    }
108}
109
110macro_rules! borrowed_entity {
111    ($name:ident, $ifc_name:literal) => {
112        crate::view::borrowed_entity!($name, $ifc_name, []);
113    };
114    // `$subtype`s are schema subtypes the projection also accepts: records
115    // that carry every slot of `$ifc_name` at the same position.
116    ($name:ident, $ifc_name:literal, [$($subtype:literal),*]) => {
117        #[doc = concat!("Borrowed projection of `", $ifc_name, "`.")]
118        #[doc = ""]
119        #[doc = "Projections handed out by a [`crate::MaterialView`] read against the"]
120        #[doc = "release the model declares; one built with `try_new` has no model and"]
121        #[doc = "reads against IFC4, as in 0.2.0."]
122        #[derive(Debug, Clone, Copy)]
123        pub struct $name<'m> {
124            id: ifc_model::EntityId,
125            entity: &'m ifc_model::Entity,
126            release: crate::release::Release<'m>,
127        }
128
129        impl<'m> $name<'m> {
130            /// Wraps `entity` as this view after checking it is an instance
131            /// of the expected IFC entity type; fails with
132            /// [`crate::MaterialError::WrongEntityType`] otherwise.
133            ///
134            /// Without a model there is no header to bind, so the projection
135            /// reads against IFC4. Use [`Self::try_from_view`] to read the
136            /// release a model declares.
137            pub fn try_new(
138                id: ifc_model::EntityId,
139                entity: &'m ifc_model::Entity,
140            ) -> crate::MaterialResult<Self> {
141                Self::check(id, entity, crate::release::Release::LEGACY)
142            }
143
144            /// Looks up `id` in the view's model and projects it against the
145            /// release the model declares.
146            ///
147            /// # Errors
148            ///
149            /// [`crate::MaterialError::UnknownEntity`] when `id` is not in
150            /// the model, and [`crate::MaterialError::WrongEntityType`] when
151            /// it is another entity type.
152            pub fn try_from_view(
153                view: crate::MaterialView<'m>,
154                id: ifc_model::EntityId,
155            ) -> crate::MaterialResult<Self> {
156                let entity = view
157                    .model()
158                    .get(id)
159                    .ok_or(crate::MaterialError::UnknownEntity { id })?;
160                Self::check(id, entity, view.release())
161            }
162
163            fn check(
164                id: ifc_model::EntityId,
165                entity: &'m ifc_model::Entity,
166                release: crate::release::Release<'m>,
167            ) -> crate::MaterialResult<Self> {
168                if !(entity.is_type($ifc_name) $(|| entity.is_type($subtype))*) {
169                    return Err(crate::MaterialError::WrongEntityType {
170                        expected: $ifc_name,
171                        actual: entity.type_name.to_string(),
172                    });
173                }
174                Ok(Self {
175                    id,
176                    entity,
177                    release,
178                })
179            }
180
181            pub(crate) fn from_known(
182                id: ifc_model::EntityId,
183                entity: &'m ifc_model::Entity,
184                release: crate::release::Release<'m>,
185            ) -> Self {
186                Self {
187                    id,
188                    entity,
189                    release,
190                }
191            }
192
193            /// The entity id of the wrapped record.
194            pub fn id(self) -> ifc_model::EntityId {
195                self.id
196            }
197
198            /// The raw, untyped entity record backing this view.
199            pub fn entity(self) -> &'m ifc_model::Entity {
200                self.entity
201            }
202
203            /// The release this projection reads against.
204            ///
205            /// # Errors
206            ///
207            /// [`crate::MaterialError::MultipleSchemas`] or
208            /// [`crate::MaterialError::UnsupportedSchema`] when the model's
209            /// header binds none.
210            pub fn schema(self) -> crate::MaterialResult<crate::SchemaVersion> {
211                self.release.bound().map(|(version, _)| version)
212            }
213
214            /// The release binding of this projection.
215            #[allow(dead_code)]
216            pub(crate) fn release(self) -> crate::release::Release<'m> {
217                self.release
218            }
219
220            /// Slot of `attribute` (IFC4 name) on this record in the bound
221            /// release; `NotInSchema` or `EntityNotInSchema` otherwise.
222            #[allow(dead_code)]
223            pub(crate) fn slot(self, attribute: &'static str) -> crate::MaterialResult<usize> {
224                self.release.slot($ifc_name, self.id, attribute)
225            }
226        }
227    };
228}
229pub(crate) use borrowed_entity;
230
231fn kind(value: &Value) -> &'static str {
232    match value {
233        Value::Null => "null",
234        Value::Derived => "derived marker",
235        Value::Bool(_) => "boolean",
236        Value::LogicalUnknown => "logical unknown",
237        Value::Integer(_) => "integer",
238        Value::Real(_) => "real",
239        Value::Text(_) => "text",
240        Value::Binary(_) => "binary",
241        Value::Enum(_) => "enumeration",
242        Value::Ref(_) => "reference",
243        Value::List(_) => "aggregate",
244        Value::Typed { .. } => "typed value",
245    }
246}
247
248fn invalid(
249    entity_type: &'static str,
250    id: EntityId,
251    attribute: &'static str,
252    expected: &str,
253    actual: &Value,
254) -> MaterialError {
255    MaterialError::InvalidValue {
256        entity: entity_type,
257        id,
258        attribute,
259        value: format!("expected {expected}, found {}", kind(actual)),
260    }
261}
262
263fn optional_raw<'a>(
264    entity_type: &'static str,
265    id: EntityId,
266    entity: &'a Entity,
267    slot: usize,
268    attribute: &'static str,
269) -> MaterialResult<Option<&'a Value>> {
270    match entity.attribute(slot) {
271        None | Some(Value::Null) => Ok(None),
272        Some(Value::Derived) => Err(invalid(
273            entity_type,
274            id,
275            attribute,
276            "an explicit value or $",
277            &Value::Derived,
278        )),
279        Some(value) => Ok(Some(value)),
280    }
281}
282
283fn required_raw<'a>(
284    entity_type: &'static str,
285    id: EntityId,
286    entity: &'a Entity,
287    slot: usize,
288    attribute: &'static str,
289) -> MaterialResult<&'a Value> {
290    optional_raw(entity_type, id, entity, slot, attribute)?.ok_or(MaterialError::MissingAttribute {
291        entity: entity_type,
292        id,
293        attribute,
294    })
295}
296
297fn unwrap_scalar<'a>(
298    entity_type: &'static str,
299    id: EntityId,
300    attribute: &'static str,
301    value: &'a Value,
302) -> MaterialResult<&'a Value> {
303    let mut current = value;
304    for _ in 0..MAX_TYPED_WRAPPERS {
305        match current {
306            Value::Typed { value, .. } => current = value,
307            _ => return Ok(current),
308        }
309    }
310    Err(MaterialError::InvalidValue {
311        entity: entity_type,
312        id,
313        attribute,
314        value: format!("typed-wrapper nesting exceeds {MAX_TYPED_WRAPPERS}"),
315    })
316}
317
318pub(crate) fn required_text<'a>(
319    entity_type: &'static str,
320    id: EntityId,
321    entity: &'a Entity,
322    slot: usize,
323    attribute: &'static str,
324) -> MaterialResult<&'a str> {
325    let raw = required_raw(entity_type, id, entity, slot, attribute)?;
326    let value = unwrap_scalar(entity_type, id, attribute, raw)?;
327    match value {
328        Value::Text(value) => Ok(value),
329        _ => Err(invalid(entity_type, id, attribute, "text", value)),
330    }
331}
332
333pub(crate) fn optional_text<'a>(
334    entity_type: &'static str,
335    id: EntityId,
336    entity: &'a Entity,
337    slot: usize,
338    attribute: &'static str,
339) -> MaterialResult<Option<&'a str>> {
340    let Some(raw) = optional_raw(entity_type, id, entity, slot, attribute)? else {
341        return Ok(None);
342    };
343    let value = unwrap_scalar(entity_type, id, attribute, raw)?;
344    match value {
345        Value::Text(value) => Ok(Some(value)),
346        _ => Err(invalid(entity_type, id, attribute, "text or $", value)),
347    }
348}
349
350pub(crate) fn required_ref(
351    entity_type: &'static str,
352    id: EntityId,
353    entity: &Entity,
354    slot: usize,
355    attribute: &'static str,
356) -> MaterialResult<EntityId> {
357    let value = required_raw(entity_type, id, entity, slot, attribute)?;
358    match value {
359        Value::Ref(target) => Ok(*target),
360        _ => Err(invalid(entity_type, id, attribute, "reference", value)),
361    }
362}
363
364pub(crate) fn optional_ref(
365    entity_type: &'static str,
366    id: EntityId,
367    entity: &Entity,
368    slot: usize,
369    attribute: &'static str,
370) -> MaterialResult<Option<EntityId>> {
371    let Some(value) = optional_raw(entity_type, id, entity, slot, attribute)? else {
372        return Ok(None);
373    };
374    match value {
375        Value::Ref(target) => Ok(Some(*target)),
376        _ => Err(invalid(entity_type, id, attribute, "reference or $", value)),
377    }
378}
379
380fn refs_from_aggregate(
381    entity_type: &'static str,
382    id: EntityId,
383    attribute: &'static str,
384    value: &Value,
385    minimum: usize,
386) -> MaterialResult<Vec<EntityId>> {
387    let Value::List(items) = value else {
388        return Err(invalid(
389            entity_type,
390            id,
391            attribute,
392            "an immediate aggregate",
393            value,
394        ));
395    };
396    if items.len() < minimum {
397        return Err(MaterialError::InvalidValue {
398            entity: entity_type,
399            id,
400            attribute,
401            value: format!("expected at least {minimum} item(s), found {}", items.len()),
402        });
403    }
404    items
405        .iter()
406        .map(|item| match item {
407            Value::Ref(target) => Ok(*target),
408            _ => Err(invalid(
409                entity_type,
410                id,
411                attribute,
412                "an aggregate of direct references",
413                item,
414            )),
415        })
416        .collect()
417}
418
419pub(crate) fn required_refs(
420    entity_type: &'static str,
421    id: EntityId,
422    entity: &Entity,
423    slot: usize,
424    attribute: &'static str,
425    minimum: usize,
426) -> MaterialResult<Vec<EntityId>> {
427    refs_from_aggregate(
428        entity_type,
429        id,
430        attribute,
431        required_raw(entity_type, id, entity, slot, attribute)?,
432        minimum,
433    )
434}
435
436pub(crate) fn optional_refs(
437    entity_type: &'static str,
438    id: EntityId,
439    entity: &Entity,
440    slot: usize,
441    attribute: &'static str,
442    minimum: usize,
443) -> MaterialResult<Option<Vec<EntityId>>> {
444    let Some(value) = optional_raw(entity_type, id, entity, slot, attribute)? else {
445        return Ok(None);
446    };
447    refs_from_aggregate(entity_type, id, attribute, value, minimum).map(Some)
448}
449
450fn number_value(
451    entity_type: &'static str,
452    id: EntityId,
453    attribute: &'static str,
454    raw: &Value,
455) -> MaterialResult<f64> {
456    let value = unwrap_scalar(entity_type, id, attribute, raw)?;
457    let number = match value {
458        Value::Real(value) => *value,
459        Value::Integer(value) => *value as f64,
460        _ => return Err(invalid(entity_type, id, attribute, "a number", value)),
461    };
462    if number.is_finite() {
463        Ok(number)
464    } else {
465        Err(MaterialError::InvalidValue {
466            entity: entity_type,
467            id,
468            attribute,
469            value: "number must be finite".to_owned(),
470        })
471    }
472}
473
474pub(crate) fn required_number(
475    entity_type: &'static str,
476    id: EntityId,
477    entity: &Entity,
478    slot: usize,
479    attribute: &'static str,
480) -> MaterialResult<f64> {
481    number_value(
482        entity_type,
483        id,
484        attribute,
485        required_raw(entity_type, id, entity, slot, attribute)?,
486    )
487}
488
489pub(crate) fn optional_number(
490    entity_type: &'static str,
491    id: EntityId,
492    entity: &Entity,
493    slot: usize,
494    attribute: &'static str,
495) -> MaterialResult<Option<f64>> {
496    let Some(value) = optional_raw(entity_type, id, entity, slot, attribute)? else {
497        return Ok(None);
498    };
499    number_value(entity_type, id, attribute, value).map(Some)
500}
501
502fn integer_value(
503    entity_type: &'static str,
504    id: EntityId,
505    attribute: &'static str,
506    raw: &Value,
507) -> MaterialResult<i64> {
508    let value = unwrap_scalar(entity_type, id, attribute, raw)?;
509    match value {
510        Value::Integer(value) => Ok(*value),
511        _ => Err(invalid(entity_type, id, attribute, "an integer", value)),
512    }
513}
514
515pub(crate) fn optional_integer(
516    entity_type: &'static str,
517    id: EntityId,
518    entity: &Entity,
519    slot: usize,
520    attribute: &'static str,
521) -> MaterialResult<Option<i64>> {
522    let Some(value) = optional_raw(entity_type, id, entity, slot, attribute)? else {
523        return Ok(None);
524    };
525    integer_value(entity_type, id, attribute, value).map(Some)
526}
527
528pub(crate) fn required_enum<'a>(
529    entity_type: &'static str,
530    id: EntityId,
531    entity: &'a Entity,
532    slot: usize,
533    attribute: &'static str,
534) -> MaterialResult<&'a str> {
535    let raw = required_raw(entity_type, id, entity, slot, attribute)?;
536    let value = unwrap_scalar(entity_type, id, attribute, raw)?;
537    match value {
538        Value::Enum(token) => Ok(token),
539        _ => Err(invalid(entity_type, id, attribute, "an enumeration", value)),
540    }
541}
542
543pub(crate) fn optional_logical(
544    entity_type: &'static str,
545    id: EntityId,
546    entity: &Entity,
547    slot: usize,
548    attribute: &'static str,
549) -> MaterialResult<Option<LogicalValue>> {
550    let Some(raw) = optional_raw(entity_type, id, entity, slot, attribute)? else {
551        return Ok(None);
552    };
553    let value = unwrap_scalar(entity_type, id, attribute, raw)?;
554    match value {
555        Value::Bool(false) => Ok(Some(LogicalValue::False)),
556        Value::Bool(true) => Ok(Some(LogicalValue::True)),
557        Value::LogicalUnknown => Ok(Some(LogicalValue::Unknown)),
558        _ => Err(invalid(
559            entity_type,
560            id,
561            attribute,
562            "a logical value or $",
563            value,
564        )),
565    }
566}
567
568pub(crate) fn required_number_array_2(
569    entity_type: &'static str,
570    id: EntityId,
571    entity: &Entity,
572    slot: usize,
573    attribute: &'static str,
574) -> MaterialResult<[f64; 2]> {
575    let value = required_raw(entity_type, id, entity, slot, attribute)?;
576    let Value::List(items) = value else {
577        return Err(invalid(
578            entity_type,
579            id,
580            attribute,
581            "an ARRAY [1:2] of two numbers",
582            value,
583        ));
584    };
585    if items.len() != 2 {
586        return Err(MaterialError::InvalidValue {
587            entity: entity_type,
588            id,
589            attribute,
590            value: format!("expected 2 values, found {}", items.len()),
591        });
592    }
593    Ok([
594        number_value(entity_type, id, attribute, &items[0])?,
595        number_value(entity_type, id, attribute, &items[1])?,
596    ])
597}