Skip to main content

laminapdf_syntax/
diagnostic.rs

1//! The parts of the error and diagnostic contract ([ADR 0026]) that every layer shares: the
2//! nine [`ErrorKind`]s and tagged positions ([`Position`], [`Location`]).
3//!
4//! Codes form one namespace across crates, listed once in `fixtures/codes.json`, from which
5//! `cargo xtask gen codes` generates [`ErrorCode`](crate::ErrorCode) and
6//! [`WarningCode`](crate::WarningCode). Each crate's `kind()` is an exhaustive match over its own
7//! variants, checked against that file by the crate's tests.
8//!
9//! [ADR 0026]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0026-error-and-diagnostic-contract.md
10
11use core::fmt;
12
13/// What kind of failure a code is: what the caller can do about it (ADR 0026 §2).
14///
15/// A closed set: bindings and the CLI match on it exhaustively, so adding a kind amends
16/// ADR 0026 and is a breaking change. That is why, unlike the error enums, it is not
17/// `#[non_exhaustive]`.
18///
19/// Added in 0.2.0.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum ErrorKind {
22    /// The input (PDF bytes, an op log, JSON) is malformed beyond what tolerance repairs.
23    Input,
24    /// The host failed to supply or take bytes (a `ByteSource` read, a sink write).
25    Io,
26    /// Valid input that Lamina PDF doesn't implement.
27    Unsupported,
28    /// A `Limits` value or another resource bound was hit.
29    Limit,
30    /// Encryption, permissions or signatures block the call, or look tampered with.
31    Security,
32    /// The caller misused the API: an unknown option, an argument out of range, an unknown ID.
33    Usage,
34    /// The call isn't valid in the object's current state; it may succeed after a change.
35    State,
36    /// A cancel token stopped the work.
37    Cancelled,
38    /// A bug in Lamina PDF or a broken invariant.
39    Internal,
40}
41
42impl ErrorKind {
43    /// Whether an error of this kind says only that one part of the input is malformed or uses
44    /// something unsupported (`input`, `unsupported`): what a pass over many parts, such as
45    /// every page or every revision, skips. Any other kind (a password, a limit, data not yet
46    /// fetched, cancellation) stops the pass, since the part it couldn't read might matter.
47    ///
48    /// Added in 0.2.0.
49    #[must_use]
50    pub const fn is_skippable(self) -> bool {
51        matches!(self, Self::Input | Self::Unsupported)
52    }
53
54    /// Every kind, in ADR 0026 §2 order.
55    ///
56    /// Added in 0.2.0.
57    pub const ALL: [Self; 9] = [
58        Self::Input,
59        Self::Io,
60        Self::Unsupported,
61        Self::Limit,
62        Self::Security,
63        Self::Usage,
64        Self::State,
65        Self::Cancelled,
66        Self::Internal,
67    ];
68
69    /// The kind's name as it appears in `codes.json` and in serialized diagnostics.
70    ///
71    /// Added in 0.2.0.
72    #[must_use]
73    pub const fn as_str(self) -> &'static str {
74        match self {
75            Self::Input => "input",
76            Self::Io => "io",
77            Self::Unsupported => "unsupported",
78            Self::Limit => "limit",
79            Self::Security => "security",
80            Self::Usage => "usage",
81            Self::State => "state",
82            Self::Cancelled => "cancelled",
83            Self::Internal => "internal",
84        }
85    }
86}
87
88impl fmt::Display for ErrorKind {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.write_str(self.as_str())
91    }
92}
93
94/// Where an error was found, tagged so that a number has one meaning (ADR 0026 §1.1).
95///
96/// The syntax layer only sees the buffer it was given, and reports positions in it as
97/// [`Position::FileOffset`]. A layer that hands it something other than the whole file
98/// re-tags them when it wraps the error: [`Position::shifted`] for a window of the file,
99/// [`Position::in_stream`] for an object stream's decoded data. `laminapdf-cos` does both.
100///
101/// Added in 0.2.0.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
103#[non_exhaustive]
104pub enum Position {
105    /// A byte offset in the input file.
106    FileOffset(u64),
107    /// The indirect object with this number (e.g. where a reference chain got too long).
108    Object(u32),
109    /// A byte offset in the decoded data of stream `object` (an object stream's contents).
110    InStream {
111        /// The stream's object number.
112        object: u32,
113        /// The byte offset in its decoded data.
114        offset: u64,
115    },
116}
117
118impl Position {
119    /// A [`Position::FileOffset`] from a buffer offset (saturating; offsets fit in `u64`).
120    ///
121    /// Added in 0.2.0.
122    #[must_use]
123    pub fn offset(offset: usize) -> Self {
124        Self::FileOffset(u64::try_from(offset).unwrap_or(u64::MAX))
125    }
126
127    /// The position moved by `base` bytes when it is a file offset: for an offset in a
128    /// window of the file that starts at `base`.
129    ///
130    /// Added in 0.2.0.
131    #[must_use]
132    pub const fn shifted(self, base: u64) -> Self {
133        match self {
134            Self::FileOffset(offset) => Self::FileOffset(offset.saturating_add(base)),
135            other => other,
136        }
137    }
138
139    /// The position re-tagged as an offset in the decoded data of stream `object`, when it is
140    /// a file offset: for a parse of that data.
141    ///
142    /// Added in 0.2.0.
143    #[must_use]
144    pub const fn in_stream(self, object: u32) -> Self {
145        match self {
146            Self::FileOffset(offset) => Self::InStream { object, offset },
147            other => other,
148        }
149    }
150}
151
152impl fmt::Display for Position {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        match *self {
155            Self::FileOffset(offset) => write!(f, "byte {offset}"),
156            Self::Object(object) => write!(f, "object {object}"),
157            Self::InStream { object, offset } => write!(f, "byte {offset} of object {object}'s stream data"),
158        }
159    }
160}
161
162/// The `location` of a serialized diagnostic (ADR 0026 §1.1): each field names one kind of
163/// position, and all of them are lamina-made values, never document text.
164///
165/// Added in 0.2.0.
166#[derive(Debug, Clone, PartialEq, Eq, Hash)]
167pub struct Location {
168    /// Byte offset in the input file.
169    pub offset: Option<u64>,
170    /// Object number of the indirect object the problem is in or at.
171    pub object: Option<u32>,
172    /// Byte offset in the decoded data of `object` (only with `object`).
173    pub stream_offset: Option<u64>,
174    /// 0-based page index.
175    pub page_index: Option<u64>,
176    /// A `LaminaPdfId` string, e.g. `p12.0`.
177    pub id: Option<String>,
178}
179
180impl Location {
181    /// No location.
182    ///
183    /// Added in 0.2.0.
184    pub const NONE: Self = Self {
185        offset: None,
186        object: None,
187        stream_offset: None,
188        page_index: None,
189        id: None,
190    };
191
192    /// A location naming only `object`, when there is one.
193    ///
194    /// Added in 0.2.0.
195    #[must_use]
196    pub const fn object(object: Option<u32>) -> Self {
197        Self { object, ..Self::NONE }
198    }
199
200    /// Whether no field is set.
201    ///
202    /// Added in 0.2.0.
203    #[must_use]
204    pub const fn is_empty(&self) -> bool {
205        self.offset.is_none()
206            && self.object.is_none()
207            && self.stream_offset.is_none()
208            && self.page_index.is_none()
209            && self.id.is_none()
210    }
211}
212
213impl Default for Location {
214    fn default() -> Self {
215        Self::NONE
216    }
217}
218
219impl From<Position> for Location {
220    fn from(position: Position) -> Self {
221        match position {
222            Position::FileOffset(offset) => Self {
223                offset: Some(offset),
224                ..Self::NONE
225            },
226            Position::Object(object) => Self::object(Some(object)),
227            Position::InStream { object, offset } => Self {
228                object: Some(object),
229                stream_offset: Some(offset),
230                ..Self::NONE
231            },
232        }
233    }
234}
235
236impl From<Option<Position>> for Location {
237    fn from(position: Option<Position>) -> Self {
238        position.map_or(Self::NONE, Self::from)
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    #[test]
247    fn kind_names_round_trip_through_the_table_order() {
248        let names: Vec<_> = ErrorKind::ALL.iter().map(|k| k.as_str()).collect();
249        assert_eq!(
250            names,
251            [
252                "input",
253                "io",
254                "unsupported",
255                "limit",
256                "security",
257                "usage",
258                "state",
259                "cancelled",
260                "internal"
261            ]
262        );
263    }
264
265    #[test]
266    fn shifted_moves_only_file_offsets() {
267        let moved = [Position::FileOffset(3), Position::Object(3)].map(|p| p.shifted(10));
268        assert_eq!(moved, [Position::FileOffset(13), Position::Object(3)]);
269    }
270
271    #[test]
272    fn in_stream_retags_a_file_offset() {
273        assert_eq!(
274            Position::FileOffset(4).in_stream(7),
275            Position::InStream { object: 7, offset: 4 }
276        );
277    }
278
279    #[test]
280    fn location_from_in_stream_names_the_object_and_the_stream_offset() {
281        let location = Location::from(Position::InStream { object: 7, offset: 4 });
282        assert_eq!(
283            (location.object, location.stream_offset, location.offset),
284            (Some(7), Some(4), None)
285        );
286    }
287}