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
//! THE ENGINE WORD — `resource = "path::To::Resource"`, the `@oneOf` it mints, and the floor it publishes
//! in that engine's own currency.
//!
//! Beside [`columns`](super::columns) rather than inside [`tests`](super::tests), on that file's own
//! precedent: one file per thing being proved.
//!
//! # Every claim here is an ABSENCE too
//!
//! The word is ADDITIVE — today's state IS the fallback — so a suite that only read what a typed
//! declaration mints would pass while an untyped one grew a seat it never asked for. Each shape is
//! therefore read twice: what the word buys, and what a declaration that did not write it still has.
//!
//! What a token stream cannot show is asserted where the emission can be RUN, in `ingraph`'s own
//! `tests/fusion_doors.rs`: that the `@oneOf` publishes as one, that two engines' floors land at two
//! scalar widths, and that a type implementing no engine trait is `E0277` at the declaration.

use crate::{
  engine::{Engine, FieldEngines},
  index::{Dedup, Elected, ElectionLabel, IndexGraphql, IndexModel, Upstream},
  model::{GraphqlKind, NodeKind},
  prefix::EmissionPrefix,
};

fn ident(name: &str) -> syn::Ident {
  syn::Ident::new(name, proc_macro2::Span::call_site())
}

/// A declaration of `kind` with nothing elected — the base every fixture below narrows.
fn index(name: &str, kind: NodeKind) -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    numbers: crate::index::Numbers::default(),
    field_numbers: Vec::new(),
    index: ident(name),
    kind,
    vis: syn::parse_quote!(pub),
    krate: syn::parse_quote!(::ingraph),
    source: Upstream {
      node: syn::parse_quote!(Caption),
      projections: Vec::new(),
    },
    dedup: Dedup::Hash,
    embeddings: Vec::new(),
    labelled: Vec::new(),
    searchable: Vec::new(),
    engines: Vec::new(),
    stores: Vec::new(),
    data: false,
    keys: false,
    subscribe: false,
    graphql: Some(IndexGraphql::of(GraphqlKind::AsyncGraphql)),
    rename: None,
    slot: None,
    extension: None,
    // `false` is what the OTHER TWO KINDS always carry — the word is a blob's, refused by name on a
    // vector and on a full-text declaration, and every fixture below is one of those two.
    fields: Vec::new(),
  }
}

/// One engine block, POINTING or not — `None` is the word written bare, which is the ordinary
/// state.
fn engine(word: &str, resource: Option<syn::Path>) -> Engine {
  Engine {
    resource,
    ..Engine::bare(ident(word))
  }
}

fn blocks(field: &str, engines: Vec<Engine>, fanout: bool) -> FieldEngines {
  FieldEngines {
    field: ident(field),
    engines,
    fanout,
  }
}

/// A VECTOR declaration electing one field, its engines as given.
fn vector(engines: Vec<Engine>) -> IndexModel {
  let mut model = index("Shots", NodeKind::Vector);
  model.embeddings = vec![Elected::new(
    ident("clip"),
    ElectionLabel::Embedding,
    syn::parse_quote!(::ingraph::Embedding<f32, 4, Clip>),
    None,
  )];
  model.engines = vec![blocks("clip", engines, false)];
  model
}

/// A FULL-TEXT declaration electing two fields, each field's engines as given.
fn fulltext(body: Vec<Engine>, title: Vec<Engine>) -> IndexModel {
  let mut model = index("Transcript", NodeKind::Fulltext);
  model.searchable = vec![ident("body"), ident("title")];
  model.engines = vec![blocks("body", body, false), blocks("title", title, false)];
  model
}

/// The tier's tokens with every space taken out — what a claim about a TYPE or a row is read off.
fn compact(model: &IndexModel) -> String {
  model.tier().emit().to_string().split_whitespace().collect()
}

/// The tier's tokens, formatted — what a failing claim prints.
fn rendered(model: &IndexModel) -> String {
  let tokens = model.tier().emit();
  syn::parse2::<syn::File>(tokens.clone())
    .map_or_else(|_| tokens.to_string(), |file| prettyplease::unparse(&file))
}

/// `lance`, typed.
fn lance() -> Engine {
  engine("lance", Some(syn::parse_quote!(app::Lance)))
}

/// `hnsw`, typed at a DIFFERENT path — the second variant.
fn hnsw() -> Engine {
  engine("hnsw", Some(syn::parse_quote!(app::hnsw::Hnsw)))
}

// -------------------------------------------------------------------------------------------------
// THE PRESENCE LAW, on this axis
// -------------------------------------------------------------------------------------------------

/// **AN UNTYPED WORD EMITS NO VARIANT, AND A SLOT WITH NO TYPED WORD EMITS NO SEAT.** The word is
/// additive, so the declaration that says nothing has to keep exactly the package it had.
///
/// Asserted as three absences rather than as one, because they fail separately: a variant package
/// nobody can reach, an `@oneOf` with no variants (which is invalid SDL), and a leaf row typed on a
/// type this expansion did not emit.
#[test]
fn an_untyped_declaration_grows_no_engine_seat() {
  for model in [
    vector(vec![engine("lance", None)]),
    fulltext(vec![engine("tantivy", None)], Vec::new()),
  ] {
    let emitted = compact(&model);
    // `SearchOptions` rather than `options`, which is a substring of every leaf package's own name
    // (`ShotsClipVectorOptions`): the projection is the one spelling only the seat can produce.
    for absent in ["EngineInput", "engine:", "floor", "SearchOptions"] {
      assert!(
        !emitted.contains(absent),
        "an untyped declaration mints `{absent}`: {}",
        rendered(&model),
      );
    }
  }
}

/// **THE SEAT IS THE TYPED WORDS AND ONLY THEM.** One block typed and one bare on the same field is
/// the mixed case, and the untyped half contributes nothing — there is no currency to publish a
/// floor in.
#[test]
fn a_bare_word_beside_a_typed_one_contributes_no_variant() {
  let model = vector(vec![lance(), engine("hnsw", None)]);
  let emitted = compact(&model);
  assert!(
    emitted.contains("ShotsClipLanceEngineInput"),
    "the typed word has no variant: {}",
    rendered(&model),
  );
  assert!(
    !emitted.contains("ShotsClipHnswEngineInput"),
    "the BARE word grew a variant with no currency to fill it: {}",
    rendered(&model),
  );
}

// -------------------------------------------------------------------------------------------------
// THE SHAPE — the β4a hand pin, emitted
// -------------------------------------------------------------------------------------------------

/// **THE FLOOR PROJECTS OFF THE NAMED TYPE, THROUGH THE SLOT KIND'S OWN SEAM.** `VectorEngine` on a
/// knn declaration, `FulltextEngine` on a full-text one — which is the E0277 teeth as well as the
/// currency: a type implementing neither is refused at the span its author wrote.
#[test]
fn the_floor_is_the_named_types_own_score() {
  let vectors = compact(&vector(vec![lance()]));
  assert!(
    vectors.contains(
      "floor:::core::option::Option<<app::Lanceas::ingraph::__private::store::VectorEngine>::Score>"
    ),
    "{vectors}",
  );
  let documents = compact(&fulltext(
    vec![engine("tantivy", Some(syn::parse_quote!(app::Tantivy)))],
    Vec::new(),
  ));
  assert!(
    documents.contains(
      "floor:::core::option::Option<<app::Tantivyas::ingraph::__private::store::FulltextEngine>::Score>"
    ),
    "{documents}",
  );
}

/// **THE KNOBS PROJECT OFF THE NAMED TYPE TOO**, through the same seam the floor does — which
/// completes the ruled per-variant shape `{floor, options}` and puts the second half of the wire
/// duty on the same type the first half already named.
///
/// The teeth are the projection, exactly as the floor's are: a type implementing no engine trait is
/// `E0277` at the declaration for BOTH rows now, and neither needed a marker to say so.
#[test]
fn the_options_are_the_named_types_own_search_options() {
  let vectors = compact(&vector(vec![lance()]));
  assert!(
    vectors.contains(
      "options:::core::option::Option<<app::Lanceas::ingraph::__private::store::VectorEngine>::SearchOptions>"
    ),
    "{vectors}",
  );
  let documents = compact(&fulltext(
    vec![engine("tantivy", Some(syn::parse_quote!(app::Tantivy)))],
    Vec::new(),
  ));
  assert!(
    documents.contains(
      "options:::core::option::Option<<app::Tantivyas::ingraph::__private::store::FulltextEngine>::SearchOptions>"
    ),
    "{documents}",
  );
}

/// **THE TWO ROWS ARE ONE VARIANT'S**, and each engine gets its own pair — so a slot naming two
/// engines publishes two floors and two knob types rather than one of either.
#[test]
fn each_variant_carries_both_rows() {
  let model = vector(vec![hnsw(), lance()]);
  let emitted = compact(&model);
  for word in ["Hnsw", "Lance"] {
    let package = emitted
      .split(&format!("structShotsClip{word}EngineInput{{"))
      .nth(1)
      .and_then(|tail| tail.split('}').next())
      .unwrap_or_else(|| panic!("`{word}`'s package is emitted: {}", rendered(&model)));
    assert!(package.contains("floor:"), "{word}: {package}");
    assert!(package.contains("options:"), "{word}: {package}");
  }
}

/// **ONE `@oneOf` PER SLOT, ONE VARIANT PER TYPED WORD** — the hand pin's shape, reached by
/// emission.
#[test]
fn two_typed_engines_share_one_oneof() {
  let model = vector(vec![hnsw(), lance()]);
  let emitted = compact(&model);
  let choice = emitted
    .split("enumShotsClipEngineInput{")
    .nth(1)
    .and_then(|tail| tail.split('}').next())
    .expect("the choice is emitted");
  assert!(
    choice.contains("Hnsw(ShotsClipHnswEngineInput),")
      && choice.contains("Lance(ShotsClipLanceEngineInput),"),
    "{}",
    rendered(&model),
  );
  assert_eq!(
    emitted.matches("EngineInput),").count(),
    2,
    "the choice holds a variant this declaration did not type: {}",
    rendered(&model),
  );
  assert!(
    emitted.contains("oneof:true"),
    "the choice publishes as a record: {}",
    rendered(&model),
  );
}

/// **THE SEAT IS UNIFORM AT ONE VARIANT.** A slot naming one typed engine still publishes the
/// choice-shaped input, so a second engine is an ADDED VARIANT rather than a changed shape.
#[test]
fn one_typed_engine_still_publishes_a_choice() {
  let model = vector(vec![lance()]);
  let emitted = compact(&model);
  let choice = emitted
    .split("enumShotsClipEngineInput{")
    .nth(1)
    .and_then(|tail| tail.split('}').next())
    .expect("the choice is emitted");
  assert!(
    choice.contains("Lance(ShotsClipLanceEngineInput),"),
    "{}",
    rendered(&model),
  );
  assert_eq!(
    emitted.matches("EngineInput),").count(),
    1,
    "a one-word slot published more than one variant: {}",
    rendered(&model),
  );
}

/// **THE ROW IS ON THE LEAF, AND ITS WIRE NAME IS `engine`.**
#[test]
fn the_leaf_carries_the_choice() {
  let model = vector(vec![lance()]);
  let emitted = compact(&model);
  assert!(
    emitted.contains("engine:::core::option::Option<ShotsClipEngineInput>"),
    "{}",
    rendered(&model),
  );
  assert!(
    emitted.contains("fnwith_engine(mutself,engine:ShotsClipEngineInput)"),
    "the row has no factory leg: {}",
    rendered(&model),
  );
}

/// **THE WIRE WORD IS THE ENGINE'S OWN, IN lowerCamel** — the same casing every other row of every
/// package crosses under.
#[test]
fn the_variant_crosses_under_its_engine_word() {
  let emitted = compact(&vector(vec![engine(
    "my_engine",
    Some(syn::parse_quote!(app::Mine)),
  )]));
  assert!(emitted.contains("\"myEngine\""), "{emitted}");
  assert!(
    emitted.contains("ShotsClipMyEngineEngineInput"),
    "{emitted}"
  );
}

// -------------------------------------------------------------------------------------------------
// THE FULL-TEXT UNION
// -------------------------------------------------------------------------------------------------

/// **A FULL-TEXT TIER'S VOCABULARY IS THE UNION ACROSS ITS FIELDS, DEDUPED.** The tier is ONE ROUTE
/// however many fields it elects, so its package is one and the words a request can name are the
/// words the declaration writes anywhere. Two fields repeating a word is the ordinary shape.
#[test]
fn a_fulltext_tier_unions_its_fields_words() {
  let model = fulltext(
    vec![engine("tantivy", Some(syn::parse_quote!(app::Tantivy)))],
    vec![
      engine("tantivy", Some(syn::parse_quote!(app::Tantivy))),
      engine("sonic", Some(syn::parse_quote!(app::Sonic))),
    ],
  );
  let emitted = compact(&model);
  assert_eq!(
    emitted
      .matches("structTranscriptTantivyEngineInput{")
      .count(),
    1,
    "one word repeated on two fields minted two packages: {}",
    rendered(&model),
  );
  let choice = emitted
    .split("enumTranscriptEngineInput{")
    .nth(1)
    .and_then(|tail| tail.split('}').next())
    .expect("the choice is emitted");
  assert!(
    choice.contains("Tantivy(TranscriptTantivyEngineInput),")
      && choice.contains("Sonic(TranscriptSonicEngineInput),"),
    "{}",
    rendered(&model),
  );
}

/// **ONE WORD NAMING TWO ENGINES IS REFUSED BY NAME**, rather than left to `E0308` inside a package
/// nobody wrote. One vocabulary with two meanings is the exact class the fold vocabulary's own
/// shipped-word check refuses one family over.
#[test]
fn one_word_bound_to_two_engines_is_refused() {
  let model = fulltext(
    vec![engine("tantivy", Some(syn::parse_quote!(app::Tantivy)))],
    vec![engine("tantivy", Some(syn::parse_quote!(other::Tantivy)))],
  );
  let emitted = compact(&model);
  assert!(emitted.contains("compile_error!"), "{emitted}");
  assert!(
    emitted.contains("app::Tantivy") && emitted.contains("other::Tantivy"),
    "the refusal does not quote both bindings: {emitted}",
  );
}

// -------------------------------------------------------------------------------------------------
// THE ROSTERS
// -------------------------------------------------------------------------------------------------

/// **THE ROSTERS SWEEP WITH THE EMISSION.** Every type the seat lands in the declaring scope and
/// every method it lands on one is on the audit's list, in emission order — which is what makes a
/// collision between an engine's variant package and a neighbour's type a named refusal rather than
/// `E0428` at a span nobody wrote.
#[test]
fn the_seat_is_rostered() {
  let model = vector(vec![hnsw(), lance()]);
  let types: Vec<String> = model
    .tier()
    .emitted_types()
    .into_iter()
    .map(|name| name.to_string())
    .collect();
  assert_eq!(
    types,
    [
      "ShotsClipHnswEngineInput",
      "ShotsClipLanceEngineInput",
      "ShotsClipEngineInput",
      "ShotsClipVectorOptions",
      "ShotsClipVectorQuestion",
    ],
    "the roster is not the emission's own walk",
  );
  let methods: Vec<String> = model
    .tier()
    .emitted_methods()
    .into_iter()
    .map(|(on, name)| format!("{on}::{name}"))
    .collect();
  for owed in [
    "ShotsClipHnswEngineInput::with_floor",
    "ShotsClipLanceEngineInput::floor",
    "ShotsClipVectorOptions::with_engine",
    "ShotsClipVectorOptions::engine",
  ] {
    assert!(methods.contains(&owed.to_owned()), "{methods:?}");
  }
}

/// **AN UNTYPED DECLARATION'S ROSTER IS UNCHANGED** — the additive law, read on the audit's own
/// list rather than on the tokens.
#[test]
fn an_untyped_declarations_roster_names_no_engine() {
  let model = vector(vec![engine("lance", None)]);
  for name in model.tier().emitted_types() {
    assert!(
      !name.to_string().contains("EngineInput"),
      "an untyped declaration rosters `{name}`",
    );
  }
  for (on, name) in model.tier().emitted_methods() {
    assert!(
      name != "engine" && !on.to_string().contains("EngineInput"),
      "an untyped declaration rosters `{on}::{name}`",
    );
  }
}

/// **EVERY TYPED SHAPE PARSES AS A FILE.** The emission is written as tokens and read back as one,
/// which is the cheapest guard there is against a shape that only looks right in a string match.
#[test]
fn every_typed_shape_parses_as_a_file() {
  for model in [
    vector(vec![lance()]),
    vector(vec![hnsw(), lance()]),
    fulltext(
      vec![engine("tantivy", Some(syn::parse_quote!(app::Tantivy)))],
      Vec::new(),
    ),
  ] {
    let tokens = model.tier().emit();
    syn::parse2::<syn::File>(tokens.clone())
      .unwrap_or_else(|e| panic!("the tier does not parse: {e}\n{tokens}"));
  }
}