Skip to main content

ingraph_codegen/
error.rs

1//! THE LEAF ERROR's midwife: an application's own failure type, dressed to render.
2//!
3//! ```ignore
4//! #[ingraph::mutation_error]
5//! pub enum WatchError {
6//!   #[ingraph(code = "NOT_A_DIRECTORY", error = "`{0}` is not a directory")]
7//!   NotADirectory(PathBuf),
8//! }
9//! ```
10//!
11//! emits `Display`, [`core::error::Error`] and one reading — `code()` — and NOTHING ELSE. The enum
12//! stays the author's: its arms, its payloads, its derives and its visibility are echoed untouched.
13//!
14//! # IT IS A CONVENIENCE AND NOT A SEAM, which is the ruling and not a hedge
15//!
16//! A hand-written error is exactly as legal here as a generated one. Nothing in this framework asks
17//! a failure type for anything but a `Display` — `error(type = "…")`'s own rendering, and the
18//! assembled face's error sum, both spend that and no more — so a type that implements `Display` by
19//! hand, or through somebody else's derive, is a first-class declared failure. What this macro buys
20//! is the CODE DISCIPLINE below, which a hand-written error simply does not get checked for.
21//!
22//! # ONE CODE PER VARIANT, and the code IS the head of the sentence
23//!
24//! Every variant writes a `code`, and the rendering is `CODE: message`. That is the one-code-head
25//! law, and it is why the code is mandatory rather than optional: a leaf error's whole job at the
26//! wire is to be recognised, and a variant with no word is a refusal a client cannot tell from its
27//! neighbour.
28//!
29//! It is also why a declaration that heads such an error a SECOND time is a mistake. A declared
30//! `error(type = "…", code = "…")` puts its own heading in front of whatever the value renders as,
31//! so an error minted here — which already carries one — is declared WITHOUT the `code` word. Two
32//! headings on one message is two vocabularies with nothing telling a reader which is which.
33//!
34//! # THE CODE SPACE IS OPEN, and the framework's own words are RESERVED
35//!
36//! An application mints whatever `SCREAMING_SNAKE_CASE` words it likes: this framework cannot
37//! enumerate everybody's failures and does not try. What it does hold is its OWN vocabulary — the
38//! [`ErrorCode`](../../ingraph/enum.ErrorCode.html) table, one word per typed refusal that can reach
39//! the wire — and a declaration that mints one of those words is refused. A client matching on
40//! `UNREACHABLE_SOURCE` would otherwise be told *the change was made and not applied* by an
41//! application error that meant something else entirely.
42//!
43//! [`RESERVED`] is that table's words, carried here because a proc macro cannot depend on the crate
44//! it generates code for. The two lists are pinned EQUAL by `ingraph`'s own `graphql::code` fixture
45//! — the file a round that adds a word already has to touch, which is what makes the pin catch that
46//! round rather than merely catch a rename.
47//!
48//! # WHAT THE DECLARATION OWES
49//!
50//! A `Debug`, because [`core::error::Error`] has it as a supertrait — and nothing here emits one,
51//! because a `Debug` this emission wrote would collide with the derive most error types already
52//! carry. A [`Display`](core::fmt::Display) on every field a template RENDERS; nothing at all on a
53//! field it never names, which is bound as `_`.
54//!
55//! # THE TEMPLATE is a format string over the variant's own fields
56//!
57//! `{0}` and `{}` name a tuple variant's fields by position; `{name}` names a struct variant's by
58//! name. What is emitted is ONE `write_str`-or-`write!` per arm with the head folded in at
59//! expansion time, and every argument passed EXPLICITLY by name — implicit capture is the
60//! declaring crate's edition to have, and an expansion does not get to assume one.
61
62use proc_macro2::TokenStream;
63use quote::{ToTokens as _, quote};
64
65#[cfg(test)]
66mod tests;
67
68/// The FRAMEWORK's own wire vocabulary, as words.
69///
70/// A mirror of [`ErrorCode`](../../ingraph/enum.ErrorCode.html)'s renderings, and it has to be one: a
71/// proc macro runs before — and without — the crate whose table this is, so the list cannot be read
72/// off the type. The two are pinned equal by `ingraph`'s own vocabulary fixture, which is where a
73/// new word is already obliged to be written down.
74///
75/// Sorted, because the refusal a collision earns names its neighbours and a list a reader can scan
76/// is a list a reviewer can check against the table.
77pub const RESERVED: &[&str] = &[
78  "AMBIGUOUS_PAGE_DIRECTION",
79  "OVERSIZED_SKIP",
80  "REPEATED_ORDER_SUBJECT",
81  "REQUEST_DROPPED",
82  "REQUEST_TIMED_OUT",
83  "STORE_REFUSED",
84  "UNPAGEABLE_ORDER",
85  "UNREACHABLE_NODE",
86  "UNREACHABLE_SOURCE",
87  "UNREADABLE_ROW",
88  "UNRENDERABLE_ORDER",
89  "UNSUPPORTED_FILTER",
90  "UNUSABLE_ADDRESS",
91  "UNUSABLE_CURSOR",
92  "UNWRITTEN_ARTIFACT",
93];
94
95/// WHICH ROAD an error was minted for — the word an author wrote, carried for the sentence.
96///
97/// The two macros emit the SAME items, and that is deliberate rather than an accident waiting to be
98/// deduplicated: what differs is which half of the line a failure belongs to, and a word that says
99/// so is what lets a reader of a declaration know whether they are looking at a write path's failure
100/// or a read path's. The day the two roads want different faces — a `ToErrorCode` row on one of them
101/// — the word is already written and no declaration has to change.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum ErrorRoad {
104  /// `#[ingraph::mutation_error]` — a declared exchange's failure.
105  Mutation,
106  /// `#[ingraph::query_error]` — a read-path author error.
107  Query,
108}
109
110impl ErrorRoad {
111  /// The attribute an author wrote, as they wrote it.
112  #[must_use]
113  pub const fn word(self) -> &'static str {
114    match self {
115      Self::Mutation => "mutation_error",
116      Self::Query => "query_error",
117    }
118  }
119
120  /// What such an error IS, for the sentence a refusal makes.
121  #[must_use]
122  pub const fn subject(self) -> &'static str {
123    match self {
124      Self::Mutation => "a declared exchange's failure",
125      Self::Query => "a read path's failure",
126    }
127  }
128}
129
130/// A validated leaf-error declaration, ready to emit.
131///
132/// PLAIN, for the reason every model in this crate has plain fields: the derive today and a manifest
133/// front end later reach the same emitter.
134#[derive(Debug, Clone)]
135pub struct ErrorModel {
136  /// The declared type — the enum both impls are emitted for.
137  pub name: syn::Ident,
138  /// Which macro minted it.
139  pub road: ErrorRoad,
140  /// Every variant, in declaration order.
141  pub variants: Vec<VariantModel>,
142}
143
144/// ONE variant of a leaf error: what it is called, what it is recognised by, and what it says.
145#[derive(Debug, Clone)]
146pub struct VariantModel {
147  /// The variant's own name.
148  pub name: syn::Ident,
149  /// Its `code = "…"` word — mandatory, and validated `SCREAMING_SNAKE_CASE`.
150  pub code: syn::LitStr,
151  /// Its `error = "…"` template, ALREADY REWRITTEN so that every placeholder names a binding this
152  /// emission introduces, beside the bindings it has to introduce for them.
153  pub rendering: Rendering,
154  /// How the variant's own fields are bound in a pattern.
155  pub shape: VariantShape,
156}
157
158/// A variant's fields, as a pattern has to spell them.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub enum VariantShape {
161  /// `Variant` — nothing to bind.
162  Unit,
163  /// `Variant(a, b)` — bound by position.
164  Tuple,
165  /// `Variant { a, b }` — bound by name.
166  Named,
167}
168
169/// A variant's message, as the emission spends it.
170#[derive(Debug, Clone)]
171pub struct Rendering {
172  /// The template with every placeholder rewritten to name a binding, and the code folded in at the
173  /// front — so the whole rendering is ONE literal and nothing at runtime assembles it.
174  pub template: String,
175  /// The fields the template referred to: the binding each is introduced under, and how the pattern
176  /// reaches it.
177  pub bound: Vec<Binding>,
178}
179
180/// ONE field a template referred to.
181#[derive(Debug, Clone)]
182pub struct Binding {
183  /// The name the template now spells and the pattern introduces.
184  pub held: syn::Ident,
185  /// WHERE in the variant it is — a position for a tuple variant, a field name for a named one.
186  pub at: BindingAt,
187}
188
189/// Where a bound field sits in its variant.
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub enum BindingAt {
192  /// A tuple variant's field, by position.
193  Position(usize),
194  /// A named variant's field, by name.
195  Named(syn::Ident),
196}
197
198impl ErrorModel {
199  /// The whole expansion: what it prints, that it IS an error, and the word it is recognised by.
200  #[must_use]
201  pub fn emit(&self) -> TokenStream {
202    let name = &self.name;
203    let display = self.display();
204    let coded = self.coded();
205    let doc = crate::emit::leading(&format!(
206      "The word this failure is recognised by — the head of everything it renders as.\n\nOne per \
207       variant and never absent, which is what `#[ingraph::{word}]` checks: {subject} whose \
208       variants shared a word would tell a client one thing about two mistakes.",
209      word = self.road.word(),
210      subject = self.road.subject(),
211    ));
212    quote! {
213      impl ::core::fmt::Display for #name {
214        fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
215          #display
216        }
217      }
218
219      impl ::core::error::Error for #name {}
220
221      impl #name {
222        #[doc = #doc]
223        #[must_use]
224        pub const fn code(&self) -> &'static str {
225          #coded
226        }
227      }
228    }
229  }
230
231  /// `Display`: one arm per variant, each rendering `CODE: message` from ONE literal.
232  fn display(&self) -> TokenStream {
233    if self.variants.is_empty() {
234      // An UNINHABITED error is matched through the place: there is no value, so there is no arm.
235      return quote!(match *self {});
236    }
237    let arms = self.variants.iter().map(|variant| {
238      let pattern = variant.pattern();
239      let template = &variant.rendering.template;
240      if variant.rendering.bound.is_empty() {
241        return quote!(#pattern => ::core::fmt::Formatter::write_str(__ingraph_f, #template));
242      }
243      // EXPLICIT named arguments, never implicit capture: the `write!` lands in the DECLARING
244      // crate, whose edition this expansion does not get to assume.
245      let arguments = variant.rendering.bound.iter().map(|binding| {
246        let held = &binding.held;
247        quote!(#held = #held)
248      });
249      quote!(#pattern => ::core::write!(__ingraph_f, #template, #(#arguments),*))
250    });
251    quote!(match self { #(#arms,)* })
252  }
253
254  /// `code()`: one arm per variant, answering the word its declaration wrote.
255  fn coded(&self) -> TokenStream {
256    if self.variants.is_empty() {
257      return quote!(match *self {});
258    }
259    let arms = self.variants.iter().map(|variant| {
260      let pattern = variant.blind();
261      let code = &variant.code;
262      quote!(#pattern => #code)
263    });
264    quote!(match self { #(#arms,)* })
265  }
266}
267
268impl VariantModel {
269  /// The pattern this variant's arm matches under, binding exactly the fields its template names.
270  fn pattern(&self) -> TokenStream {
271    let name = &self.name;
272    match self.shape {
273      VariantShape::Unit => quote!(Self::#name),
274      VariantShape::Named => {
275        let held = self.rendering.bound.iter().map(|binding| {
276          let BindingAt::Named(at) = &binding.at else {
277            return TokenStream::new();
278          };
279          let held = &binding.held;
280          quote!(#at: #held,)
281        });
282        quote!(Self::#name { #(#held)* .. })
283      }
284      VariantShape::Tuple => {
285        // Position by position, so a field the template never named is `_` rather than a binding
286        // nothing reads — and the ORDER is what makes each `_` stand for the right field.
287        let width = self
288          .rendering
289          .bound
290          .iter()
291          .filter_map(|binding| match &binding.at {
292            BindingAt::Position(at) => Some(at + 1),
293            BindingAt::Named(_) => None,
294          })
295          .max()
296          .unwrap_or(0);
297        let held = (0..width).map(|at| {
298          self
299            .rendering
300            .bound
301            .iter()
302            .find(|binding| binding.at == BindingAt::Position(at))
303            .map_or_else(|| quote!(_), |binding| binding.held.to_token_stream())
304        });
305        quote!(Self::#name(#(#held,)* ..))
306      }
307    }
308  }
309
310  /// The same variant, matched WITHOUT binding anything — what an arm that answers a constant needs.
311  fn blind(&self) -> TokenStream {
312    let name = &self.name;
313    match self.shape {
314      VariantShape::Unit => quote!(Self::#name),
315      VariantShape::Tuple => quote!(Self::#name(..)),
316      VariantShape::Named => quote!(Self::#name { .. }),
317    }
318  }
319}