ingraph_codegen/mutation.rs
1//! The MUTATION NODE's model and its DECLARATION-SIDE emission: the command vocabulary a source is
2//! controlled through, and the record a source's own expansion reads that declaration through.
3//!
4//! ```ignore
5//! #[ingraph::mutation(graphql(async_graphql))]
6//! pub struct WatchOps {
7//! #[ingraph(rename = "addWatch",
8//! handler(path = "crate::watch::add", async,
9//! context(resource("crate::Catalog")),
10//! error(type = "crate::AddWatchError", code = "ADD_FAILED")))]
11//! add: (AddWatch, AddResponse),
12//!
13//! #[ingraph(handler = "crate::watch::reindex")]
14//! reindex: (Reindex, ()),
15//! }
16//! ```
17//!
18//! # FIELDS ARE EXCHANGES, which is why there is no list to write
19//!
20//! One field is one thing an app can say. The field's TYPE answers what that exchange IS — a
21//! request, a response, a failure — through `Mutation`, and the words beside the field answer
22//! everything a type cannot: who runs it, what the wire calls it, what it was handed, how it fails.
23//! So the declaration has no second list of commands anywhere; a vocabulary that could disagree with
24//! the fields would be a vocabulary two readings could differ about.
25//!
26//! # WHAT IS EMITTED HERE, and what waits
27//!
28//! Six items always, and each answers a reader the others cannot:
29//!
30//! | item | who reads it |
31//! |---|---|
32//! | `<Node>Command` | the source's own `run` body, matching on what an app said |
33//! | `impl MutationNode for <Node>` | the `Control` line's type, through the source's `Mutation` seat |
34//! | `impl DeclaredMutation for <Node>` | everybody who cannot see these tokens |
35//! | `<Node>Response` / `<Node>Error` | whatever calls the assembled face |
36//! | `<Node>::handle_<node>` | a first-party transport, a test, the source-side caller |
37//!
38//! And, where the declaration wore a `graphql(…)` word, the WIRE FACE over all of it — the unit a
39//! root folds, and one resolver per exchange. [`wire`] is where that lives and where its own rules
40//! are written; [`face`] is where the assembled one does. What is worth knowing here is that
41//! everything above is emitted either way, so a node with no wire word still has its whole Rust
42//! surface — and that the wire and the face SHARE one call per exchange, which is the one place a
43//! handler's declared signature is cast.
44//!
45//! # The declaration record is a RECORD and not a channel
46//!
47//! `DeclaredMutation`'s table restates what these tokens already say, and that is deliberate:
48//! `Declared`'s own note gives the reason one layer over, which is that two expansions cannot read
49//! each other's tokens. A source declaring `mutation(node = "WatchOps")` expands in a pass that has
50//! never seen `WatchOps`' fields, so what crosses is a trait impl and a projection off it — nobody
51//! reads anybody's tokens and the compiler resolves the meeting.
52
53use proc_macro2::TokenStream;
54use quote::{format_ident, quote};
55use syn::ext::IdentExt as _;
56
57use crate::model::GraphqlKind;
58
59mod face;
60#[cfg(test)]
61mod tests;
62mod wire;
63
64/// A validated mutation declaration, ready to emit.
65///
66/// PLAIN, for the reason every model in this crate has plain fields: the derive today and a manifest
67/// front end later reach the same emitter.
68#[derive(Debug, Clone)]
69pub struct MutationModel {
70 /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
71 /// another.
72 pub krate: syn::Path,
73 /// The declared type — the node the command enum and both impls are emitted for.
74 pub name: syn::Ident,
75 /// The declaration's own visibility, which the minted command enum wears: a node a caller can
76 /// name has commands that caller can build.
77 pub vis: syn::Visibility,
78 /// The wire backends the `graphql(…)` word named, in the order it named them.
79 ///
80 /// CARRIED and not yet spent — see the module note. It is a list rather than a flag for the index
81 /// grammar's reason: a second backend is a second word inside one block, not a second block.
82 pub graphql: Vec<GraphqlKind>,
83 /// Every exchange, in declaration order — which is the order the command enum's arms take.
84 pub exchanges: Vec<ExchangeModel>,
85}
86
87/// ONE field of a mutation node: the exchange, and the words written beside it.
88#[derive(Debug, Clone)]
89pub struct ExchangeModel {
90 /// The field's own name.
91 pub field: syn::Ident,
92 /// Its type — an exchange, which the emission asserts by projecting `Mutation` off it.
93 pub ty: syn::Type,
94 /// The `rename = "…"` word, or nothing where the declaration wrote none.
95 pub rename: Option<syn::LitStr>,
96 /// The `handler(…)` block, which no field may omit.
97 pub handler: HandlerModel,
98}
99
100/// The `handler(…)` block: the three segments of a signature.
101///
102/// `path` is WHO, `context` is the argument half, `error` is the failing half of the return. They
103/// live in one block because they describe one function, and the `error(…)` word lives INSIDE it for
104/// the same reason — an error with no handler to belong to is an error nothing renders.
105#[derive(Debug, Clone)]
106pub struct HandlerModel {
107 /// What runs — the path the declaration wrote.
108 pub path: syn::Path,
109 /// Whether it wears the `async` word.
110 pub awaited: bool,
111 /// The resources its `context(resource("…"), …)` block granted, in declaration order.
112 pub context: Vec<syn::Path>,
113 /// Its `error(…)` word, or nothing — which is the exchange that cannot fail.
114 pub error: Option<DeclaredError>,
115}
116
117/// The `error(…)` word's two legal shapes, each optionally headed by a code.
118///
119/// `type` and `message` are MUTUALLY EXCLUSIVE, so they are two arms rather than two options: a
120/// declaration that wrote both is refused by the grammar, and a model that could hold both would be
121/// a shape the refusal exists to make unreachable.
122#[derive(Debug, Clone)]
123pub enum DeclaredError {
124 /// `error(type = "…")` — the failure is a type the application owns.
125 Rich {
126 /// The path to that type, as written.
127 ty: syn::Path,
128 /// The `code = "…"` word, where one was written.
129 code: Option<syn::LitStr>,
130 },
131 /// `error(message = "…")` — the whole failure is the declaration's own sentence.
132 Canned {
133 /// The sentence.
134 message: syn::LitStr,
135 /// The `code = "…"` word, where one was written.
136 code: Option<syn::LitStr>,
137 },
138}
139
140impl MutationModel {
141 /// The command enum's name — the node's own, with `Command` after it.
142 ///
143 /// Derived rather than declared, and there is no `command(rename = "…")` word: the node's name IS
144 /// the vocabulary's name, and a second word for it would be a name two spellings could disagree
145 /// about. A node that wants another name is renamed.
146 #[must_use]
147 pub fn command_name(&self) -> syn::Ident {
148 format_ident!("{}Command", self.name)
149 }
150
151 /// Whether EVERY handler here is blocking — the OR law's own const, read the other way round.
152 #[must_use]
153 pub fn all_sync(&self) -> bool {
154 !self
155 .exchanges
156 .iter()
157 .any(|exchange| exchange.handler.awaited)
158 }
159
160 /// The whole expansion: the vocabulary, the row that hands it to a source, the record — and, where
161 /// the declaration wore a `graphql(…)` word, the wire face over all of it.
162 #[must_use]
163 pub fn emit(&self) -> TokenStream {
164 let command = self.command();
165 let node = self.node();
166 let declared = self.declared();
167 let face = self.assembly();
168 let wire = self.wire();
169 quote! {
170 #command
171 #node
172 #declared
173 #face
174 #wire
175 }
176 }
177
178 /// THE VOCABULARY: one arm per field, carrying that exchange's request.
179 ///
180 /// The payload is written as the PROJECTION `<Ty as Mutation>::Request` rather than as the request
181 /// type itself, which is what makes this emission also the assert: a field whose type is not an
182 /// exchange is `E0277` at the field, naming the trait it does not implement, rather than a
183 /// resolution failure somewhere inside a resolver nobody has written yet.
184 fn command(&self) -> TokenStream {
185 let krate = &self.krate;
186 let vis = &self.vis;
187 let name = self.command_name();
188 let arms = self.exchanges.iter().map(|exchange| {
189 let variant = exchange.variant();
190 let ty = &exchange.ty;
191 let doc = format!(
192 "What an app says to run the `{field}` exchange.",
193 field = exchange.named(),
194 );
195 quote! {
196 #[doc = #doc]
197 #variant(<#ty as #krate::__private::source::Mutation>::Request)
198 }
199 });
200 let doc = format!(
201 "The command vocabulary of [`{node}`] — one arm per exchange it declared.",
202 node = self.name,
203 );
204 quote! {
205 #[doc = #doc]
206 #vis enum #name {
207 #(#arms),*
208 }
209 }
210 }
211
212 /// THE ROW a source's `Mutation` seat resolves through.
213 fn node(&self) -> TokenStream {
214 let krate = &self.krate;
215 let name = &self.name;
216 let command = self.command_name();
217 quote! {
218 impl #krate::__private::source::MutationNode for #name {
219 type Command = #command;
220 }
221 }
222 }
223
224 /// THE RECORD: what this declaration said, for the readers that cannot see these tokens.
225 fn declared(&self) -> TokenStream {
226 let krate = &self.krate;
227 let name = &self.name;
228 let all_sync = self.all_sync();
229 let rows = self.exchanges.iter().map(|exchange| exchange.row(krate));
230 quote! {
231 impl #krate::__private::source::DeclaredMutation for #name {
232 const ALL_SYNC: bool = #all_sync;
233 const EXCHANGES: &'static [#krate::__private::source::Exchange] = &[
234 #(#rows),*
235 ];
236 }
237 }
238 }
239}
240
241impl ExchangeModel {
242 /// The command arm this exchange mints.
243 ///
244 /// `heck`'s upper camel case and not [`emit::raise_initial`](crate::emit) — the opposite of the
245 /// choice a PUBLISHED word gets, and for the same law: a Rust field name is snake case by the
246 /// language's own convention rather than by anybody's choice, so re-casing it is a translation and
247 /// not a rewrite of somebody's word.
248 #[must_use]
249 pub fn variant(&self) -> syn::Ident {
250 use heck::ToUpperCamelCase as _;
251
252 format_ident!("{}", self.named().to_upper_camel_case())
253 }
254
255 /// The field's name as everything but Rust spells it — unraw'd, so a field legally called
256 /// `r#type` is `type` in the record and `Type` in the vocabulary.
257 #[must_use]
258 pub fn named(&self) -> String {
259 self.field.unraw().to_string()
260 }
261
262 /// This exchange's row in the declaration record — the builder chain, with a call for each word
263 /// the declaration actually wrote and nothing for the words it did not.
264 fn row(&self, krate: &syn::Path) -> TokenStream {
265 let field = self.named();
266 let handler = path_word(&self.handler.path);
267 let mut row = quote!(#krate::__private::source::Exchange::of(#field, #handler));
268
269 if let Some(rename) = &self.rename {
270 row = quote!(#row.renamed(#rename));
271 }
272 if self.handler.awaited {
273 row = quote!(#row.awaited());
274 }
275 if !self.handler.context.is_empty() {
276 let granted = self.handler.context.iter().map(path_word);
277 row = quote!(#row.granting(&[#(#granted),*]));
278 }
279 if let Some(error) = &self.handler.error {
280 let fallibility = error.emit(krate);
281 row = quote!(#row.failing(#fallibility));
282 }
283 row
284 }
285}
286
287impl DeclaredError {
288 /// This failure as the record's own three-tier fact.
289 fn emit(&self, krate: &syn::Path) -> TokenStream {
290 match self {
291 Self::Rich { ty, code } => {
292 let named = path_word(ty);
293 let code = optional(code.as_ref());
294 quote!(#krate::__private::source::Fallibility::Rich { named: #named, code: #code })
295 }
296 Self::Canned { message, code } => {
297 let code = optional(code.as_ref());
298 quote!(#krate::__private::source::Fallibility::Canned { message: #message, code: #code })
299 }
300 }
301 }
302}
303
304/// A path as the record carries it: the words the declaration wrote, with the spacing `quote` adds
305/// taken back out.
306///
307/// The record's strings are for the SENTENCE — see `Exchange`'s own note — so what matters is that
308/// `crate::watch::add` reads back as it was written rather than as `crate :: watch :: add`.
309fn path_word(path: &syn::Path) -> String {
310 quote!(#path).to_string().replace(' ', "")
311}
312
313/// A word the declaration MAY have written, as the option it is.
314fn optional(word: Option<&syn::LitStr>) -> TokenStream {
315 match word {
316 Some(word) => quote!(::core::option::Option::Some(#word)),
317 None => quote!(::core::option::Option::None),
318 }
319}