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 /// A volume was asked of a product whose compiled body is not a solid.
138 ///
139 /// Raised by `CompiledMesh::solid_mesh` for a surface model
140 /// (`IfcShellBasedSurfaceModel`, `IfcFaceBasedSurfaceModel`) and for a
141 /// backend that does not report closure. A surface has area, not
142 /// volume; reporting the divergence sum of a closed shell the file never
143 /// declared a solid would be a plausible, wrong number.
144 #[cfg(feature = "compile")]
145 #[error("{entity} is not a solid (closure {closure:?}); it has no volume")]
146 NotASolid {
147 /// The product whose body was compiled.
148 entity: EntityId,
149 /// The closure the backend reported: `Surface` or `Unknown`.
150 closure: axiolid_mesh_compile_contract::MeshClosure,
151 },
152
153 /// An opening that voids a host could not be subtracted from it (#44).
154 ///
155 /// Raised only when a caller asked for NET geometry. Returning the gross
156 /// body instead would make every net quantity downstream silently wrong,
157 /// so the host is refused and the opening named. `cause` says why: the
158 /// opening's body did not lower, it has no body, or the kernel refused the
159 /// subtraction.
160 #[error("opening {opening} could not be subtracted from {host}: {cause}")]
161 OpeningNotSubtracted {
162 /// The host whose net geometry was requested.
163 host: EntityId,
164 /// The voiding element that could not be removed.
165 opening: EntityId,
166 /// Why it could not be removed.
167 #[source]
168 cause: Box<GeometryError>,
169 },
170
171 /// The geometry is structurally impossible.
172 ///
173 /// A degenerate direction, a zero-radius circle, a self-referencing
174 /// boolean. The file parses; the geometry does not exist.
175 #[error("{entity} ({type_name}) is geometrically invalid: {detail}")]
176 Degenerate {
177 /// The offending entity.
178 entity: EntityId,
179 /// Its IFC type.
180 type_name: String,
181 /// Why it cannot be built.
182 detail: String,
183 },
184
185 /// Units could not be resolved, so coordinates have no defined scale.
186 #[error("unit resolution failed: {0}")]
187 Units(String),
188
189 /// An authored value was rejected before anything was staged (ADR 0011).
190 ///
191 /// Distinct from [`Self::Degenerate`], which describes an entity that
192 /// already exists in a file. Here there is no entity yet and therefore no
193 /// id to report: the caller passed a value that could not be written.
194 #[error("cannot author {type_name}.{attribute}: {detail}")]
195 InvalidAuthoredValue {
196 /// The IFC type being authored.
197 type_name: &'static str,
198 /// The attribute whose value was rejected.
199 attribute: &'static str,
200 /// Why it cannot be written.
201 detail: String,
202 },
203
204 /// A release-aware writer could not bind one known IFC release from the
205 /// model's `FILE_SCHEMA`: it names an unrecognised release, or several.
206 ///
207 /// A model with no `FILE_SCHEMA` binds IFC4, like the other authoring
208 /// crates. Nothing is staged.
209 #[error("cannot author {type_name}: {detail}")]
210 AuthoringSchemaUnbound {
211 /// The IFC type being authored.
212 type_name: &'static str,
213 /// What the header declares instead of one known release.
214 detail: String,
215 },
216
217 /// The model's declared release does not declare the entity a
218 /// release-aware writer was asked to author. Nothing is staged.
219 #[error("{type_name} is not declared by {schema:?}")]
220 AuthoringEntityNotInSchema {
221 /// The IFC type being authored.
222 type_name: &'static str,
223 /// The bound release.
224 schema: ifc_schema::SchemaVersion,
225 },
226}
227
228impl GeometryError {
229 /// The entity this error is about, when there is one.
230 ///
231 /// Lets a caller collect failures per element rather than aborting a whole
232 /// file for one bad wall.
233 pub fn entity(&self) -> Option<EntityId> {
234 match self {
235 Self::MissingEntity { referrer, .. } => Some(*referrer),
236 Self::MissingAttribute { entity, .. }
237 | Self::WrongValueKind { entity, .. }
238 | Self::WrongEntityType { entity, .. }
239 | Self::Unsupported { entity, .. }
240 | Self::CyclicChain { entity, .. }
241 | Self::ChainTooDeep { entity, .. }
242 | Self::AggregateTooLarge { entity, .. }
243 | Self::Degenerate { entity, .. } => Some(*entity),
244 #[cfg(feature = "compile")]
245 Self::CompilationRefused { entity, .. } => Some(*entity),
246 #[cfg(feature = "compile")]
247 Self::NotASolid { entity, .. } => Some(*entity),
248 // The opening is what failed; `host` stays readable on the variant.
249 Self::OpeningNotSubtracted { opening, .. } => Some(*opening),
250 Self::Units(_)
251 | Self::InvalidAuthoredValue { .. }
252 | Self::AuthoringSchemaUnbound { .. }
253 | Self::AuthoringEntityNotInSchema { .. } => None,
254 }
255 }
256
257 /// Is this "valid IFC we do not handle yet" rather than a broken file?
258 ///
259 /// Callers building a viewer usually want to skip and count these, while
260 /// treating genuine corruption differently.
261 pub fn is_unsupported(&self) -> bool {
262 match self {
263 Self::Unsupported { .. } => true,
264 // A net refusal is as supported as the reason behind it.
265 Self::OpeningNotSubtracted { cause, .. } => cause.is_unsupported(),
266 _ => false,
267 }
268 }
269}
270
271#[cfg(test)]
272mod tests {
273 use super::*;
274
275 #[test]
276 fn errors_name_the_entity_so_failures_are_locatable() {
277 let e = GeometryError::MissingAttribute {
278 entity: EntityId(42),
279 type_name: "IFCEXTRUDEDAREASOLID".into(),
280 attribute: "SweptArea",
281 };
282 assert_eq!(e.entity(), Some(EntityId(42)));
283 assert!(e.to_string().contains("#42"));
284 assert!(e.to_string().contains("SweptArea"));
285 }
286
287 #[test]
288 fn unsupported_is_distinguishable_from_corruption() {
289 let unsupported = GeometryError::Unsupported {
290 entity: EntityId(1),
291 type_name: "IFCSECTIONEDSPINE".into(),
292 detail: "spine interpolation",
293 };
294 let broken = GeometryError::Degenerate {
295 entity: EntityId(1),
296 type_name: "IFCCIRCLE".into(),
297 detail: "zero radius".into(),
298 };
299 assert!(unsupported.is_unsupported());
300 assert!(!broken.is_unsupported());
301 }
302}