ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! **THE COMPARISON FACE, BEFORE AND AFTER THE THIRD FOLD** — the emitters called for real, and
//! what they render pinned as bytes.
//!
//! The rewire this file stands on is INTERNAL: `interface/page.rs`'s `<I><Db>Comparison` was a
//! near-duplicate of `unit::comparison` + `unit::comparison_lowering`, and becomes a caller of them.
//! Nothing about that is supposed to move a byte of the OTHER two doors' faces, and a sentence
//! saying so is not a proof — so [`THE_UNITS_COMPARISON`] is what the shared emitters rendered
//! BEFORE the fold, captured verbatim, and [`the_units_comparison_is_the_byte_it_was`] demands those
//! exact bytes back.
//!
//! It is a tripwire on purpose. Those emitters are the RECORD's comparison and the bare
//! `#[derive(ingraph::Comparison)]`'s as much as the interface's — `ingraph-derive`'s
//! `the_comparison_face_is_one_emission` is what pins those two doors to each other, and this pins
//! the emission they share to the byte — so a change made for the interface that moves a record's
//! predicate fails here rather than in a consumer's build. A round that means to move a byte
//! recaptures this fixture, which is what makes such a move deliberate.
//!
//! # The interface's own face is pinned beside it, and it is the one expected to move
//!
//! [`THE_INTERFACES_COMPARISON`] is the same capture over `interface/page.rs`'s own emission,
//! reached through a REAL `InterfaceModel::emit()` rather than through hand-built tokens. The fold's
//! whole COST is the diff of that one file: what the near-duplicate said in its own words, and what
//! the shared emitter says instead.
//!
//! The two fixtures are then read AGAINST each other, which is what turns the by-construction
//! argument into something a test can fail:
//! [`the_interfaces_comparison_speaks_the_units_sentences`] demands that every sentence the SHAPE
//! owns appears verbatim in both, and
//! [`the_interfaces_own_paragraph_survives_and_the_shape_never_learned_it`] demands that the
//! contract's own paragraph appears in one alone.
//!
//! # Why an emitted-token pin rather than a schema one
//!
//! A comparison carries no async-graphql derive — it is the predicate a STATEMENT is built from,
//! in the types one database stores — so no schema renders it and `Schema::sdl` cannot see it. What
//! a client would notice moving is the visibility, the method names, the argument order and the
//! docs, and all four are in the tokens. So the tokens are what is captured, through
//! `prettyplease`, which is the same rendering `ingraph-codegen` already reads its own expansions
//! back with.

use ingraph_codegen::prefix::EmissionPrefix;
use ingraph_codegen::{
  interface::{InterfaceDatabase, InterfaceField, InterfaceModel, Pin, Tier},
  model::{AliasOptions, DatabaseKind, FrameworkMarker, Label, Marker},
  union::UnionMember,
  unit,
};
use quote::quote;

/// The shared emitters' output at the tip the third fold stands on, captured verbatim.
///
/// See the module note: every byte of it is `unit::comparison`'s or `unit::comparison_lowering`'s,
/// which is what a record's door and the bare door both emit.
const THE_UNITS_COMPARISON: &str = include_str!("the_third_fold/the_units_comparison.rs");

/// `interface/page.rs`'s own emission at the same tip — the face the fold is about.
const THE_INTERFACES_COMPARISON: &str = include_str!("the_third_fold/the_interfaces_comparison.rs");

/// **THE SHARED EMITTERS ARE THE BYTE THEY WERE.** A record's predicate and a bare struct's are this
/// emission over their own rows, so nothing the interface's collapse did reaches either of them.
#[test]
fn the_units_comparison_is_the_byte_it_was() {
  assert_eq!(render(the_units_face()), THE_UNITS_COMPARISON);
}

/// **THE INTERFACE'S PREDICATE IS THE BYTE IT WAS.** The fold's whole cost is this fixture's diff —
/// nothing else in the emission is allowed to move with it.
#[test]
fn the_interfaces_comparison_is_the_byte_it_was() {
  assert_eq!(render(the_interfaces_face()), THE_INTERFACES_COMPARISON);
}

/// **THE TWO FACES SPEAK ONE SET OF SENTENCES**, which is the whole of what the fold bought.
///
/// The sentences below are the SHAPE's, and no caller's noun reaches them — so the only way both
/// fixtures can carry them verbatim is that one emitter wrote both. Before the fold the interface
/// said three of its own instead, and its copy is what would have drifted.
///
/// The two sentences that DO carry a name are asserted beside them, because they are the other half
/// of the same law: the sentence is the shape's and the noun in it is the caller's, so an interface
/// says *shared `slate` column* where a record says *`slate` column* — with no mode inside the walk
/// that chose between them.
#[test]
fn the_interfaces_comparison_speaks_the_units_sentences() {
  for sentence in SHAPE_SENTENCES {
    assert!(
      THE_UNITS_COMPARISON.contains(sentence),
      "the shared emitter says it: {sentence}"
    );
    assert!(
      THE_INTERFACES_COMPARISON.contains(sentence),
      "and so does the interface, which is now the same emitter: {sentence}"
    );
  }

  assert!(THE_UNITS_COMPARISON.contains(
    "A predicate over a [`Cue`]'s columns, in the types this database stores — each field"
  ));
  assert!(THE_INTERFACES_COMPARISON.contains(
    "A predicate over a [`Screened`]'s columns, in the types this database stores — each field"
  ));
  assert!(
    THE_UNITS_COMPARISON.contains("The predicate on the `slate` column, in the type this database")
  );
  assert!(
    THE_INTERFACES_COMPARISON
      .contains("The predicate on the shared `slate` column, in the type this database")
  );
}

/// **THE CALLER'S PARAGRAPH IS THE CALLER'S**, and the shape never learned it.
///
/// What an interface's predicate knows on top of the shape — that it is lowered ONCE, above the
/// union, over names every arm has already aliased into — arrives through `UnitHeader::note` and
/// survives the fold verbatim. The other half is what makes it a seam rather than a branch: the
/// same emitter's output for a record's rows carries no trace of it.
#[test]
fn the_interfaces_own_paragraph_survives_and_the_shape_never_learned_it() {
  assert!(
    THE_INTERFACES_COMPARISON
      .contains("Written in the INTERFACE's vocabulary and lowered ONCE, above the union"),
    "the contract's own paragraph is still on its face"
  );
  assert!(
    !THE_UNITS_COMPARISON.contains("above the union"),
    "and the shape knows nothing about a union — the paragraph is the caller's"
  );
}

/// The sentences the SHAPE owns outright: no subject, no column noun, nothing a front end supplies.
const SHAPE_SENTENCES: [&str; 3] = [
  "Construct a predicate from one comparison per column, in the order this database stores them.",
  "How many conjuncts this predicate renders — the sum over its columns, since each is a comparison \
   of its own.",
  "Render every column's conjuncts into `builder`, each at the same row and one segment below the \
   address this predicate was applied at.",
];

/// **THE STRUCT WALKS `stored()` AND THE LOWERING WALKS `projected()`**, and the difference between
/// the two lists is exactly the COLLECTIONS.
///
/// This is the fold's one real difference, and it is a ROW-LIST difference rather than a shape one:
/// a predicate over a collection is a real question and the crossing that builds it is every other
/// column's, so the struct holds a field for it — but no arm of the union selects a collection, so
/// there is no column above the union for its conjuncts to land at and the lowering skips it. The
/// per-arm half renders it at each member's own edge table instead, through `SqlInterface::collections`.
///
/// Asserted as a SUBSET plus an exact complement rather than as two literals, because that is the
/// relation `InterfaceModel::projected` is defined by — `stored()` less the collections — and a
/// literal pair would still pass on the day one list stopped being the other's subset.
#[test]
fn the_struct_walks_stored_and_the_lowering_walks_projected() {
  let held = struct_members(&the_interfaces_face());
  let lowered = lowered_members(&the_interfaces_face());
  let model = reeled();
  let collected: Vec<String> = model
    .collected()
    .map(|field| field.name.to_string())
    .collect();

  assert_eq!(
    held,
    ["slate", "marks"],
    "the struct holds one field per STORED column, collections included"
  );
  assert_eq!(
    lowered,
    ["slate"],
    "and the lowering renders the PROJECTED ones alone"
  );
  assert!(
    lowered.iter().all(|member| held.contains(member)),
    "the lowering's list is a subset of the struct's, never a list of its own"
  );
  let difference: Vec<String> = held
    .iter()
    .filter(|member| !lowered.contains(member))
    .cloned()
    .collect();
  assert_eq!(
    difference, collected,
    "and the difference is exactly what the model calls collected"
  );
}

/// The interface the fold is measured against: two members, one shared scalar column and one shared
/// COLLECTION, so `stored()` and `projected()` are always different lists here.
///
/// A collection pinned at `i64` in SQLite, which is the shape that keeps the two readings of one pin
/// apart: the row holds the LIST and the comparison is keyed on the ELEMENT.
fn reeled() -> InterfaceModel {
  InterfaceModel {
    prefix: EmissionPrefix::default(),
    vis: syn::parse_quote!(pub),
    name: ident("Screened"),
    krate: syn::parse_quote!(::ingraph),
    members: vec![
      UnionMember {
        ident: ident("Reel"),
        ty: syn::parse_quote!(Reel),
      },
      UnionMember {
        ident: ident("Tape"),
        ty: syn::parse_quote!(Tape),
      },
    ],
    fields: vec![
      InterfaceField {
        name: ident("slate"),
        ty: syn::parse_quote!(String),
        tier: Tier::Stored,
        marker: None,
        copy: false,
        pins: Vec::new(),
        wire: None,
        operands: Vec::new(),
        members: Vec::new(),
      },
      InterfaceField {
        name: ident("marks"),
        ty: syn::parse_quote!(Vec<u64>),
        tier: Tier::Stored,
        marker: Some(Marker::Framework(FrameworkMarker {
          label: Label::List,
          element: Some(Label::Scalar),
        })),
        copy: false,
        pins: vec![Pin {
          kind: DatabaseKind::Sqlite,
          stored: Some(syn::parse_quote!(i64)),
        }],
        wire: None,
        operands: Vec::new(),
        members: Vec::new(),
      },
    ],
    error: None,
    computed_error: None,
    persist: vec![InterfaceDatabase {
      kind: DatabaseKind::Sqlite,
      aliases: AliasOptions::default(),
    }],
    errors: Vec::new(),
    operand_errors: Vec::new(),
    plural: None,
    connection: None,
    edge: None,
  }
}

/// The shared emitters' face, over the rows a record's door and the bare door hand them.
///
/// The rows are written here rather than read off a model on purpose: what this pins is the
/// EMITTER, and a model would put a front end's row-building between the pin and its subject. The
/// nouns are the two doors' own — `` `slate` column ``, with no adjective — which is the spelling
/// `standalone.rs` and `emit/graphql.rs` both hand it.
fn the_units_face() -> Vec<syn::Item> {
  let vis: syn::Visibility = syn::parse_quote!(pub);
  let db = ident("__INGRAPH_DB__");
  let name = ident("CueSqliteComparison");
  let crossings = quote! {
    __INGRAPH_DB__: ::ingraph::__private::comparison::Backend,
    ::ingraph::__private::graphql::TextFilter<String>:
      ::ingraph::__private::comparison::ToDatabaseComparison<String, __INGRAPH_DB__>,
    ::ingraph::__private::graphql::ScalarFilter<i64>:
      ::ingraph::__private::comparison::ToDatabaseComparison<i64, __INGRAPH_DB__>,
  };
  let rows = vec![
    unit::ComparisonColumn {
      member: ident("slate"),
      name: "`slate` column".to_owned(),
      // A STANDALONE unit is handed its rows whole, and a hand-built one is under no condition.
      gate: proc_macro2::TokenStream::new(),
      held: quote!(
        <::ingraph::__private::graphql::TextFilter<String>
          as ::ingraph::__private::comparison::ToDatabaseComparison<
            String,
            __INGRAPH_DB__,
          >>::Comparison
      ),
    },
    unit::ComparisonColumn {
      member: ident("marks"),
      name: "`marks` column".to_owned(),
      gate: proc_macro2::TokenStream::new(),
      held: quote!(
        <::ingraph::__private::graphql::ScalarFilter<i64>
          as ::ingraph::__private::comparison::ToDatabaseComparison<
            i64,
            __INGRAPH_DB__,
          >>::Comparison
      ),
    },
  ];
  let header = unit::UnitHeader {
    vis: &vis,
    name: name.clone(),
    subject: "[`Cue`]".to_owned(),
    note: None,
  };
  let (declaration, methods) = unit::comparison(&header, &db, &crossings, &rows);
  let seats = unit::LoweringSeats {
    backend: quote!(::ingraph::__private::comparison::Backend),
    complex: quote!(::ingraph::__private::comparison::ComplexComparison),
    frame: quote!(::ingraph::__private::comparison::Frame),
    at: quote!(::ingraph::__private::comparison::At),
    field_name: quote!(::ingraph::__private::field::FieldName),
  };
  // The lowering's own row list, which is the caller's second list rather than a narrowing of the
  // first — the very seam the interface's `stored()`/`projected()` split needs.
  let lowered = vec![unit::LoweringColumn {
    member: ident("slate"),
    rendered: "slate".to_owned(),
    flatten: false,
    through: None,
    gate: proc_macro2::TokenStream::new(),
  }];
  let lowering = unit::comparison_lowering(&name, &db, &crossings, &seats, &lowered);
  let file: syn::File =
    syn::parse2(quote! { #declaration #methods #lowering }).expect("an emission is a file");
  file.items
}

/// The INTERFACE's comparison face, out of a whole real expansion.
///
/// Reached through [`InterfaceModel::emit`] rather than through the emitter directly, because what
/// a declaring crate gets is the expansion — so a face that stopped being emitted at all, or that
/// arrived under another name, fails here rather than passing a pin aimed straight at it.
fn the_interfaces_face() -> Vec<syn::Item> {
  let file: syn::File = syn::parse2(reeled().emit()).expect("the expansion is a file");
  let mut found = Vec::new();
  face(&file.items, "ScreenedSqliteComparison", &mut found);
  assert_eq!(
    found.len(),
    3,
    "a comparison face is its struct, its methods and its lowering"
  );
  found
}

/// The members the comparison STRUCT declares a field for, in declaration order.
fn struct_members(items: &[syn::Item]) -> Vec<String> {
  items
    .iter()
    .find_map(|item| match item {
      syn::Item::Struct(declared) => Some(declared),
      _ => None,
    })
    .expect("the face declares its struct")
    .fields
    .iter()
    .filter_map(|field| field.ident.as_ref().map(ToString::to_string))
    .collect()
}

/// The members the LOWERING reaches, read off the `conjuncts` sum — one term per column it renders,
/// which is the list the `apply` walk is built from beside it.
fn lowered_members(items: &[syn::Item]) -> Vec<String> {
  let block = items
    .iter()
    .find_map(|item| match item {
      syn::Item::Impl(block) if trait_of(block) == "ComplexComparison" => Some(block),
      _ => None,
    })
    .expect("the face declares its lowering");
  let conjuncts = block
    .items
    .iter()
    .find_map(|member| match member {
      syn::ImplItem::Fn(function) if function.sig.ident == "conjuncts" => Some(function),
      _ => None,
    })
    .expect("a lowering counts its conjuncts");

  tight(conjuncts)
    .match_indices("(&self.")
    .filter_map(|(at, _)| {
      let rest = &tight(conjuncts)[at + "(&self.".len()..];
      rest.split(')').next().map(ToOwned::to_owned)
    })
    .collect()
}

/// One `syn::Ident`, at the call site's span — every emitted name this file writes goes through it.
fn ident(name: &str) -> syn::Ident {
  syn::Ident::new(name, proc_macro2::Span::call_site())
}

/// Tokens with their spacing removed, so a claim about them is about content rather than layout.
///
/// The interface suite's own helper, spelled again rather than shared: it is three tokens, and a
/// test reaching into a crate's private module for one would be a seam for nothing.
fn tight(tokens: impl quote::ToTokens) -> String {
  quote::ToTokens::to_token_stream(&tokens)
    .to_string()
    .replace(' ', "")
}

/// Items rendered the way this crate reads its own expansions back — as SOURCE, so a fixture's diff
/// is a diff a reviewer can read.
fn render(items: Vec<syn::Item>) -> String {
  prettyplease::unparse(&syn::File {
    shebang: None,
    frontmatter: None,
    attrs: Vec::new(),
    items,
  })
}

/// The trait one `impl` block implements, by its last segment — `""` for an inherent block.
fn trait_of(block: &syn::ItemImpl) -> String {
  block.trait_.as_ref().map_or_else(String::new, |(path, _)| {
    path
      .segments
      .last()
      .map_or_else(String::new, |segment| segment.ident.to_string())
  })
}

/// The three items ONE comparison face is, gathered out of a whole expansion by the name they
/// declare.
///
/// The walk reaches through the `const _: () = { … }` blocks an expansion nests its impls inside,
/// which is where a face's own lowering lands. The trait filter is what keeps the CROSSING out:
/// `TryFromFilter for <I><Db>Comparison` is written over the same self type and is the interface's
/// own addition rather than any part of what the units emit.
fn face(items: &[syn::Item], name: &str, found: &mut Vec<syn::Item>) {
  for item in items {
    match item {
      syn::Item::Struct(declared) if declared.ident == name => found.push(item.clone()),
      syn::Item::Impl(block)
        if base_of(&block.self_ty) == name
          && (block.trait_.is_none() || trait_of(block) == "ComplexComparison") =>
      {
        found.push(item.clone());
      }
      syn::Item::Const(constant) => {
        if let syn::Expr::Block(block) = &*constant.expr {
          let nested: Vec<syn::Item> = block
            .block
            .stmts
            .iter()
            .filter_map(|statement| match statement {
              syn::Stmt::Item(item) => Some(item.clone()),
              _ => None,
            })
            .collect();
          face(&nested, name, found);
        }
      }
      _ => {}
    }
  }
}

/// The BASE name of a written type — `ScreenedSqliteComparison<DB>` is `ScreenedSqliteComparison`.
fn base_of(ty: &syn::Type) -> String {
  match ty {
    syn::Type::Path(path) => path
      .path
      .segments
      .last()
      .map_or_else(String::new, |segment| segment.ident.to_string()),
    _ => String::new(),
  }
}