Skip to main content

ifc_alignment/
error.rs

1//! Structured alignment interpretation failures.
2
3use ifc_model::EntityId;
4
5/// Why an IFC alignment entity could not be read or lowered.
6#[non_exhaustive]
7#[derive(Debug, Clone, PartialEq)]
8pub enum AlignmentError {
9    /// A referenced entity id is not present in the model.
10    MissingEntity {
11        /// The id that resolved to nothing.
12        entity: EntityId,
13    },
14    /// An entity was not the IFC type the referencing slot requires.
15    WrongType {
16        /// The entity that was read.
17        entity: EntityId,
18        /// The IFC type the slot requires.
19        expected: &'static str,
20        /// The IFC type actually declared.
21        actual: String,
22    },
23    /// A mandatory attribute was absent, so the value cannot be inferred.
24    MissingAttribute {
25        /// The entity that was read.
26        entity: EntityId,
27        /// Zero-based slot index of the absent attribute.
28        index: usize,
29        /// Schema name of the attribute.
30        name: &'static str,
31    },
32    /// An attribute was present but held the wrong kind of value.
33    InvalidAttribute {
34        /// The entity that was read.
35        entity: EntityId,
36        /// Zero-based slot index of the offending attribute.
37        index: usize,
38        /// Schema name of the attribute.
39        name: &'static str,
40    },
41    /// The project's unit assignment does not resolve to usable lengths or angles.
42    InvalidUnits {
43        /// What expectation failed.
44        detail: &'static str,
45    },
46    /// An angle attribute was read, and the project declares no `PLANEANGLEUNIT`.
47    AngleUnitUndeclared {
48        /// The entity holding the angle.
49        entity: EntityId,
50    },
51    /// A horizontal, vertical, or cant segment carries internally inconsistent data.
52    InvalidSegment {
53        /// The segment entity.
54        entity: EntityId,
55        /// What expectation failed.
56        detail: &'static str,
57    },
58    /// A segment type or configuration this crate deliberately does not lower.
59    ///
60    /// Covers segment kinds that are legal IFC but lack the data they need in
61    /// this call (e.g. a `VIENNESEBEND` lowered without its `IfcAlignmentCant`
62    /// layout, its `GravityCenterLineHeight`, or the station a chained layout
63    /// supplies) or that have no closed-form neutral curve here (e.g.
64    /// `CUBIC`).
65    Unsupported {
66        /// The unsupported entity.
67        entity: EntityId,
68        /// The IFC type or `PredefinedType` name actually declared.
69        type_name: String,
70        /// Why it is refused rather than approximated.
71        detail: &'static str,
72    },
73    /// The assembled neutral alignment graph violates a structural invariant.
74    Graph {
75        /// What expectation failed.
76        detail: String,
77    },
78    /// The model header declares no `FILE_SCHEMA` token.
79    MissingSchema,
80    /// More than one `FILE_SCHEMA` token was declared.
81    AmbiguousSchema {
82        /// Every schema token found in the header.
83        tokens: Vec<String>,
84    },
85    /// The declared schema is not one this crate can interpret.
86    ///
87    /// Alignment entities (`IfcAlignment*`) were introduced in IFC4X3; IFC2X3
88    /// and IFC4 ADD2 TC1 do not declare them at all, so there is no version
89    /// dispatch here the way `ifc-resource`/`ifc-structural` have one --
90    /// exactly one profile is authoritative and anything else is refused.
91    UnsupportedSchema {
92        /// The rejected schema token.
93        token: String,
94    },
95    /// A relationship or nesting structure violates a stated invariant.
96    SemanticViolation {
97        /// The offending entity, when one could be identified.
98        entity: Option<EntityId>,
99        /// The invariant that was violated.
100        rule: &'static str,
101    },
102    /// An authored value was rejected before anything was staged (ADR 0011).
103    ///
104    /// Distinct from [`Self::InvalidSegment`], which describes a segment that
105    /// already exists in a file. Here there is no entity yet and therefore no
106    /// id to report: the caller passed a value that could not be written.
107    InvalidAuthoredValue {
108        /// The IFC type being authored.
109        type_name: &'static str,
110        /// The attribute whose value was rejected.
111        attribute: &'static str,
112        /// Why it cannot be written.
113        detail: String,
114    },
115    /// Two consecutive vertical segments disagree where they meet.
116    ///
117    /// The segment at `entity` restates a start height that differs from
118    /// where `previous` ends, beyond the seam tolerance: a step, refused
119    /// rather than joined because joining it would shift every downstream
120    /// height. A grade break at a height-continuous seam is legal IFC4.3 and
121    /// is reported as [`ProfileSeam::Gradient`] only when tangency is asked
122    /// for explicitly (`VerticalLayout::require_tangential`).
123    ProfileDiscontinuity {
124        /// The segment whose start disagrees.
125        entity: EntityId,
126        /// The segment it follows.
127        previous: EntityId,
128        /// Which quantity is discontinuous.
129        seam: ProfileSeam,
130        /// The previous segment's end value, in SI units.
131        expected: f64,
132        /// This segment's authored start value, in SI units.
133        actual: f64,
134    },
135    /// A dangling reference: the target id is not present in the model.
136    DanglingReference {
137        /// The entity holding the dangling reference.
138        entity: EntityId,
139        /// The attribute that names the missing target.
140        attribute: &'static str,
141        /// The id that resolved to nothing.
142        target: EntityId,
143    },
144    /// A distance along or a station value outside the range a mapping
145    /// covers, such as a distance before an alignment's first stationing
146    /// referent.
147    OutOfRange {
148        /// The entity whose mapping was queried (the `IfcAlignment` for
149        /// stationing).
150        entity: EntityId,
151        /// Which quantity was out of range.
152        quantity: &'static str,
153        /// The value queried, in SI units.
154        value: f64,
155    },
156    /// A station value that labels more than one distance along, as after
157    /// a station equation that steps back. Picking one would be a guess.
158    AmbiguousStation {
159        /// The `IfcAlignment` whose stationing was queried.
160        alignment: EntityId,
161        /// The station value queried, in metres.
162        station: f64,
163        /// Every distance along it labels, ascending, in metres.
164        distances: Vec<f64>,
165    },
166    /// Graph traversal exceeded an explicit depth or node-count bound.
167    BudgetExceeded {
168        /// The configured maximum traversal depth.
169        max_depth: usize,
170        /// The configured maximum node count.
171        max_nodes: usize,
172    },
173}
174
175/// Which quantity of a vertical profile breaks at a seam.
176#[non_exhaustive]
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178pub enum ProfileSeam {
179    /// `StartHeight` differs from the previous segment's end height: a step.
180    Height,
181    /// `StartGradient` differs from the previous `EndGradient`: a grade
182    /// break. Legal IFC4.3; produced only by an explicit tangency request
183    /// (`VerticalLayout::require_tangential`), never by reading or lowering
184    /// a profile.
185    Gradient,
186}
187
188impl std::fmt::Display for ProfileSeam {
189    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190        f.write_str(match self {
191            Self::Height => "height",
192            Self::Gradient => "gradient",
193        })
194    }
195}
196
197/// Result of an alignment read, carrying [`AlignmentError`] on failure.
198pub type AlignmentResult<T> = Result<T, AlignmentError>;
199
200impl std::fmt::Display for AlignmentError {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        match self {
203            Self::MissingEntity { entity } => write!(f, "missing alignment entity {entity}"),
204            Self::WrongType {
205                entity,
206                expected,
207                actual,
208            } => write!(f, "{entity} is {actual}; expected {expected}"),
209            Self::MissingAttribute {
210                entity,
211                index,
212                name,
213            } => write!(f, "{entity} misses {name} at slot {index}"),
214            Self::InvalidAttribute {
215                entity,
216                index,
217                name,
218            } => write!(f, "{entity} has invalid {name} at slot {index}"),
219            Self::InvalidUnits { detail } => write!(f, "invalid alignment units: {detail}"),
220            Self::AngleUnitUndeclared { entity } => write!(
221                f,
222                "{entity} holds a plane angle, and the project declares no PLANEANGLEUNIT"
223            ),
224            Self::InvalidSegment { entity, detail } => {
225                write!(f, "invalid alignment segment {entity}: {detail}")
226            }
227            Self::Unsupported {
228                entity,
229                type_name,
230                detail,
231            } => write!(f, "unsupported {type_name} at {entity}: {detail}"),
232            Self::Graph { detail } => write!(f, "invalid neutral alignment graph: {detail}"),
233            Self::MissingSchema => write!(f, "no FILE_SCHEMA token was declared"),
234            Self::AmbiguousSchema { tokens } => {
235                write!(f, "ambiguous FILE_SCHEMA tokens: {tokens:?}")
236            }
237            Self::UnsupportedSchema { token } => write!(
238                f,
239                "unsupported schema {token}: alignment entities require IFC4X3 ADD2"
240            ),
241            Self::SemanticViolation { entity, rule } => match entity {
242                Some(entity) => write!(f, "{entity} violates {rule}"),
243                None => write!(f, "violates {rule}"),
244            },
245            Self::InvalidAuthoredValue {
246                type_name,
247                attribute,
248                detail,
249            } => write!(f, "cannot author {type_name}.{attribute}: {detail}"),
250            Self::ProfileDiscontinuity {
251                entity,
252                previous,
253                seam,
254                expected,
255                actual,
256            } => write!(
257                f,
258                "vertical {seam} discontinuity at {entity}: starts at {actual}, \
259                 but {previous} ends at {expected}"
260            ),
261            Self::DanglingReference {
262                entity,
263                attribute,
264                target,
265            } => write!(f, "{entity}.{attribute} references missing {target}"),
266            Self::OutOfRange {
267                entity,
268                quantity,
269                value,
270            } => write!(
271                f,
272                "{quantity} {value} lies outside the range {entity} covers"
273            ),
274            Self::AmbiguousStation {
275                alignment,
276                station,
277                distances,
278            } => write!(
279                f,
280                "station {station} of {alignment} labels several distances along: {distances:?}"
281            ),
282            Self::BudgetExceeded {
283                max_depth,
284                max_nodes,
285            } => write!(
286                f,
287                "traversal exceeded bounds (max_depth={max_depth}, max_nodes={max_nodes})"
288            ),
289        }
290    }
291}
292
293impl std::error::Error for AlignmentError {}