ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The SOURCE declaration's emission: the DOUBLE ENTRY, which is the whole of what a source
//! declaration writes.
//!
//! ```ignore
//! #[ingraph::source(async, mutation(node = "WatchOps"))]
//! pub struct Watch { … }
//!
//! impl AsyncSource for Watch {
//!   type Mutation = WatchOps;      // the TYPE half — the author's own hand
//!   …
//! }
//! ```
//!
//! # Two entries for one fact, and the emission is what holds them together
//!
//! A source's command face is written TWICE, and neither spelling can be dropped. The WORD is what
//! the declaration says — it is what a manifest front end, a schema walk and a reader see — and the
//! TYPE is what the compiler resolves a [`Control`](../../ingraph/struct.Control.html) line through.
//! Two macro expansions cannot read each other's tokens and an attribute macro cannot write somebody
//! else's `impl`, so the word cannot mint the type and the type cannot mint the word.
//!
//! What this emission writes is the JOIN: one bound, stated over the declared type, naming the node
//! the word named. So the two entries are checked against each other at the declaration, in BOTH
//! directions:
//!
//! | written | what happens |
//! |---|---|
//! | `mutation(node = "WatchOps")` and `type Mutation = WatchOps` | it compiles |
//! | `mutation(node = "WatchOps")` and `type Mutation = ()` (or another node) | `E0271` at the WORD |
//! | no word and `type Mutation = WatchOps` | `E0271` at the DECLARATION |
//! | no word and `type Mutation = ()` | it compiles |
//!
//! The third row is the one a single-entry design would have lost: a source that mounted a node and
//! forgot to say so would publish no wire face and no reader would ever know, because a missing word
//! looks exactly like a source nobody controls. The bound is what makes silence impossible.
//!
//! # The FACE is the `async` word's, and the word is what names the trait
//!
//! `#[ingraph::source]` binds [`Source`](../../ingraph/trait.Source.html) and
//! `#[ingraph::source(async)]` binds [`AsyncSource`](../../ingraph/trait.AsyncSource.html) — the
//! dual-mode law's word-selects-face rule, applied at the one position that has to name a trait to
//! state anything at all. A declaration whose word and whose `impl` disagree is `E0277` at the
//! declaration, naming the face it does not wear, which is what
//! [`Source`](../../ingraph/trait.Source.html)'s own `on_unimplemented` note is written for.
//!
//! # THE RECORD a launch walk mounts it through
//!
//! Beside the entry, one impl:
//!
//! ```ignore
//! impl DeclaredOrigin for Watch {
//!   type Mode = Block;                                  // the `async` word, as a TYPE
//!   const MOUNTS: Option<&'static str> = Some("WatchOps");
//! }
//! ```
//!
//! `Declared`'s own arrangement for the origin layer: a walk that mounts an origin sees a type, so
//! the declaration STATES what it is and the walk NAMES it through a projection. The `Mode` seat is
//! what makes one mount door serve both faces, and the string is for a reader rather than for the
//! compiler — what resolves the mount is the seat the double entry is stated over.
//!
//! # NOTHING ELSE is emitted
//!
//! No command enum (the node's own declaration mints it), no `MutationNode` row (the node's), no
//! resolver (the node's binding pass). The host is echoed, one anonymous `const` is written beside
//! it, and the record above.

use quote::{quote, quote_spanned};
use syn::spanned::Spanned as _;

#[cfg(test)]
mod tests;

/// A validated source declaration, ready to emit.
///
/// PLAIN, for the reason every model in this crate has plain fields: the derive today and a manifest
/// front end later reach the same emitter.
#[derive(Debug, Clone)]
pub struct SourceModel {
  /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
  /// another.
  pub krate: syn::Path,
  /// The declared type — the origin the double entry is stated over.
  pub name: syn::Ident,
  /// Whether the declaration wore the `async` word, which is what names the face the bound binds.
  pub awaited: bool,
  /// The `mutation(node = "…")` word, or nothing — which is the source nobody controls.
  ///
  /// Carried as the PATH the word held rather than as a literal, because what the emission does with
  /// it is name a type. Its tokens keep the literal's own span, which is what puts a mismatch's
  /// `E0271` on the word an author has to change.
  pub node: Option<syn::Path>,
}

impl SourceModel {
  /// The double entry and the DECLARATION RECORD — see the module note.
  #[must_use]
  pub fn emit(&self) -> proc_macro2::TokenStream {
    let entry = self.entry();
    let declared = self.declared();
    quote! {
      #entry
      #declared
    }
  }

  /// THE RECORD a launch walk mounts this origin through.
  ///
  /// [`MutationModel`](crate::mutation::MutationModel)'s own arrangement one layer over: a walk that
  /// mounts an origin sees a TYPE, so the declaration states its face and the node it controls, and
  /// the walk names them through a projection. The `Mode` seat is what makes ONE mount door serve
  /// both faces — a caller does not choose which, and cannot.
  ///
  /// The mounted node is carried as the PATH the word wrote, and only as that: what the compiler
  /// resolves is the `Mutation` seat the double entry above is stated over, and this string is for a
  /// reader, a manifest front end and a refusal's sentence.
  fn declared(&self) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let name = &self.name;
    let mode = if self.awaited {
      quote!(#krate::__private::operator::Async)
    } else {
      quote!(#krate::__private::operator::Block)
    };
    let mounts = match &self.node {
      Some(node) => {
        let word = quote!(#node).to_string().replace(' ', "");
        quote!(::core::option::Option::Some(#word))
      }
      None => quote!(::core::option::Option::None),
    };
    quote! {
      impl #krate::__private::source::DeclaredOrigin for #name {
        type Mode = #mode;
        const MOUNTS: ::core::option::Option<&'static str> = #mounts;
      }
    }
  }

  /// The DOUBLE ENTRY — one anonymous `const`, whichever way the declaration was written.
  fn entry(&self) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let name = &self.name;
    let face = if self.awaited {
      quote!(#krate::__private::source::AsyncSource)
    } else {
      quote!(#krate::__private::source::Source)
    };

    // The helper's NAME is half the diagnostic: rustc prints the obligation it came from, so a
    // sentence spelled as an identifier is what a reader sees under the `E0271` — which is the only
    // place this join has to say anything, there being no `on_unimplemented` for a projection.
    let (audit, mounted, at) = match &self.node {
      Some(node) => (
        quote::format_ident!("__ingraph_a_source_mounts_the_node_its_mutation_word_named"),
        quote!(#node),
        node.span(),
      ),
      None => (
        quote::format_ident!("__ingraph_a_source_with_no_mutation_word_has_no_command_face"),
        quote!(()),
        name.span(),
      ),
    };

    // The CALL is what carries the span, and not the helper: rustc reports a projection mismatch at
    // the site that instantiated it, so the word an author has to change is where the error lands.
    //
    // The ORIGIN's own name is respanned to that word too, and it has to be: `quote_spanned!` sets
    // the span of the tokens it MINTS, and an interpolated ident keeps the one it was written with
    // — so the turbofish would otherwise carry the declaration's span and put the primary caret on
    // `struct Watch;` while the word an author has to change sat in a note. Respanning is safe
    // where the span is a real one from the same file, which both of these are: resolution is
    // unchanged and only the report moves.
    let spent = syn::Ident::new(&name.to_string(), at);
    let spend = quote_spanned!(at=> const _: fn() = #audit::<#spent>;);
    quote! {
      const _: () = {
        fn #audit<__IgSource>()
        where
          __IgSource: #face<Mutation = #mounted>,
        {
        }

        #spend
      };
    }
  }
}