Skip to main content

laminapdf_syntax/
record.rs

1//! [`Diagnostic`]: the ADR 0026 §1 object as a plain record, and its one serialisation.
2//!
3//! Every crate that hands an error to another language builds this record (the façade for
4//! its errors and warnings, the WASM bindings for theirs, `laminapdf-render` for render errors),
5//! so the object has one shape and one serialiser.
6
7use serde::ser::SerializeMap;
8use serde::{Serialize, Serializer};
9use serde_json::{Map, Value};
10
11use crate::generated::codes::{ErrorCode, WarningCode};
12use crate::{ErrorKind, Location};
13
14/// One error or warning as the [ADR 0026] §1 object: what the façade's `Error` and `Warning`
15/// serialise to, what the WASM bindings throw, as a record of strings and numbers an edge
16/// maps one-to-one (the `UniFFI` `Diagnostic` record, the TS `LaminaPdfError` fields; ADR 0028
17/// F9). Serialises with camelCase keys, optional keys omitted (never `null`).
18///
19/// Built with [`Diagnostic::error`] or [`Diagnostic::warning`], which read the kind, hint and
20/// `docsUrl` from the generated table, then the `with_` methods.
21///
22/// `message`, `hint` and `did_you_mean` never carry document or caller text ([ADR 0026] §4);
23/// `data` is the only place such strings appear, under the keys each code's explain page
24/// marks *untrusted*.
25///
26/// [ADR 0026]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0026-error-and-diagnostic-contract.md
27///
28/// Added in 0.2.0.
29#[derive(Debug, Clone, PartialEq)]
30#[non_exhaustive]
31pub struct Diagnostic {
32    /// The kebab-case code from `fixtures/codes.json`.
33    pub code: String,
34    /// One of the nine kinds.
35    pub kind: ErrorKind,
36    /// One lowercase sentence (the Rust `Display`).
37    pub message: String,
38    /// One actionable sentence for this code.
39    pub hint: Option<String>,
40    /// Candidates from Lamina PDF's own vocabulary (errors of kind `usage` only); empty today.
41    pub did_you_mean: Vec<String>,
42    /// Where: file offset, object, stream offset, page index, `LaminaPdfId`.
43    pub location: Location,
44    /// Code-specific fields, documented on the code's explain page.
45    pub data: Map<String, Value>,
46    /// The code's explain page.
47    pub docs_url: String,
48}
49
50impl Diagnostic {
51    /// The error `code` with `message`: its kind, hint and `docsUrl` from the generated
52    /// table; no location, data or candidates. `message` is one lowercase sentence that
53    /// never quotes the document or the caller ([ADR 0026] §4).
54    ///
55    /// [ADR 0026]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0026-error-and-diagnostic-contract.md
56    ///
57    /// Added in 0.2.0.
58    #[must_use]
59    pub fn error(code: ErrorCode, message: impl Into<String>) -> Self {
60        Self::of(code.as_str(), code.kind(), message.into(), code.hint(), code.docs_url())
61    }
62
63    /// The warning `code`: its kind, hint and `docsUrl` from the generated table, and its
64    /// fixed summary as the message.
65    ///
66    /// Added in 0.2.0.
67    #[must_use]
68    pub fn warning(code: WarningCode) -> Self {
69        Self::of(
70            code.as_str(),
71            code.kind(),
72            code.summary().to_owned(),
73            code.hint(),
74            code.docs_url(),
75        )
76    }
77
78    fn of(code: &str, kind: ErrorKind, message: String, hint: &str, docs_url: String) -> Self {
79        Self {
80            code: code.to_owned(),
81            kind,
82            message,
83            hint: Some(hint.to_owned()),
84            did_you_mean: Vec::new(),
85            location: Location::NONE,
86            data: Map::new(),
87            docs_url,
88        }
89    }
90
91    /// With `hint` in place of the code's (a hint with its parameter filled in).
92    ///
93    /// Added in 0.2.0.
94    #[must_use]
95    pub fn with_hint(mut self, hint: Option<String>) -> Self {
96        self.hint = hint;
97        self
98    }
99
100    /// With the candidates for `didYouMean` (errors of kind `usage` only).
101    ///
102    /// Added in 0.2.0.
103    #[must_use]
104    pub fn with_did_you_mean(mut self, did_you_mean: Vec<String>) -> Self {
105        self.did_you_mean = did_you_mean;
106        self
107    }
108
109    /// With where the problem was found.
110    ///
111    /// Added in 0.2.0.
112    #[must_use]
113    pub fn with_location(mut self, location: Location) -> Self {
114        self.location = location;
115        self
116    }
117
118    /// With the code-specific fields its explain page lists.
119    ///
120    /// Added in 0.2.0.
121    #[must_use]
122    pub fn with_data(mut self, data: Map<String, Value>) -> Self {
123        self.data = data;
124        self
125    }
126
127    /// The record as a JSON value (the §1 object).
128    ///
129    /// Added in 0.2.0.
130    #[must_use]
131    pub fn to_json(&self) -> Value {
132        serde_json::to_value(self).unwrap_or(Value::Null)
133    }
134}
135
136impl Serialize for Diagnostic {
137    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
138        let mut map = serializer.serialize_map(None)?;
139        map.serialize_entry("code", &self.code)?;
140        map.serialize_entry("kind", self.kind.as_str())?;
141        map.serialize_entry("message", &self.message)?;
142        if let Some(hint) = &self.hint {
143            map.serialize_entry("hint", hint)?;
144        }
145        if !self.did_you_mean.is_empty() {
146            map.serialize_entry("didYouMean", &self.did_you_mean)?;
147        }
148        if !self.location.is_empty() {
149            map.serialize_entry("location", &LocationJson(&self.location))?;
150        }
151        if !self.data.is_empty() {
152            map.serialize_entry("data", &self.data)?;
153        }
154        map.serialize_entry("docsUrl", &self.docs_url)?;
155        map.end()
156    }
157}
158
159/// `location` with each field present only when set (ADR 0026 §1.1).
160struct LocationJson<'a>(&'a Location);
161
162impl Serialize for LocationJson<'_> {
163    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
164        let l = self.0;
165        let mut map = serializer.serialize_map(None)?;
166        if let Some(offset) = l.offset {
167            map.serialize_entry("offset", &offset)?;
168        }
169        if let Some(object) = l.object {
170            map.serialize_entry("object", &object)?;
171        }
172        if let Some(offset) = l.stream_offset {
173            map.serialize_entry("streamOffset", &offset)?;
174        }
175        if let Some(index) = l.page_index {
176            map.serialize_entry("pageIndex", &index)?;
177        }
178        if let Some(id) = &l.id {
179            map.serialize_entry("id", id)?;
180        }
181        map.end()
182    }
183}