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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! What the options spine says, read off its tokens.
//!
//! What a spine DOES — a partial document parsing, an absent section meaning a node that never
//! starts, a misspelled key refused by name — is asserted where the emission can be run, in
//! `ingraph`'s own `tests/ingraph_options.rs`. What is here is what a token stream can be read for:
//! the field per mount, the type it holds, the words serde is given, and the shelf every framework
//! path goes through.

use crate::graph::GraphModel;

/// A root over three nodes, as the derive builds one.
pub(super) fn app() -> GraphModel {
  GraphModel {
    krate: syn::parse_quote!(::ingraph),
    vis: syn::parse_quote!(pub),
    name: syn::parse_quote!(App),
    nodes: vec![
      syn::parse_quote!(media::Video),
      syn::parse_quote!(Scene),
      syn::parse_quote!(TranscriptText),
    ],
    mounts: vec![
      syn::parse_quote!(videos),
      syn::parse_quote!(scenes),
      syn::parse_quote!(search),
    ],
    queried: Vec::new(),
    interfaces: Vec::new(),
    fused: Vec::new(),
    resources: Vec::new(),
    origins: Vec::new(),
    // No third-party engine word: these models are about the list its fields are.
    engines: Vec::new(),
    retired: None,
    generations: None,
  }
}

/// The rendered spine with every space taken out — what a claim about a TYPE or a word is read off.
pub(super) fn compact(model: &GraphModel) -> String {
  rendered(model).split_whitespace().collect()
}

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

/// The type takes the ROOT's own name, so a deployment writing `AppOptions` for an `App` has one
/// word to learn.
#[test]
fn the_spine_is_named_after_the_root() {
  assert_eq!(
    super::default_options_name(&syn::parse_quote!(App)),
    "AppOptions"
  );
  assert!(
    compact(&app()).contains("structAppOptions{"),
    "{}",
    rendered(&app())
  );
}

/// One field per DECLARED node, named by the mount — which is what makes a document's key the word
/// the declaration wrote, with no map from string to node to keep in step.
#[test]
fn every_mount_gets_a_field_holding_that_nodes_own_options() {
  let model = app();
  let emitted = compact(&model);
  for (mount, node) in [
    ("videos", "media::Video"),
    ("scenes", "Scene"),
    ("search", "TranscriptText"),
  ] {
    assert!(
      emitted.contains(&format!(
        "pub(crate){mount}:::core::option::Option<::ingraph::__private::drive::NodeSection<<{node}\
         as::ingraph::__private::drive::AsyncConstructor>::Options,<{node}as::ingraph::__private::drive\
         ::Declared>::Channels>>"
      )),
      "`{mount}` holds `{node}`'s own options and its own shelf: {}",
      rendered(&model)
    );
  }
}

/// PRESENCE IS ENABLEMENT: every section is an `Option`, so a node the deployment does not name is
/// a node it does not start.
#[test]
fn every_section_is_optional() {
  let model = app();
  let emitted = compact(&model);
  assert_eq!(
    emitted
      .matches("::core::option::Option<::ingraph::__private::drive::NodeSection<")
      .count(),
    // One per field, and one more per borrow accessor.
    model.mounts.len() * 2,
    "{}",
    rendered(&model)
  );
}

/// Every field is `serde(default)`, so a document naming three of thirty nodes parses.
///
/// One mount PLUS the registry seat: `registry` is ON EVERY ROOT (see
/// [`the_registry_seat_is_on_every_root`]) and defaults exactly as a mount's own section does.
#[test]
fn every_field_defaults_so_a_partial_document_parses() {
  let model = app();
  let emitted = compact(&model);
  assert_eq!(
    emitted.matches("#[serde(default)]").count(),
    model.mounts.len() + 1,
    "{}",
    rendered(&model)
  );
}

/// A key the spine does not have is a REFUSAL naming it, which is what `deny_unknown_fields` buys —
/// and the crate word is what makes serde's own expansion bind through the shelf.
#[test]
fn the_spine_denies_what_it_does_not_declare() {
  let model = app();
  let emitted = compact(&model);
  assert!(
    emitted.contains(r#"#[serde(crate="::ingraph::__private::serde",deny_unknown_fields)]"#),
    "{}",
    rendered(&model)
  );
}

/// The DERIVE is what rides the gate, and the struct exists in both halves: a build without serde
/// still has the type a hand-built deployment states itself with.
#[test]
fn the_declaration_is_written_once_inside_each_half_of_the_serde_gate() {
  let model = app();
  let emitted = compact(&model);
  let with = emitted
    .find("if_serde!")
    .expect("the deserialized half rides the gate");
  let without = emitted
    .find("if_no_serde!")
    .expect("the plain half rides the complement");
  assert!(with < without, "{}", rendered(&model));
  assert_eq!(
    emitted.matches("structAppOptions{").count(),
    2,
    "one declaration per half: {}",
    rendered(&model)
  );
  // The serde words are in the first half and nowhere else. One container attribute, one
  // `#[serde(default)]` per mount, and one more for the registry seat every root carries.
  assert_eq!(
    emitted.matches("#[serde(").count(),
    1 + model.mounts.len() + 1
  );
  assert!(emitted.rfind("#[serde(").unwrap_or(usize::MAX) < without);
}

/// The ACCESSOR family is emitted once, outside both halves: the two declarations are one struct
/// under two attribute sets, so an impl written twice would be a duplicate.
#[test]
fn the_accessors_are_emitted_once_for_both_halves() {
  let model = app();
  let emitted = compact(&model);
  assert_eq!(emitted.matches("implAppOptions{").count(), 1);
  for mount in ["videos", "scenes", "search"] {
    assert_eq!(
      emitted.matches(&format!("pubfnwith_{mount}(")).count(),
      1,
      "{}",
      rendered(&model)
    );
    assert_eq!(
      emitted.matches(&format!("pubfn{mount}(&self")).count(),
      1,
      "{}",
      rendered(&model)
    );
  }
}

/// The `Debug` is WRITTEN, and it reads each node's PRESENCE — never the options, whose type is the
/// author's and would otherwise be bounded for the benefit of one line.
#[test]
fn the_debug_reports_presence_rather_than_the_options() {
  let model = app();
  let emitted = compact(&model);
  assert!(
    emitted.contains("impl::core::fmt::DebugforAppOptions{"),
    "{}",
    rendered(&model)
  );
  for mount in ["videos", "scenes", "search"] {
    assert!(
      emitted.contains(&format!(
        r#".field("{mount}",&::core::option::Option::is_some(&self.{mount}))"#
      )),
      "`{mount}` reports its presence: {}",
      rendered(&model)
    );
  }
  assert!(
    !emitted.contains("::core::fmt::Debug>"),
    "no options type is bounded: {}",
    rendered(&model)
  );
}

/// The BRIDGE to the launch floor is emitted once, beside the accessors, and it names EVERY mount —
/// including the ones a deployment will leave absent, which is what makes the absence readable.
#[test]
fn the_bridge_reads_every_mount_and_not_only_the_ones_a_document_carried() {
  let model = app();
  let emitted = compact(&model);
  assert_eq!(
    emitted
      .matches("pubfnenablement(&self)->::ingraph::__private::drive::Enablement{")
      .count(),
    1,
    "{}",
    rendered(&model)
  );
  for mount in ["videos", "scenes", "search"] {
    assert!(
      emitted.contains(&format!(
        r#".mounted("{mount}",::core::option::Option::as_ref(&self.{mount}))"#
      )),
      "`{mount}` reaches the bridge: {}",
      rendered(&model)
    );
  }
  // A CHAIN off the constructor, so a root with no nodes at all emits no binding to leave unused.
  assert!(
    emitted.contains("::ingraph::__private::drive::Enablement::new()."),
    "{}",
    rendered(&model)
  );
  let empty = GraphModel {
    nodes: Vec::new(),
    mounts: Vec::new(),
    ..app()
  };
  assert!(
    compact(&empty).contains("Enablement{::ingraph::__private::drive::Enablement::new()}"),
    "{}",
    rendered(&empty)
  );
}

/// The root's own visibility travels to the spine and its accessors: a private ingraph's options
/// stay private rather than leaking into its crate's public API.
#[test]
fn the_spine_takes_the_roots_visibility() {
  let mut private = app();
  private.vis = syn::Visibility::Inherited;
  let emitted = compact(&private);
  assert!(
    !emitted.contains("pubstructAppOptions") && emitted.contains("structAppOptions"),
    "{}",
    rendered(&private)
  );
  assert!(
    !emitted.contains("pubfnwith_videos") && emitted.contains("fnwith_videos"),
    "{}",
    rendered(&private)
  );
}

/// The registry seat is on EVERY root — unlike `resources`, which is absent where a root declares
/// none, there is no marker that would make `registry` conditional, so even a root over plain nodes
/// with no resources and no origins (`app()`) carries the field, its accessor and its builder.
#[test]
fn the_registry_seat_is_on_every_root() {
  let model = app();
  let emitted = compact(&model);
  assert!(
    emitted.contains("pub(crate)registry:::ingraph::__private::drive::RegistryOptions,"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("pubconstfnregistry(&self)->&::ingraph::__private::drive::RegistryOptions{"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "pubfnwith_registry(mutself,registry:::ingraph::__private::drive::RegistryOptions,)->Self{"
    ),
    "{}",
    rendered(&model)
  );

  // A root with NO nodes at all still carries the seat — it is graph-level, not per-mount.
  let empty = GraphModel {
    nodes: Vec::new(),
    mounts: Vec::new(),
    ..app()
  };
  assert!(
    compact(&empty).contains("pub(crate)registry:::ingraph::__private::drive::RegistryOptions,"),
    "{}",
    rendered(&empty)
  );
}

/// The `Debug` prints the registry's OWN value rather than only its presence — the node rack's
/// presence-only trade does not apply, because `RegistryOptions` is the framework's own type and not
/// an author's that a bound would have to be written for.
#[test]
fn the_registry_seat_reports_its_value_in_debug() {
  let model = app();
  let emitted = compact(&model);
  assert!(
    emitted.contains(r#".field("registry",&self.registry)"#),
    "{}",
    rendered(&model)
  );
}

/// The GENERATIONS seat is CONDITIONAL, unlike the registry's: a root that wrote no
/// `generations(<engine>)` has no engine, no connection and no pointer table, so a `[generations]`
/// section on it would be a document key naming nothing.
#[test]
fn a_root_that_declared_no_seat_grows_no_generations_key() {
  let emitted = compact(&app());
  assert!(!emitted.contains("generations"), "{}", rendered(&app()));
}

/// A root that wrote the word grows the field, both accessors, the `Debug` row — and the ENGINE, as
/// an associated `const` carrying the declaration's own decision across to whatever builds the store.
#[test]
fn the_word_grows_the_field_the_accessors_and_the_engine_const() {
  let model = GraphModel {
    generations: Some(crate::graph::GenerationsSeat {
      engine: crate::model::DatabaseKind::Postgres,
    }),
    ..app()
  };
  let emitted = compact(&model);
  for expected in [
    "pub(crate)generations:::ingraph::__private::drive::GenerationsOptions,",
    "pubconstGENERATIONS_ENGINE:::ingraph::__private::drive::GenerationsEngine=::ingraph::\
     __private::drive::GenerationsEngine::Postgres;",
    "pubconstfngenerations(&self)->&::ingraph::__private::drive::GenerationsOptions{",
    "pubfnwith_generations(mutself,generations:::ingraph::__private::drive::\
     GenerationsOptions,)->Self{",
    r#".field("generations",&self.generations)"#,
  ] {
    assert!(
      emitted.contains(expected),
      "{expected}\n{}",
      rendered(&model)
    );
  }
}

/// The engine word crosses ONCE, through `DatabaseKind::generations_arm` — so the arm the spine
/// names is the runtime enum's own spelling and never sqlx's.
#[test]
fn the_engine_arm_is_the_runtime_enums_own_spelling() {
  for (kind, arm) in [
    (crate::model::DatabaseKind::Sqlite, "Sqlite"),
    (crate::model::DatabaseKind::Postgres, "Postgres"),
    // `MySql` is sqlx's spelling and `Mysql` is the framework's; they differ, which is the whole
    // reason there are two mappings.
    (crate::model::DatabaseKind::Mysql, "Mysql"),
  ] {
    assert_eq!(kind.generations_arm(), Some(arm));
  }
  // A document store has no arm — see `generations_arm`'s own note, and the derive that refuses the
  // word before a spine is ever built over it.
  assert_eq!(crate::model::DatabaseKind::Mongo.generations_arm(), None);
}

/// Where `ingraph` lives is the declaration's to move, and every framework path moves with it — the
/// serde CRATE word included, which is a string literal the token walk cannot see.
#[test]
fn the_crate_path_reaches_every_framework_name() {
  let mut vendored = app();
  vendored.krate = syn::parse_quote!(shim::vendored::ingraph);
  let emitted = compact(&vendored);
  assert_eq!(
    emitted.matches("__private").count(),
    emitted
      .matches("shim::vendored::ingraph::__private")
      .count(),
    "every shelf reference is under the declared root, and none keeps the default: {}",
    rendered(&vendored)
  );
  assert!(emitted.contains(r#"crate="shim::vendored::ingraph::__private::serde""#));
}

/// The `retired` seat is CONDITIONAL, unlike the registry's: a root that declared no ledger has no
/// engine, no connection and no table, so a `[retired]` section on it would be a document key naming
/// nothing.
#[test]
fn the_retired_seat_is_absent_where_no_ledger_is_declared() {
  let emitted = compact(&app());
  assert!(
    !emitted.contains("pub(crate)retired:"),
    "{}",
    rendered(&app())
  );
  assert!(!emitted.contains("RETIRED_ENGINE"), "{}", rendered(&app()));
  assert!(
    !emitted.contains(r#".field("retired""#),
    "{}",
    rendered(&app())
  );
}

/// A root that DID declare one grows the section, both accessors, and the engine as a `const` — the
/// word's own answer, carried across to whatever builds the store.
#[test]
fn a_declared_ledger_grows_the_section_and_names_its_engine() {
  let declared = GraphModel {
    retired: Some(crate::graph::RetiredLedger {
      engine: crate::model::DatabaseKind::Postgres,
    }),
    ..app()
  };
  let emitted = compact(&declared);
  assert!(
    emitted.contains("pub(crate)retired:::ingraph::__private::drive::RetiredOptions,"),
    "{}",
    rendered(&declared)
  );
  assert!(
    emitted.contains(
      "pubconstRETIRED_ENGINE:::ingraph::__private::drive::RetiredEngine=::ingraph::__private::\
       drive::RetiredEngine::Postgres;"
    ),
    "{}",
    rendered(&declared)
  );
  assert!(
    emitted.contains("pubconstfnretired(&self)->&::ingraph::__private::drive::RetiredOptions{"),
    "{}",
    rendered(&declared)
  );
  assert!(
    emitted.contains(
      "pubfnwith_retired(mutself,retired:::ingraph::__private::drive::RetiredOptions,)->Self{"
    ),
    "{}",
    rendered(&declared)
  );
  // The `Debug` prints the ledger's own value, on the registry seat's reasoning: it is the
  // framework's type, so printing it whole costs no bound anybody else pays.
  assert!(
    emitted.contains(r#".field("retired",&self.retired)"#),
    "{}",
    rendered(&declared)
  );
}

/// Each of the four words emits ITS OWN arm — the one place the codegen's database vocabulary
/// crosses into the runtime's engine word, so a drift between the two spellings is caught here
/// rather than as a path that does not exist in somebody's expansion.
#[test]
fn every_engine_word_emits_its_own_arm() {
  for (kind, arm) in [
    (crate::model::DatabaseKind::Sqlite, "Sqlite"),
    (crate::model::DatabaseKind::Postgres, "Postgres"),
    (crate::model::DatabaseKind::Mysql, "Mysql"),
    (crate::model::DatabaseKind::Mongo, "Mongo"),
  ] {
    let declared = GraphModel {
      retired: Some(crate::graph::RetiredLedger { engine: kind }),
      ..app()
    };
    assert!(
      compact(&declared).contains(&format!(
        "=::ingraph::__private::drive::RetiredEngine::{arm};"
      )),
      "{}",
      rendered(&declared)
    );
  }
}

/// The section is `#[serde(default)]`, so a deployment that names no `[retired]` block still parses
/// — an absent section being every knob at its default, which is where a store wired in code lives.
#[test]
fn the_retired_section_defaults() {
  let declared = GraphModel {
    retired: Some(crate::graph::RetiredLedger {
      engine: crate::model::DatabaseKind::Sqlite,
    }),
    ..app()
  };
  let emitted = compact(&declared);
  assert!(
    emitted.contains("#[serde(default)]pub(crate)retired:"),
    "{}",
    rendered(&declared)
  );
}