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
467
468
469
470
471
472
473
474
475
476
477
//! The OPEN VOCABULARY emitter's acceptance, over models built BY HAND.
//!
//! No declaration is parsed here, for the reason [`crate::tests`] states: the split that lets a
//! front end other than the derive reach this emitter only exists while the emitter can be driven
//! from a plain model.

use std::collections::BTreeMap;

use quote::ToTokens;

use super::{EnumModel, EnumVariant};
use crate::enumeration::{Escape, Namespace, StorageForm};

/// The roster the module is measured against: two named members, one of them RENAMED, and an
/// escape.
///
/// `LeftShoulder` is what proves the household fold — nothing in the model spells `left_shoulder`,
/// and the emission does.
fn roster() -> EnumModel {
  let mut model = closed();
  model.variants.push(EnumVariant {
    ident: ident("Other"),
    rename: None,
    names: BTreeMap::new(),
    upstream: None,
    escape: Some(Escape::Total),
    carrier: Some(syn::parse_quote!(::ingraph::Utf8Bytes)),
  });
  model
}

/// The same declaration with no escape — the CLOSED cell, which is what the fourth cell is measured
/// against.
fn closed() -> EnumModel {
  EnumModel {
    krate: syn::parse_quote!(::ingraph),
    vis: syn::parse_quote!(pub),
    name: ident("BodyJoint"),
    width: None,
    variants: vec![variant("Nose", None), variant("LeftShoulder", None)],
    forms: BTreeMap::new(),
    wire_name: None,
    error: None,
    remote: None,
  }
}

fn variant(name: &str, rename: Option<&str>) -> EnumVariant {
  EnumVariant {
    ident: ident(name),
    rename: rename.map(ToOwned::to_owned),
    names: BTreeMap::new(),
    upstream: None,
    escape: None,
    carrier: None,
  }
}

fn ident(name: &str) -> syn::Ident {
  syn::parse_str(name).expect("an identifier")
}

/// The expansion, read back as items.
fn emission(model: &EnumModel) -> syn::File {
  syn::parse2(model.emit()).expect("the expansion parses")
}

/// The whole expansion with its SPACING removed, for the reason the mirror's tests squash theirs:
/// the gated halves are macro invocations, whose bodies a formatter prints as the tokens stand.
fn squashed(model: &EnumModel) -> String {
  model.emit().to_string().replace(' ', "")
}

/// Anything printable, squashed the same way.
fn squash(printable: &impl ToTokens) -> String {
  printable.to_token_stream().to_string().replace(' ', "")
}

/// The obligation the key row spends on the carrier, as the expansion spells it.
const CARRIES: &str = "__IngraphCarriesAWord";

/// The expansion in two halves: the KEY DELEGATION row with the carrier obligation beside it, and
/// everything else.
///
/// The split is what lets *the carrier is named in exactly ONE row* be an assertion rather than a
/// claim — the other half is checked for the ABSENCE of the type, which only means something once the
/// rows allowed to name it have been taken out. The obligation counts as part of the key row because
/// it exists for it: that row is the only thing that spends the bound.
fn split_off_the_key_row(model: &EnumModel) -> (String, String) {
  fn belongs_to_the_key_row(stmt: &syn::Stmt) -> bool {
    match stmt {
      syn::Stmt::Item(syn::Item::Impl(item)) => item.trait_.as_ref().is_some_and(|(path, _)| {
        path
          .segments
          .last()
          .is_some_and(|last| last.ident == "DelegatesId" || last.ident == CARRIES)
      }),
      syn::Stmt::Item(syn::Item::Trait(item)) => item.ident == CARRIES,
      _ => false,
    }
  }

  let (mut key, mut rest) = (String::new(), String::new());

  for item in emission(model).items {
    let syn::Item::Const(block) = &item else {
      rest.push_str(&squash(&item));
      continue;
    };
    let syn::Expr::Block(body) = &*block.expr else {
      rest.push_str(&squash(&item));
      continue;
    };
    for stmt in &body.block.stmts {
      if belongs_to_the_key_row(stmt) {
        key.push_str(&squash(stmt));
      } else {
        rest.push_str(&squash(stmt));
      }
    }
  }

  (key, rest)
}

/// **THE HOUSEHOLD FOLD IS THE DEFAULT WORD**, and it is what the five vocabularies this mode was
/// measured against already spell by hand.
#[test]
fn a_declared_open_word_defaults_to_the_lower_case_household() {
  assert_eq!(variant("LeftShoulder", None).folded(), "left_shoulder");
  assert_eq!(
    variant("Gs1DataBarExpanded", None).folded(),
    "gs1_data_bar_expanded"
  );
  assert_eq!(variant("Code39Checksum", None).folded(), "code39_checksum");
  assert_eq!(variant("Qr", None).folded(), "qr");
  assert_eq!(variant("Code93i", None).folded(), "code93i");
}

/// **`rename` OVERRIDES the arithmetic**, and it is the only thing that does.
#[test]
fn a_rename_is_the_word_and_the_fold_is_not_applied_to_it() {
  assert_eq!(variant("Code93i", Some("code_93i")).folded(), "code_93i");
  assert_eq!(variant("Nose", Some("NOSE")).folded(), "NOSE");
}

/// **A CLOSED vocabulary's word is UNMOVED by the fold's existence** — the base state, which the
/// fourth cell was built beside rather than on top of.
#[test]
fn the_closed_cell_still_spells_its_variants_verbatim() {
  let rendered = squashed(&closed());

  assert!(rendered.contains(r#""LeftShoulder""#), "{rendered}");
  assert!(
    rendered.contains(r#""LEFT_SHOULDER""#),
    "and SHOUTS on the wire: {rendered}"
  );
  assert!(!rendered.contains(r#""left_shoulder""#), "{rendered}");
  assert!(rendered.contains("BodyJointParseError"), "{rendered}");
}

/// **THE DOOR NAMES THE FRAMEWORK'S FOLD** rather than carrying one — the single-source rule, spent
/// where it is spendable.
#[test]
fn the_emitted_door_calls_the_one_fold_and_carries_no_copy_of_it() {
  let rendered = squashed(&roster());

  assert!(
    rendered.contains("::ingraph::__private::name::folds_to(__ingraph_word,\"nose\")"),
    "{rendered}"
  );
  assert!(
    rendered.contains("::ingraph::__private::name::folds_to(__ingraph_word,\"left_shoulder\")"),
    "{rendered}"
  );
  assert!(
    rendered.contains("::ingraph::__private::name::folded(__ingraph_word)"),
    "the escape carries a FOLDED word: {rendered}"
  );
  assert!(
    !rendered.contains("eq_ignore_ascii_case"),
    "and the relation itself is nowhere in the expansion: {rendered}"
  );
}

/// **THE DOOR TRIES EVERY MEMBER BEFORE IT BUILDS AN ESCAPE** — in DECLARATION order, which is what
/// makes a value round-trip.
#[test]
fn the_roster_is_walked_in_order_and_the_escape_is_what_is_left() {
  let rendered = squashed(&roster());
  let nose = rendered
    .find(r#"folds_to(__ingraph_word,"nose")"#)
    .expect("the first member");
  let shoulder = rendered
    .find(r#"folds_to(__ingraph_word,"left_shoulder")"#)
    .expect("the second member");
  let escape = rendered
    .find("Self::Other(::core::convert::Into::into")
    .expect("the escape");

  assert!(nose < shoulder, "{rendered}");
  assert!(shoulder < escape, "{rendered}");
}

/// **THE ESCAPE'S CARRIER IS NAMED IN EXACTLY ONE ROW**, and everywhere else it is reached through
/// the conversion pair. The door builds one through `From<&str>` and reads one through `AsRef<str>`,
/// so the field's own type is the whole declaration of what it is.
///
/// The KEY DELEGATION is the exception and cannot be anything else: `Inner` is an associated TYPE,
/// and Rust has no `typeof` for the emission to write it with. What the row spells is the model's own
/// token — the type the declaration wrote on the escape — rather than a type this crate picked.
#[test]
fn the_carrier_is_reached_through_the_conversion_pair_and_spelled_only_by_the_key_row() {
  let (key, rest) = split_off_the_key_row(&roster());

  assert!(rest.contains("::core::convert::Into::into("), "{rest}");
  assert!(
    rest.contains("::core::convert::AsRef::<::core::primitive::str>::as_ref(__ingraph_word)"),
    "{rest}"
  );
  assert!(!rest.contains("Utf8Bytes"), "{rest}");
  assert!(!rest.contains("SmolStr"), "{rest}");

  assert!(
    key.contains("typeInner=::ingraph::Utf8Bytes;"),
    "the one row that names the carrier names the DECLARATION's own type: {key}"
  );
}

/// **AN OPEN VOCABULARY IS A KEY TOO**, and its two kinds of arm meet in the CARRIER: a named member
/// hands back a `static` of that type holding its own word, and the escape hands back the word it is
/// already carrying.
///
/// The named arm's word is the FACE's — the same `folded` spelling `as_str` answers with — so for
/// this mode the key word, the stored word and the cursor word are ONE word. The mirror is where they
/// part, and its own suite says so.
#[test]
fn the_open_vocabulary_delegates_the_face_word_and_the_carried_one() {
  let (key, _) = split_off_the_key_row(&roster());

  assert!(
    key.contains("unsafeimpl::ingraph::__private::id::DelegatesIdforBodyJoint"),
    "{key}"
  );
  assert!(key.contains("typeInner=::ingraph::Utf8Bytes;"), "{key}");
  for word in ["\"nose\"", "\"left_shoulder\""] {
    assert!(
      key.contains(&format!(
        "<::ingraph::Utf8Bytesas__IngraphCarriesAWord>::__ingraph_word({word})"
      )),
      "{word}: {key}"
    );
  }
  assert!(
    key.contains("Self::Other(__ingraph_word)=>__ingraph_word,"),
    "the escape delegates the word it CARRIES, borrowed rather than rebuilt: {key}"
  );
}

/// **THE CARRIER OBLIGATION IS NAMED, AND IT IS DECLARED IN THE EXPANSION**.
///
/// Named, because `#[diagnostic::on_unimplemented]` attaches to a trait and a bare `From<&'static
/// str>` is nobody's to annotate. In the EXPANSION, because a trait on the framework's own shelf is
/// reported at two different paths on two toolchains — stable names where it is defined, nightly the
/// re-export an expansion travels — and a locally declared one has a single spelling everywhere.
///
/// `do_not_recommend` is the third half of it: unmarked, the report peels to the blanket's own
/// `where` clause and the sentence becomes a footnote under a bound about `From`.
#[test]
fn the_carrier_obligation_is_declared_beside_the_row_that_spends_it() {
  let (key, rest) = split_off_the_key_row(&roster());

  assert!(key.contains("trait__IngraphCarriesAWord"), "{key}");
  assert!(key.contains("#[diagnostic::do_not_recommend]"), "{key}");
  assert!(
    key.contains("cannotcarryan`#[ingraph(other)]`escape'sword"),
    "{key}"
  );
  assert!(
    key.contains(
      "impl<T:::core::convert::From<&'static::core::primitive::str>>__IngraphCarriesAWordforT"
    ),
    "the obligation IS the door's own conversion, wearing a name: {key}"
  );
  assert!(
    !rest.contains("__IngraphCarriesAWord"),
    "and nothing outside the key row spends it: {rest}"
  );
}

/// **A VOCABULARY THAT IS NOTHING BUT ITS ESCAPE DECLARES NO OBLIGATION** — there is no named arm, so
/// no `static`, so no word to build and nothing to spend a bound on.
///
/// An unspent obligation would be an unused trait in the DECLARING crate's own module, which is a
/// `dead_code` warning somebody else has to silence. The row itself still stands: the escape's arm
/// needs no word.
#[test]
fn an_escape_only_vocabulary_keys_by_its_word_and_asks_for_no_obligation() {
  let mut model = roster();
  model.variants.retain(|variant| variant.escape.is_some());

  let (key, _) = split_off_the_key_row(&model);
  assert!(
    key.contains("Self::Other(__ingraph_word)=>__ingraph_word,"),
    "{key}"
  );
  assert!(!key.contains("__IngraphCarriesAWord"), "{key}");
  assert!(!key.contains("LazyLock"), "{key}");
}

/// **A MODEL THAT MARKS AN ESCAPE AND RECORDS NO CARRIER GETS NO KEY ROW**, and the rest of the
/// expansion is untouched.
///
/// The derive never builds one — its front end refuses an escape that is not exactly one unnamed
/// field, and records that field's type there — so this is the OTHER front end's cell, pinned so the
/// fallback is a decision rather than a surprise: `Inner` is a written type, and a model that names
/// none has nothing to write it with.
#[test]
fn an_escape_with_no_recorded_carrier_costs_the_key_row_and_nothing_else() {
  let mut model = roster();
  model
    .variants
    .last_mut()
    .expect("the escape")
    .carrier
    .take();

  let (key, rest) = split_off_the_key_row(&model);
  assert!(key.is_empty(), "{key}");

  let (_, whole) = split_off_the_key_row(&roster());
  assert_eq!(rest, whole, "every other row stands as it stood");
}

/// **AN OPEN DOOR CANNOT REFUSE**, so there is no refusal type and `FromStr::Err` says so.
#[test]
fn an_open_vocabulary_declares_no_refusal_type() {
  let model = roster();

  assert!(!model.refuses());

  let rendered = squashed(&model);
  assert!(
    rendered.contains("typeErr=::core::convert::Infallible;"),
    "{rendered}"
  );
  assert!(!rendered.contains("ParseError"), "{rendered}");
  assert!(
    !emission(&model)
      .items
      .iter()
      .any(|item| matches!(item, syn::Item::Struct(_))),
    "nothing at all stands beside the enum: {rendered}"
  );
}

/// **THE ROSTER EXCLUDES THE ESCAPE**, which carries a word rather than a name and is therefore no
/// constant.
#[test]
fn variants_lists_the_named_members_alone() {
  let rendered = squashed(&roster());

  assert!(
    rendered.contains("VARIANTS:&'static[Self]=&[Self::Nose,Self::LeftShoulder]"),
    "{rendered}"
  );
  assert!(
    rendered.contains("fnis_other(&self)"),
    "and the escape still has its predicate: {rendered}"
  );
  assert!(rendered.contains("Self::Other(..)"), "{rendered}");
}

/// **THE WIRE FACE IS A SCALAR**, where the closed cell's is a true GraphQL `enum` — the fork the
/// escape's presence decides.
#[test]
fn an_open_vocabulary_publishes_a_scalar_and_a_closed_one_an_enum() {
  let open = squashed(&roster());
  assert!(open.contains("Scalar(crate="), "{open}");
  assert!(open.contains("name=\"BodyJoint\""), "{open}");
  assert!(!open.contains("MetaTypeId::Enum"), "{open}");
  assert!(!open.contains("EnumItem"), "{open}");

  let closed = squashed(&closed());
  assert!(closed.contains("MetaTypeId::Enum"), "{closed}");
  assert!(closed.contains("EnumItem"), "{closed}");
  assert!(!closed.contains("Scalar(crate="), "{closed}");
}

/// **THE STORED FORM IS THE WORD, IN EVERY FACE**, and the decode CANONICALISES a row another
/// program wrote.
#[test]
fn an_open_vocabulary_stores_its_word_and_reads_a_stranger_s_spelling_back() {
  let rendered = squashed(&roster());

  assert!(
    rendered.contains("::std::string::String::from(BodyJoint::as_str(self))"),
    "{rendered}"
  );
  assert!(
    rendered.contains("::core::option::Option::Some(BodyJoint::new(stored))"),
    "{rendered}"
  );
  assert!(
    !rendered.contains("__ingraph_sqlite_stored"),
    "and no discriminant is stored anywhere: {rendered}"
  );
}

/// **THE CURSOR IS THE WORD TOO**, read back through the door — total, so a forged position is a
/// value rather than a refusal.
#[test]
fn the_cursor_carries_the_canonical_word_and_reads_it_through_the_door() {
  let rendered = squashed(&roster());

  assert!(
    rendered.contains("::core::primitive::str::as_bytes(BodyJoint::as_str(self))"),
    "{rendered}"
  );
  assert!(
    rendered.contains("::core::option::Option::Some(BodyJoint::new(text))"),
    "{rendered}"
  );
}

/// **THE FILTER READING IS UNMOVED** — an open vocabulary is asked MEMBERSHIP exactly as a closed
/// one is, the escape being a member like any other.
#[test]
fn the_three_interpretation_rows_are_the_same_ones_every_mode_earns() {
  let rendered = squashed(&roster());

  for row in [
    "EnumFilterMarker",
    "DefaultMarker",
    "DefaultVecMarker",
    "ColumnKind",
    "Assemble",
    "CursorValue",
  ] {
    assert!(rendered.contains(row), "{row}: {rendered}");
  }
}

/// **NO PER-FACE FACE AT ALL.** One word in every namespace means one accessor, so the closed mode's
/// `as_<face>_str` and `TryFrom<&…Name>` family has nothing to be per-face about.
#[test]
fn an_open_vocabulary_has_one_word_and_therefore_one_accessor() {
  let rendered = squashed(&roster());

  assert!(rendered.contains("fnas_str(&self)"), "{rendered}");
  for absent in [
    "as_sqlite_str",
    "as_graphql_str",
    "GraphqlName",
    "TryFrom<&",
  ] {
    assert!(!rendered.contains(absent), "{absent}: {rendered}");
  }
}

/// The FORM knob is not read in this cell, and the emission is what proves it: a declaration whose
/// model carries one still stores a word.
///
/// The refusal that stops such a declaration reaching here is the derive's; this is the emitter
/// stating that it has no second behaviour for a front end to reach by another road.
#[test]
fn a_form_in_the_model_moves_no_token_of_an_open_expansion() {
  let mut declared = roster();
  declared
    .forms
    .insert(Namespace::Sqlite, StorageForm::Integer);
  declared
    .forms
    .insert(Namespace::Graphql, StorageForm::Integer);

  assert_eq!(squashed(&declared), squashed(&roster()));
}