ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! What the graph root's expansion says, read off its tokens.
//!
//! The expansion's BEHAVIOUR is asserted where it can be run — `ingraph-derive`'s own fixtures,
//! which expand a root for real and walk it. What is here is the two things a token stream can be
//! read for: that the list survives in the order the declaration wrote it, and that every framework
//! path it names goes through the shelf.

use super::{FusedMember, GraphModel};

/// A root over two nodes, 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),
      syn::parse_quote!(Scene),
      syn::parse_quote!(TranscriptText),
    ],
    mounts: vec![
      syn::parse_quote!(videos),
      syn::parse_quote!(scenes),
      syn::parse_quote!(search),
    ],
    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,
  }
}

/// The rendered expansion with every space taken out — what a claim about a PATH or a call is read
/// off.
///
/// The whitespace goes because the formatter's line breaks are not the emission's: a path long
/// enough to wrap arrives with newlines inside its own turbofish, and a claim about which type is
/// visited is not a claim about where a line ended.
fn compact(model: &GraphModel) -> String {
  rendered(model).split_whitespace().collect()
}

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

/// One `next_type` per field, in the order the fields were written — which is the whole of what an
/// ingraph root is.
#[test]
fn the_walk_visits_every_node_in_declaration_order() {
  let model = app();
  let emitted = compact(&model);
  let positions: Vec<usize> = ["media::Video", "Scene", "TranscriptText"]
    .into_iter()
    .map(|node| {
      emitted
        .find(&format!("next_type::<{node},>("))
        .or_else(|| emitted.find(&format!("next_type::<{node}>(")))
        .unwrap_or_else(|| panic!("`{node}` is visited: {}", rendered(&model)))
    })
    .collect();
  assert!(
    positions.windows(2).all(|pair| pair[0] < pair[1]),
    "the walk runs in declaration order: {}",
    rendered(&model)
  );
}

/// Each node also gets a PREDICATE, which is what makes a field that is not a node a refusal at the
/// root rather than inside a visitor.
#[test]
fn every_node_carries_its_own_storage_predicate() {
  let model = app();
  let emitted = compact(&model);
  for node in ["media::Video", "Scene", "TranscriptText"] {
    assert!(
      emitted.contains(&format!("{node}:::ingraph::__private::schema::Describe<")),
      "`{node}` is bound where the walk names it: {}",
      rendered(&model)
    );
  }
}

/// The two entries ride the SQL family's gate, and the walk does not — a build with no database
/// still has the list.
#[test]
fn the_walk_is_ungated_and_the_two_entries_are_not() {
  let model = app();
  let emitted = compact(&model);
  let gate = emitted
    .find("if_sqlx")
    .expect("the entries are gated on the family");
  let walk = emitted.find("fntype_iter").expect("the walk is emitted");
  assert!(
    walk < gate,
    "the walk is outside the gate: {}",
    rendered(&model)
  );
  for entry in ["asyncfninit", "asyncfnvalidate"] {
    let at = emitted
      .find(entry)
      .unwrap_or_else(|| panic!("`{entry}` is emitted: {}", rendered(&model)));
    assert!(
      at > gate,
      "`{entry}` is inside the gate: {}",
      rendered(&model)
    );
  }
}

/// The root's own visibility travels to its entries: a private ingraph's walk stays private rather
/// than leaking into its crate's public API.
#[test]
fn the_entries_take_the_roots_visibility() {
  let mut private = app();
  private.vis = syn::Visibility::Inherited;
  let emitted = compact(&private);
  assert!(
    !emitted.contains("pubfntype_iter") && emitted.contains("fntype_iter"),
    "a private root emits a private walk: {}",
    rendered(&private)
  );
}

/// Where `ingraph` lives is the declaration's to move, and every framework path moves with it.
#[test]
fn the_crate_path_reaches_every_framework_name() {
  let mut vendored = app();
  vendored.krate = syn::parse_quote!(shim::vendored::ingraph);
  let emitted = compact(&vendored);
  assert_eq!(
    emitted.matches("__private").count(),
    emitted
      .matches("shim::vendored::ingraph::__private")
      .count(),
    "every shelf reference is under the declared root, and none keeps the default: {}",
    rendered(&vendored)
  );
  assert!(emitted.contains("shim::vendored::ingraph::__private::transform::TypeVisitor"));
}

/// **THE SLOT-BEARING WALK IS A SECOND LIST**, and it lists the FUSED tier: the nodes' homes are
/// tables and a fused member's are corpora, so folding the two would make every visitor prove a
/// `Describe` for members its target has no home for.
#[test]
fn the_slot_walk_visits_the_fused_tier_and_not_the_nodes() {
  let mut model = app();
  model.fused = vec![
    FusedMember {
      mount: syn::parse_quote!(media),
      ty: syn::parse_quote!(index::Media),
      queried: false,
    },
    FusedMember {
      mount: syn::parse_quote!(shots),
      ty: syn::parse_quote!(Shots),
      queried: false,
    },
  ];
  let emitted = compact(&model);

  assert!(
    emitted.contains(
      "::ingraph::__private::transform::TypeVisitor::next_type::<index::Media,>(visitor)?;::ingrap\
       h::__private::transform::TypeVisitor::next_type::<Shots>(visitor)?;"
    ),
    "the fused members, in declaration order: {}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "index::Media:::ingraph::__private::schema::Describe<<__IgVisitoras::ingraph::__private::tran\
       sform::TypeVisitor>::Db,>,Shots:::ingraph::__private::schema::Describe<"
    ),
    "one `Describe` predicate per member, at the root's own field list: {}",
    rendered(&model)
  );
  assert!(
    !emitted.contains(
      "TypeVisitor::next_type::<media::Video,>(visitor)?;::ingraph::__private::tran\
                       sform::TypeVisitor::next_type::<index::Media,>"
    ),
    "a NODE is not on this walk: {}",
    rendered(&model)
  );
}

/// **BOTH FACES ARE EMITTED, ALWAYS.** The completeness law's own precondition: a deployment may
/// mount a blocking target and an awaited one at once, so the root has to be walkable by either kind
/// of visitor whether or not this build mounts both.
#[test]
fn the_slot_walk_is_emitted_on_both_faces() {
  let mut model = app();
  model.fused = vec![FusedMember {
    mount: syn::parse_quote!(media),
    ty: syn::parse_quote!(index::Media),
    queried: false,
  }];
  let emitted = compact(&model);

  assert!(
    emitted.contains("pubfntype_iter_for<__IgVisitor>"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("pubasyncfntype_iter_for_async<__IgVisitor>"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "::ingraph::__private::transform::AsyncTypeVisitor::next_type::<index::Media,>(visitor).await\
       ?;"
    ),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "index::Media:::ingraph::__private::schema::Describe<<__IgVisitoras::ingraph::__private::tran\
       sform::AsyncTypeVisitor>::Db,>,"
    ),
    "the predicate names the AWAITED face's own target: {}",
    rendered(&model)
  );
}

/// A graph that retrieves nothing still emits the pair, walking nothing — the shape is the root's
/// and not the tier's, so a deployment that grows a fused member later needs no new item.
#[test]
fn a_root_with_no_fused_member_walks_nothing() {
  let emitted = compact(&app());
  assert!(
    emitted.contains("pubfntype_iter_for<__IgVisitor>"),
    "{}",
    rendered(&app())
  );
  assert!(
    emitted.contains("TypeVisitor,{::core::result::Result::Ok(())}"),
    "an empty walk is an `Ok`: {}",
    rendered(&app())
  );
}