Skip to main content

ifc_properties/template/
check.rs

1//! Property sets compared with the `IfcPropertySetTemplate` that
2//! `IfcRelDefinesByTemplate` links them to (#109).
3//!
4//! The check reads the model and its templates only, bound to the release
5//! the header declares; the shipped Pset catalogue is not consulted (that is
6//! `ifc-template-catalog`, which does not depend on the model). Each pair of
7//! a set and one of its templates is compared for:
8//!
9//! - the set's entity against the template's `TemplateType` (`form.rs`);
10//! - its members against the property templates, by `Name`: missing,
11//!   unexpected, wrong form, wrong measure type, recursively into complex
12//!   properties and complex templates (`members.rs`);
13//! - every object carrying the set against the template's `TemplateType`
14//!   and `ApplicableEntity` (`applicability.rs`).
15//!
16//! What the release's documentation leaves open is reported as
17//! [`TemplateFinding::Undecided`] rather than guessed, and malformed facts
18//! met on the way as [`PropertyAnomaly`].
19//!
20//! ## Internal split
21//!
22//! - `finding.rs`: the public report types.
23//! - `form.rs`: what each template type prescribes, per release.
24//! - `members.rs`: members read and compared.
25//! - `applicability.rs`: carriers, attachment side and `ApplicableEntity`.
26
27mod applicability;
28mod finding;
29mod form;
30mod members;
31
32use std::collections::{BTreeMap, BTreeSet};
33use std::sync::Arc;
34
35use ifc_model::{Entity, EntityId, Model};
36
37pub use finding::{MeasureRole, TemplateFinding, TemplateReport, UndecidedReason};
38
39use super::layout::Layout;
40use super::property_set::{read_set_template, template_links, PropertySetTemplate};
41use crate::error::{PropertyAnomaly, TemplateError};
42use crate::nesting::Nesting;
43use applicability::{applicable, carriers, Verdict};
44use form::{attachment, set_entity};
45use members::{read_members, Comparison, Member};
46
47/// Compare every templated property set in the model with its templates.
48///
49/// A set is templated when an `IfcRelDefinesByTemplate` names it; a set
50/// with several templates is compared with each. Untemplated sets are not
51/// looked at. See [`TemplateFinding`] for what is reported and
52/// [`TemplateReport`] for the order.
53///
54/// # Errors
55///
56/// [`TemplateError::Release`] when the model binds to no single supported
57/// release (as [`exact_schema`](crate::exact_schema) fails), and
58/// [`TemplateError::NoTemplates`] for a release without templates (IFC2X3).
59pub fn template_deviations(model: &Model) -> Result<TemplateReport, TemplateError> {
60    let layout = Layout::declared(model)?;
61    let mut report = TemplateReport::default();
62    let links = template_links(model, layout);
63    for &id in model.ids_of_type("IFCRELDEFINESBYTEMPLATE") {
64        if let Some(rel) = model.get(id) {
65            layout.check_arity(id, rel, &mut report.anomalies);
66        }
67    }
68    let templates = read_templates(model, layout, &links, &mut report.anomalies);
69    let templated: BTreeSet<EntityId> = links.keys().copied().collect();
70    let carried = carriers(model, layout, &templated, &mut report.anomalies);
71    let no_carriers = BTreeSet::new();
72    for (&set_id, pairs) in &links {
73        let relationship = pairs[0].0;
74        let Some(set) = model.get(set_id) else {
75            report.anomalies.push(PropertyAnomaly::MissingDefinition {
76                relationship,
77                definition: set_id,
78            });
79            continue;
80        };
81        if !layout.is_a(&set.type_name, "IFCPROPERTYSETDEFINITION") {
82            report.anomalies.push(PropertyAnomaly::MalformedAttribute {
83                entity: relationship,
84                attribute: "RelatedPropertySets",
85                found: format!("#{} {}", set_id.0, set.type_name),
86            });
87            continue;
88        }
89        layout.check_arity(set_id, set, &mut report.anomalies);
90        let members = set_members(model, layout, set_id, set, &mut report.anomalies);
91        let mut ids: Vec<EntityId> = pairs.iter().map(|(_, template)| *template).collect();
92        ids.sort_unstable();
93        ids.dedup();
94        for template in ids.iter().filter_map(|id| templates.get(id)) {
95            let pair = Pair {
96                set_id,
97                set,
98                members: members.as_deref(),
99                template,
100                objects: carried.get(&set_id).unwrap_or(&no_carriers),
101            };
102            pair.check(model, layout, &mut report.findings);
103        }
104    }
105    Ok(report)
106}
107
108/// Read each linked template once, reporting links that name none.
109fn read_templates(
110    model: &Model,
111    layout: Layout,
112    links: &BTreeMap<EntityId, Vec<(EntityId, EntityId)>>,
113    anomalies: &mut Vec<PropertyAnomaly>,
114) -> BTreeMap<EntityId, PropertySetTemplate> {
115    // Each template once, with the first relationship naming it.
116    let mut first: BTreeMap<EntityId, EntityId> = BTreeMap::new();
117    for &(relationship, template) in links.values().flatten() {
118        first
119            .entry(template)
120            .and_modify(|seen| *seen = (*seen).min(relationship))
121            .or_insert(relationship);
122    }
123    let mut read = BTreeMap::new();
124    for (id, relationship) in first {
125        match model.get(id) {
126            None => anomalies.push(PropertyAnomaly::MissingDefinition {
127                relationship,
128                definition: id,
129            }),
130            Some(entity) => match read_set_template(model, layout, id, anomalies) {
131                Some(template) => {
132                    read.insert(id, template);
133                }
134                None => anomalies.push(PropertyAnomaly::NotATemplate {
135                    container: relationship,
136                    member: id,
137                    type_name: entity.type_name.to_string(),
138                }),
139            },
140        }
141    }
142    read
143}
144
145/// The members of a property set or element quantity; `None` for any other
146/// property set definition, whose members are not named properties.
147fn set_members<'m>(
148    model: &'m Model,
149    layout: Layout,
150    id: EntityId,
151    set: &'m Entity,
152    anomalies: &mut Vec<PropertyAnomaly>,
153) -> Option<Vec<Member<'m>>> {
154    let attribute = if layout.is_a(&set.type_name, "IFCPROPERTYSET") {
155        "HasProperties"
156    } else if layout.is_a(&set.type_name, "IFCELEMENTQUANTITY") {
157        "Quantities"
158    } else {
159        return None;
160    };
161    let mut nesting = Nesting::new(anomalies);
162    let list = layout.get(set, attribute);
163    Some(read_members(
164        model,
165        layout,
166        id,
167        list,
168        attribute,
169        &mut nesting,
170    ))
171}
172
173/// One set and one of its templates.
174struct Pair<'a, 'm> {
175    set_id: EntityId,
176    set: &'m Entity,
177    members: Option<&'a [Member<'m>]>,
178    template: &'a PropertySetTemplate,
179    objects: &'a BTreeSet<EntityId>,
180}
181
182impl Pair<'_, '_> {
183    fn check(&self, model: &Model, layout: Layout, findings: &mut Vec<TemplateFinding>) {
184        let set = self.set_id;
185        let template = self.template.id;
186        let template_type = self.template.template_type.as_ref();
187        let undecided = |subject, reason| TemplateFinding::Undecided {
188            set,
189            template,
190            subject,
191            reason,
192        };
193        let rule = match template_type {
194            None => Some(form::Attachment::Any),
195            Some(token) => {
196                let rule = attachment(layout, token);
197                if rule.is_none() {
198                    let value = token.clone();
199                    findings.push(undecided(
200                        template,
201                        UndecidedReason::UnknownTemplateType { value },
202                    ));
203                }
204                rule
205            }
206        };
207        if let (Some(_), Some(token)) = (rule, template_type) {
208            if let Some(expected) = set_entity(token) {
209                if !layout.is_a(&self.set.type_name, expected) {
210                    findings.push(TemplateFinding::WrongSetKind {
211                        set,
212                        template,
213                        template_type: token.clone(),
214                        expected,
215                        found: self.set.type_name.clone(),
216                    });
217                }
218            }
219        }
220        match self.members {
221            Some(members) => Comparison {
222                model,
223                layout,
224                set,
225                template,
226                findings: &mut *findings,
227            }
228            .members(set, members, &self.template.properties),
229            None => findings.push(undecided(
230                set,
231                UndecidedReason::PredefinedSet {
232                    found: self.set.type_name.clone(),
233                },
234            )),
235        }
236        for &object in self.objects {
237            let entity = model.get(object).expect("carriers are in the model");
238            if let (Some(rule), Some(token)) = (rule, template_type) {
239                if !rule.admits(layout, &entity.type_name) {
240                    findings.push(TemplateFinding::WrongAttachment {
241                        set,
242                        template,
243                        object,
244                        template_type: token.clone(),
245                        found: entity.type_name.clone(),
246                    });
247                }
248            }
249            let Some(applicable_entity) = &self.template.applicable_entity else {
250                continue;
251            };
252            match applicable(layout, entity, applicable_entity) {
253                Verdict::Admits => {}
254                Verdict::Excludes => findings.push(TemplateFinding::OutsideApplicableEntity {
255                    set,
256                    template,
257                    object,
258                    found: entity.type_name.clone(),
259                    applicable_entity: Arc::clone(applicable_entity),
260                }),
261                Verdict::Undecided(reason) => findings.push(undecided(object, reason)),
262            }
263        }
264    }
265}