stepq/error.rs
1//! Error types shared by the whole crate.
2
3/// A convenient alias for results produced by this crate.
4pub type Result<T> = std::result::Result<T, Error>;
5
6/// Every failure `stepq` can report.
7#[derive(Debug, thiserror::Error)]
8#[non_exhaustive]
9pub enum Error {
10 /// The input is not well-formed ISO 10303-21.
11 #[error("syntax error at line {line}, column {column}: {message}")]
12 Syntax {
13 /// 1-based line of the offending token.
14 line: usize,
15 /// 1-based column of the offending token, counted in bytes.
16 column: usize,
17 /// 0-based byte offset of the offending token in the input.
18 offset: usize,
19 /// What went wrong.
20 message: String,
21 },
22
23 /// An entity instance references an `#id` that does not exist.
24 #[error("entity #{from} references undefined instance #{to}")]
25 UnresolvedReference {
26 /// The referencing instance.
27 from: u64,
28 /// The missing instance.
29 to: u64,
30 },
31
32 /// The same `#id` is declared more than once.
33 #[error("entity #{0} is defined more than once")]
34 DuplicateId(u64),
35
36 /// An external reference to another file could not be resolved.
37 #[error("external reference to {file}: {message}")]
38 ExternalReference {
39 /// The file referred to.
40 file: String,
41 /// What went wrong.
42 message: String,
43 },
44
45 /// An I/O failure while reading or writing a file.
46 #[error(transparent)]
47 Io(#[from] std::io::Error),
48
49 /// A unit, or the units of a context or item, cannot be read as stated.
50 #[error(transparent)]
51 Unit(#[from] crate::units::UnitError),
52
53 /// A point, direction, placement, surface or curve cannot be read as
54 /// stated.
55 #[error(transparent)]
56 Geometry(#[from] crate::geometry::GeometryError),
57
58 /// An assembly usage, or an occurrence, cannot be placed as stated.
59 #[error(transparent)]
60 Placement(#[from] crate::model::PlacementError),
61
62 /// A solid's topology cannot be read as stated.
63 #[error(transparent)]
64 Topology(#[from] crate::topology::TopologyError),
65}
66
67impl Error {
68 /// Builds an [`Error::Syntax`] located at byte `offset` of `src`.
69 ///
70 /// Line and column are computed here, on the error path only, so the
71 /// lexer does not track them for every byte.
72 pub(crate) fn syntax(src: &[u8], offset: usize, message: impl Into<String>) -> Self {
73 let offset = offset.min(src.len());
74 let before = &src[..offset];
75 let line_start = before
76 .iter()
77 .rposition(|&b| b == b'\n')
78 .map_or(0, |i| i + 1);
79 Self::Syntax {
80 line: before.split(|&b| b == b'\n').count(),
81 column: offset - line_start + 1,
82 offset,
83 message: message.into(),
84 }
85 }
86}