ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! WHAT THE POLLING EMISSION PUTS IN THE DECLARING SCOPE, held against
//! [`RecordModel::emitted_types`] — the collision rule's coverage of the newest family of mints.
//!
//! The grant suite beside this one reads what each emitted type IS. This one asks the other
//! question, and it is the front end's: does the table a refusal consults KNOW about them. A type
//! the emitter grows and the enumeration does not name is a collision reported inside the expansion
//! — `E0428` over items the author never wrote — and the polling family is where four names arrived
//! at once: one context per granting clock, the lending, the sweep trait and the poll vocabulary.
//!
//! # The METHOD table is silent about these types, and the silence is a measurement
//!
//! [`RecordModel::emitted_methods`] names no method on any of them, and that is correct rather than
//! a second gap. Every inherent method the polling emission writes is a FIXED name on a type no
//! column reaches — `<Node>Polling::new`, one `new` per context, and the poll vocabulary's `at`,
//! `source` and `schedule` — and the write sockets beside them are TRAIT impls, which occupy no name
//! in the declaring scope. Nothing a declaration spells can land on one, so a row here would refuse
//! a declaration for a collision that cannot happen. The test below states that as an assertion
//! rather than leaving it as a claim.
//!
//! A file of its own beside `tests`, on this crate's own precedent: one file per thing being proved.

use quote::format_ident;

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

/// A node with TWO clocks: one that grants a store and mounts a citizen, and one that does neither
/// — so the lending, a context, the sweep trait and the poll vocabulary are all emitted at once.
///
/// The mixed shape is the point. A node whose every clock grants would emit no sweep trait, and one
/// whose every clock is ungranted would emit no context, so either alone would leave a row of the
/// enumeration unexercised.
///
/// The GRANT and the MOUNT ride DIFFERENT clocks, which used to be the one shape this file could not
/// declare: the emission spelled `O: <Node>Sweeps<Handle><Info = …, Error = …>` — two argument
/// lists, which is not Rust — so the fixture routed around it by granting the mounted clock. The arm
/// is repaired, and the crossing is written here on purpose: [`emission`] parses the tokens, so this
/// roster reds on a regression of it before it compares a single name. The shape's own suite is
/// `emit::grant::bound_tests`.
fn polling() -> RecordModel {
  let mut model = model("Reaper", &["media_id"], "id");
  model.polls = Some(Polls {
    entries: vec![
      entry("hourly", &["media::Media"], None),
      entry("nightly", &[], Some("app::PromScraper")),
    ],
  });
  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 types the emission lands in the DECLARING SCOPE, in order.
///
/// TRAITS as well as structs and enums, which is what the polling family made necessary: the sweep
/// seam is a TRAIT, it occupies the same type namespace a struct does, and a walk over structs alone
/// would pass this comparison's newest entry vacuously.
fn scoped_types(file: &syn::File) -> Vec<String> {
  file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Struct(item) => Some(item.ident.to_string()),
      syn::Item::Enum(item) => Some(item.ident.to_string()),
      syn::Item::Trait(item) => Some(item.ident.to_string()),
      _ => None,
    })
    .collect()
}

/// Every item the emission declares, DESCENDING into the anonymous const the impls live in.
///
/// An inherent impl is global whatever block it was written in, so a walk that stopped at the top
/// level would report that the polling types declare no methods at all.
fn all_items(file: &syn::File) -> Vec<&syn::Item> {
  let mut found = Vec::new();
  for item in &file.items {
    found.push(item);
    if let syn::Item::Const(anonymous) = item
      && let syn::Expr::Block(block) = &*anonymous.expr
    {
      found.extend(
        block
          .block
          .stmts
          .iter()
          .filter_map(|statement| match statement {
            syn::Stmt::Item(inner) => Some(inner),
            _ => None,
          }),
      );
    }
  }
  found
}

/// THE POLLING MINTS ARE ON THE TYPE TABLE, in the emitter's own order — the anti-drift half, over a
/// declaration that has all four of them.
#[test]
fn the_enumeration_names_exactly_the_types_a_polling_node_declares() {
  let model = polling();
  let named: Vec<String> = model
    .emitted_types()
    .iter()
    .map(|declared| declared.name.to_string())
    .collect();
  assert_eq!(named, scoped_types(&emission(&model)), "`{}`", model.record);
}

/// And each of them is NAMED, so a refusal about one says which it is rather than pointing at a
/// suffix the reader has to decode.
#[test]
fn every_polling_mint_arrives_with_what_it_is() {
  let model = polling();
  let record = &model.record;
  let roles: Vec<(String, String)> = model
    .emitted_types()
    .iter()
    .map(|declared| (declared.name.to_string(), declared.role.to_string()))
    .collect();
  for (name, role) in [
    (
      poll_grants_name(record, &format_ident!("Hourly")),
      "a clock's grants context",
    ),
    (default_polling_name(record), "the lending"),
    (default_sweeps_name(record), "the sweep trait"),
  ] {
    assert!(
      roles.contains(&(name.to_string(), role.to_owned())),
      "`{name}` is {role}: {roles:?}",
    );
  }
}

/// THE METHOD TABLE'S SILENCE, asserted: every inherent method the polling family writes is a FIXED
/// name on a type no column reaches, so the enumeration names none of them and no declaration is
/// refused over one.
///
/// The inverse is what this reds. A polling type that grew a method DERIVED from a declared word —
/// an accessor per grant, say — would put a name in the declaring scope that a `copy` field could
/// collide with, and the enumeration would owe it a row.
#[test]
fn the_polling_types_declare_only_names_no_declaration_can_reach() {
  let model = polling();
  let file = emission(&model);
  let record = &model.record;
  // The POLLING family alone. The key and the lineage stand in this emission too, and both are types
  // a column DOES reach — their accessors are on the method table already, which is the contrast
  // this walk is drawn against.
  let minted: Vec<String> = [
    poll_grants_name(record, &format_ident!("Hourly")),
    default_polling_name(record),
    default_sweeps_name(record),
    default_due_name(record),
  ]
  .iter()
  .map(ToString::to_string)
  .collect();
  let mut found = Vec::new();
  for item in all_items(&file) {
    let syn::Item::Impl(declared) = item else {
      continue;
    };
    let (None, syn::Type::Path(path)) = (&declared.trait_, &*declared.self_ty) else {
      continue;
    };
    let Some(owner) = path.path.segments.last().map(|last| last.ident.to_string()) else {
      continue;
    };
    if !minted.contains(&owner) {
      continue;
    }
    found.extend(declared.items.iter().filter_map(|item| match item {
      syn::ImplItem::Fn(method) => Some(method.sig.ident.to_string()),
      _ => None,
    }));
  }
  found.sort_unstable();
  found.dedup();
  assert_eq!(
    found,
    ["at", "new", "schedule", "upstream"],
    "the poll vocabulary's three readers and the constructors — every one of them fixed",
  );
}