ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The CHANNELS emission: the block a deployment tunes a node's edges in, and the defaults its
//! author shipped.
//!
//! `subscribe(upstream(node = "…", channel = bounded(512)), …)` becomes one type and two facts:
//!
//!   * **`<Node>Channels`** — one field per declared upstream, named by the P1 law (the word the edge
//!     is already known by, in snake case), each holding an optional [`ChannelOptions`]. Typed and
//!     `deny_unknown_fields`, so a document naming a upstream this node does not draw from is refused
//!     where the reader is looking at the file, and a rename moves the key with the type it names.
//!   * **`<Node>Channels::DECLARED`** — the AUTHOR's own defaults, in declaration order. The macro
//!     declares defaults and the document owns the launch truth, so the two layers travel to the
//!     launch floor by different roads: this constant into `UpstreamWiring::with_channel`, the parsed
//!     block into `Channels`.
//!   * **`impl ChannelShelf`** — the table, in declaration order, which is the one thing the launch
//!     floor asks a shelf and the only shape it could ask for: positions are what the wiring walk
//!     numbers edges by, and a name would need a map nothing keeps in step.
//!
//! # It is emitted at EVERY arity, and for the container only
//!
//! A node drawing from ONE upstream still has that edge to tune, so the shelf is emitted wherever a
//! `subscribe(…)` container is written, unlike the `<Node>In` sum beside it — a shelf whose
//! existence depended on the count would appear the day a second upstream arrived and take a
//! deployment's document with it.
//!
//! The single-word form `subscribe = "path::To::Upstream"` gets NO shelf, and that is a fence rather
//! than an oversight: the word has no room for a `channel` beside it, so a shelf there would carry a
//! config layer over a declared layer that cannot be written. The two spellings meet when the round
//! that gives the single word a container's shape arrives.
//!
//! # Two lanes, because a derive is an attribute
//!
//! The shelf exists in every build — the launch floor reads it whether or not this one parses
//! documents — and only the DERIVE is conditional, so the declaration is written twice, once inside
//! each half of the `serde` gate. [`options`](crate::options) states the mechanism; this is the same
//! one.

use quote::quote;

use crate::{
  emit::{framework, leading, vendored},
  model::{ChannelOptions, RecordModel, Upstream, default_channels_name},
};

impl RecordModel {
  /// The channels expansion: the shelf at module scope, and its doors for the anonymous const.
  pub(super) fn channel_face(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let Some(subscription) = self.subscriptions.as_ref() else {
      return Default::default();
    };
    let upstreams = subscription.upstreams.as_slice();
    let shelf = default_channels_name(&self.record);
    let types = self.declaration(&shelf, upstreams);
    (types, self.shelf_doors(&shelf, upstreams))
  }

  /// The shelf itself, once inside each half of the `serde` gate.
  fn declaration(&self, shelf: &syn::Ident, upstreams: &[Upstream]) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let deserialized = self.shelf_struct(shelf, upstreams, true);
    let plain = self.shelf_struct(shelf, upstreams, false);
    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 }
    }
  }

  /// One lane's struct — with serde's derive and words where this build has serde.
  fn shelf_struct(
    &self,
    shelf: &syn::Ident,
    upstreams: &[Upstream],
    deserialized: bool,
  ) -> proc_macro2::TokenStream {
    let (record, vis) = (&self.record, &self.vis);
    let options = self.framework(&["drive"], "ChannelOptions");

    let fields = upstreams.iter().map(|upstream| {
      let name = upstream.shelf();
      let key = name.external().to_owned();
      let doc = leading(&format!(
        "What this deployment opens the `{}` edge as — `None` being the edge at whatever its \
         declaration and the framework say.",
        upstream.variant
      ));
      // The key is the P1 NAME rather than the field's own spelling, so a upstream whose word is a
      // Rust keyword is written in a document exactly as it is written in the declaration.
      let serde = deserialized.then(|| quote!(#[serde(default, rename = #key)]));
      quote! {
        #[doc = #doc]
        #serde
        #vis #name: ::core::option::Option<#options>,
      }
    });

    let derives = if deserialized {
      let deserialize = framework(&self.krate, &["serde"], "Deserialize");
      let serde = vendored(&self.krate, "serde");
      quote! {
        #[derive(
          ::core::fmt::Debug,
          ::core::clone::Clone,
          ::core::marker::Copy,
          ::core::default::Default,
          ::core::cmp::PartialEq,
          ::core::cmp::Eq,
          #deserialize
        )]
        #[serde(crate = #serde, deny_unknown_fields)]
      }
    } else {
      quote! {
        #[derive(
          ::core::fmt::Debug,
          ::core::clone::Clone,
          ::core::marker::Copy,
          ::core::default::Default,
          ::core::cmp::PartialEq,
          ::core::cmp::Eq
        )]
      }
    };

    let doc = leading(&format!(
      "How ONE DEPLOYMENT opens [`{record}`]'s inbound edges — one field per declared upstream, \
       absent for the ones it says nothing about.\n\nIt is the `channels` block of the node's own \
       section, and it OVERRIDES: what it names wins over the author's declared default and over \
       the framework's shipped constant, for the kind as readily as for the depth. A upstream it \
       leaves unnamed is left to those layers.\n\nThe field names are read off the declaration — the \
       upstream's own word, or the product's where `out = \"…\"` selected one — so a rename moves \
       the document's key with the type it names, and a key naming no upstream of this node is \
       refused where the file is open."
    ));
    quote! {
      #[doc = #doc]
      #derives
      #vis struct #shelf {
        #(#fields)*
      }
    }
  }

  /// The shelf's doors: the count, the author's declared table, and the reading the launch floor
  /// does through the trait.
  fn shelf_doors(&self, shelf: &syn::Ident, upstreams: &[Upstream]) -> proc_macro2::TokenStream {
    let (record, vis) = (&self.record, &self.vis);
    let arity = upstreams.len();
    let options = self.framework(&["drive"], "ChannelOptions");
    let shelf_trait = self.framework(&["drive"], "ChannelShelf");

    let declared = upstreams.iter().map(|upstream| match upstream.channel {
      Some(ChannelOptions::Bounded(capacity)) => {
        quote!(::core::option::Option::Some(#options::Bounded(#capacity)))
      }
      Some(ChannelOptions::Unbounded) => {
        quote!(::core::option::Option::Some(#options::Unbounded))
      }
      None => quote!(::core::option::Option::None),
    });
    let tuning = upstreams.iter().map(|upstream| {
      let name = upstream.shelf();
      quote!(self.#name)
    });

    let count_doc = leading(&format!("How many upstreams a [`{record}`] draws through."));
    let declared_doc = leading(&format!(
      "What [`{record}`]'s AUTHOR ships each of its edges as, in declaration order — `None` where \
       the declaration wrote no `channel` word.\n\nThe middle layer of the precedence, and the one \
       a deployment's document overrides. It is a constant rather than a default of the shelf \
       because the two are different statements: this is what the DECLARATION says, and the shelf \
       is what a deployment says."
    ));

    quote! {
      impl #shelf {
        #[doc = #count_doc]
        #vis const COUNT: usize = #arity;

        #[doc = #declared_doc]
        #vis const DECLARED: [::core::option::Option<#options>; #arity] = [#(#declared,)*];
      }

      #[automatically_derived]
      impl #shelf_trait for #shelf {
        #[inline]
        fn tuning(&self) -> impl ::core::iter::Iterator<
          Item = ::core::option::Option<#options>
        > {
          ::core::iter::IntoIterator::into_iter([#(#tuning,)*])
        }
      }
    }
  }
}

#[cfg(test)]
mod tests;