ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! What a KIND WORD's expansion says, and what a MODE WORD's leaves behind — read off the tokens.
//!
//! Beside `tests.rs` rather than inside it, because the subject is different in kind: that file
//! pins the FOREIGN form, whose whole expansion is one impl and whose rule is that nothing else is
//! emitted. This one pins the two things the resource axis added — the mode a declaration records,
//! and the engine a builtin word mints — and both of them are claims about items that exist.
//!
//! What a token stream cannot say is whether the delegation TYPE-CHECKS. That is
//! `ingraph/tests/resource_kind_word.rs`, which builds a real engine through a real declaration; the
//! claims here are the ones a compile cannot make, chiefly the NEGATIVE one — that no face of the
//! other mode was emitted.

use super::{ResourceKind, ResourceMode, ResourceModel};
use crate::prefix::EmissionPrefix;

/// A FOREIGN declaration, in whichever mode.
fn foreign(mode: ResourceMode) -> ResourceModel {
  ResourceModel {
    prefix: EmissionPrefix::default(),
    krate: syn::parse_quote!(::ingraph),
    name: syn::parse_quote!(MyAnn),
    kind: None,
    mode,
  }
}

/// The shipped full-text engine, declared in one word.
fn tantivy() -> ResourceModel {
  ResourceModel {
    prefix: EmissionPrefix::default(),
    krate: syn::parse_quote!(::ingraph),
    name: syn::parse_quote!(Ft),
    kind: Some(ResourceKind::Tantivy),
    mode: ResourceKind::Tantivy.mode(),
  }
}

/// The rendered expansion with every space taken out — what a claim about a PATH or a projection is
/// read off, a path long enough to wrap arriving with newlines inside its own turbofish.
fn compact(emitted: &proc_macro2::TokenStream) -> String {
  render(emitted).split_whitespace().collect()
}

/// The rendered expansion, formatted — what a failing claim prints.
fn render(emitted: &proc_macro2::TokenStream) -> String {
  prettyplease::unparse(&syn::parse2(emitted.clone()).expect("the expansion parses as a file"))
}

/// THE MODE IS IN THE RECORD, both ways round: a bare declaration is blocking and the `async` word
/// is what makes it otherwise.
///
/// This is the whole of what the word buys at this tier — the faces stay the author's — so a
/// declaration that recorded the wrong one is a binding that will spell the wrong face, which is
/// where it becomes `E0277`.
#[test]
fn the_declaration_records_which_face_its_engine_wears() {
  assert!(
    compact(&foreign(ResourceMode::Block).emit()).contains("constSYNC:bool=true;"),
    "{}",
    render(&foreign(ResourceMode::Block).emit())
  );
  assert!(
    compact(&foreign(ResourceMode::Async).emit()).contains("constSYNC:bool=false;"),
    "{}",
    render(&foreign(ResourceMode::Async).emit())
  );
}

/// A FOREIGN declaration emits the citizenship AND NOTHING ELSE — the open seam, unchanged by the
/// arrival of the kind words.
#[test]
fn the_foreign_form_emits_no_engine_impl() {
  let rendered = render(&foreign(ResourceMode::Async).emit());
  assert_eq!(
    rendered
      .lines()
      .filter(|line| line.contains("impl"))
      .count(),
    1,
    "{rendered}"
  );
  assert!(!rendered.contains("Fulltext"), "{rendered}");
  assert!(!rendered.contains("AsyncResource"), "{rendered}");
}

/// A FOREIGN declaration injects nothing, and a BUILTIN one injects the engine the word names.
#[test]
fn only_a_kind_word_mints_a_field() {
  assert!(foreign(ResourceMode::Block).carried_engine().is_none());

  let field = tantivy().carried_engine().expect("the kind word mints one");
  let rendered = quote::ToTokens::to_token_stream(&field)
    .to_string()
    .split_whitespace()
    .collect::<String>();
  assert_eq!(
    rendered, "__ig_engine__:::ingraph::__private::store::TantivyStore",
    "the injected field is the engine, through the shelf"
  );
}

/// THE FOUR ITEMS A KIND WORD EMITS, each one a delegation.
#[test]
fn the_kind_word_emits_the_construction_the_base_and_the_factory() {
  let emitted = tantivy().emit();
  let compact = compact(&emitted);
  for expected in [
    "impl::ingraph::__private::resource::AsyncResourceforFt",
    "impl::ingraph::__private::resource::DeclaredResourceforFt",
    "impl::ingraph::__private::store::FulltextEngineforFt",
    "impl::ingraph::__private::store::FulltextStoreforFt",
    "implFt",
  ] {
    assert!(
      compact.contains(expected),
      "the expansion is missing `{expected}`: {}",
      render(&emitted)
    );
  }
}

/// **THE MOUNT WEARS NO VERB**, which is the slot grain stated as an absence.
///
/// `FulltextRead::search` and `FulltextWrite::upsert` carry no slot parameter, so a face on the
/// MOUNT would have to bake one corpus name into itself — and a mount holds as many corpora as
/// elections point at it. The faces therefore belong to the per-slot HANDLE, and this is the claim
/// that the emission does not quietly grow them back.
///
/// A compile cannot make it: an extra face impl compiles perfectly well and is simply a second,
/// slot-blind road into one arbitrary corpus. MUTATION-CHECKED by writing one — a `FulltextRead for
/// Ft` beside the factory reds this test.
#[test]
fn the_mount_wears_the_factory_and_not_the_faces() {
  let rendered = render(&tantivy().emit());
  for face in [
    "FulltextRead",
    "FulltextWrite",
    "AsyncFulltextRead",
    "AsyncFulltextWrite",
  ] {
    assert!(
      !rendered.contains(&format!("{face} for Ft")),
      "the mount claimed `{face}`, which has nowhere to take a slot name: {rendered}"
    );
  }
}

/// THE NO-LIE CLAIM, and the reason this suite exists at all: the kind word carries the mode, so a
/// blocking store gets the BLOCKING construction face and no other.
///
/// The two store faces are SIBLINGS — neither is a supertrait of the other — and they differ in
/// exactly one verb, `open`, the per-slot factory being synchronous on both. So this is where the
/// mode is spent, and spending it is what ends the posture that named the awaited face regardless.
///
/// A compile cannot make the negative half: an extra impl compiles perfectly well and is simply
/// false. MUTATION-CHECKED by writing one — an `AsyncFulltextStore` arm beside this reds the test.
#[test]
fn a_blocking_kind_word_is_given_no_awaited_face() {
  let rendered = render(&tantivy().emit());
  assert!(
    !rendered.contains("AsyncFulltextStore"),
    "a blocking store claimed an awaited construction face: {rendered}"
  );
  assert!(
    compact(&tantivy().emit()).contains("constSYNC:bool=true;"),
    "and the record says so: {rendered}"
  );
}

/// EVERY SEAT OF THE BASE IS A PROJECTION off the engine's own handle, so the day the engine moves
/// one, this expansion moves with it rather than carrying a copy that drifted.
#[test]
fn the_base_delegates_every_seat_rather_than_naming_a_type() {
  let compact = compact(&tantivy().emit());
  for seat in [
    "Options",
    "SearchOptions",
    "Error",
    "Score",
    "Address",
    "Connection",
    "WriteBuffer",
    "ReadBuffer",
  ] {
    assert!(
      compact.contains(&format!(
        "type{seat}=<::ingraph::__private::store::TantivyFulltextas::ingraph::__private::store::FulltextEngine>::{seat};"
      )),
      "the `{seat}` seat is not projected: {}",
      render(&tantivy().emit())
    );
  }
}

/// The CONSTRUCTION is the store's, projected the same way, and `build` is its open.
#[test]
fn construction_is_the_stores_own() {
  let compact = compact(&tantivy().emit());
  assert!(
    compact.contains(
      "typeOptions=<::ingraph::__private::store::TantivyStoreas::ingraph::__private::store::FulltextStore>::Options;"
    ),
    "{}",
    render(&tantivy().emit())
  );
  assert!(
    compact.contains(
      "<::ingraph::__private::store::TantivyStoreas::ingraph::__private::store::FulltextStore>::open("
    ),
    "{}",
    render(&tantivy().emit())
  );
  assert!(
    compact.contains(".map(|__ig_engine__|Self{__ig_engine__})"),
    "the opened store lands in the field the injection minted: {}",
    render(&tantivy().emit())
  );
}

/// **THE SLOT NAME IS A PARAMETER AND NEVER A CONSTANT** — the ruled grain, read off the tokens.
///
/// A resource is the MOUNT and a slot is the CORPUS, named by the ELECTION that writes it. So the
/// factory TAKES the name and the expansion mints no name of its own: an earlier draft emitted
/// `pub const SLOT` off the declaration's snake name, which read the mount as a corpus and left two
/// elections of one declaration sharing one universe of BM25 statistics.
///
/// Both halves are asserted, because only the pair is the claim: a factory that took a parameter
/// and a constant beside it would still offer the collapsed road.
#[test]
fn the_factory_takes_the_corpus_name_and_mints_none() {
  let emitted = tantivy().emit();
  let compact = compact(&emitted);
  assert!(
    compact.contains(
      "fnfulltext(&self,slot:impl::core::convert::Into<::ingraph::__private::store::Utf8Bytes>,)"
    ),
    "the corpus name is not a parameter: {}",
    render(&emitted)
  );
  // The ITEM and not the word: `PER-SLOT` is prose in the emitted docs, and what must not exist is
  // a constant a caller could reach for instead of naming its own corpus.
  assert!(
    !compact.contains("constSLOT"),
    "the expansion mints a corpus name of its own: {}",
    render(&emitted)
  );
  assert!(
    compact.contains("pubfnconnection(&self)->&::ingraph::__private::store::TantivyStore"),
    "{}",
    render(&emitted)
  );
}

/// THE GATE: a kind word's whole expansion rides its engine's cargo feature, and the shut half hands
/// the author's own declaration back beside the sentence that names the fix.
#[test]
fn a_kind_words_expansion_rides_its_engines_gate() {
  let plain = quote::quote!(
    pub struct Ft;
  );
  let carrying = quote::quote!(
    pub struct Ft {
      __ig_engine__: Store,
    }
  );
  let expanded = tantivy().expand(&plain, &carrying).to_string();

  assert!(
    expanded.contains(":: ingraph :: __private :: gate :: if_tantivy !"),
    "{expanded}"
  );
  assert!(
    expanded.contains(":: ingraph :: __private :: gate :: if_no_tantivy !"),
    "{expanded}"
  );
  assert!(expanded.contains("compile_error !"), "{expanded}");
  assert!(
    expanded.contains("`tantivy` feature"),
    "the shut half names the feature: {expanded}"
  );
  assert!(
    expanded.matches("struct Ft").count() == 2,
    "the declaration survives whichever half is open: {expanded}"
  );
}

/// A FOREIGN declaration has no gate to ride and no second host: its expansion is the declaration
/// and the citizenship, which is exactly what it has always been.
#[test]
fn the_foreign_form_is_the_host_and_the_citizenship() {
  let plain = quote::quote!(
    pub struct MyAnn(MyAnnEngine);
  );
  let expanded = foreign(ResourceMode::Block)
    .expand(&plain, &quote::quote!(unreachable))
    .to_string();

  assert!(!expanded.contains("gate"), "{expanded}");
  assert!(!expanded.contains("unreachable"), "{expanded}");
  assert!(expanded.contains("struct MyAnn"), "{expanded}");
}

/// Every framework path goes through the shelf, so a declaration needs `ingraph` in its manifest and
/// nothing else — the kind word's expansion included, which names five framework traits and two
/// types.
#[test]
fn every_framework_path_a_kind_word_names_goes_through_the_shelf() {
  let emitted = tantivy().emit();
  let compact = compact(&emitted);
  for path in compact.match_indices("::ingraph::").map(|(at, _)| at) {
    assert!(
      compact[path..].starts_with("::ingraph::__private::"),
      "a framework path skips the shelf: {}",
      render(&emitted)
    );
  }
}

/// A renamed dependency moves every emitted path, in the gate invocations too — which is the one
/// place a `macro_rules!` name has to resolve rather than a type.
#[test]
fn a_renamed_crate_moves_a_kind_words_paths() {
  let model = ResourceModel {
    prefix: EmissionPrefix::default(),
    krate: syn::parse_quote!(crate::shim),
    name: syn::parse_quote!(Ft),
    kind: Some(ResourceKind::Tantivy),
    mode: ResourceMode::Block,
  };
  let expanded = model
    .expand(
      &quote::quote!(
        pub struct Ft;
      ),
      &quote::quote!(
        pub struct Ft {}
      ),
    )
    .to_string();

  assert!(
    expanded.contains("crate :: shim :: __private :: gate :: if_tantivy !"),
    "{expanded}"
  );
  assert!(!expanded.contains(":: ingraph ::"), "{expanded}");
}

/// The vocabulary has ONE home: a word the grammar can spell is a word the emitter can write.
#[test]
fn every_kind_word_resolves_to_the_kind_that_spells_it() {
  for word in ResourceKind::WORDS {
    let kind = ResourceKind::from_word(word).expect("a listed word names a kind");
    assert_eq!(kind.word(), *word);
  }
  assert!(ResourceKind::from_word("lance").is_none());
}

/// **THE INJECTED ENGINE FIELD TAKES THE SEAT**: a resource a platform's codegen built carries the
/// store under that platform's mark, in the field the injection appends AND in every emitted body
/// that reads it.
///
/// Both halves are asserted through [`ResourceModel::carried_engine`] and the expansion beside it,
/// because they are the pair the module's own doc calls one function: a field appended under one
/// spelling and read under another compiles to `E0609` inside somebody else's declaration.
#[test]
fn a_platform_mark_moves_the_injected_engine_field() {
  let mut model = tantivy();
  model.prefix = EmissionPrefix::new("__mg");

  let field = model
    .carried_engine()
    .expect("a builtin kind injects its engine");
  assert_eq!(
    field.ident.as_ref().expect("a named field").to_string(),
    "__mg_engine__",
  );

  let rendered = compact(&model.emit());
  assert!(
    rendered.contains("__mg_engine__"),
    "the bodies read the moved field"
  );
  assert!(
    !rendered.contains("__ig_engine__"),
    "and no body still reads `ingraph`'s spelling of it",
  );
}