ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! THE ROOT CATALOG's resource half: the fields a graph root marks `#[ingraph(resource)]`, what a
//! deployment configures them through, and the walk that declares them.
//!
//! ```ignore
//! #[ingraph::graph]
//! pub struct Media {
//!   videos: Video,
//!   #[ingraph(resource)]
//!   egemma: Egemma,
//!   #[ingraph(resource(factory))]
//!   pool: Pool,
//!   #[ingraph(resource(factory = "crate::boot::cache"))]
//!   cache: Cache,
//!   #[ingraph(resource(factory = "crate::boot::index", teardown))]
//!   index: Index,
//! }
//! ```
//!
//! # ONE namespace, and the field spells the THING
//!
//! A root's fields are the deployment's whole catalog — nodes and resources together — so a
//! resource is written exactly as a node is, the TYPE in the field and the kind in the attribute.
//! Nothing here mints a name: the mount IS the field's identifier, and two members that would
//! collide collide as two Rust fields, which is a refusal this emission does not have to write.
//!
//! # The document GROUPS them, and `resources` is reserved for that
//!
//! Struct-flat, document-nested: the spine grows one `resources` field holding a `<Root>Resources`
//! block, so a deployment writes `[resources.egemma]` and every resource's section is under one
//! roof. That is what makes `resources` a reserved mount — a member named `resources` would be a
//! second meaning for the same key — and the derive refuses one by name.
//!
//! # A SECTION is emitted for the resources that HAVE one
//!
//! [`ResourceSource::Section`] is the only source a document can carry, so it is the only one with a
//! field in the block. A `factory` resource's options close over something a document cannot hold —
//! a runtime handle, an open connection — or are computed by a function the declaration names, and
//! writing a section for one is refused where the reader is looking at the file: the field does not
//! exist, and `deny_unknown_fields` names it.
//!
//! A root that declares no document-sourced resource at all gets no block and no `resources` field,
//! which keeps the emitted spine of every root that has none byte-for-byte what it was. A document
//! that writes `resources` at such a root is refused by the same unknown-field rule.

use proc_macro2::TokenStream;
use quote::{format_ident, quote};

use crate::emit::{framework, leading, vendored};

#[cfg(test)]
mod tests;

/// `<Root>Resources` — the name a root's own resource block takes.
///
/// The options spine's rule, one field over: the type is derived from the USER's root, so a `Media`
/// configured by a `MediaOptions` groups its resources in a `MediaResources`.
#[must_use]
pub fn default_resources_name(root: &syn::Ident) -> syn::Ident {
  format_ident!("{root}Resources")
}

/// The mount name the resource block is grouped under, which no member may take.
pub const RESERVED_MOUNT: &str = "resources";

/// WHERE one declared resource's options come from — the emitter's half of the single-source law.
///
/// It mirrors the framework's own vocabulary and adds the one thing an emission needs and a runtime
/// does not: the PATH a named initializer was written as, which is a token and never a value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResourceSource {
  /// `#[ingraph(resource)]` — the deployment's `[resources.<mount>]` section.
  Section,
  /// `#[ingraph(resource(factory))]` — the application's own `prepare` closure.
  Prepare,
  /// `#[ingraph(resource(factory = "path::to::fn"))]` — a function the create walk calls itself.
  Initializer(syn::Path),
}

impl ResourceSource {
  /// Whether this resource takes a field in the emitted block.
  #[must_use]
  pub const fn is_section(&self) -> bool {
    matches!(self, Self::Section)
  }

  /// Whether the emitted create walk builds it, rather than the application's `prepare`.
  #[must_use]
  pub const fn is_walked(&self) -> bool {
    !matches!(self, Self::Prepare)
  }

  /// The framework word this source declares itself as.
  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),
    }
  }
}

/// ONE resource field of a graph root, validated and ready to emit.
///
/// PLAIN, for the reason every model in this crate has plain fields: the derive today and a manifest
/// front end later build the same thing and reach the same emitter.
#[derive(Debug, Clone)]
pub struct ResourceField {
  /// The mount — the field's own identifier, which is the document's key and the name a refusal
  /// reports the resource under.
  pub mount: syn::Ident,
  /// The declared type. The field spells the THING, so this is the resource itself and its options
  /// are reached through the contract.
  pub ty: syn::Type,
  /// The ONE source its declaration named.
  pub source: ResourceSource,
  /// Whether the field wrote `teardown` — the goodbye opt-in, which COMPOSES with either factory
  /// form.
  ///
  /// It is a second axis rather than a fourth source, and it has to be: where the options come from
  /// and whether the built value has something to say on the way out are unrelated questions, and
  /// folding them into one enum would give the grammar a spelling per pair.
  pub teardown: bool,
}

/// One root's resource catalog, ready to emit.
///
/// It borrows for [`OptionsSpine`](crate::options::OptionsSpine)'s reason: what it needs is the list
/// the root model already holds, and a second copy is a second thing to keep in step.
#[derive(Debug, Clone, Copy)]
pub struct Catalog<'a> {
  /// Where `ingraph` lives, as the declaration named it.
  pub krate: &'a syn::Path,
  /// The root's own visibility — what the block and its accessors take.
  pub vis: &'a syn::Visibility,
  /// The root type, whose name the block derives its own from.
  pub root: &'a syn::Ident,
  /// The RESOURCES, in declaration order.
  pub resources: &'a [ResourceField],
}

impl Catalog<'_> {
  /// Every resource whose options come from the document, in declaration order.
  pub fn sections(&self) -> impl Iterator<Item = &ResourceField> {
    self
      .resources
      .iter()
      .filter(|resource| resource.source.is_section())
  }

  /// Whether the spine carries a `resources` field at all — see the module note.
  #[must_use]
  pub fn has_block(&self) -> bool {
    self.sections().next().is_some()
  }

  /// The block a deployment writes its resource sections in, and the walk that declares every
  /// resource whether or not it has one.
  #[must_use]
  pub fn emit(&self) -> TokenStream {
    let block = self.block();
    let walk = self.walk();
    quote! {
      #block
      #walk
    }
  }

  /// `<Root>Resources` — one field per document-sourced resource, plus its accessors and a `Debug`
  /// that reports presence.
  ///
  /// Nothing at all where no resource takes a section, which is what keeps a root that declares none
  /// exactly as it was.
  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
    }
  }

  /// One lane's struct — with serde's derive and words where this build has serde.
  ///
  /// Two lanes for [`options`](crate::options)' reason, which is the same one every emitted
  /// document type has: a derive is an attribute, and an attribute cannot be added by a macro that
  /// expands to nothing, so the declaration is written once inside each half of the gate.
  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)*
      }
    }
  }

  /// The accessor family: one `with_<mount>` and one borrow per document-sourced resource.
  ///
  /// The spine's own shape one field over — construction is the default plus one builder per member
  /// — and ungated for the same reason, the two declarations above being one struct under two
  /// attribute sets.
  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)*
      }
    }
  }

  /// A `Debug` reporting each resource's PRESENCE, and never the options themselves.
  ///
  /// The options spine's trade, made again for its reason: a resource's options are the author's
  /// type, and deriving here would put a `Debug` bound on every one of them for the benefit of this
  /// line.
  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()
        }
      }
    }
  }

  /// `<Root>::resource_iter` and `<Root>::resources` — the RESOURCE half of the walk, and the
  /// catalog it collects into.
  ///
  /// Inherent for [`type_iter`](crate::graph::GraphModel)'s reason, and it is the same mechanism: an
  /// impl may not add a where clause to a trait method, and this walk states one citizenship
  /// predicate per resource field. That predicate is the teaching the ruling asks for — a field
  /// marked `resource` whose type never took `#[ingraph::resource]`, or never implemented
  /// [`AsyncResource`], is `E0277` where the ROOT is written.
  ///
  /// `resources` drives it into the framework's own collector, which is infallible — so the emitted
  /// body names the impossible arm rather than unwrapping it.
  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 {},
          }
        }
      }
    }
  }
}