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
//! The FLAGS 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 attribute reach this emitter only exists while the emitter can be
//! driven from a plain model.
//!
//! What the suite watches is the ARITY the kind is named for. A flags column answers with a subset
//! where a vocabulary's answers with one name, and every place this emission departs from
//! [`crate::enumeration`]'s — a type MINTED rather than declared, one storage form rather than two,
//! a cursor carrying the bit pattern rather than a word — is a place where the sister kind's own
//! pin would have passed a wrong emission.

use heck::ToLowerCamelCase as _;
use quote::ToTokens as _;

use super::{BitWidth, FlagBit, FlagsModel};

/// The declaration the whole module is measured against: three bits at the widest width this kind
/// carries, one of them documented and none of them renamed, and two attributes above the type — so
/// the forwarding law always has an ORDER to get wrong rather than a single attribute it cannot.
fn disposition() -> FlagsModel {
  FlagsModel {
    krate: syn::parse_quote!(::ingraph),
    vis: syn::parse_quote!(pub),
    name: ident("Disposition"),
    width: BitWidth::U32,
    bits: vec![
      FlagBit {
        attrs: vec![syn::parse_quote!(#[doc = "The default track for its kind."])],
        ..bit("Default", 0x1)
      },
      bit("Forced", 0x2),
      bit("HearingImpaired", 0x4),
    ],
    attrs: vec![
      syn::parse_quote!(#[doc = "Which roles a track takes."]),
      syn::parse_quote!(#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]),
    ],
    remote: None,
    wire_name: None,
  }
}

/// The same declaration at the NARROWEST width this kind carries.
///
/// Three bits fit in a byte, so nothing about the vocabulary moves and everything about the STORED
/// number does — which is what makes it the control for every width claim.
fn narrow() -> FlagsModel {
  FlagsModel {
    width: BitWidth::U8,
    ..disposition()
  }
}

/// The same declaration reached through a VENDORED framework, as `crate = "…"` would have said.
fn vendored() -> FlagsModel {
  FlagsModel {
    krate: syn::parse_quote!(vendored::ingraph),
    ..disposition()
  }
}

fn bit(name: &str, value: u128) -> FlagBit {
  FlagBit {
    ident: ident(name),
    rename: None,
    upstream: None,
    value,
    attrs: Vec::new(),
  }
}

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

/// The expansion, read back as items.
fn emission(model: &FlagsModel) -> 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.
fn rendered(model: &FlagsModel) -> String {
  prettyplease::unparse(&emission(model))
}

/// The ONE invocation the type is MINTED by.
///
/// A macro call is opaque to `syn`, which is the whole reason this kind's claims are made against
/// its TOKENS: what a `bitflags!` body says is not an item until that crate has read it.
fn minted(file: &syn::File) -> &syn::ItemMacro {
  let mut invocations = file.items.iter().filter_map(|item| match item {
    syn::Item::Macro(item) => Some(item),
    _ => None,
  });
  let minted = invocations.next().expect("the expansion mints a type");
  assert!(invocations.next().is_none(), "one invocation and no other");
  minted
}

/// What the minted type is HANDED — the invocation's tokens, with the spacing removed.
fn declaration(model: &FlagsModel) -> String {
  let file = emission(model);
  minted(&file).mac.tokens.to_string().replace(' ', "")
}

/// Whether a path is one of `ingraph`'s conditional-expansion gates.
fn is_gate(path: &syn::Path) -> bool {
  path
    .segments
    .iter()
    .skip_while(|segment| segment.ident != "__private")
    .nth(1)
    .is_some_and(|segment| segment.ident == "gate")
}

/// Every anonymous const's statements, in emission order — the STORAGE block first, the gated WIRE
/// block second.
fn blocks(file: &syn::File) -> Vec<Vec<syn::Stmt>> {
  file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Const(anonymous) if anonymous.ident == "_" => Some(&anonymous.expr),
      _ => None,
    })
    .map(|block| {
      let syn::Expr::Block(block) = block.as_ref() else {
        panic!("the const's value is a block");
      };
      block.block.stmts.clone()
    })
    .collect()
}

/// The STORAGE const's statements — the rows and the gates they ride.
fn body(file: &syn::File) -> Vec<syn::Stmt> {
  blocks(file).swap_remove(0)
}

/// The WIRE const's statements — one gate, holding both crossings.
fn wire(file: &syn::File) -> Vec<syn::Stmt> {
  let mut blocks = blocks(file);
  assert_eq!(blocks.len(), 2, "the expansion is two anonymous consts");
  blocks.swap_remove(1)
}

/// The STORAGE const, tight — for a claim about what did NOT reach it.
fn ungated(model: &FlagsModel) -> String {
  let held = body(&emission(model));
  quote::quote!(#(#held)*).to_string().replace(' ', "")
}

/// Every trait the UNGATED part of the expansion implements, named by its last segment.
fn ungated_traits(model: &FlagsModel) -> Vec<String> {
  body(&emission(model))
    .iter()
    .filter_map(|stmt| match stmt {
      syn::Stmt::Item(syn::Item::Impl(item)) => item.trait_.as_ref(),
      _ => None,
    })
    .map(|(path, _)| tight(path))
    .collect()
}

/// Every GATED group AS WRITTEN: which gate, and the traits it holds.
///
/// Read off the wrapper rather than off its contents, because the question is what a build WITHOUT
/// that backend sees — which the gate decides and the items inside cannot.
fn gated(model: &FlagsModel) -> Vec<(String, Vec<String>)> {
  body(&emission(model))
    .iter()
    .filter_map(|stmt| match stmt {
      syn::Stmt::Macro(gate) if is_gate(&gate.mac.path) => Some(&gate.mac),
      _ => None,
    })
    .map(|gate| {
      let held: syn::File = syn::parse2(gate.tokens.clone()).expect("a gate holds parsable items");
      let traits = held
        .items
        .iter()
        .filter_map(|item| match item {
          syn::Item::Impl(item) => item.trait_.as_ref().map(|(path, _)| tight(path)),
          _ => None,
        })
        .collect();
      (tight(&gate.path), traits)
    })
    .collect()
}

/// One gate's whole body, tight — for a claim about the primitive a backend binds.
fn inside(model: &FlagsModel, gate: &str) -> String {
  body(&emission(model))
    .iter()
    .find_map(|stmt| match stmt {
      syn::Stmt::Macro(item) if is_gate(&item.mac.path) && tight(&item.mac.path) == gate => {
        Some(item.mac.tokens.to_string().replace(' ', ""))
      }
      _ => None,
    })
    .unwrap_or_else(|| panic!("no `{gate}` group"))
}

/// Every type the expansion declares into the DECLARING scope, named as it names them.
fn declared_structs(file: &syn::File) -> Vec<String> {
  file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Struct(item) => Some(item.ident.to_string()),
      _ => None,
    })
    .collect()
}

/// Every `const` the minted body declares, in declaration order.
///
/// This is the bit WORD list: the same string `bitflags::parser::to_writer` spells and the wire's
/// name list carries, which is why one reading of it answers for all three.
fn constants(model: &FlagsModel) -> Vec<String> {
  let file = emission(model);
  flat_tokens(minted(&file).mac.tokens.clone())
    .windows(2)
    .filter_map(|pair| match pair {
      [
        proc_macro2::TokenTree::Ident(keyword),
        proc_macro2::TokenTree::Ident(name),
      ] if keyword == "const" => Some(name.to_string()),
      _ => None,
    })
    .collect()
}

/// The wire face's `FIELDS`, in emission order.
fn fields(model: &FlagsModel) -> Vec<String> {
  let list = body(&emission(model))
    .iter()
    .filter_map(|stmt| match stmt {
      syn::Stmt::Item(syn::Item::Impl(item)) => Some(item.items.clone()),
      _ => None,
    })
    .flatten()
    .find_map(|item| match item {
      syn::ImplItem::Const(item) if item.ident == "FIELDS" => Some(item.expr),
      _ => None,
    })
    .expect("the wire face declares its field list");

  let syn::Expr::Reference(list) = list else {
    panic!("the field list is a slice");
  };
  let syn::Expr::Array(list) = *list.expr else {
    panic!("the field list is an array behind that slice");
  };
  list
    .elems
    .iter()
    .map(|field| match field {
      syn::Expr::Lit(syn::ExprLit {
        lit: syn::Lit::Str(word),
        ..
      }) => word.value(),
      other => panic!("a field is a string literal: {}", other.to_token_stream()),
    })
    .collect()
}

/// A path as it would be written, with the token spacing removed.
fn tight(path: &syn::Path) -> String {
  path
    .segments
    .last()
    .expect("a path has a last segment")
    .ident
    .to_string()
}

/// **The expansion MINTS its type and declares none of its own.**
///
/// The declaration face is an `enum` and the expansion is a `struct`, so what an author wrote is
/// gone by the time rustc has an item to have an opinion about — and the type that replaces it
/// comes out of `bitflags!` rather than out of this emitter. There is nothing else to name: a
/// vocabulary declares its refusal type beside itself because a caller writes it in a signature,
/// and a flags set's two failures are an `Option` and a `BoxDynError` that need no name at all.
///
/// Three items, therefore, and the shape of them is the claim: one invocation reached through the
/// shelf, and the two anonymous consts every row is scoped inside.
#[test]
fn the_expansion_mints_one_bitflags_type_and_declares_nothing_itself() {
  let file = emission(&disposition());

  assert_eq!(
    minted(&file)
      .mac
      .path
      .to_token_stream()
      .to_string()
      .replace(' ', ""),
    "::ingraph::__private::bitflags::bitflags"
  );
  assert!(
    declared_structs(&file).is_empty(),
    "{:?}",
    declared_structs(&file)
  );
  assert_eq!(
    file.items.len(),
    3,
    "the invocation, the storage block and the gated wire block"
  );
}

/// **What an author wrote about their type stays true of the type the door mints**, in the order
/// they wrote it.
///
/// A rewriting attribute is the one place a declaration's own attributes can be silently dropped —
/// the manifest they were written above does not survive — so the forwarding is the law that makes
/// `#[derive(…)]` above a flags declaration mean what it says. Order is half of it: attribute
/// expansion is top-down, and two attributes that swapped would be two derives expanding against
/// each other's output.
#[test]
fn the_declarations_own_attributes_ride_in_front_of_the_minted_type() {
  let written = declaration(&disposition());
  let doc = written.find("#[doc=").expect("the declaration's own doc");
  let derive = written
    .find("#[derive(")
    .expect("the declaration's own derive");
  let minted_type = written
    .find("pubstructDisposition")
    .expect("the minted type");

  assert!(doc < derive, "as written: {written}");
  assert!(derive < minted_type, "in front of the type: {written}");

  let mut reversed = disposition();
  reversed.attrs.reverse();
  let reversed = declaration(&reversed);
  assert!(
    reversed.find("#[derive(") < reversed.find("#[doc="),
    "the order is the declaration's and not a sort: {reversed}"
  );
}

/// **The door FORWARDS attributes and invents none.**
///
/// No derive is added for the author, and the reason is a collision: a `Copy` this door injected
/// would be a duplicate wherever an author wrote one, at a span the declaration cannot edit. The
/// bound that actually needs it says so instead — `FlagsValue: … + Copy + Send + Sync` reports
/// `E0277` naming the trait at the type, which is a sentence about the declaration rather than
/// about the expansion.
#[test]
fn the_door_forwards_attributes_and_invents_none() {
  let mut model = disposition();
  model.attrs.clear();
  model.bits[0].attrs.clear();

  let written = declaration(&model);
  assert!(written.starts_with("pubstructDisposition"), "{written}");
  assert!(!written.contains("#["), "nothing was added: {written}");
}

/// **A bit is a SUFFIXED HEX literal at the declared width**, and the backing integer is that same
/// width.
///
/// Hex because that is how a bit is written and a decimal `4` says nothing about which one it is;
/// suffixed because the `const` would otherwise take an INFERRED type, and a literal whose width is
/// inferred is a literal that changes meaning when the declaration's width does. The two move
/// together here — `flags(u8)` restates the backing type and every literal on it — which is what
/// keeps a widened declaration from carrying values typed at the old width.
#[test]
fn a_bit_is_a_suffixed_hex_literal_at_the_declared_width() {
  let written = declaration(&disposition());
  assert!(
    written.contains("Disposition:::core::primitive::u32{"),
    "{written}"
  );
  assert!(written.contains("constDEFAULT=0x1u32;"), "{written}");
  assert!(written.contains("constFORCED=0x2u32;"), "{written}");
  assert!(
    written.contains("constHEARING_IMPAIRED=0x4u32;"),
    "{written}"
  );

  let narrowed = declaration(&narrow());
  assert!(
    narrowed.contains("Disposition:::core::primitive::u8{"),
    "{narrowed}"
  );
  assert!(
    narrowed.contains("constHEARING_IMPAIRED=0x4u8;"),
    "{narrowed}"
  );
}

/// **A bit's own attributes reach its `const`**, which is what carries a doc comment into the
/// expansion.
///
/// The manifest's variant is where an author documents a flag and the `const` is the only thing
/// that survives, so an emission that dropped the attributes would put every flags set in a schema
/// under an undocumented name — and rustdoc would report nothing, there being no item left to be
/// missing a doc.
///
/// The undocumented bits are the other half: nothing is invented for a bit that wrote nothing.
#[test]
fn a_bits_own_attributes_reach_its_const() {
  let written = declaration(&disposition());
  let body = written
    .split_once('{')
    .expect("the minted type has a body")
    .1;

  assert!(
    body.starts_with("#[doc="),
    "the bit's own doc leads it: {written}"
  );
  assert!(body.contains("]constDEFAULT=0x1u32;"), "{written}");
  assert!(
    body.ends_with("constFORCED=0x2u32;constHEARING_IMPAIRED=0x4u32;}"),
    "a bit that wrote nothing carries nothing: {written}"
  );
}

/// **The const names are the identifiers SHOUTED.**
///
/// `SCREAMING_SNAKE_CASE` is what an associated const is spelled with everywhere in the ecosystem,
/// and the casing is free to be a Rust convention here because a flags column stores no word for a
/// casing rule to rewrite. It buys one thing beyond looking right: the const's name IS the token
/// `bitflags::parser::to_writer` prints, so the strict text form can be that function rather than a
/// renderer written here that could come to disagree with it.
#[test]
fn the_const_names_are_the_identifiers_shouted() {
  assert_eq!(
    constants(&disposition()),
    ["DEFAULT", "FORCED", "HEARING_IMPAIRED"]
  );
}

/// **A `rename` moves the const, the word and the field TOGETHER.**
///
/// They are three readings of one declaration rather than three declarations — the const's name is
/// the text form's token, and the field is that token under GraphQL's own casing — so a rename that
/// moved one and not the others would mint a type whose stored text and whose schema disagreed
/// about what a bit is called. The old spellings leave the expansion entirely, which is the other
/// half: a rename MOVES the word rather than adding a second one.
#[test]
fn a_rename_moves_the_const_the_word_and_the_field_together() {
  let mut model = disposition();
  model.bits[2].rename = Some("HARD_OF_HEARING".to_owned());

  assert_eq!(model.bits[2].word(), "HARD_OF_HEARING");
  assert_eq!(model.bits[2].field(), "hardOfHearing");
  assert_eq!(constants(&model), ["DEFAULT", "FORCED", "HARD_OF_HEARING"]);
  assert_eq!(fields(&model), ["default", "forced", "hardOfHearing"]);

  let rendered = rendered(&model);
  assert!(!rendered.contains("HEARING_IMPAIRED"), "{rendered}");
  assert!(!rendered.contains("hearingImpaired"), "{rendered}");
}

/// **The minted type takes the DECLARATION's visibility.**
///
/// The type is not the author's to write, so its visibility is the one thing about the manifest
/// that decides whether the expansion escapes the module — and a `pub` invented here would publish
/// a crate-private vocabulary through every signature that names it.
#[test]
fn the_minted_type_takes_the_declarations_visibility() {
  let mut model = disposition();
  model.vis = syn::parse_quote!(pub(crate));

  let written = declaration(&model);
  assert!(written.contains("pub(crate)structDisposition"), "{written}");
}

/// **The wire face carries the type's OWN name and one field per bit.**
///
/// Two constants and no third, because they are the whole of what the generic faces need that
/// `bitflags::Flags` does not already carry: the SDL name, which is the Rust one unless
/// `graphql(rename = "…")` moved it, and the camelCase field a selection set writes — GraphQL's
/// convention rather than this crate's, and the one casing the const's own name is not already in.
#[test]
fn the_wire_face_carries_the_types_own_name_and_a_field_per_bit() {
  let rendered = rendered(&disposition());

  assert!(
    rendered.contains(r#"const GRAPHQL_NAME: &'static ::core::primitive::str = "Disposition";"#),
    "{rendered}"
  );
  assert_eq!(
    fields(&disposition()),
    ["default", "forced", "hearingImpaired"]
  );
}

/// **A RAW name is published without its escape.**
///
/// `r#` is Rust's way of spelling a word that collides with its grammar and no part of the name, so
/// the schema publishes `type` — while the minted type keeps the escape, that being the only way
/// the identifier can be written at all.
#[test]
fn a_raw_name_is_published_without_its_escape() {
  let mut model = disposition();
  model.name = syn::Ident::new_raw("type", proc_macro2::Span::call_site());

  assert_eq!(model.sdl_name(), "type");
  let rendered = rendered(&model);
  assert!(
    rendered.contains(r#"const GRAPHQL_NAME: &'static ::core::primitive::str = "type";"#),
    "{rendered}"
  );
  assert!(declaration(&model).contains("structr#type"), "{rendered}");
}

/// **The field list is PARALLEL to the bit list**, and it is parallel structurally rather than by
/// convention.
///
/// `FlagsValue::FIELDS` is a second list beside `bitflags::Flags::FLAGS` because the first of the
/// two lives in the vendored crate and this emitter cannot add a column to it. The join is by
/// POSITION, and `bits` zips them — so two lists that disagreed in length would silently lose the
/// tail, and two that disagreed in order would answer every selection with the wrong bit. Both come
/// off one loop over one declaration, which is what this pins: same length, same order, and the
/// i-th field is the i-th const under the one casing that separates them.
#[test]
fn the_field_list_is_parallel_to_the_bit_list() {
  let mut model = disposition();
  model.bits[1].rename = Some("FORCED_SUBTITLES".to_owned());

  let constants = constants(&model);
  let fields = fields(&model);

  assert_eq!(constants.len(), model.bits.len(), "{constants:?}");
  assert_eq!(fields.len(), constants.len(), "{fields:?}");
  for (constant, field) in constants.iter().zip(&fields) {
    assert_eq!(&constant.to_lower_camel_case(), field);
  }
}

/// **The reading rows are the ungated ones, and they are what a column of this type is READ
/// through.**
///
/// The wire face carries the bit table every generic seat reads; the filter and the two inferences
/// say how a column of the type — and a COLLECTION of it — is read without a word on the field; the
/// cursor codec is what the storability audit demands of every persisted column, and it is ungated
/// with them because a cursor minted against one dialect is handed back to a process talking to
/// another. `ColumnKind` joins them one step further out: a flags set is ONE column in every
/// dialect, so its width has no backend to vary with and no gate to sit behind.
///
/// Nothing else escapes a gate, and `#[automatically_derived]` is the only attribute any of them
/// carries — a row this emitter wrote is not a row anybody has to document.
#[test]
fn the_reading_rows_are_the_ungated_ones() {
  assert_eq!(
    ungated_traits(&disposition()),
    [
      "FlagsValue",
      "FlagsFilterMarker",
      "DefaultMarker",
      "DefaultVecMarker",
      "CursorValue",
      "ColumnKind",
      // The SAMENESS row beside the width row, ungated with it.
      "ColumnEq"
    ]
  );

  for stmt in body(&emission(&disposition())) {
    let syn::Stmt::Item(syn::Item::Impl(item)) = stmt else {
      continue;
    };
    let attrs: Vec<String> = item
      .attrs
      .iter()
      .map(|attr| attr.to_token_stream().to_string().replace(' ', ""))
      .collect();
    assert_eq!(attrs, ["#[automatically_derived]"]);
  }
}

/// **Each SQL dialect gets ONE storage group, and MongoDB gets none.**
///
/// Storage is the backing integer in every face — there is no `text`/`integer` fork here, because
/// the mask questions are ARITHMETIC on the bit pattern and a text column cannot answer `hasAll` at
/// all — so what varies per dialect is only the primitive it binds, and that is exactly four rows
/// behind exactly one gate each.
///
/// The READ sits behind the FAMILY's gate instead, and the position is the claim: what varies per
/// dialect is the `Decode` it delegates to, which it states as an obligation, so one impl serves
/// every dialect below it. MongoDB's group is absent rather than empty — `MongoFlagsComparison` is
/// written and its three mask words are the server's own; what is missing is a lane in this
/// workspace that could compile the carrier.
#[test]
fn each_sql_dialect_gets_one_storage_group_and_mongodb_gets_none() {
  let rows = || {
    vec![
      // The DECLARED WORD leads: a flags column is declared at the width this dialect STORES the
      // bits at, which is the same table the three crossings beside it read.
      "StoredAs".to_owned(),
      "Type".to_owned(),
      "Encode".to_owned(),
      "Decode".to_owned(),
      "Carrier".to_owned(),
    ]
  };

  assert_eq!(
    gated(&disposition()),
    vec![
      ("if_sqlx".to_owned(), vec!["Assemble".to_owned()]),
      ("if_sqlite".to_owned(), rows()),
      ("if_postgres".to_owned(), rows()),
      ("if_mysql".to_owned(), rows()),
    ]
  );
}

/// **A `u32` set binds as `i64` on Postgres and as itself everywhere else.**
///
/// The widening is the house carrier table's, spent unchanged: Postgres has no unsigned type and no
/// `TINYINT`, so `u8` binds as `i16` and `u32` as `i64` exactly as an enum discriminant of the same
/// width does. A second widening rule here would be a second answer to a question already settled,
/// and a flags column and an enum column storing the same width ARE the same column.
///
/// Both directions are pinned, because they widen for different reasons. The bind casts UP and is
/// exact by construction — every target in that table holds its source's whole range. The read
/// narrows back to the DECLARED width first and then asks `from_bits`, so a dialect that handed
/// back a number outside the declared width and a number inside it carrying an undeclared bit are
/// both refused rather than truncated into a value the declaration never wrote.
#[test]
fn a_u32_set_binds_as_i64_on_postgres_and_as_itself_elsewhere() {
  let postgres = inside(&disposition(), "if_postgres");
  assert!(
    postgres.contains("letstored=<::core::primitive::i64as"),
    "the column is READ at the dialect's own width: {postgres}"
  );
  assert!(
    postgres.contains("qb.push_bind(Disposition::bits(self)as::core::primitive::i64);"),
    "{postgres}"
  );
  assert!(
    postgres.contains("<::core::primitive::u32as::core::convert::TryFrom<::core::primitive::i64>>"),
    "the way back narrows to the declared width: {postgres}"
  );
  assert!(
    !postgres.contains("as::core::primitive::u32"),
    "nothing binds unsigned on Postgres: {postgres}"
  );

  for gate in ["if_sqlite", "if_mysql"] {
    let held = inside(&disposition(), gate);
    assert!(
      held.contains("qb.push_bind(Disposition::bits(self)as::core::primitive::u32);"),
      "{gate}: {held}"
    );
    assert!(!held.contains("i64"), "{gate}: {held}");
  }

  let widened = inside(&narrow(), "if_postgres");
  assert!(
    widened.contains("qb.push_bind(Disposition::bits(self)as::core::primitive::i16);"),
    "the table's own widening and not a constant: {widened}"
  );
  assert!(!inside(&narrow(), "if_sqlite").contains("i16"));
}

/// **The cursor writes the BIT PATTERN, big-endian, at the declared width.**
///
/// A cursor is minted by one process and handed back to another that may be talking to a different
/// dialect, so its codec belongs to the TYPE and cannot be per-backend. For a vocabulary that
/// forced a choice of canonical form, its stored form varying by face; a flags set stores the bit
/// pattern in every face, so the pattern IS the type's own form and there is nothing to choose.
///
/// Big-endian is this crate's byte order for every durable number, and the width is CHECKED coming
/// back twice over: a client's bytes are a client's, so four of them are not a `u32` unless they are
/// exactly four, and `from_bits` refuses the value unless every bit of it was declared.
#[test]
fn the_cursor_writes_the_bit_pattern_big_endian_at_the_declared_width() {
  let wide = ungated(&disposition());
  assert!(
    wide.contains("::core::primitive::u32::to_be_bytes(Disposition::bits(self),)"),
    "{wide}"
  );
  assert!(wide.contains("[::core::primitive::u8;4usize]"), "{wide}");
  assert!(
    wide.contains("Disposition::from_bits(::core::primitive::u32::from_be_bytes(fixed))"),
    "{wide}"
  );

  let narrowed = ungated(&narrow());
  assert!(
    narrowed.contains("::core::primitive::u8::to_be_bytes(Disposition::bits(self),)"),
    "{narrowed}"
  );
  assert!(
    narrowed.contains("[::core::primitive::u8;1usize]"),
    "{narrowed}"
  );
}

/// **The two CROSSING rows are one gated block, and they are the whole of what this declaration
/// owes the wire.**
///
/// A vocabulary emits its `EnumType`, `InputType` and `OutputType` here, because a GraphQL enum's
/// values are the declaration's own and only the declaring crate can write them. A flags type owes
/// none of the three: both of its seats are generic in `ingraph` over `FlagsValue` and read the bit
/// table at runtime, so what is left is saying WHICH seat each direction takes.
///
/// The two seats are DIFFERENT types, where a vocabulary crosses as itself in both directions. That
/// asymmetry is the kind's: a flags value has a dozen readings worth publishing and one worth
/// accepting, so the output is an object and the input is a scalar — and an object and a scalar
/// under one name is a registry collision.
///
/// Nothing leaks past the binding gate, which is the block's reason for existing: a build of
/// `ingraph` without `async-graphql` expands this declaration's schema surface to nothing while
/// keeping every storage row it had.
#[test]
fn the_two_crossing_rows_are_one_gated_block() {
  let emitted = emission(&disposition());
  let wire = wire(&emitted);

  assert_eq!(wire.len(), 1, "the wire block is one statement: the gate");
  let syn::Stmt::Macro(gate) = &wire[0] else {
    panic!("the wire block's statement is a gate invocation");
  };
  assert!(is_gate(&gate.mac.path), "{}", tight(&gate.mac.path));
  assert_eq!(tight(&gate.mac.path), "if_async_graphql");

  let held: syn::File = syn::parse2(gate.mac.tokens.clone()).expect("a gate holds parsable items");
  assert_eq!(
    held
      .items
      .iter()
      .filter_map(|item| match item {
        syn::Item::Impl(item) => item.trait_.as_ref().map(|(path, _)| tight(path)),
        _ => None,
      })
      .collect::<Vec<_>>(),
    ["ToGraphqlOutput", "ToGraphqlInput"]
  );

  let seats = gate.mac.tokens.to_string().replace(' ', "");
  assert!(
    seats.contains("typeOutput<'__ingraph>=::ingraph::__private::graphql::FlagsView<Self>;"),
    "{seats}"
  );
  assert!(
    seats.contains("typeInput=::ingraph::__private::graphql::FlagsInput<Self>;"),
    "{seats}"
  );

  let storage = ungated(&disposition());
  for name in [
    "ToGraphqlOutput",
    "ToGraphqlInput",
    "FlagsView",
    "FlagsInput",
  ] {
    assert!(
      !storage.contains(name),
      "{name} escaped the gate: {storage}"
    );
  }
}

/// **Every framework path goes through `__private`**, and through a MODULE beneath it.
///
/// The shelf is what emitted code is allowed to depend on, so the framework can move an item
/// without regenerating anyone's expansion. `crate::tests` states the rule for the record's
/// emission and `enumeration::tests` for the vocabulary's; a third emitter is a third place it can
/// be broken — and this one has a path the others do not, the vendored `bitflags` the type is
/// minted by.
///
/// The control is the second half, and it is what keeps the first from being an answer about
/// nothing: a root the emission names OUTSIDE the shelf — `::core::primitive::u32` reaches every
/// row — is reported, so an empty answer above is a scan that looked and found nothing rather than
/// a scan that never looked.
#[test]
fn every_framework_path_goes_through_a_private_module() {
  for model in [disposition(), vendored()] {
    assert!(
      ill_formed_shelf_paths(&model).is_empty(),
      "{:?}",
      ill_formed_shelf_paths(&model)
    );
  }

  let mut elsewhere = disposition();
  elsewhere.krate = syn::parse_quote!(core);
  assert!(!ill_formed_shelf_paths(&elsewhere).is_empty());
}

/// Every place the emission names the framework crate and does NOT continue
/// `::__private::<module…>::<item>`.
fn ill_formed_shelf_paths(model: &FlagsModel) -> Vec<String> {
  let root = model
    .krate
    .segments
    .last()
    .expect("a crate path has a last segment")
    .ident
    .to_string();
  let tokens = flat_tokens(model.emit());

  let colon = |at: usize| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ':');
  let ident = |at: usize| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Ident(_)));
  let named = |at: usize, name: &str| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Ident(id)) if id == name);
  // `#root :: __private`, then `:: <ident>` at least twice — the last is the ITEM and what comes
  // before it is the module path it lives in.
  let well_formed = |at: usize| {
    if !(colon(at + 1) && colon(at + 2) && named(at + 3, "__private")) {
      return false;
    }
    let mut segments = 0;
    let mut cursor = at + 3;
    while colon(cursor + 1) && colon(cursor + 2) && ident(cursor + 3) {
      segments += 1;
      cursor += 3;
    }
    segments >= 2
  };

  (0..tokens.len())
    .filter(|at| named(*at, &root))
    .filter(|at| !well_formed(*at))
    .map(|at| {
      tokens[at..(at + 10).min(tokens.len())]
        .iter()
        .map(ToString::to_string)
        .collect()
    })
    .collect()
}

/// Every token in the stream, groups flattened, so a path spanning a group boundary is still one
/// run of tokens to scan.
fn flat_tokens(stream: proc_macro2::TokenStream) -> Vec<proc_macro2::TokenTree> {
  stream
    .into_iter()
    .flat_map(|token| match token {
      proc_macro2::TokenTree::Group(group) => flat_tokens(group.stream()),
      other => vec![other],
    })
    .collect()
}

/// **The shelf follows a declared `crate = "…"`**, and the vendored `bitflags` follows it too.
///
/// A crate that re-exports `ingraph` under its own name is the case the knob exists for, and an
/// emission that reached `::ingraph` anyway would compile only where that name happens to be in the
/// dependency graph. The type this kind is MINTED by is reached the same way as every trait it
/// implements, which is what keeps one answer to *where does the framework live* rather than two.
#[test]
fn the_shelf_follows_a_declared_crate_path() {
  let rendered = rendered(&vendored());

  assert!(
    rendered.contains("vendored::ingraph::__private::bitflags::bitflags!"),
    "{rendered}"
  );
  assert!(
    rendered.contains("impl vendored::ingraph::__private::flags::FlagsValue for Disposition"),
    "{rendered}"
  );
  assert_eq!(
    rendered.matches("vendored::ingraph::__private").count(),
    rendered.matches("::ingraph::__private").count(),
    "no shelf path is rooted anywhere else: {rendered}"
  );
}