Skip to main content

readcon_core/
error.rs

1use std::fmt;
2use std::num::{ParseFloatError, ParseIntError};
3
4#[derive(Debug, Clone)]
5pub enum ParseError {
6    IncompleteHeader,
7    IncompleteFrame,
8    IncompleteVelocitySection,
9    InvalidVectorLength {
10        expected: usize,
11        found: usize,
12    },
13    InvalidNumberFormat(String),
14    MissingSpecVersion,
15    UnsupportedSpecVersion(u32),
16    InvalidMetadataJson(String),
17    IncompleteForceSection,
18    IncompleteEnergySection,
19    /// Declared optional section was incomplete or mislabeled.
20    IncompleteSection(String),
21    UnknownSection(String),
22    ValidationError(String),
23    /// NaN, Inf, Infinity, or a signed or mixed-case spelling, in any mode.
24    /// Clause CON-num.1 (D1).
25    NonFiniteValue(String),
26    /// Column 4 is not a legal integer flag. Clause CON-mask.5 (D8).
27    InvalidFixedFlag(String),
28    /// A count field is not an unsigned integer, or a per-type count is 0
29    /// when the type count is 1 or more. A type count of 0 is legal.
30    /// Clauses CON-count.1 and CON-error.3 (D4).
31    InvalidCount(String),
32    /// A unit expression is missing, mistyped, or the wrong dimension.
33    /// A minor of 1 or later with velocities and no `units.time` is this
34    /// class on read and on write.
35    /// Clauses CON-units.11, CON-units.12, CON-units.13, and CON-units.14 (D11).
36    InvalidUnits(String),
37    /// Unknown major, or JSON `con_spec_version` 0 or 1.
38    /// Clause CON-line2.5 (D15).
39    UnsupportedVersion(u32),
40    /// An in-place builder mutation
41    /// (`ConFrameBuilder::set_atom_position` / `set_atom_velocity` /
42    /// `set_atom_force` / `set_atom_energy` / `set_atom_fixed` /
43    /// `set_atom_mass` / clear_*) was called with an atom index past
44    /// the current length. Surfaces as `IndexError` in PyO3 and as
45    /// `RKR_STATUS_INDEX_OUT_OF_BOUNDS` over the C ABI.
46    IndexOutOfBounds {
47        index: usize,
48        len: usize,
49    },
50    /// Two atoms share a CON type (symbol) but their masses differ
51    /// beyond [`crate::types::ConFrameBuilder::TYPE_MASS_ABS_TOL`].
52    /// CON line 9 stores one mass per type, so the builder cannot
53    /// represent per-atom mass variation inside a type.
54    MassMismatch {
55        symbol: String,
56        first_mass: f64,
57        found_mass: f64,
58        atom_index: usize,
59    },
60    /// A sidecar read failed for a reason other than a missing file.
61    Io(String),
62}
63
64impl fmt::Display for ParseError {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        match self {
67            ParseError::IncompleteHeader => {
68                write!(f, "file ended unexpectedly while parsing frame header")
69            }
70            ParseError::IncompleteFrame => {
71                write!(f, "file ended unexpectedly while reading atom data")
72            }
73            ParseError::IncompleteVelocitySection => {
74                write!(f, "file ended unexpectedly while reading velocity section")
75            }
76            ParseError::InvalidVectorLength { expected, found } => {
77                write!(f, "expected {expected} values on line, found {found}")
78            }
79            ParseError::InvalidNumberFormat(msg) => {
80                write!(f, "invalid number format: {msg}")
81            }
82            ParseError::MissingSpecVersion => {
83                write!(
84                    f,
85                    "line 2 must be a JSON object containing \"con_spec_version\""
86                )
87            }
88            ParseError::UnsupportedSpecVersion(v) | ParseError::UnsupportedVersion(v) => {
89                write!(f, "unsupported con_spec_version: {v}")
90            }
91            ParseError::InvalidMetadataJson(msg) => {
92                write!(f, "invalid JSON metadata on line 2: {msg}")
93            }
94            ParseError::IncompleteForceSection => {
95                write!(f, "file ended unexpectedly while reading force section")
96            }
97            ParseError::IncompleteEnergySection => {
98                write!(f, "file ended unexpectedly while reading energy section")
99            }
100            ParseError::IncompleteSection(name) => {
101                write!(f, "file ended unexpectedly while reading {name} section")
102            }
103            ParseError::UnknownSection(name) => {
104                write!(f, "unknown section type in metadata: {name}")
105            }
106            ParseError::ValidationError(msg) => {
107                write!(f, "CON validation failed: {msg}")
108            }
109            ParseError::NonFiniteValue(token) => {
110                write!(f, "non-finite value: {token}")
111            }
112            ParseError::InvalidFixedFlag(msg) => {
113                write!(f, "invalid fixed flag: {msg}")
114            }
115            ParseError::InvalidCount(msg) => {
116                write!(f, "invalid count: {msg}")
117            }
118            ParseError::InvalidUnits(msg) => {
119                write!(f, "invalid units: {msg}")
120            }
121            ParseError::IndexOutOfBounds { index, len } => {
122                write!(
123                    f,
124                    "atom index {index} is out of bounds (builder holds {len} atoms)"
125                )
126            }
127            ParseError::MassMismatch {
128                symbol,
129                first_mass,
130                found_mass,
131                atom_index,
132            } => {
133                write!(
134                    f,
135                    "atoms of type {symbol} have inconsistent masses: first {first_mass}, atom {atom_index} has {found_mass} (CON stores one mass per type)"
136                )
137            }
138            ParseError::Io(msg) => write!(f, "index read failed: {msg}"),
139        }
140    }
141}
142
143impl std::error::Error for ParseError {}
144
145/// Start of the text of a [`ParseError::NonFiniteValue`] that names a cell field.
146const CELL_FIELD: &str = "cell field ";
147const CELL_VALUE_JOINT: &str = " is ";
148
149impl ParseError {
150    /// A cell number that is NaN or infinite, as [`ParseError::NonFiniteValue`].
151    ///
152    /// `field` is the name the caller knows the number by, for example
153    /// `boxl[1]`, `angles[2]`, `cell[4]`, or `lattice_vectors[0][2]`.
154    /// `value` is its spelling: the token of a file, or the Rust rendering of
155    /// the number (`NaN`, `inf`, `-inf`). [`Self::in_frame`] adds the frame.
156    pub fn non_finite_cell(field: &str, value: impl std::fmt::Display) -> Self {
157        ParseError::NonFiniteValue(format!("{CELL_FIELD}{field}{CELL_VALUE_JOINT}{value}"))
158    }
159
160    /// Recover the typed error from the text a `String`-error layer carries.
161    ///
162    /// For a layer that can carry only text: a Cap'n Proto failure, or the
163    /// `String` form of a [`ConvertError`]. A message made by `to_string` on
164    /// a cell error comes back as the same error; any other message gives
165    /// `None`.
166    #[must_use]
167    pub fn from_cell_text(message: &str) -> Option<Self> {
168        let rest = message.strip_prefix("non-finite value: ")?;
169        rest.starts_with(CELL_FIELD)
170            .then(|| ParseError::NonFiniteValue(rest.to_string()))
171    }
172
173    /// Recover any [`ParseError::NonFiniteValue`], of a cell or of an atom
174    /// row, from its `to_string` text. Any other message gives `None`.
175    #[must_use]
176    pub fn from_non_finite_text(message: &str) -> Option<Self> {
177        let rest = message.strip_prefix("non-finite value: ")?;
178        (!rest.is_empty()).then(|| ParseError::NonFiniteValue(rest.to_string()))
179    }
180
181    /// True for the error [`Self::non_finite_cell`] makes.
182    pub fn is_non_finite_cell(&self) -> bool {
183        matches!(self, ParseError::NonFiniteValue(text) if text.starts_with(CELL_FIELD))
184    }
185
186    /// The 0-based frame a non-finite cell error names, if it names one.
187    #[must_use]
188    pub fn named_frame(&self) -> Option<u64> {
189        let ParseError::NonFiniteValue(text) = self else {
190            return None;
191        };
192        let rest = text.strip_prefix(CELL_FIELD)?;
193        let (field, _) = rest.split_once(CELL_VALUE_JOINT)?;
194        let (_, frame) = field.split_once(" of frame ")?;
195        frame.parse().ok()
196    }
197
198    /// Names `frame` (0-based) in a non-finite cell error that does not name
199    /// one yet. Every other error, and a cell error that already names a
200    /// frame, is returned as it was.
201    #[must_use]
202    pub fn in_frame(self, frame: u64) -> Self {
203        let ParseError::NonFiniteValue(text) = &self else {
204            return self;
205        };
206        let Some(rest) = text.strip_prefix(CELL_FIELD) else {
207            return self;
208        };
209        match rest.split_once(CELL_VALUE_JOINT) {
210            Some((field, value)) if !field.contains(' ') => ParseError::NonFiniteValue(format!(
211                "{CELL_FIELD}{field} of frame {frame}{CELL_VALUE_JOINT}{value}"
212            )),
213            _ => self,
214        }
215    }
216}
217
218impl ParseError {
219    /// Stable class name from the v3.1 error table (CON-error.1).
220    pub fn class_name(&self) -> &'static str {
221        match self {
222            ParseError::IncompleteHeader => "IncompleteHeader",
223            ParseError::IncompleteFrame => "IncompleteFrame",
224            ParseError::IncompleteVelocitySection => "IncompleteVelocitySection",
225            ParseError::InvalidVectorLength { .. } => "InvalidVectorLength",
226            ParseError::InvalidNumberFormat(_) => "InvalidNumberFormat",
227            ParseError::MissingSpecVersion => "MissingSpecVersion",
228            ParseError::UnsupportedSpecVersion(_) | ParseError::UnsupportedVersion(_) => {
229                "UnsupportedVersion"
230            }
231            ParseError::InvalidMetadataJson(_) => "InvalidMetadataJson",
232            ParseError::IncompleteForceSection => "IncompleteForceSection",
233            ParseError::IncompleteEnergySection => "IncompleteEnergySection",
234            ParseError::IncompleteSection(_) => "IncompleteSection",
235            ParseError::UnknownSection(_) => "UnknownSection",
236            ParseError::ValidationError(_) => "ValidationError",
237            ParseError::IndexOutOfBounds { .. } => "IndexOutOfBounds",
238            ParseError::MassMismatch { .. } => "MassMismatch",
239            ParseError::NonFiniteValue(_) => "NonFiniteValue",
240            ParseError::InvalidFixedFlag(_) => "InvalidFixedFlag",
241            ParseError::InvalidCount(_) => "InvalidCount",
242            ParseError::InvalidUnits(_) => "InvalidUnits",
243            ParseError::Io(_) => "Io",
244        }
245    }
246
247    /// 1-based file line when this failure is tied to a known header line.
248    /// Metadata failures are line 2 of a single-frame file (CON-error.2).
249    /// Other failures report the line recorded by the iterator, or 0 when
250    /// the producing call did not have a cursor.
251    pub fn line(&self) -> u32 {
252        match self {
253            ParseError::MissingSpecVersion
254            | ParseError::InvalidMetadataJson(_)
255            | ParseError::UnsupportedSpecVersion(_)
256            | ParseError::UnsupportedVersion(_) => 2,
257            _ => 0,
258        }
259    }
260}
261
262impl From<ParseFloatError> for ParseError {
263    fn from(e: ParseFloatError) -> Self {
264        ParseError::InvalidNumberFormat(e.to_string())
265    }
266}
267
268impl From<ParseIntError> for ParseError {
269    fn from(e: ParseIntError) -> Self {
270        ParseError::InvalidNumberFormat(e.to_string())
271    }
272}
273
274impl From<serde_json::Error> for ParseError {
275    fn from(e: serde_json::Error) -> Self {
276        ParseError::InvalidMetadataJson(e.to_string())
277    }
278}
279
280/// Error of a reader, writer, or converter for a format other than CON text:
281/// the extended-XYZ and PDB scanners and the Cap'n Proto frame converters.
282///
283/// A failure with a CON error class, such as a non-finite cell, is
284/// [`ConvertError::Parse`] and keeps its [`ParseError`]. The format's own
285/// diagnostics are [`ConvertError::Message`]. `Display` is the inner text in
286/// both cases.
287#[derive(Debug, Clone)]
288pub enum ConvertError {
289    Parse(ParseError),
290    Message(String),
291}
292
293impl ConvertError {
294    /// The typed error, when this failure has a CON error class.
295    pub fn parse_error(&self) -> Option<&ParseError> {
296        match self {
297            ConvertError::Parse(error) => Some(error),
298            ConvertError::Message(_) => None,
299        }
300    }
301
302    /// True for the error [`ParseError::non_finite_cell`] makes.
303    pub fn is_non_finite_cell(&self) -> bool {
304        self.parse_error()
305            .is_some_and(ParseError::is_non_finite_cell)
306    }
307
308    /// [`ParseError::in_frame`] on a typed error. A message is returned as
309    /// it was.
310    #[must_use]
311    pub fn in_frame(self, frame: u64) -> Self {
312        match self {
313            ConvertError::Parse(error) => ConvertError::Parse(error.in_frame(frame)),
314            message => message,
315        }
316    }
317}
318
319impl fmt::Display for ConvertError {
320    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321        match self {
322            ConvertError::Parse(error) => write!(f, "{error}"),
323            ConvertError::Message(message) => f.write_str(message),
324        }
325    }
326}
327
328impl std::error::Error for ConvertError {
329    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
330        match self {
331            ConvertError::Parse(error) => Some(error),
332            ConvertError::Message(_) => None,
333        }
334    }
335}
336
337/// A [`ConvertError::Message`] equals its text. A typed error equals no
338/// string.
339impl PartialEq<str> for ConvertError {
340    fn eq(&self, other: &str) -> bool {
341        matches!(self, ConvertError::Message(message) if message == other)
342    }
343}
344
345impl PartialEq<&str> for ConvertError {
346    fn eq(&self, other: &&str) -> bool {
347        self == *other
348    }
349}
350
351impl From<ParseError> for ConvertError {
352    fn from(error: ParseError) -> Self {
353        ConvertError::Parse(error)
354    }
355}
356
357impl From<String> for ConvertError {
358    fn from(message: String) -> Self {
359        ConvertError::Message(message)
360    }
361}
362
363impl From<&str> for ConvertError {
364    fn from(message: &str) -> Self {
365        ConvertError::Message(message.to_string())
366    }
367}
368
369/// The text of the error. [`ParseError::from_cell_text`] recovers a
370/// non-finite cell error from it.
371impl From<ConvertError> for String {
372    fn from(error: ConvertError) -> Self {
373        error.to_string()
374    }
375}
376
377/// A parse failure plus the 1-based file line and 0-based frame index.
378///
379/// The line is the cursor that produced the error. Metadata helpers that
380/// report line 2 are used only when that cursor is still 0.
381#[derive(Debug)]
382pub struct LocatedParseError {
383    pub error: ParseError,
384    pub line: u32,
385    pub frame_index: u64,
386}
387
388impl LocatedParseError {
389    pub fn new(error: ParseError, cursor_line: u32, frame_index: u64) -> Self {
390        let line = if cursor_line != 0 {
391            cursor_line
392        } else {
393            error.line()
394        };
395        Self {
396            error: error.in_frame(frame_index),
397            line,
398            frame_index,
399        }
400    }
401}
402
403impl fmt::Display for LocatedParseError {
404    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405        write!(f, "{}", self.error)
406    }
407}
408
409impl std::error::Error for LocatedParseError {
410    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
411        Some(&self.error)
412    }
413}