ifc_properties/exact.rs
1//! Exact, fail-closed IFC2X3/IFC4/IFC4X3 property resolution.
2//!
3//! Unlike the permissive views, this traversal rejects any incomplete or
4//! malformed assignment data before it can claim an exact absence. Every
5//! structural fact comes from the table of the one release the header
6//! declares; nothing is aliased across releases.
7//!
8//! # Exact versus permissive
9//!
10//! The permissive views (`property_set`, `quantity_sets`, `query`) are for
11//! interactive inspection. A rule engine, validator or checker uses this
12//! exact API and must never map one of its errors to "absent": an error
13//! means the file could not prove the answer, which is not the same as the
14//! property being missing.
15//!
16//! Exact values keep their declared IFC value type and explicit unit
17//! identity. A downstream adapter that cannot project a value category or
18//! unit losslessly into its own model must reject it rather than coerce it.
19
20mod assignment;
21mod complex;
22mod composite;
23mod enumerate;
24mod index;
25mod material;
26mod measure;
27mod predefined;
28mod quantity;
29mod refs;
30mod release;
31mod set;
32mod unit;
33mod value;
34mod values;
35
36use std::{fmt, sync::Arc};
37
38use ifc_model::{EntityId, Model};
39use ifc_schema::SchemaVersion;
40
41use assignment::{assigned_sets, Relations};
42pub use enumerate::{
43 exact_properties, exact_properties_where, exact_property_sets_where, ExactPropertyEntry,
44 ExactPropertySetEntry,
45};
46pub use index::PropertyIndex;
47pub use material::{
48 exact_material_properties_where, exact_material_property, exact_material_property_sets_where,
49};
50pub use predefined::{exact_predefined_sets, ExactPredefinedSet};
51use release::{validate_model, Release};
52use set::find_property;
53pub use unit::{
54 convert_between, exact_project_unit, exact_unit, measure_unit_type, resolve_unit,
55 si_conversion, si_to_project, ExactUnit, ExactUnitError, MeasureUnitType,
56};
57pub use values::{
58 ExactBoundedValue, ExactComplexMember, ExactComplexValue, ExactEntityRef, ExactEnumeratedValue,
59 ExactEnumeration, ExactReferenceValue, ExactTableRow, ExactTableValue, ExactTypedValue,
60};
61
62/// Provenance of an exact result.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64#[non_exhaustive]
65pub enum ExactSource {
66 /// Resolved from a property set assigned directly to the occurrence
67 /// via `IfcRelDefinesByProperties`.
68 Occurrence,
69 /// Resolved from a set in `HasPropertySets` of the `IfcTypeObject` with
70 /// this entity id: inherited through the occurrence's type, or, when a
71 /// type object is queried, that object's own set (#193), so the id is
72 /// then the queried object's.
73 Type(EntityId),
74 /// Resolved from a material property set of the material definition
75 /// with this entity id (#218): an `IfcMaterialProperties`, or in IFC2X3
76 /// one of its subtypes, whose `Material` is that definition.
77 Material(EntityId),
78}
79
80/// Exact IFC logical value without collapsing unknown into a boolean.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum ExactLogical {
83 /// `IfcLogical` value `.F.`.
84 False,
85 /// `IfcLogical` value `.U.` — genuinely undetermined, not absent.
86 Unknown,
87 /// `IfcLogical` value `.T.`.
88 True,
89}
90
91/// Values accepted by the exact resolver.
92///
93/// An `IfcPropertySingleValue` or a simple quantity resolves to one of the
94/// scalar variants. The other `IfcSimpleProperty` kinds resolve to a
95/// composite variant whose scalars carry their own declared types
96/// ([`ExactTypedValue`]), and a complex property or quantity to
97/// [`ExactValue::Complex`]; for those, [`ExactProperty::value_type`] is
98/// `None`.
99#[derive(Debug, Clone, PartialEq)]
100#[non_exhaustive]
101pub enum ExactValue {
102 /// The property carried no value (`$`), distinct from an absent property.
103 Null,
104 /// An `IFCBOOLEAN` payload.
105 Bool(bool),
106 /// An `IFCLOGICAL` payload, keeping the tri-state distinction.
107 Logical(ExactLogical),
108 /// An `IFCBINARY` payload, stored as its literal encoded text.
109 Binary(Arc<str>),
110 /// An `IFCINTEGER` payload.
111 Integer(i64),
112 /// An `IFCREAL` (or compatible measure) payload; always finite.
113 Real(f64),
114 /// An `IFCTEXT`/`IFCLABEL`/`IFCIDENTIFIER`-family string payload.
115 Text(Arc<str>),
116 /// An `IfcPropertyEnumeratedValue`: its selected values and its
117 /// reference enumeration.
118 Enumerated(ExactEnumeratedValue),
119 /// An `IfcPropertyListValue`: its `ListValues` in file order, all of
120 /// one declared type; empty only when the attribute is `$` (IFC4 and
121 /// IFC4X3). The shared `Unit` is [`ExactProperty::unit_id`].
122 List(Vec<ExactTypedValue>),
123 /// An `IfcPropertyBoundedValue`: lower and upper bound and set point.
124 Bounded(Box<ExactBoundedValue>),
125 /// An `IfcPropertyTableValue`: its rows, expression, units and
126 /// interpolation.
127 Table(ExactTableValue),
128 /// An `IfcPropertyReferenceValue`: its usage name and target entity.
129 Reference(ExactReferenceValue),
130 /// An enumeration constant held by a predefined set's attribute, as
131 /// written without its dots, e.g. `SWINGING` for
132 /// `IfcDoorPanelProperties.PanelOperation`; always a member of the
133 /// declared enumeration in the bound release.
134 Enum(Arc<str>),
135 /// An entity held by a predefined set's attribute, e.g. the
136 /// `IfcShapeAspect` of `ShapeAspectStyle`; checked, not followed.
137 Entity(ExactEntityRef),
138 /// An `IfcComplexProperty` or `IfcPhysicalComplexQuantity` (#208): its
139 /// members, each resolved as a set member is. The complex is present
140 /// but is no value of any type, so [`ExactProperty::value_type`] and
141 /// [`ExactProperty::unit_id`] are `None`.
142 Complex(ExactComplexValue),
143}
144
145/// A uniquely resolved property with IFC identity and provenance.
146#[derive(Debug, Clone, PartialEq)]
147#[non_exhaustive]
148pub struct ExactProperty {
149 /// Whether the value came from the occurrence or from a type object's
150 /// `HasPropertySets` (inherited, or the queried type object's own).
151 pub source: ExactSource,
152 /// The owning `IfcPropertySet.Name` or `IfcElementQuantity.Name`; for a
153 /// predefined set its `Name`, or its entity name in the release's
154 /// spelling (`IfcDoorLiningProperties`) when it states none.
155 pub property_set: Arc<str>,
156 /// Entity id of the `IfcPropertySet`, `IfcElementQuantity` or
157 /// predefined set.
158 pub set_id: EntityId,
159 /// Entity id of the `IfcProperty` (single, enumerated, list, bounded,
160 /// table or reference value, or complex), or of the
161 /// `IfcPhysicalQuantity` (e.g. `IfcQuantityLength`, or a complex
162 /// quantity). For an attribute of a predefined set, which is no entity
163 /// of its own, the set's id.
164 pub property_id: EntityId,
165 /// Declared IFC value type (for example `IFCINTEGER` or `IFCLENGTHMEASURE`).
166 ///
167 /// `None` for a single value whose `NominalValue` is `$`, for a
168 /// composite value, whose scalars carry their own types, and for a
169 /// complex property or quantity, which has no value type at all.
170 ///
171 /// For a quantity it is the declared type of its value attribute in the
172 /// bound release (`LengthValue : IfcLengthMeasure` gives
173 /// `IFCLENGTHMEASURE`), since a quantity stores a bare number. For a
174 /// predefined set's attribute it is the attribute's declared type
175 /// (`LiningDepth : IfcPositiveLengthMeasure` gives
176 /// `IFCPOSITIVELENGTHMEASURE`), also when the value is `$`, except that a
177 /// select-typed attribute reports the member type the file wrote.
178 pub value_type: Option<Arc<str>>,
179 /// The explicit unit that applies to every value, if stated:
180 /// `IfcPropertySingleValue.Unit`, `IfcPropertyListValue.Unit`,
181 /// `IfcPropertyBoundedValue.Unit`, the `Unit` of an enumerated value's
182 /// `IfcPropertyEnumeration`, or `IfcPhysicalSimpleQuantity.Unit`.
183 /// A table's two units are in [`ExactTableValue`]; a reference value has
184 /// none.
185 pub unit_id: Option<EntityId>,
186 /// The resolved `NominalValue`, composite value, or the quantity's value.
187 pub value: ExactValue,
188}
189
190/// Exact lookup result.
191#[derive(Debug, Clone, PartialEq)]
192#[non_exhaustive]
193pub enum ExactResolution {
194 /// The property was found exactly once across occurrence and inherited sets.
195 Present(ExactProperty),
196 /// No occurrence or inherited property set, quantity set or predefined
197 /// set carried a matching property, quantity or attribute; this is a
198 /// proven absence, not a lookup failure.
199 ///
200 /// A predefined set's attribute that is `$` is not absent: it is
201 /// `Present` with [`ExactValue::Null`].
202 Absent,
203}
204
205/// Why a property cannot be resolved exactly.
206#[derive(Debug, Clone, PartialEq, Eq)]
207#[non_exhaustive]
208pub enum ExactPropertyError {
209 /// The model carries STEP-level diagnostics, so exactness cannot be
210 /// guaranteed; count of diagnostics is reported for context. Unit
211 /// resolution raises it only for a diagnostic it cannot classify, a
212 /// duplicate id the reader could not attribute, a skipped record without
213 /// an id, or no project after a skipped record (#615).
214 IncompleteModel {
215 /// Number of diagnostics recorded against the model.
216 diagnostics: usize,
217 },
218 /// The model header declares no `FILE_SCHEMA`.
219 MissingSchema,
220 /// The model header declares more than one schema.
221 MultipleSchemas {
222 /// Number of schemas declared in the header.
223 schemas: usize,
224 },
225 /// The model header declares a schema other than IFC2X3, IFC4 or
226 /// IFC4X3 (`IFC4X3_ADD2`).
227 UnsupportedSchema {
228 /// The declared schema token.
229 schema: String,
230 },
231 /// An entity reference points at an id absent from the model.
232 MissingReference {
233 /// The entity holding the reference.
234 from: EntityId,
235 /// The entity id that could not be resolved.
236 to: EntityId,
237 },
238 /// An aggregate attribute (list/set) was `$`, empty when required, or
239 /// not encoded as a list at all.
240 MalformedAggregate {
241 /// The entity whose attribute was malformed.
242 entity: EntityId,
243 /// Name of the offending attribute.
244 attribute: &'static str,
245 },
246 /// The occurrence is assigned to more than one `IfcTypeObject` via
247 /// `IfcRelDefinesByType`, which IFC forbids.
248 MultipleTypeAssignments {
249 /// The occurrence with conflicting type assignments.
250 object: EntityId,
251 /// The first `IfcTypeObject` found.
252 first: EntityId,
253 /// The second, conflicting `IfcTypeObject` found.
254 second: EntityId,
255 },
256 /// `IfcRelDefinesByProperties.RelatedObjects` names an object that is
257 /// not a non-type `IfcObjectDefinition`. A type object there is refused
258 /// even when it is the queried object: its sets belong in its
259 /// `HasPropertySets` (IFC4 and IFC4X3 `NoRelatedTypeObject`; IFC2X3
260 /// admits only `IfcObject`).
261 InvalidOccurrenceTarget {
262 /// The `IfcRelDefinesByProperties` relationship.
263 relationship: EntityId,
264 /// The invalid related object.
265 object: EntityId,
266 },
267 /// `IfcRelDefinesByType.RelatedObjects` names an object that is not an
268 /// `IfcObject`.
269 InvalidTypeTarget {
270 /// The `IfcRelDefinesByType` relationship.
271 relationship: EntityId,
272 /// The invalid related object.
273 object: EntityId,
274 },
275 /// The queried entity can carry no property sets in the declared
276 /// release: it is neither an object `IfcRelDefinesByProperties` may
277 /// relate (`IfcObject` in IFC2X3, a non-type `IfcObjectDefinition` in
278 /// IFC4 and IFC4X3) nor an `IfcTypeObject` (accepted since #193). For
279 /// a material query (#218): the entity is no material definition the
280 /// release's `IfcMaterialProperties.Material` accepts.
281 InvalidQueryObject {
282 /// The rejected query object.
283 object: EntityId,
284 /// The object's actual IFC type name.
285 type_name: Arc<str>,
286 },
287 /// The same entity id appears more than once in an aggregate attribute
288 /// that must have unique members.
289 DuplicateAggregateMember {
290 /// The entity holding the aggregate.
291 entity: EntityId,
292 /// Name of the offending attribute.
293 attribute: &'static str,
294 /// The entity id that appeared more than once.
295 member: EntityId,
296 },
297 /// Two property sets with the same name matched the query for the same
298 /// source (occurrence or type), making the result ambiguous.
299 DuplicateMatchingSets {
300 /// Whether the ambiguity arose among occurrence or type sets.
301 source: ExactSource,
302 /// The first matching property set.
303 first: EntityId,
304 /// The second, conflicting matching property set.
305 second: EntityId,
306 },
307 /// Two properties with the same name matched within the same set.
308 DuplicateMatchingProperties {
309 /// The `IfcPropertySet` containing the ambiguous properties.
310 set: EntityId,
311 /// The first matching property.
312 first: EntityId,
313 /// The second, conflicting matching property.
314 second: EntityId,
315 },
316 /// A `Name` attribute expected to be a string was `$`, a reference, or
317 /// otherwise not text.
318 MalformedName {
319 /// The entity whose name attribute was malformed.
320 entity: EntityId,
321 /// Name of the offending attribute (normally `"Name"`).
322 attribute: &'static str,
323 },
324 /// A `RelatingPropertyDefinition` reference resolves to an entity that
325 /// is not an `IfcPropertySetDefinition`; or a predefined property set
326 /// holds the requested name in an attribute this resolver cannot read
327 /// exactly (an aggregate, such as
328 /// `IfcReinforcementDefinitionProperties.ReinforcementSectionDefinitions`);
329 /// or a predefined set that states no `Name`, and so cannot be ruled out
330 /// by a set name, has an attribute of the requested name (#66).
331 UnsupportedDefinition {
332 /// The rejected entity.
333 entity: EntityId,
334 /// The entity's actual IFC type name.
335 type_name: Arc<str>,
336 },
337 /// A member of `IfcPropertySet.HasProperties` or
338 /// `IfcComplexProperty.HasProperties` is not an `IfcProperty`, or a
339 /// member of `IfcElementQuantity.Quantities` or
340 /// `IfcPhysicalComplexQuantity.HasQuantities` is not an
341 /// `IfcPhysicalQuantity`.
342 UnsupportedProperty {
343 /// The rejected entity.
344 entity: EntityId,
345 /// The entity's actual IFC type name.
346 type_name: Arc<str>,
347 },
348 /// A value the release requires was `$`: a quantity's value, or a
349 /// required value of another kind (IFC2X3
350 /// `IfcPropertyReferenceValue.PropertyReference`).
351 MissingValueSlot {
352 /// The property with the missing value.
353 property: EntityId,
354 },
355 /// An entity's attribute count does not match what the declared
356 /// release's schema declares for its type (a malformed or truncated STEP record).
357 MalformedEntitySlots {
358 /// The malformed entity.
359 entity: EntityId,
360 /// The entity's IFC type name.
361 type_name: Arc<str>,
362 /// Attribute count the schema declares for this type.
363 expected: usize,
364 /// Attribute count actually present on the entity.
365 actual: usize,
366 },
367 /// `IfcPropertySingleValue.Unit` references an entity that is not a
368 /// member of the `IfcUnit` select.
369 UnsupportedUnit {
370 /// The property with the invalid unit reference.
371 property: EntityId,
372 },
373 /// `IfcPropertySingleValue.NominalValue` carries a typed value whose
374 /// declared type is not accepted by `IFCVALUE`, or whose payload does
375 /// not match its declared type.
376 UnsupportedValue {
377 /// The property with the invalid value.
378 property: EntityId,
379 },
380 /// `IfcPropertySingleValue.NominalValue` is an `IFCREAL` that is NaN or
381 /// infinite, which IFC does not permit.
382 NonFiniteReal {
383 /// The property with the non-finite real value.
384 property: EntityId,
385 },
386 /// A traversed record, typed value, or select member names a construct
387 /// that the release declared in `FILE_SCHEMA` does not define, for
388 /// example an `IfcDoorType` or an `IfcPropertySetDefinitionSet` in an
389 /// IFC2X3 file. The file mixes releases, so nothing it says about the
390 /// property is trusted.
391 NotInSchema {
392 /// The entity holding or being the foreign construct.
393 entity: EntityId,
394 /// The construct's name as written in the file.
395 name: Arc<str>,
396 /// The release the header declares.
397 schema: SchemaVersion,
398 },
399 /// Values that the property's release constrains contradict one of
400 /// those constraints, so no one reading of them is exact: list members
401 /// or bounds of different types, table columns of unequal length, a
402 /// selected value missing from the referenced enumeration, or a repeated
403 /// member of a `LIST OF UNIQUE`.
404 InconsistentValues {
405 /// The property or `IfcPropertyEnumeration` holding the values.
406 entity: EntityId,
407 /// The release's label of the violated WHERE rule (for example
408 /// `WR31`, or `SameUnitUpperLower` in IFC4), or `<Attribute> UNIQUE`
409 /// for a repeated member of a unique list.
410 rule: &'static str,
411 },
412 /// The entity name given to [`exact_predefined_sets`] is not a
413 /// predefined property set in the declared release: not declared there
414 /// at all, or an `IfcPropertySet`, a quantity set, or one of their
415 /// supertypes.
416 NotAPredefinedSet {
417 /// The entity name as requested.
418 name: Arc<str>,
419 /// The release the header declares.
420 schema: SchemaVersion,
421 },
422 /// A proper subtype of `IfcRelDefinesByProperties` or
423 /// `IfcRelDefinesByType` relates the queried object, such as IFC2X3
424 /// `IfcRelOverridesProperties`. Its semantics change which value applies,
425 /// and the exact resolver does not interpret them, so it refuses rather
426 /// than answer as if the relationship were absent.
427 UnsupportedRelationship {
428 /// The relationship instance.
429 relationship: EntityId,
430 /// Its IFC type name.
431 type_name: Arc<str>,
432 },
433 /// A complex property or quantity reaches itself again through its
434 /// members (#208). The schema forbids only a direct self-member; a
435 /// longer cycle has no finite resolution either.
436 ComplexCycle {
437 /// The complex whose member list closes the cycle.
438 complex: EntityId,
439 /// The member already being resolved higher up the path.
440 member: EntityId,
441 },
442 /// A complex property or quantity nested deeper than the resolver
443 /// follows below one set member (#208).
444 ComplexTooDeep {
445 /// The complex whose members would exceed the depth.
446 complex: EntityId,
447 /// The nesting depth followed.
448 limit: usize,
449 },
450 /// Resolving one set member followed more nested member references
451 /// than its budget (#208). Members may be shared between complexes,
452 /// so a small file can expand into an enormous tree.
453 ComplexBudgetExceeded {
454 /// The complex whose member exceeded the budget.
455 complex: EntityId,
456 /// The nested member references followed.
457 limit: usize,
458 },
459}
460impl fmt::Display for ExactPropertyError {
461 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
462 write!(f, "exact IFC property resolution failed: {self:?}")
463 }
464}
465
466/// The IFC release a model's properties are resolved against.
467///
468/// This is the release `exact_property` binds to: the single `FILE_SCHEMA`
469/// token, if it names a release the exact resolver supports (IFC2X3 TC1,
470/// IFC4 ADD2 TC1 or IFC4X3 ADD2, the bundled tables). A consumer binds its vocabulary per release with this answer
471/// instead of re-parsing the header. It fails exactly as `exact_property`
472/// fails at model level: diagnostics, no schema, several schemas, or an
473/// unsupported one.
474///
475/// # Errors
476///
477/// [`ExactPropertyError::IncompleteModel`], [`ExactPropertyError::MissingSchema`],
478/// [`ExactPropertyError::MultipleSchemas`], or
479/// [`ExactPropertyError::UnsupportedSchema`].
480pub fn exact_schema(model: &Model) -> Result<SchemaVersion, ExactPropertyError> {
481 validate_model(model).map(|release| release.version)
482}
483
484impl std::error::Error for ExactPropertyError {}
485
486/// Resolve a property or quantity by exact set and property name.
487///
488/// Single, enumerated, list, bounded, table and reference values resolve,
489/// the last five as composite [`ExactValue`]s. An `IfcComplexProperty` or
490/// `IfcPhysicalComplexQuantity` resolves as [`ExactValue::Complex`]: present,
491/// with no value type (#208).
492///
493/// A predefined property set (`IfcDoorLiningProperties` and the like) is
494/// searched too: its members are the attributes its entity declares, by
495/// schema name (`LiningDepth`), and its set name is its `Name`, or its
496/// entity name (`IfcDoorLiningProperties`) when it states none. A door with
497/// one `IfcDoorPanelProperties` per leaf is ambiguous here; list such sets
498/// with [`exact_predefined_sets`].
499///
500/// The model is resolved against the single release its `FILE_SCHEMA`
501/// declares, IFC2X3, IFC4 or IFC4X3 (see [`exact_schema`]); every domain,
502/// select and slot count is that release's. With `set_name == None`, all
503/// assigned sets are searched. Occurrence values override matching inherited
504/// values at property level. To enumerate every property instead of naming
505/// one, use [`exact_properties`].
506///
507/// `object` may also be an `IfcTypeObject` of the release (an `IfcWallType`,
508/// an IFC2X3 `IfcDoorStyle`, ...). Its own `HasPropertySets` are then
509/// searched, with the validation an occurrence's inherited type sets get,
510/// and a result carries [`ExactSource::Type`] with `object`'s id. `$` states
511/// no sets, a proven absence; an empty list is refused as for an inherited
512/// type. A type object named in an `IfcRelDefinesByProperties` is refused
513/// ([`ExactPropertyError::InvalidOccurrenceTarget`]), never ignored.
514///
515/// Quantity sets are searched like property sets, as buildingSMART IDS
516/// treats a quantity as a property: `Qto_WallBaseQuantities.Length` resolves
517/// to the `IfcQuantityLength` of that name. A property set and a quantity set
518/// of the same matching name on one source are ambiguous and refused.
519/// WHERE rules such as `LengthValue >= 0` are not evaluated; the value is
520/// the file's.
521///
522/// # Errors
523///
524/// Any [`ExactPropertyError`]: the answer is refused rather than guessed
525/// whenever the evidence is incomplete, ambiguous, or foreign to the
526/// declared release.
527pub fn exact_property(
528 model: &Model,
529 object: EntityId,
530 set_name: Option<&str>,
531 property_name: &str,
532) -> Result<ExactResolution, ExactPropertyError> {
533 let release = validate_model(model)?;
534 property_in(model, release, None, object, set_name, property_name)
535}
536
537/// [`exact_property`] once the model is bound to `release`, from a scan of
538/// every relationship when one is given.
539fn property_in(
540 model: &Model,
541 release: Release,
542 relations: Option<&Relations>,
543 object: EntityId,
544 set_name: Option<&str>,
545 property_name: &str,
546) -> Result<ExactResolution, ExactPropertyError> {
547 let assigned = assigned_sets(model, release, relations, object)?;
548 let occurrence = find_property(
549 model,
550 release,
551 &assigned.occurrence_sets,
552 ExactSource::Occurrence,
553 set_name,
554 property_name,
555 )?;
556 let inherited = match &assigned.type_sets {
557 Some((type_id, sets)) => find_property(
558 model,
559 release,
560 sets,
561 ExactSource::Type(*type_id),
562 set_name,
563 property_name,
564 )?,
565 None => None,
566 };
567 Ok(occurrence
568 .or(inherited)
569 .map_or(ExactResolution::Absent, ExactResolution::Present))
570}