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
//! The WIRE BINDING: the emitted OUTPUT OBJECT and its ADDRESS as a client reads them, and the two
//! INPUT objects a client writes — the `<E>OrderBy` the ruled `orderBy: [<T>OrderBy!]` argument is a
//! list of (`@oneOf`, one column per term), and the `<E>Filter` the `where` argument takes (an
//! ordinary input object, any number of columns at once).
//!
//! [`graphql`](super::graphql) writes the SHAPES; this file writes what makes one a schema. The
//! split is not tidiness — it is what the era rule left behind. That file emits structures and an
//! enum and binds them to no library, and its note says the external names are carried on the model
//! for exactly this round to spend. This is that round, for the one type it can be spent on.
//!
//! # The gate is not a `#[cfg]`
//!
//! `if_async_graphql!` — the binding gate. A `#[cfg(feature = "async-graphql")]` written inside an
//! expansion asks whether the DECLARING crate has a feature by that name, which is a different
//! manifest and usually no feature at all; the gate asks the question of `ingraph`'s own build,
//! which is where the library actually is. Every backend impl in this crate already rides one.
//!
//! # The face is WRITTEN OUT, because a derive cannot be attached from here
//!
//! An attribute in IMPL position can be emitted freely — the impl is written here and the attribute
//! goes on it. A DERIVE cannot: a derive belongs to the type's own declaration, which
//! [`graphql`](super::graphql) writes OUTSIDE the gate, and a type that existed only where the
//! binding does would vanish from every build without it. Emitting the declaration twice, once with
//! the derive and once without, is the other way out, and it doubles the emitted text of a wire type
//! to buy back a derive whose whole output is one `InputType` impl.
//!
//! So the face is written out, exactly as `ingraph`'s own filter faces are, and for one of the same
//! reasons: **the registry entry is ours**, so `description: None` is a fact of the emission rather
//! than a hope about what a derive lifted. That matters here more than anywhere: the emitted
//! order-by carries generated prose on the type AND on every variant — *Order by the `title` column,
//! in the direction given* — and async-graphql's derives call `get_rustdoc` unconditionally with no
//! key to decline it, so a derive would have published all of it.
//!
//! # FOUR FACES SHIP, THREE UNCONDITIONALLY AND ONE UNDER A CONDITION
//!
//! `<E>OrderBy` names NO type the declaration chose: every field is an `OrderDirection`, which is the
//! framework's own. `<E>GraphqlOutput` and `<E>KeyOutput` DO name the declaration's types, and each
//! demands the OUTPUT CROSSING (`ingraph::ToGraphqlOutput`) of every form it returns — which is a
//! demand the framework can now meet for every class of its own vocabulary. So all three are
//! UNCONDITIONAL.
//!
//! **`<E>Filter` SHIPS TOO, and the condition it rides is the LIST LEG's.** It demands `InputType` of
//! every stored column's filter, and that demand cannot be made conditional AT THE IMPL: a `where`
//! clause naming only concrete types is a TRIVIAL BOUND, which stable rustc rejects at the item that
//! declares it (`trivial_bounds` is unstable). `renderable`, the helper that wrote such a clause, is
//! not resurrected. What is conditional instead is the EMISSION —
//! [`RecordModel::wire_filters`](crate::model::RecordModel::wire_filters) — and the condition is not
//! a guess about which filters render: it is *does anything on the wire take one*. async-graphql
//! registers the types reachable from the schema root, so a face no argument names is not in an SDL
//! at all, and emitting one would be an obligation with no reader.
//!
//! **What the two rows that HELD it cost, measured at this tip.** The whole workspace compiles
//! `--all-features` with the face emitted under that condition, and the corpus needed exactly two
//! changes, both in `ingraph-derive`'s `enums.rs` and both a DECLARATION rather than a framework row
//! — see the crossing's own note in [`super::cross`]. Neither of the two rows below was among them:
//! `TextFilter<Tag>` is `labels.rs`'s and that record has no stored id, so it has no query lane and
//! no argument asks it for a predicate; `ListFilter<u128, …>`'s element bound is
//! `ToGraphqlInput` since #231, which `u128` has a row in.
//!
//! The crossing rather than `OutputType` directly, and the difference is what a `u128` id renders
//! as: the emitted MEMBER stays the declaration's own type (layer 1, which no word moves), and the
//! resolver returns `<u128 as ToGraphqlOutput>::Output<'_>` — the `U128` carrier. Type-directed,
//! so `type Uuid7 = u128` reaches it too; a projection matching TOKENS would have handed the id
//! straight through and rendered nothing at all.
//!
//! Unconditional, they refuse declarations the framework itself cannot serve — and the size of that
//! refusal is MEASURED at this tip rather than predicted. The whole workspace was compiled with the
//! three faces emitted unconditionally, `--all-features`, and every unsatisfied row read off the
//! compiler:
//!
//! | missing row | where | who can supply it |
//! |---|---|---|
//! | `u128: OutputType` (×10) | `labels.rs`'s id | ~~the CARRIER projection~~ **CLOSED** — the OUTPUT CROSSING, and the face reads THROUGH it: an id member stays a `u128` and the resolver returns `<u128 as ToGraphqlOutput>::Output<'_>`, which IS `U128` |
//! | `SignedDuration: OutputType` | `fixtures.rs` | **CLOSED** by the same map, through `JiffDuration` |
//! | `Codec`/`Grade`/`Channel`/`Db`: `OutputType` | `enums.rs`, `fixtures.rs` | ~~**NOBODY**~~ **CLOSED** — `enumeration::wire` emits the output leg now, and `#[derive(ingraph::Enum)]` is the one door that carries it |
//! | `Codec`/`Grade`/`Db`: `InputType` | the same | **CLOSED, but not all by one word** — `Grade` is an `enum` and takes the derive; `fixtures.rs`'s `Codec` and `Db` are STRUCTS reading as enumerations, so no `enum` derive can serve them and the corpus pays a `#[Scalar]` each |
//! | `Tag`: `InputType`/`OutputType`, `Reel<Tag>`/`Roll<Tag>`: `OutputType` | `labels.rs`, `fixtures.rs` | **CLOSED by the corpus** — the OUTPUT leg needs no derive at all (`ToGraphqlOutput` is an ordinary trait a declaring crate writes for its own type, and a `Vec` of that type needs NOTHING further: the map reads its collection fork off the element's own `DefaultVecMarker`, which such a crate already writes for the filter side), and the INPUT leg is one `#[Scalar]` per type |
//! | `TextFilter<Tag>: InputType` | `labels.rs`, `fixtures.rs` | ~~**NOBODY**~~ **THE DECLARING CRATE, since #231** — the CARRIER AXIS is the road: `TextFilter<S, I>` carries the reading as a parameter, this crate holds ONE generic row over it, and a declaring crate joins by implementing `TextWire<Tag>` on a marker it owns. Unclaimed in the corpus, and it costs nothing there: neither record has a query lane |
//! | `u128: InputType` | `fixtures.rs`'s `shadowed` | ~~**NOBODY**~~ **CLOSED by #231** — the collection faces ask the element for `ToGraphqlInput` now rather than for `InputType`, and `u128` crosses through `U128` there |
//!
//! The COLLECTION classes this table used to carry are gone from it, and that is what the round that
//! wrote the generic `ListFilter<T, VF>` / `SetFilter<T, VF>` faces bought: an element a declaring
//! crate owns now reaches a schema through one local row in `ingraph`, so no `ListFilter<Tag, …>`
//! appears above.
//!
//! `graphql::filter`'s own note already says the shape out loud — *a `Vec<Timestamp>` column
//! resolves to `ListFilter<Timestamp>` in Rust and reaches no schema*, which the generic rows have
//! since answered. So *this declaration has no wire face* is the framework's designed state for part
//! of its own vocabulary, and an unconditional face turns that state into a compile error inside an
//! expansion its author cannot edit.
//!
//! **A CORRECTION, measured: RFC 2451 does NOT admit `impl ForeignTrait for ForeignType<Local>`.**
//! This note claimed it did, and that a declarer's crate could therefore have minted
//! `impl InputType for EnumFilter<Codec>`. It could not. The orphan rule's sequence is
//! `T0, T1..=Tn` — the self type followed by the TRAIT's parameters — and at least one of them must
//! be a LOCAL type, where `ForeignType<Local>` is not one. `InputType` takes no parameter, so the
//! sequence is the self type alone and there is nowhere for a local type to sit. What RFC 2451
//! actually admits is the local type in a trait parameter: `impl<T> ForeignTrait<Local> for
//! ForeignType<T>`. Measured by writing the impl out in full in `labels.rs` and reading `E0117` —
//! *impl doesn't have any local type before any uncovered type parameters*.
//!
//! The enum row's conclusion survives the correction and its reason changes: `EnumFilter` is
//! `ingraph`'s OWN type, so one generic `impl<T: InputType> InputType for EnumFilter<T>` there is a
//! plain local impl serving every declared enum at once — and that generic row is not a convenience,
//! it is the ONLY road. What is left for the declarer is `Codec: InputType`, an impl on its own type.
//!
//! **BOTH of the rows that were open are closed, and one axis closed them.**
//!
//! `TextFilter<Tag>: InputType` was `E0117` in the declaring crate for the reason just corrected, and
//! `E0119` in `ingraph`: a generic `impl<S: InputType> InputType for TextFilter<S>` overlapped the two
//! concrete registrations, and replacing them with one would have published `SmolStrFilter` —
//! async-graphql names that scalar `SmolStr` — renaming the canonical `TextFilter` the crate defends.
//! The CARRIER AXIS took the second wall away so the first stopped mattering: the reading is a
//! PARAMETER now (`TextFilter<S, I = Builtin>`), the two concrete registrations are rows of
//! `Builtin`'s, and one generic row over the parameter has nothing for coherence to reason about. A
//! declaring crate writes `impl TextWire<Tag> for TagWire`, which is legal there because the marker
//! is local.
//!
//! `u128: InputType` was the same wall from the other side, and it is what the generic collection
//! rows COST: `ListFilter<T, VF>` asked `T: InputType` for its six list slots and `hasElement`. The
//! bound is `ToGraphqlInput` now — the INPUT-side twin of the output crossing, keyed on the operand
//! type — so a `Vec<u128>` column publishes `[u128!]`, which is the form the scalar column of the
//! same type already published.
//!
//! **The OUTPUT leg of the vocabulary row is supplied**, and it was the single fact deciding whether
//! the three faces could ever be unconditional: a record exposing a vocabulary column — which two
//! corpus declarations and the executed wire schema all do — could carry no output object however
//! many other rows fell. `enumeration::wire` writes `OutputType` beside the input face, hand-written
//! and inside the binding gate, with one residual wall stated at that module: a build enabling
//! async-graphql's own `boxed-trait` feature refuses the impl (`E0195`), because that feature
//! rewrites the trait method into a boxed-future one.
//!
//! **Measured at this tip: the OUTPUT OBJECT and its ADDRESS have ZERO unsatisfied rows over the
//! whole corpus, and both now SHIP.** Both are emitted unconditionally, reading through
//! `ToGraphqlOutput`; the workspace compiles `--all-features --all-targets` and the executed
//! `ingraph/tests/wire_schema.rs` renders their SDL and reads real rows back through them.
//!
//! **And the FILTER ships with them, one condition apart.** The `where` argument names `<E>Filter`,
//! so the list resolver's predicate leg and this face are one round: `emit::queries` writes the
//! argument, `emit::cross` writes the crossing that resolves it against a store, and
//! `ingraph/tests/wire_where.rs` executes all three against a real SQLite pool. The ARGUMENT OBJECT's
//! `filter` member is a different position and is still nobody's — that object mirrors the engine's
//! find surface and no resolver takes one.
//!
//! One corpus row moved with the crossing's own rework: an element that appears in a COLLECTION now
//! owes `DefaultVecMarker`, because that is where the output map reads a `Vec`'s fork from. It is the
//! INPUT side's own trait, so the cost is one line and the fact is stated once for both positions —
//! `ingraph-derive`'s `labels.rs` carries it for `Tag`.
//!
//! # The naming layers, on this face
//!
//! An order-by field is an INPUT position, and it takes the FILTER's name for its column — one
//! column, one input name, so a client never spells the same column two ways in one document. The
//! OUTPUT position is free to differ and does: `output(rename = "startsAt")` moves what a client
//! READS and leaves `beginsAt` here, which is what two faces on the model are for.
//!
//! [`wire_field`] is the one rename act, and it applies only where the declaration named nothing —
//! so a declared name reaches a client exactly as written, and an undeclared one takes
//! async-graphql's own camelCase, which is the ruled division.
//!
//! The TYPE names are [`wire_type`]'s, and that rule is one sentence with two readings — see its own
//! note.
//!
//! # THE `__async_graphql_` PREFIX PIN — the emitted Rust idents are mangled and every wire name is
//! SPELLED
//!
//! Every FUNCTION an emitted `#[Object]` face declares — and every ARGUMENT one takes — wears the
//! `__async_graphql_` prefix, through [`method::wire_method`](crate::method::wire_method), which is
//! that shape's one home. The prefix is a namespace this emission owns AND it names the BACKEND
//! whose face this is, so a second GraphQL binding mints its own beside these rather than colliding
//! with them; a declaration writing into either is writing into the framework's, which is precisely
//! what the pin puts out of reach.
//!
//! **The wire names come back PER ITEM, and that is the mechanism rather than a detail.** A
//! `#[graphql(name = "…")]` sits on every field of both faces now, not only on the renamed ones:
//! async-graphql's default is the RENAME RULE over the method ident (`object.rs`'s
//! `method_args.name.clone().unwrap_or_else(|| rename_fields.rename(sig.ident.unraw(), …))`, 7.2.1),
//! and after the pin that ident is `__async_graphql_title`. The explicit key WINS over the rule at
//! both positions —
//! `args::ObjectField::name` for a field, `args::Argument::name` for an argument — which is what
//! makes per-item names the road.
//!
//! The IMPL-level knobs (`rename_fields`, `rename_args`) are NOT the road, and the reason is not
//! taste. A rule is ONE FUNCTION OF THE IDENT applied to every item of the block, and this face has
//! two kinds of name in it: a word the declaration wrote — `bitRate` over a member called `checksum`
//! — and the fallback for a field that wrote none. No function of `__async_graphql_checksum`
//! produces `bitRate`, so a rule cannot serve the first kind at all, and serving only the second is
//! what the per-item key already does.
//!
//! What a rule WOULD do is leave the wire a function of the mangling, and after the BACKEND SWEEP
//! that is no longer even a near miss. `Inflector` skips a leading separator run in both of its
//! families (`to_case_camel_like`'s `!found_real_char && is_not_alphanumeric` arm,
//! `to_case_snake_like`'s `first_character` guard) and camelCases what remains — so `__title` used
//! to render `title` by an upstream detail nothing promised, and `__async_graphql_title` renders
//! `asyncGraphqlTitle`. The written key is what holds the wire still across a prefix that names its
//! backend, which is why it is on EVERY item rather than on the renamed ones.
//!
//! Two things do NOT take the prefix, and each is ruled:
//!
//! * the emitted TYPES — `<E>GraphqlOutput`, `<E>KeyOutput`, `<E>OrderBy` — which are the visible
//!   vocabulary a declaration names and an application mounts;
//! * the ACCESSORS [`graphql`](super::graphql) writes, which are layer 2 and the Rust read road, so
//!   a caller spells `title_ref()` exactly as before.
//!
//! **SDL byte-identical**, and that is the proof the sweep was a rename of Rust idents alone: the
//! executed schemas of `ingraph/tests/wire_schema.rs` and `ingraph/tests/wire_trio.rs` export the
//! same bytes before and after.
//!
//! # BUILD PIN — every emitted async-graphql ATTRIBUTE passes `crate = "…"`
//!
//! The shelf's whole point is that a DECLARING crate never needs async-graphql in its own manifest:
//! `#krate::__private::async_graphql` is the path every emitted name is reached through, and
//! `RecordModel::framework` is what writes it. An ATTRIBUTE is the one thing that path is not enough
//! for, because a derive expands into paths of its OWN — and async-graphql's derives resolve those
//! through `proc_macro_crate::crate_name("async-graphql")`, read against the crate being compiled
//! (`async-graphql-derive`'s `get_crate_path`, `src/utils.rs`). In a declaring crate that lookup
//! fails and the fallback is a bare `::async_graphql`, which resolves to nothing.
//!
//! So an emitted async-graphql attribute has TWO halves and both are required:
//!
//! 1. the attribute's own PATH is the shelf path — `#[#krate::__private::async_graphql::Object]`,
//!    never `#[::async_graphql::Object]`, or the ATTRIBUTE itself does not resolve;
//! 2. the `crate = "…"` key names the same shelf, or the attribute resolves and everything it
//!    EXPANDS TO does not.
//!
//! This is the redirect sqlx never offered — its derives take no such key, which is why the row's
//! `FromRow` is written out by hand — and it is why async-graphql is the one shelved crate whose
//! derives are redirected rather than replaced.
//!
//! **The audit, measured at this tip:** the emission writes NO async-graphql attribute at all. The
//! order door below is three hand-written impls carrying `#[automatically_derived]` and nothing
//! else, and every async-graphql NAME inside them is already rooted through the shelf. So the rule
//! has nothing to fix here and everything to guard: `ingraph-codegen`'s own
//! `no_emitted_async_graphql_attribute_is_missing_the_crate_key` walks the emitted text of the
//! corpus and holds the rule over whatever a later round adds.
//!
//! `model::GraphqlKind` carries three attribute NAMES — `output_object`, `input_derive`,
//! `order_by_derive` — and `enumeration.rs` a fourth, all spelled as bare `::async_graphql::…`
//! paths. None of them is emitted today (they are read by pins alone), and each is half a rule when
//! it is: the path they answer is the one that does not resolve in a declaring crate. Whichever
//! round first spends one owes it both halves above.

use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned as _;

use crate::{
  method::{Member, wire_method},
  model::{
    Graphql, GraphqlBackend, RecordModel, default_filter_name, default_key_output_name,
    default_order_by_name, default_output_name,
  },
  name::RustSafeName,
  unit,
};

#[cfg(test)]
mod key_faces_tests;
#[cfg(test)]
mod key_rename_tests;
#[cfg(test)]
mod tests;

/// A declared name as a client sees it: verbatim where the declaration wrote one, and lower camel
/// case where the framework fell back on the Rust field's own name.
///
/// The fork is what keeps ⑤'s ruling true on a face that has no method for async-graphql to rename:
/// camelCase is the BACKEND's act over domain-named Rust fields, so applying it to a name a
/// declaration chose would be this emitter overriding that choice. `declared` is compared against
/// the field's own spelling to tell the two apart, and the comparison is exact rather than a guess —
/// the model stores the fallback AS the field's name, so equality is precisely *nothing was
/// written*.
pub(super) fn wire_field(declared: &str, source: &syn::Ident) -> String {
  if source == declared {
    return wire_member(source);
  }
  declared.to_owned()
}

/// The client's name for a member NO declaration named: async-graphql's own camelCase over the Rust
/// name, with a raw prefix dropped.
///
/// Its own function because the prefix pin made it one. The library used to compute this itself,
/// off the method ident; the emitted idents are prefixed now, so the fallback has to be SPELLED — a
/// `#[graphql(name = "…")]` on every wire item, including the ones nobody renamed. Both faces read
/// it here rather than each spelling `lower_camel`, so *what a client sees where nothing was
/// written* has one home.
///
/// The unraw is [`RustSafeName`]'s, which is the crate's one answer to that question: `r#type` is how
/// Rust spells a column called `type`, and async-graphql's own rename runs through `Ident::unraw`
/// too — so this agrees with the library on the input the library used to be given.
///
/// `pub(crate)` since B-27: an INTERFACE has no per-field rename grammar at all, so every contract
/// field is this case, and reading the fallback here rather than respelling `lower_camel` is what
/// keeps one answer to *what a client sees where nothing was written*.
pub(crate) fn wire_member(source: &syn::Ident) -> String {
  lower_camel(RustSafeName::from_ident(source).external())
}

/// `media_id` → `mediaId`. async-graphql's own field rename rule, applied where no method exists for
/// the library to apply it to.
///
/// # A LEADING underscore is EATEN, and that is a correction
///
/// This carried the opposite claim — *a leading underscore run is kept, because a rule that silently
/// produced `id` from `_id` would collide with the framework's own address member* — and the code
/// under it always dropped it. The tests beside this module caught the divergence, and the DOC is
/// what was wrong.
///
/// Measured, at the library this rule is a copy of: async-graphql renames a field through
/// `RenameTarget::Field` → `RenameRule::Camel` → `Inflector::to_camel_case`, whose loop `continue`s
/// past every non-alphanumeric character before the first real one (`Inflector` 0.11.4,
/// `src/cases/case/mod.rs`, the `!found_real_char && is_not_alphanumeric` arm). So `_id` renders as
/// `id` on an `#[Object]` method too — and "fixing" this function would have CREATED the divergence
/// it warned about, spelling one column `_id` on the hand-written face and `id` on the derived one.
///
/// The collision the old note feared is real and is async-graphql's, not this emitter's; a
/// declaration that writes `_id` beside the framework's own address member gets it either way, and
/// the place to refuse that is the emitted-type collision rule rather than a rename that disagreed
/// with the library.
///
/// The one deliberate difference is the DEGENERATE case: a name that is all separator (`__`) leaves
/// nothing to render, and this returns the name itself where `to_camel_case` returns the empty
/// string. An empty GraphQL field name is invalid SDL, so the fallback is the safer of two answers
/// for an input no declaration is expected to write.
fn lower_camel(name: &str) -> String {
  let mut camel = String::with_capacity(name.len());
  let mut upper = false;
  for character in name.chars() {
    if character == '_' {
      upper = !camel.is_empty();
    } else if upper {
      camel.extend(character.to_uppercase());
      upper = false;
    } else {
      camel.push(character);
    }
  }
  if camel.is_empty() {
    return name.to_owned();
  }
  camel
}

/// The SDL name of ONE emitted type: a declared rename VERBATIM, and otherwise the name the
/// framework publishes for that type.
///
/// # The ruled rule, and why it needs the second parameter
///
/// *An emitted output publishes the record's TYPE name — strip the framework's default suffix,
/// publish a declared rename verbatim.* Read at the OUTPUT carriers that is a strip:
/// `VideoTrackGraphqlOutput` → `VideoTrack`, `VideoTrackKeyOutput` → `VideoTrackKey`, because
/// `GraphqlOutput` is a Rust CARRIER's convention and a client has no business reading it. Read at
/// the input types it is the identity: `VideoTrackOrderBy` and `VideoTrackFilter` are the names the
/// design's own SDL is written in, so there is nothing on them a schema does not read.
///
/// One function over both, because the half that differs is one VALUE — what to publish where the
/// declaration renamed nothing — and the half that does not is the rule: a name a declaration chose
/// is a name it chose, and no convention of this emitter may move it.
///
/// `default` is compared against the DECLARED name to tell the two cases apart, and the comparison
/// is exact rather than a guess: [`RustSafeName`] stores the framework's fallback AS the name, so
/// equality is precisely *nothing was written*. A declaration that renames a type to the string the
/// framework would have picked lands in the default arm, which is the same answer either way.
fn wire_type(declared: &RustSafeName, default: &syn::Ident, published: &syn::Ident) -> String {
  if default == declared.external() {
    return published.to_string();
  }
  declared.external().to_owned()
}

/// The OUTPUT OBJECT's published name — the one word both the object's own registration and the
/// root field returning it are built from.
///
/// Here rather than at either caller, because the two must agree by construction: a declared
/// `output(rename = "…")` moves the type a client reads AND the field it reads it through, and two
/// spellings of [`wire_type`]'s call is where that would come apart.
pub(super) fn published_output(graphql: &Graphql, model: &RecordModel) -> String {
  wire_type(
    &graphql.output,
    &default_output_name(&model.record),
    &model.record,
  )
}

/// The ADDRESS's BASE — the word both of its faces are built on where neither was named outright.
///
/// Here rather than at either caller, for [`published_output`]'s reason: `key(rename = "Address")`
/// re-bases BOTH halves of the address face, and two spellings of [`wire_type`]'s call is where that
/// would come apart.
///
/// # The `Input` SUFFIX IS THE ONE BLESSED DERIVATION, and no other rename composes
///
/// The user's ruling of 2026-08-16. A rename word is otherwise VERBATIM — what an author typed is
/// what a client reads — and the argument face's DEFAULT is the single exception, because GraphQL
/// keeps input and output types in ONE namespace: the sending half of an address must differ from
/// the reading half by something, and the only question is whether that something is predictable. It
/// is: the suffix is deterministic, it is the shape async-graphql's own derivations already take,
/// and a reader who wrote `Address` can say what the argument is called without looking.
///
/// **The precedent is narrow and is recorded as narrow**: this is the one composition, it applies to
/// the BASE alone, and a later reader may not cite it as licence for a second. In particular a
/// declared [`published_key_object`] does NOT compose — `output(rename = "AddressM")` leaves the
/// argument at `AddressInput`, because a name an author chose is not a stem this framework may
/// suffix. Two names in one namespace need two words or none, which is exactly why the member seats
/// were minted.
fn key_base(graphql: &Graphql, model: &RecordModel) -> String {
  wire_type(
    &graphql.key_output,
    &default_key_output_name(&model.record),
    &format_ident!("{}Key", model.record),
  )
}

/// The ADDRESS OBJECT's published name — what a client READS an address back in.
///
/// MEMBER, then BASE-DERIVED, then DEFAULT, which is the 2026-08-16 ruling's resolution order read
/// at one seat: `key(output(rename = "…"))` answers first, `key(rename = "…")` re-bases where it did
/// not, and a record that wrote neither publishes `<Record>Key`. The member arm is answered without
/// consulting the base, which is what makes `key(output(rename = "…"))` STANDALONE-LEGAL.
pub(super) fn published_key(graphql: &Graphql, model: &RecordModel) -> String {
  graphql
    .key_object
    .clone()
    .unwrap_or_else(|| key_base(graphql, model))
}

/// The ADDRESS ARGUMENT's published name — what a client SENDS a compound address in.
///
/// [`published_key`]'s twin at the other end of one address, under the same three-step resolution:
/// `key(input(rename = "…"))`, else the base with the one blessed suffix on it, else
/// `<Record>KeyInput`.
///
/// Here rather than at its one caller, for [`published_key`]'s reason — and the two are deliberately
/// NOT one function with a flag: the derivations differ (one composes, one does not) and a shared
/// body would have to branch on which face it was answering anyway.
pub(super) fn published_key_input(graphql: &Graphql, model: &RecordModel) -> String {
  graphql
    .key_argument
    .clone()
    .unwrap_or_else(|| format!("{}Input", key_base(graphql, model)))
}

/// The published output's PLURAL — the declaration's own word where it wrote one, and otherwise the
/// word English gives the name [`published_output`] just answered.
///
/// Here, beside that one, for exactly its reason: the single and the page are two spellings of ONE
/// published name, so a declared `output(rename = "Track")` moves both together and neither caller
/// derives its own. A plural taken from the RECORD's name instead would leave a renamed record
/// answering `track(id:)` beside `reels`.
///
/// The WORD rather than the field name. Lowering an initial is [`super::queries`]'s one naming act
/// and stays there, so `plural = "Corpora"` and `plural = "corpora"` reach the same field — and the
/// next reader of this word (a connection, an aggregate) spells its own name from the same fact
/// rather than from a field name it would have to un-spell.
pub(super) fn published_plural(graphql: &Graphql, model: &RecordModel) -> String {
  graphql
    .plural
    .clone()
    .unwrap_or_else(|| crate::plural::of(&published_output(graphql, model)))
}

/// The true prelude, re-imported around the two `#[Object]` blocks — the one place this emission
/// cannot write its own paths.
///
/// # It is a MEASURED defect of somebody else's macro, not a precaution
///
/// Every path this crate emits is absolute (`::core::option::Option::None`), because an expansion
/// lands in the DECLARER's namespace and a module that declares `struct None;` would otherwise
/// capture it. `ingraph-derive`'s `shadowed` fixture is that module, written to hold the rule.
///
/// `#[Object]` is async-graphql's macro and its output is not ours: it writes a bare `None`, which
/// the fixture's `pub struct None;` wins — `E0308: expected Option<__FieldIdent>, found None`,
/// reported at the `#[ingraph::record(…)]` the declarer wrote, naming a type nobody in that file
/// mentions. Measured the moment the output face went unconditional.
///
/// A `use` inside an anonymous const shadows the module's items for the tokens in that const and
/// nothing outside it, so the foreign expansion resolves the names it means. The const is the
/// crate's own grouping idiom — `enumeration::wire` already hosts the enum's whole face in one —
/// and TRAIT IMPLS inside one apply globally, which is what makes the wrapping free.
///
/// The list is the prelude the fixture shadows rather than the subset one library happens to spell:
/// what is being defended against is a foreign macro's tokens, and those change with its version.
pub(crate) fn prelude() -> proc_macro2::TokenStream {
  // ONE `use` per name, spelled absolutely, rather than the braced groups that read better: the
  // emission's own audit walks every path it writes and refuses a bare `std` name, and a
  // `{self, None, Some}` group flattens into leaves it cannot tell from one. The rule is worth more
  // than the line count.
  let why = "the prelude is re-imported for a FOREIGN macro's tokens, and which of these names \
             that macro spells is its business rather than this emission's";
  quote! {
    #[allow(unused_imports, reason = #why)]
    use ::core::clone::Clone;
    #[allow(unused_imports, reason = #why)]
    use ::core::cmp::Eq;
    #[allow(unused_imports, reason = #why)]
    use ::core::cmp::PartialEq;
    #[allow(unused_imports, reason = #why)]
    use ::core::convert::From;
    #[allow(unused_imports, reason = #why)]
    use ::core::convert::Into;
    #[allow(unused_imports, reason = #why)]
    use ::core::convert::TryFrom;
    #[allow(unused_imports, reason = #why)]
    use ::core::default::Default;
    #[allow(unused_imports, reason = #why)]
    use ::core::fmt::Debug;
    #[allow(unused_imports, reason = #why)]
    use ::core::hash::Hash;
    #[allow(unused_imports, reason = #why)]
    use ::core::iter::Iterator;
    #[allow(unused_imports, reason = #why)]
    use ::core::marker::Copy;
    #[allow(unused_imports, reason = #why)]
    use ::core::option::Option;
    #[allow(unused_imports, reason = #why)]
    use ::core::option::Option::None;
    #[allow(unused_imports, reason = #why)]
    use ::core::option::Option::Some;
    #[allow(unused_imports, reason = #why)]
    use ::core::result::Result;
    #[allow(unused_imports, reason = #why)]
    use ::core::result::Result::Err;
    #[allow(unused_imports, reason = #why)]
    use ::core::result::Result::Ok;
    #[allow(unused_imports, reason = #why)]
    use ::std::boxed::Box;
    #[allow(unused_imports, reason = #why)]
    use ::std::string::String;
    #[allow(unused_imports, reason = #why)]
    use ::std::vec::Vec;
  }
}

impl RecordModel {
  /// This record's wire binding, behind the binding gate — or nothing, for a record with no
  /// `graphql(…)` block to bind.
  ///
  /// THREE faces: the output object, its address, and the order-by. What is still held is the
  /// FILTER's, and the module note carries the two rows that hold it.
  pub(super) fn wire(&self) -> proc_macro2::TokenStream {
    let Some(graphql) = self.graphql.as_ref() else {
      return proc_macro2::TokenStream::new();
    };
    let Some(backend) = graphql.backends.first() else {
      return proc_macro2::TokenStream::new();
    };
    let order_by = self.order_by_face(backend);
    let filter = self.filter_face(graphql);
    let output = self.output_face(graphql, backend);
    let key_output = self.key_output_face(graphql);
    let key_input = self.key_input_face(graphql);
    // The QUERY UNIT's face carries a SECOND gate of its own — the database's — so it is written
    // beside this block rather than inside it: an engine call names one dialect's row, where the two
    // faces above name none.
    let queries = self.queries_face();
    let gate = self.framework(&["gate"], "if_async_graphql");
    let prelude = prelude();
    quote! {
      #gate! {
        const _: () = {
          #prelude

          #output
          #key_output
          #key_input
        };

        #order_by
        #filter

        #queries
      }
    }
  }

  /// The OUTPUT object's face: `#[Object]` over the ACCESSORS
  /// [`graphql`](super::graphql) already wrote, every member crossing through
  /// `ToGraphqlOutput`.
  ///
  /// # A SECOND impl block, and it has to be
  ///
  /// The accessors are `const fn` borrows carrying generated documentation, and the attribute would
  /// both refuse the constness and publish the prose. Two blocks also keep the delegation visible —
  /// every method here READS an accessor, which is what makes `output(field = "…")` a rename with a
  /// consequence rather than a Rust detail.
  ///
  /// # The three naming layers are visible in every method
  ///
  /// The method is named after LAYER 1 — the emitted member, which no word moves — UNDER THE
  /// `__async_graphql_` PREFIX, and READS through LAYER 2, the accessor. That pairing is what keeps
  /// the two rename axes independent: a field renamed in Rust alone keeps the client's name, and a
  /// field renamed for the client alone keeps its Rust one. LAYER 3 is `#[graphql(name = "…")]`,
  /// written out on EVERY field — see the module note's pin: the prefix is what took the fallback
  /// away from the library, so this emission spells it.
  ///
  /// The method names cannot collide with the accessors: those are layer 2 under the borrow suffix
  /// and wear no prefix — `__async_graphql_checksum` beside `checksum_ref`, whatever either was
  /// renamed to.
  ///
  /// # THE `&self`-ONLY INVARIANT, AMENDED — a second CLASS of field, not a broken rule
  ///
  /// This note used to read *every method on both faces is a `&self` reader, so there is no named
  /// parameter to prefix and no argument name to spell*. That was true of every field this object
  /// had, and it stays true of every field of that CLASS: a COLUMN ACCESSOR answers off the hydrated
  /// row, so it takes `&self` and nothing else — giving one a context would say a row's own value
  /// depended on the request that asked for it.
  ///
  /// An ARTIFACT field is a different class. What it answers is WHERE A BLOB IS, and that belongs to
  /// the STORE — which arrives at run time, in the request's own context, through the door a
  /// deployment installed. So it takes `&async_graphql::Context<'_>`, and the invariant is restated
  /// of the class rather than of the object: column accessors are `&self`-only, and a STORE-MEDIATED
  /// field reaches the request.
  ///
  /// The same amendment is written at [`crate::method::wire_method`], the other site that stated the
  /// rule, and the two are kept in step deliberately — a reader arriving at either has to find the
  /// same sentence.
  ///
  /// The ARGUMENT-NAMING pin is unchanged and has its first spender: the context parameter wears
  /// [`wire_method`]'s own prefix like every other emitted ident, so nothing a declaration can name
  /// collides with it.
  ///
  /// # THE CROSSING happens here and nowhere else
  ///
  /// `<Ty as ToGraphqlOutput>::Output<'_>` rather than `&Ty`, and that is the whole of what makes a
  /// `u128` id reach a client at all: the member stays the declaration's own type, the accessor still
  /// hands back a `&Uuid7`, and the wire face returns the `U128` carrier. Type-directed, so
  /// `type Uuid7 = u128` reaches the row through the alias.
  ///
  /// UNCONDITIONALLY, and that is measured rather than hoped: the whole corpus was compiled with
  /// both output faces demanded through the crossing and nothing was missing. There is no `where`
  /// clause to make it conditional with — see the module note.
  ///
  /// # No doc attribute, anywhere in the block
  ///
  /// async-graphql's `#[Object]` calls `get_rustdoc` on the block and on every method, and the rule
  /// is that descriptions come from `attrs(desc = …)` and nowhere else. The documented accessors this
  /// delegates to are in a DIFFERENT impl block, which the attribute never reads, so there is nothing
  /// for it to find.
  fn output_face(&self, graphql: &Graphql, backend: &GraphqlBackend) -> proc_macro2::TokenStream {
    let ty = graphql.output.safe();
    let sdl = published_output(graphql, self);
    let ag = self.framework(&[], "async_graphql");
    let shelf = self.vendored("async_graphql");
    let crossing = self.framework(&["graphql"], "ToGraphqlOutput");
    let id_ty = &self.key.id.ty;
    let key_output = graphql.key_output.safe();
    let id_borrow = Member::Borrow.name(&format_ident!("id"));
    let key_borrow = Member::Borrow.name(&format_ident!("key"));
    let id = self.wire_writes_id().then(|| {
      let method = wire_method(&format_ident!("id"));
      quote! {
        #[graphql(name = "id")]
        async fn #method(&self) -> <#id_ty as #crossing>::Output<'_> {
          <#id_ty as #crossing>::to_graphql_output(Self::#id_borrow(self))
        }
      }
    });
    let key_method = wire_method(&format_ident!("key"));
    let fields = backend.fields().iter().map(|field| {
      let member = &field.source;
      let method = wire_method(member);
      let borrow = Member::Borrow.name(field.accessor());
      let ty = field.wire_ty();
      // LAYER 3, and it is written out for EVERY field now — a declared word verbatim, and
      // async-graphql's own camelCase where nothing was written. The library cannot supply the
      // second any more: it derives a default from the METHOD, and the method wears the
      // `__async_graphql_` prefix.
      let name = wire_field(field.output.name.external(), member);
      // The CONDITION on the face's own function: async-graphql reads the `#[Object]` impl's items,
      // so a field the build removed is a function this impl does not declare and a name the SDL
      // does not carry. The SCHEMA follows the build.
      let gate = self.gate(member);
      quote! {
        #gate
        #[graphql(name = #name)]
        async fn #method(&self) -> <#ty as #crossing>::Output<'_> {
          <#ty as #crossing>::to_graphql_output(Self::#borrow(self))
        }
      }
    });
    let artifacts = self.artifact_fields();
    quote! {
      #[#ag::Object(crate = #shelf, name = #sdl)]
      impl #ty {
        #id

        #[graphql(name = "key")]
        async fn #key_method(&self) -> &#key_output {
          Self::#key_borrow(self)
        }

        #(#fields)*
        #(#artifacts)*
      }
    }
  }

  /// ONE OR TWO FIELDS PER ARTIFACT POSITION — `locate(cover = "media::Cover", …)`, on this
  /// record's own output object.
  ///
  /// The ADDRESS always, and the BYTES where the position's full form asked for them —
  /// `locate(cover(family = "media::Cover", data))`. Both are the same store-mediated class and both
  /// take the request's context; what differs is that one renders and the other reads, which is why
  /// only the second is `.await`ed.
  ///
  /// # The ASK is on this word and the PERMIT is on the family, and neither is the other's default
  ///
  /// A field's presence in the SDL is decided by the expansion that writes the `#[Object]` block —
  /// this one — so the family's own `data` word cannot put a field anywhere; and a field emitted
  /// unconditionally would either publish bytes a family never permitted or force every located
  /// family to write the word. Both roads were measured. What is emitted here is the ASK, and the
  /// projection it spends — `read_artifact::<Family, Self>`, whose `A: ArtifactData` bound — is
  /// `E0277` at the position that asked, carrying a sentence that points both ways.
  ///
  /// # Why the field is written HERE, by the record that named the family
  ///
  /// A blob family's address belongs on the output object of the entity its objects are derived
  /// from, and that object is this expansion's. The family's own macro could not add it: a second
  /// `#[Object]` block on one type is `E0119` three times over — on `ContainerType`, `OutputType`
  /// and `ObjectType` — so there is no *afterwards* for another declaration to write into. The word
  /// therefore lives on the ENTITY, and the OWNING expansion writes the field into the object it
  /// already owns. That is the whole of why `locate(…)` is where it is.
  ///
  /// # Everything it needs is a PROJECTION off the family's path
  ///
  /// This expansion has one token of the family: the path the author wrote. It reads none of the
  /// family's declaration and could not — two derives do not see each other's tokens — so the slot,
  /// the suffix and the store all arrive through
  /// [`ArtifactStore`](crate::model::RecordModel) and its siblings, projected off that path. Each
  /// projection is a TOOTH as well as a fact:
  ///
  /// | the emitted projection | what refuses, and where |
  /// |---|---|
  /// | `<Family as ArtifactStore>::Location` | `E0277` at the path — the family names no store this deployment can reach |
  /// | `ArtifactSuffix<Self>` | `E0277` — the family reads a column, and this object is not the row it reads |
  /// | the KEY, built from this record's own | `E0308` — the family was derived from a DIFFERENT entity |
  ///
  /// The last is the one worth naming out loud: a blob node's `Transformer::Key` is bound to its
  /// UPSTREAM's, so a `locate(…)` naming a family derived from somebody else does not typecheck at
  /// the key argument. Nothing here checks that relationship; the projection is what makes it
  /// checkable.
  ///
  /// # The KEY is rebuilt rather than borrowed
  ///
  /// The object holds `<E>KeyOutput` — the key's columns projected onto the wire — and the store
  /// addresses by `<E>Key`. They are the same columns in the same order and are two types, so the
  /// resolver constructs one from the other through the emitted positional `new`. It costs one clone
  /// per key column per located field, and the alternative — holding the domain key on the wire
  /// object beside its projection — would put a second copy of the address on every row a client
  /// ever reads, whether or not it asked for an artifact.
  ///
  /// # NULLABLE IS THE DEFAULT TRUTH, and `required` is the author's informed promotion
  ///
  /// The ADDRESS is nullable by ARCHITECTURE: an artifact is written by the indexing pipeline
  /// asynchronously after the entity exists, so *not yet generated* is a normal state and an
  /// `Option` is what says so. The `Option` is the STORE's — `ArtifactStore::locate` answers one, and
  /// each store draws its own split between an object that is not there and a store that could not
  /// be asked — so a bare position hands a client exactly what the family answered.
  ///
  /// `locate(cover(family = "…", required))` promotes the field to `BlobLocation!`, with
  /// `data(required)`'s exact semantics one field over: the WALK is the same either way — the door,
  /// the suffix, the render — and what the word changes is the PUBLISHED TYPE, plus the one thing
  /// that type forces, which is what to do with an absence a non-null field cannot carry.
  ///
  /// So the signed field takes the SIGNED WALK: `locate_signed_artifact` converts `None` into a
  /// named field error quoting the word, naming the family and saying which of the two repairs the
  /// reader has — the artifact is late, or the signature was never true here. A resolver answering
  /// `Err` is dropped from the response whatever its type, an `Option` absorbing only a failure
  /// raised INSIDE the value it wraps and never one raised instead of it; that measurement stands
  /// and is what makes the word's ERROR road identical at both spellings. Both roads are executed in
  /// `ingraph/tests/artifact_address_signature.rs` and `ingraph/tests/artifact_absence.rs`.
  ///
  /// # THE WORD MEANS ONE THING AT BOTH STORE-MEDIATED POSITIONS
  ///
  /// The BYTES road answers an `Option` of its own now — `ArtifactData::read` learns an absence for
  /// free, on the way to reading — so this emission mints no `Some` for it and the two fields are
  /// spelled the same way: `read_artifact` at a bare position hands a client the family's own
  /// answer, and `read_signed_artifact` at a signed one converts a `None` into the SAME named field
  /// error the address's signed walk raises. Two roads, one fork, one refusal.
  ///
  /// The two fields are independent: a position may sign for the address, for the bytes, for both or
  /// for neither, and each word promotes only its own field.
  fn artifact_fields(&self) -> Vec<proc_macro2::TokenStream> {
    if self.artifacts.is_empty() {
      return Vec::new();
    }
    let ag = self.framework(&[], "async_graphql");
    let store = self.framework(&["record"], "ArtifactStore");
    let locate = self.framework(&["graphql"], "locate_artifact");
    let signed = self.framework(&["graphql"], "locate_signed_artifact");
    let read = self.framework(&["graphql"], "read_artifact");
    let signed_read = self.framework(&["graphql"], "read_signed_artifact");
    let key_name = &self.key.name;
    let key_borrow = Member::Borrow.name(&format_ident!("key"));
    let columns: Vec<_> = self.key.columns().map(|column| &column.name).collect();
    let ctx = wire_method(&format_ident!("ctx"));
    self
      .artifacts
      .iter()
      .flat_map(|artifact| {
        let family = &artifact.family;
        let method = wire_method(&artifact.name);
        let name = wire_member(&artifact.name);
        let word = artifact.name.to_string();
        // The path is respanned onto the string that wrote it, which is this grammar's standing rule
        // for a referring word: every refusal the projections above can raise — the missing store,
        // the wrong row, the other entity's key — lands where its author can edit it.
        let family = quote_spanned!(family.span()=> #family);
        // Written once and spent by both fields: the two ask the same store about the same object,
        // so a key they could build differently is a pair of fields that can disagree about which
        // one they mean.
        let key = quote! {
          &#key_name::new(#(
            ::core::clone::Clone::clone(&Self::#key_borrow(self).#columns),
          )*)
        };
        // `BlobLocation!` WHERE THE AUTHOR SIGNED FOR IT, and `BlobLocation` where they did not —
        // the ask's own fork one field over, arrived at through the same reasoning and spelled the
        // same way. TWO WALKS rather than one and a wrapper: the store's own `Option` is the answer
        // now, so the bare field hands it straight to a client and the signed one spends the word on
        // it — which is the only place the two roads differ at all.
        let address = if artifact.required {
          quote! {
            #[graphql(name = #name)]
            async fn #method(
              &self,
              #ctx: &#ag::Context<'_>,
            ) -> #ag::Result<<#family as #store>::Location> {
              #signed::<#family, Self>(#ctx, #word, self, #key)
            }
          }
        } else {
          quote! {
            #[graphql(name = #name)]
            async fn #method(
              &self,
              #ctx: &#ag::Context<'_>,
            ) -> #ag::Result<::core::option::Option<<#family as #store>::Location>> {
              #locate::<#family, Self>(#ctx, #word, self, #key)
            }
          }
        };
        let bytes = artifact.data.as_ref().map(|data| {
          let method = wire_method(&format_ident!(
            "{plain}_data",
            plain = RustSafeName::from_ident(&artifact.name).external()
          ));
          // THE DEFAULT IS RESOLVED HERE, and that is the model's own note read from this end: the
          // camelCase a client sees where nothing was written has one home, and it is this one.
          let name = data
            .name()
            .map_or_else(|| format!("{name}Data"), ToOwned::to_owned);
          // `String!` WHERE THE AUTHOR SIGNED FOR IT, and `String` where they did not — the
          // address's own fork one field over, and now arrived at the same way: TWO WALKS rather
          // than one and a wrapper, because the store's own `Option` is the answer on this road too.
          // The bare field hands a client what the family answered, and the signed one spends the
          // word on it. A failed read is dropped from the response whatever the field's type, an
          // `Option` absorbing only a failure raised INSIDE the value it wraps; what the word
          // changes is the published type and what to do with an absence a non-null field cannot
          // carry. Measured beside the address's own word in
          // `ingraph/tests/artifact_address_signature.rs`.
          if data.required() {
            quote! {
              #[graphql(name = #name)]
              async fn #method(
                &self,
                #ctx: &#ag::Context<'_>,
              ) -> #ag::Result<::std::string::String> {
                #signed_read::<#family, Self>(#ctx, #word, self, #key).await
              }
            }
          } else {
            quote! {
              #[graphql(name = #name)]
              async fn #method(
                &self,
                #ctx: &#ag::Context<'_>,
              ) -> #ag::Result<::core::option::Option<::std::string::String>> {
                #read::<#family, Self>(#ctx, #word, self, #key).await
              }
            }
          }
        });
        [Some(address), bytes].into_iter().flatten()
      })
      .collect()
  }

  /// The ADDRESS object's face, and the one wire face here that reads MEMBERS rather than accessors.
  ///
  /// `<E>KeyOutput` is mechanical from the key's columns: no `graphql(…)` word names one, so there is
  /// no layer-2 rename for an accessor to carry and no accessor family was ever emitted for it. The
  /// members are this crate's substrate and this impl lands in the same crate, so reading them is the
  /// substrate read by its own crate — which is the whole of what `pub(crate)` is for.
  ///
  /// A word naming nothing still leaves a NAME to publish, and after the prefix pin this face is
  /// where that is most visible: every method here carries `#[graphql(name = …)]` although no
  /// declaration asked for one. Under the old two-underscore prefix leaving them off would not have
  /// broken the SDL — Inflector eats a leading separator run, so `__reel_id` camelCased to `reelId`
  /// anyway — and under the BACKEND prefix it would: `__async_graphql_reel_id` camelCases to
  /// `asyncGraphqlReelId`. The written name is what makes the prefix invisible on the wire, and the
  /// sweep is what turned that from prudence into the load-bearing half.
  ///
  /// The crossing is the output object's, for the reason the object's own members take it: a key
  /// column may be a `u128`, and an address a client cannot read is an address it cannot resume a
  /// page from.
  ///
  /// It always has at least one field — a key has an id — so the empty-object question the two INPUT
  /// faces answer never arises here.
  fn key_output_face(&self, graphql: &Graphql) -> proc_macro2::TokenStream {
    let ty = graphql.key_output.safe();
    let sdl = published_key(graphql, self);
    let ag = self.framework(&[], "async_graphql");
    let shelf = self.vendored("async_graphql");
    let crossing = self.framework(&["graphql"], "ToGraphqlOutput");
    let columns = self.key.columns().map(|column| {
      let member = &column.name;
      let method = wire_method(member);
      // No `graphql(…)` word reaches a key column, so the name is always the fallback — which after
      // the prefix pin is this emission's to spell rather than the library's to derive.
      let name = wire_member(member);
      let ty = &column.ty;
      quote! {
        #[graphql(name = #name)]
        async fn #method(&self) -> <#ty as #crossing>::Output<'_> {
          <#ty as #crossing>::to_graphql_output(&self.#member)
        }
      }
    });
    quote! {
      #[#ag::Object(crate = #shelf, name = #sdl)]
      impl #ty {
        #(#columns)*
      }
    }
  }

  /// The ADDRESS ARGUMENT's face — `<E>KeyInput` as a PRODUCT input object, over a compound key
  /// alone.
  ///
  /// Nothing for a ROOT, whose address crosses inward as its id and mints no type at all —
  /// `emit::graphql`'s `key_input` carries the ruling and both halves of the fork. The two are
  /// emitted from one predicate ([`Key::compound`](crate::model::Key::compound)), so a face without
  /// a type or a type without a face is not a state this emission can reach.
  ///
  /// # Hand-rolled, for the reason every input face here is
  ///
  /// `#[derive(InputObject)]` is written ON a declaration, the declaration is ungated, and
  /// `#[cfg_attr]` cannot stand in — that predicate asks whether the DECLARING crate has a feature
  /// called `async-graphql`, which is a different manifest and usually no feature at all. So the
  /// registration, the parse and the write-back are written out, exactly as the `@oneOf` faces
  /// beside them already are. What separates this one from those is the flag: `oneof: false`, every
  /// field non-null, because an address is a PRODUCT — a step missing is not a narrower address.
  ///
  /// # The CROSSING is at `parse`, and the refusal is the member's
  ///
  /// Each field's wire type is `<Ty as ToGraphqlInput>::Input` and the value is crossed back the
  /// moment it parses, so a `u128` step arrives as its carrier and a step a client wrote wrong is
  /// refused under THIS member's name rather than as one sentence about the whole address. The
  /// struct holds the declaration's own types, which is what leaves the outer
  /// [`ToGraphqlInput`](../../../ingraph/trait.ToGraphqlInput.html) row infallible.
  ///
  /// # `InputObjectType` and not `OneofObjectType`
  ///
  /// The two marker traits are what async-graphql's own validator reads to decide whether the
  /// exactly-one rule applies. Implementing this one and not that one is the whole of how a product
  /// input says it is not a choice.
  fn key_input_face(&self, graphql: &Graphql) -> proc_macro2::TokenStream {
    if !self.key.compound() {
      return proc_macro2::TokenStream::new();
    }
    let ty = crate::model::default_key_input_name(&self.record);
    // The SDL name is this face's OWN seat where the declaration wrote one, and otherwise the
    // address's base plus `Input` — which is where this face parts from the object beside it: that
    // one publishes `<E>Key` because a client READS addresses far more often than it sends them, and
    // GraphQL keeps input and output types in ONE namespace, so the sending half has to differ by
    // something. See [`published_key_input`] for the resolution and [`key_base`] for why the suffix
    // is the one blessed composition in this grammar.
    //
    // The RUST name does not move, which is the axis law: a rename word moves a FACE.
    let sdl = published_key_input(graphql, self);
    let ag = self.framework(&[], "async_graphql");
    let crossing = self.framework(&["graphql"], "ToGraphqlInput");
    let members: Vec<(&syn::Ident, String, &syn::Type)> = self
      .key
      .columns()
      .map(|column| (&column.name, wire_member(&column.name), &column.ty))
      .collect();
    let entries = members.iter().map(|(_, field, ty)| {
      quote! {
        __ingraph_fields.insert(
          ::std::string::String::from(#field),
          #ag::registry::MetaInputValue {
            name: ::std::string::String::from(#field),
            description: ::core::option::Option::None,
            // NON-NULL: the wire type is written WITHOUT an `Option` around it, which is the whole
            // of how a required input field is spelled at this layer.
            ty: <<#ty as #crossing>::Input as #ag::InputType>::create_type_info(
              __ingraph_registry,
            ),
            deprecation: #ag::registry::Deprecation::NoDeprecated,
            default_value: ::core::option::Option::None,
            visible: ::core::option::Option::None,
            inaccessible: false,
            tags: ::std::vec::Vec::new(),
            is_secret: false,
            directive_invocations: ::std::vec::Vec::new(),
          },
        );
      }
    });
    let reads = members.iter().map(|(member, field, ty)| {
      quote! {
        // A LOOKUP rather than a removal, so the members are read in the KEY's own order whatever
        // order the request wrote them in — a removal walk would make the two orders have to agree.
        //
        // `Option::map` OVER `Option::cloned`: the latter is inherent on BOTH `Option<&T>` and
        // `Option<&mut T>`, so a path call is `E0034` at a span the author cannot edit — the
        // measurement the answer legs already carry.
        let #member = <<#ty as #crossing>::Input as #ag::InputType>::parse(
          ::core::option::Option::map(
            #ag::indexmap::IndexMap::get(&__ingraph_object, #field),
            ::core::clone::Clone::clone,
          ),
        )
        .map_err(#ag::InputValueError::propagate)?;
        let #member = <#ty as #crossing>::cross(#member)
          .map_err(#ag::InputValueError::custom)?;
      }
    });
    let names = members.iter().map(|(member, _, _)| member);
    let writes = members.iter().map(|(member, field, ty)| {
      quote! {
        __ingraph_map.insert(
          #ag::Name::new(#field),
          <<#ty as #crossing>::Input as #ag::InputType>::to_value(
            &<#ty as #crossing>::carry(&self.#member),
          ),
        );
      }
    });
    quote! {
      #[automatically_derived]
      impl #ag::InputType for #ty {
        type RawValueType = Self;

        #[inline]
        fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
          ::std::borrow::Cow::Borrowed(#sdl)
        }

        fn create_type_info(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> ::std::string::String {
          __ingraph_registry.create_input_type::<Self, _>(
            #ag::registry::MetaTypeId::InputObject,
            |__ingraph_registry| #ag::registry::MetaType::InputObject {
              name: ::std::string::String::from(#sdl),
              description: ::core::option::Option::None,
              input_fields: {
                let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
                #(#entries)*
                __ingraph_fields
              },
              visible: ::core::option::Option::None,
              inaccessible: false,
              tags: ::std::vec::Vec::new(),
              rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
              // A PRODUCT: every field is required and all of them are read. The `@oneOf` faces
              // beside this one set the other flag and mean the other thing.
              oneof: false,
              directive_invocations: ::std::vec::Vec::new(),
            },
          )
        }

        fn parse(
          __ingraph_value: ::core::option::Option<#ag::Value>,
        ) -> #ag::InputValueResult<Self> {
          if let ::core::option::Option::Some(#ag::Value::Object(__ingraph_object)) =
            __ingraph_value
          {
            #(#reads)*
            return ::core::result::Result::Ok(Self { #(#names,)* });
          }
          ::core::result::Result::Err(#ag::InputValueError::expected_type(
            ::core::option::Option::unwrap_or_default(__ingraph_value),
          ))
        }

        fn to_value(&self) -> #ag::Value {
          let mut __ingraph_map = #ag::indexmap::IndexMap::new();
          #(#writes)*
          #ag::Value::Object(__ingraph_map)
        }

        #[inline]
        fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
          ::core::option::Option::Some(self)
        }
      }

      #[automatically_derived]
      impl #ag::InputObjectType for #ty {}
    }
  }

  /// The order-by as a `@oneOf` input object: one nullable field per orderable column, exactly one
  /// of them supplied.
  ///
  /// The SHAPE was fixed when the type was declared — an enum of single-value tuple variants, which
  /// is what `OneofObject` takes — and what is written here is that derive's own output, at the one
  /// place a derive could not be attached. `oneof: true` is the one flag that separates this entry
  /// from an ordinary input object's, and it is what makes *exactly one field* the VALIDATOR's rule
  /// rather than a resolver's: a request setting two, or none, is refused before anything runs,
  /// through a literal and through a variable alike.
  ///
  /// A record with no orderable column gets NO face, and the absence is the answer rather than an
  /// omission: an input object with no fields is not a GraphQL type, so a schema naming one would be
  /// invalid. Such a record has no order to write either — the enum is uninhabited — so nothing is
  /// lost that a client could have spelled.
  fn order_by_face(&self, backend: &GraphqlBackend) -> proc_macro2::TokenStream {
    let ordered = self.ordered_columns();
    if !self.orderable() || ordered.is_empty() {
      return proc_macro2::TokenStream::new();
    }
    let name = self.order_by.safe();
    // Through [`wire_type`], which is where the ruled naming rule lives — and the order-by is its
    // IDENTITY reading: the type it publishes is the one the framework already named, `<T>OrderBy`
    // being the schema's own vocabulary rather than a Rust carrier's convention. Routed through it
    // anyway, so the one live wire face spends the rule rather than spelling around it.
    let default = default_order_by_name(&self.record);
    let sdl = wire_type(&self.order_by, &default, &default);
    // The SUBJECT's name is the FILTER's, and taking it from there rather than from the field is the
    // whole of the coherence: an order-by term and a filter field name ONE column at ONE schema
    // position — the input side — so a declaration's `input(rename = …)` has to move both or a
    // client would spell the same column two ways in one document. The OUTPUT position is free to
    // differ, and does: it is a second position, which is why the model carries two faces.
    let terms: Vec<unit::wire::OrderField> = ordered
      .iter()
      .map(|(_, column)| {
        let (_, declared, _) = backend.filter_field(column);
        unit::wire::OrderField {
          field: wire_field(&declared, column.member()),
          variant: column.order_variant(),
          // The WIRE's own narrowing, and the only place it happens: the enum above generates full,
          // so a Rust caller orders by every stored column, and `graphql(skip)` decides which of
          // those terms the SCHEMA registers and parses. Both backends' words are asked — the
          // record-wide one and this backend's — through the one reading that joins them.
          published: self.published(&column.source)
            && !backend.skipped().iter().any(|held| held == &column.source),
          gate: self.gate(&column.source),
        }
      })
      .collect();
    // A withheld term is no field of the input object, so a record whose every orderable column is
    // withheld would publish an object with no fields — which is not a GraphQL type. No face, then:
    // the same refusal the empty-order case one paragraph up makes, at the one word that can now
    // produce it.
    if !terms.iter().any(|term| term.published) {
      return proc_macro2::TokenStream::new();
    }
    unit::wire::order_by_face(
      &unit::wire::InputFace {
        krate: &self.krate,
        name,
        sdl: &sdl,
      },
      &terms,
    )
  }

  /// The FILTER as an ordinary input object: one NULLABLE field per stored column, each carrying
  /// that column's own filter, and any number of them supplied.
  ///
  /// The order-by's twin, one flag apart — `oneof: false`, because a predicate narrows by every
  /// field a client writes where an order term names exactly one column. Both go through
  /// [`Self::input_type_info`], which is what keeps that the only difference.
  ///
  /// # It is emitted where something SPENDS it, and the module note is why
  ///
  /// This face demands `InputType` of every stored column's filter, and those filters name the
  /// DECLARATION's own types. There is no `where` clause that makes such a demand conditional —
  /// trivial bounds are unstable — so the emission is conditional instead, at
  /// [`RecordModel::wire_filters`], which reads the LIST leg's own condition. An input object no
  /// argument names is not in an SDL anyway, so the narrowing costs a schema nothing.
  ///
  /// # A record storing NOTHING gets no face
  ///
  /// An input object with no fields is not a GraphQL type, so a schema naming one would be invalid —
  /// the same refusal the order-by makes one paragraph up. The condition cannot fire while
  /// [`RecordModel::wire_filters`] holds (an ordered column is a stored one), and it is written out
  /// because the face is what would be malformed, not the predicate.
  ///
  /// # `Option<F>` at the field and NOT `Nullable<F>`
  ///
  /// Two different absences, and the type says which. `Option` at this position is *the client
  /// wrote no predicate for this column* — an unwritten field narrows nothing — where
  /// `Nullable<F>` is the column's own NULL state and lives inside `F` for a nullable column,
  /// carrying `isNull`. The struct's member is `Option<F>` for exactly that reason and this face
  /// parses what the member holds.
  fn filter_face(&self, graphql: &Graphql) -> proc_macro2::TokenStream {
    if !self.wire_filters() {
      return proc_macro2::TokenStream::new();
    }
    let rows = graphql.filter_rows(self);
    let relations = graphql.relation_rows(self);
    if rows.is_empty() && relations.is_empty() {
      return proc_macro2::TokenStream::new();
    }
    let name = graphql.filter.safe();
    // Through [`wire_type`] at its IDENTITY reading, as the order-by is: `<T>Filter` is the design's
    // own SDL vocabulary rather than a Rust carrier's convention, so the framework's default name is
    // what a client reads and a declared `filter(rename = "…")` moves it verbatim.
    let default = default_filter_name(&self.record);
    let sdl = wire_type(&graphql.filter, &default, &default);
    // The INPUT position's name, which is the order-by term's too — one column, one input name, so a
    // client never spells the same column two ways in one document.
    let fields: Vec<unit::wire::FilterField> = rows
      .into_iter()
      .map(|row| unit::wire::FilterField {
        field: wire_field(&row.declared, &row.member),
        filter: row.filter,
        gate: self.gate(&row.member),
        member: row.member,
      })
      .collect();
    // The REVERSE relation positions, in the declaration's own order after every column — handed to
    // the face as their own slice because their three legs differ from a column's by the BOX, which
    // the shared emission puts on and takes off.
    let positions: Vec<unit::wire::RelationPosition> = relations
      .into_iter()
      .map(|row| unit::wire::RelationPosition {
        field: wire_member(&row.member),
        member: row.member,
        held: row.held,
      })
      .collect();
    unit::wire::filter_face(
      &unit::wire::InputFace {
        krate: &self.krate,
        name,
        sdl: &sdl,
      },
      &fields,
      &positions,
    )
  }
}