Skip to main content

ifc_validate/
property_set.rs

1//! Property and quantity set names using a reserved prefix (#511).
2//!
3//! buildingSMART reserves the `Pset_` and `Qto_` prefixes for the sets its
4//! PSD/QTO catalog defines. A custom `IfcPropertySet` named
5//! `Pset_FRS_BASt` is legal EXPRESS, so no schema rule catches it, but the
6//! bSI validation service rejects it (rule PSE001) and every tool reading
7//! `Pset_` names as catalog sets misreads it.
8//!
9//! The check is a [`Severity::Warning`](crate::Severity::Warning): the file
10//! is legal, and very likely wrong. It needs the release's catalog, which
11//! this crate does not link (the catalog belongs to `ifc-template-catalog`,
12//! and the facade composes the two); a caller supplies it as a
13//! [`PropertySetCatalog`]. Without one, a file using reserved names gets a
14//! single unsupported finding saying they were not checked, never silence.
15//!
16//! For a set the catalog defines, the members inside it are checked too
17//! (#537): properties and quantities the template does not
18//! declare, and members whose entity form or value types differ from it.
19//! The catalog supplies the template through
20//! [`PropertySetCatalog::template`]; without one, those sets' members are
21//! reported once per rule as not checked.
22//!
23//! The prefix is matched without regard to case (`PSET_x` is reserved
24//! too); the catalog lookup is exact.
25
26mod members;
27mod template;
28
29pub use template::{
30    CatalogMember, CatalogMemberForm, CatalogQuantityKind, CatalogSet, CatalogSetKind,
31};
32
33use ifc_model::{EntityId, Model};
34use ifc_schema::{Schema, SchemaVersion};
35
36use crate::report::{Finding, FindingDetail, Path, Report, ReservedSetName};
37
38/// The rule id of this check.
39const RULE: &str = "property.reserved_set_name";
40
41/// The prefixes buildingSMART reserves.
42const RESERVED: [&str; 2] = ["Pset_", "Qto_"];
43
44/// The set names a release's PSD/QTO catalog defines.
45///
46/// Implemented by the facade over `ifc-template-catalog`; any other source
47/// of the catalog may implement it too.
48pub trait PropertySetCatalog {
49    /// Whether the catalog of `version` defines a property or quantity set
50    /// named exactly `name`; `None` when no catalog of that release is
51    /// available here.
52    fn defines(&self, version: SchemaVersion, name: &str) -> Option<bool>;
53
54    /// The members the catalog of `version` declares for the set named
55    /// exactly `name`; `None` when it gives no member templates for it.
56    ///
57    /// The default gives none, so a catalog that only knows names still
58    /// works: its sets' members are reported once as not checked (#537).
59    fn template(&self, version: SchemaVersion, name: &str) -> Option<CatalogSet> {
60        let _ = (version, name);
61        None
62    }
63}
64
65/// Warns on every set whose reserved-prefix name the catalog lacks.
66pub(crate) fn check(
67    model: &Model,
68    schema: &Schema,
69    catalog: Option<&dyn PropertySetCatalog>,
70    report: &mut Report,
71) {
72    let sets = reserved_sets(model, schema);
73    if sets.is_empty() {
74        return;
75    }
76    let release = schema
77        .version()
78        .map_or_else(|| schema.name().to_owned(), |v| v.release_id().to_owned());
79    let lookup = |name: &str| {
80        let version = schema.version()?;
81        catalog?.defines(version, name)
82    };
83    // Whether any lookup is possible at all, asked once.
84    if lookup(&sets[0].2).is_none() {
85        let why = if catalog.is_none() {
86            "no PSD/QTO catalog was supplied".to_owned()
87        } else {
88            format!("the supplied catalog has no {release} edition")
89        };
90        report.push(Finding::unsupported(
91            RULE,
92            Path::File,
93            format!(
94                "{} property or quantity set names use a reserved prefix (Pset_, Qto_) and were not \
95                 checked: {why}",
96                sets.len()
97            ),
98        ));
99        return;
100    }
101    let mut defined = Vec::new();
102    for (id, slot, name, prefix) in sets {
103        let known = lookup(&name);
104        if known == Some(true) {
105            defined.push((id, name.clone()));
106        }
107        if known == Some(false) {
108            report.push(
109                Finding::warning(
110                    RULE,
111                    Path::Attribute {
112                        entity: id,
113                        index: slot,
114                        name: Some("Name".into()),
115                    },
116                    format!(
117                        "'{name}' uses the reserved prefix {prefix}, but the {release} catalog \
118                         defines no set of that name; a custom set must not use Pset_ or Qto_ \
119                         (bSI PSE001)"
120                    ),
121                )
122                .with_detail(FindingDetail::ReservedSetName(ReservedSetName {
123                    name,
124                    prefix: prefix.to_owned(),
125                    release: release.clone(),
126                })),
127            );
128        }
129    }
130    if let Some(catalog) = catalog {
131        members::check(model, schema, catalog, &release, &defined, report);
132    }
133}
134
135/// Every `IfcPropertySet` and `IfcElementQuantity` whose name starts with
136/// a reserved prefix: id, `Name` slot, name, prefix.
137fn reserved_sets(model: &Model, schema: &Schema) -> Vec<(EntityId, usize, String, &'static str)> {
138    let mut found = Vec::new();
139    for (type_name, _) in model.type_histogram() {
140        if !["IfcPropertySet", "IfcElementQuantity"]
141            .iter()
142            .any(|set| schema.is_a(type_name, set))
143        {
144            continue;
145        }
146        let Some(slot) = schema
147            .attribute_names(type_name)
148            .iter()
149            .position(|name| *name == "Name")
150        else {
151            continue;
152        };
153        for (id, entity) in model.of_type(type_name) {
154            let Some(name) = entity
155                .attribute(slot)
156                .and_then(|v| v.unwrap_typed().as_text())
157            else {
158                continue;
159            };
160            let prefix = RESERVED.iter().find(|prefix| {
161                name.get(..prefix.len())
162                    .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
163            });
164            if let Some(prefix) = prefix {
165                found.push((id, slot, name.to_owned(), *prefix));
166            }
167        }
168    }
169    found.sort_by_key(|(id, ..)| *id);
170    found
171}
172
173#[cfg(all(test, feature = "ifc4", feature = "ifc4x1"))]
174mod tests {
175    use super::*;
176    use ifc_model::{Entity, Value};
177
178    struct Fixed(&'static [&'static str]);
179
180    impl PropertySetCatalog for Fixed {
181        fn defines(&self, version: SchemaVersion, name: &str) -> Option<bool> {
182            (version == SchemaVersion::Ifc4).then(|| self.0.contains(&name))
183        }
184    }
185
186    fn model(names: &[&str]) -> Model {
187        let mut model = Model::new();
188        for name in names {
189            model.push(Entity::new(
190                "IFCPROPERTYSET",
191                vec![
192                    Value::Text("0abcdefghijklmnopqrstu".into()),
193                    Value::Null,
194                    Value::Text((*name).into()),
195                    Value::Null,
196                    Value::List(Vec::new()),
197                ],
198            ));
199        }
200        model
201    }
202
203    fn run(model: &Model, catalog: Option<&dyn PropertySetCatalog>) -> Report {
204        let mut report = Report::new();
205        check(model, ifc_schema::ifc4(), catalog, &mut report);
206        report
207    }
208
209    #[test]
210    fn a_reserved_name_outside_the_catalog_is_a_warning() {
211        let catalog = Fixed(&["Pset_WallCommon"]);
212        let report = run(
213            &model(&["Pset_WallCommon", "Pset_FRS_BASt", "MyCompany_Set", "qto_x"]),
214            Some(&catalog),
215        );
216        let warned: Vec<_> = report
217            .findings()
218            .iter()
219            .filter(|f| f.rule == RULE)
220            .map(|f| f.message.clone())
221            .collect();
222        assert_eq!(warned.len(), 2, "{warned:?}");
223        assert!(warned[0].contains("Pset_FRS_BASt"));
224        assert!(warned[1].contains("qto_x"));
225        assert!(report.is_conformant(), "a warning is not a violation");
226    }
227
228    #[test]
229    fn without_a_catalog_the_names_are_admitted_unchecked() {
230        let report = run(&model(&["Pset_FRS_BASt", "Pset_WallCommon"]), None);
231        assert_eq!(report.findings().len(), 1);
232        assert_eq!(report.findings()[0].severity, crate::Severity::Unsupported);
233        assert!(run(&model(&["MySet"]), None).findings().is_empty());
234    }
235
236    #[test]
237    fn a_release_the_catalog_lacks_is_admitted_unchecked() {
238        let catalog = Fixed(&[]);
239        let mut report = Report::new();
240        check(
241            &model(&["Pset_FRS_BASt"]),
242            ifc_schema::ifc4x1(),
243            Some(&catalog),
244            &mut report,
245        );
246        assert_eq!(report.findings().len(), 1);
247        assert!(report.findings()[0].message.contains("IFC4X1"));
248    }
249}