ingraph_codegen/mutation/
face.rs1use proc_macro2::TokenStream;
59use quote::{ToTokens as _, format_ident, quote, quote_spanned};
60use syn::spanned::Spanned as _;
61
62use super::{DeclaredError, ExchangeModel, MutationModel};
63
64#[cfg(test)]
65mod tests;
66
67impl MutationModel {
68 #[must_use]
74 pub fn response_name(&self) -> syn::Ident {
75 format_ident!("{}Response", self.name)
76 }
77
78 #[must_use]
80 pub fn error_name(&self) -> syn::Ident {
81 format_ident!("{}Error", self.name)
82 }
83
84 #[must_use]
89 pub fn face_name(&self) -> syn::Ident {
90 format_ident!("handle_{}", crate::emit::snake(&self.name.to_string()))
91 }
92
93 #[must_use]
95 pub fn awaited(&self) -> bool {
96 !self.all_sync()
97 }
98
99 pub(super) fn assembly(&self) -> TokenStream {
101 let response = self.response();
102 let error = self.error();
103 let rendering = self.rendering();
104 let calls = self.calls();
105 let assembled = self.assembled();
106 quote! {
107 #response
108 #error
109 #rendering
110 #calls
111 #assembled
112 }
113 }
114
115 fn response(&self) -> TokenStream {
122 let krate = &self.krate;
123 let vis = &self.vis;
124 let name = self.response_name();
125 let arms = self.exchanges.iter().map(|exchange| {
126 let variant = exchange.variant();
127 let ty = &exchange.ty;
128 let doc = crate::emit::leading(&format!(
129 "What the `{field}` exchange answered.",
130 field = exchange.named(),
131 ));
132 quote! {
133 #[doc = #doc]
134 #variant(<#ty as #krate::__private::source::Mutation>::Response)
135 }
136 });
137 let doc = crate::emit::leading(&format!(
138 "What [`{node}`]'s assembled face answers with — one arm per exchange it declared.\n\nThe \
139 node-level response sum, revived: the WIRE answers per field and never through this type, \
140 and what it serves is every other caller of \
141 [`{node}::{face}`]({node}::{face}).",
142 node = self.name,
143 face = self.face_name(),
144 ));
145 let debugged = self.exchanges.iter().map(|exchange| {
150 let variant = exchange.variant();
151 let printed = variant.to_string();
152 quote!(Self::#variant(_) => ::core::fmt::Formatter::write_str(__ingraph_f, #printed))
153 });
154 let debug = if self.exchanges.is_empty() {
155 quote!(match *self {})
156 } else {
157 quote!(match self { #(#debugged,)* })
158 };
159 quote! {
160 #[doc = #doc]
161 #vis enum #name {
162 #(#arms),*
163 }
164
165 impl ::core::fmt::Debug for #name {
166 fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
167 #debug
168 }
169 }
170 }
171 }
172
173 fn error(&self) -> TokenStream {
179 let vis = &self.vis;
180 let name = self.error_name();
181 let arms = self.fallible().map(|exchange| {
182 let variant = exchange.variant();
183 let doc = crate::emit::leading(&format!(
184 "The `{field}` exchange refused.",
185 field = exchange.named(),
186 ));
187 let payload = match &exchange.handler.error {
188 Some(DeclaredError::Rich { ty, .. }) => quote!((#ty)),
189 _ => TokenStream::new(),
192 };
193 quote! {
194 #[doc = #doc]
195 #variant #payload
196 }
197 });
198 let doc = crate::emit::leading(&format!(
199 "How [`{node}`]'s assembled face refuses — one arm per exchange that declared a failure.\n\nA \
200 node whose every exchange is the `Never` tier gets an enum with NO variants, which is the \
201 honest answer rather than an omission: there is no way for such a node to fail, so there is \
202 no value of this type.",
203 node = self.name,
204 ));
205 quote! {
206 #[doc = #doc]
207 #vis enum #name {
208 #(#arms),*
209 }
210 }
211 }
212
213 fn rendering(&self) -> TokenStream {
231 let name = self.error_name();
232 let empty = self.fallible().next().is_none();
233 let (display, debug, code) = if empty {
236 (
237 quote!(match *self {}),
238 quote!(match *self {}),
239 quote!(match *self {}),
240 )
241 } else {
242 let displayed = self.fallible().map(|exchange| exchange.displayed());
243 let debugged = self.fallible().map(|exchange| {
244 let variant = exchange.variant();
245 let printed = variant.to_string();
246 let bound = exchange.binds_a_payload().then(|| quote!((_)));
247 quote!(Self::#variant #bound => ::core::fmt::Formatter::write_str(__ingraph_f, #printed))
248 });
249 let coded = self.fallible().map(|exchange| {
250 let variant = exchange.variant();
251 let bound = exchange.binds_a_payload().then(|| quote!((_)));
252 let word = match exchange.declared_code() {
253 Some(code) => quote!(::core::option::Option::Some(#code)),
254 None => quote!(::core::option::Option::None),
255 };
256 quote!(Self::#variant #bound => #word)
257 });
258 (
259 quote!(match self { #(#displayed,)* }),
260 quote!(match self { #(#debugged,)* }),
261 quote!(match self { #(#coded,)* }),
262 )
263 };
264 let doc = crate::emit::leading(
265 "The heading this failure renders under, where its declaration wrote a `code` word.\n\nThe \
266 same fact `Fallibility::code` carries in the declaration record, reachable from the value \
267 itself — which is what a caller mapping this sum onto a transport's own vocabulary needs.",
268 );
269 quote! {
270 impl ::core::fmt::Display for #name {
271 fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
272 #display
273 }
274 }
275
276 impl ::core::fmt::Debug for #name {
277 fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
278 #debug
279 }
280 }
281
282 impl ::core::error::Error for #name {}
283
284 impl #name {
285 #[doc = #doc]
286 #[must_use]
287 pub const fn code(&self) -> ::core::option::Option<&'static str> {
288 #code
289 }
290 }
291 }
292 }
293
294 fn calls(&self) -> TokenStream {
296 let name = &self.name;
297 let calls = self.exchanges.iter().map(|exchange| exchange.call(self));
298 quote! {
299 impl #name {
300 #(#calls)*
301 }
302 }
303 }
304
305 fn assembled(&self) -> TokenStream {
307 let vis = &self.vis;
308 let name = &self.name;
309 let face = self.face_name();
310 let command = self.command_name();
311 let response = self.response_name();
312 let error = self.error_name();
313 let granted = self.granted();
314 let parameters = granted
315 .iter()
316 .map(|(held, resource)| quote!(#held: &#resource));
317 let awaited = self.awaited().then(|| quote!(async));
318 let arms = self
319 .exchanges
320 .iter()
321 .map(|exchange| exchange.arm(self, &granted));
322 let body = if self.exchanges.is_empty() {
325 quote!(match __ingraph_cmd {})
326 } else {
327 quote!(match __ingraph_cmd { #(#arms)* })
328 };
329 let doc = crate::emit::leading(&format!(
330 "Run whatever this node was told — [`{node}`]'s TOTAL CAPABILITY, in one \
331 {face_kind}function.\n\nOne arm per declared exchange, each calling that exchange's own \
332 handler at the signature its `error(…)` word chose. The face is {face_kind}because \
333 `ALL_SYNC` is `{all_sync}` — the OR law: a node whose every handler is blocking assembles \
334 into a blocking function, and one awaited handler makes the whole face awaited.\n\nThe WIRE \
335 does not come through here. A schema publishes one root field per exchange and calls that \
336 exchange's handler directly; what this serves is every other caller — a first-party \
337 transport, a test, and the source-side party holding a command off its own `Control` \
338 line.\n\n# Errors\n\nWhichever of [`{error}`]({error})'s arms the exchange that ran declared.",
339 node = self.name,
340 face_kind = if self.awaited() {
341 "awaited "
342 } else {
343 "blocking "
344 },
345 all_sync = self.all_sync(),
346 ));
347 quote! {
348 impl #name {
349 #[doc = #doc]
350 #vis #awaited fn #face(
351 #(#parameters,)*
352 __ingraph_cmd: #command,
353 ) -> ::core::result::Result<#response, #error> {
354 #body
355 }
356 }
357 }
358 }
359
360 fn fallible(&self) -> impl Iterator<Item = &ExchangeModel> {
362 self
363 .exchanges
364 .iter()
365 .filter(|exchange| exchange.handler.error.is_some())
366 }
367
368 fn granted(&self) -> Vec<(syn::Ident, syn::Path)> {
380 let mut taken: Vec<String> = vec!["cmd".to_owned()];
383 let mut granted: Vec<(syn::Ident, syn::Path)> = Vec::new();
384 for resource in self
385 .exchanges
386 .iter()
387 .flat_map(|exchange| &exchange.handler.context)
388 {
389 if granted
390 .iter()
391 .any(|(_, held)| super::path_word(held) == super::path_word(resource))
392 {
393 continue;
394 }
395 let bare = resource.segments.last().map_or_else(
396 || "granted".to_owned(),
397 |segment| crate::emit::snake(&segment.ident.to_string()),
398 );
399 let mut held = bare.clone();
400 let mut at = 1;
401 while taken.contains(&held) {
402 held = format!("{bare}_{at}");
403 at += 1;
404 }
405 taken.push(held.clone());
406 granted.push((format_ident!("{held}"), resource.clone()));
407 }
408 granted
409 }
410}
411
412impl ExchangeModel {
413 #[must_use]
416 pub fn call_name(&self) -> syn::Ident {
417 format_ident!("__ingraph_exchange_{}", self.named())
418 }
419
420 fn binds_a_payload(&self) -> bool {
422 matches!(&self.handler.error, Some(DeclaredError::Rich { .. }))
423 }
424
425 fn declared_code(&self) -> Option<&syn::LitStr> {
427 match &self.handler.error {
428 Some(DeclaredError::Rich { code, .. } | DeclaredError::Canned { code, .. }) => code.as_ref(),
429 None => None,
430 }
431 }
432
433 fn displayed(&self) -> TokenStream {
435 let variant = self.variant();
436 let head = self.declared_code().map(|code| {
437 let head = format!("{code}: ", code = code.value());
438 quote!(::core::fmt::Formatter::write_str(__ingraph_f, #head)?;)
439 });
440 match &self.handler.error {
441 Some(DeclaredError::Rich { .. }) => quote! {
444 Self::#variant(__ingraph_refusal) => {
445 #head
446 ::core::fmt::Display::fmt(__ingraph_refusal, __ingraph_f)
447 }
448 },
449 Some(DeclaredError::Canned { message, code }) => {
452 let sentence = match code {
453 Some(code) => format!(
454 "{code}: {message}",
455 code = code.value(),
456 message = message.value()
457 ),
458 None => message.value(),
459 };
460 quote!(Self::#variant => ::core::fmt::Formatter::write_str(__ingraph_f, #sentence))
461 }
462 None => TokenStream::new(),
463 }
464 }
465
466 fn call(&self, model: &MutationModel) -> TokenStream {
473 let krate = &model.krate;
474 let mutation = crate::emit::framework(krate, &["source"], "Mutation");
475 let ty = &self.ty;
476 let name = self.call_name();
477 let path = &self.handler.path;
478
479 let granted: Vec<syn::Ident> = (0..self.handler.context.len())
480 .map(|at| format_ident!("__ingraph_granted_{at}"))
481 .collect();
482 let parameters = granted
483 .iter()
484 .zip(&self.handler.context)
485 .map(|(held, resource)| quote!(#held: &#resource));
486 let awaited = self.handler.awaited.then(|| quote!(.await));
487 let face = self.handler.awaited.then(|| quote!(async));
488 let call = quote_spanned! {path.span()=>
489 #path(#(#granted,)* __ingraph_request) #awaited
490 };
491
492 let tier = match &self.handler.error {
493 None => quote!(<#ty as #mutation>::Response),
494 Some(DeclaredError::Rich { ty: failure, .. }) => {
495 let failure = failure.to_token_stream();
496 quote!(::core::result::Result<<#ty as #mutation>::Response, #failure>)
497 }
498 Some(DeclaredError::Canned { .. }) => {
499 quote!(::core::result::Result<<#ty as #mutation>::Response, ()>)
500 }
501 };
502 let doc = crate::emit::leading(&format!(
503 "The `{field}` exchange's handler, called at the signature its declaration chose.\n\nHidden, \
504 and there is exactly ONE of it: the wire's resolver and the assembled face both spend this \
505 call, so a body that wears another signature is refused once, at the `handler` word.",
506 field = self.named(),
507 ));
508 quote! {
509 #[doc = #doc]
510 #[doc(hidden)]
511 #face fn #name(
512 #(#parameters,)*
513 __ingraph_request: <#ty as #mutation>::Request,
514 ) -> #tier {
515 let __ingraph_outcome: #tier = #call;
516 __ingraph_outcome
517 }
518 }
519 }
520
521 fn arm(&self, model: &MutationModel, granted: &[(syn::Ident, syn::Path)]) -> TokenStream {
523 let command = model.command_name();
524 let response = model.response_name();
525 let error = model.error_name();
526 let variant = self.variant();
527 let call = self.call_name();
528 let arguments = self.handler.context.iter().map(|resource| {
531 granted
532 .iter()
533 .find(|(_, held)| super::path_word(held) == super::path_word(resource))
534 .map_or_else(|| quote!(#resource), |(held, _)| quote!(#held))
535 });
536 let awaited = self.handler.awaited.then(|| quote!(.await));
537 let ran = quote!(Self::#call(#(#arguments,)* __ingraph_request) #awaited);
538
539 match &self.handler.error {
540 None => quote! {
541 #command::#variant(__ingraph_request) => ::core::result::Result::Ok(
542 #response::#variant(#ran)
543 ),
544 },
545 Some(DeclaredError::Rich { .. }) => quote! {
546 #command::#variant(__ingraph_request) => match #ran {
547 ::core::result::Result::Ok(__ingraph_answer) =>
548 ::core::result::Result::Ok(#response::#variant(__ingraph_answer)),
549 ::core::result::Result::Err(__ingraph_refusal) =>
550 ::core::result::Result::Err(#error::#variant(__ingraph_refusal)),
551 },
552 },
553 Some(DeclaredError::Canned { .. }) => quote! {
554 #command::#variant(__ingraph_request) => match #ran {
555 ::core::result::Result::Ok(__ingraph_answer) =>
556 ::core::result::Result::Ok(#response::#variant(__ingraph_answer)),
557 ::core::result::Result::Err(()) =>
560 ::core::result::Result::Err(#error::#variant),
561 },
562 },
563 }
564 }
565}