use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use crate::emit::{framework, leading, vendored};
#[cfg(test)]
mod tests;
#[must_use]
pub fn default_resources_name(root: &syn::Ident) -> syn::Ident {
format_ident!("{root}Resources")
}
pub const RESERVED_MOUNT: &str = "resources";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResourceSource {
Section,
Prepare,
Initializer(syn::Path),
}
impl ResourceSource {
#[must_use]
pub const fn is_section(&self) -> bool {
matches!(self, Self::Section)
}
#[must_use]
pub const fn is_walked(&self) -> bool {
!matches!(self, Self::Prepare)
}
fn word(&self, krate: &syn::Path) -> TokenStream {
let source = framework(krate, &["resource"], "ResourceSource");
match self {
Self::Section => quote!(#source::Section),
Self::Prepare => quote!(#source::Prepare),
Self::Initializer(_) => quote!(#source::Initializer),
}
}
}
#[derive(Debug, Clone)]
pub struct ResourceField {
pub mount: syn::Ident,
pub ty: syn::Type,
pub source: ResourceSource,
pub teardown: bool,
}
#[derive(Debug, Clone, Copy)]
pub struct Catalog<'a> {
pub krate: &'a syn::Path,
pub vis: &'a syn::Visibility,
pub root: &'a syn::Ident,
pub resources: &'a [ResourceField],
}
impl Catalog<'_> {
pub fn sections(&self) -> impl Iterator<Item = &ResourceField> {
self
.resources
.iter()
.filter(|resource| resource.source.is_section())
}
#[must_use]
pub fn has_block(&self) -> bool {
self.sections().next().is_some()
}
#[must_use]
pub fn emit(&self) -> TokenStream {
let block = self.block();
let walk = self.walk();
quote! {
#block
#walk
}
}
fn block(&self) -> TokenStream {
if !self.has_block() {
return TokenStream::new();
}
let krate = self.krate;
let deserialized = self.declaration(true);
let plain = self.declaration(false);
let methods = self.methods();
let debug = self.debug();
let if_serde = quote!(#krate::__private::gate::if_serde);
let if_no_serde = quote!(#krate::__private::gate::if_no_serde);
quote! {
#if_serde ! { #deserialized }
#if_no_serde ! { #plain }
#methods
#debug
}
}
fn declaration(&self, deserialized: bool) -> TokenStream {
let vis = self.vis;
let root = self.root;
let name = default_resources_name(root);
let resource = framework(self.krate, &["resource"], "AsyncResource");
let fields = self.sections().map(|field| {
let (mount, ty) = (&field.mount, &field.ty);
let doc = leading(&format!(
"What this deployment builds `{mount}` with — `None` being the resource at its options' own \
`Default`.\n\nThe field NAME is the mount name, so a document's key is the word the \
declaration wrote: `[resources.{mount}]`."
));
let default = deserialized.then(|| quote!(#[serde(default)]));
quote! {
#[doc = #doc]
#default
pub(crate) #mount: ::core::option::Option<<#ty as #resource>::Options>,
}
});
let derives = if deserialized {
let deserialize = framework(self.krate, &["serde"], "Deserialize");
let serde = vendored(self.krate, "serde");
quote! {
#[derive(::core::default::Default, #deserialize)]
#[serde(crate = #serde, deny_unknown_fields)]
}
} else {
quote!(#[derive(::core::default::Default)])
};
let doc = leading(&format!(
"What ONE DEPLOYMENT of [`{root}`] builds its shared resources with — one section per \
document-sourced resource, absent for the ones it says nothing about.\n\nAn absent section \
is the resource at its options' own `Default`, and an options type without one has said its \
knobs are mandatory: the create walk then refuses by name, which is the node side's rule one \
tier over.\n\nA resource declared `factory` has NO field here. Its options come from the \
application's own hand or from the function its declaration names, and a section for one is \
refused as an unknown field, where the reader is looking at the file."
));
quote! {
#[doc = #doc]
#derives
#vis struct #name {
#(#fields)*
}
}
}
fn methods(&self) -> TokenStream {
let vis = self.vis;
let name = default_resources_name(self.root);
let resource = framework(self.krate, &["resource"], "AsyncResource");
let methods = self.sections().map(|field| {
let (mount, ty) = (&field.mount, &field.ty);
let with = format_ident!("with_{mount}");
let held = quote!(<#ty as #resource>::Options);
let with_doc = leading(&format!(
"Build `{mount}` with `options` — the door a deployment states in code rather than in a \
document."
));
let borrow_doc = leading(&format!(
"What `{mount}` is to be built with, or `None` where this deployment wrote no section for \
it."
));
quote! {
#[doc = #with_doc]
#[inline]
#[must_use]
#vis fn #with(mut self, options: #held) -> Self {
self.#mount = ::core::option::Option::Some(options);
self
}
#[doc = #borrow_doc]
#[inline]
#[must_use]
#vis fn #mount(&self) -> ::core::option::Option<&#held> {
self.#mount.as_ref()
}
}
});
quote! {
impl #name {
#(#methods)*
}
}
}
fn debug(&self) -> TokenStream {
let name = default_resources_name(self.root);
let fields = self.sections().map(|field| {
let key = field.mount.to_string();
let mount = &field.mount;
quote!(.field(#key, &::core::option::Option::is_some(&self.#mount)))
});
quote! {
impl ::core::fmt::Debug for #name {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.debug_struct(::core::stringify!(#name))
#(#fields)*
.finish()
}
}
}
}
fn walk(&self) -> TokenStream {
let krate = self.krate;
let vis = self.vis;
let root = self.root;
let resources = framework(krate, &["resource"], "ResourceCatalog");
let visitor = framework(krate, &["resource"], "ResourceVisitor");
let declared = self.resources.iter().map(|field| {
let ty = &field.ty;
let mount = field.mount.to_string();
let source = field.source.word(krate);
quote! {
#visitor::next_resource::<#ty>(visitor, #mount, #source)?;
}
});
let iter_doc = leading(
"Apply `visitor` to every RESOURCE this graph declares, in the order its fields are \
written.\n\nEach call carries the three facts a resource declaration states: the type, the \
mount it is written under, and the ONE source its options come from.\n\n# Errors\n\nThe first \
resource the visitor refuses, with the ones after it unvisited.",
);
let catalog_doc = leading(&format!(
"THE ROOT CATALOG of [`{root}`] — every declared resource, its mount, and its one options \
source.\n\nWhat `launch` installs on the plan it is handed, so a deployment never writes the \
declared set: the root's fields ARE it."
));
quote! {
impl #root {
#[doc = #iter_doc]
#vis fn resource_iter<__IgResources>(
visitor: &mut __IgResources,
) -> ::core::result::Result<(), <__IgResources as #visitor>::Error>
where
__IgResources: #visitor,
{
#(#declared)*
::core::result::Result::Ok(())
}
#[doc = #catalog_doc]
#[must_use]
#vis fn resources() -> #resources {
let mut declared = #resources::new();
match Self::resource_iter(&mut declared) {
::core::result::Result::Ok(()) => declared,
::core::result::Result::Err(never) => match never {},
}
}
}
}
}
}