ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! What the resource catalog's expansion says, read off its tokens.
//!
//! What the catalog DOES — a document filling a section, a `factory` resource reaching the
//! application's own hand, a door the declaration did not name refusing by name — is asserted where
//! the emission can be run, in `ingraph`'s own `tests/resource_catalog.rs`. What is here is what a
//! token stream can be read for: which resources take a field and which do not, the projection each
//! field holds, the words serde is given, the order the walk declares them in, and the shape of the
//! create walk's first step.

use super::{Catalog, ResourceField, ResourceSource};
use crate::graph::GraphModel;

/// A root over one node and all three resource sources, as the derive builds one.
fn app() -> GraphModel {
  GraphModel {
    krate: syn::parse_quote!(::ingraph),
    vis: syn::parse_quote!(pub),
    name: syn::parse_quote!(App),
    nodes: vec![syn::parse_quote!(media::Video)],
    mounts: vec![syn::parse_quote!(videos)],
    queried: Vec::new(),
    interfaces: Vec::new(),
    fused: Vec::new(),
    resources: vec![
      ResourceField {
        mount: syn::parse_quote!(egemma),
        ty: syn::parse_quote!(models::Egemma),
        source: ResourceSource::Section,
        teardown: false,
      },
      ResourceField {
        mount: syn::parse_quote!(pool),
        ty: syn::parse_quote!(Pool),
        source: ResourceSource::Prepare,
        teardown: false,
      },
      ResourceField {
        mount: syn::parse_quote!(cache),
        ty: syn::parse_quote!(Cache),
        source: ResourceSource::Initializer(syn::parse_quote!(crate::boot::cache)),
        teardown: false,
      },
    ],
    origins: Vec::new(),
    // No third-party engine word: this root's subject is its resources.
    engines: Vec::new(),
    retired: None,
    generations: None,
  }
}

/// A root with nodes only — the shape every declaration written before this round has.
fn nodes_only() -> GraphModel {
  GraphModel {
    queried: Vec::new(),
    interfaces: Vec::new(),
    fused: Vec::new(),
    resources: Vec::new(),
    origins: Vec::new(),
    // No third-party engine word: these models are about the list its fields are.
    engines: Vec::new(),
    retired: None,
    generations: None,
    ..app()
  }
}

/// The whole expansion with every space taken out — what a claim about a TYPE or a call is read off.
fn compact(model: &GraphModel) -> String {
  rendered(model).split_whitespace().collect()
}

/// The whole expansion, formatted — what a failing claim prints.
fn rendered(model: &GraphModel) -> String {
  prettyplease::unparse(&syn::parse2(model.emit()).expect("the expansion parses as a file"))
}

/// A claim, taken through the same wringer the expansion is.
///
/// The gated lanes render as macro-invocation token soup and the ungated ones as formatted Rust, so
/// every assertion here is made on both with the whitespace removed — and a claim written by hand
/// has to be spelled the same way rather than remembered to be.
fn packed(claim: &str) -> String {
  claim.split_whitespace().collect()
}

/// Where `compact` starts saying every fragment of `claim`, IN ORDER — `None` where it does not.
///
/// A sequence rather than one long string, because a pretty-printer's line breaks decide where a
/// trailing comma lands inside a generic argument list — which is a fact about the formatter and
/// never about the emission. What each claim here is about is the parts and their order, and the
/// position it answers with is what an ORDER claim between two of them reads.
fn says(compact: &str, claim: &[&str]) -> Option<usize> {
  let mut at = 0;
  let mut head = None;
  for fragment in claim {
    let fragment = packed(fragment);
    let found = at + compact[at..].find(&fragment)?;
    head.get_or_insert(found);
    at = found + fragment.len();
  }
  head
}

/// **THE BLOCK CARRIES THE DOCUMENT-SOURCED RESOURCES AND NOTHING ELSE.** One field per
/// `#[ingraph(resource)]`, each holding that resource's own options through the contract — and no
/// field at all for the two `factory` forms, whose options never come from a document.
#[test]
fn the_block_holds_a_section_only_for_the_resources_that_have_one() {
  let compact = compact(&app());
  assert!(
    compact.contains(&packed(
      "pub (crate) egemma : ::core::option::Option < < models::Egemma as \
       ::ingraph::__private::resource::AsyncResource > ::Options >"
    )),
    "{}",
    rendered(&app())
  );
  assert!(!compact.contains("pub(crate)pool:"), "{}", rendered(&app()));
  assert!(
    !compact.contains("pub(crate)cache:"),
    "{}",
    rendered(&app())
  );
}

/// **THE SPINE GROUPS THEM UNDER ONE KEY.** `resources` is a field of the options struct holding the
/// block, which is what makes a document write `[resources.egemma]` — and it is defaulted, so a
/// deployment that tunes none of them writes no block at all.
#[test]
fn the_spine_carries_the_block_under_the_reserved_key() {
  let compact = compact(&app());
  assert!(
    compact.contains(&packed("pub (crate) resources : AppResources")),
    "{}",
    rendered(&app())
  );
  assert!(
    compact.contains(&packed(
      "#[serde(default)] pub (crate) resources : AppResources"
    )),
    "{}",
    rendered(&app())
  );
  assert!(
    compact.contains(&packed(
      "#[serde(crate = \"::ingraph::__private::serde\", deny_unknown_fields)]"
    )),
    "{}",
    rendered(&app())
  );
}

/// **A ROOT WITH NO DOCUMENT-SOURCED RESOURCE GAINS NOTHING.** No block type, no `resources` field,
/// no accessors — so every declaration written before this round emits exactly what it did, and a
/// document that writes `resources` at one is refused as the unknown field it is.
#[test]
fn a_root_with_no_sections_carries_no_block() {
  let compact = compact(&nodes_only());
  assert!(
    !compact.contains("AppResources"),
    "{}",
    rendered(&nodes_only())
  );
  assert!(
    !compact.contains("pub(crate)resources:"),
    "{}",
    rendered(&nodes_only())
  );
  assert!(
    !compact.contains("fnwith_resources"),
    "{}",
    rendered(&nodes_only())
  );
}

/// **THE ACCESSORS ARE THE DEPLOYMENT'S CODE DOOR.** A builder and a borrow on the block, and the
/// same pair on the spine for the block itself — the shape a node's section already has.
#[test]
fn the_block_and_the_spine_both_take_their_options_in_code() {
  let compact = compact(&app());
  for door in [
    &[
      "pub fn with_egemma (mut self , options :",
      "< models::Egemma as ::ingraph::__private::resource::AsyncResource > ::Options",
      ") -> Self",
    ][..],
    &["pub fn with_resources (mut self , resources : AppResources) -> Self"][..],
    &["pub const fn resources (& self) -> & AppResources"][..],
  ] {
    assert!(
      says(&compact, door).is_some(),
      "{door:?}\n{}",
      rendered(&app())
    );
  }
}

/// **THE WALK DECLARES EVERY RESOURCE, IN DECLARATION ORDER, WITH ALL THREE FACTS.** Including the
/// `factory` ones: a resource the document cannot configure is still a citizen, and the cross-check
/// that refuses an undeclared demand reads exactly this list.
#[test]
fn the_walk_declares_all_three_sources_in_order() {
  let compact = compact(&app());
  let calls: Vec<usize> = [
    ("models::Egemma", "egemma", "Section"),
    ("Pool", "pool", "Prepare"),
    ("Cache", "cache", "Initializer"),
  ]
  .iter()
  .map(|&(ty, mount, source)| {
    let call = [
      format!("next_resource :: < {ty}"),
      "visitor".to_owned(),
      format!("\"{mount}\""),
      format!("::ingraph::__private::resource::ResourceSource::{source}"),
    ];
    let claim: Vec<&str> = call.iter().map(String::as_str).collect();
    says(&compact, &claim).unwrap_or_else(|| panic!("{claim:?}\n{}", rendered(&app())))
  })
  .collect();
  assert!(calls[0] < calls[1] && calls[1] < calls[2], "{calls:?}");
}

/// **THE CATALOG IS COLLECTED, NOT RESTATED.** `resources()` drives the same walk into the
/// framework's own collector, so the list a launch installs on its plan and the list a visitor sees
/// are one list.
#[test]
fn the_catalog_is_the_walk_driven_into_the_frameworks_collector() {
  let compact = compact(&app());
  assert!(
    compact.contains(&packed(
      "pub fn resources () -> ::ingraph::__private::resource::ResourceCatalog"
    )),
    "{}",
    rendered(&app())
  );
  assert!(
    compact.contains(&packed("Self::resource_iter (& mut declared)")),
    "{}",
    rendered(&app())
  );
}

/// **THE CREATE WALK BUILDS THE DECLARED SOURCES AND LEAVES `prepare` ITS OWN.** A section resource
/// falls back to the probe, an initializer is called by the walk, and the bare `factory` gets no
/// call at all — its options being the application's to hand over.
#[test]
fn the_create_walk_drives_the_two_declared_sources_only() {
  let compact = compact(&app());
  assert!(
    says(
      &compact,
      &[
        "let AppResources { egemma : __ingraph_resource_egemma",
        "} = options.resources ;",
      ]
    )
    .is_some(),
    "{}",
    rendered(&app())
  );
  assert!(
    says(
      &compact,
      &[
        "declared_resource :: < models::Egemma",
        "(& mut __ingraph_creation , move || ::core::option::Option::or_else \
       (__ingraph_resource_egemma ,",
        "::ingraph::__private::drive::bare_resource_options ! (models::Egemma)",
      ]
    )
    .is_some(),
    "{}",
    rendered(&app())
  );
  assert!(
    says(
      &compact,
      &[
        "declared_resource :: < Cache",
        "(& mut __ingraph_creation ,",
        "|| ::core::option::Option::Some (crate::boot::cache ())",
      ]
    )
    .is_some(),
    "{}",
    rendered(&app())
  );
  assert!(
    !compact.contains("declared_resource::<Pool"),
    "{}",
    rendered(&app())
  );
}

/// **RESOURCES COME FIRST, AND THE `prepare` HOOK STILL COMES BEFORE THE NODES.** The ruled order,
/// read off the one place it is written: the walk's own token stream.
#[test]
fn the_declared_resources_are_built_before_prepare_and_prepare_before_the_nodes() {
  let compact = compact(&app());
  let resource = compact
    .find(&packed("declared_resource :: < models::Egemma"))
    .expect("the section resource is built");
  let prepare = compact
    .find(&packed("prepare (& mut __ingraph_creation) . await ?"))
    .expect("the hook runs");
  let node = compact
    .find(&packed("node :: < media::Video"))
    .expect("the node pass runs");
  assert!(resource < prepare, "{}", rendered(&app()));
  assert!(prepare < node, "{}", rendered(&app()));
}

/// **THE PLAN'S DECLARED SET IS THE ROOT'S.** The entry installs its own catalog on the plan it is
/// handed, exactly as it installs the options' enablement — which is the whole of what "the Plan's
/// `ResourceCatalog` declaration half dissolves" means at the token level.
#[test]
fn the_entry_installs_the_roots_own_catalog() {
  let compact = compact(&app());
  assert!(
    says(
      &compact,
      &[
        "::ingraph::__private::drive::Plan::with_resources (",
        "::ingraph::__private::drive::Plan::with_enablement (plan , __ingraph_enablement ,)",
        ", Self::resources () ,)",
      ]
    )
    .is_some(),
    "{}",
    rendered(&app())
  );
}

/// **A RESOURCE'S ERROR IS ERASED WHERE THE LAUNCH IS WRITTEN.** One predicate per resource beside
/// the node ones, so a resource whose refusal cannot be erased is refused at the call site rather
/// than inside the walk.
#[test]
fn every_resource_carries_its_error_predicate() {
  let compact = compact(&app());
  assert!(
    compact.contains(&packed(
      "< models::Egemma as ::ingraph::__private::resource::AsyncResource > ::Error : \
       ::core::error::Error"
    )),
    "{}",
    rendered(&app())
  );
  assert!(
    compact.contains(&packed(
      "< Pool as ::ingraph::__private::resource::AsyncResource > ::Error : ::core::error::Error"
    )),
    "{}",
    rendered(&app())
  );
}

/// The catalog borrowed off a model answers about its own list without emitting anything.
#[test]
fn the_catalog_reads_its_own_list() {
  let model = app();
  let catalog: Catalog<'_> = model.catalog();
  assert!(catalog.has_block());
  assert_eq!(catalog.sections().count(), 1);
  assert!(!model.catalog().resources[1].source.is_walked());
  assert!(model.catalog().resources[2].source.is_walked());
  assert!(!nodes_only().catalog().has_block());
}