1use std::collections::HashMap;
22
23use ifc_model::{EntityId, Model, Value};
24use ifc_schema::{AggregateKind, Aggregation, Bound, Schema};
25
26use crate::report::{Finding, Path, Report};
27
28const MAX_LEVELS: usize = 8;
30
31pub fn aggregate_bounds(model: &Model, schema: &Schema, report: &mut Report) {
34 let mut ids: Vec<_> = model.iter().map(|(id, _)| id).collect();
35 ids.sort_unstable();
36 for id in ids {
37 let Some(entity) = model.get(id) else {
38 continue;
39 };
40 let declared = schema.attributes(&entity.type_name);
41 for (index, value) in entity.attributes.iter().enumerate() {
42 let Some(attribute) = declared.get(index) else {
43 continue;
44 };
45 if attribute.aggregation.is_empty() {
46 continue;
47 }
48 let Value::List(items) = value else {
51 continue;
52 };
53 let site = Site {
54 entity: id,
55 index,
56 name: &attribute.name,
57 };
58 level(&site, &attribute.aggregation, items, 0, report);
59 }
60 }
61}
62
63struct Site<'a> {
65 entity: EntityId,
66 index: usize,
67 name: &'a str,
68}
69
70impl Site<'_> {
71 fn path(&self) -> Path {
72 Path::Attribute {
73 entity: self.entity,
74 index: self.index,
75 name: Some(self.name.to_owned()),
76 }
77 }
78}
79
80fn level(
81 site: &Site<'_>,
82 levels: &[Aggregation],
83 items: &[Value],
84 depth: usize,
85 report: &mut Report,
86) {
87 let Some(aggregation) = levels.first() else {
88 return;
89 };
90 if depth >= MAX_LEVELS {
91 return;
92 }
93 size(site, aggregation, items.len(), depth, report);
94 if aggregation.forbids_duplicates() {
95 duplicates(site, aggregation, items, depth, report);
96 }
97 let inner = &levels[1..];
98 if inner.is_empty() {
99 return;
100 }
101 for item in items {
102 match item {
103 Value::List(nested) => level(site, inner, nested, depth + 1, report),
104 Value::Null if aggregation.optional_elements => {}
107 other => report.push(Finding::error(
108 "structure.aggregate.nesting",
109 site.path(),
110 format!(
111 "{} nests {} aggregation levels; level {} holds {} instead of an aggregate",
112 site.name,
113 levels.len() + depth,
114 depth + 2,
115 crate::type_check::describe_value(other)
116 ),
117 )),
118 }
119 }
120}
121
122fn admitted(aggregation: &Aggregation) -> (Option<u64>, Option<u64>) {
124 let lower = aggregation.lower.as_integer();
125 let upper = match aggregation.upper {
126 Bound::Unbounded => None,
127 ref bound => bound.as_integer(),
128 };
129 if aggregation.kind == AggregateKind::Array {
130 return match (lower, upper) {
132 (Some(l), Some(u)) if u >= l => (Some(u - l + 1), Some(u - l + 1)),
133 _ => (None, None),
134 };
135 }
136 (lower, upper)
137}
138
139fn size(site: &Site<'_>, aggregation: &Aggregation, len: usize, depth: usize, report: &mut Report) {
140 let (minimum, maximum) = admitted(aggregation);
141 let len = len as u64;
142 let where_ = if depth == 0 {
143 String::new()
144 } else {
145 format!(" at nesting level {}", depth + 1)
146 };
147 if let Some(minimum) = minimum.filter(|&minimum| len < minimum) {
148 report.push(Finding::error(
149 "structure.aggregate.too_few",
150 site.path(),
151 format!(
152 "{}{where_} declares {}; the file wrote {len} element(s), fewer than {minimum}",
153 site.name,
154 declaration(aggregation)
155 ),
156 ));
157 }
158 if let Some(maximum) = maximum.filter(|&maximum| len > maximum) {
159 report.push(Finding::error(
160 "structure.aggregate.too_many",
161 site.path(),
162 format!(
163 "{}{where_} declares {}; the file wrote {len} element(s), more than {maximum}",
164 site.name,
165 declaration(aggregation)
166 ),
167 ));
168 }
169}
170
171fn duplicates(
172 site: &Site<'_>,
173 aggregation: &Aggregation,
174 items: &[Value],
175 depth: usize,
176 report: &mut Report,
177) {
178 let mut first: HashMap<String, usize> = HashMap::with_capacity(items.len());
181 for (position, item) in items.iter().enumerate() {
182 if matches!(item, Value::Null) {
183 continue;
184 }
185 if let Some(earlier) = first.insert(format!("{item:?}"), position) {
186 let what = if aggregation.kind == AggregateKind::Set {
187 "a SET"
188 } else {
189 "declared UNIQUE"
190 };
191 let level = if depth == 0 {
192 String::new()
193 } else {
194 format!(" at nesting level {}", depth + 1)
195 };
196 report.push(Finding::error(
197 "structure.aggregate.duplicate",
198 site.path(),
199 format!(
200 "{}{level} is {what}, but element {position} repeats element {earlier}",
201 site.name
202 ),
203 ));
204 return;
207 }
208 }
209}
210
211fn declaration(aggregation: &Aggregation) -> String {
212 let kind = match aggregation.kind {
213 AggregateKind::List => "LIST",
214 AggregateKind::Set => "SET",
215 AggregateKind::Bag => "BAG",
216 AggregateKind::Array => "ARRAY",
217 _ => "AGGREGATE",
218 };
219 let bound = |bound: &Bound| match bound {
220 Bound::Integer(value) => value.to_string(),
221 Bound::Unbounded => "?".to_owned(),
222 Bound::Expression(text) => text.clone(),
223 _ => "?".to_owned(),
224 };
225 format!(
226 "{kind} [{}:{}]",
227 bound(&aggregation.lower),
228 bound(&aggregation.upper)
229 )
230}
231
232#[cfg(test)]
233mod tests {
234 use super::*;
235 use ifc_model::Entity;
236
237 fn real(value: f64) -> Value {
238 Value::Real(value)
239 }
240
241 fn rules(report: &Report) -> Vec<&str> {
242 report.findings().iter().map(|f| f.rule.as_str()).collect()
243 }
244
245 fn point(coordinates: Vec<Value>) -> Report {
246 let schema = ifc_schema::ifc4();
247 let mut model = Model::new();
248 model.push(Entity::new(
249 "IFCCARTESIANPOINT",
250 vec![Value::List(coordinates)],
251 ));
252 let mut report = Report::new();
253 aggregate_bounds(&model, schema, &mut report);
254 report
255 }
256
257 #[test]
258 fn a_list_outside_its_bounds_is_reported() {
259 assert!(rules(&point(vec![real(0.0), real(1.0)])).is_empty());
260 assert_eq!(rules(&point(Vec::new())), ["structure.aggregate.too_few"]);
261 assert_eq!(
262 rules(&point(vec![real(0.0); 4])),
263 ["structure.aggregate.too_many"]
264 );
265 }
266
267 fn point_list(rows: Vec<Value>) -> Report {
268 let schema = ifc_schema::ifc4();
269 let mut model = Model::new();
270 model.push(Entity::new(
271 "IFCCARTESIANPOINTLIST3D",
272 vec![Value::List(rows), Value::Null],
273 ));
274 let mut report = Report::new();
275 aggregate_bounds(&model, schema, &mut report);
276 report
277 }
278
279 #[test]
280 fn a_nested_level_is_checked_for_shape_and_bounds() {
281 let row = |n: usize| Value::List(vec![real(0.0); n]);
282 assert!(rules(&point_list(vec![row(3), row(3)])).is_empty());
283 assert_eq!(
284 rules(&point_list(vec![row(3), row(2)])),
285 ["structure.aggregate.too_few"]
286 );
287 assert_eq!(
288 rules(&point_list(vec![row(3), real(1.0)])),
289 ["structure.aggregate.nesting"]
290 );
291 }
292
293 #[test]
294 fn a_unique_list_may_not_repeat_an_element() {
295 let schema = ifc_schema::ifc4();
296 let run = |refs: &[u64]| {
297 let mut model = Model::new();
298 model.push(Entity::new(
299 "IFCPOLYLOOP",
300 vec![Value::List(
301 refs.iter().map(|&id| Value::Ref(EntityId(id))).collect(),
302 )],
303 ));
304 let mut report = Report::new();
305 aggregate_bounds(&model, schema, &mut report);
306 report
307 };
308 assert!(rules(&run(&[1, 2, 3])).is_empty());
309 assert_eq!(rules(&run(&[1, 2, 1])), ["structure.aggregate.duplicate"]);
310 }
311}