ifc_validate/structure/
required.rs1use ifc_model::{Model, Value};
4use ifc_schema::Schema;
5
6use crate::report::{Finding, Path, Report};
7
8pub fn required_attributes(model: &Model, schema: &Schema, report: &mut Report) {
23 let mut ids: Vec<_> = model.iter().map(|(id, _)| id).collect();
24 ids.sort_unstable();
25 for id in ids {
26 let Some(entity) = model.get(id) else {
27 continue;
28 };
29 let Some(definition) = schema.entity(&entity.type_name) else {
30 continue;
33 };
34 let declared = schema.attributes(&entity.type_name);
35 if entity.attributes.len() != declared.len() {
36 report.push(Finding::error(
37 "structure.required.slot_count",
38 Path::Entity(id),
39 format!(
40 "{} declares {} attributes, the record has {}",
41 definition.name,
42 declared.len(),
43 entity.attributes.len()
44 ),
45 ));
46 continue;
47 }
48 for (index, (value, attribute)) in entity.attributes.iter().zip(declared.iter()).enumerate()
49 {
50 let is_derived = is_derived_slot(schema, &entity.type_name, &attribute.name);
51 let path = || Path::Attribute {
52 entity: id,
53 index,
54 name: Some(attribute.name.clone()),
55 };
56 match value {
57 Value::Derived if !is_derived => report.push(Finding::error(
58 "structure.required.not_derived",
59 path(),
60 "written as `*` but the schema does not derive it",
61 )),
62 Value::Null if is_derived => report.push(Finding::error(
63 "structure.required.derived_as_null",
64 path(),
65 "a derived slot must be written `*`, not `$`",
66 )),
67 Value::Null if !attribute.optional => report.push(Finding::error(
68 "structure.required.missing",
69 path(),
70 "required attribute is not stated",
71 )),
72 _ if is_derived && !matches!(value, Value::Derived) => report.push(Finding::error(
73 "structure.required.derived_has_value",
74 path(),
75 "a derived slot must be written `*`, not a value",
76 )),
77 _ => {}
78 }
79 }
80 }
81}
82
83fn is_derived_slot(schema: &Schema, type_name: &str, attribute: &str) -> bool {
88 if schema
89 .entity(type_name)
90 .is_some_and(|definition| definition.is_derived(attribute))
91 {
92 return true;
93 }
94 schema
95 .supertypes(type_name)
96 .iter()
97 .filter_map(|name| schema.entity(name))
98 .any(|definition| definition.is_derived(attribute))
99}