ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! What a leaf error's expansion says, read off its tokens.
//!
//! Its BEHAVIOUR — what each variant renders as, that the code is the head, that the enum is
//! otherwise untouched — is asserted where it can be run: `ingraph/tests/error_macros.rs`, which
//! expands both words the way a declaring crate does. What is here is what a token stream can be
//! read for: the three items, the shape of each arm's pattern, and the fact that the whole rendering
//! is ONE literal with nothing assembled at runtime.

use super::{
  Binding, BindingAt, ErrorModel, ErrorRoad, RESERVED, Rendering, VariantModel, VariantShape,
};

/// The emitted tokens with every space taken out.
fn tokens(model: &ErrorModel) -> String {
  model.emit().to_string().split_whitespace().collect()
}

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

/// One declaration with all three variant shapes in it.
fn watch_error() -> ErrorModel {
  ErrorModel {
    name: syn::parse_quote!(WatchError),
    road: ErrorRoad::Mutation,
    variants: vec![
      VariantModel {
        name: syn::parse_quote!(NotADirectory),
        code: syn::parse_quote!("NOT_A_DIRECTORY"),
        rendering: Rendering {
          template: "NOT_A_DIRECTORY: `{__ingraph_at_0}` is not a directory".to_owned(),
          bound: vec![Binding {
            held: syn::parse_quote!(__ingraph_at_0),
            at: BindingAt::Position(0),
          }],
        },
        shape: VariantShape::Tuple,
      },
      VariantModel {
        name: syn::parse_quote!(AlreadyWatched),
        code: syn::parse_quote!("ALREADY_WATCHED"),
        rendering: Rendering {
          template: "ALREADY_WATCHED: {__ingraph_named_root} is already watched".to_owned(),
          bound: vec![Binding {
            held: syn::parse_quote!(__ingraph_named_root),
            at: BindingAt::Named(syn::parse_quote!(root)),
          }],
        },
        shape: VariantShape::Named,
      },
      VariantModel {
        name: syn::parse_quote!(ShuttingDown),
        code: syn::parse_quote!("SHUTTING_DOWN"),
        rendering: Rendering {
          template: "SHUTTING_DOWN: this deployment is winding down".to_owned(),
          bound: Vec::new(),
        },
        shape: VariantShape::Unit,
      },
    ],
  }
}

/// THREE ITEMS and no fourth — the enum itself is the author's, and the echo is the entry point's.
#[test]
fn the_expansion_is_a_display_an_error_and_a_reading() {
  let model = watch_error();
  let rendered = rendered(&model);
  let tops: Vec<&str> = rendered
    .lines()
    .filter(|line| line.starts_with("impl "))
    .collect();
  assert_eq!(
    tops,
    vec![
      "impl ::core::fmt::Display for WatchError {",
      "impl ::core::error::Error for WatchError {}",
      "impl WatchError {",
    ],
    "{rendered}"
  );
  // NO FRAMEWORK PATH is named: the whole emission is `::core`, which is why the macro has no
  // `crate = "…"` word. Asserted as the absence of the shelf's own spelling — the bindings and the
  // doc sentence carry the word `ingraph` and neither is a path.
  assert!(!rendered.contains("::ingraph"), "{rendered}");
}

/// THE RENDERING IS ONE LITERAL PER ARM, the code folded in at expansion time — so nothing at
/// runtime assembles a heading and there is one place the one-code-head law is applied.
#[test]
fn each_arm_renders_from_one_literal_with_the_code_already_in_it() {
  let model = watch_error();
  let emitted = tokens(&model);
  // A variant with nothing to interpolate needs no formatting machinery at all.
  assert!(
    emitted.contains(
      "Self::ShuttingDown=>::core::fmt::Formatter::write_str(__ingraph_f,\"SHUTTING_DOWN:\
       thisdeploymentiswindingdown\")"
    ),
    "{}",
    rendered(&model)
  );
  // One that does passes its arguments EXPLICITLY by name — implicit capture is the declaring
  // crate's edition to have.
  assert!(
    emitted.contains(
      "::core::write!(__ingraph_f,\"NOT_A_DIRECTORY:`{__ingraph_at_0}`isnotadirectory\",\
       __ingraph_at_0=__ingraph_at_0)"
    ),
    "{}",
    rendered(&model)
  );
}

/// EACH SHAPE binds the way its own variant has to be matched.
#[test]
fn every_variant_shape_is_matched_the_way_it_is_written() {
  let model = watch_error();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("Self::NotADirectory(__ingraph_at_0,..)"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("Self::AlreadyWatched{root:__ingraph_named_root,..}"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("Self::ShuttingDown=>"),
    "{}",
    rendered(&model)
  );
}

/// A FIELD THE TEMPLATE NEVER NAMED is `_` and not a binding, so it owes no `Display` — asserted
/// through a variant whose template reads its SECOND field alone.
#[test]
fn a_field_no_placeholder_named_is_never_bound() {
  let model = ErrorModel {
    variants: vec![VariantModel {
      name: syn::parse_quote!(BadDepth),
      code: syn::parse_quote!("BAD_DEPTH"),
      rendering: Rendering {
        template: "BAD_DEPTH: depth {__ingraph_at_1}".to_owned(),
        bound: vec![Binding {
          held: syn::parse_quote!(__ingraph_at_1),
          at: BindingAt::Position(1),
        }],
      },
      shape: VariantShape::Tuple,
    }],
    ..watch_error()
  };
  assert!(
    tokens(&model).contains("Self::BadDepth(_,__ingraph_at_1,..)"),
    "{}",
    rendered(&model)
  );
}

/// THE READING answers a constant per variant, and matches BLIND — it needs no field at all.
#[test]
fn the_reading_answers_a_word_and_binds_nothing() {
  let model = watch_error();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("pubconstfncode(&self)->&'staticstr"),
    "{}",
    rendered(&model)
  );
  for (pattern, word) in [
    ("Self::NotADirectory(..)", "NOT_A_DIRECTORY"),
    ("Self::AlreadyWatched{..}", "ALREADY_WATCHED"),
    ("Self::ShuttingDown", "SHUTTING_DOWN"),
  ] {
    assert!(
      emitted.contains(&format!("{pattern}=>\"{word}\"")),
      "{pattern}: {}",
      rendered(&model)
    );
  }
}

/// AN ERROR WITH NO VARIANTS is matched through the place, there being no value to match.
#[test]
fn an_error_with_no_variants_is_matched_through_the_place() {
  let model = ErrorModel {
    variants: Vec::new(),
    ..watch_error()
  };
  assert_eq!(
    tokens(&model).matches("match*self{}").count(),
    2,
    "{}",
    rendered(&model)
  );
}

/// BOTH ROADS EMIT THE SAME ITEMS — the word is what a declaration SAYS and not what it changes.
#[test]
fn the_two_roads_emit_one_thing() {
  let write = watch_error();
  let read = ErrorModel {
    road: ErrorRoad::Query,
    ..watch_error()
  };
  // The emitted ITEMS are identical; only the doc sentence differs, which is where the word lives.
  let strip = |model: &ErrorModel| {
    rendered(model)
      .lines()
      .filter(|line| !line.contains("`#[ingraph::"))
      .map(str::to_owned)
      .collect::<Vec<_>>()
  };
  assert_eq!(strip(&write), strip(&read));
  assert_eq!(ErrorRoad::Mutation.word(), "mutation_error");
  assert_eq!(ErrorRoad::Query.word(), "query_error");
}

/// THE RESERVED LIST is sorted and holds no duplicate — it is read by a linear scan and printed to a
/// reviewer, and both want the same property.
#[test]
fn the_reserved_vocabulary_is_a_sorted_set() {
  let mut sorted = RESERVED.to_vec();
  sorted.sort_unstable();
  assert_eq!(sorted, RESERVED, "the list is written in order");
  sorted.dedup();
  assert_eq!(sorted.len(), RESERVED.len(), "no word is written twice");
  for word in RESERVED {
    assert!(
      word
        .bytes()
        .all(|byte| byte.is_ascii_uppercase() || byte == b'_'),
      "`{word}` is not SCREAMING_SNAKE_CASE"
    );
  }
}