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
//! What the launch entry says, read off its tokens.
//!
//! What an entry DOES — a document launching a subset, the ruled order of the walks, a world that
//! feeds and stops — is asserted where the emission can be run, in `ingraph`'s own
//! `tests/ingraph_launch.rs`. What is here is what a token stream can be read for: the two names,
//! the parameters and their bounds, the node pass in declaration order, 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 entry 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 entry, formatted — what a failing claim prints.
pub(super) fn rendered(model: &GraphModel) -> String {
  prettyplease::unparse(&syn::parse2(model.launch().emit()).expect("the entry parses as a file"))
}

/// Both emitted names take the ROOT's own, so a deployment that learned `AppOptions` has learned
/// the family.
#[test]
fn the_node_bag_is_named_after_the_root() {
  assert_eq!(
    super::default_nodes_name(&syn::parse_quote!(App)),
    "AppNodes"
  );
  assert!(
    compact(&app()).contains("structAppNodes{"),
    "{}",
    rendered(&app())
  );
}

/// One slot per DECLARED node, holding that node's own type under an `Option` — which is
/// presence-is-enablement arriving at the far end of the walk.
#[test]
fn every_mount_gets_a_slot_holding_its_own_node() {
  let emitted = compact(&app());
  for (mount, node) in [
    ("videos", "media::Video"),
    ("scenes", "Scene"),
    ("search", "TranscriptText"),
  ] {
    let field = format!("{mount}:::core::option::Option<{node}>");
    assert!(emitted.contains(&field), "{field} in {}", rendered(&app()));
  }
}

/// A node leaves the bag by being TAKEN, because a resident owns the operator it runs.
#[test]
fn each_node_comes_out_of_the_bag_once() {
  let emitted = compact(&app());
  for mount in ["videos", "scenes", "search"] {
    let taker = format!("pubfntake_{mount}(&mutself)->::core::option::Option<");
    assert!(emitted.contains(&taker), "{taker} in {}", rendered(&app()));
  }
  assert!(
    emitted.contains("::core::option::Option::take(&mutself.videos)"),
    "{}",
    rendered(&app())
  );
}

/// The bag's `Debug` reports which slots are FILLED and never the nodes, so no author's type is
/// asked for a `Debug` it did not write.
#[test]
fn the_bag_reports_presence_rather_than_its_nodes() {
  let emitted = compact(&app());
  assert!(
    emitted.contains(r#".field("videos",&::core::option::Option::is_some(&self.videos))"#),
    "{}",
    rendered(&app())
  );
  assert!(
    !emitted.contains("derive(::core::fmt::Debug)"),
    "the bag's `Debug` is written, not derived: {}",
    rendered(&app())
  );
}

/// The entries are on the ROOT, async, and each hands back the framework's running world
/// PARAMETERISED BY THAT ROOT — `App<Self>`, which is the whole of what an emission contributes to
/// a type every indexer shares.
///
/// THREE of them: the converged pair a deployment reaches for first, and the hand-wired door beside
/// them for an arrangement that has a value only its author can name.
#[test]
fn the_entry_is_one_async_door_on_the_root() {
  let emitted = compact(&app());
  assert!(emitted.contains("implApp{"), "{}", rendered(&app()));
  assert!(
    emitted.contains("pubasyncfnlaunch_wired<__INGRAPH_PREPARE__,__INGRAPH_WIRE__>("),
    "{}",
    rendered(&app())
  );
  assert!(
    emitted.contains("pubasyncfnlaunch(options:AppOptions,)"),
    "the converged door takes ONE argument: {}",
    rendered(&app())
  );
  assert!(
    emitted.contains("pubasyncfnlaunch_with<__INGRAPH_PREPARE__>("),
    "{}",
    rendered(&app())
  );
  assert!(
    emitted.contains(
      "->::core::result::Result<::ingraph::__private::drive::App<Self>,::ingraph::__private::\
       drive::LaunchError,>"
    ),
    "{}",
    rendered(&app())
  );
}

/// The four parameters, in the order the sequence spends them: what this deployment runs, what the
/// declarations say, and the two walks an emission cannot spell.
#[test]
fn the_entry_takes_the_options_the_plan_and_the_two_walks_it_cannot_write() {
  let emitted = compact(&app());
  for parameter in [
    "options:AppOptions,",
    "plan:::ingraph::__private::drive::Plan,",
    "prepare:__INGRAPH_PREPARE__,",
    "wire:__INGRAPH_WIRE__,",
  ] {
    assert!(
      emitted.contains(parameter),
      "{parameter} in {}",
      rendered(&app())
    );
  }
}

/// `prepare` is ASYNC and takes the walk itself, because building a resource is I/O and the walk is
/// what carries the context a construction will read it out of.
#[test]
fn the_prepare_hook_is_an_async_call_on_the_create_walk() {
  assert!(
    compact(&app()).contains(
      "__INGRAPH_PREPARE__:::core::ops::AsyncFnOnce(&mut::ingraph::__private::drive::Creation<'_>,)\
       ->::core::result::Result<(),::ingraph::__private::drive::LaunchError>,"
    ),
    "{}",
    rendered(&app())
  );
}

/// `wire` is handed the built nodes and the wiring walk, and gives back an IGNITION — never a
/// running world. That is SOURCES LAST, kept structural through the emitted door: the caller may
/// register what it starts and cannot spend the moment it starts.
#[test]
fn the_wire_hook_gives_back_an_ignition_and_never_a_running_world() {
  let emitted = compact(&app());
  assert!(
    emitted.contains(
      "__INGRAPH_WIRE__:::core::ops::FnOnce(AppNodes,::ingraph::__private::drive::Wiring<'_>,)->::\
       core::result::Result<::ingraph::__private::drive::Ignition,::ingraph::__private::drive::\
       LaunchError,>,"
    ),
    "{}",
    rendered(&app())
  );
  assert!(
    emitted.contains(
      "::core::result::Result::Ok(::ingraph::__private::drive::Ignition::into_app::<Self>(__ingrap\
       h_ignition),)"
    ),
    "{}",
    rendered(&app())
  );
}

/// One `AsyncConstructor::Error` predicate per declared node, so a root nobody launches carries no
/// obligation and a node whose error cannot be erased is refused where the launch is written.
#[test]
fn the_erasure_each_node_owes_is_a_predicate_the_call_site_discharges() {
  let emitted = compact(&app());
  for node in ["media::Video", "Scene", "TranscriptText"] {
    let predicate = format!(
      "<{node}as::ingraph::__private::drive::AsyncConstructor>::Error:::core::error::Error+::core::\
       marker::Send+::core::marker::Sync+'static,"
    );
    assert!(
      emitted.contains(&predicate),
      "{predicate} in {}",
      rendered(&app())
    );
  }
}

/// The ENABLEMENT bridge is spent HERE and nowhere else: the plan states the declarations' topology
/// and the options state which of it this deployment runs, and the entry is where the two meet. The
/// root's own CATALOG is installed in the same breath and for the same reason — the resources a
/// deployment has are the root's fields, so a plan carries neither fact for long.
#[test]
fn the_options_own_enablement_replaces_the_plans() {
  assert!(
    compact(&app()).contains(
      "letmut__ingraph_creation=::ingraph::__private::drive::Wired::create(&__ingraph_wired,);"
    ),
    "{}",
    rendered(&app())
  );
  assert!(
    compact(&app()).contains(
      "let__ingraph_enablement=AppOptions::enablement(&options);let__ingraph_registries=::std::syn\
       c::Arc::new(::ingraph::__private::drive::Registries::new(::core::clone::Clone::clone(AppOpt\
       ions::registry(&options)),),);let__ingraph_wired=::ingraph::__private::drive::Plan::validate\
       (::ingraph::__private::drive::Plan::with_resources(::ingraph::__private::drive::Plan::with_e\
       nablement(plan,__ingraph_enablement,),Self::resources(),),)?;"
    ),
    "{}",
    rendered(&app())
  );
}

/// `prepare` runs BEFORE the first node is built — the ruled order, so a construction reaching for
/// a shared resource finds what the hook put there.
#[test]
fn the_hook_runs_before_the_first_node_is_built() {
  let emitted = compact(&app());
  let hook = emitted
    .find("prepare(&mut__ingraph_creation).await?;")
    .unwrap_or_else(|| panic!("{}", rendered(&app())));
  let first = emitted
    .find("Creation::node::<media::Video,>")
    .unwrap_or_else(|| panic!("{}", rendered(&app())));
  assert!(hook < first, "{}", rendered(&app()));
}

/// One `node` call per declared mount, in DECLARATION order, each with its own section moved out of
/// the options and its own bare-options probe spelled at the concrete type.
#[test]
fn the_node_pass_is_the_declaration_read_top_to_bottom() {
  let emitted = compact(&app());
  let mut at = 0;
  for (mount, node) in [
    ("videos", "media::Video"),
    ("scenes", "Scene"),
    ("search", "TranscriptText"),
  ] {
    let call = format!(
      "__ingraph_nodes.{mount}=::ingraph::__private::drive::Creation::node::<{node},>(\
       &mut__ingraph_creation,\"{mount}\",::core::option::Option::map(options.{mount},\
       ::ingraph::__private::drive::NodeSection::unshelved,),\
       ::ingraph::__private::drive::bare_options!({node}),).await?;"
    );
    let found = emitted
      .find(&call)
      .unwrap_or_else(|| panic!("{call} in {}", rendered(&app())));
    assert!(found >= at, "{call} out of order in {}", rendered(&app()));
    at = found;
  }
}

/// A root with no nodes emits the whole family anyway: an empty bag, an entry that builds nothing,
/// and no `where` clause a predicate would have had to be written into.
#[test]
fn a_root_with_no_nodes_still_has_a_door() {
  let empty = GraphModel {
    nodes: Vec::new(),
    mounts: Vec::new(),
    ..app()
  };
  let emitted = compact(&empty);
  assert!(emitted.contains("structAppNodes{}"), "{}", rendered(&empty));
  assert!(
    emitted.contains("let__ingraph_nodes=AppNodes{};"),
    "{}",
    rendered(&empty)
  );
}

/// A private root's entry stays private, so a crate-internal ingraph does not leak a launch door
/// into its crate's public API.
#[test]
fn the_entry_takes_the_roots_own_visibility() {
  let private = GraphModel {
    vis: syn::Visibility::Inherited,
    ..app()
  };
  let emitted = compact(&private);
  assert!(
    emitted.contains("structAppNodes{"),
    "{}",
    rendered(&private)
  );
  assert!(
    !emitted.contains("pubasyncfnlaunch"),
    "{}",
    rendered(&private)
  );
  assert!(
    emitted.contains("asyncfnlaunch_wired<"),
    "{}",
    rendered(&private)
  );
  assert!(
    emitted.contains("asyncfnlaunch(options:"),
    "{}",
    rendered(&private)
  );
}

/// Every framework path goes through the shelf, so an expansion never names a dependency the
/// declaring crate has no reason to have.
#[test]
fn every_framework_path_goes_through_the_shelf() {
  let emitted = rendered(&app());
  for line in emitted.lines() {
    assert!(
      !line.contains("ingraph::drive"),
      "a path outside the shelf: {line}"
    );
  }
}

/// A root with ONE slot-bearing member beside its nodes — what layer two and the sole-default law
/// are both read off.
fn retrieving() -> GraphModel {
  let mut model = app();
  model.fused = vec![crate::graph::FusedMember {
    mount: syn::parse_quote!(media),
    ty: syn::parse_quote!(index::Media),
    queried: false,
  }];
  model
}

/// **LAYER TWO SITS BETWEEN `prepare` AND THE FIRST NODE**, which is the whole of the ruled order:
/// the mounts exist by then, and a construction reaching a corpus finds it made.
#[test]
fn the_habitat_pass_runs_after_prepare_and_before_the_node_pass() {
  let model = retrieving();
  let emitted = compact(&model);
  let at = |needle: &str| {
    emitted
      .find(needle)
      .unwrap_or_else(|| panic!("{needle} is not emitted: {}", rendered(&model)))
  };

  let prepare = at("prepare(&mut__ingraph_creation).await?;");
  let habitat = at(
    "<index::Mediaas::ingraph::__private::drive::Habitats>::make(&mut__ingraph_creation,).await?;",
  );
  let node = at("__ingraph_nodes.videos=::ingraph::__private::drive::Creation::node::<");
  assert!(
    prepare < habitat && habitat < node,
    "prepare, then layer two, then the nodes: {}",
    rendered(&model)
  );
}

/// **THE COMPLETION BARRIER IS STRUCTURAL.** The pass is inside the create walk's own fallible
/// phase, so a refusal takes the arm every other create failure takes and everything already built
/// says its goodbyes — rather than being a discipline the entry keeps.
#[test]
fn a_refusing_walk_reaches_the_pre_ignition_unwind() {
  let model = retrieving();
  let emitted = compact(&model);
  let make = emitted
    .find("Habitats>::make(&mut__ingraph_creation,).await?;")
    .expect("the pass is emitted");
  let unwind = emitted
    .find("::ingraph::__private::drive::Creation::unwind(")
    .expect("the create half's unwind arm");
  let barrier = emitted
    .find("letmut__ingraph_ignition=")
    .expect("the ignition, which is where a graph starts serving");
  assert!(make < unwind, "{}", rendered(&model));
  assert!(unwind < barrier, "{}", rendered(&model));
}

/// **LAWS TWO AND THREE HAVE AN EMITTED CALLER.** Each member's unbound corpora reach `Plan::binding`
/// before the walk that resolves them, which is what makes the sole-default law reachable from a
/// launch rather than only from a hand-wired arrangement.
#[test]
fn the_unbound_corpora_reach_the_plan_before_it_is_validated() {
  let model = retrieving();
  let emitted = compact(&model);
  assert!(
    emitted.contains(
      "for__ingraph_corpusin<index::Mediaas::ingraph::__private::drive::Habitats>::UNBOUND{__ingrap\
       h_plan=::ingraph::__private::drive::Plan::binding(__ingraph_plan,::core::convert::Into::into\
       (__ingraph_corpus),);}"
    ),
    "{}",
    rendered(&model)
  );
  let binding = emitted.find("Plan::binding(").expect("the row is stated");
  let validate = emitted
    .find("::ingraph::__private::drive::Plan::validate(")
    .expect("the walk that resolves it");
  assert!(binding < validate, "{}", rendered(&model));
}

/// **MOUNTED IS VISITED, AT THE EMISSION.** Each member's TARGETS reach `Plan::mounting` before the
/// validate walk — which is what builds a store this deployment only READS, there being no node
/// anywhere holding a handle on it for the launch to read.
#[test]
fn the_pointed_targets_reach_the_plan_as_mounts_before_it_is_validated() {
  let model = retrieving();
  let emitted = compact(&model);
  assert!(
    emitted.contains(
      "for__ingraph_mountin<index::Mediaas::ingraph::__private::drive::Habitats>::TARGETS{__ingraph\
       _plan=::ingraph::__private::drive::Plan::mounting(__ingraph_plan,__ingraph_mount(),);}"
    ),
    "{}",
    rendered(&model)
  );
  let mounting = emitted.find("Plan::mounting(").expect("the row is stated");
  let validate = emitted
    .find("::ingraph::__private::drive::Plan::validate(")
    .expect("the walk that reads it");
  assert!(mounting < validate, "{}", rendered(&model));
  assert_eq!(
    emitted.matches("Habitats>::TARGETS").count(),
    2,
    "one in `launch_wired` and one in `launch_with`: {}",
    rendered(&model)
  );
}

/// A root that retrieves nothing emits NEITHER pass, and the plan is not even rebound: an emitted
/// loop over no members and a rename nobody spends are both noise in somebody else's crate.
#[test]
fn a_root_with_no_slot_bearing_member_emits_neither_pass() {
  let emitted = compact(&app());
  assert!(
    !emitted.contains("Habitats>::make("),
    "{}",
    rendered(&app())
  );
  assert!(!emitted.contains("Plan::binding("), "{}", rendered(&app()));
  assert!(!emitted.contains("Plan::mounting("), "{}", rendered(&app()));
  assert!(
    !emitted.contains("letmut__ingraph_plan=plan;"),
    "the hand-wired door's parameter goes straight into the walk: {}",
    rendered(&app())
  );
}

/// BOTH DOORS drive it. The completeness law is a property of the launch and not of which entry a
/// deployment happened to go through, so the hand-wired door carries the same two passes.
#[test]
fn the_hand_wired_door_carries_both_passes_too() {
  let model = retrieving();
  let emitted = compact(&model);
  assert_eq!(
    emitted
      .matches("Habitats>::make(&mut__ingraph_creation,).await?;")
      .count(),
    2,
    "one in `launch_wired` and one in `launch_with`: {}",
    rendered(&model)
  );
  assert!(
    emitted.contains("letmut__ingraph_plan=plan;"),
    "the hand-wired door rebinds its plan so the rows can be stated on it: {}",
    rendered(&model)
  );
}