ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! THE ROUTE'S BOUND ON THE OPERATOR, over the 2×2 the polling round never crossed: does the node
//! hold a MOUNTED inline citizen, and does an UNMOUNTED clock GRANT.
//!
//! The bound is one line of `emit::grant`'s route and it is assembled from two independent halves —
//! the sweep trait's ARGUMENTS (one per handle an unmounted granting clock was lent) and the node's
//! ANSWER PAIR (`Info` and `Error`, bound where a mounted citizen anchored them). Each half has its
//! own trigger, so the arm is a 2×2 and not a pair of alternatives, and a trait reference carrying
//! BOTH has to spell them in ONE argument list: `<Node>Sweeps<Handle, Info = …, Error = …>`.
//!
//! # Why this file exists — the cell B-35's own matrices never wrote
//!
//! Both axes were exercised, and never at once, because every fixture that had them put the GRANT
//! and the MOUNT on the SAME CLOCK:
//!
//!   * `poll_execution.rs`'s `Mixed` crosses a mounted clock with an unmounted one — and neither
//!     grants, so the sweep trait takes no arguments and the bound has one half;
//!   * `poll_grants.rs`'s `Mixed` crosses a granting clock with an ungranted one — and neither
//!     mounts, so nothing anchors a pair and the bound has the other half;
//!   * `poll_execution.rs`'s `Reaper` grants AND mounts, on one clock — which is the arm where the
//!     node sweeps nothing at all, so the operator takes no trait bound to spell wrong.
//!
//! The defect needed the two words on DIFFERENT clocks of one node, and that is a cell a matrix
//! built by varying one word at a time cannot reach. What it emitted was
//! `O: <Node>Sweeps<Handle><Info = …, Error = …>` — two argument lists, which is not Rust — so the
//! whole expansion failed to parse at the declaration, for every node of that shape.
//!
//! Read off the EMISSION, and the parse is half the assertion: [`crate::tests::emission`] reads the
//! tokens back as a file, so a bound that does not parse reds here before any string is compared.
//! The live half — a declaration of that shape compiling for real — is
//! `ingraph-derive/tests/poll_grant_anchor.rs`.

use quote::format_ident;

use crate::{
  model::{
    Grant, Grants, PollBody, PollCadence, PollEntry, PollMode, Polls, RecordModel,
    default_sweeps_name,
  },
  name::RustSafeName,
  tests::{emission, model},
};

/// A node whose UNMOUNTED clock grants what `granting` says, standing beside a mounted inline
/// citizen where `anchored` says there is one.
///
/// The unmounted clock is in every cell, which is what keeps the comparison about the bound: a node
/// with no unmounted clock sweeps nothing and states no trait bound at all, so it would answer a
/// different question.
fn node(anchored: bool, granting: bool) -> RecordModel {
  let mut model = model("Reaper", &["media_id"], "id");
  let granted: &[&str] = if granting { &["media::Media"] } else { &[] };
  let mut entries = vec![entry("hourly", granted, None)];
  if anchored {
    entries.push(entry("scrape", &[], Some("app::Scraper")));
  }
  model.polls = Some(Polls { entries });
  model
}

/// One clock, as the front end would have settled it — the variant folded, the mode written.
fn entry(name: &str, granted: &[&str], handler: Option<&str>) -> PollEntry {
  use heck::ToUpperCamelCase as _;

  PollEntry {
    name: format_ident!("{name}"),
    variant: format_ident!("{}", name.to_upper_camel_case()),
    cadence: PollCadence::Every(core::time::Duration::new(600, 0)),
    grants: (!granted.is_empty()).then(|| Grants {
      grants: granted.iter().copied().map(grant).collect(),
    }),
    body: handler.map_or(PollBody::Light, |path| {
      PollBody::Citizen(syn::parse_str(path).expect("a type path"))
    }),
    mode: PollMode::AsyncInline,
    concurrent: false,
  }
}

/// One grant, with the mount the front end folds off the path's last segment.
fn grant(path: &str) -> Grant {
  let node: syn::Path = syn::parse_str(path).expect("a type path");
  let segment = &node
    .segments
    .last()
    .expect("a path has at least one segment")
    .ident;
  let mount = RustSafeName::new(segment.to_string(), proc_macro2::Span::call_site());
  Grant { node, mount }
}

/// The emission as one string with its spaces gone — the grant suite's own reader.
fn tight(model: &RecordModel) -> String {
  model.emit().to_string().replace(' ', "")
}

/// THE 2×2, and every cell spells the trait reference ONCE.
///
/// The pair is the mounted citizen's wherever there is one, which is the anchor law the route
/// states; what this walk adds is that binding it costs the ARGUMENTS nothing — the handles stay in
/// front of the bindings, inside the same `<…>`.
#[test]
fn the_sweep_bound_carries_its_handles_and_its_pair_in_one_argument_list() {
  let pair = "Info=<app::Scraperas::ingraph::__private::drive::AsyncTick<()>>::Info,\
              Error=<app::Scraperas::ingraph::__private::drive::AsyncTick<()>>::Error";
  for (anchored, granting, arguments) in [
    (false, false, String::new()),
    (false, true, "<MediaHandle>".to_owned()),
    (true, false, format!("<{pair}>")),
    (true, true, format!("<MediaHandle,{pair}>")),
  ] {
    let model = node(anchored, granting);
    // The PARSE, first and on its own: an unparsable bound is not a wrong string, it is an
    // expansion the compiler never reads past.
    let _ = emission(&model);
    let sweeps = default_sweeps_name(&model.record);
    let expected = format!("O:{sweeps}{arguments}+::core::marker::Send,");
    assert!(
      tight(&model).contains(&expected),
      "mounted={anchored} granting={granting} wants `{expected}`: {}",
      tight(&model),
    );
  }
}

/// **THE DEFECT ITSELF, as an absence.** No cell spells the sweep trait's name followed by two
/// argument lists.
///
/// The half that cannot be asserted by looking for something: the repair is a `<` that is no longer
/// written, and a matrix comparing only what each cell SHOULD contain would pass a spelling that
/// contained both.
#[test]
fn no_pairing_reopens_a_second_argument_list_on_the_sweep_trait() {
  for anchored in [false, true] {
    for granting in [false, true] {
      let model = node(anchored, granting);
      let sweeps = default_sweeps_name(&model.record);
      let emitted = tight(&model);
      assert!(
        !emitted.contains(&format!("{sweeps}<MediaHandle><")),
        "mounted={anchored} granting={granting}: {emitted}"
      );
    }
  }
}