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

use std::collections::BTreeMap;

use quote::ToTokens as _;

use super::{EnumModel, EnumVariant, IntegerWidth, Namespace, StorageForm};

/// The vocabulary the whole module is measured against: three variants, one of them carrying a
/// discriminant the declaration wrote, so the integer form always has something to get wrong.
fn codec() -> EnumModel {
  EnumModel {
    krate: syn::parse_quote!(::ingraph),
    vis: syn::parse_quote!(pub),
    name: ident("Codec"),
    width: None,
    variants: vec![variant("H264"), variant("Vp9"), variant("Tape")],
    forms: BTreeMap::new(),
    wire_name: None,
    error: None,
    remote: None,
  }
}

fn variant(name: &str) -> EnumVariant {
  EnumVariant {
    ident: ident(name),
    rename: None,
    names: BTreeMap::new(),
    upstream: None,
    escape: None,
    carrier: None,
  }
}

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

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

/// 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, the face and the parsing.
fn body(file: &syn::File) -> Vec<syn::Stmt> {
  blocks(file).swap_remove(0)
}

/// The WIRE const's statements — one gate, holding the whole schema face.
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)
}

/// Every trait the UNGATED part of the expansion implements, named by its last segment.
fn ungated_traits(model: &EnumModel) -> 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: &EnumModel) -> 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();
      (
        gate
          .path
          .segments
          .last()
          .expect("a path has a last segment")
          .ident
          .to_string(),
        traits,
      )
    })
    .collect()
}

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

/// The method face's item names, in emission order.
fn methods(model: &EnumModel) -> Vec<String> {
  body(&emission(model))
    .iter()
    .filter_map(|stmt| match stmt {
      syn::Stmt::Item(syn::Item::Impl(item)) if item.trait_.is_none() => Some(&item.items),
      _ => None,
    })
    .flatten()
    .filter_map(|item| match item {
      syn::ImplItem::Fn(item) => Some(item.sig.ident.to_string()),
      syn::ImplItem::Const(item) => Some(item.ident.to_string()),
      _ => None,
    })
    .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 declares its REFUSAL type and nothing else.**
///
/// A vocabulary is a value somebody else already declared, so there is nothing here to name — except
/// the one type a caller has to be able to spell, which is what a failed parse hands back. The
/// impls are scoped where they can collide with nothing the declaring module wrote.
#[test]
fn the_expansion_declares_only_the_refusal_a_parse_answers_with() {
  let file = emission(&codec());

  assert_eq!(
    declared_structs(&file),
    ["CodecParseError"],
    "{:?}",
    file.to_token_stream()
  );
  assert_eq!(
    file
      .items
      .iter()
      .filter(|item| matches!(item, syn::Item::Const(_)))
      .count(),
    2,
    "the storage block and the gated wire block"
  );
}

/// 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()
}

/// **A DECLARED name is the one the expansion emits, everywhere the type is named.**
///
/// The struct it declares, and both signatures a caller reads it out of — `FromStr::Err` and the
/// text face's `TryFrom::Error` — because a rename that moved the declaration and not the
/// signatures would be a type nobody could name. The default is absent from the whole emission,
/// which is the other half: the rename MOVES the type rather than adding a second spelling of it.
#[test]
fn the_declared_name_is_what_the_whole_expansion_calls_the_refusal() {
  let mut model = codec();
  model.forms.insert(Namespace::Sqlite, StorageForm::Text);
  model.error = Some(ident("NoSuchCodec"));

  assert_eq!(model.error(), "NoSuchCodec");
  assert_eq!(declared_structs(&emission(&model)), ["NoSuchCodec"]);

  let rendered = rendered(&model);
  assert!(rendered.contains("type Err = NoSuchCodec;"), "{rendered}");
  assert!(rendered.contains("type Error = NoSuchCodec;"), "{rendered}");
  assert!(!rendered.contains("CodecParseError"), "{rendered}");
}

/// **A rename moves the TYPE and not the sentence.**
///
/// What failed is a parse into the vocabulary, so the message names the vocabulary — which is also
/// what keeps a declaration that renames the type from silently rewording every refusal its users
/// already match on.
#[test]
fn a_renamed_refusal_still_names_the_vocabulary_in_its_message() {
  const SENTENCE: &str = r#""`Codec`: no variant answers to this name""#;

  assert!(rendered(&codec()).contains(SENTENCE));
  let mut model = codec();
  model.error = Some(ident("NoSuchCodec"));
  assert!(rendered(&model).contains(SENTENCE), "{}", rendered(&model));
}

/// **A declaration that says nothing is stored as a discriminant in every compiled-in backend.**
///
/// Storage is machine-facing, so silence is not "unstored" — it is the default form, and the rows
/// arrive for each SQL backend behind that backend's gate.
///
/// The READ is the one row 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 the rows below cover. Behind the per-dialect gates it would arrive twice in
/// a build with two of them; behind none it would name a trait a build without sqlx has not got.
#[test]
fn a_declaration_that_says_nothing_stores_the_discriminant_everywhere() {
  let model = codec();

  assert_eq!(
    gated(&model),
    vec![
      ("if_sqlx".to_owned(), vec!["Assemble".to_owned()]),
      (
        "if_sqlite".to_owned(),
        vec![
          "Type".to_owned(),
          "Encode".to_owned(),
          "Decode".to_owned(),
          // The DECLARED WORD: the stored form's own, so a vocabulary that stores an integer is
          // declared at that width and one that stores text at the dialect's text word.
          "StoredAs".to_owned(),
          "Carrier".to_owned()
        ]
      ),
      (
        "if_postgres".to_owned(),
        vec![
          "Type".to_owned(),
          "Encode".to_owned(),
          "Decode".to_owned(),
          // The DECLARED WORD: the stored form's own, so a vocabulary that stores an integer is
          // declared at that width and one that stores text at the dialect's text word.
          "StoredAs".to_owned(),
          "Carrier".to_owned()
        ]
      ),
      (
        "if_mysql".to_owned(),
        vec![
          "Type".to_owned(),
          "Encode".to_owned(),
          "Decode".to_owned(),
          // The DECLARED WORD: the stored form's own, so a vocabulary that stores an integer is
          // declared at that width and one that stores text at the dialect's text word.
          "StoredAs".to_owned(),
          "Carrier".to_owned()
        ]
      ),
    ]
  );
  for gate in ["if_sqlite", "if_postgres", "if_mysql"] {
    assert!(inside(&model, gate).contains("i64"), "{gate}");
  }
}

/// **The reading rows are ungated, and they are what a column of this type is READ through.**
///
/// The filter and the two inferences say how a column of the type — and a COLLECTION of it — is
/// read; the cursor codec is what the storability audit demands of every persisted column, since a
/// page resumes by binding the last row's values back — 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 for the same kind of reason one step further out: a declared enum is ONE column as text and
/// one as an integer, so its width has no backend to vary with and no gate to sit behind.
///
/// `DefaultVecMarker` is the row [`the_vec_reading_serves_both_wire_positions`] is about: it is what
/// every framework-registered type takes from `to_filter!`, and a declared vocabulary had none.
///
/// `DelegatesId` is ungated for the strongest version of the same reason: it is what admits this
/// vocabulary to the sealed id set, and what a KEY may be is not a backend's question — a
/// declaration that stores nothing at all still has an aggregate group column and a `#[ingraph(id)]`
/// available to it.
#[test]
fn the_reading_rows_and_the_parsing_face_are_ungated() {
  assert_eq!(
    ungated_traits(&codec()),
    [
      "EnumFilterMarker",
      "DefaultMarker",
      "DefaultVecMarker",
      "CursorValue",
      "FromStr",
      "TryFrom",
      "DelegatesId",
      "ColumnKind",
      // The SAMENESS row, ungated for the width row's own reason: two words of a vocabulary are
      // one column value or they are not, and no dialect changes the answer.
      "ColumnEq"
    ]
  );
}

/// **THE `Vec` READING IS EMITTED, AND IT SERVES BOTH WIRE POSITIONS.**
///
/// A `Vec<Codec>` column naming no word had NO default reading, where a `Vec<i64>` had one from
/// `to_filter!` — a declared vocabulary is as registerable as any type the framework registers
/// itself, and this row is that asymmetry closed. It is a LIST, which is `to_filter!`'s own default
/// for every element that does not say otherwise, and a word on the field still beats it.
///
/// It pays twice, which is why the pin says so: the OUTPUT crossing reads its collection fork off
/// this same row, so a `Vec` of the vocabulary gets a filter and a wire form from ONE emitted line.
/// The output side used to carry a second row of its own on an element-keyed trait —
/// `the_output_crossing_is_emitted_for_the_value` pins that it is gone.
#[test]
fn the_vec_reading_serves_both_wire_positions() {
  let rendered = rendered(&codec());
  assert!(
    rendered.contains("::marker::DefaultVecMarker for Codec"),
    "the collection's reading:\n{rendered}"
  );
  assert!(
    rendered.contains("::marker::ListMarker<") && rendered.contains("::std::vec::Vec<Codec>,"),
    "a list of the vocabulary:\n{rendered}"
  );
  assert!(
    rendered.contains("::marker::EnumMarker<Codec>,"),
    "its element read as the vocabulary:\n{rendered}"
  );
}

/// **The width follows `#[repr(…)]`, and Postgres widens it exactly as the house carrier table
/// does.**
///
/// `u8` is a `u8` column on SQLite and MySQL, which both carry one, and a `SMALLINT` on Postgres,
/// which carries no unsigned type at all. That widening is the framework's own `widened_carriers!`
/// restated, and it is why a vocabulary's rows are per-backend rather than one dialect-generic row.
#[test]
fn the_width_follows_the_repr_and_only_postgres_widens() {
  let mut model = codec();
  model.width = Some(IntegerWidth::U8);

  for gate in ["if_sqlite", "if_mysql"] {
    let held = inside(&model, gate);
    assert!(held.contains("u8"), "{gate}: {held}");
    assert!(!held.contains("i16"), "{gate}: {held}");
  }
  let postgres = inside(&model, "if_postgres");
  assert!(postgres.contains("i16"), "{postgres}");
  assert!(!postgres.contains("u8"), "{postgres}");
}

/// **The default width is `i64`, and the reason is that a narrower one could truncate.**
///
/// A fieldless enum with no repr hint has discriminants of type `isize`, so a declaration may write
/// a number no `i32` holds; the map casts the variant, and an `as` cast to a narrower type wraps
/// silently. `i64` is the only width in the house table that holds every such declaration.
#[test]
fn the_default_width_is_the_one_no_declaration_can_overflow() {
  assert_eq!(codec().width(), IntegerWidth::I64);
  assert_eq!(IntegerWidth::DEFAULT, IntegerWidth::I64);
  assert!(inside(&codec(), "if_sqlite").contains("i64"));
}

/// **The integer map casts the VARIANT, so a declared discriminant stays authoritative.**
///
/// `Codec::Vp9 as i64` and not `1i64`: the declaration may write `= 9`, and a number chosen here
/// would be a second numbering free to disagree with the one somebody's rows were written under.
#[test]
fn the_integer_map_casts_the_variant_rather_than_writing_a_number() {
  let held = inside(&codec(), "if_sqlite").replace(' ', "");

  assert!(
    held.contains("Codec::Vp9as::core::primitive::i64"),
    "{held}"
  );
}

/// **A per-backend TEXT form binds that backend's own word**, and leaves every other backend on the
/// discriminant.
#[test]
fn one_backend_takes_the_text_form_without_moving_the_others() {
  let mut model = codec();
  model.forms.insert(Namespace::Postgres, StorageForm::Text);
  model.variants[0]
    .names
    .insert(Namespace::Postgres, "avc".to_owned());

  let postgres = inside(&model, "if_postgres");
  assert!(postgres.contains("as_postgres_str"), "{postgres}");
  assert!(!postgres.contains("i64"), "{postgres}");
  assert!(inside(&model, "if_sqlite").contains("i64"));
  assert!(rendered(&model).contains(r#""avc""#));
}

/// **The FACE is decided by the FORM, and it is backend-free.**
///
/// A text namespace gets an accessor handing back its own name type and a conversion reading one;
/// an integer namespace gets neither, because there is no word for a name type to hold. Neither
/// rides a gate: a word names no driver.
#[test]
fn the_form_decides_which_namespaces_have_a_face() {
  let bare = codec();
  assert_eq!(
    methods(&bare),
    [
      "VARIANTS",
      "as_str",
      "as_graphql_str",
      "is_h264",
      "is_vp9",
      "is_tape"
    ]
  );
  assert_eq!(
    ungated_traits(&bare)
      .iter()
      .filter(|name| *name == "TryFrom")
      .count(),
    1,
    "only the wire speaks text by default"
  );

  let mut model = codec();
  model.forms.insert(Namespace::Sqlite, StorageForm::Text);
  model.forms.insert(Namespace::Graphql, StorageForm::Integer);
  assert_eq!(
    methods(&model),
    [
      "VARIANTS",
      "as_str",
      "as_sqlite_str",
      "is_h264",
      "is_vp9",
      "is_tape"
    ]
  );
  assert!(
    !rendered(&model).contains("GraphqlName"),
    "{}",
    rendered(&model)
  );
}

/// **The wire SHOUTS and a stored word does not**, and the asymmetry is the ecosystem's.
///
/// A GraphQL enum's members are `SCREAMING_SNAKE_CASE` by convention, so a wire face spelling a
/// variant `Vp9` would be the one schema in an ecosystem that did not. A stored word has no such
/// convention, and a mangling rule that changed would rewrite somebody's rows — so the same variant
/// is `VP9` on the wire and `Vp9` in the column, from ONE declaration that renamed nothing.
#[test]
fn the_wire_shouts_where_a_stored_word_is_verbatim() {
  let mut model = codec();
  model.forms.insert(Namespace::Mysql, StorageForm::Text);

  let rendered = rendered(&model);
  assert!(rendered.contains(r#""VP9""#), "{rendered}");
  assert!(rendered.contains(r#""TAPE""#), "{rendered}");
  assert!(rendered.contains(r#""Vp9""#), "{rendered}");
  assert!(rendered.contains(r#""Tape""#), "{rendered}");
}

/// **A global `rename` moves the canonical word, and every unrenamed face follows it.**
#[test]
fn a_global_rename_moves_every_face_that_did_not_state_its_own() {
  let mut model = codec();
  model.forms.insert(Namespace::Sqlite, StorageForm::Text);
  model.variants[1].rename = Some("vp09".to_owned());
  model.variants[1]
    .names
    .insert(Namespace::Graphql, "VP9".to_owned());

  let rendered = rendered(&model);
  assert!(
    rendered.contains(r#""vp09""#),
    "the canonical word, and SQLite's: {rendered}"
  );
  assert!(rendered.contains(r#""VP9""#), "the wire's own: {rendered}");
  assert!(
    !rendered.contains(r#""VP09""#),
    "the wire stated its own: {rendered}"
  );
}

/// **A raw variant is canonically unraw'd.**
///
/// The `r#` is Rust's escape for a word that collides with its grammar and no part of the name, so
/// the canonical word is `type` — which is what a schema and a hand-written row would spell.
#[test]
fn a_raw_variant_is_canonically_the_word_without_its_escape() {
  let mut model = codec();
  model.forms.insert(Namespace::Sqlite, StorageForm::Text);
  model.variants[2].ident = syn::Ident::new_raw("type", proc_macro2::Span::call_site());

  let rendered = rendered(&model);
  assert!(rendered.contains(r#""type""#), "{rendered}");
  assert!(!rendered.contains(r##""r#type""##), "{rendered}");
  assert_eq!(model.variants[2].predicate(), "is_type");
}

/// **MongoDB has a NAMESPACE and no storage row.**
///
/// `MongoCarrier` is the seam its row would take and no lane in this workspace can compile a
/// generated one, so the row waits — while the namespace is emitted with the others, which is what a
/// hand-written carrier is written in terms of.
#[test]
fn mongodb_gets_its_namespace_and_no_storage_row() {
  let mut model = codec();
  model.forms.insert(Namespace::Mongo, StorageForm::Text);

  assert!(
    gated(&model).iter().all(|(gate, _)| gate != "if_mongo"),
    "{:?}",
    gated(&model)
  );
  assert!(methods(&model).contains(&"as_mongo_str".to_owned()));
  assert!(rendered(&model).contains("MongoName"));
}

/// **NO BACKEND DERIVE AND NO BACKEND ATTRIBUTE**, which is what keeps `description: None` a fact
/// of the emission rather than a hope about what a derive lifted: async-graphql's own derives call
/// `get_rustdoc` unconditionally, with no key to decline it.
///
/// The STORAGE half names no backend at all — a word names no driver and no library — and the whole
/// expansion carries `#[automatically_derived]` and nothing else on its impls.
#[test]
fn the_expansion_carries_no_backend_derive_and_no_backend_attribute() {
  let rendered = rendered(&codec());
  let held = body(&emission(&codec()));
  let storage = quote::quote!(#(#held)*).to_string();

  assert!(!storage.contains("async_graphql"), "{storage}");
  for attrs in attributes(&emission(&codec())) {
    assert_eq!(attrs, "#[automatically_derived]", "{rendered}");
  }
}

/// **The WIRE face is a SECOND anonymous const, and the whole of it is inside the binding gate** —
/// so 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_wire_face_is_one_gated_block() {
  let emitted = emission(&codec());
  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!(
    gate
      .mac
      .path
      .segments
      .last()
      .expect("a path has a last segment")
      .ident,
    "if_async_graphql"
  );
}

/// Every non-doc attribute the expansion puts on an impl, tightly rendered.
fn attributes(file: &syn::File) -> Vec<String> {
  file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Impl(item) => Some(&item.attrs),
      _ => None,
    })
    .chain(body(file).iter().filter_map(|stmt| match stmt {
      syn::Stmt::Item(syn::Item::Impl(item)) => Some(&item.attrs),
      _ => None,
    }))
    .flatten()
    .filter(|attr| !attr.path().is_ident("doc"))
    .map(|attr| attr.to_token_stream().to_string().replace(' ', ""))
    .collect()
}

/// **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; a second emitter is a second place it can be broken.
#[test]
fn every_framework_path_goes_through_a_private_module() {
  let mut model = codec();
  for namespace in Namespace::ALL {
    model.forms.insert(namespace, StorageForm::Text);
  }

  assert!(
    ill_formed_shelf_paths(&model).is_empty(),
    "{:?}",
    ill_formed_shelf_paths(&model)
  );
}

/// Every place the emission names the framework crate and does NOT continue
/// `::__private::<module…>::<item>`.
fn ill_formed_shelf_paths(model: &EnumModel) -> 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()
}