Skip to main content

ifc_validate/structure/
inverse.rs

1//! INVERSE attribute cardinality (#461).
2//!
3//! An INVERSE clause states how many instances of the `FOR` entity may
4//! reference an instance through the `FOR` attribute: `SET [1:?]` at least
5//! one, `SET [0:1]` at most one, and a single entity (no aggregate) exactly
6//! one. `IfcOpeningElement.VoidsElements` is such a single inverse: an
7//! opening that voids no element, or two, breaks it.
8//!
9//! The clauses come from the declared release's own tables, inherited ones
10//! included; a subtype redeclaring an inverse replaces it. Referrers are
11//! counted once each through the reverse index, as the facade's INVERSE
12//! reads do (#462): an instance of the `FOR` entity or a subtype, holding
13//! the target in the `FOR` attribute's slot. An upper bound written as an
14//! expression is not evaluated.
15
16use std::collections::HashMap;
17
18use ifc_model::{EntityId, Model, ReverseIndex};
19use ifc_schema::{Aggregation, Schema};
20
21use crate::report::{Finding, Path, Report};
22
23/// One INVERSE clause of a type, resolved for counting.
24struct Clause<'s> {
25    name: &'s str,
26    entity: &'s str,
27    slot: usize,
28    lower: u64,
29    upper: Option<u64>,
30    declared: String,
31}
32
33/// Reports every instance referenced by more or fewer instances than one
34/// of its INVERSE clauses allows.
35pub fn inverse_cardinality(model: &Model, schema: &Schema, report: &mut Report) {
36    let mut types: Vec<(&str, usize)> = model.type_histogram();
37    types.sort_unstable_by_key(|(name, _)| *name);
38    let clauses: Vec<(&str, Vec<Clause<'_>>)> = types
39        .iter()
40        .map(|(name, _)| (*name, clauses(schema, name)))
41        .filter(|(_, clauses)| !clauses.is_empty())
42        .collect();
43    if clauses.is_empty() {
44        return;
45    }
46    let reverse = ReverseIndex::build(model);
47    let mut is_a: HashMap<(&str, &str), bool> = HashMap::new();
48    let mut findings: Vec<(EntityId, Finding)> = Vec::new();
49    for (type_name, clauses) in &clauses {
50        for &id in model.ids_of_type(type_name) {
51            for clause in clauses {
52                let mut count = 0u64;
53                let mut last = None;
54                for referrer in reverse.referrers(id) {
55                    if referrer.slot != clause.slot || last == Some(referrer.from) {
56                        continue;
57                    }
58                    let Some(source) = model.get(referrer.from) else {
59                        continue;
60                    };
61                    let source_type: &str = &source.type_name;
62                    let fits = *is_a
63                        .entry((source_type, clause.entity))
64                        .or_insert_with(|| schema.is_a(source_type, clause.entity));
65                    if fits {
66                        count += 1;
67                        last = Some(referrer.from);
68                    }
69                }
70                let too_many = clause.upper.is_some_and(|upper| count > upper);
71                if count < clause.lower || too_many {
72                    findings.push((
73                        id,
74                        Finding::error(
75                            "structure.inverse.cardinality",
76                            Path::Entity(id),
77                            format!(
78                                "{} is {}, but {count} {} reference it",
79                                clause.name,
80                                clause.declared,
81                                if count == 1 {
82                                    "instance does"
83                                } else {
84                                    "instances do"
85                                }
86                            ),
87                        ),
88                    ));
89                }
90            }
91        }
92    }
93    findings.sort_by_key(|(id, _)| *id);
94    for (_, finding) in findings {
95        report.push(finding);
96    }
97}
98
99/// Every INVERSE clause of `type_name`, inherited first, redeclarations
100/// replacing what they redeclare.
101fn clauses<'s>(schema: &'s Schema, type_name: &str) -> Vec<Clause<'s>> {
102    let Some(entity) = schema.entity(type_name) else {
103        return Vec::new();
104    };
105    let mut chain: Vec<&str> = schema.supertypes(&entity.name);
106    chain.reverse();
107    chain.push(&entity.name);
108    let mut out: Vec<Clause<'s>> = Vec::new();
109    for owner in chain {
110        let Some(owner) = schema.entity(owner) else {
111            continue;
112        };
113        for inverse in &owner.inverses {
114            let Some(slot) = schema
115                .attribute_names(&inverse.entity)
116                .iter()
117                .position(|name| name.eq_ignore_ascii_case(&inverse.for_attribute))
118            else {
119                continue;
120            };
121            let (lower, upper, declared) = bounds(inverse.aggregation.as_ref(), &inverse.entity);
122            let clause = Clause {
123                name: &inverse.name,
124                entity: &inverse.entity,
125                slot,
126                lower,
127                upper,
128                declared,
129            };
130            match out
131                .iter_mut()
132                .find(|existing| existing.name.eq_ignore_ascii_case(&inverse.name))
133            {
134                Some(existing) => *existing = clause,
135                None => out.push(clause),
136            }
137        }
138    }
139    out
140}
141
142/// The bounds of a clause and how it reads: a single inverse is `[1:1]`.
143fn bounds(aggregation: Option<&Aggregation>, entity: &str) -> (u64, Option<u64>, String) {
144    let Some(aggregation) = aggregation else {
145        return (1, Some(1), format!("exactly one {entity}"));
146    };
147    let lower = aggregation.lower.as_integer().unwrap_or(0);
148    let upper = aggregation.upper.as_integer();
149    let upper_text = upper.map_or_else(|| "?".to_owned(), |u| u.to_string());
150    let kind = format!("{:?}", aggregation.kind).to_ascii_uppercase();
151    (
152        lower,
153        upper,
154        format!("{kind} [{lower}:{upper_text}] OF {entity}"),
155    )
156}
157
158#[cfg(all(test, feature = "ifc4"))]
159mod tests {
160    use super::*;
161    use ifc_model::{Entity, Value};
162
163    fn opening(voids: usize) -> Report {
164        let schema = ifc_schema::ifc4();
165        let mut model = Model::new();
166        let width = schema.attribute_count("IfcOpeningElement");
167        let opening = model.push(Entity::new("IFCOPENINGELEMENT", vec![Value::Null; width]));
168        let names = schema.attribute_names("IfcRelVoidsElement");
169        let slot = names
170            .iter()
171            .position(|n| *n == "RelatedOpeningElement")
172            .expect("declared");
173        for _ in 0..voids {
174            let mut attributes = vec![Value::Null; names.len()];
175            attributes[slot] = Value::Ref(opening);
176            model.push(Entity::new("IFCRELVOIDSELEMENT", attributes));
177        }
178        let mut report = Report::new();
179        inverse_cardinality(&model, schema, &mut report);
180        report
181    }
182
183    /// `VoidsElements` is a single inverse: exactly one relation.
184    #[test]
185    fn a_single_inverse_needs_exactly_one_referrer() {
186        assert_eq!(opening(1).findings().len(), 0);
187        for count in [0, 2] {
188            let report = opening(count);
189            assert_eq!(report.findings().len(), 1, "{count}");
190            let finding = &report.findings()[0];
191            assert_eq!(finding.rule, "structure.inverse.cardinality");
192            assert!(
193                finding.message.contains("VoidsElements"),
194                "{}",
195                finding.message
196            );
197        }
198    }
199}