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
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
//! The interface emitter's acceptance, over models built BY HAND.
//!
//! No declaration is parsed here, for the reason [`crate::tests`] states: the split that lets a
//! front end other than the derive reach this emitter only exists while the emitter can be driven
//! from a plain model.

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

use super::{
  InterfaceDatabase, InterfaceField, InterfaceModel, MemberColumn, Operand, Pin, Tier,
  default_derivations_name, default_fields_name, default_filter_name, default_id_name,
  default_input_name, default_key_name, default_kind_name, default_order_by_name,
  default_output_name, default_row_name,
};
use crate::{model::DatabaseKind, union::UnionMember};

/// The interface the whole module is measured against: two members, one field of every tier, and a
/// stored field pinned at two databases so a per-database reading is always under test.
pub(super) fn media() -> InterfaceModel {
  InterfaceModel {
    prefix: EmissionPrefix::default(),
    vis: syn::parse_quote!(pub),
    name: ident("Media"),
    krate: syn::parse_quote!(::ingraph),
    members: vec![
      member("Video", syn::parse_quote!(Video)),
      member("Audio", syn::parse_quote!(Audio)),
    ],
    fields: vec![
      InterfaceField {
        name: ident("title"),
        ty: syn::parse_quote!(String),
        tier: Tier::Stored,
        marker: None,
        copy: false,
        pins: Vec::new(),
        wire: None,
        operands: Vec::new(),
        members: Vec::new(),
      },
      InterfaceField {
        name: ident("mask"),
        ty: syn::parse_quote!(Mask),
        tier: Tier::Stored,
        marker: None,
        copy: true,
        pins: vec![
          Pin {
            kind: DatabaseKind::Sqlite,
            stored: Some(syn::parse_quote!(u32)),
          },
          Pin {
            kind: DatabaseKind::Postgres,
            stored: None,
          },
        ],
        wire: None,
        // The SQLite pin moved the type, so the operand crossing into that database is declared and
        // the crossing into Postgres — where the pin is the domain type — is the stored type's own.
        // Both shapes are therefore always under test.
        operands: vec![Operand {
          kind: DatabaseKind::Sqlite,
          convert: syn::parse_quote!(narrow),
        }],
        // `Audio` calls the field something else, so every reader of a member's column is under
        // test on both answers at once.
        members: vec![MemberColumn {
          variant: ident("Audio"),
          column: ident("flags"),
        }],
      },
      InterfaceField {
        name: ident("display_label"),
        ty: syn::parse_quote!(String),
        tier: Tier::Computed,
        marker: None,
        copy: false,
        pins: Vec::new(),
        wire: None,
        operands: Vec::new(),
        members: Vec::new(),
      },
      InterfaceField {
        name: ident("checksum"),
        ty: syn::parse_quote!(u64),
        tier: Tier::TryComputed,
        marker: None,
        copy: true,
        pins: Vec::new(),
        wire: None,
        operands: Vec::new(),
        members: Vec::new(),
      },
    ],
    error: None,
    computed_error: None,
    persist: Vec::new(),
    errors: Vec::new(),
    operand_errors: Vec::new(),
    plural: None,
    connection: None,
    edge: None,
  }
}

pub(super) fn member(name: &str, ty: syn::Type) -> UnionMember {
  UnionMember {
    ident: ident(name),
    ty,
  }
}

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

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

/// The whole expansion as one string, so a claim about it can be a substring.
pub(super) fn rendered(model: &InterfaceModel) -> String {
  prettyplease::unparse(&emission(model))
}

/// Tokens with their spacing removed, so a comparison is about content rather than layout.
pub(super) fn tight(tokens: impl ToTokens) -> String {
  tokens.to_token_stream().to_string().replace(' ', "")
}

/// **The member face is the UNION's, token for token.**
///
/// Not "the same shape" and not "the same method names": the two emissions are compared as tokens,
/// so a receiver, a doc line or a constness that moved on one side and not the other fails here.
/// That is what the seam is worth — an interface inherits the union's face rather than carrying a
/// copy of it.
#[test]
fn the_member_face_is_the_unions_own_emission() {
  let interface = media();
  let union = crate::union::UnionModel {
    krate: interface.krate.clone(),
    vis: interface.vis.clone(),
    name: interface.name.clone(),
    members: interface.members.clone(),
    error: interface.error.clone(),
    // NO WIRE WORD, which is what keeps this comparison about the SEAM: a union's own backend faces
    // hang off its model rather than off the emission both member sets share, so a union that
    // declares none emits exactly what an interface's member face does.
    graphql: Vec::new(),
  };

  assert_eq!(tight(interface.union_face()), tight(union.emit()));
}

/// **A rename moves the refusal here exactly as it does over a union** — one convention, reached
/// through one function, so the two member sets cannot come to spell the suffix differently.
#[test]
fn the_refusal_takes_the_declared_name_or_the_shared_convention() {
  assert_eq!(media().error(), "MediaUnwrapError");

  let mut renamed = media();
  renamed.error = Some(ident("NoSuchMedia"));
  assert_eq!(renamed.error(), "NoSuchMedia");

  let rendered = rendered(&renamed);
  assert!(rendered.contains("struct NoSuchMedia"), "{rendered}");
  assert!(!rendered.contains("MediaUnwrapError"), "{rendered}");
}

/// **The tier partition is total**: every field is stored or computed, never both and never
/// neither.
#[test]
fn every_field_is_in_exactly_one_tier() {
  let model = media();
  let stored: Vec<String> = model.stored().map(|field| field.name.to_string()).collect();
  let computed: Vec<String> = model
    .computed()
    .map(|field| field.name.to_string())
    .collect();

  assert_eq!(stored, ["title", "mask"]);
  assert_eq!(computed, ["display_label", "checksum"]);
  assert_eq!(stored.len() + computed.len(), model.fields.len());
}

/// **Only `try_computed` is fallible**, which is the one bit the contract's `Result` reads.
#[test]
fn the_fallible_tier_is_the_one_that_says_so() {
  assert!(!Tier::Stored.computed());
  assert!(!Tier::Stored.fallible());
  assert!(Tier::Computed.computed());
  assert!(!Tier::Computed.fallible());
  assert!(Tier::TryComputed.computed());
  assert!(Tier::TryComputed.fallible());
}

/// **A field with no pin is stored at its DOMAIN type**, at every database — the same uniform
/// mapping a record's own row takes when its declaration writes no `type = "…"`.
///
/// The `postgres` pin on the fixture's `mask` carries `None`, which is the case that separates
/// "this database was named" from "this database moved the type": both answer with the domain type,
/// and only one of them puts the database in [`InterfaceModel::databases`].
#[test]
fn an_unpinned_field_is_stored_at_the_type_it_was_declared_with() {
  let model = media();
  let title = &model.fields[0];
  let mask = &model.fields[1];

  for kind in DatabaseKind::ALL {
    assert_eq!(tight(title.pinned(kind)), "String", "{kind:?}");
  }
  assert_eq!(tight(mask.pinned(DatabaseKind::Sqlite)), "u32");
  assert_eq!(tight(mask.pinned(DatabaseKind::Postgres)), "Mask");
  assert_eq!(tight(mask.pinned(DatabaseKind::Mongo)), "Mask");
}

/// **The database set JOINS the block and the pins**, in the framework's own order rather than in
/// either declaration's.
///
/// Both halves are exercised in isolation and together: a field pin alone names a database, the
/// block alone names one, and the union of the two is what the equations are checked at.
#[test]
fn the_databases_are_the_block_and_the_pins_together() {
  assert_eq!(
    media().databases(),
    [DatabaseKind::Sqlite, DatabaseKind::Postgres],
    "the pins alone"
  );

  let mut blocked = media();
  blocked.persist = vec![selected(DatabaseKind::Mongo)];
  assert_eq!(
    blocked.databases(),
    [
      DatabaseKind::Sqlite,
      DatabaseKind::Postgres,
      DatabaseKind::Mongo
    ],
    "the block adds one, and the order is the framework's"
  );

  let mut unpinned = media();
  unpinned.fields[1].pins.clear();
  unpinned.persist = vec![selected(DatabaseKind::Mysql)];
  assert_eq!(
    unpinned.databases(),
    [DatabaseKind::Mysql],
    "the block alone, for a declaration whose fields are all short-form"
  );
}

/// **A fallible computed field answers with the boxed refusal until a declaration names one.**
#[test]
fn the_computed_error_defaults_to_the_boxed_refusal() {
  assert_eq!(
    tight(media().computed_error()),
    tight(crate::model::boxed_error())
  );

  let mut declared = media();
  declared.computed_error = Some(syn::parse_quote!(media::ComputeError));
  assert_eq!(tight(declared.computed_error()), "media::ComputeError");
}

/// **Every name that reaches the declaring scope is enumerated**, and the enumeration is what a
/// front end's collision rule reads.
#[test]
fn the_enumeration_names_every_type_that_reaches_the_scope() {
  let names: Vec<String> = media()
    .emitted_types()
    .iter()
    .map(|declared| declared.name.to_string())
    .collect();

  assert_eq!(
    names,
    [
      "MediaUnwrapError",
      "MediaFields",
      "MediaDerivations",
      "MediaKind",
      "MediaId",
      "MediaKey",
      "MediaSqliteRow",
      "MediaPostgresRow",
      "MediaSqliteCursor",
      "MediaSqliteComparison",
      "MediaPostgresCursor",
      "MediaPostgresComparison",
      "MediaOrderBy",
      "MediaFilter",
      "MediaGraphqlInput",
      "MediaGraphqlOutput",
      "MediaQueries"
    ]
  );
}

/// **Each name arrives with what it IS**, so a front end's collision refusal has one author — and a
/// name added to the emission cannot be added without a phrase for it.
#[test]
fn every_emitted_name_says_which_of_the_declarations_types_it_is() {
  let roles: Vec<String> = media()
    .emitted_types()
    .iter()
    .map(|declared| declared.role.to_string())
    .collect();

  assert_eq!(
    roles,
    [
      "the refusal a wrong-variant unwrap answers with",
      "the contract trait",
      "the derivations trait",
      "the discriminant",
      "the address",
      "the key type",
      "the `sqlite` row",
      "the `postgres` row",
      "the `sqlite` cursor value",
      "the `sqlite` comparison",
      "the `postgres` cursor value",
      "the `postgres` comparison",
      "the order-by",
      "the filter",
      "the wire arguments",
      "the wire output",
      "the query unit"
    ]
  );
}

/// **An interface that promises no stored column has no projection**, and neither its discriminant
/// nor a row is named: a contract over derived values is a real declaration, so what is missing is
/// the emission rather than a diagnostic.
#[test]
fn an_interface_with_nothing_to_select_declares_no_projection() {
  let mut model = media();
  model.fields.retain(|field| field.tier.computed());
  model.persist = vec![selected(DatabaseKind::Sqlite)];

  let names: Vec<String> = model
    .emitted_types()
    .iter()
    .map(|declared| declared.name.to_string())
    .collect();

  assert!(!model.projects());
  assert_eq!(
    names,
    [
      "MediaUnwrapError",
      "MediaFields",
      "MediaDerivations",
      "MediaGraphqlOutput"
    ],
    "the wire OUTPUT is unconditional where the projection's names are not: every member has a wire \
     face, so the sum over them is writable whatever a declaration stores"
  );
}

/// **Every name the projection SPENDS follows the reserved convention**, so the ones that now have
/// an emission are called what the reservation said they would be.
#[test]
fn the_projection_takes_the_names_that_were_reserved_for_it() {
  let interface = ident("Media");

  assert_eq!(default_kind_name(&interface), "MediaKind");
  assert_eq!(default_id_name(&interface), "MediaId");
  assert_eq!(default_key_name(&interface), "MediaKey");
  assert_eq!(
    default_row_name(&interface, DatabaseKind::Sqlite),
    "MediaSqliteRow"
  );

  let rendered = rendered(&media());
  assert!(rendered.contains("enum MediaKind"), "{rendered}");
  assert!(rendered.contains("enum MediaId"), "{rendered}");
  assert!(rendered.contains("enum MediaKey"), "{rendered}");
  assert!(rendered.contains("struct MediaSqliteRow"), "{rendered}");
  assert!(rendered.contains("struct MediaPostgresRow"), "{rendered}");
}

/// **The RESERVED list is EMPTY, and every name that was on it is emitted.**
///
/// A reservation is what keeps a name from being decided twice — once by the function and again by
/// the emission that lands later — so the list's whole purpose is to be spent. Each name is spelled
/// here beside the emission that took it, which is what fails the day the two are made to disagree.
///
/// The KEY was the last off, and it left by RULING rather than by a consumer. The sentence that
/// used to stand here — *nothing projects a member's own `*Key`* — was measured false:
/// `Transformer::Key` is one associated type over the `Identifiable::Id` the address sum already
/// projects, and the emission below is the proof. What actually held the key back was DEMAND, and
/// the ruling is that the fusion seam's premise is minted before that seam rather than with it.
#[test]
fn every_reserved_name_has_been_spent_on_its_emission() {
  let interface = ident("Media");

  assert_eq!(default_key_name(&interface), "MediaKey");
  assert_eq!(default_output_name(&interface), "MediaGraphqlOutput");
  assert_eq!(default_order_by_name(&interface), "MediaOrderBy");
  assert_eq!(default_filter_name(&interface), "MediaFilter");
  assert_eq!(default_input_name(&interface), "MediaGraphqlInput");

  let rendered = rendered(&media());
  for name in [
    "MediaKey",
    "MediaGraphqlOutput",
    "MediaOrderBy",
    "MediaFilter",
    "MediaGraphqlInput",
  ] {
    assert!(
      rendered.contains(name),
      "`{name}` was reserved and is emitted: {rendered}"
    );
  }
}

/// **The two DECLARED names follow the declaration's own name**, so a renamed interface renames its
/// contract with it.
#[test]
fn the_contract_names_follow_the_interfaces_own() {
  let interface = ident("Playable");

  assert_eq!(default_fields_name(&interface), "PlayableFields");
  assert_eq!(default_derivations_name(&interface), "PlayableDerivations");
  assert_eq!(media().fields_name(), "MediaFields");
  assert_eq!(media().derivations_name(), "MediaDerivations");
}
/// Every item the expansion declares, DESCENDING into the anonymous const the impls live in.
fn all_items(file: &syn::File) -> Vec<&syn::Item> {
  fn walk<'a>(item: &'a syn::Item, into: &mut Vec<&'a syn::Item>) {
    into.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 {
          walk(inner, into);
        }
      }
    }
  }
  let mut items = Vec::new();
  for item in &file.items {
    walk(item, &mut items);
  }
  items
}

/// The trait an expansion declares under `name`, with its method signatures in declaration order.
fn declared_trait(file: &syn::File, name: &str) -> Vec<String> {
  all_items(file)
    .into_iter()
    .find_map(|item| match item {
      syn::Item::Trait(item) if item.ident == name => Some(item),
      _ => None,
    })
    .unwrap_or_else(|| panic!("`{name}` is declared"))
    .items
    .iter()
    .filter_map(|item| match item {
      syn::TraitItem::Fn(item) => Some(tight(&item.sig)),
      _ => None,
    })
    .collect()
}

/// Every trait impl the expansion writes, as `<Trait> for <Self>`.
fn trait_impls(file: &syn::File) -> Vec<String> {
  all_items(file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Impl(item) => item
        .trait_
        .as_ref()
        .map(|(path, _)| format!("{} for {}", tight(path), tight(&item.self_ty))),
      _ => None,
    })
    .collect()
}

/// **The DOMAIN contract is stored-only.**
///
/// A computed field is answered from the wire output rather than from a row, so putting one here
/// would make every member's domain type owe a method its rows have no column for. The two lists
/// are asserted together, because the split is the claim: what leaves one face arrives on the other.
#[test]
fn the_contract_carries_the_stored_tier_and_the_derivations_the_computed_one() {
  let file = emission(&media());

  assert_eq!(
    declared_trait(&file, "MediaFields"),
    [
      "fntitle(&self)->&::core::primitive::str",
      "fnmask(&self)->Mask"
    ]
  );
  assert_eq!(
    declared_trait(&file, "MediaDerivations"),
    [
      "fndisplay_label(&self)->String",
      "fnchecksum(&self)->::core::result::Result<u64,::std::boxed::Box<dyn::core::error::Error+::\
       core::marker::Send+::core::marker::Sync+'static>>"
    ]
  );
}

/// **The house getter law, over what the declaration said**: a `copy` field by value, a `String` as
/// a `str` borrow, and anything else as a borrow of its own type.
///
/// The `String` rule is SYNTACTIC and its wrong answer is benign — an alias hiding one takes the
/// plain borrow, which is a working getter over a working type — so the alias is on the roster
/// beside the spelling it hides.
#[test]
fn a_projection_follows_the_declared_type_and_the_copy_claim() {
  let mut model = media();
  model.fields.push(InterfaceField {
    name: ident("caption"),
    ty: syn::parse_quote!(Text),
    tier: Tier::Stored,
    marker: None,
    copy: false,
    pins: Vec::new(),
    wire: None,
    operands: Vec::new(),
    members: Vec::new(),
  });

  assert_eq!(
    declared_trait(&emission(&model), "MediaFields"),
    [
      "fntitle(&self)->&::core::primitive::str",
      "fnmask(&self)->Mask",
      "fncaption(&self)->&Text"
    ]
  );
}

/// **A member's implementation is FIELD ACCESS**, which is where the teeth are: nothing between the
/// declaration and the member's own struct for a mismatch to hide behind.
#[test]
fn a_member_answers_the_contract_by_reading_its_own_field() {
  let rendered = rendered(&media());

  assert!(
    rendered.contains("impl MediaFields for Video"),
    "{rendered}"
  );
  assert!(
    rendered.contains("impl MediaFields for Audio"),
    "{rendered}"
  );
  assert!(rendered.contains("&self.title"), "{rendered}");
  assert!(rendered.contains("self.mask"), "{rendered}");
}

/// **The interface answers by MATCHING**, and each arm is qualified through the trait — a member
/// carrying an inherent method of the same name for its own reasons must not be what the delegation
/// reaches.
#[test]
fn the_interface_delegates_to_whichever_member_is_held() {
  let rendered = rendered(&media());

  assert!(
    rendered.contains("impl MediaFields for Media"),
    "{rendered}"
  );
  assert!(
    rendered.contains("Self::Video(member) => <Video as MediaFields>::title(member)"),
    "{rendered}"
  );
  assert!(
    rendered.contains("Self::Audio(member) => <Audio as MediaFields>::mask(member)"),
    "{rendered}"
  );
}

/// **`<I>Derivations` is implemented NOWHERE.**
///
/// An author writing a derivation writes their own glue, so there is no adapter under the trait and
/// no impl beside it — the whole of what this round emits for the computed tier is the declaration.
#[test]
fn the_derivations_trait_is_declared_and_implemented_by_nobody() {
  let impls = trait_impls(&emission(&media()));

  assert!(
    !impls.iter().any(|item| item.contains("MediaDerivations")),
    "{impls:?}"
  );
  assert_eq!(
    impls
      .iter()
      .filter(|item| item.starts_with("MediaFields for"))
      .count(),
    3,
    "two members and the interface itself: {impls:?}"
  );
}

/// **The TIES come first, and the order is the diagnostic.**
///
/// rustc reports in emission order, so a type that is not a member at all is told THAT rather than
/// being told about a field it does not have. The three are asserted by position, which is what a
/// reordering would fail on.
#[test]
fn the_membership_ties_are_emitted_before_anything_reads_a_column() {
  let rendered = rendered(&media());
  let at = |needle: &str| {
    rendered
      .find(needle)
      .unwrap_or_else(|| panic!("`{needle}` is emitted: {rendered}"))
  };

  let membership = at("transform::implements::<Video, Media>");
  let stored = at("transform::stores_rows::<Video>");
  let wire = at("transform::has_a_wire_face::<Video>");
  let contract = at("impl MediaFields for Video");

  assert!(membership < stored, "membership leads: {rendered}");
  assert!(stored < wire);
  assert!(wire < contract, "and every tie precedes the columns");
}

/// **The two traits reach the DECLARING SCOPE and nothing else does.**
///
/// They are named in signatures a member writes, so they land where an author can spell them and
/// take part in the collision rule; the impls and the ties name nothing anybody has to spell, so
/// they sit inside the anonymous const where they collide with nothing.
#[test]
fn only_the_enumerated_types_land_in_the_declaring_scope() {
  let file = emission(&media());
  let scoped: Vec<String> = file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Struct(item) => Some(item.ident.to_string()),
      syn::Item::Trait(item) => Some(item.ident.to_string()),
      syn::Item::Enum(item) => Some(item.ident.to_string()),
      _ => None,
    })
    .collect();

  assert_eq!(
    scoped,
    media()
      .emitted_types()
      .iter()
      .map(|declared| declared.name.to_string())
      .collect::<Vec<_>>()
  );
}

/// **Every emitted item is exactly as visible as the declaration** — a private interface's contract
/// stays private rather than leaking into its crate's public API.
#[test]
fn the_contract_mirrors_the_declarations_visibility() {
  let mut model = media();
  model.vis = syn::parse_quote!(pub(crate));
  let rendered = rendered(&model);

  assert!(
    rendered.contains("pub(crate) trait MediaFields"),
    "{rendered}"
  );
  assert!(
    rendered.contains("pub(crate) trait MediaDerivations"),
    "{rendered}"
  );
  assert!(!rendered.contains("pub trait"), "{rendered}");
}

/// **A declared computed error is what the fallible signature answers with**, in the trait and in
/// its `# Errors` note alike.
#[test]
fn the_declared_computed_error_types_the_fallible_derivation() {
  let mut model = media();
  model.computed_error = Some(syn::parse_quote!(media::ComputeError));
  let file = emission(&model);

  assert_eq!(
    declared_trait(&file, "MediaDerivations")[1],
    "fnchecksum(&self)->::core::result::Result<u64,media::ComputeError>"
  );
  assert!(
    rendered(&model).contains("[`media::ComputeError`]"),
    "the `# Errors` note names it too"
  );
}

/// **One equation per (stored field, database, member), and its NAME says which.**
///
/// The pin is a fact about a row, so it is discharged at the row: the member's own, at a concrete
/// backend, at the type the declaration said. A computed field has no equation because it has no
/// column, and the databases are the joined set — the block's and the pins'.
#[test]
fn every_pin_is_discharged_at_the_row_that_has_to_satisfy_it() {
  let emitted = tight(media().equations());

  for (member, database, field, backend, ty) in [
    ("video", "sqlite", "title", "Sqlite", "String"),
    ("video", "sqlite", "mask", "Sqlite", "u32"),
    ("video", "postgres", "mask", "Postgres", "Mask"),
    ("audio", "postgres", "title", "Postgres", "String"),
  ] {
    let equation = format!(
      "fn_{member}_{database}_{field}(row:&<{Member}as::ingraph::__private::transform::Record<::\
       ingraph::__private::sqlx::{backend}>>::Row)->&{ty}{{&row.{field}}}",
      Member = if member == "video" { "Video" } else { "Audio" },
    );
    assert!(emitted.contains(&equation), "{equation}\n{emitted}");
  }

  assert!(
    !emitted.contains("display_label"),
    "a computed field has no column to equate: {emitted}"
  );
  assert!(
    !emitted.contains("if_mysql"),
    "and a database nothing named is not checked: {emitted}"
  );
}

/// **Every equation's name begins with `_`, and that is what silences `dead_code`.**
///
/// Nothing calls one. A function nobody calls is a warning at a span its author cannot edit, and
/// rustc's own convention — an item whose name starts with `_` is not reported — is what answers it
/// without an `#[allow]` in generated code. Measured: the same function without the underscore is a
/// denied warning.
#[test]
fn every_equation_is_named_out_of_the_dead_code_lint() {
  let emitted = tight(media().equations());
  let names: Vec<&str> = emitted
    .match_indices("fn")
    .map(|(at, _)| {
      let rest = &emitted[at + 2..];
      &rest[..rest.find('(').expect("a function takes arguments")]
    })
    .collect();

  assert_eq!(names.len(), 8, "two members, two fields, two databases");
  assert!(names.iter().all(|name| name.starts_with('_')), "{names:?}");
}

/// **The equations ride the per-database GATE**, which is what keeps declare-many/build-one: an
/// equation names a CONCRETE backend, so ungated it would make a declaration naming Postgres fail to
/// compile in a build without the Postgres driver.
#[test]
fn the_equations_ride_the_gate_of_the_database_they_name() {
  let emitted = tight(media().equations());
  let at = |needle: &str| {
    emitted
      .find(needle)
      .unwrap_or_else(|| panic!("`{needle}` is emitted: {emitted}"))
  };

  assert!(at("gate::if_sqlite!") < at("fn_video_sqlite_title"));
  assert!(at("fn_audio_sqlite_mask") < at("gate::if_postgres!"));
  assert!(at("fn_video_postgres_title") > at("gate::if_postgres!"));
}

/// **A declaration that names no database states no fact about rows**, so it writes no equation and
/// no gate — where a `persist(…)` block alone is enough to make one.
#[test]
fn an_interface_about_no_database_writes_no_equation() {
  let mut unpinned = media();
  unpinned.fields[1].pins.clear();
  assert!(tight(unpinned.equations()).is_empty());

  unpinned.persist = vec![selected(DatabaseKind::Mongo)];
  let emitted = tight(unpinned.equations());
  assert!(emitted.contains("gate::if_mongo!"), "{emitted}");
  assert!(
    emitted.contains(
      "fn_video_mongo_mask(row:&<Videoas::ingraph::__private::transform::Record<::\
                      ingraph::__private::comparison::mongo::Mongo>>::Row)->&Mask"
    ),
    "an unpinned field is checked at the DOMAIN type, and mongo's backend is not sqlx's: {emitted}"
  );
}

/// **The expansion implements NO framework trait**, and that is the era rule seen from this
/// emitter: every impl it writes is of a trait the SAME expansion declared.
///
/// What it names of the framework is exactly three audits, the storage vocabulary its equations
/// project through, and the gates they ride — all of them SPENT rather than implemented. An impl of
/// a framework trait here would owe every consumer a revision the day that trait settled
/// differently, which is the rule `crate::emit` states for the other emitter.
///
/// The walk descends into the anonymous const and opens no gate, because a gate holds only
/// equations: a framework trait impl appearing inside one would be caught by the shape of what a
/// gate is allowed to carry, which the equation tests state.
#[test]
fn the_expansion_implements_only_the_traits_it_declared_or_the_engine_publishes() {
  let declared: Vec<String> = media()
    .emitted_types()
    .iter()
    .map(|item| item.name.to_string())
    .collect();
  // The framework traits an interface's PROJECTION is authorised to bind, spelled as the shelf
  // paths the emission writes. Each is a settled seam with no consumer type of its own in it, over
  // a self type this emission also declares — the ground `crate::emit::query`'s own note states for
  // the record's engine bindings, and the whole of what is admitted here beyond `core`.
  let engine = [
    "::ingraph::__private::interface::InterfaceKind",
    "::ingraph::__private::sqlx::FromRow",
    // The PAGE's three, each the same kind of seam: a settled surface with no consumer type of its
    // own, over a self type this emission declares. The cursor value's codec and its binding are
    // what a page is resumed and bound through, and the predicate's lowering is what its own map's
    // item bound already demands — the ground `crate::emit::query` states for the record's cursor.
    "::ingraph::__private::cursor::CursorValue",
    "::ingraph::__private::comparison::sql::Carrier",
    "::ingraph::__private::comparison::ComplexComparison",
    // The ORDER's SUBJECT, which is what a client's written order is keyed on so no two of its
    // terms name one column. Over the emitted order-by, and gated on nothing — generated code
    // cannot spell a feature of this crate, so a trait an expansion names exists in every build of
    // it. It joined with B-27, the wire ORDER argument being what spends it.
    "::ingraph::__private::graphql::ToSubjectPath",
    // The WIRE FACE's own seams, which B-27 brought: the two INPUT objects a client writes and the
    // SDL interface its members implement, each over a type this emission declares. They are the
    // async-graphql derives' own output at the one place a derive could not be attached — see
    // `interface::face` and `unit::wire` — so what is bound here is a settled library surface with
    // no consumer type of its own in it.
    "::ingraph::__private::async_graphql::InputType",
    "::ingraph::__private::async_graphql::InputObjectType",
    "::ingraph::__private::async_graphql::OneofObjectType",
    "::ingraph::__private::async_graphql::OutputType",
    "::ingraph::__private::async_graphql::InterfaceType",
    "::ingraph::__private::async_graphql::resolver_utils::ContainerType",
    // And the three faces the ROOT reaches the unit through, over types this emission declares.
    "::ingraph::__private::transform::Graphql",
    "::ingraph::__private::transform::GraphqlInput",
    "::ingraph::__private::transform::GraphqlOutput",
    // The CROSSING, over a self type this emission declares and from a source type it declares
    // beside it. It is the seam a RECORD's emission cannot write, and the difference is the
    // dialect: a record's comparison is generic in its database, where this one is stated at the
    // concrete backend the interface's whole engine face already names.
    "::ingraph::__private::comparison::TryFromFilter",
  ];

  for implemented in trait_impls(&emission(&media())) {
    let (implemented_trait, _) = implemented
      .split_once(" for ")
      .expect("an impl names a trait and a self type");
    let engine_seam = engine
      .iter()
      .any(|seam| implemented_trait.starts_with(seam));
    assert!(
      declared.iter().any(|name| name == implemented_trait)
        || implemented_trait.starts_with("::core::")
        || engine_seam,
      "`{implemented}` is none of this expansion's own, `core`'s, or the engine's published seams"
    );
  }
}

/// **Every framework name the expansion writes goes through the SHELF**, and the declaration's own
/// root is what it is rooted at — so a re-export shim moves all of them at once.
#[test]
fn every_framework_path_is_rooted_at_the_declared_crate() {
  let mut model = media();
  model.krate = syn::parse_quote!(shim::ingraph);
  let emitted = tight(model.emit());

  assert!(emitted.contains("shim::ingraph::__private::transform::implements"));
  assert!(emitted.contains("shim::ingraph::__private::gate::if_sqlite"));
  assert!(emitted.contains("shim::ingraph::__private::sqlx::Sqlite"));
  assert_eq!(
    emitted.matches("__private").count(),
    emitted.matches("shim::ingraph::__private").count(),
    "every shelf reach is rooted at the DECLARED crate: {emitted}"
  );
  assert!(
    !emitted.contains("shim::ingraph::transform"),
    "and none of them steps past the shelf into a real module path: {emitted}"
  );
}

/// **A member block moves the ACCESS and not the METHOD.**
///
/// The contract's name is the interface's whatever member is held — a caller writes one name — and
/// what changes is which field that member's own implementation reads. The three readers are
/// asserted together, because the claim is that they agree: the member's impl, the row equation,
/// and the delegation that reaches neither.
#[test]
fn a_member_block_moves_the_access_and_leaves_the_method_alone() {
  let model = media();
  let contract = tight(model.contract());
  let equations = tight(model.equations());

  assert!(
    contract.contains(
      "implMediaFieldsforAudio{#[inline]fntitle(&self)->&::core::primitive::str{&\
                       self.title}#[inline]fnmask(&self)->Mask{self.flags}}"
    ),
    "the method is `mask` and the access is `flags`: {contract}"
  );
  assert!(
    contract.contains(
      "implMediaFieldsforVideo{#[inline]fntitle(&self)->&::core::primitive::str{&\
                       self.title}#[inline]fnmask(&self)->Mask{self.mask}}"
    ),
    "and a member that renamed nothing reads its own name: {contract}"
  );
  assert!(
    contract.contains("Self::Audio(member)=><AudioasMediaFields>::mask(member)"),
    "the delegation calls the CONTRACT's name, which no member block moves: {contract}"
  );
  assert!(
    equations.contains(
      "fn_audio_sqlite_mask(row:&<Audioas::ingraph::__private::transform::Record<\
                        ::ingraph::__private::sqlx::Sqlite>>::Row)->&u32{&row.flags}"
    ),
    "and the row is read at the same name the struct is: {equations}"
  );
}

/// **`InterfaceField::column` is the ONE place the default is resolved.**
///
/// Three consumers read it — the member's contract impl, the row equation, and the arrangement
/// layer that will render `<column> AS <field>` — so a default spelled at three sites is how two of
/// them come to disagree about a column nobody renamed.
#[test]
fn one_resolver_answers_what_each_member_calls_a_field() {
  let model = media();
  let mask = &model.fields[1];

  assert_eq!(*mask.column(&ident("Audio")), "flags");
  assert_eq!(
    *mask.column(&ident("Video")),
    "mask",
    "the default is the interface's own name"
  );
  assert_eq!(
    *model.fields[0].column(&ident("Audio")),
    "title",
    "and a field no member renamed answers alike for every one of them"
  );
}

/// **The projection carries one field per SHARED column, at the type the interface pinned** — and
/// the discriminant beside them.
///
/// The pin is I-1's, spent here rather than re-derived: a database with no pin keeps the domain
/// type, which is what makes `title` a `String` in both rows and `mask` a `u32` in one alone.
#[test]
fn the_projection_carries_the_shared_columns_at_the_pinned_types() {
  let rendered = rendered(&media());

  assert!(
    rendered.contains(
      "pub struct MediaSqliteRow {\n    __ig_kind__: MediaKind,\n    id: MediaId,\n    title: String,\n    mask: u32,\n}"
    ),
    "{rendered}"
  );
  assert!(
    rendered.contains(
      "pub struct MediaPostgresRow {\n    __ig_kind__: MediaKind,\n    id: MediaId,\n    title: String,\n    mask: Mask,\n}"
    ),
    "the unpinned database keeps the domain type: {rendered}"
  );
}

/// **A COMPUTED field is not on the projection**, by construction rather than by a filter here: a
/// derived value is read out of no column, so there is nothing for a statement to select.
#[test]
fn a_derived_value_has_no_column_to_project() {
  let rendered = rendered(&media());

  assert!(!rendered.contains("display_label: "), "{rendered}");
  assert!(!rendered.contains("checksum: "), "{rendered}");
}

/// **The discriminant's word is the member's own, snake-cased**, which is [`crate::union::word`]'s
/// answer — the same resolver `is_video` and `_video_sqlite_mask` go through.
#[test]
fn the_discriminant_word_is_the_members_own() {
  let emitted = tight(media().projection());

  assert!(emitted.contains(r#"Self::Video=>"video","#), "{emitted}");
  assert!(emitted.contains(r#"Self::Audio=>"audio","#), "{emitted}");
  assert!(
    emitted.contains(r#"constINTERFACE:&'static::core::primitive::str="Media";"#),
    "{emitted}"
  );
}

/// **The binding is one impl per SQL database, each riding that database's GATE** — the arrangement
/// the equations have, for the same reason: the impl names a CONCRETE backend, so ungated a
/// declaration naming Postgres would fail to compile in a build without the Postgres driver.
#[test]
fn the_binding_rides_the_gate_of_the_database_it_names() {
  let emitted = tight(media().bindings());
  let at = |needle: &str| {
    emitted
      .find(needle)
      .unwrap_or_else(|| panic!("`{needle}` is emitted: {emitted}"))
  };

  assert!(at("gate::if_sqlite!") < at("typeRow=MediaSqliteRow;"));
  assert!(at("typeRow=MediaSqliteRow;") < at("gate::if_postgres!"));
  assert!(at("gate::if_postgres!") < at("typeRow=MediaPostgresRow;"));
  assert!(!emitted.contains("if_mysql"), "{emitted}");
}

/// **Each arm carries the two names of every shared column**, and they differ exactly where a member
/// block moved it — `Audio` calls `mask` `flags`, and every other pair is the name twice.
#[test]
fn each_arm_carries_what_its_member_calls_the_shared_column() {
  let emitted = tight(media().bindings());

  assert!(
    emitted.contains(
      r#"InterfaceArm::new(MediaKind::Audio,&[::ingraph::__private::interface::InterfaceColumn::new(::ingraph::__private::field::FieldName::new("title"),::ingraph::__private::field::FieldName::new("title")),::ingraph::__private::interface::InterfaceColumn::new(::ingraph::__private::field::FieldName::new("mask"),::ingraph::__private::field::FieldName::new("flags")),])"#
    ),
    "{emitted}"
  );
}

/// **The member's TABLE is asked of the member's own binding**, never restated — so a member that
/// renames its table moves this reading with it and there is no copy here to update.
#[test]
fn the_address_is_the_members_own_and_never_a_copy() {
  let emitted = tight(media().bindings());

  assert!(
    emitted.contains(
      "MediaKind::Video=><<Videoas::ingraph::__private::transform::Record<::ingraph::__private::\
       sqlx::Sqlite>>::Rowas::ingraph::__private::query::sql::SqlQuery<::ingraph::__private::sqlx::\
       Sqlite>>::ADDRESS,"
    ),
    "{emitted}"
  );
}

/// **An interface with nothing to select writes no binding either**, which is one condition asked
/// twice rather than two that could disagree.
#[test]
fn an_interface_with_no_projection_has_no_binding() {
  let mut model = media();
  model.fields.retain(|field| field.tier.computed());
  model.persist = vec![selected(DatabaseKind::Sqlite)];

  assert!(tight(model.projection()).is_empty());
  assert!(tight(model.bindings()).is_empty());
}

/// **The address sum's payload is the FAMILY PROJECTION**, never a name this crate builds: an id's
/// type is the member's declaration's, and a convention-built one would be a second spelling of
/// something that declaration can move.
#[test]
fn the_address_carries_each_members_own_id_through_the_projection() {
  let emitted = tight(media().projection());

  assert!(
    emitted.contains("Video(<Videoas::ingraph::__private::transform::Identifiable>::Id)"),
    "{emitted}"
  );
  assert!(
    emitted.contains("Audio(<Audioas::ingraph::__private::transform::Identifiable>::Id)"),
    "{emitted}"
  );
  assert!(
    emitted.contains("Self::Video(_)=>MediaKind::Video,"),
    "and reading the kind back off the address is what keeps the pair coherent: {emitted}"
  );
}

/// **The KEY sum is the address one associated type over**: the payload is `Transformer::Key`
/// through the family projection, one variant per member and never a name this crate builds.
///
/// The kind arm is COUNTED rather than found, which is what makes this a claim about two sums at
/// once: a member's arm is written twice, once by the address and once by the key, so dropping
/// either one leaves that member at a count of 1 and this reds.
#[test]
fn the_key_carries_each_members_own_key_through_the_projection() {
  let emitted = tight(media().projection());

  assert!(
    emitted.contains("Video(<Videoas::ingraph::__private::transform::Transformer>::Key)"),
    "{emitted}"
  );
  assert!(
    emitted.contains("Audio(<Audioas::ingraph::__private::transform::Transformer>::Key)"),
    "{emitted}"
  );
  assert_eq!(
    emitted.matches("Self::Video(_)=>MediaKind::Video,").count(),
    2,
    "both addresses read the discriminant back off themselves: {emitted}"
  );
  assert_eq!(
    emitted.matches("Self::Audio(_)=>MediaKind::Audio,").count(),
    2,
    "{emitted}"
  );
}

/// **Nothing decodes a KEY out of a row, and nothing builds one.** The statement selects the address
/// column, the cursor freezes the address, and hydration eats addresses — so a `FromRow` here would
/// be machinery for a row shape no arm of the union projects.
///
/// The ROW's own decode is asserted beside the absence, so this is *the key has none* rather than
/// *this expansion writes no decodes*.
#[test]
fn nothing_decodes_a_key_out_of_a_row() {
  let emitted = tight(media().projection());

  assert!(
    emitted.contains("FromRow<'a,__INGRAPH_ROW__>forMediaSqliteRow"),
    "the row is decoded: {emitted}"
  );
  assert!(
    !emitted.contains("forMediaKey"),
    "and the key is not: {emitted}"
  );
  assert!(
    !emitted.contains("MediaKey::Video("),
    "nor is one built anywhere — the type is the vocabulary and nothing spends it yet: {emitted}"
  );
}

/// **The DISCRIMINANT is decoded before the ADDRESS**, which is the whole shape of the address
/// decode: it is what decides which variant the id is, so the per-kind branch has exactly one home.
#[test]
fn the_decode_reads_the_discriminant_before_the_address() {
  let emitted = tight(media().projection());
  let at = |needle: &str| {
    emitted
      .find(needle)
      .unwrap_or_else(|| panic!("`{needle}` is emitted: {emitted}"))
  };

  assert!(at("let__ig_kind__=<MediaKindas") < at("letid=match__ig_kind__{"));
  assert!(at("letid=match__ig_kind__{") < at("lettitle:String=__row.try_get"));
  assert!(
    emitted.contains("MediaKind::Audio=>MediaId::Audio(__row.try_get(__ingraph_id)?),"),
    "{emitted}"
  );
}

/// **The synthesized column wears the fence and the real one does not.** `__ig_kind__` is a name a
/// declaration cannot spell, so a shared field called `kind` collides with nothing; `id` is a
/// member's own column under one output name and stays ordinary.
#[test]
fn the_discriminant_wears_the_fence_and_the_address_does_not() {
  let emitted = tight(media().projection());

  assert!(emitted.contains("__ig_kind__:MediaKind,"), "{emitted}");
  assert!(emitted.contains("id:MediaId,"), "{emitted}");
  assert!(
    !emitted.contains("kind:MediaKind,"),
    "a bare `kind` would compete with a field a declaration may promise: {emitted}"
  );
}

/// **The wire filter is the STORED tier and nothing else** — a computed field is derived from a
/// member's wire output and is a column nowhere, so it has no operand to be filtered by.
///
/// The absence is the refusal: a client naming one names a member of this struct that does not
/// exist, which is what the derive's own `a_computed_field_is_absent_from_an_interfaces_filter`
/// fixture pins at the call site.
#[test]
fn the_filter_carries_the_shared_columns_and_no_derived_one() {
  let emitted = tight(media().wire());

  assert!(emitted.contains("pubstructMediaFilter{"), "{emitted}");
  assert!(
    emitted.contains("title:::core::option::Option<"),
    "{emitted}"
  );
  assert!(
    emitted.contains("mask:::core::option::Option<"),
    "{emitted}"
  );
  assert!(
    !emitted.contains("display_label:") && !emitted.contains("checksum:"),
    "a derived value is statically absent: {emitted}"
  );
  assert!(emitted.contains("pubfnwith_title(mutself,"), "{emitted}");
  assert!(emitted.contains("pubconstfnmask_ref(&self)"), "{emitted}");
}

/// **The operand's form is the DOMAIN type**, which is what makes the crossing writable: a filter's
/// kind and its comparison's are ONE or nothing crosses between them.
///
/// Asserted as the same token stream the PREDICATE holds, rather than as a spelling, so the day
/// either side asks a different question this fails.
#[test]
fn the_filter_and_the_predicate_ask_one_question_of_a_type() {
  let model = media();
  let filter = tight(model.wire());
  let asked = tight(
    model.filter_of(
      model
        .stored()
        .next()
        .expect("the fixture's first stored field is `title`"),
    ),
  );

  assert!(
    filter.contains(&format!("title:::core::option::Option<{asked}>")),
    "{filter}"
  );
  assert!(
    tight(model.page()).contains(&asked),
    "the predicate asks the same projection the filter does"
  );
}

/// **The arguments mirror the LANE**, and what the lane does not offer is not a member: an
/// interface's order is never absent, so there is no unordered ceiling, and `InterfaceFind` binds
/// no `OFFSET`.
#[test]
fn the_arguments_are_the_lane_and_carry_no_member_it_cannot_spend() {
  let emitted = tight(media().wire());

  assert!(emitted.contains("pubstructMediaGraphqlInput{"), "{emitted}");
  assert!(
    emitted.contains("order:::std::vec::Vec<MediaOrderBy>,"),
    "{emitted}"
  );
  assert!(
    emitted.contains("filter:::core::option::Option<MediaFilter>,"),
    "{emitted}"
  );
  for member in ["first", "last", "after", "before"] {
    assert!(
      emitted.contains(&format!("{member}:::core::option::Option<")),
      "{member}: {emitted}"
    );
  }
  assert!(
    !emitted.contains("limit:::core::option::Option<")
      && !emitted.contains("skip:::core::option::Option<"),
    "a member no method could spend is an argument object promising a query the engine refuses: \
     {emitted}"
  );
  assert!(
    emitted.contains("after:::core::option::Option<::std::string::String>,"),
    "a cursor is the STRING a client holds — the typed slot is per database and this object is \
     not: {emitted}"
  );
}

/// **The crossing names a CONCRETE backend**, which is the whole of why it can be written: at a
/// generic dialect the projection resolves through the impl that defines it and demands what that
/// impl demands of the database.
///
/// It rides that database's gate with the rest of the engine face, and a declaration about no SQL
/// database has none.
#[test]
fn the_crossing_is_stated_at_the_dialect_its_binding_already_names() {
  let emitted = tight(media().bindings());

  assert!(
    emitted.contains(
      "impl::ingraph::__private::comparison::TryFromFilter<MediaFilter>for \
       MediaSqliteComparison<::ingraph::__private::sqlx::Sqlite>"
    ) || emitted.contains(
      "impl::ingraph::__private::comparison::TryFromFilter<MediaFilter>forMediaSqliteComparison<::ingraph::__private::sqlx::Sqlite>"
    ),
    "{emitted}"
  );
  assert!(
    emitted.contains("::ingraph::__private::gate::if_sqlite!"),
    "and it rides the gate the rest of the engine face does: {emitted}"
  );

  let mut bare = media();
  bare.fields.retain(|field| field.tier.computed());
  assert!(
    tight(bare.bindings()).is_empty(),
    "a declaration with nothing stored projects nothing and crosses nothing"
  );
}

/// **A DECLARED converter replaces the chain, and an undeclared one is the stored type's own
/// `TryFrom`** — two shapes rather than one with a hole, because what a declared leg says is *do
/// not ask the stored type how to take this value, I have answered*.
///
/// The fixture's `mask` declares one for SQLite and not for Postgres, so both readings are under
/// test at once and neither is a claim about the other.
#[test]
fn a_declared_operand_leg_replaces_the_stored_types_own() {
  let emitted = tight(media().bindings());

  assert!(
    emitted.contains("try_from_filter_with(__ingraph_held,narrow)"),
    "{emitted}"
  );
  assert!(
    emitted.contains("::ingraph::__private::comparison::TryFromFilter<"),
    "and the Postgres half takes the trait crossing instead: {emitted}"
  );
  assert!(
    emitted.contains("::core::option::Option::None=>::core::default::Default::default()"),
    "a column the client said nothing about is the EMPTY comparison: {emitted}"
  );
}

/// **The crossing's refusal is the declared cell, or the boxed one** — and the boxed default is
/// what makes every column's crossing unify without a declaration saying anything.
#[test]
fn the_crossing_answers_with_the_cell_its_database_named() {
  let boxed = tight(media().bindings());
  assert!(
    boxed.contains("typeError=::std::boxed::Box<dyn::core::error::Error+::core::marker::Send+::core::marker::Sync+'static>"),
    "{boxed}"
  );

  let mut declared = media();
  declared.operand_errors = vec![super::InterfaceError {
    kind: DatabaseKind::Sqlite,
    error: syn::parse_quote!(crate::TooWide),
  }];
  let emitted = tight(declared.bindings());
  assert!(emitted.contains("typeError=crate::TooWide;"), "{emitted}");
  assert!(
    emitted.contains("typeError=::std::boxed::Box<"),
    "and the database with no cell keeps the boxed refusal: {emitted}"
  );
}

/// One database of an interface's own `persist(…)` selection, at every alias answer's default.
fn selected(kind: DatabaseKind) -> InterfaceDatabase {
  InterfaceDatabase {
    kind,
    aliases: crate::model::AliasOptions::default(),
  }
}

/// The collection fixture: `media()` plus one COLLECTION pin, so every reader of a many-valued
/// shared column is under test beside the scalar ones rather than in a model of its own.
///
/// `list(scalar)` over a `Vec<u64>` pinned at `i64` in SQLite, which is the shape that made the
/// refuse-until fixture: the row holds the LIST and the comparison is keyed on the ELEMENT, so the
/// two readings of one pin are always different types here.
fn reeled() -> InterfaceModel {
  let mut model = media();
  model.fields.push(InterfaceField {
    name: ident("marks"),
    ty: syn::parse_quote!(Vec<u64>),
    tier: Tier::Stored,
    marker: Some(crate::model::Marker::Framework(
      crate::model::FrameworkMarker {
        label: crate::model::Label::List,
        element: Some(crate::model::Label::Scalar),
      },
    )),
    copy: false,
    pins: vec![Pin {
      kind: DatabaseKind::Sqlite,
      stored: Some(syn::parse_quote!(i64)),
    }],
    wire: None,
    operands: Vec::new(),
    members: Vec::new(),
  });
  model
}

/// **The pin's WORD splits the two readers**, and the row equation is the half that takes the list.
///
/// The `E0308` the refuse-until fixture pinned — `&i64` asserted against a row field of `&Vec<i64>`
/// — dies here: the equation asserts the `Vec` because the word said the column is many-valued.
/// The CROSSING keeps the element, which is the other half of the split and is asserted beside it so
/// the two cannot come to agree.
#[test]
fn a_collection_pins_the_list_at_the_row_and_the_element_at_the_crossing() {
  let model = reeled();
  let equations = tight(model.equations());

  assert!(
    equations.contains("fn_video_sqlite_marks(row:&<Videoas"),
    "the row equation is written for the collection at all: {equations}"
  );
  assert!(
    equations.contains(">::Row)->&::std::vec::Vec<i64>"),
    "and it takes the LIST: {equations}"
  );
  assert!(
    equations.contains(">::Row)->&u32"),
    "where a scalar pin is unchanged at both sites: {equations}"
  );
  assert!(
    equations.contains("ToDatabaseComparison<i64,"),
    "the comparison reading of the same pin is keyed on the ELEMENT: {equations}"
  );
  // The one shape a pin cannot state: `type = "Vec<u64>"` with no per-database `type`, where the
  // domain type is the LIST and one value of it is not. The element is ASKED of the type rather
  // than read off the tokens, so an aliased collection stays transparent one level in.
  assert!(
    equations.contains(
      "ToDatabaseComparison<<Vec<u64>as::ingraph::__private::state::State<::ingraph::__private::state::Extracted<::ingraph::__private::state::Inner>>>::Output,"
    ),
    "an UNPINNED collection is keyed on its element projection: {equations}"
  );
  assert!(
    !equations.contains("Vec<Vec<u64>>"),
    "and never on a list of lists: {equations}"
  );
}

/// **The consistency equation meets a member's own word at its COMPARISON**, which is where a
/// sequence and a set stop being the same type.
///
/// One per (member, database, collection field) and NONE anywhere else: a scalar pin has one stored
/// reading, so the row equation already says all there is to say about it.
#[test]
fn the_word_is_asserted_against_every_members_own_collection_kind() {
  let emitted = tight(reeled().equations());

  for member in ["video", "audio"] {
    assert!(
      emitted.contains(&format!("fn_{member}_sqlite_marks_collection(")),
      "{emitted}"
    );
  }
  assert!(
    emitted.contains("__ingraph_held.marks_ref()"),
    "it reads the member's column through the comparison's borrow face: {emitted}"
  );
  assert!(
    emitted.contains("::ingraph::__private::marker::ListMarker<"),
    "at the type the INTERFACE's word resolves to: {emitted}"
  );
  assert!(
    !emitted.contains("_mask_collection"),
    "and a scalar pin gets none: {emitted}"
  );
}

/// **A collection is promised and equated, and it is not a column of the union's output.**
///
/// An arm renders `SELECT "<member's name>" AS "<interface's>"`, and no backend keeps every
/// collection in a column of the row — so the projection row, its decode, the arms' column list and
/// the cursor all take [`InterfaceModel::projected`], which is the stored tier less the collections.
#[test]
fn a_collection_is_no_column_of_the_projection() {
  let model = reeled();
  let projection = tight(model.projection());
  let binding = tight(model.bindings());
  let page = tight(model.page());

  assert!(
    projection.contains("title:String,"),
    "the scalar columns are still the row's: {projection}"
  );
  assert!(
    !projection.contains("marks"),
    "and the collection is not on the row, nor in its decode: {projection}"
  );
  let arms = binding
    .split_once("constARMS")
    .and_then(|(_, rest)| rest.split_once("];"))
    .map(|(arms, _)| arms.to_owned())
    .expect("the binding states its arms");
  assert!(
    !arms.contains("marks"),
    "no arm SELECTS it — the arms' column list is `projected()`: {arms}"
  );
  assert!(
    binding.contains("fncollections<"),
    "and the predicate reaches it per arm instead, at the member's own edge table: {binding}"
  );
  assert!(
    !page.contains("Marks("),
    "and no cursor slot holds it: {page}"
  );
  assert!(
    model.projects(),
    "an interface promising one is still a projection — the union has the tail to select"
  );
}

/// **The order-by vocabulary OPENS to a collection, and the term it mints says `edge`.**
///
/// Parity with the record floor on the half that is a vocabulary, and the honest subject on the half
/// that is storage: no arm of the union selects a collection, so the row being ordered has no column
/// for one whatever backend answers — which is what `OrderTerm::edge` states and what
/// `Unpushable::CollectionTable` reports when a page meets it.
///
/// A record's own term asks `edge_stored` and may answer `array`; an interface cannot ask and must
/// not guess, the storage form being the MEMBER's. The two constructors are asserted together so a
/// day that gave the interface an `array` term reddens here.
#[test]
fn a_collection_is_an_order_term_and_its_subject_is_the_edge() {
  let emitted = tight(reeled().ordering());

  assert!(
    emitted.contains("Marks(::ingraph::__private::graphql::OrderDirection)"),
    "{emitted}"
  );
  assert!(
    emitted
      .contains("Self::Marks(__ingraph_direction)=>::ingraph::__private::cursor::OrderTerm::edge("),
    "the collection's term is EDGE: {emitted}"
  );
  assert!(
    emitted
      .contains("Self::Title(__ingraph_direction)=>::ingraph::__private::cursor::OrderTerm::new("),
    "and a scalar's is unchanged: {emitted}"
  );
  assert!(
    !emitted.contains("OrderTerm::array"),
    "an interface never mints an array term — the storage form is the MEMBER's: {emitted}"
  );
}

/// **THE SYNTHETIC WORDS TAKE THE MODEL's SEAT** where no database block moved them, so an
/// interface a platform's codegen built invents its discriminant and its derived table under that
/// platform's mark.
///
/// And it is never SILENT there. The engine holds one default and it is `ingraph`'s, so a moved
/// model must state both words in its emission — which is exactly what
/// [`InterfaceModel::mints_the_default_words`] answering `false` buys.
#[test]
fn a_platform_mark_moves_the_synthetic_words_and_ends_the_silence() {
  let mut model = media();
  model.prefix = EmissionPrefix::new("__mg");

  for kind in [DatabaseKind::Sqlite, DatabaseKind::Postgres] {
    assert_eq!(model.kind_word(kind), "__mg_kind__");
    assert_eq!(model.source_word(kind), "__mg_union__");
    assert!(
      !model.mints_the_default_words(kind),
      "the engine still believes `__ig_kind__`, so the expansion has to say otherwise",
    );
  }
}

/// A DATABASE's own `alias(prefix = …)` still wins over the model's seat, which is the altitude
/// rule: the declaration's word is nearer the column than the framework's mark is.
#[test]
fn a_database_block_outranks_the_models_own_mark() {
  let mut model = media();
  model.prefix = EmissionPrefix::new("__mg");
  model.persist = vec![crate::interface::InterfaceDatabase {
    kind: DatabaseKind::Sqlite,
    aliases: crate::model::AliasOptions {
      prefix: Some(String::from("__mine")),
      depth: None,
    },
  }];

  assert_eq!(model.kind_word(DatabaseKind::Sqlite), "__mine_kind__");
  assert_eq!(
    model.kind_word(DatabaseKind::Postgres),
    "__mg_kind__",
    "the database beside it named nothing, so it takes the model's seat",
  );
}