Skip to main content

ifc_geometry/
error.rs

1//! Why interpreting a geometry entity failed.
2//!
3//! Every failure names the entity that caused it. A geometry bug in a
4//! 500k-entity file is unfindable otherwise, and "returned None" tells you
5//! nothing about which of 3,000 walls was malformed.
6
7use ifc_model::EntityId;
8use thiserror::Error;
9
10/// The result of interpreting IFC geometry.
11pub type GeometryResult<T> = Result<T, GeometryError>;
12
13/// Failures when reading or lowering IFC geometry.
14#[derive(Debug, Clone, PartialEq, Error)]
15#[non_exhaustive]
16pub enum GeometryError {
17    /// An entity referenced by an attribute is not in the model.
18    #[error("{referrer} references missing entity {missing}")]
19    MissingEntity {
20        /// The entity holding the dangling reference.
21        referrer: EntityId,
22        /// The id that does not resolve.
23        missing: EntityId,
24    },
25
26    /// An attribute slot was empty but the geometry needs it.
27    #[error("{entity} ({type_name}) has no {attribute}")]
28    MissingAttribute {
29        /// The offending entity.
30        entity: EntityId,
31        /// Its IFC type.
32        type_name: String,
33        /// Which attribute was required.
34        attribute: &'static str,
35    },
36
37    /// An attribute held a value of the wrong shape.
38    #[error("{entity} ({type_name}).{attribute}: expected {expected}, found {found}")]
39    WrongValueKind {
40        /// The offending entity.
41        entity: EntityId,
42        /// Its IFC type.
43        type_name: String,
44        /// Which attribute.
45        attribute: &'static str,
46        /// What the schema requires.
47        expected: &'static str,
48        /// What the file actually contains.
49        found: String,
50    },
51
52    /// The entity is not the type the caller assumed.
53    #[error("{entity} is {actual}, not a {expected}")]
54    WrongEntityType {
55        /// The offending entity.
56        entity: EntityId,
57        /// The type it actually has.
58        actual: String,
59        /// The type family that was required.
60        expected: &'static str,
61    },
62
63    /// A recognized IFC entity whose interpretation is not implemented.
64    ///
65    /// Distinct from [`Self::WrongEntityType`]: the file is valid and we simply
66    /// do not handle it yet. Never silently substituted with a wrong shape.
67    #[error("{type_name} ({entity}) is valid IFC but not yet interpreted: {detail}")]
68    Unsupported {
69        /// The entity in question.
70        entity: EntityId,
71        /// Its IFC type.
72        type_name: String,
73        /// What specifically is missing.
74        detail: &'static str,
75    },
76
77    /// A placement or mapped-item chain refers back to itself.
78    ///
79    /// The IFC spec pushes cycle prevention to the application layer, so real
80    /// files do contain them. Detecting beats overflowing the stack.
81    #[error("cyclic {kind} chain through {entity}")]
82    CyclicChain {
83        /// Where the cycle was detected.
84        entity: EntityId,
85        /// What kind of chain: `placement`, `mapped item`, ...
86        kind: &'static str,
87    },
88
89    /// A chain exceeded its depth limit without closing.
90    #[error("{kind} chain through {entity} exceeded depth {limit}")]
91    ChainTooDeep {
92        /// Where the walk gave up.
93        entity: EntityId,
94        /// What kind of chain.
95        kind: &'static str,
96        /// The limit that was hit.
97        limit: usize,
98    },
99
100    /// An aggregate declared more elements than the caller's budget allows.
101    ///
102    /// IFC aggregate counts are file-controlled, so a small hostile file can
103    /// declare an enormous element count and drive a large allocation before
104    /// any geometric validation runs. This is that budget refusing, and it is
105    /// always a refusal: nothing is truncated to fit.
106    #[error("{entity} ({type_name}) declares {requested} {what}, over the limit of {limit}")]
107    AggregateTooLarge {
108        /// The offending entity.
109        entity: EntityId,
110        /// Its IFC type.
111        type_name: String,
112        /// What was being counted: `knot multiplicities`, `triangle indices`.
113        what: &'static str,
114        /// How many elements the file asked for.
115        requested: u128,
116        /// The budget that refused it.
117        limit: usize,
118    },
119
120    /// A lowered product reached the mesh compiler, which refused it.
121    ///
122    /// Distinct from [`Self::Unsupported`]: lowering succeeded and the neutral
123    /// DAG is valid IFC meaning. What failed is *execution* -- a provider that
124    /// cannot evaluate this operation, or a budget that will not fund it. The
125    /// compiler's own reason is preserved verbatim, because it names the
126    /// missing capability precisely enough for a caller to register a provider
127    /// for it. Only reachable with the `compile` feature.
128    #[cfg(feature = "compile")]
129    #[error("{entity} could not be compiled to a mesh: {reason}")]
130    CompilationRefused {
131        /// The product whose body representation was being compiled.
132        entity: EntityId,
133        /// The compiler's refusal, as reported by the provider.
134        reason: String,
135    },
136
137    /// The geometry is structurally impossible.
138    ///
139    /// A degenerate direction, a zero-radius circle, a self-referencing
140    /// boolean. The file parses; the geometry does not exist.
141    #[error("{entity} ({type_name}) is geometrically invalid: {detail}")]
142    Degenerate {
143        /// The offending entity.
144        entity: EntityId,
145        /// Its IFC type.
146        type_name: String,
147        /// Why it cannot be built.
148        detail: String,
149    },
150
151    /// Units could not be resolved, so coordinates have no defined scale.
152    #[error("unit resolution failed: {0}")]
153    Units(String),
154
155    /// An authored value was rejected before anything was staged (ADR 0011).
156    ///
157    /// Distinct from [`Self::Degenerate`], which describes an entity that
158    /// already exists in a file. Here there is no entity yet and therefore no
159    /// id to report: the caller passed a value that could not be written.
160    #[error("cannot author {type_name}.{attribute}: {detail}")]
161    InvalidAuthoredValue {
162        /// The IFC type being authored.
163        type_name: &'static str,
164        /// The attribute whose value was rejected.
165        attribute: &'static str,
166        /// Why it cannot be written.
167        detail: String,
168    },
169}
170
171impl GeometryError {
172    /// The entity this error is about, when there is one.
173    ///
174    /// Lets a caller collect failures per element rather than aborting a whole
175    /// file for one bad wall.
176    pub fn entity(&self) -> Option<EntityId> {
177        match self {
178            Self::MissingEntity { referrer, .. } => Some(*referrer),
179            Self::MissingAttribute { entity, .. }
180            | Self::WrongValueKind { entity, .. }
181            | Self::WrongEntityType { entity, .. }
182            | Self::Unsupported { entity, .. }
183            | Self::CyclicChain { entity, .. }
184            | Self::ChainTooDeep { entity, .. }
185            | Self::AggregateTooLarge { entity, .. }
186            | Self::Degenerate { entity, .. } => Some(*entity),
187            #[cfg(feature = "compile")]
188            Self::CompilationRefused { entity, .. } => Some(*entity),
189            Self::Units(_) | Self::InvalidAuthoredValue { .. } => None,
190        }
191    }
192
193    /// Is this "valid IFC we do not handle yet" rather than a broken file?
194    ///
195    /// Callers building a viewer usually want to skip and count these, while
196    /// treating genuine corruption differently.
197    pub fn is_unsupported(&self) -> bool {
198        matches!(self, Self::Unsupported { .. })
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[test]
207    fn errors_name_the_entity_so_failures_are_locatable() {
208        let e = GeometryError::MissingAttribute {
209            entity: EntityId(42),
210            type_name: "IFCEXTRUDEDAREASOLID".into(),
211            attribute: "SweptArea",
212        };
213        assert_eq!(e.entity(), Some(EntityId(42)));
214        assert!(e.to_string().contains("#42"));
215        assert!(e.to_string().contains("SweptArea"));
216    }
217
218    #[test]
219    fn unsupported_is_distinguishable_from_corruption() {
220        let unsupported = GeometryError::Unsupported {
221            entity: EntityId(1),
222            type_name: "IFCSECTIONEDSPINE".into(),
223            detail: "spine interpolation",
224        };
225        let broken = GeometryError::Degenerate {
226            entity: EntityId(1),
227            type_name: "IFCCIRCLE".into(),
228            detail: "zero radius".into(),
229        };
230        assert!(unsupported.is_unsupported());
231        assert!(!broken.is_unsupported());
232    }
233}