1use ifc_model::{Entity, Value};
20use ifc_schema::Schema;
21
22use crate::check::{
23 aggregate_element, describe_value, enumerations_of, is_derived_slot, judge_value, Verdict,
24};
25use crate::error::{AuthorError, AuthorResult};
26
27#[derive(Debug, Clone)]
31pub struct EntityBuilder<'a> {
32 schema: &'a Schema,
33 entity: String,
34 set: Vec<(String, Value)>,
38}
39
40impl<'a> EntityBuilder<'a> {
41 pub fn new(schema: &'a Schema, entity: impl Into<String>) -> Self {
49 Self {
50 schema,
51 entity: entity.into(),
52 set: Vec::new(),
53 }
54 }
55
56 #[must_use]
61 pub fn set(mut self, attribute: impl Into<String>, value: Value) -> Self {
62 self.set.push((attribute.into(), value));
63 self
64 }
65
66 pub fn text(self, attribute: impl Into<String>, text: impl Into<std::sync::Arc<str>>) -> Self {
68 self.set(attribute, Value::Text(text.into()))
69 }
70
71 pub fn real(self, attribute: impl Into<String>, value: f64) -> Self {
73 self.set(attribute, Value::Real(value))
74 }
75
76 pub fn reference(self, attribute: impl Into<String>, id: ifc_model::EntityId) -> Self {
78 self.set(attribute, Value::Ref(id))
79 }
80
81 pub fn enumeration(
83 self,
84 attribute: impl Into<String>,
85 constant: impl Into<std::sync::Arc<str>>,
86 ) -> Self {
87 self.set(attribute, Value::Enum(constant.into()))
88 }
89}
90
91impl EntityBuilder<'_> {
92 pub fn build(self) -> AuthorResult<Entity> {
101 let declared = self.schema.attributes(&self.entity);
102 if declared.is_empty() && self.schema.entity(&self.entity).is_none() {
103 return Err(AuthorError::UnknownEntity {
104 entity: self.entity,
105 });
106 }
107
108 let mut slots: Vec<Value> = declared
112 .iter()
113 .map(|attribute| {
114 if is_derived_slot(self.schema, &self.entity, &attribute.name) {
115 Value::Derived
116 } else {
117 Value::Null
118 }
119 })
120 .collect();
121 let mut filled = vec![false; declared.len()];
122
123 for (name, value) in &self.set {
124 let Some(index) = declared
125 .iter()
126 .position(|a| a.name.eq_ignore_ascii_case(name))
127 else {
128 return Err(AuthorError::UnknownAttribute {
129 entity: self.entity.clone(),
130 attribute: name.clone(),
131 known: declared.iter().map(|a| a.name.clone()).collect(),
132 });
133 };
134 if filled[index] {
135 return Err(AuthorError::DuplicateAttribute {
136 entity: self.entity.clone(),
137 attribute: declared[index].name.clone(),
138 });
139 }
140 check_value(self.schema, &self.entity, declared[index], value)?;
141 slots[index] = value.clone();
142 filled[index] = true;
143 }
144
145 for (index, attribute) in declared.iter().enumerate() {
146 if !filled[index] && !attribute.optional && !matches!(slots[index], Value::Derived) {
147 return Err(AuthorError::MissingRequired {
148 entity: self.entity.clone(),
149 attribute: attribute.name.clone(),
150 });
151 }
152 }
153
154 Ok(Entity::new(self.entity.to_ascii_uppercase(), slots))
155 }
156
157 pub fn insert(self, model: &mut ifc_model::Model) -> AuthorResult<ifc_model::EntityId> {
166 let entity = self.build()?;
167 Ok(model.push(entity))
168 }
169}
170
171pub(crate) fn check_value(
176 schema: &Schema,
177 entity: &str,
178 attribute: &ifc_schema::Attribute,
179 value: &Value,
180) -> AuthorResult<()> {
181 let derived = is_derived_slot(schema, entity, &attribute.name);
183 match (derived, value) {
184 (true, Value::Derived) => return Ok(()),
185 (true, other) => {
186 return Err(AuthorError::DerivedAttribute {
187 entity: entity.to_owned(),
188 attribute: attribute.name.clone(),
189 found: describe_value(other),
190 })
191 }
192 (false, Value::Derived) => {
193 return Err(AuthorError::NotDerived {
194 entity: entity.to_owned(),
195 attribute: attribute.name.clone(),
196 })
197 }
198 (false, _) => {}
199 }
200
201 let aliased = if attribute.aggregate {
211 None
212 } else {
213 aggregate_element(schema, &attribute.type_name)
214 };
215 let expected_aggregate = attribute.aggregate || aliased.is_some();
216 if !matches!(value, Value::Null) {
217 let supplied_aggregate = matches!(value, Value::List(_));
218 if supplied_aggregate != expected_aggregate {
219 return Err(AuthorError::AggregateMismatch {
220 entity: entity.to_owned(),
221 attribute: attribute.name.clone(),
222 expected_aggregate,
223 });
224 }
225 }
226
227 if attribute.name.eq_ignore_ascii_case("GlobalId") {
231 if let Value::Text(text) = value {
232 if ifc_model::guid::Guid::parse(text).is_none() {
233 return Err(AuthorError::InvalidGlobalId {
234 entity: entity.to_owned(),
235 found: text.to_string(),
236 });
237 }
238 }
239 }
240
241 let element_type = aliased.as_deref().unwrap_or(&attribute.type_name);
252 let verdicts: Vec<(Verdict, &Value)> = match value {
253 Value::List(_) => {
254 let mut elements = Vec::new();
255 let levels = attribute.aggregation.len().max(1);
256 if !elements_at(value, levels, &mut elements) {
257 return Err(AuthorError::AggregateMismatch {
258 entity: entity.to_owned(),
259 attribute: attribute.name.clone(),
260 expected_aggregate: true,
261 });
262 }
263 elements
264 .into_iter()
265 .map(|item| (judge_value(schema, element_type, item), item))
266 .collect()
267 }
268 scalar => vec![(judge_value(schema, &attribute.type_name, scalar), scalar)],
269 };
270 if verdicts
271 .iter()
272 .any(|(verdict, _)| *verdict == Verdict::WrongType)
273 {
274 return Err(AuthorError::TypeMismatch {
275 entity: entity.to_owned(),
276 attribute: attribute.name.clone(),
277 expected: attribute.type_name.clone(),
278 found: describe_value(value),
279 });
280 }
281 if let Some((Verdict::NotMember { enumeration }, offending)) = verdicts
282 .iter()
283 .find(|(verdict, _)| matches!(verdict, Verdict::NotMember { .. }))
284 {
285 let enumerations = enumerations_of(schema, enumeration, 16);
286 let mut constant = *offending;
288 while let Value::Typed { value, .. } = constant {
289 constant = value;
290 }
291 return Err(AuthorError::NotEnumerationMember {
292 entity: entity.to_owned(),
293 attribute: attribute.name.clone(),
294 enumeration: enumerations
295 .iter()
296 .map(|(name, _)| *name)
297 .collect::<Vec<_>>()
298 .join(" | "),
299 constant: match constant {
300 Value::Enum(text) => text.to_string(),
301 other => describe_value(other),
302 },
303 allowed: enumerations
304 .iter()
305 .flat_map(|(_, members)| members.iter().cloned())
306 .collect(),
307 });
308 }
309 if let Some((Verdict::WrongForm { typed_required }, offending)) = verdicts
310 .into_iter()
311 .find(|(verdict, _)| matches!(verdict, Verdict::WrongForm { .. }))
312 {
313 return Err(AuthorError::ValueForm {
314 entity: entity.to_owned(),
315 attribute: attribute.name.clone(),
316 declared: element_type.to_owned(),
317 typed_required,
318 found: describe_value(offending),
319 });
320 }
321 Ok(())
322}
323
324fn elements_at<'v>(value: &'v Value, levels: usize, out: &mut Vec<&'v Value>) -> bool {
327 match value {
328 Value::List(items) if levels > 0 => {
329 items.iter().all(|item| elements_at(item, levels - 1, out))
330 }
331 _ if levels == 0 => {
332 out.push(value);
333 true
334 }
335 _ => false,
336 }
337}