ingraph-derive 0.1.0

The attribute and derive macros for ingraph: the words a record, node, key, filter and vocabulary declaration is written in.
Documentation
//! **THE `locate` WORD** — the record head's artifact positions, as the grammar reads them and as
//! it refuses them.
//!
//! A suite of its own beside [`crate::tests`], for the reason the other per-word suites give: what
//! is asserted here is ONE word's grammar — the form it takes, the four ways of writing that form
//! wrongly, and the two rules the assembly holds it to — and holding that apart from the record
//! suite's own rule table keeps a change to either visible.
//!
//! # Every accepting test states an EXCLUSION, and that is what this suite is really for
//!
//! `locate(…)` was added to a head walk that already reads a dozen words, next door to the one it
//! is a sibling of. The failure mode a new entry in such a walk has is not that it fails to parse —
//! it is that it CONSUMES a neighbour, or that a neighbour consumes it, and the declaration still
//! compiles with one word silently gone. A model assertion about `artifacts` alone cannot see that.
//! So every test below that accepts a declaration also asserts what `derived(…)`, `graphql(…)` and
//! `lineage(…)` reached the model as, in the same declaration.
//!
//! # The word's OWN sibling relationship is the second subject
//!
//! `derived(…)` names what points BACK at this record and `locate(…)` names what was derived FROM
//! it. Both mint a word on one wire face and neither declares a Rust field, so the two share a
//! namespace — which is a rule about the PAIR rather than about either word, and
//! [`refuses_a_family_that_repeats_a_reverse_position`] is the only place it is asserted.

use ingraph_codegen::prelude::*;
use quote::ToTokens as _;

use crate::host;

/// The pass under test, at the kind this word is about — a record, being what the ruling puts the
/// word on.
fn record(input: &syn::DeriveInput) -> syn::Result<RecordModel> {
  let (host, options) = host::split(input);
  crate::parse::parse(&host, &options, NodeKind::Record)
}

/// The artifact positions of a model, as `<name> = <family>` pairs in declaration order.
fn artifacts(model: &RecordModel) -> Vec<(String, String)> {
  model
    .artifacts
    .iter()
    .map(|artifact| (artifact.name.to_string(), rendered(&artifact.family)))
    .collect()
}

/// A path as it would be written, with the token spacing removed.
fn rendered(path: &syn::Path) -> String {
  path.to_token_stream().to_string().replace(' ', "")
}

/// EVERY refusal a declaration raised, as sentences — a `locate` mistake usually fires beside the
/// neighbour it was written next to, and `Display` on a combined [`syn::Error`] yields only the
/// first.
fn refusals(input: &syn::DeriveInput) -> Vec<String> {
  record(input)
    .expect_err("this declaration is refused")
    .into_iter()
    .map(|error| error.to_string())
    .collect()
}

/// Whether any of `messages` names `rule`.
fn names(messages: &[String], rule: &str) -> bool {
  messages.iter().any(|message| message.contains(rule))
}

/// **THE BLOCK REACHES THE MODEL AS ITS FAMILIES**, in the order they were written — and the three
/// words written beside it reach the model as themselves.
///
/// The ruling's own declaration, verbatim: several entries, each a domain word this record mints,
/// each naming the path to a blob node's TYPE.
#[test]
fn a_locate_block_reaches_the_model_as_its_families() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite,
      lineage(fields(media)),
      graphql(async_graphql),
      derived(tracks = "app::Track"),
      locate(card = "app::Card", poster = "app::Poster"),
    )]
    struct Frame { #[ingraph(id)] at: i64, media: String }
  })
  .expect("the ruling's own declaration is the one this word exists for");

  assert_eq!(
    artifacts(&model),
    [
      ("card".to_owned(), "app::Card".to_owned()),
      ("poster".to_owned(), "app::Poster".to_owned()),
    ],
    "one entry per artifact, several allowed, in the order they were written"
  );

  // THE EXCLUSION: the three neighbours, read out of the same model.
  assert_eq!(
    model
      .derived
      .iter()
      .map(|position| position.name.to_string())
      .collect::<Vec<_>>(),
    ["tracks"],
    "the reverse container beside it is untouched"
  );
  assert!(
    model.graphql.is_some(),
    "and the wire face is still declared"
  );
  assert_eq!(
    model
      .lineage
      .iter()
      .flat_map(|lineage| lineage.path().iter())
      .map(|column| column.name.to_string())
      .collect::<Vec<_>>(),
    ["media"],
    "and the lineage still names its field"
  );
}

/// **THE WORD IS OPTIONAL, AND ITS ABSENCE IS EMPTY** — a record nothing was derived from writes no
/// block, and every neighbour means what it meant before the word existed.
///
/// The compatibility half: this is the declaration every record in the tree already is, and its
/// model must not have changed shape under it.
#[test]
fn a_record_that_wrote_no_word_locates_nothing() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite,
      lineage(fields(media)),
      graphql(async_graphql),
      derived(tracks = "app::Track"),
    )]
    struct Frame { #[ingraph(id)] at: i64, media: String }
  })
  .expect("a record with no artifact family is spelled by omitting the block");

  assert!(
    model.artifacts.is_empty(),
    "absence by omission, with no sentinel"
  );
  assert_eq!(
    model
      .derived
      .iter()
      .map(|position| position.name.to_string())
      .collect::<Vec<_>>(),
    ["tracks"],
    "and the sibling that WAS written is still read"
  );
  assert!(model.graphql.is_some(), "the wire face too");
  assert_eq!(
    model
      .lineage
      .iter()
      .flat_map(|lineage| lineage.path().iter())
      .count(),
    1,
    "and the lineage"
  );
}

/// **ONE FAMILY MAY BE THE WHOLE BLOCK**, and the word neither needs a sibling beside it nor takes
/// one over: `derived(…)` is absent here, and that changes nothing about how `locate(…)` is read.
#[test]
fn one_family_is_a_whole_block_without_the_sibling() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media)), graphql(async_graphql), locate(thumb = "app::Thumbnail"))]
    struct Frame { #[ingraph(id)] at: i64, media: String }
  })
  .expect("one artifact family is a declaration");

  assert_eq!(
    artifacts(&model),
    [("thumb".to_owned(), "app::Thumbnail".to_owned())]
  );
  assert!(
    model.derived.is_empty(),
    "the sibling was not written, and the word did not write one"
  );
  assert!(model.graphql.is_some(), "the wire face is still declared");
  assert!(model.lineage.is_some(), "and so is the lineage");
}

/// **ONE POSITION, ONE NAME.** A word minted twice inside one block names one address twice.
#[test]
fn refuses_a_repeated_family_name() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(locate(card = "app::Card", card = "app::Poster"))]
    struct Frame { #[ingraph(id)] at: i64 }
  });
  assert!(
    names(
      &refused,
      "`card` is declared more than once in `locate(…)` — one position, one name"
    ),
    "the refusal counts the word: {refused:?}"
  );
}

/// **ONE BLOCK CARRIES EVERY FAMILY**, exactly as one block carries every reverse position.
#[test]
fn refuses_a_second_locate_block() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(locate(card = "app::Card"), locate(poster = "app::Poster"))]
    struct Frame { #[ingraph(id)] at: i64 }
  });
  assert!(
    names(
      &refused,
      "`locate(…)` is declared more than once — one block carries every artifact family"
    ),
    "the refusal is about the block: {refused:?}"
  );
}

/// **THE RIGHT SIDE IS A PATH IN A STRING LITERAL**, and every way of writing something else earns
/// the one sentence that says which half is which.
#[test]
fn refuses_a_family_that_is_not_a_path_in_a_string() {
  for written in [
    quote::quote!(locate(card = 3)),
    quote::quote!(locate(card = "not a path")),
    quote::quote!(locate(card)),
  ] {
    let refused = refusals(&syn::parse_quote! {
      #[ingraph(#written)]
      struct Frame { #[ingraph(id)] at: i64 }
    });
    assert!(
      names(
        &refused,
        "an artifact position is `<name> = \"path::to::Family\"`"
      ) && names(&refused, "the TYPE, not a field inside it"),
      "the refusal names the form and the thing the path points at: {refused:?}"
    );
  }
}

/// **THE LEFT SIDE IS A WORD THIS RECORD MINTS**, so a path there is not a spelling mistake — it is
/// the entry read backwards, and the sentence says what the left side is for.
#[test]
fn refuses_a_multi_segment_left_side() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(locate(app::Card = "app::Card"))]
    struct Frame { #[ingraph(id)] at: i64 }
  });
  assert!(
    names(
      &refused,
      "the left side of an artifact position is a WORD this record mints"
    ) && names(&refused, "The TYPE goes on the right"),
    "the refusal names both sides: {refused:?}"
  );
}

/// **THE SIBLING'S OWN OPTION WORDS ARE REFUSED BY NAME**, and their reason survives the round that
/// un-refused the form around them: a family is named by its type, and it is derived from one
/// upstream, so both of `derived(…)`'s options are answered before they can be asked.
///
/// The FORM they are written in is legal now — see [`crate::locate_full_form_tests`] — so what this
/// measures is that un-refusing the block did not admit the sibling's vocabulary with it.
#[test]
fn refuses_the_siblings_option_words_by_name() {
  for written in [
    quote::quote!(locate(card(type = "app::Card"))),
    quote::quote!(locate(card(family = "app::Card", field = "at"))),
  ] {
    let refused = refusals(&syn::parse_quote! {
      #[ingraph(#written)]
      struct Frame { #[ingraph(id)] at: i64 }
    });
    assert!(
      names(
        &refused,
        "`type` and `field` are `derived(…)`'s option words"
      ) && names(&refused, "no second `ref` column for a `field` to select"),
      "the refusal names the words it is refusing and why: {refused:?}"
    );
  }
}

/// **A BLOCK NAMING NO FAMILY IS REFUSED AT THE ASSEMBLY**, exactly as its sibling's empty block is
/// — a record nothing was derived from is spelled by omitting the word.
#[test]
fn refuses_a_locate_block_naming_no_family() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(locate())]
    struct Frame { #[ingraph(id)] at: i64 }
  });
  assert!(
    names(
      &refused,
      "`locate(…)` names the artifact families this record answers an address for, and it names \
       none"
    ) && names(&refused, "spelled by omitting the block"),
    "the refusal is about the record's families: {refused:?}"
  );
}

/// **A FAMILY MAY NOT TAKE A FIELD'S NAME.** There is no Rust field for an address, so nothing
/// collides in the struct; what collides is the FACE.
#[test]
fn refuses_a_family_that_takes_a_fields_name() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(locate(media = "app::Card"))]
    struct Frame { #[ingraph(id)] at: i64, media: String }
  });
  assert!(
    names(&refused, "`media` is already a field of this record")
      && names(
        &refused,
        "One namespace per face: rename the artifact, or the field"
      ),
    "the refusal names the half the word was already spent on: {refused:?}"
  );
}

/// **A FAMILY MAY NOT TAKE A REVERSE POSITION'S NAME EITHER** — the rule about the PAIR, and the
/// only place the two fieldless words are held to one namespace.
#[test]
fn refuses_a_family_that_repeats_a_reverse_position() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(derived(cover = "app::CoverRow"), locate(cover = "app::Cover"))]
    struct Frame { #[ingraph(id)] at: i64 }
  });
  assert!(
    names(
      &refused,
      "`cover` is already a reverse position this record declares"
    ) && names(
      &refused,
      "One namespace per face: rename the artifact, or the reverse position"
    ),
    "the refusal names the sibling: {refused:?}"
  );
}

/// **A REVERSE POSITION THAT WAS ITSELF DROPPED MINTS NOTHING**, so an artifact may take its word:
/// the assembly reads the SETTLED positions, and a position refused for taking a field's name is
/// not a name this record ever answered for.
///
/// One refusal for one mistake — the alternative is a declaration whose author fixes the field
/// collision and finds a second sentence waiting about a word nobody kept.
#[test]
fn a_dropped_reverse_position_leaves_its_word_free() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(derived(media = "app::Track"), locate(media = "app::Card"))]
    struct Frame { #[ingraph(id)] at: i64, media: String }
  });
  assert!(
    names(&refused, "`media` is already a field of this record"),
    "the field collision is reported: {refused:?}"
  );
  assert!(
    !names(&refused, "already a reverse position this record declares"),
    "and the dropped position raises no second one: {refused:?}"
  );
}

/// **THE WORD JOINED THE HEAD'S VOCABULARY**, which is what makes a typo of it a near miss rather
/// than an unknown attribute with no road out.
#[test]
fn a_near_miss_of_the_word_is_named() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(locat(card = "app::Card"))]
    struct Frame { #[ingraph(id)] at: i64 }
  });
  assert!(
    names(&refused, "did you mean `locate`?"),
    "the head's suggestion list carries the word: {refused:?}"
  );
  assert!(
    names(&refused, "`derived(…)`, `locate(…)`"),
    "and the sentence listing what a record takes names it beside its sibling: {refused:?}"
  );
}