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
//! **`locate`'s FULL FORM** — `locate(thumb(family = "…", data))`, as the grammar reads it and as it
//! refuses it.
//!
//! A suite beside [`crate::locate_tests`] rather than inside it, because what is asserted here is a
//! form that suite pinned as REFUSED. Holding the two apart is what makes the reversal legible: the
//! shorthand's rules are unchanged and are still measured next door, and every claim about the form
//! that was un-refused is here.
//!
//! # The claim the whole file is arranged around
//!
//! The ASK is on the ENTITY and the PERMIT is on the FAMILY. Only the first of those is grammar, so
//! only the first is measurable here — what the family permits is a bound, and `ingraph`'s
//! `artifact_ask` suite is where a compiler refuses an ask no family answered. What this file
//! measures is that the word reaches the model, that its wire name is carried verbatim where one was
//! written and left for the face to resolve where none was, and that nothing else in the head
//! changed shape underneath it.
//!
//! # Every accepting test states an EXCLUSION
//!
//! [`crate::locate_tests`]' own rule, and it is the same rule for the same reason: the form was
//! added to an entry reader that already had one, next door to a word it shares a namespace with. A
//! new form's failure mode is that it consumes a neighbour or is consumed by one, and a model
//! assertion about the new field alone cannot see that.

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

use crate::host;

/// The pass under test, at the kind this word is about.
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(),
        artifact
          .family
          .to_token_stream()
          .to_string()
          .replace(' ', ""),
      )
    })
    .collect()
}

/// What each position ASKED for: [`None`] where it wants the address alone, and otherwise the wire
/// name it wrote or `""` where it left the default to the face.
fn asks(model: &RecordModel) -> Vec<Option<String>> {
  model
    .artifacts
    .iter()
    .map(|artifact| {
      artifact
        .data
        .as_ref()
        .map(|data| data.name().unwrap_or_default().to_owned())
    })
    .collect()
}

/// EVERY refusal a declaration raised, as sentences.
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 RULING'S OWN DECLARATION** — `locate(thumb(family = "Poster", data))` reaches the model as
/// a position that names its family and asks for the bytes.
///
/// The ask carries NO NAME, which is the default rather than a gap: `<domain-word>Data` is resolved
/// at the wire face, where the framework's one camelCase authority lives.
#[test]
fn the_full_form_reaches_the_model_as_a_family_and_an_ask() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite,
      lineage(fields(media)),
      graphql(async_graphql),
      derived(tracks = "app::Track"),
      locate(thumb(family = "app::Poster", data)),
    )]
    struct Frame { #[ingraph(id)] at: i64, media: String }
  })
  .expect("the ruling's own declaration");

  assert_eq!(
    artifacts(&model),
    [("thumb".to_owned(), "app::Poster".to_owned())],
    "the family is what `family = \"…\"` named"
  );
  assert_eq!(
    asks(&model),
    [Some(String::new())],
    "the ask is present and names no field, which is the default"
  );

  // THE EXCLUSION: the sibling next door and the wire face are untouched by a form that was
  // refused until this round.
  assert_eq!(
    model
      .derived
      .iter()
      .map(|position| position.name.to_string())
      .collect::<Vec<_>>(),
    ["tracks"],
    "the reverse container beside it still reads its own entry"
  );
  assert!(
    model.graphql.is_some(),
    "and the wire face is still declared"
  );
}

/// **THE RENAME REACHES THE MODEL VERBATIM** — `data = "thumbBytes"` is what a client sees, and
/// nothing here camelCases a name a declaration chose.
#[test]
fn a_named_ask_carries_its_wire_field_verbatim() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite,
      lineage(fields(media)),
      graphql(async_graphql),
      locate(thumb(family = "app::Poster", data = "thumbBytes")),
    )]
    struct Frame { #[ingraph(id)] at: i64, media: String }
  })
  .expect("the rider's own spelling");

  assert_eq!(asks(&model), [Some("thumbBytes".to_owned())]);
}

/// **THE FULL FORM WITHOUT AN ASK IS THE SHORTHAND WRITTEN LONG**, and it is accepted for the
/// same-reader law's reason: `derived(…)`'s full form takes its source word alone, so refusing the
/// analogue here would be the two words diverging at the one place they were joined.
#[test]
fn a_full_form_that_asks_for_nothing_is_the_shorthand() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite,
      lineage(fields(media)),
      graphql(async_graphql),
      locate(card = "app::Card", poster(family = "app::Poster")),
    )]
    struct Frame { #[ingraph(id)] at: i64, media: String }
  })
  .expect("both spellings in one block");

  assert_eq!(
    artifacts(&model),
    [
      ("card".to_owned(), "app::Card".to_owned()),
      ("poster".to_owned(), "app::Poster".to_owned()),
    ],
    "two forms, one block, one order"
  );
  assert_eq!(
    asks(&model),
    [None, None],
    "and neither of them asked for bytes"
  );
}

/// **THE TWO FORMS MIX, AND THE ASK FOLLOWS THE POSITION THAT WROTE IT.** One block, three
/// positions, one ask — so a reader can see that the word is per-position rather than per-block.
#[test]
fn the_ask_belongs_to_the_position_that_wrote_it() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite,
      lineage(fields(media)),
      graphql(async_graphql),
      locate(
        card = "app::Card",
        poster(family = "app::Poster", data),
        sheet(family = "app::Sheet", data = "sheetBytes"),
      ),
    )]
    struct Frame { #[ingraph(id)] at: i64, media: String }
  })
  .expect("three positions, three spellings");

  assert_eq!(
    asks(&model),
    [None, Some(String::new()), Some("sheetBytes".to_owned())],
    "the address alone, the default name, and the written one"
  );
}

/// **A BLOCK NAMING NO FAMILY IS REFUSED AT THE OPTION IT LEFT OUT.** The author has the form right
/// and omitted the one word that is not optional, so the sentence names that word rather than
/// restating both spellings of an entry.
#[test]
fn refuses_a_full_form_that_names_no_family() {
  for written in [
    quote::quote!(locate(card())),
    quote::quote!(locate(card(data))),
    quote::quote!(locate(card(data = "cardBytes"))),
  ] {
    let refused = refusals(&syn::parse_quote! {
      #[ingraph(#written)]
      struct Frame { #[ingraph(id)] at: i64 }
    });
    assert!(
      names(
        &refused,
        "an artifact position's full form names the family it addresses"
      ) && names(&refused, "`family = \"path::to::Family\"`"),
      "{written}: {refused:?}"
    );
  }
}

/// **`family` IS A TYPE PATH IN A STRING**, and a bare word or a non-path earns the option's own
/// sentence rather than the entry's.
#[test]
fn refuses_a_family_that_is_not_a_type_path() {
  for written in [
    quote::quote!(locate(card(family = Card, data))),
    quote::quote!(locate(card(family = "not a path", data))),
    quote::quote!(locate(card(family, data))),
  ] {
    let refused = refusals(&syn::parse_quote! {
      #[ingraph(#written)]
      struct Frame { #[ingraph(id)] at: i64 }
    });
    assert!(
      names(
        &refused,
        "`family` names the `#[ingraph::blob]` node this position addresses"
      ),
      "{written}: {refused:?}"
    );
  }
}

/// **THE ASK TAKES ITS OWN THREE SHAPES AND NOTHING ELSE**, and a value that is not a word is
/// refused with all three spellings and the default named.
///
/// The asymmetry with the FAMILY's own `data` — bare there, and may carry more here — is what the
/// two words are: a permission has nothing to say about a schema, and an ask mints a field, may be
/// told what to call it, and may be signed for as non-null.
///
/// `data(rename = "bytes")` LEFT this list in the index-graphql round: the block form is a real
/// spelling now, and what it carries is the `required` signature beside the name. An empty `()` is
/// the block with nothing in it, which the shared block reader takes as the bare word.
#[test]
fn refuses_an_ask_that_carries_anything_but_a_name() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(locate(card(family = "app::Card", data = 4096)))]
    struct Frame { #[ingraph(id)] at: i64 }
  });
  assert!(
    names(
      &refused,
      "the `data` ask is written bare, `data = \"thumbBytes\"` to name the wire field"
    ) && names(&refused, "The default name is `<name>Data`"),
    "{refused:?}"
  );
}

/// **THE BLOCK FORM CARRIES A NAME AND A SIGNATURE**, and refuses everything else by name.
#[test]
fn the_ask_block_takes_a_rename_and_the_required_word() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite, locate(card(family = "app::Card", data(rename = "cardBytes", required))))]
    struct Frame { #[ingraph(id)] at: i64 }
  })
  .expect("the block form is legal");
  let bytes = model.artifacts[0]
    .data
    .as_ref()
    .expect("the position asked");
  assert_eq!(bytes.name(), Some("cardBytes"));
  assert!(bytes.required());

  // The BARE ask keeps the shipped nullable answer, which is the exclusion that makes the claim
  // above about the WORD rather than about the block.
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite, locate(card(family = "app::Card", data)))]
    struct Frame { #[ingraph(id)] at: i64 }
  })
  .expect("the bare ask is legal");
  let bytes = model.artifacts[0]
    .data
    .as_ref()
    .expect("the position asked");
  assert_eq!(bytes.name(), None);
  assert!(!bytes.required());

  let refused = refusals(&syn::parse_quote! {
    #[ingraph(locate(card(family = "app::Card", data(nullable))))]
    struct Frame { #[ingraph(id)] at: i64 }
  });
  assert!(
    names(&refused, "There is no word for the nullable form"),
    "the one-way law is in the sentence: {refused:?}"
  );
}

/// **ONE ASK PER POSITION**, exactly as one position takes one name.
#[test]
fn refuses_a_repeated_ask() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(locate(card(family = "app::Card", data, data = "cardBytes")))]
    struct Frame { #[ingraph(id)] at: i64 }
  });
  assert!(
    names(
      &refused,
      "`data` is declared more than once in an artifact position"
    ),
    "{refused:?}"
  );
}

/// **ONE `family` PER POSITION**, for the reason a repeated option always earns: one option, one
/// value.
#[test]
fn refuses_a_repeated_family() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(locate(card(family = "app::Card", family = "app::Poster")))]
    struct Frame { #[ingraph(id)] at: i64 }
  });
  assert!(
    names(
      &refused,
      "`family` is declared more than once in an artifact position"
    ),
    "{refused:?}"
  );
}

/// **TWO ASKS MAY NOT NAME ONE FIELD.** The namespace rule one word over: an ask mints a name on the
/// same face the position does, so two positions naming one field is one name on one face.
///
/// What is NOT checked is a written name colliding with another position's DEFAULT — see
/// `parse::locate_model`, whose note says why that boundary is where the camelCase authority is.
#[test]
fn refuses_two_asks_naming_one_wire_field() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(locate(
      card(family = "app::Card", data = "bytes"),
      poster(family = "app::Poster", data = "bytes"),
    ))]
    struct Frame { #[ingraph(id)] at: i64 }
  });
  assert!(
    names(
      &refused,
      "`bytes` is the wire field `card` already asks for"
    ) && names(&refused, "One namespace per face"),
    "{refused:?}"
  );
}

/// **AN UNKNOWN OPTION IS REFUSED WITH THE TWO WORDS THE FORM TAKES**, and a near miss of either is
/// suggested — the position's own vocabulary, per the near-miss line's rule that no position may be
/// added without deciding what a typo of its words looks like.
#[test]
fn refuses_an_unknown_option_and_suggests_the_near_miss() {
  let refused = refusals(&syn::parse_quote! {
    #[ingraph(locate(card(famly = "app::Card", data)))]
    struct Frame { #[ingraph(id)] at: i64 }
  });
  assert!(
    names(&refused, "unknown entry in an artifact position")
      && names(&refused, "did you mean `family`"),
    "{refused:?}"
  );
}