Skip to main content

datumesh_core/
error.rs

1//! Error codes (SPEC 10.2) and the error type every fallible function returns.
2
3use core::fmt;
4
5macro_rules! codes {
6    ($( $(#[$doc:meta])* $variant:ident = $text:literal, )*) => {
7        /// One variant per `E_*` code of SPEC 10.2.
8        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
9        #[non_exhaustive]
10        pub enum ErrorCode {
11            $( $(#[$doc])* $variant, )*
12        }
13
14        impl ErrorCode {
15            /// Every code, in the order of SPEC 10.2.
16            pub const ALL: &'static [ErrorCode] = &[$(ErrorCode::$variant,)*];
17
18            /// The code as written in the specification, e.g. `"E_SIGNATURE"`.
19            pub const fn as_str(self) -> &'static str {
20                match self { $(ErrorCode::$variant => $text,)* }
21            }
22
23            /// Looks a code up by its text; `None` for anything not in SPEC 10.2.
24            pub fn from_code(text: &str) -> Option<ErrorCode> {
25                match text { $($text => Some(ErrorCode::$variant),)* _ => None }
26            }
27        }
28    };
29}
30
31codes! {
32    /// Not strict JSON (6.1).
33    ParseJson = "E_PARSE_JSON",
34    /// A member name repeated in one object.
35    ParseDuplicateKey = "E_PARSE_DUPLICATE_KEY",
36    /// Not a cell URI by the outer grammar (5.1).
37    ParseUri = "E_PARSE_URI",
38    /// Missing or extra member, wrong JSON type, wrong `proto`, null; content for a non-blob.
39    Schema = "E_SCHEMA",
40    /// Invalid DNS name, namespace, function name, code language or key reference.
41    CanonName = "E_CANON_NAME",
42    /// Invalid or reserved argument name.
43    CanonArgName = "E_CANON_ARG_NAME",
44    /// An argument or `asof` repeated in a URI.
45    CanonArgDuplicate = "E_CANON_ARG_DUPLICATE",
46    /// URI arguments out of order, or `asof` not last.
47    CanonArgOrder = "E_CANON_ARG_ORDER",
48    /// Non-canonical percent-encoding or non-UTF-8 bytes.
49    CanonPercent = "E_CANON_PERCENT",
50    /// Unknown type name, value of the wrong JSON type, or a bad valid-time declaration.
51    CanonType = "E_CANON_TYPE",
52    /// Number not in canonical decimal form.
53    CanonNumber = "E_CANON_NUMBER",
54    /// A unit rule of 7.1 or `units.md` broken.
55    CanonUnit = "E_CANON_UNIT",
56    /// Date not `YYYY-MM-DD` or not a calendar day.
57    CanonDate = "E_CANON_DATE",
58    /// Instant not `YYYY-MM-DDTHH:MM:SS.ffffffZ` or not a real time.
59    CanonInstant = "E_CANON_INSTANT",
60    /// Control, unassigned or surrogate code point, not NFC, or empty summary.
61    CanonString = "E_CANON_STRING",
62    /// Blob not `<sha256>:<length>:<media type>`.
63    CanonBlob = "E_CANON_BLOB",
64    /// Hash, key id or signature not lowercase hex of the right length.
65    CanonHex = "E_CANON_HEX",
66    /// Licence neither an SPDX identifier nor an `https://` URL.
67    CanonLicence = "E_CANON_LICENCE",
68    /// `inputs` not strictly ascending.
69    CanonSet = "E_CANON_SET",
70    /// A limit from 4.5 exceeded.
71    CanonLimit = "E_CANON_LIMIT",
72    /// A slice marker where a single cell is required.
73    Slice = "E_SLICE",
74    /// `publisher` differs from `cell.ns`.
75    PublisherMismatch = "E_PUBLISHER_MISMATCH",
76    /// `valid` does not echo exactly the valid-time arguments.
77    ValidMismatch = "E_VALID_MISMATCH",
78    /// A time-order rule broken.
79    TimeOrder = "E_TIME_ORDER",
80    /// An argument the function does not declare.
81    ArgUnknown = "E_ARG_UNKNOWN",
82    /// A declared argument not bound.
83    ArgMissing = "E_ARG_MISSING",
84    /// The key document could not be retrieved.
85    KeyUnavailable = "E_KEY_UNAVAILABLE",
86    /// The key document is malformed or breaks a rule of 9.2.
87    KeyDoc = "E_KEY_DOC",
88    /// The key document has no key with that id.
89    KeyUnknown = "E_KEY_UNKNOWN",
90    /// `issued` is outside the key's validity window.
91    KeyNotValid = "E_KEY_NOT_VALID",
92    /// The Ed25519 signature does not verify.
93    Signature = "E_SIGNATURE",
94    /// No descriptor found for `fn_hash`.
95    FnUnavailable = "E_FN_UNAVAILABLE",
96    /// The descriptor does not hash to `fn_hash`.
97    FnHashMismatch = "E_FN_HASH_MISMATCH",
98    /// An argument's type differs from its declaration.
99    ArgType = "E_ARG_TYPE",
100    /// `type` differs from the declared return type.
101    ReturnType = "E_RETURN_TYPE",
102    /// An input receipt cannot be found, or has another hash.
103    InputUnavailable = "E_INPUT_UNAVAILABLE",
104    /// An input receipt is not signature-valid.
105    InputInvalid = "E_INPUT_INVALID",
106    /// An input receipt is a cell of an undeclared function.
107    InputUndeclared = "E_INPUT_UNDECLARED",
108    /// Recomputation gives a different type or value.
109    ValueMismatch = "E_VALUE_MISMATCH",
110    /// Blob content has another length or hash than the blob states.
111    BlobMismatch = "E_BLOB_MISMATCH",
112    /// A response envelope breaks a rule of 5.5.
113    Envelope = "E_ENVELOPE",
114}
115
116impl fmt::Display for ErrorCode {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.write_str(self.as_str())
119    }
120}
121
122/// A failure: its code, the JSON path (or URI part) where it was found, and a human detail.
123#[derive(Clone, Debug, PartialEq, Eq)]
124pub struct Error {
125    code: ErrorCode,
126    path: String,
127    detail: String,
128}
129
130impl Error {
131    /// Builds an error. `path` is a JSONPath-like location such as `$.cell.args.base`.
132    pub fn new(code: ErrorCode, path: impl Into<String>, detail: impl Into<String>) -> Error {
133        Error { code, path: path.into(), detail: detail.into() }
134    }
135
136    /// The code of SPEC 10.2.
137    pub fn code(&self) -> ErrorCode {
138        self.code
139    }
140
141    /// The code as text, e.g. `"E_SIGNATURE"`.
142    pub fn code_str(&self) -> &'static str {
143        self.code.as_str()
144    }
145
146    /// Where the failure was found: `$` is the whole input, `$.a.b[0]` a member.
147    pub fn path(&self) -> &str {
148        &self.path
149    }
150
151    /// A human-readable explanation. Not stable; do not match on it.
152    pub fn detail(&self) -> &str {
153        &self.detail
154    }
155
156    /// The same failure reported under another code (e.g. wrapping as `E_KEY_DOC`).
157    pub(crate) fn recode(self, code: ErrorCode) -> Error {
158        let detail = if self.code == code { self.detail } else { format!("{}: {}", self.code, self.detail) };
159        Error { code, path: self.path, detail }
160    }
161}
162
163impl fmt::Display for Error {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        write!(f, "{} at {}: {}", self.code, self.path, self.detail)
166    }
167}
168
169impl std::error::Error for Error {}
170
171/// Shorthand used throughout the crate.
172pub type Result<T> = core::result::Result<T, Error>;
173
174pub(crate) fn err<T>(code: ErrorCode, path: &str, detail: impl Into<String>) -> Result<T> {
175    Err(Error::new(code, path, detail))
176}
177
178/// Appends a member name to a path.
179pub(crate) fn member(path: &str, name: &str) -> String {
180    format!("{path}.{name}")
181}
182
183/// Appends an array index to a path.
184pub(crate) fn index(path: &str, i: usize) -> String {
185    format!("{path}[{i}]")
186}