ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The REWRITE MODE, at the token level — and the mode boundary, which is the assertion the rest of
//! the suite depends on.
//!
//! Whether the device WORKS is a claim about a compiled program, and the corpus in
//! `ingraph-derive/tests/entity_record_remote.rs` is where it is made. What is here is what only
//! this side can say: that an ordinary model emits not one token of the device, and that a wrapping
//! one emits exactly the family the mode promises.

use quote::ToTokens as _;

use crate::{
  construct::{Blanket, Cross, Seat},
  model::{Field, NodeKind, RecordModel},
  tests::{emission, model},
};

/// The suite's own record, made a REWRITE.
fn wrapping() -> RecordModel {
  let mut model = model("Video", &["media_id"], "id");
  model.kind = NodeKind::Entity;
  model.persist = None;
  model.remote = Some(syn::parse_quote!(upstream::Video));
  model
}

/// The whole emission as one string, gates opened.
fn rendered(model: &RecordModel) -> String {
  emission(model).into_token_stream().to_string()
}

/// **THE MODE BOUNDARY.** A declaration that wrote no `remote` gets nothing this module writes —
/// no bridge, no reference family, and readers that are the ordinary ones.
#[test]
fn an_ordinary_declaration_emits_not_one_token_of_the_device() {
  let ordinary = rendered(&model("Video", &["media_id"], "id"));
  for absent in [
    "__IngraphRemoteBridge",
    "__ingraph_cross",
    "repr (transparent)",
    "Deref",
    "BorrowMut",
  ] {
    assert!(
      !ordinary.contains(absent),
      "an ordinary declaration emitted `{absent}`"
    );
  }
  assert!(
    ordinary.contains("& self . media_id"),
    "and its readers are the field reads they always were"
  );
}

/// The reference family, all eight items of it — and every body is `self.0`, which is what makes
/// the family the language's guarantee rather than a layout claim.
#[test]
fn the_reference_family_is_eight_impls_over_one_field() {
  let wrapped = rendered(&wrapping());
  for expected in [
    "impl :: core :: convert :: AsRef < upstream :: Video > for Video",
    "impl :: core :: convert :: AsMut < upstream :: Video > for Video",
    "impl :: core :: ops :: Deref for Video",
    "impl :: core :: ops :: DerefMut for Video",
    "impl :: core :: borrow :: Borrow < upstream :: Video > for Video",
    "impl :: core :: borrow :: BorrowMut < upstream :: Video > for Video",
    "impl :: core :: convert :: From < upstream :: Video > for Video",
    "impl :: core :: convert :: From < Video > for upstream :: Video",
  ] {
    assert!(
      wrapped.contains(expected),
      "the emission is missing `{expected}`"
    );
  }
  assert!(
    !wrapped.contains("transmute"),
    "and it conjures nothing — `self.0` is a field access"
  );
}

/// The BRIDGE carries both diagnostic attributes, and the second is what keeps the sentence the
/// framework's: without `do_not_recommend` the report descends through the blanket impl and names
/// `Into`, which is true and is not what this device wants to say.
#[test]
fn the_bridge_is_a_marker_that_refuses_in_the_frameworks_own_words() {
  let wrapped = rendered(&wrapping());
  assert!(wrapped.contains("diagnostic :: on_unimplemented"));
  assert!(wrapped.contains("diagnostic :: do_not_recommend"));
  assert!(
    wrapped.contains("upstream :: Video"),
    "and the note names the remote a reader has to go and look at"
  );
}

/// **BY VALUE FOR DATA, BY REFERENCE FOR IDENTITY** — the asymmetry the framework's borrowed
/// identity seats force, asserted where it is written rather than inferred from a compile.
#[test]
fn a_data_column_crosses_and_an_identity_column_borrows() {
  let wrapped = rendered(&wrapping());
  assert!(
    wrapped.contains("fn checksum (& self) -> u64 { __ingraph_cross (self . 0 . checksum ()) }"),
    "a data column is read through the accessor and crossed"
  );
  assert!(
    wrapped.contains("fn id_ref (& self) -> & Uuid7 { self . 0 . id () }"),
    "an identity column is borrowed straight off the remote"
  );
}

/// No mutator and no `const`: a remote's fields are its own, and a foreign accessor is not this
/// emission's to declare `const`.
#[test]
fn a_wrapper_declares_no_mutator_and_no_const_reader() {
  let wrapped = rendered(&wrapping());
  assert!(
    !wrapped.contains("fn set_checksum"),
    "nothing assigns into a remote"
  );
  assert!(!wrapped.contains("fn with_checksum"));
  assert!(
    !wrapped.contains("const fn checksum"),
    "a foreign accessor is not this emission's to declare `const`"
  );
}

/// **THE ENUMERATION AND THE EMISSION ARE ONE WALK.** The collision check reads the names really
/// emitted, in both modes, which is what keeps a refusal about a duplicate method true.
#[test]
fn the_name_enumeration_names_exactly_the_wrappers_readers() {
  let model = wrapping();
  let wrapped = rendered(&model);
  for emitted in model
    .emitted_methods()
    .into_iter()
    .filter(|emitted| emitted.owner_name == model.record)
  {
    assert!(
      wrapped.contains(&format!("fn {} (", emitted.name)),
      "`{}` is enumerated and not emitted",
      emitted.name
    );
  }
}

/// A field's own documentation MIGRATES onto its reader — the rewrite deletes the field it was
/// written on, and the reader is where that field's meaning is still answerable.
#[test]
fn a_manifest_fields_docs_ride_its_reader() {
  let mut model = wrapping();
  model.fields[2].docs =
    vec![syn::parse_quote!(#[doc = " The checksum, as the upstream holds it."])];
  let wrapped = rendered(&model);
  assert!(
    wrapped.contains("The checksum, as the upstream holds it."),
    "the sentence the author wrote survives the item that carried it"
  );
}

/// **THE ZERO-WORD GOLDEN.** A declaration that describes no protocol emits the tokens the rewrite
/// mode emitted before the construction vocabulary existed — these two strings, byte for byte.
///
/// They are not a description of the current implementation: they were captured off `origin/main`
/// at the commit the suite landed on, and they are the whole promise the vocabulary is free. Every
/// word in `builder(…)` is an override of a default, so if the DEFAULT ever moved, every existing
/// declaration's raise would move with it silently — this is the assertion that says so loudly.
///
/// Both shapes, because the emission has two: the CHAIN a protocol with nothing to unroll keeps,
/// and the STATEMENT form a gated link forces.
#[test]
fn the_default_law_emits_what_it_always_emitted() {
  let plain = wrapping();
  assert_eq!(
    raise(&plain).to_string(),
    "Self (upstream :: Video :: new (__ingraph_cross (row . media_id) , __ingraph_cross (row . \
     id) , __ingraph_cross (row . checksum) , __ingraph_cross (row . chapters)) . with_cover_id \
     (__ingraph_cross (row . cover_id)))",
  );

  let mut gated = wrapping();
  let last = gated.fields.len() - 1;
  gated.fields[last].condition =
    crate::model::Condition::of(vec![syn::parse_quote!(#[cfg(feature = "x")])], Vec::new());
  assert_eq!(
    raise(&gated).to_string(),
    "Self ({ let mut __ingraph_built = upstream :: Video :: new (__ingraph_cross (row . media_id) \
     , __ingraph_cross (row . id) , __ingraph_cross (row . checksum) , __ingraph_cross (row . \
     chapters)) ; # [cfg (feature = \"x\")] { __ingraph_built = __ingraph_built . with_cover_id \
     (__ingraph_cross (row . cover_id)) ; } __ingraph_built })",
  );
}

/// The raise this model emits, with one value per field read off a binding called `row`.
///
/// Shared by every protocol pin below: what changes between them is the DECLARATION, and holding
/// the values fixed is what makes the emitted call the only thing a difference can come from.
fn raise(model: &RecordModel) -> proc_macro2::TokenStream {
  let values: Vec<(syn::Ident, proc_macro2::TokenStream)> = model
    .fields
    .iter()
    .map(|field| {
      let name = field.column.source.clone();
      (name.clone(), quote::quote!(row.#name))
    })
    .collect();
  model.remote_build(&values)
}

/// One manifest column of the wrapping model, by name.
fn column<'a>(model: &'a mut RecordModel, name: &str) -> &'a mut Field {
  model
    .fields
    .iter_mut()
    .find(|field| field.column.source == name)
    .expect("a declared column")
}

/// **EACH CROSSING WORD MOVES THE ARGUMENT IT IS WRITTEN ON**, and moves nothing else.
///
/// The token level is where this can be said at all: the compiled lane proves the calls RESOLVE,
/// and these say which call was written. Both are needed — a crossing that resolved by accident
/// would pass the first and fail this.
#[test]
fn each_crossing_word_writes_the_argument_it_is_written_on() {
  let bridged = raise(&wrapping()).to_string();
  assert!(
    bridged.contains("__ingraph_cross (row . checksum)"),
    "the default is the bridge with its target inferred: {bridged}"
  );

  let mut pinned = wrapping();
  column(&mut pinned, "checksum").build.cross = Some(Cross::Into);
  assert!(
    raise(&pinned)
      .to_string()
      .contains("__ingraph_cross :: < u64 , _ > (row . checksum)"),
    "`into` pins the bridge's target to the column's own type"
  );

  let mut blanketed = wrapping();
  blanketed.construction.blanket = vec![Blanket {
    ty: syn::parse_quote!(u64),
  }];
  let claimed = raise(&blanketed).to_string();
  assert!(
    claimed.contains("__ingraph_cross :: < u64 , _ > (row . checksum)"),
    "a blanket reaches the same place, keyed by the type: {claimed}"
  );
  assert!(
    claimed.contains("__ingraph_cross (row . chapters)"),
    "and claims only the columns of that type"
  );

  // The per-column word BEATS the per-type one, which is the precedence stated in tokens.
  let mut overridden = blanketed;
  column(&mut overridden, "checksum").build.cross =
    Some(Cross::Map(syn::parse_quote!(narrow::checksum)));
  assert!(
    raise(&overridden)
      .to_string()
      .contains("narrow :: checksum (row . checksum)"),
    "`map` replaces the bridge outright"
  );

  let mut whole = wrapping();
  column(&mut whole, "cover_id").build.option = true;
  assert!(
    raise(&whole)
      .to_string()
      .contains(":: core :: option :: Option :: map (row . cover_id , __ingraph_cross)"),
    "`option` hands the seat the option and crosses the item"
  );
}

/// **EACH SEAT WORD MOVES A COLUMN BETWEEN THE PROTOCOL'S LISTS**, which is the saddle's own half of
/// the vocabulary — the writer knows only the seat it is handed.
#[test]
fn each_seat_word_moves_the_column_it_is_written_on() {
  let mut linked = wrapping();
  column(&mut linked, "checksum").build.seat = Some(Seat::With(None));
  let written = raise(&linked).to_string();
  assert!(
    written.contains(". with_checksum (__ingraph_cross (row . checksum))"),
    "a required column reaches a link: {written}"
  );
  assert!(
    !written.contains("new (__ingraph_cross (row . media_id) , __ingraph_cross (row . id) ,                        __ingraph_cross (row . checksum)"),
    "and leaves the argument list"
  );

  let mut positional = wrapping();
  column(&mut positional, "cover_id").build.seat = Some(Seat::Arg);
  let written = raise(&positional).to_string();
  assert!(
    written.contains("__ingraph_cross (row . cover_id))"),
    "an optional column reaches the argument list: {written}"
  );
  assert!(
    !written.contains("with_cover_id"),
    "and leaves the link it had by default"
  );

  let mut mutated = wrapping();
  column(&mut mutated, "checksum").build.seat = Some(Seat::Set(None));
  assert!(
    raise(&mutated)
      .to_string()
      .contains("{ __ingraph_built . set_checksum (__ingraph_cross (row . checksum)) ; }"),
    "a setter unrolls the chain and mutates the device's own binding"
  );

  let mut skipped = wrapping();
  column(&mut skipped, "checksum").build.skip = true;
  let written = raise(&skipped).to_string();
  assert!(
    !written.contains("row . checksum"),
    "a skipped column reaches no seat at all: {written}"
  );
  assert!(
    written.contains("__ingraph_cross (row . chapters)"),
    "and nothing else moved"
  );
}