Skip to main content

ifc_properties/query/
assignment.rs

1//! Resolving which properties apply to an object.
2//!
3//! # Precedence is a real decision, and it is made explicit
4//!
5//! An occurrence inherits property sets from its type
6//! (`IfcRelDefinesByType` -> `IfcTypeObject.HasPropertySets`) and may carry
7//! its own (`IfcRelDefinesByProperties`). When both state a set of the same
8//! NAME, the occurrence wins: that is the IFC4 rule, and it is what every
9//! authoring tool means by overriding a type default.
10//!
11//! Nothing about that is inferable from the entity graph -- both routes are
12//! just relationships -- so this module states it once, applies it uniformly,
13//! and reports which source each surviving set came from. A caller that needs
14//! the type's original value can still see it: overridden sets are not
15//! discarded, they are recorded as shadowed.
16//!
17//! # Slots
18//!
19//! ```text
20//! IfcRelDefinesByType  4 = RelatedObjects  5 = RelatingType
21//! ```
22//!
23//! Note this is the OPPOSITE arrangement to `IfcRelDefinesByProperties`,
24//! where the definition is slot 5 and the objects slot 4 -- the same two slot
25//! numbers carrying different roles.
26
27use std::collections::BTreeMap;
28
29use ifc_model::{EntityId, Model, Value};
30
31use crate::error::PropertyAnomaly;
32use crate::pset::{property_sets_by_object, Attachment, PropertySet};
33
34const REL_TYPE_RELATED_OBJECTS: usize = 4;
35const REL_TYPE_RELATING_TYPE: usize = 5;
36
37/// Where a resolved property or quantity set came from.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Source {
40    /// Stated directly on the occurrence.
41    Occurrence,
42    /// Inherited from the object's type.
43    Type(EntityId),
44}
45
46/// A property set that applies to an object, with its provenance.
47#[derive(Debug, Clone, PartialEq)]
48#[non_exhaustive]
49pub struct ResolvedSet {
50    /// Where it came from.
51    pub source: Source,
52    /// The set itself.
53    pub set: PropertySet,
54    /// A same-named set this one overrode, if any.
55    ///
56    /// Populated when an occurrence set shadows a type set. Kept rather than
57    /// dropped so a caller can explain WHY a value differs from the type
58    /// default, which is a question every model checker eventually asks.
59    pub shadowed: Option<Box<ResolvedSet>>,
60}
61
62/// Resolved property sets per object, after precedence is applied.
63pub type ResolvedProperties = BTreeMap<EntityId, Vec<ResolvedSet>>;
64
65/// Every property set applying to every object, precedence applied.
66///
67/// Sets are ordered by name so output is deterministic regardless of file
68/// ordering or hash iteration.
69pub fn resolved_properties(model: &Model) -> (ResolvedProperties, Vec<PropertyAnomaly>) {
70    let (direct, mut anomalies) = property_sets_by_object(model);
71    let out = resolve(model, &direct, &mut anomalies)
72        .into_iter()
73        .map(|(object, sets)| {
74            let sets = sets
75                .into_iter()
76                .map(|p| ResolvedSet {
77                    source: p.source,
78                    set: p.set,
79                    shadowed: p.shadowed.map(|(source, set)| {
80                        Box::new(ResolvedSet {
81                            source,
82                            set,
83                            shadowed: None,
84                        })
85                    }),
86                })
87                .collect();
88            (object, sets)
89        })
90        .collect();
91    (out, anomalies)
92}
93
94/// A set that carries an id and a name, so precedence can key it.
95pub(super) trait NamedSet: Clone {
96    fn set_id(&self) -> EntityId;
97    fn set_name(&self) -> Option<&str>;
98}
99
100impl NamedSet for PropertySet {
101    fn set_id(&self) -> EntityId {
102        self.id
103    }
104
105    fn set_name(&self) -> Option<&str> {
106        self.name.as_deref()
107    }
108}
109
110/// A set that won its name for one object, and the type set it overrode.
111pub(super) struct Precedence<S> {
112    pub(super) source: Source,
113    pub(super) set: S,
114    pub(super) shadowed: Option<(Source, S)>,
115}
116
117/// Apply precedence to the sets attached to each object and its type.
118///
119/// Anomalies for type assignments and for same-named sets on one owner are
120/// appended to `anomalies`.
121pub(super) fn resolve<S: NamedSet>(
122    model: &Model,
123    direct: &BTreeMap<EntityId, Vec<(Attachment, S)>>,
124    anomalies: &mut Vec<PropertyAnomaly>,
125) -> BTreeMap<EntityId, Vec<Precedence<S>>> {
126    let types = type_assignments(model, anomalies);
127
128    // Every object that has sets of its own or a type that does.
129    let mut objects: Vec<EntityId> = direct.keys().copied().collect();
130    objects.extend(types.keys().copied());
131    objects.sort_unstable();
132    objects.dedup();
133
134    duplicate_set_names(direct, anomalies);
135
136    let mut out: BTreeMap<EntityId, Vec<Precedence<S>>> = BTreeMap::new();
137    for object in objects {
138        // Type sets first, so occurrence sets can overwrite by name. Within
139        // one source, sets arrive in id order and the first of a name wins.
140        let mut by_name: BTreeMap<String, Precedence<S>> = BTreeMap::new();
141        if let Some(&type_id) = types.get(&object) {
142            for (attachment, set) in direct.get(&type_id).into_iter().flatten() {
143                // A type's own sets are what an occurrence inherits. Sets
144                // attached to the type by the forbidden relationship are
145                // included: the file states them, and the anomaly already
146                // records that it should not have.
147                let _ = attachment;
148                if by_name.contains_key(&key(set)) {
149                    continue;
150                }
151                by_name.insert(
152                    key(set),
153                    Precedence {
154                        source: Source::Type(type_id),
155                        set: set.clone(),
156                        shadowed: None,
157                    },
158                );
159            }
160        }
161        for (attachment, set) in direct.get(&object).into_iter().flatten() {
162            if *attachment != Attachment::Occurrence {
163                continue;
164            }
165            // A same-named occurrence set already resolved is a duplicate,
166            // not something to shadow: shadowing is occurrence over type.
167            if by_name
168                .get(&key(set))
169                .is_some_and(|r| r.source == Source::Occurrence)
170            {
171                continue;
172            }
173            let shadowed = by_name.remove(&key(set)).map(|r| (r.source, r.set));
174            by_name.insert(
175                key(set),
176                Precedence {
177                    source: Source::Occurrence,
178                    set: set.clone(),
179                    shadowed,
180                },
181            );
182        }
183        if !by_name.is_empty() {
184            out.insert(object, by_name.into_values().collect());
185        }
186    }
187    out
188}
189
190/// Report every owner holding two same-named sets through one route.
191///
192/// Checked per owner and per attachment route, so a type's duplicates are
193/// reported once even when many occurrences inherit them, and even when none
194/// does. An occurrence set overriding a same-named type set is precedence,
195/// not a duplicate, and is not reported. Sets arrive in id order, so the
196/// kept set is the one resolution keeps.
197fn duplicate_set_names<S: NamedSet>(
198    direct: &BTreeMap<EntityId, Vec<(Attachment, S)>>,
199    anomalies: &mut Vec<PropertyAnomaly>,
200) {
201    for (&owner, sets) in direct {
202        let mut kept: BTreeMap<(bool, String), EntityId> = BTreeMap::new();
203        for (attachment, set) in sets {
204            let slot = (*attachment == Attachment::Type, key(set));
205            match kept.get(&slot) {
206                Some(&first) => anomalies.push(PropertyAnomaly::DuplicateSetName {
207                    owner,
208                    kept: first,
209                    rejected: set.set_id(),
210                }),
211                None => {
212                    kept.insert(slot, set.set_id());
213                }
214            }
215        }
216    }
217}
218
219/// Property sets applying to one object.
220pub fn properties_of(model: &Model, object: EntityId) -> Vec<ResolvedSet> {
221    resolved_properties(model)
222        .0
223        .remove(&object)
224        .unwrap_or_default()
225}
226
227/// Find a single property by set name and property name.
228///
229/// Returns the winning value after precedence, so a caller asking for
230/// `Pset_WallCommon.IsExternal` gets the occurrence's answer when it has one
231/// and the type's otherwise -- which is what the question means.
232pub fn property_value<'a>(
233    resolved: &'a [ResolvedSet],
234    set_name: &str,
235    property_name: &str,
236) -> Option<&'a crate::pset::Property> {
237    resolved
238        .iter()
239        .find(|r| r.set.name.as_deref() == Some(set_name))
240        .and_then(|r| r.set.property(property_name))
241}
242
243/// Map each object to its type, via `IfcRelDefinesByType`.
244fn type_assignments(
245    model: &Model,
246    anomalies: &mut Vec<PropertyAnomaly>,
247) -> BTreeMap<EntityId, EntityId> {
248    let mut out: BTreeMap<EntityId, EntityId> = BTreeMap::new();
249    // First relationship by id wins, whatever order the file lists them in.
250    let mut relations = model.ids_of_type("IFCRELDEFINESBYTYPE").to_vec();
251    relations.sort_unstable();
252    for id in relations {
253        let Some(rel) = model.get(id) else { continue };
254        let Some(type_id) = rel.attributes.get(REL_TYPE_RELATING_TYPE).and_then(one_ref) else {
255            continue;
256        };
257        if model.get(type_id).is_none() {
258            anomalies.push(PropertyAnomaly::MissingDefinition {
259                relationship: id,
260                definition: type_id,
261            });
262            continue;
263        }
264        for object in rel
265            .attributes
266            .get(REL_TYPE_RELATED_OBJECTS)
267            .and_then(refs)
268            .unwrap_or_default()
269        {
270            if model.get(object).is_none() {
271                anomalies.push(PropertyAnomaly::MissingObject {
272                    relationship: id,
273                    object,
274                });
275                continue;
276            }
277            match out.get(&object) {
278                None => {
279                    out.insert(object, type_id);
280                }
281                Some(&kept) if kept != type_id => anomalies.push(PropertyAnomaly::TypedTwice {
282                    object,
283                    kept,
284                    rejected: type_id,
285                    relation: id,
286                }),
287                Some(_) => {}
288            }
289        }
290    }
291    out
292}
293
294/// Key a set by name, falling back to its id when the file omits the name.
295///
296/// `ExistsName` requires one, so the fallback only fires on malformed files.
297/// Keying those by id keeps them distinct instead of collapsing every
298/// unnamed set into one bucket.
299fn key<S: NamedSet>(set: &S) -> String {
300    match set.set_name() {
301        Some(name) => name.to_string(),
302        None => format!("#{}", set.set_id().0),
303    }
304}
305
306fn one_ref(value: &Value) -> Option<EntityId> {
307    match value.unwrap_typed() {
308        Value::Ref(id) => Some(*id),
309        _ => None,
310    }
311}
312
313fn refs(value: &Value) -> Option<Vec<EntityId>> {
314    match value {
315        Value::List(items) => Some(items.iter().filter_map(one_ref).collect()),
316        _ => None,
317    }
318}