1use std::collections::HashSet;
30
31use ifc_model::{Entity, EntityId, Model, Value};
32use ifc_schema::{ifc2x3, ifc4, ifc4x3, Schema, SchemaVersion, TypeKind};
33
34use crate::error::{ResourceError, ResourceResult};
35use crate::{ConstructionResource, ResourceTime};
36
37#[derive(Debug, Clone, Copy)]
38pub struct ResourceView<'m, 's> {
42 pub(crate) model: &'m Model,
43 pub(crate) schema: &'s Schema,
44}
45
46impl<'m, 's> ResourceView<'m, 's> {
47 pub fn new(model: &'m Model, schema: &'s Schema) -> ResourceResult<Self> {
51 let Some(version) = schema.version() else {
52 return Err(ResourceError::UnsupportedSchema {
53 token: schema.name().to_owned(),
54 });
55 };
56 if !matches!(
57 version,
58 SchemaVersion::Ifc2x3 | SchemaVersion::Ifc4 | SchemaVersion::Ifc4x3
59 ) {
60 return Err(ResourceError::UnsupportedSchema {
61 token: schema.name().to_owned(),
62 });
63 }
64 match model.header().schema.as_slice() {
65 [] => {}
66 [token] if SchemaVersion::from_header_token(token) == Some(version) => {}
67 [token] => {
68 return Err(ResourceError::UnsupportedSchema {
69 token: token.clone(),
70 });
71 }
72 tokens => {
73 return Err(ResourceError::AmbiguousSchema {
74 tokens: tokens.to_vec(),
75 });
76 }
77 }
78 Ok(Self { model, schema })
79 }
80
81 #[must_use]
83 pub fn schema(&self) -> &'s Schema {
84 self.schema
85 }
86
87 pub fn resource(&self, id: EntityId) -> ResourceResult<ConstructionResource<'m, 's>> {
90 ConstructionResource::from_record(self.record(id, "IfcConstructionResource")?)
91 }
92
93 pub fn resource_time(&self, id: EntityId) -> ResourceResult<ResourceTime<'m, 's>> {
95 Ok(ResourceTime::from_record(
96 self.record(id, "IfcResourceTime")?,
97 ))
98 }
99
100 pub(crate) fn record(
101 &self,
102 id: EntityId,
103 expected: &'static str,
104 ) -> ResourceResult<Record<'m, 's>> {
105 Record::new(self.model, self.schema, id, expected)
106 }
107
108 pub(crate) fn require_entity(&self, entity_type: &'static str) -> ResourceResult<()> {
111 require_entity(self.schema, None, entity_type)
112 }
113
114 pub(crate) fn is_ifc2x3(&self) -> bool {
116 self.schema.version() == Some(SchemaVersion::Ifc2x3)
117 }
118
119 pub(crate) fn ids_of_ancestor(&self, ancestor: &str) -> Vec<EntityId> {
120 self.model
121 .iter()
122 .filter_map(|(id, entity)| self.schema.is_a(&entity.type_name, ancestor).then_some(id))
123 .collect()
124 }
125}
126
127impl<'m> ResourceView<'m, 'static> {
128 pub fn for_model(model: &'m Model) -> ResourceResult<Self> {
133 let token = match model.header().schema.as_slice() {
134 [] => return Err(ResourceError::MissingSchema),
135 [token] => token,
136 tokens => {
137 return Err(ResourceError::AmbiguousSchema {
138 tokens: tokens.to_vec(),
139 });
140 }
141 };
142 let version = SchemaVersion::from_header_token(token).ok_or_else(|| {
143 ResourceError::UnsupportedSchema {
144 token: token.clone(),
145 }
146 })?;
147 let schema = match version {
148 SchemaVersion::Ifc2x3 => ifc2x3(),
149 SchemaVersion::Ifc4 => ifc4(),
150 SchemaVersion::Ifc4x3 => ifc4x3(),
151 _ => {
154 return Err(ResourceError::UnsupportedSchema {
155 token: token.clone(),
156 });
157 }
158 #[allow(unreachable_patterns)]
161 _ => {
162 return Err(ResourceError::UnsupportedSchema {
163 token: token.clone(),
164 });
165 }
166 };
167 Self::new(model, schema)
168 }
169}
170
171fn require_entity(
172 schema: &Schema,
173 entity: Option<EntityId>,
174 entity_type: &'static str,
175) -> ResourceResult<()> {
176 if schema.entity(entity_type).is_none() {
177 return Err(ResourceError::NotInSchema {
178 schema: schema.name().to_owned(),
179 entity,
180 entity_type: entity_type.to_owned(),
181 attribute: None,
182 });
183 }
184 Ok(())
185}
186
187pub(crate) fn validate_object_assignment(
188 model: &Model,
189 schema: &Schema,
190 relation: Option<EntityId>,
191 related_objects_type: Option<&str>,
192 related_objects: &[EntityId],
193) -> ResourceResult<()> {
194 let Some(category) = related_objects_type else {
195 return Ok(());
196 };
197 let expected = if category.eq_ignore_ascii_case("NOTDEFINED") {
198 return Ok(());
199 } else if category.eq_ignore_ascii_case("PRODUCT") {
200 "IfcProduct"
201 } else if category.eq_ignore_ascii_case("PROCESS") {
202 "IfcProcess"
203 } else if category.eq_ignore_ascii_case("CONTROL") {
204 "IfcControl"
205 } else if category.eq_ignore_ascii_case("RESOURCE") {
206 "IfcResource"
207 } else if category.eq_ignore_ascii_case("ACTOR") {
208 "IfcActor"
209 } else if category.eq_ignore_ascii_case("GROUP") {
210 "IfcGroup"
211 } else if category.eq_ignore_ascii_case("PROJECT") {
212 "IfcProject"
213 } else {
214 return Err(ResourceError::InvalidEnumeration {
215 entity: relation,
216 attribute: "RelatedObjectsType",
217 value: category.to_owned(),
218 });
219 };
220 if related_objects.iter().any(|target| {
221 model
222 .get(*target)
223 .is_none_or(|entity| !schema.is_a(&entity.type_name, expected))
224 }) {
225 return Err(ResourceError::SemanticViolation {
226 entity: relation,
227 rule: "IfcRelAssigns.WR1_IfcCorrectObjectAssignment",
228 });
229 }
230 Ok(())
231}
232
233#[derive(Debug, Clone, Copy)]
234pub(crate) struct Record<'m, 's> {
235 pub(crate) model: &'m Model,
236 pub(crate) schema: &'s Schema,
237 pub(crate) id: EntityId,
238 pub(crate) entity: &'m Entity,
239}
240
241impl<'m, 's> Record<'m, 's> {
242 pub(crate) fn new(
243 model: &'m Model,
244 schema: &'s Schema,
245 id: EntityId,
246 expected: &'static str,
247 ) -> ResourceResult<Self> {
248 require_entity(schema, Some(id), expected)?;
249 let entity = model.get(id).ok_or(ResourceError::EntityNotFound { id })?;
250 if !schema.is_a(&entity.type_name, expected) {
251 return Err(ResourceError::WrongType {
252 id,
253 expected,
254 actual: entity.type_name.to_string(),
255 });
256 }
257 Ok(Self {
258 model,
259 schema,
260 id,
261 entity,
262 })
263 }
264
265 fn slot(&self, attribute: &'static str) -> ResourceResult<usize> {
266 self.schema
267 .attribute_names(&self.entity.type_name)
268 .iter()
269 .position(|name| name.eq_ignore_ascii_case(attribute))
270 .ok_or_else(|| self.not_in_schema(attribute))
271 }
272
273 pub(crate) fn is_ifc2x3(&self) -> bool {
275 self.schema.version() == Some(SchemaVersion::Ifc2x3)
276 }
277
278 pub(crate) fn not_in_schema(&self, attribute: &'static str) -> ResourceError {
281 ResourceError::NotInSchema {
282 schema: self.schema.name().to_owned(),
283 entity: Some(self.id),
284 entity_type: self.entity.type_name.to_string(),
285 attribute: Some(attribute),
286 }
287 }
288
289 pub(crate) fn value(&self, attribute: &'static str) -> ResourceResult<&'m Value> {
290 self.entity
291 .attributes
292 .get(self.slot(attribute)?)
293 .ok_or(ResourceError::MissingAttribute {
294 entity: self.id,
295 attribute,
296 })
297 }
298
299 pub(crate) fn required_text(&self, attribute: &'static str) -> ResourceResult<&'m str> {
300 match self.value(attribute)?.unwrap_typed() {
301 Value::Text(value) => Ok(value),
302 _ => Err(self.invalid(attribute, "text")),
303 }
304 }
305
306 pub(crate) fn optional_text_list(
307 &self,
308 attribute: &'static str,
309 minimum: usize,
310 ) -> ResourceResult<Vec<&'m str>> {
311 let values = match self.value(attribute)?.unwrap_typed() {
312 Value::Null | Value::Derived => return Ok(Vec::new()),
313 Value::List(values) => values,
314 _ => return Err(self.invalid(attribute, "aggregate of text or null")),
315 };
316 if values.len() < minimum {
317 return Err(ResourceError::InvalidCardinality {
318 entity: self.id,
319 attribute,
320 minimum,
321 actual: values.len(),
322 });
323 }
324 values
325 .iter()
326 .map(|value| match value.unwrap_typed() {
327 Value::Text(value) => Ok(value.as_ref()),
328 _ => Err(self.invalid(attribute, "aggregate of text or null")),
329 })
330 .collect()
331 }
332
333 pub(crate) fn optional_text(&self, attribute: &'static str) -> ResourceResult<Option<&'m str>> {
334 match self.value(attribute)?.unwrap_typed() {
335 Value::Null | Value::Derived => Ok(None),
336 Value::Text(value) => Ok(Some(value)),
337 _ => Err(self.invalid(attribute, "text or null")),
338 }
339 }
340
341 pub(crate) fn optional_bool(&self, attribute: &'static str) -> ResourceResult<Option<bool>> {
342 match self.value(attribute)?.unwrap_typed() {
343 Value::Null | Value::Derived => Ok(None),
344 Value::Bool(value) => Ok(Some(*value)),
345 _ => Err(self.invalid(attribute, "boolean or null")),
346 }
347 }
348
349 pub(crate) fn optional_positive_number(
350 &self,
351 attribute: &'static str,
352 ) -> ResourceResult<Option<f64>> {
353 let value = match self.value(attribute)?.unwrap_typed() {
354 Value::Null | Value::Derived => return Ok(None),
355 Value::Integer(value) => *value as f64,
356 Value::Real(value) => *value,
357 _ => return Err(self.invalid(attribute, "finite positive number or null")),
358 };
359 if !value.is_finite() || value <= 0.0 {
360 return Err(self.invalid(attribute, "finite positive number or null"));
361 }
362 Ok(Some(value))
363 }
364
365 pub(crate) fn optional_finite_number(
366 &self,
367 attribute: &'static str,
368 ) -> ResourceResult<Option<f64>> {
369 let value = match self.value(attribute)?.unwrap_typed() {
370 Value::Null | Value::Derived => return Ok(None),
371 Value::Integer(value) => *value as f64,
372 Value::Real(value) => *value,
373 _ => return Err(self.invalid(attribute, "finite number or null")),
374 };
375 if !value.is_finite() {
376 return Err(self.invalid(attribute, "finite number or null"));
377 }
378 Ok(Some(value))
379 }
380
381 pub(crate) fn required_non_negative_number(
382 &self,
383 attribute: &'static str,
384 ) -> ResourceResult<f64> {
385 let value = match self.value(attribute)?.unwrap_typed() {
386 Value::Integer(value) => *value as f64,
387 Value::Real(value) => *value,
388 _ => return Err(self.invalid(attribute, "finite non-negative number")),
389 };
390 if !value.is_finite() || value < 0.0 {
391 return Err(self.invalid(attribute, "finite non-negative number"));
392 }
393 Ok(value)
394 }
395
396 pub(crate) fn required_enum(&self, attribute: &'static str) -> ResourceResult<&'m str> {
397 let value = match self.value(attribute)?.unwrap_typed() {
398 Value::Enum(value) => value,
399 _ => return Err(self.invalid(attribute, "declared enumeration")),
400 };
401 if !self.declares_enum_member(attribute, value) {
402 return Err(ResourceError::InvalidEnumeration {
403 entity: Some(self.id),
404 attribute,
405 value: value.to_string(),
406 });
407 }
408 Ok(value)
409 }
410
411 pub(crate) fn optional_enum(&self, attribute: &'static str) -> ResourceResult<Option<&'m str>> {
412 let value = match self.value(attribute)?.unwrap_typed() {
413 Value::Null | Value::Derived => return Ok(None),
414 Value::Enum(value) => value,
415 _ => return Err(self.invalid(attribute, "declared enumeration or null")),
416 };
417 if !self.declares_enum_member(attribute, value) {
418 return Err(ResourceError::InvalidEnumeration {
419 entity: Some(self.id),
420 attribute,
421 value: value.to_string(),
422 });
423 }
424 Ok(Some(value))
425 }
426
427 fn declares_enum_member(&self, attribute: &str, value: &str) -> bool {
428 let declarations = self.schema.attributes(&self.entity.type_name);
429 let Some(declaration) = declarations
430 .iter()
431 .find(|candidate| candidate.name.eq_ignore_ascii_case(attribute))
432 else {
433 return false;
434 };
435 let mut type_name = declaration.type_name.as_str();
436 for _ in 0..16 {
437 let Some(definition) = self.schema.type_def(type_name) else {
438 return false;
439 };
440 match &definition.kind {
441 TypeKind::Enumeration(members) => {
442 return members
443 .iter()
444 .any(|member| member.eq_ignore_ascii_case(value));
445 }
446 TypeKind::Defined(alias) => type_name = alias,
447 TypeKind::Select(_) => return false,
448 _ => return false,
449 }
450 }
451 false
452 }
453
454 pub(crate) fn optional_ref(
455 &self,
456 attribute: &'static str,
457 expected: &'static str,
458 ) -> ResourceResult<Option<EntityId>> {
459 let target = match self.value(attribute)?.unwrap_typed() {
460 Value::Null | Value::Derived => return Ok(None),
461 Value::Ref(target) => *target,
462 _ => return Err(self.invalid(attribute, "entity reference or null")),
463 };
464 self.check_reference(attribute, target, &[expected], expected)?;
465 Ok(Some(target))
466 }
467
468 pub(crate) fn required_ref(
469 &self,
470 attribute: &'static str,
471 expected: &'static str,
472 ) -> ResourceResult<EntityId> {
473 let Value::Ref(target) = self.value(attribute)?.unwrap_typed() else {
474 return Err(self.invalid(attribute, "entity reference"));
475 };
476 self.check_reference(attribute, *target, &[expected], expected)?;
477 Ok(*target)
478 }
479
480 pub(crate) fn optional_ref_select(
481 &self,
482 attribute: &'static str,
483 expected: &'static str,
484 members: &[&str],
485 ) -> ResourceResult<Option<EntityId>> {
486 let target = match self.value(attribute)?.unwrap_typed() {
487 Value::Null | Value::Derived => return Ok(None),
488 Value::Ref(target) => *target,
489 _ => return Err(self.invalid(attribute, "entity reference or null")),
490 };
491 self.check_reference(attribute, target, members, expected)?;
492 Ok(Some(target))
493 }
494
495 pub(crate) fn required_ref_select(
496 &self,
497 attribute: &'static str,
498 expected: &'static str,
499 members: &[&str],
500 ) -> ResourceResult<EntityId> {
501 let Value::Ref(target) = self.value(attribute)?.unwrap_typed() else {
502 return Err(self.invalid(attribute, "entity reference"));
503 };
504 self.check_reference(attribute, *target, members, expected)?;
505 Ok(*target)
506 }
507
508 pub(crate) fn refs(
509 &self,
510 attribute: &'static str,
511 expected: &'static str,
512 minimum: usize,
513 optional: bool,
514 unique: bool,
515 ) -> ResourceResult<Vec<EntityId>> {
516 self.refs_select(attribute, expected, &[expected], minimum, optional, unique)
517 }
518
519 pub(crate) fn refs_select(
520 &self,
521 attribute: &'static str,
522 expected: &'static str,
523 members: &[&str],
524 minimum: usize,
525 optional: bool,
526 unique: bool,
527 ) -> ResourceResult<Vec<EntityId>> {
528 let values = match self.value(attribute)?.unwrap_typed() {
529 Value::Null | Value::Derived if optional => return Ok(Vec::new()),
530 Value::List(values) => values,
531 _ => return Err(self.invalid(attribute, "aggregate of entity references")),
532 };
533 if values.len() < minimum {
534 return Err(ResourceError::InvalidCardinality {
535 entity: self.id,
536 attribute,
537 minimum,
538 actual: values.len(),
539 });
540 }
541 let mut targets = Vec::with_capacity(values.len());
542 let mut seen = HashSet::with_capacity(values.len());
543 for value in values {
544 let Value::Ref(target) = value.unwrap_typed() else {
545 return Err(self.invalid(attribute, "aggregate of entity references"));
546 };
547 if unique && !seen.insert(*target) {
548 return Err(ResourceError::DuplicateReference {
549 entity: self.id,
550 attribute,
551 target: *target,
552 });
553 }
554 self.check_reference(attribute, *target, members, expected)?;
555 targets.push(*target);
556 }
557 Ok(targets)
558 }
559
560 pub(crate) fn check_reference(
561 &self,
562 attribute: &'static str,
563 target: EntityId,
564 members: &[&str],
565 expected: &'static str,
566 ) -> ResourceResult<()> {
567 let entity = self
568 .model
569 .get(target)
570 .ok_or(ResourceError::DanglingReference {
571 entity: self.id,
572 attribute,
573 target,
574 })?;
575 if !members
576 .iter()
577 .any(|member| self.schema.is_a(&entity.type_name, member))
578 {
579 return Err(ResourceError::WrongReferenceType {
580 entity: self.id,
581 attribute,
582 target,
583 expected,
584 actual: entity.type_name.to_string(),
585 });
586 }
587 Ok(())
588 }
589
590 pub(crate) fn require_object_type_if(
591 &self,
592 condition: bool,
593 rule: &'static str,
594 ) -> ResourceResult<()> {
595 if condition
596 && self
597 .optional_text("ObjectType")?
598 .is_none_or(|value| value.trim().is_empty())
599 {
600 return Err(ResourceError::SemanticViolation {
601 entity: Some(self.id),
602 rule,
603 });
604 }
605 Ok(())
606 }
607
608 fn invalid(&self, attribute: &'static str, expected: &'static str) -> ResourceError {
609 ResourceError::InvalidValue {
610 entity: self.id,
611 attribute,
612 expected,
613 }
614 }
615}
616
617#[cfg(test)]
618mod intermediate_release_tests {
619 use super::*;
620
621 #[test]
624 fn ifc4x1_and_ifc4x2_are_refused_not_aliased() {
625 for token in ["IFC4X1", "IFC4X2"] {
626 let mut model = Model::new();
627 model.header_mut().schema = vec![token.to_owned()];
628 assert!(
629 matches!(
630 ResourceView::for_model(&model),
631 Err(ResourceError::UnsupportedSchema { token: found }) if found == token
632 ),
633 "{token} must be refused"
634 );
635 }
636 }
637}