laminapdf_syntax/error.rs
1//! The error type of the syntax layer.
2
3use crate::diagnostic::{ErrorKind, Location, Position};
4use crate::limits::Limit;
5
6/// Everything that can go wrong while lexing, parsing or decoding PDF syntax.
7///
8/// Every fallible public function returns [`Result`]; no input is allowed to panic.
9///
10/// Positions are offsets in the buffer that was parsed, reported as
11/// [`Position::FileOffset`]: a caller that parsed something other than the file re-tags them
12/// with [`Error::map_position`] (`laminapdf-cos` does, for windows and object streams).
13/// `Display` formats only fixed text and numbers, never bytes or names read from the input
14/// (ADR 0026 §4).
15///
16/// Added in 0.2.0.
17#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
18#[non_exhaustive]
19pub enum Error {
20 /// The input ended before a complete token or object was read.
21 #[error("unexpected end of input at {at}")]
22 UnexpectedEof {
23 /// Where more input was expected.
24 at: Position,
25 },
26 /// A token or structure did not match what the grammar requires.
27 #[error("syntax error at {at}: {message}")]
28 Syntax {
29 /// Where the offending token is.
30 at: Position,
31 /// Human-readable description of what was expected.
32 message: &'static str,
33 },
34 /// A hard [`Limits`](crate::Limits) value was exceeded (ADR 0003 §3).
35 #[error("{} exceeded{}", limit.name(), at.map(|at| format!(" at {at}")).unwrap_or_default())]
36 LimitExceeded {
37 /// Which limit.
38 limit: Limit,
39 /// Where it was hit, when known: an offset for syntax limits (nesting, string length),
40 /// an object for the reader's limits (reference chains); `None` for decoding budgets.
41 at: Option<Position>,
42 },
43 /// An object had a different type than the structure requires.
44 #[error("type error: expected {expected} for {context}")]
45 Type {
46 /// The expected PDF type (e.g. "name").
47 expected: &'static str,
48 /// Where the value was found (e.g. "/Filter").
49 context: &'static str,
50 },
51 /// The stream uses a filter that is not implemented. The name is read from the file, so
52 /// it is kept here but never formatted (ADR 0026 §4).
53 #[error("unsupported filter")]
54 UnsupportedFilter(String),
55 /// Compressed data was corrupt.
56 #[error("corrupt compressed data: {0}")]
57 Decompress(&'static str),
58 /// Filter parameters (e.g. a PNG predictor) were malformed.
59 #[error("invalid {kind}: {message}")]
60 InvalidStructure {
61 /// Which structure (e.g. "PNG predictor").
62 kind: &'static str,
63 /// What was wrong with it.
64 message: &'static str,
65 },
66}
67
68impl Error {
69 /// Every code [`Error::code`] can return.
70 ///
71 /// Added in 0.2.0.
72 pub const CODES: &'static [&'static str] = &[
73 "unexpected-eof",
74 "syntax",
75 "limit-exceeded",
76 "type",
77 "unsupported-filter",
78 "decompress",
79 "invalid-structure",
80 ];
81
82 /// A stable kebab-case code for this error, part of the public API in Rust, WASM and
83 /// TypeScript (listed in `fixtures/codes.json`).
84 ///
85 /// Added in 0.2.0.
86 #[must_use]
87 pub const fn code(&self) -> &'static str {
88 match self {
89 Self::UnexpectedEof { .. } => "unexpected-eof",
90 Self::Syntax { .. } => "syntax",
91 Self::LimitExceeded { .. } => "limit-exceeded",
92 Self::Type { .. } => "type",
93 Self::UnsupportedFilter(_) => "unsupported-filter",
94 Self::Decompress(_) => "decompress",
95 Self::InvalidStructure { .. } => "invalid-structure",
96 }
97 }
98
99 /// The kind of this error ([ADR 0026] §2), as `fixtures/codes.json` lists it for
100 /// [`Error::code`] (a test checks every variant).
101 ///
102 /// [ADR 0026]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0026-error-and-diagnostic-contract.md
103 ///
104 /// Added in 0.2.0.
105 #[must_use]
106 pub const fn kind(&self) -> ErrorKind {
107 match self {
108 Self::UnexpectedEof { .. }
109 | Self::Syntax { .. }
110 | Self::Type { .. }
111 | Self::Decompress(_)
112 | Self::InvalidStructure { .. } => ErrorKind::Input,
113 Self::LimitExceeded { .. } => ErrorKind::Limit,
114 Self::UnsupportedFilter(_) => ErrorKind::Unsupported,
115 }
116 }
117
118 /// Where the error was found (ADR 0026 §1.1); empty when there is no position.
119 ///
120 /// Added in 0.2.0.
121 #[must_use]
122 pub fn location(&self) -> Location {
123 Location::from(self.position())
124 }
125
126 /// The tagged position this error carries, if any.
127 ///
128 /// Added in 0.2.0.
129 #[must_use]
130 pub const fn position(&self) -> Option<Position> {
131 match *self {
132 Self::UnexpectedEof { at } | Self::Syntax { at, .. } => Some(at),
133 Self::LimitExceeded { at, .. } => at,
134 Self::Type { .. } | Self::UnsupportedFilter(_) | Self::Decompress(_) | Self::InvalidStructure { .. } => {
135 None
136 }
137 }
138 }
139
140 /// This error with its position passed through `f`: how a caller re-tags an offset in
141 /// the buffer it parsed ([`Position::shifted`] for a window of the file,
142 /// [`Position::in_stream`] for a stream's decoded data).
143 ///
144 /// Added in 0.2.0.
145 #[must_use]
146 pub fn map_position(self, f: impl FnOnce(Position) -> Position) -> Self {
147 match self {
148 Self::UnexpectedEof { at } => Self::UnexpectedEof { at: f(at) },
149 Self::Syntax { at, message } => Self::Syntax { at: f(at), message },
150 Self::LimitExceeded { limit, at } => Self::LimitExceeded { limit, at: at.map(f) },
151 other => other,
152 }
153 }
154
155 /// An [`Error::LimitExceeded`] for `limit` at buffer offset `at`.
156 pub(crate) fn limit(limit: Limit, at: Option<usize>) -> Self {
157 Self::LimitExceeded {
158 limit,
159 at: at.map(Position::offset),
160 }
161 }
162}
163
164/// Shorthand for `Result<T, laminapdf_syntax::Error>`.
165///
166/// Added in 0.2.0.
167pub type Result<T> = core::result::Result<T, Error>;
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172 use crate::test_codes as codes;
173
174 /// One value of every variant: the match in [`Error::kind`] has no wildcard, so a new
175 /// variant is a compile error there, and this list is what the tests compare.
176 fn samples() -> Vec<Error> {
177 let at = Position::FileOffset(0);
178 vec![
179 Error::UnexpectedEof { at },
180 Error::Syntax { at, message: "m" },
181 Error::LimitExceeded {
182 limit: Limit::NestingDepth,
183 at: None,
184 },
185 Error::Type {
186 expected: "name",
187 context: "/Filter",
188 },
189 Error::UnsupportedFilter(String::new()),
190 Error::Decompress("m"),
191 Error::InvalidStructure {
192 kind: "k",
193 message: "m",
194 },
195 ]
196 }
197
198 #[test]
199 fn codes_lists_the_code_of_every_variant_in_order() {
200 assert_eq!(codes::distinct(samples().iter().map(Error::code)), Error::CODES);
201 }
202
203 #[test]
204 fn every_variant_has_the_kind_codes_json_lists() {
205 codes::assert_kinds_match(samples().iter().map(|e| (e.code(), e.kind().as_str())));
206 }
207}