Skip to main content

ifc_properties/pset/
set.rs

1//! `IfcPropertySet` and how it reaches an object.
2//!
3//! # Two attachment routes, and one of them is forbidden for types
4//!
5//! ```text
6//! IfcRelDefinesByProperties  4 = RelatedObjects  5 = RelatingPropertyDefinition
7//! IfcTypeObject              5 = HasPropertySets          (a direct attribute)
8//! ```
9//!
10//! `IfcRelDefinesByProperties` carries a WHERE rule:
11//!
12//! ```text
13//! NoRelatedTypeObject : SIZEOF(QUERY(Types <* RelatedObjects |
14//!                       'IFC4.IFCTYPEOBJECT' IN TYPEOF(Types))) = 0;
15//! ```
16//!
17//! A type object may NOT be given properties by that relationship: it holds
18//! them in its own `HasPropertySets` attribute instead. A reader that only
19//! follows the relationship finds no type properties at all, and one that
20//! accepts types through it will happily read malformed files without
21//! comment. Both routes are read here, and the forbidden combination is
22//! reported.
23
24use std::collections::BTreeMap;
25use std::sync::Arc;
26
27use ifc_model::{EntityId, Model, Value};
28
29use crate::error::PropertyAnomaly;
30use crate::nesting::Nesting;
31use crate::pset::attach::sets_by_object;
32use crate::pset::scalar::{read_property, Property};
33
34/// `IfcPropertySet.HasProperties`.
35const SET_HAS_PROPERTIES: usize = 4;
36/// `IfcRoot.Name` / `Description`.
37const ROOT_NAME: usize = 2;
38const ROOT_DESCRIPTION: usize = 3;
39
40/// How a property set reached the object that carries it.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Attachment {
43    /// Attached to an occurrence by `IfcRelDefinesByProperties`.
44    Occurrence,
45    /// Held directly by an `IfcTypeObject` in `HasPropertySets`.
46    Type,
47}
48
49/// An `IfcPropertySet` with its properties resolved.
50#[derive(Debug, Clone, PartialEq)]
51#[non_exhaustive]
52pub struct PropertySet {
53    /// The `IfcPropertySet` entity.
54    pub id: EntityId,
55    /// `Name`. The schema requires it (`ExistsName`).
56    pub name: Option<Arc<str>>,
57    /// `Description`, when stated.
58    pub description: Option<Arc<str>>,
59    /// Properties in file order.
60    pub properties: Vec<Property>,
61}
62
63impl PropertySet {
64    /// Look up a property by name.
65    ///
66    /// The schema requires unique property names within a set
67    /// (`UniquePropertyNames`), so the first match is the only match in a
68    /// well-formed file. In a malformed one this is the first in
69    /// `HasProperties` order, and
70    /// [`property_sets_by_object`] reports the others as
71    /// [`PropertyAnomaly::DuplicatePropertyName`].
72    pub fn property(&self, name: &str) -> Option<&Property> {
73        self.properties
74            .iter()
75            .find(|p| p.name.as_deref() == Some(name))
76    }
77}
78
79/// Read one `IfcPropertySet` by id, resolving its properties.
80///
81/// Returns `None` when the entity is absent or is not a property set. Other
82/// `IfcPropertySetDefinition` subtypes (quantity sets, predefined sets) are
83/// deliberately excluded: they are not `IfcPropertySet` and have their own
84/// attribute layouts.
85///
86/// Members this reader cannot resolve (absent ids, cyclic or over-deep
87/// complex properties) are left out without saying so; use
88/// [`property_set_checked`] to have each one reported.
89pub fn property_set(model: &Model, id: EntityId) -> Option<PropertySet> {
90    property_set_checked(model, id).map(|(set, _)| set)
91}
92
93/// Read one `IfcPropertySet` by id, reporting every member left unread.
94///
95/// The same value as [`property_set`], with a
96/// [`PropertyAnomaly::MissingMember`] for each `HasProperties` id absent
97/// from the file, a [`PropertyAnomaly::MemberNotReference`] for each item
98/// that is not an entity reference, a [`PropertyAnomaly::DuplicateMember`]
99/// for each member listed again (read once), and the nesting anomalies
100/// described on
101/// [`property_checked`](crate::property_checked) for its complex properties.
102pub fn property_set_checked(
103    model: &Model,
104    id: EntityId,
105) -> Option<(PropertySet, Vec<PropertyAnomaly>)> {
106    let entity = model.get(id)?;
107    if !entity.type_name.eq_ignore_ascii_case("IFCPROPERTYSET") {
108        return None;
109    }
110    let mut anomalies = Vec::new();
111    let mut nesting = Nesting::new(&mut anomalies);
112    let mut properties = Vec::new();
113    let members = nesting.members(
114        id,
115        "HasProperties",
116        entity.attributes.get(SET_HAS_PROPERTIES),
117    );
118    for member in members {
119        if !nesting.admit(model, id, member) {
120            continue;
121        }
122        if let Some(property) = read_property(model, member, &mut nesting) {
123            properties.push(property);
124        }
125    }
126    let set = PropertySet {
127        id,
128        name: entity.attributes.get(ROOT_NAME).and_then(text),
129        description: entity.attributes.get(ROOT_DESCRIPTION).and_then(text),
130        properties,
131    };
132    Some((set, anomalies))
133}
134
135/// Property sets found on each object, with how each one was attached.
136pub type AttachedSets = BTreeMap<EntityId, Vec<(Attachment, PropertySet)>>;
137
138/// Every property set in the file, keyed by the object carrying it.
139///
140/// Both routes are followed. A set reachable by both appears once per object,
141/// with `Attachment` recording how it arrived: precedence is a caller
142/// decision, so the reader must not collapse the distinction here.
143///
144/// Anomalies report a type object attached by the forbidden relationship,
145/// relationships whose targets are missing from the file, and, once per set,
146/// the members [`property_set_checked`] could not resolve.
147pub fn property_sets_by_object(model: &Model) -> (AttachedSets, Vec<PropertyAnomaly>) {
148    let (out, mut anomalies) =
149        sets_by_object(model, property_set_checked, |set: &PropertySet| set.id);
150    // A set shared by many objects is checked once.
151    let mut unique: BTreeMap<EntityId, &PropertySet> = BTreeMap::new();
152    for (_, set) in out.values().flatten() {
153        unique.entry(set.id).or_insert(set);
154    }
155    for set in unique.values() {
156        duplicate_property_names(set, &mut anomalies);
157    }
158    (out, anomalies)
159}
160
161/// `UniquePropertyNames` (IFC4) / `WR32` (IFC2X3): report each property whose
162/// name an earlier one in the same set already has.
163fn duplicate_property_names(set: &PropertySet, anomalies: &mut Vec<PropertyAnomaly>) {
164    let mut first: BTreeMap<&str, EntityId> = BTreeMap::new();
165    for property in &set.properties {
166        let Some(name) = property.name.as_deref() else {
167            continue;
168        };
169        match first.get(name) {
170            Some(&kept) => anomalies.push(PropertyAnomaly::DuplicatePropertyName {
171                set: set.id,
172                kept,
173                rejected: property.id,
174            }),
175            None => {
176                first.insert(name, property.id);
177            }
178        }
179    }
180}
181
182fn text(value: &Value) -> Option<Arc<str>> {
183    match value.unwrap_typed() {
184        Value::Text(t) => Some(t.clone()),
185        _ => None,
186    }
187}