ifc-resource 0.2.0

Construction resources: labour, equipment, material, crew, subcontract.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! Shared schema-resolved borrowed view primitives.

use std::collections::HashSet;

use ifc_model::{Entity, EntityId, Model, Value};
use ifc_schema::{ifc4, ifc4x3, Schema, SchemaVersion, TypeKind};

use crate::error::{ResourceError, ResourceResult};
use crate::{ConstructionResource, ResourceTime};

#[derive(Debug, Clone, Copy)]
/// Borrowed, schema-resolved entry point for the bounded IFC4 resource
/// slice: pairs a model with the schema selected for it and exposes
/// per-entity projection and query methods.
pub struct ResourceView<'m, 's> {
    pub(crate) model: &'m Model,
    pub(crate) schema: &'s Schema,
}

impl<'m, 's> ResourceView<'m, 's> {
    /// Builds a view over `model` using an explicit `schema`, failing if
    /// `schema` is not IFC4 or IFC4X3, or does not match the model's
    /// declared `FILE_SCHEMA` token.
    pub fn new(model: &'m Model, schema: &'s Schema) -> ResourceResult<Self> {
        let Some(version) = schema.version() else {
            return Err(ResourceError::UnsupportedSchema {
                token: schema.name().to_owned(),
            });
        };
        if !matches!(version, SchemaVersion::Ifc4 | SchemaVersion::Ifc4x3) {
            return Err(ResourceError::UnsupportedSchema {
                token: schema.name().to_owned(),
            });
        }
        match model.header().schema.as_slice() {
            [] => {}
            [token] if SchemaVersion::from_header_token(token) == Some(version) => {}
            [token] => {
                return Err(ResourceError::UnsupportedSchema {
                    token: token.clone(),
                });
            }
            tokens => {
                return Err(ResourceError::AmbiguousSchema {
                    tokens: tokens.to_vec(),
                });
            }
        }
        Ok(Self { model, schema })
    }

    /// The bundled schema this view resolves attributes against.
    #[must_use]
    pub fn schema(&self) -> &'s Schema {
        self.schema
    }

    /// Projects a concrete `IfcConstructionResource` occurrence by entity
    /// id.
    pub fn resource(&self, id: EntityId) -> ResourceResult<ConstructionResource<'m, 's>> {
        ConstructionResource::from_record(self.record(id, "IfcConstructionResource")?)
    }

    /// Projects an `IfcResourceTime` by entity id.
    pub fn resource_time(&self, id: EntityId) -> ResourceResult<ResourceTime<'m, 's>> {
        Ok(ResourceTime::from_record(
            self.record(id, "IfcResourceTime")?,
        ))
    }

    pub(crate) fn record(
        &self,
        id: EntityId,
        expected: &'static str,
    ) -> ResourceResult<Record<'m, 's>> {
        Record::new(self.model, self.schema, id, expected)
    }

    pub(crate) fn ids_of_ancestor(&self, ancestor: &str) -> Vec<EntityId> {
        self.model
            .iter()
            .filter_map(|(id, entity)| self.schema.is_a(&entity.type_name, ancestor).then_some(id))
            .collect()
    }
}

impl<'m> ResourceView<'m, 'static> {
    /// Selects the bundled schema matching the model's declared
    /// `FILE_SCHEMA` token (IFC4 ADD2 TC1 or IFC4X3 ADD2), failing if the
    /// header names no schema, more than one, or an unsupported one.
    pub fn for_model(model: &'m Model) -> ResourceResult<Self> {
        let token = match model.header().schema.as_slice() {
            [] => return Err(ResourceError::MissingSchema),
            [token] => token,
            tokens => {
                return Err(ResourceError::AmbiguousSchema {
                    tokens: tokens.to_vec(),
                });
            }
        };
        let version = SchemaVersion::from_header_token(token).ok_or_else(|| {
            ResourceError::UnsupportedSchema {
                token: token.clone(),
            }
        })?;
        let schema = match version {
            SchemaVersion::Ifc4 => ifc4(),
            SchemaVersion::Ifc4x3 => ifc4x3(),
            SchemaVersion::Ifc2x3 => {
                return Err(ResourceError::UnsupportedSchema {
                    token: token.clone(),
                });
            }
        };
        Self::new(model, schema)
    }
}

pub(crate) fn validate_object_assignment(
    model: &Model,
    schema: &Schema,
    relation: Option<EntityId>,
    related_objects_type: Option<&str>,
    related_objects: &[EntityId],
) -> ResourceResult<()> {
    let Some(category) = related_objects_type else {
        return Ok(());
    };
    let expected = if category.eq_ignore_ascii_case("NOTDEFINED") {
        return Ok(());
    } else if category.eq_ignore_ascii_case("PRODUCT") {
        "IfcProduct"
    } else if category.eq_ignore_ascii_case("PROCESS") {
        "IfcProcess"
    } else if category.eq_ignore_ascii_case("CONTROL") {
        "IfcControl"
    } else if category.eq_ignore_ascii_case("RESOURCE") {
        "IfcResource"
    } else if category.eq_ignore_ascii_case("ACTOR") {
        "IfcActor"
    } else if category.eq_ignore_ascii_case("GROUP") {
        "IfcGroup"
    } else if category.eq_ignore_ascii_case("PROJECT") {
        "IfcProject"
    } else {
        return Err(ResourceError::InvalidEnumeration {
            entity: relation,
            attribute: "RelatedObjectsType",
            value: category.to_owned(),
        });
    };
    if related_objects.iter().any(|target| {
        model
            .get(*target)
            .is_none_or(|entity| !schema.is_a(&entity.type_name, expected))
    }) {
        return Err(ResourceError::SemanticViolation {
            entity: relation,
            rule: "IfcRelAssigns.WR1_IfcCorrectObjectAssignment",
        });
    }
    Ok(())
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct Record<'m, 's> {
    pub(crate) model: &'m Model,
    pub(crate) schema: &'s Schema,
    pub(crate) id: EntityId,
    pub(crate) entity: &'m Entity,
}

impl<'m, 's> Record<'m, 's> {
    pub(crate) fn new(
        model: &'m Model,
        schema: &'s Schema,
        id: EntityId,
        expected: &'static str,
    ) -> ResourceResult<Self> {
        let entity = model.get(id).ok_or(ResourceError::EntityNotFound { id })?;
        if !schema.is_a(&entity.type_name, expected) {
            return Err(ResourceError::WrongType {
                id,
                expected,
                actual: entity.type_name.to_string(),
            });
        }
        Ok(Self {
            model,
            schema,
            id,
            entity,
        })
    }

    fn slot(&self, attribute: &'static str) -> ResourceResult<usize> {
        self.schema
            .attribute_names(&self.entity.type_name)
            .iter()
            .position(|name| name.eq_ignore_ascii_case(attribute))
            .ok_or(ResourceError::MissingAttribute {
                entity: self.id,
                attribute,
            })
    }

    pub(crate) fn value(&self, attribute: &'static str) -> ResourceResult<&'m Value> {
        self.entity
            .attributes
            .get(self.slot(attribute)?)
            .ok_or(ResourceError::MissingAttribute {
                entity: self.id,
                attribute,
            })
    }

    pub(crate) fn required_text(&self, attribute: &'static str) -> ResourceResult<&'m str> {
        match self.value(attribute)?.unwrap_typed() {
            Value::Text(value) => Ok(value),
            _ => Err(self.invalid(attribute, "text")),
        }
    }

    pub(crate) fn optional_text_list(
        &self,
        attribute: &'static str,
        minimum: usize,
    ) -> ResourceResult<Vec<&'m str>> {
        let values = match self.value(attribute)?.unwrap_typed() {
            Value::Null | Value::Derived => return Ok(Vec::new()),
            Value::List(values) => values,
            _ => return Err(self.invalid(attribute, "aggregate of text or null")),
        };
        if values.len() < minimum {
            return Err(ResourceError::InvalidCardinality {
                entity: self.id,
                attribute,
                minimum,
                actual: values.len(),
            });
        }
        values
            .iter()
            .map(|value| match value.unwrap_typed() {
                Value::Text(value) => Ok(value.as_ref()),
                _ => Err(self.invalid(attribute, "aggregate of text or null")),
            })
            .collect()
    }

    pub(crate) fn optional_text(&self, attribute: &'static str) -> ResourceResult<Option<&'m str>> {
        match self.value(attribute)?.unwrap_typed() {
            Value::Null | Value::Derived => Ok(None),
            Value::Text(value) => Ok(Some(value)),
            _ => Err(self.invalid(attribute, "text or null")),
        }
    }

    pub(crate) fn optional_bool(&self, attribute: &'static str) -> ResourceResult<Option<bool>> {
        match self.value(attribute)?.unwrap_typed() {
            Value::Null | Value::Derived => Ok(None),
            Value::Bool(value) => Ok(Some(*value)),
            _ => Err(self.invalid(attribute, "boolean or null")),
        }
    }

    pub(crate) fn optional_positive_number(
        &self,
        attribute: &'static str,
    ) -> ResourceResult<Option<f64>> {
        let value = match self.value(attribute)?.unwrap_typed() {
            Value::Null | Value::Derived => return Ok(None),
            Value::Integer(value) => *value as f64,
            Value::Real(value) => *value,
            _ => return Err(self.invalid(attribute, "finite positive number or null")),
        };
        if !value.is_finite() || value <= 0.0 {
            return Err(self.invalid(attribute, "finite positive number or null"));
        }
        Ok(Some(value))
    }

    pub(crate) fn required_non_negative_number(
        &self,
        attribute: &'static str,
    ) -> ResourceResult<f64> {
        let value = match self.value(attribute)?.unwrap_typed() {
            Value::Integer(value) => *value as f64,
            Value::Real(value) => *value,
            _ => return Err(self.invalid(attribute, "finite non-negative number")),
        };
        if !value.is_finite() || value < 0.0 {
            return Err(self.invalid(attribute, "finite non-negative number"));
        }
        Ok(value)
    }

    pub(crate) fn required_enum(&self, attribute: &'static str) -> ResourceResult<&'m str> {
        let value = match self.value(attribute)?.unwrap_typed() {
            Value::Enum(value) => value,
            _ => return Err(self.invalid(attribute, "declared enumeration")),
        };
        if !self.declares_enum_member(attribute, value) {
            return Err(ResourceError::InvalidEnumeration {
                entity: Some(self.id),
                attribute,
                value: value.to_string(),
            });
        }
        Ok(value)
    }

    pub(crate) fn optional_enum(&self, attribute: &'static str) -> ResourceResult<Option<&'m str>> {
        let value = match self.value(attribute)?.unwrap_typed() {
            Value::Null | Value::Derived => return Ok(None),
            Value::Enum(value) => value,
            _ => return Err(self.invalid(attribute, "declared enumeration or null")),
        };
        if !self.declares_enum_member(attribute, value) {
            return Err(ResourceError::InvalidEnumeration {
                entity: Some(self.id),
                attribute,
                value: value.to_string(),
            });
        }
        Ok(Some(value))
    }

    fn declares_enum_member(&self, attribute: &str, value: &str) -> bool {
        let declarations = self.schema.attributes(&self.entity.type_name);
        let Some(declaration) = declarations
            .iter()
            .find(|candidate| candidate.name.eq_ignore_ascii_case(attribute))
        else {
            return false;
        };
        let mut type_name = declaration.type_name.as_str();
        for _ in 0..16 {
            let Some(definition) = self.schema.type_def(type_name) else {
                return false;
            };
            match &definition.kind {
                TypeKind::Enumeration(members) => {
                    return members
                        .iter()
                        .any(|member| member.eq_ignore_ascii_case(value));
                }
                TypeKind::Defined(alias) => type_name = alias,
                TypeKind::Select(_) => return false,
            }
        }
        false
    }

    pub(crate) fn optional_ref(
        &self,
        attribute: &'static str,
        expected: &'static str,
    ) -> ResourceResult<Option<EntityId>> {
        let target = match self.value(attribute)?.unwrap_typed() {
            Value::Null | Value::Derived => return Ok(None),
            Value::Ref(target) => *target,
            _ => return Err(self.invalid(attribute, "entity reference or null")),
        };
        self.check_reference(attribute, target, &[expected], expected)?;
        Ok(Some(target))
    }

    pub(crate) fn required_ref(
        &self,
        attribute: &'static str,
        expected: &'static str,
    ) -> ResourceResult<EntityId> {
        let Value::Ref(target) = self.value(attribute)?.unwrap_typed() else {
            return Err(self.invalid(attribute, "entity reference"));
        };
        self.check_reference(attribute, *target, &[expected], expected)?;
        Ok(*target)
    }

    pub(crate) fn optional_ref_select(
        &self,
        attribute: &'static str,
        expected: &'static str,
        members: &[&str],
    ) -> ResourceResult<Option<EntityId>> {
        let target = match self.value(attribute)?.unwrap_typed() {
            Value::Null | Value::Derived => return Ok(None),
            Value::Ref(target) => *target,
            _ => return Err(self.invalid(attribute, "entity reference or null")),
        };
        self.check_reference(attribute, target, members, expected)?;
        Ok(Some(target))
    }

    pub(crate) fn required_ref_select(
        &self,
        attribute: &'static str,
        expected: &'static str,
        members: &[&str],
    ) -> ResourceResult<EntityId> {
        let Value::Ref(target) = self.value(attribute)?.unwrap_typed() else {
            return Err(self.invalid(attribute, "entity reference"));
        };
        self.check_reference(attribute, *target, members, expected)?;
        Ok(*target)
    }

    pub(crate) fn refs(
        &self,
        attribute: &'static str,
        expected: &'static str,
        minimum: usize,
        optional: bool,
        unique: bool,
    ) -> ResourceResult<Vec<EntityId>> {
        let values = match self.value(attribute)?.unwrap_typed() {
            Value::Null | Value::Derived if optional => return Ok(Vec::new()),
            Value::List(values) => values,
            _ => return Err(self.invalid(attribute, "aggregate of entity references")),
        };
        if values.len() < minimum {
            return Err(ResourceError::InvalidCardinality {
                entity: self.id,
                attribute,
                minimum,
                actual: values.len(),
            });
        }
        let mut targets = Vec::with_capacity(values.len());
        let mut seen = HashSet::with_capacity(values.len());
        for value in values {
            let Value::Ref(target) = value.unwrap_typed() else {
                return Err(self.invalid(attribute, "aggregate of entity references"));
            };
            if unique && !seen.insert(*target) {
                return Err(ResourceError::DuplicateReference {
                    entity: self.id,
                    attribute,
                    target: *target,
                });
            }
            self.check_reference(attribute, *target, &[expected], expected)?;
            targets.push(*target);
        }
        Ok(targets)
    }

    pub(crate) fn check_reference(
        &self,
        attribute: &'static str,
        target: EntityId,
        members: &[&str],
        expected: &'static str,
    ) -> ResourceResult<()> {
        let entity = self
            .model
            .get(target)
            .ok_or(ResourceError::DanglingReference {
                entity: self.id,
                attribute,
                target,
            })?;
        if !members
            .iter()
            .any(|member| self.schema.is_a(&entity.type_name, member))
        {
            return Err(ResourceError::WrongReferenceType {
                entity: self.id,
                attribute,
                target,
                expected,
                actual: entity.type_name.to_string(),
            });
        }
        Ok(())
    }

    pub(crate) fn require_object_type_if(
        &self,
        condition: bool,
        rule: &'static str,
    ) -> ResourceResult<()> {
        if condition
            && self
                .optional_text("ObjectType")?
                .is_none_or(|value| value.trim().is_empty())
        {
            return Err(ResourceError::SemanticViolation {
                entity: Some(self.id),
                rule,
            });
        }
        Ok(())
    }

    fn invalid(&self, attribute: &'static str, expected: &'static str) -> ResourceError {
        ResourceError::InvalidValue {
            entity: self.id,
            attribute,
            expected,
        }
    }
}