Skip to main content

ifc_step/
error.rs

1//! Why a STEP parse failed at the IFC adapter boundary.
2
3use std::fmt;
4
5use ifc_model::{EntityId, ModelError};
6
7use crate::SyntaxLocation;
8use thiserror::Error;
9
10/// Failures specific to reading or writing IFC STEP text.
11#[derive(Debug, Clone, Error)]
12#[non_exhaustive]
13pub enum StepError {
14    /// The bytes do not begin with the ISO-10303-21 magic.
15    #[error("not a STEP physical file: {0}")]
16    NotStep(String),
17
18    /// Malformed syntax at a known byte offset.
19    #[error("syntax error at byte {offset}: {detail}")]
20    Syntax {
21        /// Byte offset into the source.
22        offset: usize,
23        /// What went wrong.
24        detail: String,
25    },
26
27    /// A record in the DATA section had no `#id=` prefix.
28    #[error("entity record without an id at byte {offset}")]
29    MissingEntityId {
30        /// Byte offset into the source.
31        offset: usize,
32    },
33
34    /// A REAL token has no decimal point (`1E-05`).
35    ///
36    /// ISO 10303-21 requires the point, so a strict read refuses the token.
37    /// A lenient read ([`crate::StepCodec::lenient`]) reads it as the REAL
38    /// it spells and reports a diagnostic.
39    #[error("syntax error at byte {offset}: REAL `{token}` has no decimal point (ISO 10303-21 requires one)")]
40    RealWithoutDecimalPoint {
41        /// Byte offset of the token in the source.
42        offset: usize,
43        /// The token as written.
44        token: String,
45    },
46
47    /// Two records of the DATA section share one instance id.
48    ///
49    /// A strict read refuses the file, because an id that names two records
50    /// is ambiguous. A lenient read ([`crate::StepCodec::lenient`]) keeps the
51    /// later record and reports a `DuplicateId` diagnostic naming the id.
52    #[error("duplicate instance id {id} at byte {offset}")]
53    DuplicateId {
54        /// The id both records carry.
55        id: EntityId,
56        /// Byte offset of the later record in the source.
57        offset: usize,
58    },
59
60    /// The model contains a REAL value Part 21 cannot represent.
61    #[error("entity #{entity} slot {slot} contains a non-finite REAL")]
62    NonFiniteReal {
63        /// Entity containing the value.
64        entity: EntityId,
65        /// Top-level positional attribute containing the value.
66        slot: usize,
67    },
68
69    /// Underlying I/O failure.
70    #[error("io error: {0}")]
71    Io(String),
72}
73
74impl StepError {
75    /// Maps an `openbim-step` failure over `input` onto this crate's error.
76    ///
77    /// The substrate refuses a REAL without its decimal point with a typed
78    /// error whose span covers exactly the number; with the source at hand,
79    /// that becomes [`StepError::RealWithoutDecimalPoint`] naming the token
80    /// as written. Every other failure maps as [`From`] does.
81    pub(crate) fn from_step(input: &[u8], error: openbim_step::StepError) -> Self {
82        if error.is_real_without_point() {
83            let span = error.span();
84            if let Some(token) = input.get(span.start..span.end) {
85                return Self::RealWithoutDecimalPoint {
86                    offset: span.start,
87                    token: String::from_utf8_lossy(token).into_owned(),
88                };
89            }
90        }
91        error.into()
92    }
93}
94
95/// Without the source bytes the token cannot be quoted, so a REAL without
96/// its decimal point maps to [`StepError::Syntax`] at the token's offset,
97/// with the substrate's detail, which names the token.
98impl From<openbim_step::StepError> for StepError {
99    fn from(error: openbim_step::StepError) -> Self {
100        if error.is_not_step() {
101            Self::NotStep(error.detail().to_owned())
102        } else {
103            Self::Syntax {
104                offset: error.span().start,
105                detail: error.detail().to_owned(),
106            }
107        }
108    }
109}
110
111impl From<StepError> for ModelError {
112    fn from(error: StepError) -> Self {
113        match error {
114            StepError::NotStep(detail) => ModelError::WrongFormat {
115                expected: "STEP",
116                detail,
117            },
118            StepError::Syntax { offset, detail } => ModelError::Syntax { offset, detail },
119            StepError::MissingEntityId { offset } => ModelError::Syntax {
120                offset,
121                detail: "entity record without an id".into(),
122            },
123            StepError::RealWithoutDecimalPoint { offset, token } => ModelError::Syntax {
124                offset,
125                detail: format!(
126                    "REAL `{token}` has no decimal point (ISO 10303-21 requires one; \
127                     a lenient read accepts it)"
128                ),
129            },
130            StepError::DuplicateId { id, .. } => ModelError::DuplicateId(id),
131            StepError::NonFiniteReal { entity, slot } => ModelError::Write(format!(
132                "entity #{entity} slot {slot} contains a non-finite REAL"
133            )),
134            StepError::Io(message) => ModelError::Io(message),
135        }
136    }
137}
138
139/// A refused read, with the input it refused handed back.
140///
141/// `try_read_owned` takes the buffer; on failure the caller gets it back
142/// uncopied, so it can locate the error in it or read it again under another
143/// policy.
144#[derive(Clone)]
145#[non_exhaustive]
146pub struct ReadFailure {
147    /// Why the read failed.
148    pub error: ModelError,
149    /// The input, as it was passed in.
150    pub bytes: Vec<u8>,
151}
152
153impl ReadFailure {
154    /// Where in [`ReadFailure::bytes`] the error is, for a syntax error.
155    #[must_use]
156    pub fn location(&self) -> Option<SyntaxLocation> {
157        SyntaxLocation::locate(&self.bytes, &self.error)
158    }
159}
160
161impl fmt::Debug for ReadFailure {
162    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
163        formatter
164            .debug_struct("ReadFailure")
165            .field("error", &self.error)
166            .field("bytes", &format_args!("<{} bytes>", self.bytes.len()))
167            .finish()
168    }
169}
170
171impl fmt::Display for ReadFailure {
172    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
173        self.error.fmt(formatter)
174    }
175}
176
177impl std::error::Error for ReadFailure {
178    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
179        self.error.source()
180    }
181}
182
183impl From<ReadFailure> for ModelError {
184    fn from(failure: ReadFailure) -> Self {
185        failure.error
186    }
187}