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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
//! A derived index's emission, over models built BY HAND — `crate::tests`' rule, one tier over.

use crate::prefix::EmissionPrefix;
use quote::ToTokens as _;

use super::{
  Dedup, Elected, ElectionLabel, Fold, IndexGraphql, IndexModel, Labelled, Projected, Upstream,
};
use crate::model::{Column, GraphqlKind, NodeKind, Projection};

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

fn column(name: &str, ty: &str, project: Projection) -> Column {
  Column {
    name: ident(name),
    source: ident(name),
    ty: syn::parse_str(ty).expect("a type"),
    project,
  }
}

fn projected(field: &str, from: &str, ty: &str) -> Projected {
  Projected {
    field: ident(field),
    from: ident(from),
    ty: syn::parse_str(ty).expect("a type"),
  }
}

/// A two-field document over one upstream, with one field borrowed and one handed back by value —
/// so both accessor shapes are on the emitted type at once.
pub(super) fn document() -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    numbers: crate::index::Numbers::default(),
    field_numbers: Vec::new(),
    stores: Vec::new(),
    extension: None,
    data: false,
    keys: false,
    subscribe: false,
    graphql: Some(IndexGraphql::of(GraphqlKind::AsyncGraphql)),
    rename: None,
    slot: None,
    index: ident("SearchDocument"),
    kind: NodeKind::Fulltext,
    vis: syn::Visibility::Public(syn::token::Pub::default()),
    krate: syn::parse_quote!(::ingraph),
    source: Upstream {
      node: syn::parse_quote!(asr::Segment),
      projections: vec![
        projected("title", "speaker", "String"),
        projected("ordinal", "index", "u32"),
      ],
    },
    dedup: Dedup::Hash,
    // No embedding: `knn` is the vector kind's marker, and this is a full-text model.
    embeddings: Vec::new(),
    // The TEXT field alone wears `searchable`; `ordinal` is payload — hydrated with the document and
    // matched by nothing. The asymmetry is the point: a subject built from *every projection* would
    // name `ordinal` too, which is the posture the marker dissolved.
    labelled: Vec::new(),
    searchable: vec![ident("title")],
    // No engine named: the portable case, which declares the slots and leaves the deployment to
    // say where they are opened.
    engines: Vec::new(),
    fields: vec![
      column("title", "String", Projection::Borrowed),
      column("ordinal", "u32", Projection::Copied),
    ],
  }
}

/// One election, off a named field of the two-embedding declaration below — in the ANONYMOUS space,
/// which is what a field declaring no third argument is in.
fn elected(field: &str, width: &str) -> Elected {
  declared(
    field,
    &format!("Embedding<f32, {width}>"),
    ElectionLabel::Embedding,
  )
}

/// One election off a field of any declared spelling and label — the general form of [`elected`].
///
/// The width rides the fixture's TYPE and is spent nowhere in the model: every fact about the
/// coordinates is projected off that type in the emission, so what a fixture states here is what a
/// declaration states — the field, its label and its spelling.
fn declared(field: &str, ty: &str, label: ElectionLabel) -> Elected {
  Elected::new(
    ident(field),
    label,
    syn::parse_str(ty).expect("a type"),
    None,
  )
}

/// A two-embedding index over one upstream, electing the SECOND.
///
/// The order is the point everywhere this shape appears: an emission reading *the first field of
/// embedding type* would answer `caption_embedding`, so a test built on this model fails that reading
/// instead of coinciding with it.
pub(super) fn embedding_index() -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    stores: Vec::new(),
    extension: None,
    data: false,
    keys: false,
    subscribe: false,
    index: ident("SegmentEmbedding"),
    kind: NodeKind::Vector,
    source: Upstream {
      node: syn::parse_quote!(asr::Segment),
      projections: vec![
        projected(
          "caption_embedding",
          "caption_embedding",
          "Embedding<f32, 4>",
        ),
        projected("image_embedding", "image_embedding", "Embedding<f32, 4>"),
      ],
    },
    embeddings: vec![elected("image_embedding", "4")],
    // Stated rather than inherited from `document()`: a vector declaration takes no `searchable`
    // marker at all, so a model carrying one would be a shape the front end cannot produce.
    labelled: Vec::new(),
    searchable: Vec::new(),
    fields: vec![
      column(
        "caption_embedding",
        "Embedding<f32, 4>",
        Projection::Borrowed,
      ),
      column("image_embedding", "Embedding<f32, 4>", Projection::Borrowed),
    ],
    ..document()
  }
}

/// The same declaration electing BOTH of its embeddings, at two widths.
///
/// The widths differ on purpose: what a per-election method carries is ITS OWN election's width, so
/// a model where the two agreed would let a query type read off the wrong one and still pass.
pub(super) fn two_elections() -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    stores: Vec::new(),
    extension: None,
    data: false,
    keys: false,
    subscribe: false,
    embeddings: vec![
      elected("caption_embedding", "4"),
      elected("image_embedding", "8"),
    ],
    fields: vec![
      column(
        "caption_embedding",
        "Embedding<f32, 4>",
        Projection::Borrowed,
      ),
      column("image_embedding", "Embedding<f32, 8>", Projection::Borrowed),
    ],
    ..embedding_index()
  }
}

/// The emission, read back as a file — with every CONDITIONAL-EXPANSION GATE opened, as a build
/// carrying that feature would open it.
///
/// [`crate::tests::emission`]'s walk, reached rather than copied: the retrieve face rides the
/// observation gate pair, so a walk that stepped over a macro invocation would find no async impl at
/// all and every assertion below would pass vacuously.
///
/// # THE FUSION TREE IS SUBTRACTED, and that is a division of authority rather than a blind spot
///
/// A declaration now mints two independent families at module scope: the markers, doors and bindings
/// this suite is about, and the fusion packages [`crate::fuse`] is about. Every helper below counts
/// module-scope structs or module-scope inherent methods, and the second family has both — so
/// leaving it in would make every count here an assertion about a file the suite does not own, and
/// a package's own `new()` would read as a door.
///
/// Subtracted by TOKEN IDENTITY against the tier's own emission rather than by a name pattern: the
/// two come from the same tokens, so the match is exact and a package renamed tomorrow stays
/// subtracted without anybody editing a list here.
///
/// # AND SO IS THE WIRE CITIZENSHIP, on the same division and by the same mechanism
///
/// The query unit and its `Graphql` binding are a THIRD family at module scope — the mounting the
/// wire road minted, whose own suite is `index::citizen`. It lands a struct beside the markers, so
/// leaving it in would make every count here an assertion about a file this suite does not own,
/// exactly as the fusion tree would.
fn emission(model: &IndexModel) -> syn::File {
  use quote::ToTokens as _;

  let file: syn::File = syn::parse2(model.emit()).expect("the emission is a parsable file");
  let tier: syn::File =
    syn::parse2(model.tier().emit()).expect("the fusion tree is a parsable file");
  let citizen: syn::File =
    syn::parse2(model.citizen()).expect("the wire citizenship is a parsable file");
  let elsewhere: std::collections::HashSet<String> = tier
    .items
    .iter()
    .chain(citizen.items.iter())
    .map(|item| item.to_token_stream().to_string())
    .collect();
  let items = file
    .items
    .into_iter()
    .filter(|item| !elsewhere.contains(&item.to_token_stream().to_string()))
    .collect();
  syn::File {
    items: crate::tests::ungate(items),
    ..file
  }
}

/// The retrieve impl alone, rendered — the async inherent block, which is the one `shared` drops.
fn retrieve_source(model: &IndexModel) -> String {
  let file = emission(model);
  items(&file)
    .into_iter()
    .filter(|item| {
      matches!(item, syn::Item::Impl(block) if block.trait_.is_none() && block
      .items
      .iter()
      .any(|inner| matches!(inner, syn::ImplItem::Fn(method) if method.sig.asyncness.is_some())))
    })
    .map(rendered)
    .collect::<Vec<_>>()
    .join(" ")
}

/// Every item the emission declares, descending into the const the impls live in.
fn items(file: &syn::File) -> Vec<&syn::Item> {
  let mut found = Vec::new();
  for item in &file.items {
    found.push(item);
    if let syn::Item::Const(anonymous) = item
      && let syn::Expr::Block(block) = &*anonymous.expr
    {
      for statement in &block.block.stmts {
        if let syn::Stmt::Item(inner) = statement {
          found.push(inner);
        }
      }
    }
  }
  found
}

/// One emitted item, rendered — the whole assertion for the shapes whose content is a signature.
fn rendered(item: &syn::Item) -> String {
  item.to_token_stream().to_string()
}

/// The ONE-STORAGE MARKER is at MODULE SCOPE, and the placement is the whole mechanism: two markers
/// inside two anonymous consts would be two items in two scopes, colliding with nothing.
#[test]
fn the_marker_is_minted_beside_the_declaration_and_not_inside_the_const() {
  let file = emission(&document());
  let top: Vec<String> = file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Const(declared) => Some(declared.ident.to_string()),
      _ => None,
    })
    .collect();
  assert!(
    top.contains(&"__ig_SearchDocument_holds_one_storage".to_owned()),
    "the marker is a top-level item: {top:?}",
  );
}

/// NO `*Key` and NO `*Lineage` type — the two a record declares, and the two a node whose key is not
/// its to mint has nothing to declare.
///
/// Asserted as an ABSENCE over the walked items, because what would break the tier is a type
/// ARRIVING: a test that only read the types that are there would pass over an extra one.
#[test]
fn a_derived_index_declares_no_address_type_of_its_own() {
  let file = emission(&document());
  for item in items(&file) {
    assert!(
      !matches!(item, syn::Item::Struct(_) | syn::Item::Enum(_)),
      "a derived index mints no type: {}",
      rendered(item),
    );
  }
}

/// γ′ — the injected field: its name, its type and its visibility, decided by the emitter that reads
/// them back.
#[test]
fn the_carried_key_is_a_projection_of_the_upstreams() {
  let field = document().carried_key();
  assert_eq!(
    field.ident.as_ref().map(ToString::to_string),
    Some("__ig_key__".to_owned())
  );
  assert_eq!(
    field.ty.to_token_stream().to_string(),
    "< asr :: Segment as :: ingraph :: __private :: transform :: Transformer > :: Key",
    "the type is the UPSTREAM's key, named through the trait rather than copied — which is also \
     the bound that makes a path naming something other than a node `E0277`",
  );
  assert_eq!(
    field.vis.to_token_stream().to_string(),
    "pub (crate)",
    "the stamp every field of a declaration wears, with no exception carved for this one",
  );
}

/// The CONSTRUCTOR, which a record deliberately has none of: the macro added a field, so the struct
/// literal an author would write no longer names every field.
///
/// The key comes FIRST, because it is the argument the declaration did not declare.
#[test]
fn the_constructor_takes_the_carried_key_first() {
  let file = emission(&document());
  let new = methods(&file)
    .into_iter()
    .find(|method| method.sig.ident == "new")
    .expect("the constructor");
  let parameters: Vec<String> = new
    .sig
    .inputs
    .iter()
    .map(|input| input.to_token_stream().to_string())
    .collect();
  assert_eq!(
    parameters,
    [
      "__ig_key__ : < asr :: Segment as :: ingraph :: __private :: transform :: Transformer > :: \
       Key",
      "title : String",
      "ordinal : u32",
    ]
  );
}

/// `key_ref` and NO `key`: the by-value half is `Transformer::key`, and an inherent method of that
/// name would shadow it with a second spelling of one answer.
#[test]
fn the_carried_key_is_borrowed_and_never_shadowed() {
  let file = emission(&document());
  let names: Vec<String> = methods(&file)
    .into_iter()
    .map(|method| method.sig.ident.to_string())
    .collect();
  assert!(names.contains(&"key_ref".to_owned()), "{names:?}");
  assert!(
    !names.contains(&"key".to_owned()),
    "the inherent impl declares no `key`: {names:?}",
  );
}

/// EVERY member of the entity binding is a projection of the upstream's own, and the two that are
/// not are the empty product: a derived index becomes no row and shows no wire face.
///
/// `Id` is read off the KEY rather than off the upstream, and the difference is which impl has to
/// exist — this expansion borrows through the carried key, so what it needs is that the key answers.
#[test]
fn the_binding_projects_every_member_from_the_upstream() {
  let file = emission(&document());
  let binding = trait_impl(&file, "Transformer");
  let types = associated_types(binding);
  assert_eq!(
    types,
    [
      (
        "Key".to_owned(),
        "< asr :: Segment as :: ingraph :: __private :: transform :: Transformer > :: Key"
          .to_owned()
      ),
      (
        "Lineage".to_owned(),
        "< asr :: Segment as :: ingraph :: __private :: transform :: Transformer > :: Lineage"
          .to_owned()
      ),
      ("Record".to_owned(), "()".to_owned()),
      ("Graphql".to_owned(), "()".to_owned()),
    ]
  );
  let identifiable = trait_impl(&file, "Identifiable");
  assert_eq!(
    associated_types(identifiable),
    [(
      "Id".to_owned(),
      "< < asr :: Segment as :: ingraph :: __private :: transform :: Transformer > :: Key as :: \
       ingraph :: __private :: transform :: Identifiable > :: Id"
        .to_owned()
    )],
    "the id is the KEY's, which is the impl this expansion borrows through",
  );
}

/// ONE PROJECTION AUDIT PER FIELD, whose BODY is a direct field read of the upstream and whose
/// RETURN TYPE is the index field's own.
///
/// One function per field rather than one for the source, so the errors arrive one per mistake. A
/// direct read rather than an accessor call, because a record's accessor is spelled four ways
/// depending on the projection its own declaration asked for and this expansion cannot see which.
#[test]
fn one_audit_per_field_reads_the_upstream_field_directly() {
  let file = emission(&document());
  let audits: Vec<String> = items(&file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Fn(declared) if declared.sig.ident.to_string().starts_with("__ig_project_") => {
        Some(rendered(item))
      }
      _ => None,
    })
    .collect();
  assert_eq!(
    audits,
    [
      "# [allow (dead_code)] fn __ig_project_title (value : & asr :: Segment) -> & String { & \
       value . speaker }",
      "# [allow (dead_code)] fn __ig_project_ordinal (value : & asr :: Segment) -> & u32 { & value \
       . index }",
    ]
  );
}

/// The two FIXED names are enumerated for the front end, so a field deriving one of them is refused
/// at the declaration rather than inside the expansion.
///
/// Two of MANY: the fan door, the folds and the whole read surface are on the same table, and
/// [`super::audits`] is where its membership is pinned against the emission.
#[test]
fn the_emitted_methods_carry_the_two_names_the_emitter_fixes() {
  let names: Vec<String> = document()
    .emitted_methods()
    .into_iter()
    .map(|emitted| emitted.name.to_string())
    .collect();
  assert!(
    names.contains(&"new".to_owned()) && names.contains(&"key_ref".to_owned()),
    "{names:?}",
  );
  assert!(
    names.contains(&"title_ref".to_owned()) && names.contains(&"set_title".to_owned()),
    "beside every field's own family, mutators included: {names:?}",
  );
}

/// EVERY field takes the mutators, and the carried key takes none: the key is the upstream's answer
/// about which message this document is, and a document that could be re-keyed in place could lie
/// about where it came from.
#[test]
fn the_fields_are_mutable_and_the_carried_key_is_not() {
  let file = emission(&document());
  let names: Vec<String> = methods(&file)
    .into_iter()
    .map(|method| method.sig.ident.to_string())
    .collect();
  for mutator in ["set_title", "with_title", "set_ordinal", "with_ordinal"] {
    assert!(names.contains(&mutator.to_owned()), "{names:?}");
  }
  for withheld in ["set_key", "with_key", "set___ig_key__"] {
    assert!(!names.contains(&withheld.to_owned()), "{names:?}");
  }
}

/// The DOCUMENT half of the emission is one emission for all three storages: the carrier, the
/// entity binding and the projection audits are identical, and the kind's noun reaches only a doc
/// line.
///
/// TWO exceptions, each asserted separately and each a fact about what a kind IS rather than about
/// what an emitter got round to. The RETRIEVE face is the first — a `blob` answers an ADDRESS rather
/// than a ranking, so it has no hit stream to rank, and a `vector` waits on a declaration ruling. The
/// ARTIFACT BRIDGE is the second, and it is the mirror image: an artifact family is the only kind
/// whose objects another declaration serves, so it is the only kind that has to write its facts into
/// a type for that declaration to project. Comparing the whole emissions would have made the shared
/// claim untestable the moment either became true, which is what [`shared`] is for.
#[test]
fn the_word_reaches_the_prose_and_nothing_else() {
  let mut artifact = document();
  artifact.kind = NodeKind::Blob;
  let one = shared(&document());
  let other = shared(&artifact);
  assert_ne!(one, other, "the doc line carries the noun");
  assert_eq!(
    one.replace("a full-text index", ""),
    other.replace("an artifact family", ""),
    "and nothing else does",
  );
}

/// The RETRIEVE face is emitted for BOTH retrieving kinds and for neither the third.
///
/// `blob` never gets one, and that absence is permanent: an artifact family is addressed rather than
/// ranked, so there is no hit stream for a tier A to collapse. `vector` used to be here beside it,
/// waiting — first on a bound, which A′ removed by making `VectorEngine` R-free, and then on a FACT
/// no grammar stated. `embedding(<field>)` states it. See
/// [`IndexModel::retrieve`](super::IndexModel).
#[test]
fn both_retrieving_kinds_answer_and_the_artifact_family_does_not() {
  for (model, retrieves) in [
    (document(), true),
    (embedding_index(), true),
    (
      IndexModel {
        prefix: EmissionPrefix::default(),
        stores: Vec::new(),
        extension: None,
        data: false,
        keys: false,
        subscribe: false,
        kind: NodeKind::Blob,
        ..document()
      },
      false,
    ),
  ] {
    let names: Vec<String> = methods(&emission(&model))
      .into_iter()
      .map(|method| method.sig.ident.to_string())
      .collect();
    // The vector kind spells its pair PER ELECTION and the full-text kind spells one unsuffixed
    // pair, so what is shared between the two is the claim that a pair EXISTS rather than its name.
    let pair = if model.kind == NodeKind::Vector {
      [
        "retrieve_keys_by_image_embedding",
        "retrieve_by_image_embedding",
      ]
    } else {
      ["retrieve_keys", "retrieve"]
    };
    for verb in pair {
      assert_eq!(
        names.contains(&verb.to_owned()),
        retrieves,
        "{:?} and `{verb}`: {names:?}",
        model.kind,
      );
    }
  }
}

/// EVERY ELECTION gets its own QUAD, and there is no unsuffixed alias at any cardinality.
///
/// The single-election model is asserted beside the two-election one, because the claim that would
/// be easiest to get wrong is exactly the one about N = 1: a `retrieve_keys` emitted when a
/// declaration happens to elect once would be a name that MOVED the day a second `knn` marker
/// arrived, breaking callers of a method nobody edited.
///
/// It was a PAIR until the by-key read landed, a TRIPLE when the similar-by-example door joined it,
/// and it is a QUAD now that the read itself is a door. All four are suffixed by the same law and
/// for the same reason — each answers from ONE column — so the list grows by a row per election
/// rather than gaining a shape of its own.
///
/// The FULL-TEXT arm is the same law at a smaller count: a pair per election, suffixed by that same
/// reason, with no `get_` and no `similar` because a full-text by-key read has no grammar yet. What
/// it has that the vector arm does not is the UNSUFFIXED pair above the family — see
/// [`elections`](super::elections) for why that is not an alias for the N = 1 case.
///
/// The filter takes BOTH prefixes, for the reason [`elections::reads`](super::elections) states:
/// keyed on `retrieve` alone this list would call itself exhaustive while stepping straight over
/// `get_<field>`.
#[test]
fn every_election_is_spelled_and_none_is_aliased() {
  let named = |model: &IndexModel| -> Vec<String> {
    methods(&emission(model))
      .into_iter()
      .map(|method| method.sig.ident.to_string())
      .filter(|name| name.starts_with("retrieve") || name.starts_with("get_"))
      .collect()
  };

  assert_eq!(
    named(&embedding_index()),
    [
      "retrieve_keys_by_image_embedding",
      "retrieve_by_image_embedding",
      "get_image_embedding",
      "retrieve_similar_by_image_embedding",
    ],
    "one election is still spelled by its field",
  );
  assert_eq!(
    named(&two_elections()),
    [
      "retrieve_keys_by_caption_embedding",
      "retrieve_by_caption_embedding",
      "get_caption_embedding",
      "retrieve_similar_by_caption_embedding",
      "retrieve_keys_by_image_embedding",
      "retrieve_by_image_embedding",
      "get_image_embedding",
      "retrieve_similar_by_image_embedding",
    ],
    "two elections are two quads, in declared order",
  );
  assert_eq!(
    named(&document()),
    [
      "retrieve_keys",
      "retrieve",
      "retrieve_keys_by_title",
      "retrieve_by_title",
    ],
    "and the full-text kind is the whole-subject pair PLUS one per election — ONE election is two \
     pairs and not one, `All` and `These([title])` being two questions; there is still no \
     `get_title`, a full-text by-key read being a grammar this round does not own",
  );
}

/// Each election's pair carries ITS OWN column and ITS OWN width, and neither leaks into the other's.
///
/// The two elections declare different widths, so a method reading the FIRST election for every pair
/// would put `4` on both — which is the mutation this pins.
#[test]
fn each_election_asks_its_own_column_at_its_own_width() {
  let file = emission(&two_elections());
  let body = |name: &str| {
    methods(&file)
      .into_iter()
      .find(|method| method.sig.ident == name)
      .map(|method| {
        format!(
          "{} {}",
          method.sig.to_token_stream(),
          method.block.to_token_stream()
        )
      })
      .unwrap_or_else(|| panic!("`{name}` is emitted"))
  };

  for (method, column, width) in [
    (
      "retrieve_keys_by_caption_embedding",
      "caption_embedding",
      "__INGRAPH_WIDTH_CAPTION_EMBEDDING__",
    ),
    (
      "retrieve_keys_by_image_embedding",
      "image_embedding",
      "__INGRAPH_WIDTH_IMAGE_EMBEDDING__",
    ),
  ] {
    let emitted = body(method);
    assert!(
      emitted.contains(&format!("VectorColumn :: new (\"{column}\")")),
      "`{method}` asks for its own column: {emitted}",
    );
    assert!(
      emitted.contains(width),
      "`{method}` names its OWN election's width binding: {emitted}",
    );
  }

  // And tier B reaches ITS OWN tier A rather than the declaration's first.
  assert!(
    body("retrieve_by_image_embedding").contains("Self :: retrieve_keys_by_image_embedding"),
    "{}",
    body("retrieve_by_image_embedding"),
  );
}

/// The two flavours differ in the SEAM, the QUERY and the ENGINE CALL, and in nothing else.
///
/// Read as a difference rather than as two transcripts: what a change to the shared half would break
/// is both arms at once, and what this pins is that the flavour reaches exactly three positions.
#[test]
fn the_two_flavours_differ_in_three_positions() {
  let full = retrieve_source(&document());
  let vector = retrieve_source(&embedding_index());

  for (fulltext_only, vector_only) in [
    ("FulltextEngine", "VectorEngine"),
    ("AsyncFulltextRead", "AsyncVectorRead"),
    ("FulltextQuery", "VectorQuery"),
    (":: keyed ::", ":: vector_keyed ::"),
    ("search (slot", "knn (slot"),
    ("query . text ()", "query . coordinates ()"),
  ] {
    assert!(
      full.contains(fulltext_only) && !full.contains(vector_only),
      "the full-text arm names `{fulltext_only}` and not `{vector_only}`",
    );
    assert!(
      vector.contains(vector_only) && !vector.contains(fulltext_only),
      "the vector arm names `{vector_only}` and not `{fulltext_only}`",
    );
  }

  // And the SHARED half really is shared: tier B takes keys and gathers rows, by which point a knn
  // and a search have produced the same thing.
  //
  // THE ROW JOINED THIS LIST, and that is the engine cutover as a golden. It was a DIFFERENCE while
  // each family had its own engine-keyed row trait; a `Field` is engine-blind, so both arms now
  // demand the same one word and the row stopped being a thing a flavour decides.
  for both in [
    "store :: Field",
    "AsyncGather",
    "filled",
    "ranked_keys",
    "RetrieveError",
    "HashSeen",
  ] {
    assert!(
      full.contains(both) && vector.contains(both),
      "`{both}` is the pipeline's rather than a flavour's",
    );
  }

  // And the two retired names are absent from BOTH, which is what keeps the line above from reading
  // as a coincidence: `Field` matches inside `FulltextField`, so the shared assertion alone would
  // still hold on the day the per-engine row came back.
  for retired in ["FulltextField", "VectorField"] {
    assert!(
      !full.contains(retired) && !vector.contains(retired),
      "`{retired}` is deleted and no arm names it",
    );
  }
}

/// The vector query carries the DECLARATION's width, so the index's shape reaches its caller.
///
/// `N` is read off the elected field's own type and restated nowhere, which is the same one-home
/// rule that keeps `const DIM` off `VectorRecord`. Asking a 4-wide index with a 768-wide embedding
/// is `E0308` at the call because of this line.
#[test]
fn the_vector_query_carries_the_elected_fields_width() {
  let source = retrieve_source(&embedding_index());
  assert!(
    source.contains("VectorQuery < < __INGRAPH_ENGINE__ as")
      && source.contains(":: Element , < __INGRAPH_ENGINE__ as"),
    "the element and the score are the ENGINE's: {source}",
  );
  assert!(
    source.contains("__INGRAPH_WIDTH_IMAGE_EMBEDDING__")
      && source.contains("__INGRAPH_SPACE_IMAGE_EMBEDDING__"),
    "and the geometry is the elected field's own bindings: {source}",
  );
}

/// `impl VectorRecord` writes EVERY ELECTED FIELD and no other, and the unelected embedding is named
/// nowhere on any query path.
///
/// `embedding_index` declares `caption_embedding` FIRST and elects `image_embedding`, so an emission taking the
/// first embedding-typed field it found would answer `caption_embedding` — and this is the assertion that
/// would red. The absence half is the payload posture made mechanical: a field the word did not
/// elect reaches its own accessor and reaches nothing a knn can see, through ANY column.
#[test]
fn the_vector_record_projects_the_elected_field_and_no_other() {
  let file = emission(&embedding_index());
  let record = vector_record(&file);

  assert!(record.contains("& self . image_embedding"), "{record}");
  assert!(
    record.contains("VectorColumn :: new (\"image_embedding\")"),
    "under the name the election gave it: {record}",
  );
  assert!(
    !record.contains("caption_embedding"),
    "the payload embedding is not on this path: {record}",
  );
  assert!(
    record.contains("type Element = < < Embedding < f32 , 4 > as")
      && record.contains(":: Element ;")
      && record.contains("type Filter = ()"),
    "the element is the elected field's own projection and the filter is the empty product: \
     {record}",
  );

  // And the QUERY PATH does not name it either. The payload is reachable — through its own accessor
  // family, and as a constructor argument, which is exactly what *stored and hydrated* means — so
  // the claim worth pinning is the narrow one: no emitted tier mentions the field the word did not
  // elect, so no knn can be routed through it.
  let path = retrieve_source(&embedding_index());
  assert!(
    !path.contains("caption_embedding"),
    "no tier names the payload embedding: {path}",
  );
  assert!(
    methods(&file)
      .iter()
      .any(|method| method.sig.ident == "caption_embedding_ref"),
    "and it is not unreachable — a payload is stored and hydrated, just never knn'd",
  );
}

/// **ONE ELECTION MARKER PER ELECTION, AT MODULE SCOPE — and the placement is the mechanism.**
///
/// The marker is what a lane names, so it has to be spellable from the scope the declaration was
/// written in; inside the anonymous `const` it would be reachable only by the expansion itself. It
/// is the one-storage marker's placement argument reaching a second item, for the opposite reason —
/// that one moves out to COLLIDE, and this one to be CALLED.
///
/// The name carries the declaration's, which is the naming law every item this family mints in the
/// declarer's scope is under: two declarations electing a field of the same name are an ordinary
/// program, and a marker named after the field alone would make the second one `E0428`.
#[test]
fn every_election_mints_a_marker_beside_the_declaration() {
  let file = emission(&two_elections());
  let top: Vec<String> = file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Struct(declared) => Some(declared.ident.to_string()),
      _ => None,
    })
    .collect();

  assert_eq!(
    top,
    [
      "SegmentEmbeddingByCaptionEmbedding",
      "SegmentEmbeddingByImageEmbedding"
    ],
    "one per election, in declared order, each carrying the declaration's name",
  );

  let source = items(&file)
    .into_iter()
    .filter(|item| matches!(item, syn::Item::Impl(block) if block.trait_.is_some()))
    .map(rendered)
    .collect::<Vec<_>>()
    .join(" ");
  assert!(
    source.contains("Elected < SegmentEmbedding > for SegmentEmbeddingByCaptionEmbedding")
      && source.contains("VectorColumn :: new (\"caption_embedding\")"),
    "the first marker answers with the first election's column: {source}",
  );
  assert!(
    source.contains("Elected < SegmentEmbedding > for SegmentEmbeddingByImageEmbedding")
      && source.contains("VectorColumn :: new (\"image_embedding\")"),
    "and the second with the second's: {source}",
  );
}

/// A declaration that ELECTS NOTHING mints no marker, and neither absence is an oversight.
///
/// A full-text declaration ELECTS, and still mints nothing here: the vector marker is parameterized
/// by a `VectorColumn`, and the full-text engine seam has no column for one to name. The `blob` kind
/// is the same absence for a different reason: an artifact family is addressed rather than ranked,
/// so it elects nothing at all.
#[test]
fn a_declaration_that_elects_nothing_mints_no_marker() {
  let file = emission(&document());

  assert!(
    !file
      .items
      .iter()
      .any(|item| matches!(item, syn::Item::Struct(_))),
    "a full-text declaration has no election to name",
  );
}

/// The record face writes ALL the elected columns, in declared order, each under its own name.
///
/// The WRITE half is where a second election is easiest to drop: the read half would still emit its
/// pair, so the column would be queryable and empty. Dropping a pair here is the mutation this pins.
#[test]
fn the_record_face_writes_every_election() {
  let record = vector_record(&emission(&two_elections()));

  assert!(
    record.contains("VectorColumn :: new (\"caption_embedding\")")
      && record.contains("self . caption_embedding")
      && record.contains("VectorColumn :: new (\"image_embedding\")")
      && record.contains("self . image_embedding"),
    "both elections are written: {record}",
  );
  assert!(
    record
      .find("caption_embedding")
      .zip(record.find("image_embedding"))
      .is_some_and(|(first, second)| first < second),
    "in the order the declaration elected them: {record}",
  );
  assert!(
    record.contains("type Element = < < Embedding < f32 , 4 > as"),
    "at the one element a slot materializes — the FIRST election's projection, which every other \
     election's has to unify with: {record}",
  );
}

/// The one emitted `impl VectorRecord`, rendered.
fn vector_record(file: &syn::File) -> String {
  items(file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Impl(block) if block.trait_.is_some() => Some(rendered(item)),
      _ => None,
    })
    .find(|source| source.contains("VectorRecord"))
    .expect("the vector kind emits the record face")
}

/// A blob model carries no election and emits no record face — the word is the vector kind's.
#[test]
fn only_an_embedding_index_states_its_coordinates() {
  for model in [
    document(),
    IndexModel {
      prefix: EmissionPrefix::default(),
      stores: Vec::new(),
      extension: None,
      data: false,
      keys: false,
      subscribe: false,
      kind: NodeKind::Blob,
      ..document()
    },
  ] {
    assert!(
      !shared(&model).contains("VectorRecord"),
      "{:?} states no coordinates",
      model.kind,
    );
  }
}

/// The two mechanisms differ in the MEMBERSHIP named and in the BOUND carried, and in nothing else
/// — which is what makes `dedup(…)` a bounds choice rather than a second pipeline.
#[test]
fn the_dedup_word_picks_a_membership_and_a_bound() {
  let mut listed = document();
  listed.dedup = Dedup::Eq;
  let hashed = emission(&document()).to_token_stream().to_string();
  let listed = emission(&listed).to_token_stream().to_string();

  assert!(hashed.contains("retrieve :: HashSeen"), "{hashed}");
  assert!(
    hashed.contains(":: core :: hash :: Hash + :: core :: cmp :: Eq + :: core :: clone :: Clone"),
    "{hashed}",
  );
  assert!(!hashed.contains("EqSeen"), "{hashed}");

  assert!(listed.contains("retrieve :: EqSeen"), "{listed}");
  assert!(
    listed.contains(":: core :: cmp :: PartialEq + :: core :: clone :: Clone"),
    "{listed}",
  );
  assert!(!listed.contains("HashSeen"), "{listed}");
  assert!(!listed.contains(":: core :: hash :: Hash"), "{listed}");

  // Everything OUTSIDE the two positions is the same emission.
  assert_eq!(
    hashed
      .replace("HashSeen", "")
      .replace(":: core :: hash :: Hash + :: core :: cmp :: Eq + ", ""),
    listed
      .replace("EqSeen", "")
      .replace(":: core :: cmp :: PartialEq + ", ""),
  );
}

/// TIER A is the engine alone and TIER B composes the store onto it: the first names no gather at
/// all, and the second names it in its store parameter, its filter, its answer and its refusal.
#[test]
fn the_two_tiers_are_the_engine_and_the_engine_plus_the_store() {
  let file = emission(&document());
  // The SIGNATURE and the BODY, not the doc comment — a doc line saying *no filter* is prose and
  // this is about the emitted code.
  let rendered = |name: &str| {
    methods(&file)
      .into_iter()
      .find(|method| method.sig.ident == name)
      .map(|method| {
        (
          method.sig.to_token_stream().to_string(),
          method.block.to_token_stream().to_string(),
        )
      })
      .unwrap_or_else(|| panic!("`{name}` is emitted"))
  };

  let (keys, body) = rendered("retrieve_keys");
  // THE BRAND: the engine arrives inside `SlotHandle<E, Self>`, so the DECLARATION is named in the
  // signature and a wrong-slot read is `E0308` naming both.
  assert!(
    keys.contains(
      "slot : & mut :: ingraph :: __private :: store :: SlotHandle < __INGRAPH_ENGINE__ , Self >"
    ),
    "{keys}",
  );
  assert!(body.contains("SlotHandle :: search (slot ,"), "{body}");
  // bytes → Key, the emission's own line — and the KEY is named in it, because the engine cannot.
  assert!(
    body.contains("retrieve :: keyed :: < __INGRAPH_ENGINE__ , < asr :: Segment as"),
    "{body}",
  );
  assert!(body.contains("ranked_keys"), "{body}");
  // The engine seam takes NO record parameter anywhere in the signature — A′ as a token assertion.
  assert!(
    !keys.contains("FulltextEngine < Self >"),
    "the seam is R-free: {keys}",
  );
  // And the key's ROW is demanded at the call, which is what makes a type with no row a refusal
  // there rather than a surprise at runtime. It names NO ENGINE — `Field` is one impl per TYPE — so
  // the bound is one word rather than one per engine, and the retired spelling is pinned absent
  // beside it because `Field` matches inside `FulltextField`.
  assert!(keys.contains("store :: Field"), "{keys}");
  assert!(
    !keys.contains("FulltextField"),
    "the row is engine-blind: {keys}"
  );
  // The LEASE is the read face's and the vocabulary is the base's, so the signature names both
  // traits — which is the seam split visible in one emitted `where`.
  assert!(
    keys.contains("__INGRAPH_ENGINE__ : :: ingraph :: __private :: store :: AsyncFulltextRead"),
    "{keys}",
  );
  assert!(
    !keys.contains("AsyncGather"),
    "tier A takes no store: {keys}"
  );
  assert!(!keys.contains("filter"), "tier A takes no filter: {keys}");

  let (whole, body) = rendered("retrieve");
  // Tier B carries the same brand — a wrong-slot read is refused on both tiers, not just one.
  assert!(
    whole.contains(
      "slot : & mut :: ingraph :: __private :: store :: SlotHandle < __INGRAPH_ENGINE__ , Self >"
    ),
    "{whole}",
  );
  assert!(whole.contains("retrieve :: AsyncGather"), "{whole}");
  assert!(whole.contains("filter :"), "{whole}");
  assert!(body.contains("retrieve :: filled"), "{body}");
  assert!(whole.contains("RetrieveError"), "{whole}");
  // The UPSTREAM entity is what tier B answers with — not the key, and not this declaration.
  assert!(
    whole.contains("Ranked < asr :: Segment ,"),
    "tier B answers with the whole upstream entity: {whole}",
  );
  // And tier A runs UNBOUNDED under it, because the fill loop's filter is what limits the page. The
  // SPELLING is the door family's own currency since the retype — `NonZeroUsize::MAX` — and the
  // MEANING is unchanged; `index::k_seat` is where that pair is asserted as a pair.
  assert!(body.contains("NonZeroUsize :: MAX"), "{body}");
}

/// THE ARTIFACT BRIDGE is emitted for the BLOB kind and for neither of the other two.
///
/// The presence law at the kind: an artifact family is the only one whose objects another
/// declaration serves, so it is the only one that writes its facts into a type. A full-text index
/// hands back a RANKING and a vector index a neighbourhood; neither has an address for somebody
/// else's wire face to answer, so neither has anything to bridge.
///
/// The EXCLUSIONS are what make this a claim about the kind rather than about one word: a fulltext
/// model and a vector one are asked for the same four traits and must have none of them.
#[test]
fn the_artifact_bridge_is_the_blob_kinds_alone() {
  let blob = {
    let mut model = document();
    model.kind = NodeKind::Blob;
    emitted(&model)
  };

  assert!(
    blob.contains("record :: BlobArtifact for SearchDocument"),
    "{blob}"
  );
  assert!(
    blob.contains("record :: ArtifactSuffix < __INGRAPH_ROW__ > for SearchDocument"),
    "{blob}"
  );
  // The SLOT is the declaration's own name, snake-cased — the convention every durable name a
  // declaration mints already takes.
  assert!(
    blob.contains("SlotName :: new (\"search_document\")"),
    "{blob}"
  );

  for kind in [NodeKind::Fulltext, NodeKind::Vector] {
    let mut model = document();
    model.kind = kind;
    let other = emitted(&model);
    for trait_name in [
      "BlobArtifact",
      "ArtifactSuffix",
      "ArtifactStore",
      "ArtifactData",
    ] {
      assert!(
        !other.contains(trait_name),
        "{kind:?} binds {trait_name}: {other}"
      );
    }
  }
}

/// A family that named NO store this crate can spell gets no `ArtifactStore`, and that absence is
/// the openness: a word bound at a graph root is a type no expansion can see, so the impl is left
/// for whoever can name it. `data` without a spellable store is the same absence one trait further
/// out — reading takes a store.
#[test]
fn the_store_impls_follow_the_shipped_word_and_the_data_word() {
  let bare = {
    let mut model = document();
    model.kind = NodeKind::Blob;
    model.data = true;
    emitted(&model)
  };
  assert!(!bare.contains("ArtifactStore"), "{bare}");
  assert!(!bare.contains("ArtifactData"), "{bare}");

  let shipped = {
    let mut model = document();
    model.kind = NodeKind::Blob;
    model.stores = vec![crate::engine::Engine::bare(ident("fs"))];
    emitted(&model)
  };
  assert!(
    shipped.contains("record :: ArtifactStore for SearchDocument"),
    "{shipped}"
  );
  // The EXCLUSION: the capability follows the WORD, so a family that did not write `data` has no
  // `ArtifactData` however spellable its store is.
  assert!(!shipped.contains("ArtifactData"), "{shipped}");

  let served = {
    let mut model = document();
    model.kind = NodeKind::Blob;
    model.stores = vec![crate::engine::Engine::bare(ident("fs"))];
    model.data = true;
    emitted(&model)
  };
  assert!(
    served.contains("record :: ArtifactData for SearchDocument"),
    "{served}"
  );
}

/// The whole expansion as one string — what a presence claim about a trait impl reads.
fn emitted(model: &IndexModel) -> String {
  model.emit().to_string()
}

/// The DOCUMENT half of an emission — everything but the two parts the three storages do NOT share.
///
/// It drops the anonymous `const` WRAPPER (which holds every inner item and would therefore carry
/// the retrieve face back in) and keeps the marker beside the inner items. Then it drops the two
/// exceptions by name: the retrieve face, recognised by the async method on its inherent impl, and
/// the ARTIFACT BRIDGE, recognised by the framework traits only an artifact family binds. What is
/// left is exactly the set the three storages must agree on.
fn shared(model: &IndexModel) -> String {
  /// The bridge's four traits, by their last path segment — the set only an artifact family binds.
  const BRIDGE: &[&str] = &[
    "BlobArtifact",
    "ArtifactSuffix",
    "ArtifactStore",
    "ArtifactData",
  ];

  let file = emission(model);
  items(&file)
    .into_iter()
    .filter(|item| !matches!(item, syn::Item::Const(anonymous) if matches!(&*anonymous.expr, syn::Expr::Block(_))))
    .filter(|item| !matches!(item, syn::Item::Impl(block) if block.trait_.is_none() && block
      .items
      .iter()
      .any(|inner| matches!(inner, syn::ImplItem::Fn(method) if method.sig.asyncness.is_some()))))
    .filter(|item| !matches!(item, syn::Item::Impl(block) if block
      .trait_
      .as_ref()
      .and_then(|(path, _)| path.segments.last())
      .is_some_and(|segment| BRIDGE.contains(&&*segment.ident.to_string()))))
    .map(|item| item.to_token_stream().to_string())
    .collect::<Vec<_>>()
    .join(" ")
}

/// Every inherent method the emission declares, descending into the const the impl lives in.
fn methods(file: &syn::File) -> Vec<&syn::ImplItemFn> {
  items(file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Impl(declared) if declared.trait_.is_none() => Some(declared),
      _ => None,
    })
    .flat_map(|declared| &declared.items)
    .filter_map(|item| match item {
      syn::ImplItem::Fn(method) => Some(method),
      _ => None,
    })
    .collect()
}

/// The one impl of a named trait, by its last path segment.
fn trait_impl<'a>(file: &'a syn::File, name: &str) -> &'a syn::ItemImpl {
  items(file)
    .into_iter()
    .find_map(|item| match item {
      syn::Item::Impl(declared)
        if declared
          .trait_
          .as_ref()
          .and_then(|(path, _)| path.segments.last())
          .is_some_and(|segment| segment.ident == name) =>
      {
        Some(declared)
      }
      _ => None,
    })
    .unwrap_or_else(|| panic!("an impl of `{name}`"))
}

/// One impl's associated types, in the order they were written.
fn associated_types(declared: &syn::ItemImpl) -> Vec<(String, String)> {
  declared
    .items
    .iter()
    .filter_map(|item| match item {
      syn::ImplItem::Type(bound) => Some((
        bound.ident.to_string(),
        bound.ty.to_token_stream().to_string(),
      )),
      _ => None,
    })
    .collect()
}

/// A SET-ELECTING model over the same upstream: one set election beside one single election, the SET
/// declared and elected FIRST.
///
/// The order is the point: an emission reporting every election through one face would put the set's
/// members under a single-election column or the poster under an ordinal, and the partition below is
/// what reds both readings.
fn set_index() -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    numbers: crate::index::Numbers::default(),
    field_numbers: Vec::new(),
    stores: Vec::new(),
    extension: None,
    data: false,
    keys: false,
    subscribe: false,
    graphql: Some(IndexGraphql::of(GraphqlKind::AsyncGraphql)),
    rename: None,
    slot: None,
    index: ident("ClipVectors"),
    kind: NodeKind::Vector,
    source: Upstream {
      node: syn::parse_quote!(media::Clip),
      projections: vec![
        projected("frames", "frame_vecs", "Vec<Embedding<f32, 4>>"),
        projected("poster", "poster_vec", "Embedding<f32, 4>"),
      ],
    },
    embeddings: vec![
      declared("frames", "Vec<Embedding<f32, 4>>", ElectionLabel::List),
      elected("poster", "4"),
    ],
    labelled: Vec::new(),
    searchable: Vec::new(),
    engines: Vec::new(),
    fields: vec![
      column("frames", "Vec<Embedding<f32, 4>>", Projection::Borrowed),
      column("poster", "Embedding<f32, 4>", Projection::Borrowed),
    ],
    vis: syn::parse_quote!(pub),
    krate: syn::parse_quote!(::ingraph),
    dedup: Dedup::Hash,
  }
}

/// **THE LABEL IS THE MODEL'S ONLY SHAPE FACT**, and the field's type is carried WHOLE beside it —
/// unpeeled, unread, and identical in the model to whatever the author wrote.
#[test]
fn the_label_states_the_shape_and_the_type_is_carried_whole() {
  let one = declared("poster", "Embedding<f32, 768>", ElectionLabel::Embedding);
  let many = declared("frames", "Vec<Embedding<f32, 768>>", ElectionLabel::List);

  assert_eq!(one.label, ElectionLabel::Embedding);
  assert_eq!(many.label, ElectionLabel::List);
  assert!(!one.label.is_set() && many.label.is_set());
  assert_eq!(
    many.ty.to_token_stream().to_string(),
    "Vec < Embedding < f32 , 768 > >",
    "the declared type, unpeeled",
  );
  assert_eq!(
    one.ty.to_token_stream().to_string(),
    "Embedding < f32 , 768 >",
  );
}

/// **AN ALIAS IS AN ELECTION.** The model holds the token the author wrote and asks nothing of it,
/// so a field spelled `ClipFrames` carries the same label and the same road as one spelled out —
/// which is the whole of what the type-read cost and could not give.
#[test]
fn an_alias_is_carried_exactly_as_a_spelled_out_type_is() {
  let aliased = declared("frames", "ClipFrames", ElectionLabel::List);

  assert_eq!(aliased.label, ElectionLabel::List);
  assert_eq!(aliased.ty.to_token_stream().to_string(), "ClipFrames");
}

/// **THE DECLARED FOLD IS EMITTED FOR A SET ELECTION AND FOR NOTHING ELSE**, and an election that
/// wrote no word falls back to the shipped citizen rather than to nothing.
#[test]
fn the_declared_fold_is_emitted_per_set_election() {
  let source = set_index().emit().to_string();

  assert!(
    source.contains("fn fold_by_frames ()") && !source.contains("fn fold_by_poster ()"),
    "one accessor, for the election whose label states a set: {source}",
  );
  assert!(
    source.contains("retrieve :: Sum"),
    "an election that declared no fold takes the shipped one: {source}",
  );

  let mut declared = set_index();
  declared.embeddings[0].fold = Some(Fold::Custom(syn::parse_quote!(app::PositionWeighted)));
  let named = declared.emit().to_string();
  assert!(
    named.contains("fn fold_by_frames () -> app :: PositionWeighted")
      && named.contains("as :: core :: default :: Default > :: default ()"),
    "and a declared one is constructed through `Default`: {named}",
  );

  // THE SHORTHAND resolves to the framework's own citizen, through the SHELF — which is why the
  // resolution lives in the emission and not in the front end: this is the one layer that knows
  // where the shelf is.
  let mut shipped = set_index();
  shipped.embeddings[0].fold = Some(Fold::Max);
  let by_word = shipped.emit().to_string();
  assert!(
    by_word.contains("fn fold_by_frames () -> :: ingraph :: __private :: retrieve :: Max")
      && by_word.contains("as :: core :: default :: Default > :: default ()"),
    "`fold(max)` names the citizen and builds it the same way: {by_word}",
  );
}

/// **AN UNELECTED LABEL IS AUDITED TOO** — accepted is not unexamined. The claim is the same claim,
/// so it meets the same compiler; what it does NOT grow is a face.
#[test]
fn a_labelled_payload_field_is_audited_and_grows_no_face() {
  let mut model = set_index();
  model.labelled = vec![Labelled::new(
    ident("caption"),
    ElectionLabel::Embedding,
    syn::parse_str("Embedding<f32, 4>").expect("a type"),
  )];
  let source = model.emit().to_string();

  assert!(
    source.contains("elects_one :: < Embedding < f32 , 4 > >"),
    "the payload label's claim is stated: {source}",
  );
  assert!(
    !source.contains("VectorColumn :: new (\"caption\")")
      && !source.contains("fold_by_caption")
      && !source.contains("retrieve_keys_by_caption"),
    "and nothing else grows for it: {source}",
  );
}

/// The two labels name the two framework multiplicity markers and the two audits, which is what
/// keeps the emission's claim and the declaration's word one fact.
#[test]
fn each_label_names_its_marker_and_its_audit() {
  assert_eq!(ElectionLabel::Embedding.as_str(), "embedding");
  assert_eq!(ElectionLabel::List.as_str(), "list(embedding)");
  assert_eq!(ElectionLabel::Embedding.multiplicity(), "One");
  assert_eq!(ElectionLabel::List.multiplicity(), "Set");
  assert_eq!(ElectionLabel::Embedding.audit(), "elects_one");
  assert_eq!(ElectionLabel::List.audit(), "elects_a_set");
}

/// **THE AUDIT IS EMITTED PER ELECTION**, holding each field's own type to the label it wrote — so a
/// lying label is `E0277` at the election word rather than a face silently emitted for the wrong
/// shape.
#[test]
fn every_election_emits_the_audit_its_label_claims() {
  let source = set_index().emit().to_string();

  assert!(
    source.contains("elects_a_set :: < Vec < Embedding < f32 , 4 > > >"),
    "the set election's claim: {source}",
  );
  assert!(
    source.contains("elects_one :: < Embedding < f32 , 4 > >"),
    "and the single election's: {source}",
  );
}

/// **NO FACT IS READ OFF A TOKEN.** The width and the space reach the emitted signatures as
/// PROJECTIONS through the election family, so an alias, a re-export and a downstream carrier all
/// answer where a peel would have refused.
#[test]
fn the_width_and_the_space_are_projected_rather_than_spelled() {
  let mut aliased = set_index();
  aliased.embeddings[0] = declared("frames", "ClipFrames", ElectionLabel::List);
  let source = retrieve_source(&aliased);

  assert!(
    source.contains("__INGRAPH_WIDTH_FRAMES__") && source.contains("__INGRAPH_SPACE_FRAMES__"),
    "the signatures name the bindings: {source}",
  );

  let whole = aliased.emit().to_string();
  assert!(
    whole.contains("const __INGRAPH_WIDTH_FRAMES__ : usize = << ClipFrames as")
      && whole.contains(":: WIDTH ;"),
    "and the binding is the ALIAS's own projection, unread by this crate: {whole}",
  );
  assert!(
    whole.contains("type __INGRAPH_SPACE_FRAMES__ = << ClipFrames as")
      && whole.contains(":: Space ;"),
    "space likewise: {whole}",
  );
}

/// **The two write faces PARTITION at the token level**: the set election appears under an ordinal in
/// `vector_sets` and the single election appears in `vectors`, and neither appears in the other.
#[test]
fn the_record_face_reports_a_set_under_ordinals_and_a_single_under_neither() {
  let record = vector_record(&emission(&set_index()));
  let (vectors, sets) = record
    .split_once("fn vector_sets")
    .expect("a set election emits the set face");

  assert!(
    vectors.contains("VectorColumn :: new (\"poster\")") && !vectors.contains("\"frames\""),
    "the single election alone reaches `vectors`: {vectors}",
  );
  assert!(
    sets.contains("VectorColumn :: new (\"frames\")") && !sets.contains("\"poster\""),
    "the set election alone reaches `vector_sets`: {sets}",
  );
  assert!(
    sets.contains("0u32 ..") && sets.contains("zip"),
    "ordinals are minted at their own width, in field order: {sets}",
  );
}

/// A declaration with NO set election emits no set face at all, keeping the trait's empty default —
/// so an expansion says nothing about a face its declaration does not have.
#[test]
fn a_declaration_with_no_set_election_emits_no_set_face() {
  let record = vector_record(&emission(&embedding_index()));

  assert!(!record.contains("fn vector_sets"), "{record}");
}

/// **The SET DOOR is emitted for a set election and for nothing else**, takes the set query and the
/// word, and answers in `Scored` with the fold's own two halves inside it.
#[test]
fn the_set_door_is_emitted_only_for_a_set_election() {
  let single = retrieve_source(&embedding_index());
  assert!(
    !single.contains("retrieve_keys_by_image_vec_with"),
    "a single election grows no set door: {single}",
  );

  let source = retrieve_source(&set_index());
  assert!(
    source.contains("retrieve_keys_by_frames_with")
      && !source.contains("retrieve_keys_by_poster_with"),
    "one door, for the election whose type states a set: {source}",
  );
  assert!(
    source.contains("FoldedQuery") && source.contains("FoldSemantics"),
    "it takes the set query and a fold: {source}",
  );
  assert!(
    source.contains("owner_best") && source.contains("set_scored"),
    "and is the two published halves composed: {source}",
  );
  assert!(
    source.contains("HashBests"),
    "the dedup word picks the accumulator as it picks the membership: {source}",
  );
}

/// The SPACE and the WIDTH ride the set door's signature exactly as they ride the pair's, which is
/// what keeps a query built in another space `E0308` at the call on this road too — projected on
/// both, off the elected field's own type.
#[test]
fn the_set_door_carries_the_projected_width_and_space() {
  let mut spaced = set_index();
  spaced.embeddings[0] = declared(
    "frames",
    "Vec<Embedding<f32, 768, Clip>>",
    ElectionLabel::List,
  );
  let source = retrieve_source(&spaced);

  assert!(
    source.contains("FoldedQuery < < __INGRAPH_ENGINE__ as"),
    "{source}"
  );
  assert!(
    source.contains("__INGRAPH_WIDTH_FRAMES__") && source.contains("__INGRAPH_SPACE_FRAMES__"),
    "the set door names the same two bindings the pair does: {source}",
  );

  let whole = spaced.emit().to_string();
  assert!(
    whole.contains("<< Vec < Embedding < f32 , 768 , Clip > > as") && whole.contains(":: WIDTH ;"),
    "and each binding is the elected type's own projection: {whole}",
  );
}

/// **THE INJECTED KEY TAKES THE SEAT**: an index a platform's codegen built carries its upstream's
/// key in that platform's field, and its one-storage marker under that platform's mark.
///
/// The field is read back through [`IndexModel::carried_key`] — the very value a front end appends
/// to the author's struct — so the appended field and the bodies that read it are shown to be one
/// spelling rather than two that happen to agree.
#[test]
fn a_platform_mark_moves_the_injected_key_and_the_storage_marker() {
  let mut model = document();
  model.prefix = EmissionPrefix::new("__mg");

  assert_eq!(
    model
      .carried_key()
      .ident
      .as_ref()
      .expect("the injected key is a named field")
      .to_string(),
    "__mg_key__",
  );

  let file: syn::File = syn::parse2(model.emit()).expect("the expansion parses as a file");
  let expansion = prettyplease::unparse(&file);
  assert!(
    expansion.contains("__mg_key__"),
    "the bodies read the moved field"
  );
  assert!(
    !expansion.contains("__ig_key__"),
    "and no body still reads `ingraph`'s spelling of it",
  );
  assert!(
    expansion.contains("__mg_SearchDocument_holds_one_storage")
      && !expansion.contains("__ig_SearchDocument_holds_one_storage"),
    "the marker a second storage would collide with is the platform's, so one type may hold both",
  );
}