ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! WHAT THE `tracing(level = …)` WORD EMITS — the level const and the instrumented query entries.
//!
//! A suite of its own beside [`crate::tests`], for the reason the derive's per-word suites give:
//! what is asserted here is ONE word's emission — which items it grows, which gate each rides, and
//! that a build without observation gets back exactly the tokens it got before the word existed.
//!
//! Every assertion reads the emission AS WRITTEN, gates and all, rather than through
//! [`crate::tests::emission`] — because the subject IS the gate. A walk that opened it would be
//! asserting about a build rather than about what an expansion hands the compiler.

use crate::{
  model::{RecordModel, TracingLevel},
  tests::{model, whole_row},
};

/// The emission's tokens as text, which is what a gate can be read out of: a gate is a macro
/// invocation, so its contents are tokens and not items until the macro runs.
fn emitted(model: &RecordModel) -> String {
  model.emit().to_string()
}

/// A model that wrote the word.
fn observed(level: TracingLevel) -> RecordModel {
  let mut model = model("Decode", &[], "id");
  model.tracing = Some(level);
  model
}

/// **The const rides `if_tracing!` and nothing else does.** A build with no observation discards it
/// unparsed, and `Declared::TRACING`'s own default is what nothing then reads.
#[test]
fn the_level_const_rides_the_observation_gate() {
  let emission = emitted(&observed(TracingLevel::Debug));
  assert!(
    emission.contains("gate :: if_tracing"),
    "the const is not gated: {emission}"
  );
  assert!(
    emission.contains("const TRACING"),
    "no const at all: {emission}"
  );
  assert!(
    emission.contains("TracingLevel :: Debug"),
    "the declared level did not reach the emission: {emission}"
  );
}

/// **Every shipped level reaches the emission as its own variant**, read off the enum rather than
/// off a list beside it — so a level added to one and not the other fails here.
#[test]
fn every_level_emits_its_own_variant() {
  for level in TracingLevel::ALL {
    let emission = emitted(&observed(level));
    let variant = level.variant();
    assert!(
      emission.contains(&format!("TracingLevel :: {variant}")),
      "`{word}` emitted no variant: {emission}",
      word = level.as_str()
    );
  }
}

/// **A DECLARATION WITH NO WORD EMITS NO CONST**, which is the economy the `teardown` word already
/// keeps: the trait's default states `Info`, so the ONE place the default lives is the trait and a
/// silent node cannot come to disagree with it.
#[test]
fn a_silent_declaration_emits_no_const() {
  let emission = emitted(&model("Decode", &[], "id"));
  assert!(
    !emission.contains("const TRACING"),
    "a node that wrote no word states a level: {emission}"
  );
  assert!(
    !emission.contains("if_tracing"),
    "a node that wrote no word carries the gate: {emission}"
  );
}

/// **The query face's three crossing doors are written TWICE**, once inside each half of the gate
/// pair — the shape the options spine's `Deserialize` already uses, and for the same reason: an
/// attribute cannot be added by a macro that expands to nothing, and neither can a wrapper be
/// subtracted by one.
#[test]
fn the_query_doors_are_written_once_per_half() {
  let emission = emitted(&whole_row());
  assert!(emission.contains("if_tracing"), "{emission}");
  assert!(emission.contains("if_no_tracing"), "{emission}");
  // One `get_sqlite` per half, and the builder doors are outside both — they open no connection, so
  // there is nothing for a span to time.
  assert_eq!(
    emission.matches("async fn get_sqlite").count(),
    2,
    "the entry is not written once per half: {emission}"
  );
  assert_eq!(
    emission.matches("fn find_sqlite <").count(),
    1,
    "the builder door was duplicated, and it crosses to nothing: {emission}"
  );
}

/// **THE INSTRUMENTED HALF opens one span, named and fielded** — and the level is a CONSTANT, which
/// is the whole reason an emitted span can be cheaper than a framework one.
#[test]
fn the_instrumented_half_opens_a_named_span() {
  let emission = emitted(&whole_row());
  assert!(emission.contains("\"ingraph.query\""), "{emission}");
  assert!(emission.contains("tracing :: Level :: INFO"), "{emission}");
  for field in ["record", "entry", "db"] {
    assert!(
      emission.contains(&format!("{field} =")),
      "the span carries no `{field}`: {emission}"
    );
  }
  for entry in ["\"get\"", "\"insert\"", "\"upsert\""] {
    assert!(
      emission.contains(entry),
      "no door named {entry}: {emission}"
    );
  }
}

/// The DECLARED level governs the emitted span too — one knob, both halves.
#[test]
fn the_declared_level_is_the_emitted_spans_level() {
  let mut model = whole_row();
  model.tracing = Some(TracingLevel::Trace);
  let emission = emitted(&model);
  assert!(emission.contains("tracing :: Level :: TRACE"), "{emission}");
  assert!(
    !emission.contains("tracing :: Level :: INFO"),
    "the default is still being spent: {emission}"
  );
}

/// **THE DEFAULT BUILD IS UNCHANGED**, which is the G6 clause's own acceptance and the only one a
/// reader of a `git diff` cannot check by eye.
///
/// The gate-shut half is compared against the emission of the same model as it was BEFORE the word
/// existed — reconstructed by taking the shut half's tokens and the ungated remainder. What it
/// asserts is that no `tracing` name survives into a build without the feature: a shut
/// `if_tracing!` discards its tokens unparsed, and the surviving `if_no_tracing!` half names
/// nothing the library would have to supply.
#[test]
fn the_gate_shut_build_names_no_tracing() {
  let shut = shut_halves(whole_row().emit());
  assert!(!shut.is_empty(), "there is no shut half to check");
  assert!(
    !shut.contains("tracing"),
    "a build with observation off still names tracing: {shut}"
  );
  assert!(
    shut.contains("async fn get_sqlite"),
    "the shut half lost the entry it exists to keep: {shut}"
  );
}

/// Every `if_no_tracing!` group's contents, as text — what a build WITHOUT observation compiles.
///
/// A TOKEN walk rather than an item walk, and the reason is where the query face lands: an emission
/// nests its impls inside an anonymous `const`, so a gate is a `Stmt::Macro` one level down and an
/// item walk over the file's own list finds nothing. Tokens have no such layers.
fn shut_halves(tokens: proc_macro2::TokenStream) -> String {
  let mut kept = String::new();
  // Whether the ident just read was the gate's own name, so the group that follows its `!` is the
  // one to keep. Reset by every other ident, which is what makes this a match on the PAIR rather
  // than on a name appearing anywhere.
  let mut named = false;
  for tree in tokens {
    match tree {
      proc_macro2::TokenTree::Ident(ident) => named = ident == "if_no_tracing",
      proc_macro2::TokenTree::Group(group) if named => {
        kept.push_str(&group.stream().to_string());
        named = false;
      }
      proc_macro2::TokenTree::Group(group) => kept.push_str(&shut_halves(group.stream())),
      _ => {}
    }
  }
  kept
}