ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The POLL emission: the vocabulary a node's ticks arrive under, and the schedule its clocks make.
//!
//! `poll(<name>, every = "…" | cron = "…")` becomes two things and no more:
//!
//!   * **`<Node>Due`** — one variant per entry, named by the word the entry minted. A tick carries a
//!     POSITION, this translates the position into the name, and the author matches on the name. The
//!     third of the rename-proof identity types beside `<Node>In` and `<Node>Out`, and it is emitted
//!     at EVERY arity: a fan-in of one collapses to the message type because there already is one,
//!     and a clock of one has no such fallback — a tick's identity is a position either way.
//!   * **`<Node>Due::schedule()`** — the declared cadences as the runtime's own `Schedule`, in
//!     declaration order. Without it the schedule words would be parsed into a model nothing spends,
//!     which is the shape this crate refuses by doctrine: a word nobody reads is a promise rather
//!     than a rule.
//!
//! # Why `schedule()` is fallible at EVERY arity
//!
//! A calendar expression is checked at expansion, so nothing about the EXPRESSION can fail here.
//! What can is the machine: a zone name has to be resolved against the running host's database, and
//! the host that runs is not the host that compiled. So the door answers a `Result` — and it answers
//! one even where every entry is an interval, because a signature that changed shape when a
//! declaration swapped `every` for `cron` would break the hand that wired it for a reason that has
//! nothing to do with the caller.
//!
//! # What is NOT emitted, and why
//!
//! A capability grant. The design that answered *how does a sweeping node declare its right to write
//! to another node's store* was ruled in an era when a poll entry NAMED a node, and the ruled entries
//! mint bare names instead — so where a grant would point is not something the records answer.
//! Nothing here invents one: a context is supplied by the wiring, and which handles it carries is
//! still hand-written.

use quote::quote;

use crate::{
  emit::leading,
  model::{PollCadence, PollEntry, RecordModel, default_due_name},
};

impl RecordModel {
  /// The poll expansion: the vocabulary at module scope, and its doors for the anonymous const.
  pub(super) fn poll_face(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let Some(polls) = self.polls.as_ref() else {
      return Default::default();
    };
    let entries = polls.entries.as_slice();
    let (record, vis) = (&self.record, &self.vis);
    let due = default_due_name(record);

    let doc = leading(&format!(
      "WHICH of a [`{record}`]'s clocks came due — one variant per `poll(…)` entry, named by the \
       word the entry minted."
    ));
    let identity_note = leading(
      "A tick carries a POSITION in the node's schedule, and this is what that position MEANS. \
       Matching on the name rather than on the number is what makes the declaration reorderable: \
       moving an entry moves its position and changes no body.",
    );
    let variants = entries.iter().map(|entry| {
      let variant = &entry.variant;
      let doc = leading(&format!("The `{}` clock — {}.", entry.name, cadence(entry)));
      quote! {
        #[doc = #doc]
        #variant,
      }
    });

    let types = quote! {
      #[doc = #doc]
      #[doc = ""]
      #[doc = #identity_note]
      #[derive(
        ::core::fmt::Debug,
        ::core::clone::Clone,
        ::core::marker::Copy,
        ::core::cmp::PartialEq,
        ::core::cmp::Eq,
        ::core::hash::Hash
      )]
      #vis enum #due {
        #(#variants)*
      }
    };
    (types, self.due_doors(&due, entries))
  }

  /// The vocabulary's doors: the count, the two translations, and the schedule.
  fn due_doors(&self, due: &syn::Ident, entries: &[PollEntry]) -> proc_macro2::TokenStream {
    let (record, vis) = (&self.record, &self.vis);
    let arity = entries.len();
    let upstream = self.framework(&["drive"], "PollUpstream");
    let schedule = self.framework(&["drive"], "Schedule");
    let calendar_error = self.framework(&["drive"], "CalendarError");
    let duration = quote!(::core::time::Duration);

    let named = entries.iter().enumerate().map(|(index, entry)| {
      let variant = &entry.variant;
      quote!(#index => ::core::option::Option::Some(Self::#variant),)
    });
    let positions = entries.iter().enumerate().map(|(index, entry)| {
      let variant = &entry.variant;
      quote!(Self::#variant => #index,)
    });
    let steps = entries.iter().map(|entry| match &entry.cadence {
      PollCadence::Every(interval) => {
        let (seconds, nanoseconds) = (interval.as_secs(), interval.subsec_nanos());
        quote!(let schedule = schedule.every(#duration::new(#seconds, #nanoseconds));)
      }
      PollCadence::Calendar {
        expression,
        zone: None,
      } => quote!(let schedule = schedule.cron(#expression)?;),
      PollCadence::Calendar {
        expression,
        zone: Some(zone),
      } => quote!(let schedule = schedule.cron_in(#expression, #zone)?;),
    });

    let count_doc = leading(&format!("How many clocks a [`{record}`] declares."));
    let at_doc = leading(
      "The clock at `upstream`'s position, or `None` where this node has no such entry — the \
       translation an emitted wrapper makes on the way from a tick to a body.",
    );
    let source_doc = leading(
      "This clock's position in declaration order, which is the position its ticks arrive under.",
    );
    let schedule_doc = leading(&format!(
      "The runtime schedule a [`{record}`]'s declared clocks make, in declaration order."
    ));
    let schedule_errors = leading(
      "# Errors\n\nThe calendar seam's refusal, where an entry's zone is one the RUNNING machine's \
       time zone database does not have. The expressions themselves were read at expansion, so \
       nothing about a declaration can fail here — which is why a node whose every entry is an \
       interval answers `Ok` unconditionally and still answers a `Result`: a signature that changed \
       when a declaration swapped `every` for `cron` would break the hand that wired it.",
    );

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

        #[doc = #at_doc]
        #[inline]
        #[must_use]
        #vis const fn at(upstream: #upstream) -> ::core::option::Option<Self> {
          match upstream.index() {
            #(#named)*
            _ => ::core::option::Option::None,
          }
        }

        #[doc = #source_doc]
        #[inline]
        #[must_use]
        #vis const fn upstream(self) -> #upstream {
          #upstream::new(match self {
            #(#positions)*
          })
        }

        #[doc = #schedule_doc]
        #[doc = ""]
        #[doc = #schedule_errors]
        #vis fn schedule() -> ::core::result::Result<#schedule, #calendar_error> {
          let schedule = #schedule::new();
          #(#steps)*
          ::core::result::Result::Ok(schedule)
        }
      }
    }
  }
}

/// One entry's cadence as an author would read it back, for the variant's own doc line.
fn cadence(entry: &PollEntry) -> String {
  match &entry.cadence {
    PollCadence::Every(interval) => format!("every {interval:?}"),
    PollCadence::Calendar {
      expression,
      zone: None,
    } => format!("`{expression}`, in the system's zone"),
    PollCadence::Calendar {
      expression,
      zone: Some(zone),
    } => format!("`{expression}`, in `{zone}`"),
  }
}

#[cfg(test)]
mod tests;