ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! What the FOLD writes, read off the tokens — the half of the emission a live lane cannot show.
//!
//! `ingraph/tests/aggregate_recompute.rs` drives the whole kind against a real table and proves the
//! ANSWERS are right. What it cannot see is the SHAPE of the call that produced them: a fold reached
//! through an inferred `self.fold(…)` and one reached through `<F as Measure<T>>::fold(…)` compute
//! the same value, and only one of them is the static monomorphized call the closed design ruled
//! for. So the two suites split by what each can witness — answers there, call shape here.

use quote::ToTokens as _;

use crate::{
  aggregate::{AggregateModel, Grouped, Measure, Measured},
  model::Projection,
};

/// A model over one group column and the measures named, with nothing else true about it.
///
/// `over` in the model's own suite builds the same shape and this one differs in the two things the
/// fold reads: the measure's fold and its `from` seat. Beside it rather than shared, because a
/// helper serving both would have to take every field either one varies.
fn folding(measures: &[(&str, Measure, Option<&str>)]) -> AggregateModel {
  let ident = |name: &str| syn::Ident::new(name, proc_macro2::Span::call_site());
  AggregateModel {
    aggregate: ident("CodecCensus"),
    vis: syn::parse_quote!(pub),
    krate: syn::parse_quote!(::ingraph),
    krate_spelled: None,
    upstream: syn::parse_quote!(demux::Track),
    groups: vec![Grouped {
      field: ident("codec"),
      from: ident("codec_name"),
      ty: syn::parse_quote!(Codec),
      projection: Projection::Borrowed,
    }],
    measures: measures
      .iter()
      .map(|(field, by, from)| Measured {
        field: ident(field),
        by: by.clone(),
        from: from.map(ident),
        ty: syn::parse_quote!(u64),
        projection: Projection::Borrowed,
      })
      .collect(),
    triggers: proc_macro2::TokenStream::new(),
    stores: proc_macro2::TokenStream::new(),
    graphql: None,
  }
}

/// The fold's tokens, rendered without the spacing `to_string` puts in.
fn tight(model: &AggregateModel) -> String {
  model.fold().to_string().replace(' ', "")
}

/// **THE GROUP COLUMN IS READ THROUGH THE UPSTREAM'S OWN ACCESSOR**, by the name the `group(…)`
/// entry gave it and not by the field it fills.
///
/// The two spellings are two facts — a name this declaration chose, and a column the upstream owns —
/// and the whole reason `group(…)` writes both out even when they match is that they need not. So
/// the read names the UPSTREAM's, fully qualified through its path so it cannot pick up an inherent
/// method of something else in scope.
#[test]
fn a_group_column_is_read_off_the_upstream_by_the_name_the_entry_gave() {
  let emitted = tight(&folding(&[("count", Measure::Counting, None)]));

  assert!(
    emitted.contains("demux::Track::codec_name_ref(__ig_row)"),
    "the read is the upstream's accessor, qualified: {emitted}"
  );
  assert!(
    !emitted.contains("codec_ref"),
    "and never this declaration's own field name: {emitted}"
  );
}

/// **THE MEASURE CALL IS STATIC AND FULLY QUALIFIED**, with the item type WRITTEN.
///
/// The closed design's ruling for T4's call shape, read off the tokens. `Counting` implements the
/// trait at every item type there is, so an inferred call over it is `E0282` — its own `NAME` const
/// records that measurement one crate over — and the emission therefore never leaves the parameter
/// to inference.
#[test]
fn a_measure_is_called_statically_with_its_item_type_written() {
  let emitted = tight(&folding(&[("count", Measure::Counting, None)]));

  assert!(
    emitted.contains("<::ingraph::__private::measure::Countingas::ingraph::__private::measure::Measure<&demux::Track>>::fold"),
    "the citizen, the trait and the item type are all named: {emitted}"
  );
}

/// **A CITIZEN AND A QUOTED PATH ARRIVE AT ONE CONSTRUCTION** — `Default`, which is the elected
/// fold's own line one kind over.
///
/// A bare word names a framework citizen and a path names the declaring crate's own type. The
/// shorthand resolves at the emission, which is the one place that knows where the shelf is, and
/// neither arm is privileged after that.
#[test]
fn a_shipped_word_and_a_declared_path_are_both_default_constructed() {
  let shipped = tight(&folding(&[("count", Measure::Counting, None)]));
  assert!(
    shipped
      .contains("<::ingraph::__private::measure::Countingas::core::default::Default>::default()"),
    "{shipped}"
  );

  let declared = tight(&folding(&[(
    "peak",
    Measure::Declared(syn::parse_quote!(app::Largest)),
    None,
  )]));
  assert!(
    declared.contains("<app::Largestas::core::default::Default>::default()"),
    "the path is emitted verbatim for rustc to resolve: {declared}"
  );
}

/// **`Owed` DECIDES WHAT THE SLICE IS** — a column's values where the fold reads one, the group's
/// ROWS where it reads none.
///
/// The axis the grammar checked the `from` seat against, answering the emission's own question one
/// step later. `counting` is handed the rows because it answers how many there are about items of
/// every type there is; `summing` is handed the named column's values, cloned out of each row.
#[test]
fn the_slice_a_fold_is_handed_is_what_it_owes_its_entry() {
  let counted = tight(&folding(&[("count", Measure::Counting, None)]));
  assert!(
    counted.contains(">::fold(&<::ingraph::__private::measure::Countingas::core::default::Default>::default(),&__ig_held)"),
    "counting folds the group's rows: {counted}"
  );

  let summed = tight(&folding(&[("bytes", Measure::Summing, Some("size"))]));
  assert!(
    summed.contains("demux::Track::size_ref(__ig_row)"),
    "summing reads the column its entry named: {summed}"
  );
  assert!(
    summed.contains("&__ig_column)"),
    "and is handed that column's values rather than the rows: {summed}"
  );
}

/// **EVERY DECLARED COLUMN IS FILLED**, group and measure alike, in one struct literal.
///
/// The row shape's own claim at the emission: a column the fold left out would be `E0063` inside an
/// expansion, which is the failure a `..Default::default()` would have hidden.
#[test]
fn one_row_per_group_fills_every_column_the_declaration_wrote() {
  let emitted = tight(&folding(&[
    ("count", Measure::Counting, None),
    ("bytes", Measure::Summing, Some("size")),
  ]));

  assert!(emitted.contains("Self{codec,count:"), "{emitted}");
  assert!(emitted.contains("bytes:"), "{emitted}");
  assert!(
    !emitted.contains("Default::default()}"),
    "no struct-update tail hides a column nobody filled: {emitted}"
  );
}

/// **THE PARTITION IS A LINEAR PROBE OVER `PartialEq`**, and demands nothing more of a group type.
///
/// Hashing would demand `Hash + Eq` of every group column and sorting would demand `Ord`, and the
/// answer is the same either way. What the probe buys is that a column keyed by a type with an
/// equality and no ordering is declarable at all — so the absence of the two heavier bounds is the
/// claim, and it is read as the absence of the calls that would have needed them.
#[test]
fn the_groups_are_found_by_equality_and_nothing_heavier() {
  let emitted = tight(&folding(&[("count", Measure::Counting, None)]));

  assert!(
    emitted.contains("__ig_groups.iter_mut().find(|(__ig_seen,_)|*__ig_seen==__ig_key)"),
    "{emitted}"
  );
  for heavier in ["HashMap", "BTreeMap", "sort_by", "Hash", "cmp"] {
    assert!(
      !emitted.contains(heavier),
      "the fold reaches for no `{heavier}`: {emitted}"
    );
  }
}

/// **THE VISIBILITY AND THE UPSTREAM ARE THE DECLARATION'S** — the fold is as reachable as the type
/// it answers with, and it takes the node the head named.
#[test]
fn the_fold_is_as_visible_as_the_declaration_and_takes_its_upstream() {
  let model = folding(&[("count", Measure::Counting, None)]);
  let emitted = tight(&model);

  assert!(
    emitted.contains("pubfnfold(__ig_rows:&[demux::Track])->::std::vec::Vec<Self>"),
    "{emitted}"
  );
  assert_eq!(
    model.vis.to_token_stream().to_string(),
    "pub",
    "the visibility read back is the one the declaration wrote",
  );
}