Skip to main content

ifc_resource/query/
allocation.rs

1//! `IfcRelAssignsToResource` projections and inverse lookup.
2
3use ifc_model::EntityId;
4
5use crate::error::{ResourceError, ResourceResult};
6use crate::view::{validate_object_assignment, Record, ResourceView};
7use crate::ResourceKind;
8
9#[derive(Debug, Clone, PartialEq, Eq)]
10/// Decoded `IfcRelAssignsToResource` assignment: a resource and the objects
11/// assigned to it.
12pub struct ResourceAllocation {
13    relation: EntityId,
14    resource: EntityId,
15    related_objects: Vec<EntityId>,
16    related_objects_type: Option<String>,
17}
18
19impl ResourceAllocation {
20    /// The entity id of the `IfcRelAssignsToResource` relation itself.
21    #[must_use]
22    pub fn relation_id(&self) -> EntityId {
23        self.relation
24    }
25
26    /// The `RelatingResource` attribute: the assigned resource or resource
27    /// type.
28    #[must_use]
29    pub fn resource_id(&self) -> EntityId {
30        self.resource
31    }
32
33    /// The `RelatedObjects` attribute: objects the resource is assigned to.
34    #[must_use]
35    pub fn related_objects(&self) -> &[EntityId] {
36        &self.related_objects
37    }
38
39    /// The `RelatedObjectsType` enumeration, when authored.
40    #[must_use]
41    pub fn related_objects_type(&self) -> Option<&str> {
42        self.related_objects_type.as_deref()
43    }
44}
45
46impl<'m, 's> ResourceView<'m, 's> {
47    /// Projects an `IfcRelAssignsToResource` relation by entity id.
48    pub fn allocation(&self, id: EntityId) -> ResourceResult<ResourceAllocation> {
49        let record = self.record(id, "IfcRelAssignsToResource")?;
50        decode_allocation(record)
51    }
52
53    /// Every `IfcRelAssignsToResource` relation naming this resource as
54    /// `RelatingResource`, in ancestor order.
55    ///
56    /// Under IFC2X3 an `IfcConstructionMaterialResource` or
57    /// `IfcConstructionProductResource` also carries the release's `WR1`
58    /// (at most one such relation) and `WR2` (its `RelatedObjectsType`, when
59    /// authored, is `PRODUCT`); a violation is a typed refusal.
60    pub fn allocations_for(&self, resource: EntityId) -> ResourceResult<Vec<ResourceAllocation>> {
61        let projected = self.resource(resource)?;
62        let mut result = Vec::new();
63        for relation in self.ids_of_ancestor("IfcRelAssignsToResource") {
64            let allocation = self.allocation(relation)?;
65            if allocation.resource == resource {
66                result.push(allocation);
67            }
68        }
69        if self.is_ifc2x3()
70            && matches!(
71                projected.kind(),
72                ResourceKind::Material | ResourceKind::Product
73            )
74        {
75            if result.len() > 1 {
76                return Err(ResourceError::SemanticViolation {
77                    entity: Some(resource),
78                    rule: "IFC2X3 material/product resource WR1: at most one ResourceOf",
79                });
80            }
81            if result.first().is_some_and(|allocation| {
82                allocation
83                    .related_objects_type()
84                    .is_some_and(|category| !category.eq_ignore_ascii_case("PRODUCT"))
85            }) {
86                return Err(ResourceError::SemanticViolation {
87                    entity: Some(resource),
88                    rule: "IFC2X3 material/product resource WR2: ResourceOf must be PRODUCT",
89                });
90            }
91        }
92        Ok(result)
93    }
94}
95
96fn decode_allocation(record: Record<'_, '_>) -> ResourceResult<ResourceAllocation> {
97    let resource = record.required_ref_select(
98        "RelatingResource",
99        "IfcResourceSelect",
100        &["IfcResource", "IfcTypeResource"],
101    )?;
102    let related_objects = record.refs("RelatedObjects", "IfcObjectDefinition", 1, false, true)?;
103    let related_objects_type = record.optional_enum("RelatedObjectsType")?;
104    validate_object_assignment(
105        record.model,
106        record.schema,
107        Some(record.id),
108        related_objects_type,
109        &related_objects,
110    )?;
111    if related_objects.contains(&resource) {
112        return Err(ResourceError::SemanticViolation {
113            entity: Some(record.id),
114            rule: "IfcRelAssignsToResource must not assign its resource to itself",
115        });
116    }
117    Ok(ResourceAllocation {
118        relation: record.id,
119        resource,
120        related_objects,
121        related_objects_type: related_objects_type.map(str::to_owned),
122    })
123}