1use std::collections::HashSet;
4
5use ifc_model::{Entity, EntityId, Model, Value};
6use ifc_schema::{ifc2x3, ifc4, ifc4x3, Schema, SchemaVersion, TypeKind};
7
8use crate::error::{StructuralError, StructuralResult};
9use crate::{
10 AnalysisModel, BoundaryCondition, ConnectionCondition, LoadConfiguration, LoadGroup, Member,
11 Reaction, ResultGroup, StaticLoad, StructuralAction, StructuralConnection,
12 SurfaceReinforcementArea,
13};
14
15#[derive(Debug, Clone, Copy)]
17pub struct StructuralView<'m, 's> {
18 pub(crate) model: &'m Model,
19 pub(crate) schema: &'s Schema,
20}
21
22impl<'m, 's> StructuralView<'m, 's> {
23 #[must_use]
24 pub fn new(model: &'m Model, schema: &'s Schema) -> Self {
26 Self { model, schema }
27 }
28
29 #[must_use]
30 pub fn schema(&self) -> &'s Schema {
32 self.schema
33 }
34
35 pub fn analysis_model(&self, id: EntityId) -> StructuralResult<AnalysisModel<'m, 's>> {
37 Ok(AnalysisModel::from_record(
38 self.record(id, "IfcStructuralAnalysisModel")?,
39 ))
40 }
41
42 pub fn load_group(&self, id: EntityId) -> StructuralResult<LoadGroup<'m, 's>> {
44 Ok(LoadGroup::from_record(
45 self.record(id, "IfcStructuralLoadGroup")?,
46 ))
47 }
48
49 pub fn result_group(&self, id: EntityId) -> StructuralResult<ResultGroup<'m, 's>> {
51 Ok(ResultGroup::from_record(
52 self.record(id, "IfcStructuralResultGroup")?,
53 ))
54 }
55
56 pub fn member(&self, id: EntityId) -> StructuralResult<Member<'m, 's>> {
58 Member::from_record(self.record(id, "IfcStructuralMember")?)
59 }
60
61 pub fn connection(&self, id: EntityId) -> StructuralResult<StructuralConnection<'m, 's>> {
63 StructuralConnection::from_record(self.record(id, "IfcStructuralConnection")?)
64 }
65
66 pub fn boundary_condition(&self, id: EntityId) -> StructuralResult<BoundaryCondition<'m, 's>> {
68 BoundaryCondition::from_record(self.record(id, "IfcBoundaryCondition")?)
69 }
70
71 pub fn connection_condition(
73 &self,
74 id: EntityId,
75 ) -> StructuralResult<ConnectionCondition<'m, 's>> {
76 ConnectionCondition::from_record(self.record(id, "IfcStructuralConnectionCondition")?)
77 }
78
79 pub fn action(&self, id: EntityId) -> StructuralResult<StructuralAction<'m, 's>> {
81 StructuralAction::from_record(self.record(id, "IfcStructuralAction")?)
82 }
83
84 pub fn load(&self, id: EntityId) -> StructuralResult<StaticLoad<'m, 's>> {
93 StaticLoad::from_record(self.record(id, "IfcStructuralLoad")?)
94 }
95
96 pub fn load_configuration(&self, id: EntityId) -> StructuralResult<LoadConfiguration<'m, 's>> {
98 Ok(LoadConfiguration::from_record(
99 self.record(id, "IfcStructuralLoadConfiguration")?,
100 ))
101 }
102
103 pub fn surface_reinforcement_area(
111 &self,
112 id: EntityId,
113 ) -> StructuralResult<SurfaceReinforcementArea<'m, 's>> {
114 const ENTITY: &str = "IfcSurfaceReinforcementArea";
115 if self.schema.entity(ENTITY).is_none() {
116 return Err(StructuralError::UnsupportedSchema {
117 token: self.schema.name().to_owned(),
118 });
119 }
120 SurfaceReinforcementArea::from_record(self.record(id, ENTITY)?)
121 }
122
123 pub fn reaction(&self, id: EntityId) -> StructuralResult<Reaction<'m, 's>> {
125 Reaction::from_record(self.record(id, "IfcStructuralReaction")?)
126 }
127
128 pub fn static_load(&self, id: EntityId) -> StructuralResult<StaticLoad<'m, 's>> {
130 self.load(id)
131 }
132
133 pub(crate) fn record(
135 &self,
136 id: EntityId,
137 expected: &'static str,
138 ) -> StructuralResult<Record<'m, 's>> {
139 Record::new(self.model, self.schema, id, expected)
140 }
141
142 pub(crate) fn ids_of_ancestor(&self, ancestor: &str) -> Vec<EntityId> {
144 let matching_types: HashSet<_> = self
145 .model
146 .type_histogram()
147 .into_iter()
148 .filter_map(|(type_name, _)| self.schema.is_a(type_name, ancestor).then_some(type_name))
149 .collect();
150 self.model
151 .iter()
152 .filter_map(|(id, entity)| matching_types.contains(&*entity.type_name).then_some(id))
153 .collect()
154 }
155}
156
157impl<'m> StructuralView<'m, 'static> {
158 pub fn for_model(model: &'m Model) -> StructuralResult<Self> {
163 let token = match model.header().schema.as_slice() {
164 [] => return Err(StructuralError::MissingSchema),
165 [token] => token,
166 tokens => {
167 return Err(StructuralError::AmbiguousSchema {
168 tokens: tokens.to_vec(),
169 })
170 }
171 };
172 let version = SchemaVersion::from_header_token(token).ok_or_else(|| {
173 StructuralError::UnsupportedSchema {
174 token: token.clone(),
175 }
176 })?;
177 let schema = match version {
178 SchemaVersion::Ifc2x3 => ifc2x3(),
179 SchemaVersion::Ifc4 => ifc4(),
180 SchemaVersion::Ifc4x3 => ifc4x3(),
181 _ => {
184 return Err(StructuralError::UnsupportedSchema {
185 token: token.clone(),
186 })
187 }
188 };
189 Ok(Self::new(model, schema))
190 }
191}
192
193#[derive(Debug, Clone, Copy)]
194pub(crate) struct Record<'m, 's> {
195 pub(crate) model: &'m Model,
196 pub(crate) schema: &'s Schema,
197 pub(crate) id: EntityId,
198 pub(crate) entity: &'m Entity,
199}
200
201impl<'m, 's> Record<'m, 's> {
202 pub(crate) fn new(
203 model: &'m Model,
204 schema: &'s Schema,
205 id: EntityId,
206 expected: &'static str,
207 ) -> StructuralResult<Self> {
208 let entity = model
209 .get(id)
210 .ok_or(StructuralError::EntityNotFound { id })?;
211 if !schema.is_a(&entity.type_name, expected) {
212 return Err(StructuralError::WrongType {
213 id,
214 expected,
215 actual: entity.type_name.to_string(),
216 });
217 }
218 Ok(Self {
219 model,
220 schema,
221 id,
222 entity,
223 })
224 }
225
226 pub(crate) fn has_attribute(&self, attribute: &str) -> bool {
227 self.schema
228 .attribute_names(&self.entity.type_name)
229 .iter()
230 .any(|name| name.eq_ignore_ascii_case(attribute))
231 }
232
233 fn slot(&self, attribute: &'static str) -> StructuralResult<usize> {
234 self.schema
235 .attribute_names(&self.entity.type_name)
236 .iter()
237 .position(|name| name.eq_ignore_ascii_case(attribute))
238 .ok_or(StructuralError::MissingAttribute {
239 entity: self.id,
240 attribute,
241 })
242 }
243
244 pub(crate) fn value(&self, attribute: &'static str) -> StructuralResult<&'m Value> {
245 let slot = self.slot(attribute)?;
246 self.entity
247 .attributes
248 .get(slot)
249 .ok_or(StructuralError::MissingAttribute {
250 entity: self.id,
251 attribute,
252 })
253 }
254
255 pub(crate) fn optional_text(
256 &self,
257 attribute: &'static str,
258 ) -> StructuralResult<Option<&'m str>> {
259 match self.value(attribute)?.unwrap_typed() {
260 Value::Null | Value::Derived => Ok(None),
261 Value::Text(value) => Ok(Some(value)),
262 _ => Err(self.invalid(attribute, "text or null")),
263 }
264 }
265
266 pub(crate) fn require_object_type_if(
267 &self,
268 condition: bool,
269 rule: &'static str,
270 ) -> StructuralResult<()> {
271 if condition
272 && self
273 .optional_text("ObjectType")?
274 .is_none_or(|value| value.trim().is_empty())
275 {
276 return Err(StructuralError::SemanticViolation {
277 entity: Some(self.id),
278 rule,
279 });
280 }
281 Ok(())
282 }
283
284 pub(crate) fn required_enum(&self, attribute: &'static str) -> StructuralResult<&'m str> {
285 match self.value(attribute)?.unwrap_typed() {
286 Value::Enum(value) if self.declares_enum_member(attribute, value) => Ok(value),
287 _ => Err(self.invalid(attribute, "enumeration")),
288 }
289 }
290
291 pub(crate) fn optional_enum(
292 &self,
293 attribute: &'static str,
294 ) -> StructuralResult<Option<&'m str>> {
295 match self.value(attribute)?.unwrap_typed() {
296 Value::Null | Value::Derived => Ok(None),
297 Value::Enum(value) if self.declares_enum_member(attribute, value) => Ok(Some(value)),
298 _ => Err(self.invalid(attribute, "enumeration or null")),
299 }
300 }
301
302 fn declares_enum_member(&self, attribute: &str, value: &str) -> bool {
303 let attributes = self.schema.attributes(&self.entity.type_name);
304 let Some(declaration) = attributes
305 .iter()
306 .find(|declaration| declaration.name.eq_ignore_ascii_case(attribute))
307 else {
308 return false;
309 };
310 let mut type_name = declaration.type_name.as_str();
311 for _ in 0..16 {
312 let Some(type_def) = self.schema.type_def(type_name) else {
313 return false;
314 };
315 match &type_def.kind {
316 TypeKind::Enumeration(members) => {
317 return members
318 .iter()
319 .any(|member| member.eq_ignore_ascii_case(value));
320 }
321 TypeKind::Defined(alias) => type_name = alias,
322 TypeKind::Select(_) => return false,
323 _ => return false,
324 }
325 }
326 false
327 }
328
329 pub(crate) fn optional_bool(&self, attribute: &'static str) -> StructuralResult<Option<bool>> {
330 match self.value(attribute)?.unwrap_typed() {
331 Value::Null | Value::Derived => Ok(None),
332 Value::Bool(value) => Ok(Some(*value)),
333 _ => Err(self.invalid(attribute, "boolean or null")),
334 }
335 }
336
337 pub(crate) fn required_bool(&self, attribute: &'static str) -> StructuralResult<bool> {
338 self.optional_bool(attribute)?
339 .ok_or_else(|| self.invalid(attribute, "boolean"))
340 }
341
342 pub(crate) fn optional_number(&self, attribute: &'static str) -> StructuralResult<Option<f64>> {
343 let value = match self.value(attribute)?.unwrap_typed() {
344 Value::Null | Value::Derived => Ok(None),
345 Value::Integer(value) => Ok(Some(*value as f64)),
346 Value::Real(value) => Ok(Some(*value)),
347 _ => Err(self.invalid(attribute, "number or null")),
348 }?;
349 if value.is_some_and(|number| !number.is_finite()) {
350 return Err(self.invalid(attribute, "finite number or null"));
351 }
352 Ok(value)
353 }
354
355 pub(crate) fn optional_ref(
356 &self,
357 attribute: &'static str,
358 expected: &'static str,
359 ) -> StructuralResult<Option<EntityId>> {
360 let target = match self.value(attribute)?.unwrap_typed() {
361 Value::Null | Value::Derived => return Ok(None),
362 Value::Ref(target) => *target,
363 _ => return Err(self.invalid(attribute, "entity reference or null")),
364 };
365 self.check_reference(attribute, target, &[expected], expected)?;
366 Ok(Some(target))
367 }
368
369 pub(crate) fn required_ref(
370 &self,
371 attribute: &'static str,
372 expected: &'static str,
373 ) -> StructuralResult<EntityId> {
374 self.optional_ref(attribute, expected)?
375 .ok_or_else(|| self.invalid(attribute, "entity reference"))
376 }
377
378 pub(crate) fn required_ref_select(
379 &self,
380 attribute: &'static str,
381 expected: &'static str,
382 members: &[&str],
383 ) -> StructuralResult<EntityId> {
384 let target = match self.value(attribute)?.unwrap_typed() {
385 Value::Ref(target) => *target,
386 _ => return Err(self.invalid(attribute, "entity reference")),
387 };
388 self.check_reference(attribute, target, members, expected)?;
389 Ok(target)
390 }
391
392 pub(crate) fn optional_set_refs(
393 &self,
394 attribute: &'static str,
395 expected: &'static str,
396 minimum_when_present: usize,
397 ) -> StructuralResult<Vec<EntityId>> {
398 let values = match self.value(attribute)?.unwrap_typed() {
399 Value::Null | Value::Derived => return Ok(Vec::new()),
400 Value::List(values) => values,
401 _ => return Err(self.invalid(attribute, "aggregate of entity references or null")),
402 };
403 if values.len() < minimum_when_present {
404 return Err(StructuralError::InvalidCardinality {
405 entity: self.id,
406 attribute,
407 minimum: minimum_when_present,
408 maximum: None,
409 actual: values.len(),
410 });
411 }
412 let mut targets = Vec::with_capacity(values.len());
413 let mut unique = HashSet::with_capacity(values.len());
414 for value in values {
415 let Value::Ref(target) = value.unwrap_typed() else {
416 return Err(self.invalid(attribute, "aggregate of entity references"));
417 };
418 if !unique.insert(*target) {
419 return Err(self.invalid(attribute, "SET of unique entity references"));
420 }
421 self.check_reference(attribute, *target, &[expected], expected)?;
422 targets.push(*target);
423 }
424 Ok(targets)
425 }
426
427 pub(crate) fn required_set_refs_select(
428 &self,
429 attribute: &'static str,
430 expected: &'static str,
431 members: &[&str],
432 minimum: usize,
433 ) -> StructuralResult<Vec<EntityId>> {
434 let values = match self.value(attribute)?.unwrap_typed() {
435 Value::List(values) => values,
436 _ => return Err(self.invalid(attribute, "aggregate of entity references")),
437 };
438 if values.len() < minimum {
439 return Err(StructuralError::InvalidCardinality {
440 entity: self.id,
441 attribute,
442 minimum,
443 maximum: None,
444 actual: values.len(),
445 });
446 }
447 let mut targets = Vec::with_capacity(values.len());
448 let mut unique = HashSet::with_capacity(values.len());
449 for value in values {
450 let Value::Ref(target) = value.unwrap_typed() else {
451 return Err(self.invalid(attribute, "aggregate of entity references"));
452 };
453 if !unique.insert(*target) {
454 return Err(self.invalid(attribute, "SET of unique entity references"));
455 }
456 self.check_reference(attribute, *target, members, expected)?;
457 targets.push(*target);
458 }
459 Ok(targets)
460 }
461
462 fn check_reference(
463 &self,
464 attribute: &'static str,
465 target: EntityId,
466 members: &[&str],
467 expected: &'static str,
468 ) -> StructuralResult<()> {
469 let target_entity = self
470 .model
471 .get(target)
472 .ok_or(StructuralError::DanglingReference {
473 entity: self.id,
474 attribute,
475 target,
476 })?;
477 if !members
478 .iter()
479 .any(|member| self.schema.is_a(&target_entity.type_name, member))
480 {
481 return Err(StructuralError::WrongReferenceType {
482 entity: self.id,
483 attribute,
484 target,
485 expected,
486 actual: target_entity.type_name.to_string(),
487 });
488 }
489 Ok(())
490 }
491
492 fn invalid(&self, attribute: &'static str, expected: &'static str) -> StructuralError {
493 StructuralError::InvalidValue {
494 entity: self.id,
495 attribute,
496 expected,
497 }
498 }
499}
500
501#[cfg(test)]
502mod intermediate_release_tests {
503 use super::*;
504
505 #[test]
508 fn ifc4x1_and_ifc4x2_are_refused_not_aliased() {
509 for token in ["IFC4X1", "IFC4X2"] {
510 let mut model = Model::new();
511 model.header_mut().schema = vec![token.to_owned()];
512 assert!(
513 matches!(
514 StructuralView::for_model(&model),
515 Err(StructuralError::UnsupportedSchema { token: found }) if found == token
516 ),
517 "{token} must be refused"
518 );
519 }
520 }
521}