Skip to main content

ifc_properties/
error.rs

1//! Why a property lookup failed, and what a file got wrong.
2//!
3//! Anomalies describe a MALFORMED file, not a reader failure. They are
4//! returned alongside results rather than replacing them: one broken
5//! relationship must not hide every valid property in the model.
6
7use ifc_model::EntityId;
8use ifc_schema::SchemaVersion;
9
10/// A structural problem found while reading properties.
11///
12/// `#[non_exhaustive]`: new structural checks add variants without breaking
13/// callers that match on this type.
14#[derive(Debug, Clone, PartialEq)]
15#[non_exhaustive]
16pub enum PropertyAnomaly {
17    /// An object assigned two different types by `IfcRelDefinesByType`.
18    ///
19    /// IFC4 `IfcObject.IsTypedBy` is `SET [0:1]`; IFC2X3 `IfcObject` WR1
20    /// allows at most one. The first relationship by id is kept, and only
21    /// its type's sets are inherited.
22    TypedTwice {
23        /// The object with two types.
24        object: EntityId,
25        /// The type kept.
26        kept: EntityId,
27        /// The type rejected.
28        rejected: EntityId,
29        /// The `IfcRelDefinesByType` that was rejected.
30        relation: EntityId,
31    },
32    /// Two property sets, or two quantity sets, of the same name on one owner.
33    ///
34    /// IFC4 forbids it on both occurrences (`IfcObject.UniquePropertySetNames`)
35    /// and types (`IfcTypeObject.UniquePropertySetNames`); IFC2X3 states no
36    /// such rule. No release forbids two same-named quantity sets, since
37    /// `UniquePropertySetNames` counts only `IfcPropertySet`. Either way the
38    /// resolved view is keyed by name, so the set
39    /// with the lower id is kept and the other is reported here rather than
40    /// silently overwriting it.
41    DuplicateSetName {
42        /// The occurrence or type holding both sets.
43        owner: EntityId,
44        /// The set kept.
45        kept: EntityId,
46        /// The set not resolved.
47        rejected: EntityId,
48    },
49    /// Two properties of the same name in one property set, or two property
50    /// templates of the same name in one set or complex template, or two
51    /// quantities of the same name in one `IfcElementQuantity`.
52    ///
53    /// Forbidden in IFC4 (`IfcPropertySet.UniquePropertyNames`) and IFC2X3
54    /// (`WR32`). [`PropertySet::property`](crate::PropertySet::property)
55    /// answers with the first in `HasProperties` order. For quantities the
56    /// rule is `UniqueQuantityNames` in IFC4 and later; IFC2X3 has none.
57    /// [`quantity_sets_by_object`](crate::quantity_sets_by_object) reports
58    /// them, and [`QuantitySet::quantity`](crate::QuantitySet::quantity)
59    /// answers with the first. For templates,
60    /// `IfcPropertySetTemplate` and `IfcComplexPropertyTemplate` both carry
61    /// `UniquePropertyNames`; `set` is then the template, and the first
62    /// template in `HasPropertyTemplates` order is the one a check uses.
63    DuplicatePropertyName {
64        /// The property set.
65        set: EntityId,
66        /// The property kept.
67        kept: EntityId,
68        /// The property shadowed.
69        rejected: EntityId,
70    },
71    /// An `IfcTypeObject` attached by `IfcRelDefinesByProperties`.
72    ///
73    /// Forbidden by the `NoRelatedTypeObject` WHERE rule: a type carries its
74    /// sets in `HasPropertySets`. The set is still reported, because refusing
75    /// to read a common exporter bug helps nobody.
76    TypeAttachedByRelationship {
77        /// The offending relationship.
78        relationship: EntityId,
79        /// The type object that must not be there.
80        type_object: EntityId,
81    },
82    /// A relationship names a property definition absent from the file.
83    MissingDefinition {
84        /// The relationship.
85        relationship: EntityId,
86        /// The id it named.
87        definition: EntityId,
88    },
89    /// An `IfcTypeObject` lists a definition absent from the file in
90    /// `HasPropertySets`.
91    ///
92    /// The set cannot be read, so the type carries nothing for it.
93    MissingTypeSet {
94        /// The type object listing the definition.
95        type_object: EntityId,
96        /// The id it named.
97        definition: EntityId,
98    },
99    /// A relationship names an object absent from the file.
100    MissingObject {
101        /// The relationship.
102        relationship: EntityId,
103        /// The id it named.
104        object: EntityId,
105    },
106    /// A quantity states a unit whose type contradicts the quantity kind.
107    ///
108    /// `IfcQuantityLength.WR21` requires a LENGTHUNIT, and the sibling
109    /// quantities carry the same rule. A file breaking it has stated two
110    /// different things about the same number.
111    QuantityUnitMismatch {
112        /// The quantity entity.
113        quantity: EntityId,
114        /// The unit it named.
115        unit: EntityId,
116        /// The `IfcUnitEnum` the schema requires.
117        expected: &'static str,
118        /// The `IfcUnitEnum` the file stated.
119        found: String,
120    },
121    /// A simple quantity states a negative value.
122    ///
123    /// Every `IfcQuantity*` carries `WR22 : Value >= 0.` (count included). A
124    /// negative area is not a small error; it is a value no consumer should
125    /// use for takeoff.
126    NegativeQuantity {
127        /// The quantity entity.
128        quantity: EntityId,
129        /// The value stated.
130        value: f64,
131    },
132    /// A simple quantity states no value.
133    ///
134    /// The value attribute (`LengthValue`, `AreaValue`, ...) is not
135    /// `OPTIONAL` on any `IfcQuantity*`. The quantity stays in its set's
136    /// `quantities` as `Quantity::Unresolved` with
137    /// `UnresolvedValue::Missing`, and is named here.
138    QuantityValueMissing {
139        /// The quantity entity.
140        quantity: EntityId,
141    },
142    /// A simple quantity's value attribute holds something other than a
143    /// number, such as text or a reference.
144    ///
145    /// The quantity stays in its set's `quantities` as
146    /// `Quantity::Unresolved` with `UnresolvedValue::NotNumeric`, and is
147    /// named here.
148    QuantityValueNotNumeric {
149        /// The quantity entity.
150        quantity: EntityId,
151        /// The value found, rendered for the message.
152        found: String,
153    },
154    /// A property set, quantity set, complex property or complex quantity,
155    /// or a property set or complex template, lists a member id that is not
156    /// in the file.
157    ///
158    /// The member cannot be read, so it is absent from the resolved value.
159    MissingMember {
160        /// The set or complex entity listing the member.
161        container: EntityId,
162        /// The id it named.
163        member: EntityId,
164    },
165    /// A member list holds an item that is not an entity reference.
166    ///
167    /// `IfcPropertySet.HasProperties`, `IfcComplexProperty.HasProperties`,
168    /// `IfcElementQuantity.Quantities` and
169    /// `IfcPhysicalComplexQuantity.HasQuantities` are sets of entity
170    /// references. An item such as a string or number names no member, so
171    /// nothing is read for it.
172    MemberNotReference {
173        /// The set or complex entity holding the list.
174        container: EntityId,
175        /// The list attribute, e.g. `"HasProperties"`.
176        attribute: &'static str,
177        /// The item found, rendered for the message.
178        found: String,
179    },
180    /// A member list names the same entity more than once.
181    ///
182    /// Each of those lists is an EXPRESS `SET`, which cannot hold one
183    /// instance twice. The member is read once, at its first position.
184    DuplicateMember {
185        /// The set or complex entity holding the list.
186        container: EntityId,
187        /// The list attribute, e.g. `"Quantities"`.
188        attribute: &'static str,
189        /// The member listed again.
190        member: EntityId,
191    },
192    /// A complex property, complex quantity or complex property template
193    /// reaches itself again through its members.
194    ///
195    /// The schema forbids only a DIRECT self-member (`IfcComplexProperty`
196    /// `WR21`, `IfcPhysicalComplexQuantity.NoSelfReference`,
197    /// `IfcComplexPropertyTemplate.NoSelfReference`); a longer cycle is just
198    /// as unresolvable. `member` is already being read higher
199    /// up the same path, so it is left out of `complex`'s resolved members.
200    ComplexCycle {
201        /// The complex entity whose member list closes the cycle.
202        complex: EntityId,
203        /// The member that re-enters the path.
204        member: EntityId,
205    },
206    /// Complex nesting deeper than the reader follows.
207    ///
208    /// `complex` is resolved with its name and usage, but its members are
209    /// not read.
210    ComplexTooDeep {
211        /// The complex entity whose members were not read.
212        complex: EntityId,
213        /// The nesting depth followed.
214        limit: usize,
215    },
216    /// One read followed more nested member references than its budget.
217    ///
218    /// Members may legally be shared between complex properties, so a
219    /// small file can expand into an enormous tree. Once the budget is
220    /// spent, the remaining members of `complex` are not read.
221    ComplexBudgetExceeded {
222        /// The complex entity whose remaining members were not read.
223        complex: EntityId,
224        /// The nested member references followed.
225        limit: usize,
226    },
227    /// A template's member list, or an `IfcRelDefinesByTemplate`, names an
228    /// entity that is not a template of the required kind.
229    ///
230    /// `HasPropertyTemplates` is a `SET [1:?] OF IfcPropertyTemplate` and
231    /// `RelatingTemplate` an `IfcPropertySetTemplate`. The entity is not
232    /// read as a template.
233    NotATemplate {
234        /// The template or relationship naming it.
235        container: EntityId,
236        /// The entity named.
237        member: EntityId,
238        /// Its IFC type name.
239        type_name: String,
240    },
241    /// A record's attribute count differs from what the bound release
242    /// declares for its entity.
243    ///
244    /// Attributes are read by name from that release's table, so a short
245    /// record would otherwise read its missing trailing attributes as unset.
246    /// The attributes present are still read.
247    SlotCountMismatch {
248        /// The malformed record.
249        entity: EntityId,
250        /// Its IFC type name.
251        type_name: String,
252        /// The attribute count the release declares.
253        expected: usize,
254        /// The attribute count in the file.
255        actual: usize,
256    },
257    /// An attribute holds a value its declared type does not admit: a
258    /// number where a label is declared, an enumeration constant that is not
259    /// a member of the release's enumeration, or a reference to an entity
260    /// outside the declared type.
261    ///
262    /// The value is still reported as written where the view has a place
263    /// for it (an enumeration constant, a reference id), and left unset
264    /// otherwise.
265    MalformedAttribute {
266        /// The entity holding the attribute.
267        entity: EntityId,
268        /// The attribute, as the schema names it.
269        attribute: &'static str,
270        /// The value found, rendered for the message.
271        found: String,
272    },
273}
274
275/// Why property templates could not be read or checked against the
276/// release a model declares.
277///
278/// Distinct from [`PropertyAnomaly`]: an anomaly is a malformed fact inside
279/// a file that can still be read; this refuses the whole request.
280#[derive(Debug, Clone, PartialEq, Eq)]
281#[non_exhaustive]
282pub enum TemplateError {
283    /// The model cannot be bound to one release, for the reason
284    /// [`exact_schema`](crate::exact_schema) gives: STEP diagnostics, no or
285    /// several `FILE_SCHEMA` entries, or an unsupported one.
286    Release(crate::ExactPropertyError),
287    /// The declared release defines no property templates.
288    ///
289    /// `IfcPropertySetTemplate` and its property templates are new in IFC4;
290    /// IFC2X3 TC1 declares none of them, so nothing in such a file can be a
291    /// template.
292    NoTemplates {
293        /// The release the header declares.
294        schema: ifc_schema::SchemaVersion,
295    },
296    /// The entity is not in the model.
297    MissingEntity {
298        /// The id named by the caller.
299        id: EntityId,
300    },
301    /// The entity is not the kind of template asked for.
302    NotATemplate {
303        /// The entity.
304        id: EntityId,
305        /// Its IFC type name.
306        type_name: String,
307    },
308}
309
310impl std::fmt::Display for TemplateError {
311    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312        match self {
313            Self::Release(error) => write!(f, "{error}"),
314            Self::NoTemplates { schema } => {
315                write!(f, "{schema:?} defines no property templates")
316            }
317            Self::MissingEntity { id } => write!(f, "#{} is not in the model", id.0),
318            Self::NotATemplate { id, type_name } => {
319                write!(f, "#{} is a {type_name}, not the template asked for", id.0)
320            }
321        }
322    }
323}
324
325impl std::error::Error for TemplateError {}
326
327/// A refused authoring request.
328///
329/// Distinct from [`PropertyAnomaly`], which reports what a FILE got wrong.
330/// These say the CALLER asked for something the schema does not allow, and
331/// are returned before anything is staged so a rejected edit never reaches
332/// a transaction.
333#[derive(Debug, Clone, PartialEq, Eq)]
334#[non_exhaustive]
335pub enum PropertyError {
336    /// The entity is not in the model.
337    MissingEntity {
338        /// The id named by the caller.
339        id: EntityId,
340    },
341    /// The entity is not a simple quantity type.
342    NotAQuantity {
343        /// The entity.
344        id: EntityId,
345        /// What it actually is.
346        type_name: String,
347    },
348    /// The entity is not an `IfcElementQuantity`.
349    NotAQuantitySet {
350        /// The entity.
351        id: EntityId,
352        /// What it actually is.
353        type_name: String,
354    },
355    /// An authored attribute value is not valid for its slot.
356    ///
357    /// Raised before staging, so a rejected draft never reaches the model.
358    AuthoringInvalid {
359        /// The entity type being authored.
360        entity: &'static str,
361        /// The attribute that failed.
362        attribute: &'static str,
363        /// The offending value, rendered for the message.
364        value: String,
365    },
366    /// The model's header declares several schemas; authoring binds to
367    /// exactly one release.
368    MultipleSchemas {
369        /// Number of `FILE_SCHEMA` declarations.
370        schemas: usize,
371    },
372    /// The model's header declares one schema with no bundled table, so no
373    /// layout can be trusted.
374    UnsupportedSchema {
375        /// The `FILE_SCHEMA` token as written.
376        schema: String,
377    },
378    /// The model's release does not declare this entity, such as
379    /// `IfcQuantityNumber` (IFC4X3 only) in an IFC2X3 or IFC4 model.
380    EntityNotInSchema {
381        /// The entity type, in schema casing.
382        entity: &'static str,
383        /// The release the model declares.
384        schema: SchemaVersion,
385    },
386    /// An authoring call supplied a value for an attribute the model's
387    /// release does not declare, such as a `Formula` for an IFC2X3
388    /// quantity. It is refused rather than dropped.
389    AuthoringNotInSchema {
390        /// The entity type, in schema casing.
391        entity: &'static str,
392        /// The attribute.
393        attribute: &'static str,
394        /// The release the model declares.
395        schema: SchemaVersion,
396    },
397    /// The record to edit does not have the attribute count its release
398    /// declares, so no slot in it can be trusted.
399    MalformedEntitySlots {
400        /// The record.
401        id: EntityId,
402        /// Its type.
403        type_name: String,
404        /// Attribute count the release declares.
405        expected: usize,
406        /// Attribute count the record has.
407        actual: usize,
408    },
409    /// The model's release requires an attribute the authoring call leaves
410    /// unset, such as the IFC2X3 `IfcRoot.OwnerHistory` (#191). It is refused
411    /// rather than written as `$`; the `*_with_owner_history` writers take
412    /// the `IfcOwnerHistory` IFC2X3 needs.
413    //
414    // Last, so no earlier variant's implicit discriminant moves.
415    AuthoringRequired {
416        /// The entity type being authored.
417        entity: &'static str,
418        /// The required attribute, as the release names it.
419        attribute: &'static str,
420        /// The release the model declares.
421        schema: SchemaVersion,
422    },
423    /// A value of the declared type in the form ISO 10303-21 does not use
424    /// for it (#215).
425    ///
426    /// A typed parameter (`IFCLENGTHMEASURE(2.5)`) is written exactly where
427    /// the declared type is a SELECT, so a bare value in an `IfcValue` slot
428    /// cannot say which member it is (§12.1.8); a member's own parameter is
429    /// written bare (§12.1.6). Mirrors `ifc-author`'s `AuthorError::ValueForm`.
430    /// A value that is no member of the declared type at all is
431    /// [`AuthoringInvalid`](Self::AuthoringInvalid) instead.
432    //
433    // Last, so no earlier variant's implicit discriminant moves.
434    ValueForm {
435        /// The entity type being authored.
436        entity: &'static str,
437        /// The attribute that was set.
438        attribute: &'static str,
439        /// The declared type, or the element type of a declared aggregate,
440        /// e.g. `IfcValue`.
441        declared: &'static str,
442        /// Whether the declared type requires the typed form: `true` for a
443        /// bare value in a SELECT slot, `false` for a wrapper where a bare
444        /// value is written.
445        typed_required: bool,
446        /// What the supplied value actually was.
447        found: String,
448    },
449}
450
451impl std::fmt::Display for PropertyError {
452    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453        match self {
454            Self::MissingEntity { id } => write!(f, "#{} is not in the model", id.0),
455            Self::NotAQuantity { id, type_name } => {
456                write!(f, "#{} is a {type_name}, not a simple quantity", id.0)
457            }
458            Self::NotAQuantitySet { id, type_name } => {
459                write!(f, "#{} is a {type_name}, not an IfcElementQuantity", id.0)
460            }
461            Self::AuthoringInvalid {
462                entity,
463                attribute,
464                value,
465            } => write!(
466                f,
467                "{entity}.{attribute} rejected the authored value: {value}"
468            ),
469            Self::MultipleSchemas { schemas } => write!(
470                f,
471                "the header declares {schemas} schemas; authoring binds to exactly one"
472            ),
473            Self::UnsupportedSchema { schema } => {
474                write!(
475                    f,
476                    "the header declares {schema}, which has no bundled table"
477                )
478            }
479            Self::EntityNotInSchema { entity, schema } => {
480                write!(f, "{entity} is not an entity of {schema:?}")
481            }
482            Self::AuthoringNotInSchema {
483                entity,
484                attribute,
485                schema,
486            } => write!(
487                f,
488                "cannot author {entity}.{attribute}: not defined by {schema:?}"
489            ),
490            Self::AuthoringRequired {
491                entity,
492                attribute,
493                schema,
494            } => write!(f, "cannot author {entity}: {schema:?} requires {attribute}"),
495            Self::ValueForm {
496                entity,
497                attribute,
498                declared,
499                typed_required: true,
500                found,
501            } => write!(
502                f,
503                "{entity}.{attribute} is declared {declared}, a SELECT, so a value must be \
504                 written as a typed parameter naming its type; found {found}"
505            ),
506            Self::ValueForm {
507                entity,
508                attribute,
509                declared,
510                typed_required: false,
511                found,
512            } => write!(
513                f,
514                "{entity}.{attribute} is declared {declared}, whose member's parameter is \
515                 written bare; found {found}"
516            ),
517            Self::MalformedEntitySlots {
518                id,
519                type_name,
520                expected,
521                actual,
522            } => write!(
523                f,
524                "#{} {type_name} has {actual} attributes; its release declares {expected}",
525                id.0
526            ),
527        }
528    }
529}
530
531/// Result alias for authoring and reading helpers in this crate.
532pub type PropertyResult<T> = Result<T, PropertyError>;
533
534impl std::error::Error for PropertyError {}