Skip to main content

openbim_ifc_binding_core/
error.rs

1//! Errors raised by every binding.
2//!
3//! Each error carries a stable machine-readable [`BindingError::code`] and a
4//! human message. The codes are shared by all hosts (ADR 0013), so a
5//! JavaScript `err.code`, a Python `err.code` and a C status all name the same
6//! failure the same way.
7//!
8//! Every code is therefore part of the public contract of all three
9//! bindings: a code may be added, never renamed or reused for a different
10//! failure. The `tests` module below pins the released set.
11
12use std::fmt;
13
14/// Why a binding call failed.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum BindingError {
17    /// The STEP input could not be parsed.
18    Parse(String),
19    /// The model could not be serialized.
20    Write(String),
21    /// No entity has the given id.
22    MissingEntity(u64),
23    /// A host value did not follow the tagged value encoding.
24    InvalidValue(String),
25    /// An id or index was outside the range the model can represent.
26    OutOfRange(String),
27    /// The file's header names no schema this crate bundles, or (from a
28    /// domain view, #123) a release the view is not verified for, such as
29    /// IFC4X1 for property sets or georeferencing.
30    UnsupportedSchema(String),
31    /// A file could not be opened or read.
32    Io(String),
33    /// No ifcXML XSD profile is named by the given token (only `IFC4` and
34    /// `IFC4X3_ADD2` have one).
35    UnsupportedProfile(String),
36    /// The operation needs a binding feature this build left out, e.g.
37    /// `validate` in a size-trimmed browser package.
38    FeatureDisabled(&'static str),
39    /// A domain view (#123) refused the file's data: it contradicts the
40    /// schema, is ambiguous where the schema allows one answer, or cannot
41    /// prove an exact answer (a lenient read's skipped records). Or an
42    /// authoring batch (#330) would leave the model contradicting the
43    /// schema: a second `IfcProject`, or an object contained, aggregated or
44    /// typed twice.
45    InvalidModel(String),
46    /// A domain view (#123) followed a reference to an entity the file does
47    /// not contain.
48    MissingReference(String),
49    /// A domain view (#123) stopped at its traversal budget: a cycle, or
50    /// nesting deeper than it follows.
51    BudgetExceeded(String),
52    /// A domain view (#123) met a construct it does not interpret, such as
53    /// a coordinate operation with no project-to-map form; refused rather
54    /// than approximated.
55    Unsupported(String),
56    /// A domain query (#123) named an entity of a type the query does not
57    /// accept, such as the property sets of a cartesian point; or a property
58    /// edit named a set type the set does not have.
59    WrongEntityType(String),
60    /// A property edit (#123) wrote a value its template refuses: the
61    /// release's PSD/QTO catalog entry for the set (data type, enumeration,
62    /// form, quantity kind, a property it does not declare), or the
63    /// property's own `IfcPropertyEnumeration`.
64    TemplateViolation(String),
65    /// A property edit (#123) removed a property the object does not state,
66    /// including one it only inherits from its type object.
67    MissingProperty(String),
68    /// A property edit wrote to a `Pset_`/`Qto_` set before the release's
69    /// PSD/QTO catalog was loaded, in a build that loads it at runtime
70    /// (`property-catalog-runtime`, #318). Load it and retry.
71    CatalogNotLoaded(String),
72    /// A by-name attribute access (#326) named no attribute of the
73    /// entity's type in the declared release: neither an explicit one nor,
74    /// for a read, an `INVERSE` one (#462).
75    UnknownAttribute(String),
76    /// A by-name attribute write (#326) named a slot the entity's type
77    /// derives: the file writes it `*` and it holds no value to set.
78    DerivedAttribute(String),
79    /// An authoring batch (#330) left a required attribute of the declared
80    /// release unset, such as IFC2X3's `OwnerHistory`.
81    MissingAttribute(String),
82    /// An authoring batch (#330) removed an entity that an entity other
83    /// than a relationship still references; remove or edit that first.
84    StillReferenced(String),
85    /// A plain host value written by name (#342) does not fit the
86    /// attribute's declared type in the declared release: a string for an
87    /// integer, a name no enumeration item has, a reference to an entity
88    /// of a type the attribute does not accept.
89    TypeMismatch(String),
90    /// A plain host value written by name (#342) fits more than one member
91    /// of the attribute's SELECT, such as a string for `IfcValue`; the
92    /// detail names the candidates. Wrap the value explicitly instead.
93    AmbiguousValue(String),
94    /// A selector or value path (#464) does not follow the grammar, or
95    /// names a class or attribute the declared release does not declare.
96    InvalidSelector {
97        /// What is wrong.
98        detail: String,
99        /// The byte range of the offending text in the UTF-8 query.
100        span: (usize, usize),
101    },
102    /// A by-name attribute write (#462) named an `INVERSE` attribute of the
103    /// entity's type: it holds no slot; write the referencing attribute.
104    InverseAttribute(String),
105    /// EXPRESS rule text (#538) that does not fit the model's declared
106    /// release: it declares another schema, or disagrees with the release's
107    /// tables about an entity's attributes.
108    ExpressMismatch(String),
109    /// EXPRESS rule text (#538) that does not parse, or whose rules use a
110    /// name that binds to nothing.
111    InvalidExpress(String),
112    /// An undo or redo (#465) with nothing to step through: history is off
113    /// (limit `0`), or that stack is empty.
114    HistoryEmpty(String),
115    /// An undo or redo (#465) after the model changed outside the history;
116    /// the held entries no longer describe it, so nothing was changed.
117    HistoryStale(String),
118}
119
120impl BindingError {
121    /// Stable code for programmatic handling.
122    pub const fn code(&self) -> &'static str {
123        match self {
124            Self::Parse(_) => "parse",
125            Self::Write(_) => "write",
126            Self::MissingEntity(_) => "missing-entity",
127            Self::InvalidValue(_) => "invalid-value",
128            Self::OutOfRange(_) => "out-of-range",
129            Self::UnsupportedSchema(_) => "unsupported-schema",
130            Self::Io(_) => "io",
131            Self::UnsupportedProfile(_) => "unsupported-profile",
132            Self::FeatureDisabled(_) => "feature-disabled",
133            Self::InvalidModel(_) => "invalid-model",
134            Self::MissingReference(_) => "missing-reference",
135            Self::BudgetExceeded(_) => "budget-exceeded",
136            Self::Unsupported(_) => "unsupported",
137            Self::WrongEntityType(_) => "wrong-entity-type",
138            Self::TemplateViolation(_) => "template-violation",
139            Self::MissingProperty(_) => "missing-property",
140            Self::CatalogNotLoaded(_) => "catalog-not-loaded",
141            Self::UnknownAttribute(_) => "unknown-attribute",
142            Self::DerivedAttribute(_) => "derived-attribute",
143            Self::MissingAttribute(_) => "missing-attribute",
144            Self::StillReferenced(_) => "still-referenced",
145            Self::TypeMismatch(_) => "type-mismatch",
146            Self::AmbiguousValue(_) => "ambiguous-value",
147            Self::InverseAttribute(_) => "inverse-attribute",
148            Self::InvalidSelector { .. } => "invalid-selector",
149            Self::ExpressMismatch(_) => "express-mismatch",
150            Self::InvalidExpress(_) => "invalid-express",
151            Self::HistoryEmpty(_) => "history-empty",
152            Self::HistoryStale(_) => "history-stale",
153        }
154    }
155
156    /// The byte range in the query an `invalid-selector` refusal names.
157    pub const fn span(&self) -> Option<(usize, usize)> {
158        match self {
159            Self::InvalidSelector { span, .. } => Some(*span),
160            _ => None,
161        }
162    }
163}
164
165impl fmt::Display for BindingError {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        match self {
168            // The detail names its format: `STEP: ...` or `ifcXML: ...`.
169            Self::Parse(detail) => write!(f, "cannot parse {detail}"),
170            Self::Write(detail) => write!(f, "cannot write {detail}"),
171            Self::MissingEntity(id) => write!(f, "no entity #{id}"),
172            Self::InvalidValue(detail) => write!(f, "invalid IFC value: {detail}"),
173            Self::OutOfRange(detail) => write!(f, "out of range: {detail}"),
174            // The detail is the header token, or names why it is refused:
175            // not bundled in this build, or not read by a domain view.
176            Self::UnsupportedSchema(detail) => write!(f, "unsupported schema: {detail:?}"),
177            Self::Io(detail) => write!(f, "cannot read file: {detail}"),
178            Self::UnsupportedProfile(token) => write!(
179                f,
180                "no ifcXML XSD profile for {token:?} (IFC4 or IFC4X3_ADD2)"
181            ),
182            Self::FeatureDisabled(feature) => {
183                write!(f, "this build leaves out the `{feature}` feature")
184            }
185            Self::InvalidModel(detail) => write!(f, "invalid model: {detail}"),
186            Self::MissingReference(detail) => write!(f, "missing reference: {detail}"),
187            Self::BudgetExceeded(detail) => write!(f, "budget exceeded: {detail}"),
188            Self::Unsupported(detail) => write!(f, "unsupported: {detail}"),
189            Self::WrongEntityType(detail) => write!(f, "wrong entity type: {detail}"),
190            Self::TemplateViolation(detail) => write!(f, "template violation: {detail}"),
191            Self::MissingProperty(detail) => write!(f, "missing property: {detail}"),
192            Self::CatalogNotLoaded(detail) => write!(
193                f,
194                "catalog not loaded: {detail}; load the release's catalog first \
195                 (JavaScript: `await IfcModel.loadCatalog(release)`)"
196            ),
197            Self::UnknownAttribute(detail) => write!(f, "unknown attribute: {detail}"),
198            Self::DerivedAttribute(detail) => write!(f, "derived attribute: {detail}"),
199            Self::MissingAttribute(detail) => write!(f, "missing attribute: {detail}"),
200            Self::StillReferenced(detail) => write!(f, "still referenced: {detail}"),
201            Self::TypeMismatch(detail) => write!(f, "type mismatch: {detail}"),
202            Self::AmbiguousValue(detail) => write!(
203                f,
204                "ambiguous value: {detail}; pass an explicit typed value instead"
205            ),
206            Self::InvalidSelector { detail, span } => write!(
207                f,
208                "invalid selector: {detail} at bytes {}..{}",
209                span.0, span.1
210            ),
211            Self::InverseAttribute(detail) => write!(f, "inverse attribute: {detail}"),
212            Self::ExpressMismatch(detail) => write!(f, "EXPRESS mismatch: {detail}"),
213            Self::InvalidExpress(detail) => write!(f, "invalid EXPRESS: {detail}"),
214            Self::HistoryEmpty(detail) => write!(f, "history empty: {detail}"),
215            Self::HistoryStale(detail) => write!(f, "history stale: {detail}"),
216        }
217    }
218}
219
220impl std::error::Error for BindingError {}
221
222#[cfg(test)]
223mod tests {
224    use std::collections::BTreeSet;
225
226    use super::BindingError;
227
228    /// Released codes in declaration order. Append a new code; never edit or
229    /// remove one, because hosts match on these strings.
230    const RELEASED_CODES: &[&str] = &[
231        "parse",
232        "write",
233        "missing-entity",
234        "invalid-value",
235        "out-of-range",
236        "unsupported-schema",
237        "io",
238        "unsupported-profile",
239        "feature-disabled",
240        "invalid-model",
241        "missing-reference",
242        "budget-exceeded",
243        "unsupported",
244        "wrong-entity-type",
245        "template-violation",
246        "missing-property",
247        "catalog-not-loaded",
248        "unknown-attribute",
249        "derived-attribute",
250        "missing-attribute",
251        "still-referenced",
252        "type-mismatch",
253        "ambiguous-value",
254        "invalid-selector",
255        "inverse-attribute",
256        "express-mismatch",
257        "invalid-express",
258        "history-empty",
259        "history-stale",
260    ];
261
262    /// One value of every variant, in declaration order.
263    fn one_of_each() -> Vec<BindingError> {
264        let all = vec![
265            BindingError::Parse(String::new()),
266            BindingError::Write(String::new()),
267            BindingError::MissingEntity(0),
268            BindingError::InvalidValue(String::new()),
269            BindingError::OutOfRange(String::new()),
270            BindingError::UnsupportedSchema(String::new()),
271            BindingError::Io(String::new()),
272            BindingError::UnsupportedProfile(String::new()),
273            BindingError::FeatureDisabled(""),
274            BindingError::InvalidModel(String::new()),
275            BindingError::MissingReference(String::new()),
276            BindingError::BudgetExceeded(String::new()),
277            BindingError::Unsupported(String::new()),
278            BindingError::WrongEntityType(String::new()),
279            BindingError::TemplateViolation(String::new()),
280            BindingError::MissingProperty(String::new()),
281            BindingError::CatalogNotLoaded(String::new()),
282            BindingError::UnknownAttribute(String::new()),
283            BindingError::DerivedAttribute(String::new()),
284            BindingError::MissingAttribute(String::new()),
285            BindingError::StillReferenced(String::new()),
286            BindingError::TypeMismatch(String::new()),
287            BindingError::AmbiguousValue(String::new()),
288            BindingError::InvalidSelector {
289                detail: String::new(),
290                span: (0, 0),
291            },
292            BindingError::InverseAttribute(String::new()),
293            BindingError::ExpressMismatch(String::new()),
294            BindingError::InvalidExpress(String::new()),
295            BindingError::HistoryEmpty(String::new()),
296            BindingError::HistoryStale(String::new()),
297        ];
298        // Exhaustive on purpose: a new variant does not compile until it is
299        // listed above, so its code cannot escape the snapshot.
300        for error in &all {
301            match error {
302                BindingError::Parse(_)
303                | BindingError::Write(_)
304                | BindingError::MissingEntity(_)
305                | BindingError::InvalidValue(_)
306                | BindingError::OutOfRange(_)
307                | BindingError::UnsupportedSchema(_)
308                | BindingError::Io(_)
309                | BindingError::UnsupportedProfile(_)
310                | BindingError::FeatureDisabled(_)
311                | BindingError::InvalidModel(_)
312                | BindingError::MissingReference(_)
313                | BindingError::BudgetExceeded(_)
314                | BindingError::Unsupported(_)
315                | BindingError::WrongEntityType(_)
316                | BindingError::TemplateViolation(_)
317                | BindingError::MissingProperty(_)
318                | BindingError::CatalogNotLoaded(_)
319                | BindingError::UnknownAttribute(_)
320                | BindingError::DerivedAttribute(_)
321                | BindingError::MissingAttribute(_)
322                | BindingError::StillReferenced(_)
323                | BindingError::TypeMismatch(_)
324                | BindingError::AmbiguousValue(_)
325                | BindingError::InvalidSelector { .. }
326                | BindingError::InverseAttribute(_)
327                | BindingError::ExpressMismatch(_)
328                | BindingError::InvalidExpress(_)
329                | BindingError::HistoryEmpty(_)
330                | BindingError::HistoryStale(_) => {}
331            }
332        }
333        all
334    }
335
336    #[test]
337    fn released_codes_are_never_renamed_or_reused() {
338        let codes: Vec<&str> = one_of_each().iter().map(BindingError::code).collect();
339        assert!(
340            codes.len() >= RELEASED_CODES.len(),
341            "a BindingError variant was removed: {codes:?}"
342        );
343        assert_eq!(
344            &codes[..RELEASED_CODES.len()],
345            RELEASED_CODES,
346            "a released BindingError code changed; add a new code instead"
347        );
348        let unique: BTreeSet<&str> = codes.iter().copied().collect();
349        assert_eq!(
350            unique.len(),
351            codes.len(),
352            "two variants share a code: {codes:?}"
353        );
354    }
355}