ingraph-derive 0.1.0

The attribute and derive macros for ingraph: the words a record, node, key, filter and vocabulary declaration is written in.
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
//! The interface parser's acceptance: what a declaration may say, and every shape it may not.

use ingraph_codegen::{
  interface::{InterfaceModel, Tier},
  model::DatabaseKind,
};
use quote::ToTokens;

/// The pass under test, over a declaration written the way the derive took one — see
/// [`host::split`](crate::host::split) for why these suites keep writing it in one piece.
pub(super) fn parse(
  input: &syn::DeriveInput,
) -> syn::Result<ingraph_codegen::interface::InterfaceModel> {
  let (host, arguments) = crate::host::split(input);
  super::parse(&host, &arguments)
}

/// Every field a model kept, as its name, its domain type and the tier it landed in.
fn fields(model: &InterfaceModel) -> Vec<(String, String, Tier)> {
  model
    .fields
    .iter()
    .map(|field| (field.name.to_string(), tight(&field.ty), field.tier))
    .collect()
}

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

fn tight(tokens: impl ToTokens) -> String {
  tokens.to_token_stream().to_string().replace(' ', "")
}

/// The refusal a declaration gets, as one string.
pub(super) fn refusal(input: &syn::DeriveInput) -> String {
  parse(input)
    .expect_err("the declaration is refused")
    .into_iter()
    .map(|error| error.to_string())
    .collect::<Vec<_>>()
    .join(" | ")
}

/// **The SHORT form is every default**: a stored field, at the type it was written with, at no
/// database in particular and by borrow.
#[test]
fn the_short_form_takes_every_default() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(fields(title: String, duration: Duration))]
    pub enum Media {
      Video(Video),
      Audio(Audio),
    }
  })
  .expect("a name and a type is a whole field");

  assert_eq!(
    fields(&model),
    [
      ("title".to_owned(), "String".to_owned(), Tier::Stored),
      ("duration".to_owned(), "Duration".to_owned(), Tier::Stored),
    ]
  );
  assert!(model.fields.iter().all(|field| !field.copy));
  assert!(model.fields.iter().all(|field| field.pins.is_empty()));
  assert_eq!(model.databases(), []);
  assert_eq!(model.krate, syn::parse_quote!(::ingraph));
}

/// **The LONG form is where a pin, a projection and a tier are written**, and the two forms sit in
/// one list.
#[test]
fn the_long_form_carries_the_pins_the_projection_and_the_tier() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(fields(
      title: String,
      mask(type = "Mask", copy, persist(sqlite(type = "u32"), postgres)),
      display_label(type = "String", graphql(computed)),
      checksum(type = "u64", graphql(try_computed)),
    ))]
    pub enum Media {
      Video(Video),
    }
  })
  .expect("the long form is the same field with more said about it");

  assert_eq!(
    fields(&model),
    [
      ("title".to_owned(), "String".to_owned(), Tier::Stored),
      ("mask".to_owned(), "Mask".to_owned(), Tier::Stored),
      (
        "display_label".to_owned(),
        "String".to_owned(),
        Tier::Computed
      ),
      ("checksum".to_owned(), "u64".to_owned(), Tier::TryComputed),
    ]
  );

  let mask = &model.fields[1];
  assert!(mask.copy);
  assert_eq!(tight(mask.pinned(DatabaseKind::Sqlite)), "u32");
  assert_eq!(
    tight(mask.pinned(DatabaseKind::Postgres)),
    "Mask",
    "a database named with no `type` keeps the domain type — and is still named"
  );
  assert_eq!(
    model.databases(),
    [DatabaseKind::Sqlite, DatabaseKind::Postgres]
  );
}

/// **The interface's own `persist(…)` selects databases** for the fields that pinned none, which is
/// the only way a short-form-only declaration has of saying which rows its contract is about.
#[test]
fn the_block_selects_the_databases_a_short_form_field_is_checked_at() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(persist(sqlite, mongo), fields(title: String))]
    pub enum Media {
      Video(Video),
    }
  })
  .expect("a selection is not a storage declaration");

  assert_eq!(
    model
      .persist
      .iter()
      .map(|database| database.kind)
      .collect::<Vec<_>>(),
    [DatabaseKind::Sqlite, DatabaseKind::Mongo]
  );
  assert_eq!(
    model.databases(),
    [DatabaseKind::Sqlite, DatabaseKind::Mongo]
  );
}

/// **The SYNTHETIC WORDS take the record's own knob**, per database and PREFIX ONLY.
///
/// An interface holds no table, so what moves is everything a union statement INVENTS: the
/// discriminant every arm projects, and the derived table the outer query selects from. Both are
/// resolved from one prefix, so a declaration cannot move one and leave the other.
#[test]
fn a_database_block_names_the_namespace_its_words_are_minted_in() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(persist(sqlite(alias(prefix = "__mine")), postgres), fields(title: String))]
    pub enum Media {
      Video(Video),
    }
  })
  .expect("the same entry the record's database block takes");

  assert_eq!(model.kind_word(DatabaseKind::Sqlite), "__mine_kind__");
  assert_eq!(model.source_word(DatabaseKind::Sqlite), "__mine_union__");
  assert!(!model.mints_the_default_words(DatabaseKind::Sqlite));

  assert_eq!(model.kind_word(DatabaseKind::Postgres), "__ig_kind__");
  assert_eq!(model.source_word(DatabaseKind::Postgres), "__ig_union__");
  assert!(
    model.mints_the_default_words(DatabaseKind::Postgres),
    "the database beside it named nothing, and states nothing",
  );
}

/// **The SILENT branch is pinned**, and it is the one every deployment takes.
///
/// At the default the emission states NOTHING and the engine's own `SqlInterface::KIND`/`SOURCE`
/// answer — so the party that WRITES `'video' AS "__ig_kind__"` into each arm is `ingraph`'s own
/// literal, while the party that READS it is [`InterfaceModel::kind_word`], which builds the name
/// out of the mint's namespace. Two independent derivations of one string, live together, at the
/// default.
///
/// They agreed only by a coincidence nothing held. The reserved-prefix pin in
/// [`crate::tests`] keeps the two `ALIAS_PREFIX` constants level, but nothing said
/// `interface::KIND` was that prefix plus `_kind__`. Moving the namespace — which that pin permits,
/// all three crates together — would leave the engine's literal behind, and every arm would then
/// project a column the emitted decode asks for by another name: a failure inside a `try_get`, with
/// no red build anywhere.
///
/// This is the equation between the two PRODUCERS, and it lives in this crate for the
/// reserved-prefix pin's own reason: `ingraph-derive` is the one context that can see the mint and
/// the engine at once.
#[test]
fn the_engines_own_words_are_the_ones_the_default_mints() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(persist(sqlite, postgres), fields(title: String))]
    pub enum Media {
      Video(Video),
    }
  })
  .expect("a declaration that moves nothing");

  for kind in [DatabaseKind::Sqlite, DatabaseKind::Postgres] {
    assert!(
      model.mints_the_default_words(kind),
      "{kind:?} named no prefix, so the emission is silent and the engine answers",
    );
    assert_eq!(
      model.kind_word(kind),
      ingraph::interface::KIND.as_str(),
      "the arm writes the engine's word and the decode reads the mint's; they must be one string",
    );
    assert_eq!(
      model.source_word(kind),
      ingraph::interface::SOURCE.as_str(),
      "the derived table is named by the engine and qualified by the mint",
    );
  }
}

/// **`depth` is refused on an interface**, BY THE REASON rather than as an unknown word.
///
/// The word is the length of an alias table and an interface owns no table to mint one for, so an
/// author who wrote it has a concrete idea and the useful answer is which half of the knob applies
/// here. Accepting it and reading nothing would be the accept-and-ignore this grammar refuses
/// everywhere else.
#[test]
fn an_interface_has_no_alias_table_for_a_depth_to_size() {
  let refused = refusal(&syn::parse_quote! {
    #[ingraph(persist(sqlite(alias(depth = 16))), fields(title: String))]
    pub enum Media {
      Video(Video),
    }
  });

  assert!(
    refused.contains("owns no table to mint one for"),
    "{refused}"
  );
}

/// The block's own rules reach an interface too — a prefix outside the fence, and a block naming no
/// knob, both of which are `alias(…)`'s rather than the record's.
#[test]
fn an_interfaces_alias_block_is_held_to_the_same_rules() {
  for (declaration, expected) in [
    (
      syn::parse_quote! {
        #[ingraph(persist(sqlite(alias(prefix = "mine"))), fields(title: String))]
        pub enum Media {
          Video(Video),
        }
      },
      "does not begin `__`",
    ),
    (
      syn::parse_quote! {
        #[ingraph(persist(sqlite(alias())), fields(title: String))]
        pub enum Media {
          Video(Video),
        }
      },
      "names neither knob",
    ),
  ] {
    let refused = refusal(&declaration);
    assert!(refused.contains(expected), "{refused}");
  }
}

/// **The empty block's sentence names one knob here and two on a record**, because that is what each
/// takes — the list is the block's own vocabulary rather than a fixed string.
#[test]
fn the_empty_block_names_only_the_knob_an_interface_has() {
  let refused = refusal(&syn::parse_quote! {
    #[ingraph(persist(sqlite(alias())), fields(title: String))]
    pub enum Media {
      Video(Video),
    }
  });

  assert!(refused.contains("it takes `prefix = \"…\"`,"), "{refused}");
  assert!(!refused.contains("`depth = N`"), "{refused}");
}

/// **The COMPUTED cell is db-less**, and it is the one place in this grammar where a crossing's
/// error is not written inside a database's block.
#[test]
fn the_computed_cell_names_no_database() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(
      graphql(computed(error = "media::ComputeError")),
      fields(label(type = "String", graphql(try_computed))),
    )]
    pub enum Media {
      Video(Video),
    }
  })
  .expect("a computed value is derived from the member, so the crossing has no database");

  assert_eq!(tight(model.computed_error()), "media::ComputeError");
}

/// **Everything else the enum-level block takes**, in one declaration: the framework root, the
/// refusal's name, and the fact that both reach the model.
#[test]
fn the_enum_level_block_carries_the_root_and_the_refusals_name() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(crate = "shim::ingraph", unwrap_error(rename = "NoSuchMedia"), fields(title: String))]
    pub enum Media {
      Video(Video),
    }
  })
  .expect("a re-export shim is where the framework may live");

  assert_eq!(tight(&model.krate), "shim::ingraph");
  assert_eq!(model.error(), "NoSuchMedia");
  assert_eq!(
    model
      .emitted_types()
      .iter()
      .map(|declared| declared.name.to_string())
      .collect::<Vec<_>>(),
    [
      "NoSuchMedia",
      "MediaFields",
      "MediaDerivations",
      "MediaGraphqlOutput"
    ]
  );
}

/// **A field spelled with a Rust keyword is readable, and keeps its escape.**
///
/// `parse_any` is what reads the name; the `r#` STAYS because this name is Rust and nothing else —
/// it becomes a contract method and a row field, and both are spelled the way the declaration
/// spelled them. A record's column strips the escape on its way to a `CREATE TABLE`, and an
/// interface has no table to strip it for.
#[test]
fn a_field_may_be_spelled_with_a_keyword() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(fields(r#type: Kind, r#match(type = "bool")))]
    pub enum Media {
      Video(Video),
    }
  })
  .expect("`parse_any` is what reads a keyword as a name");

  assert_eq!(
    fields(&model)
      .into_iter()
      .map(|(name, _, _)| name)
      .collect::<Vec<_>>(),
    ["r#type", "r#match"]
  );
}

/// **An interface with no fields is a UNION**, and the refusal says which derive equips one — both
/// for a missing block and for an empty one.
#[test]
fn refuses_an_interface_that_promises_nothing() {
  for declaration in [
    syn::parse_quote! {
      pub enum Media { Video(Video) }
    },
    syn::parse_quote! {
      #[ingraph(fields())]
      pub enum Media { Video(Video) }
    },
  ] {
    let refused: syn::DeriveInput = declaration;
    let message = refusal(&refused);
    assert!(message.contains("is a UNION"), "{message}");
    assert!(message.contains("`#[derive(ingraph::Union)]`"), "{message}");
  }
}

/// **A field names its type**, whichever form it was written in.
#[test]
fn refuses_a_field_that_names_no_type() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(fields(title(copy)))]
    pub enum Media { Video(Video) }
  });

  assert!(message.contains("a field names its type"), "{message}");
}

/// **The long form's type is a STRING, and the bare token is refused by NAME.**
///
/// The spelling the grammar took before this level joined the family, so the refusal has to teach
/// rather than only decline — an author writing it has the right idea and one word to change.
///
/// ONCE, which is the other half of the claim: the value was refused where it was written, so the
/// field is not ALSO told that it names no type — a mistake it did not make, reported at a span
/// that is not where the one it did make is. [`refusal`] joins what it collected with `" | "`, so a
/// second voice is visible here.
#[test]
fn refuses_a_bare_type_by_naming_the_spelling() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(fields(title(type = String)))]
    pub enum Media { Video(Video) }
  });

  assert!(
    message.contains("`type = \"<Type>\"` in the long one, in a string literal"),
    "{message}"
  );
  assert!(
    !message.contains(" | "),
    "one mistake, one refusal: {message}"
  );
}

/// **A GENERIC type round-trips through the string**, which is what this level needs the literal to
/// carry: `Vec<i64>` is the shape a collection pin declares, and a form that lost its arguments
/// would be a contract about the wrong type.
#[test]
fn the_string_form_carries_a_generic_type() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(fields(marks(type = "Vec<i64>", list(scalar))))]
    pub enum Media { Video(Video) }
  })
  .expect("a type in a string literal is the type it spells");

  assert_eq!(tight(&model.fields[0].ty), "Vec<i64>");
}

/// **An entry neither form admits is refused**, so a misspelling is never read as a field.
#[test]
fn refuses_an_entry_a_field_does_not_take() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(fields(title(type = "String", indexed)))]
    pub enum Media { Video(Video) }
  });

  assert!(message.contains("unknown entry on a field"), "{message}");
}

/// **One field, one promise.**
#[test]
fn refuses_a_field_declared_twice() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(fields(title: String, title(type = "u64")))]
    pub enum Media { Video(Video) }
  });

  assert!(message.contains("is declared more than once"), "{message}");
  assert!(message.contains("one field, one promise"), "{message}");
}

/// **The AXIS LAW is refused by name at every level a domain belongs.**
///
/// Three positions, one rule: the interface's own block, a field's own options, and inside a
/// field's `graphql(…)`. A database is a block INSIDE a domain, never a domain of its own.
#[test]
fn refuses_a_database_written_where_a_domain_belongs() {
  for declaration in [
    syn::parse_quote! {
      #[ingraph(sqlite(type = "u32"), fields(title: String))]
      pub enum Media { Video(Video) }
    },
    syn::parse_quote! {
      #[ingraph(fields(title(type = "String", sqlite(type = "u32"))))]
      pub enum Media { Video(Video) }
    },
    syn::parse_quote! {
      #[ingraph(fields(title(type = "String", graphql(sqlite(type = "u32")))))]
      pub enum Media { Video(Video) }
    },
  ] {
    let refused: syn::DeriveInput = declaration;
    let message = refusal(&refused);
    assert!(
      message.contains("`sqlite` is a DATABASE and this is not a database's scope"),
      "{message}"
    );
  }
}

/// **A computed field is not stored, in BOTH directions**, and the refusal points at whichever
/// entry arrived second.
#[test]
fn refuses_a_field_that_is_computed_and_pinned() {
  let computed_first = refusal(&syn::parse_quote! {
    #[ingraph(fields(label(type = "String", graphql(computed), persist(sqlite(type = "text")))))]
    pub enum Media { Video(Video) }
  });
  assert!(
    computed_first.contains("is COMPUTED and pinned"),
    "{computed_first}"
  );

  let pinned_first = refusal(&syn::parse_quote! {
    #[ingraph(fields(label(type = "String", persist(sqlite(type = "text")), graphql(computed))))]
    pub enum Media { Video(Video) }
  });
  assert!(
    pinned_first.contains("is PINNED and computed"),
    "{pinned_first}"
  );
}

/// **A field is COMPUTED once**: the two words are the same claim about whether deriving it can
/// fail, and there is no third answer.
#[test]
fn refuses_a_field_that_claims_both_computed_words() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(fields(label(type = "String", graphql(computed, try_computed))))]
    pub enum Media { Video(Video) }
  });

  assert!(message.contains("a field is COMPUTED once"), "{message}");
}

/// **The OUTPUT position is the one still ADMITTED-AND-REFUSED**, so its refusal names the shape
/// and says what it arrives with rather than reporting an unknown word.
///
/// Both levels, because both are real entries of the settled design: a field's row-to-wire leg, and
/// the interface-level cell that would type what it refuses with.
#[test]
fn refuses_the_cell_whose_consumer_has_not_landed_by_naming_it() {
  let field = refusal(&syn::parse_quote! {
    #[ingraph(fields(mask(type = "Mask",
      graphql(output(sqlite(from = "hex_of_mask"))))))]
    pub enum Media { Video(Video) }
  });
  assert!(
    field.contains("`output(<db>(from = \"…\"))` is a field's own row-to-wire crossing"),
    "{field}"
  );
  assert!(
    field.contains("arrives with the interface's own output face"),
    "{field}"
  );

  let declaration = refusal(&syn::parse_quote! {
    #[ingraph(graphql(output(sqlite(try_from(error = "media::Error")))), fields(title: String))]
    pub enum Media { Video(Video) }
  });
  assert!(
    declaration.contains("arrives with the interface's own output face"),
    "{declaration}"
  );
}

/// **The OPERAND cells are read now**, both of them, and each answers what its own level knows: the
/// FIELD names the function one column's values cross through, and the INTERFACE names what the
/// whole crossing refuses with.
#[test]
fn the_operand_cells_are_read_at_the_level_each_belongs_to() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(
      persist(sqlite, postgres),
      graphql(input(comparison(sqlite(try_into(error = "media::TooWide"))))),
      fields(mask(type = "Mask",
        persist(sqlite(type = "u32")),
        graphql(input(comparison(sqlite(try_into = "narrow")))))),
    )]
    pub enum Media { Video(Video) }
  })
  .expect("both operand cells have consumers");

  let mask = &model.fields[0];
  assert_eq!(
    mask.operand(DatabaseKind::Sqlite).map(tight).as_deref(),
    Some("narrow")
  );
  assert_eq!(
    mask.operand(DatabaseKind::Postgres).map(tight),
    None,
    "a database with no converter crosses through the stored type's own `TryFrom`"
  );
  assert_eq!(
    tight(model.operand_error(DatabaseKind::Sqlite)),
    "media::TooWide"
  );
  assert!(
    tight(model.operand_error(DatabaseKind::Postgres)).contains("dyn"),
    "and a database with no cell takes the boxed refusal"
  );
}

/// **The three other legs are refused in the operand position too**, for the reason they are
/// refused in `persist(…)`: an interface performs no crossing in their direction.
///
/// And the POSITION axis admits `comparison` alone — an order carries a direction and never a
/// value, and a cursor already speaks the stored vocabulary.
#[test]
fn the_operand_position_takes_one_leg_and_one_position() {
  for leg in ["from", "try_from", "into"] {
    let word = ident(leg);
    let message = refusal(&syn::parse_quote! {
      #[ingraph(
        graphql(input(comparison(sqlite(#word(error = "media::Error"))))),
        fields(title: String)
      )]
      pub enum Media { Video(Video) }
    });
    assert!(
      message.contains("is not the leg an operand takes"),
      "{message}"
    );
  }

  for (position, why) in [
    ("orderby", "carries a DIRECTION and a subject"),
    ("pagination", "opaque engine round trip"),
  ] {
    let word = ident(position);
    let message = refusal(&syn::parse_quote! {
      #[ingraph(graphql(input(#word(sqlite(try_into(error = "E"))))), fields(title: String))]
      pub enum Media { Video(Video) }
    });
    assert!(message.contains(why), "{message}");
  }
}

/// **A computed field has no operand to cross**, being statically absent from the filter — so a
/// converter on one types a hop nothing takes.
#[test]
fn refuses_an_operand_crossing_on_a_computed_field() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(fields(label(type = "String",
      graphql(computed, input(comparison(sqlite(try_into = "narrow")))))))]
    pub enum Media { Video(Video) }
  });

  assert!(
    message.contains("is COMPUTED and names an operand crossing"),
    "{message}"
  );
}

/// **One database, one operand converter**, which is the rule every block in this grammar keeps.
#[test]
fn refuses_a_second_operand_converter_for_one_database() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(fields(mask(type = "Mask", graphql(input(comparison(
      sqlite(try_into = "a"), sqlite(try_into = "b")
    ))))))]
    pub enum Media { Video(Video) }
  });

  assert!(
    message.contains("is declared more than once for this field's operand"),
    "{message}"
  );
}

/// **The HYDRATION cell is read now**, its consumer having landed: `try_into` is the read leg the
/// emitted hydration performs, so the type an author names is the type that method answers with.
#[test]
fn the_hydration_cell_is_read_and_the_other_three_legs_are_not() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(persist(sqlite(try_into(error = "media::Error"))), fields(title: String))]
    pub enum Media { Video(Video) }
  })
  .expect("`try_into` types the crossing the hydration performs");

  assert_eq!(model.errors.len(), 1);
  assert_eq!(model.errors[0].kind, DatabaseKind::Sqlite);
  assert_eq!(
    tight(model.hydration_error(DatabaseKind::Sqlite)),
    "media::Error"
  );
  assert!(
    tight(model.hydration_error(DatabaseKind::Postgres)).contains("dyn"),
    "a database with no cell takes the boxed refusal"
  );

  for leg in ["from", "try_from", "into"] {
    let word = syn::Ident::new(leg, proc_macro2::Span::call_site());
    let message = refusal(&syn::parse_quote! {
      #[ingraph(persist(sqlite(#word(error = "media::Error"))), fields(title: String))]
      pub enum Media { Video(Video) }
    });
    assert!(
      message.contains(&format!(
        "`{leg}(error = \"…\")` is an interface's per-leg refusal cell"
      )),
      "{message}"
    );
    assert!(message.contains("arrives with the find half"), "{message}");
  }
}

/// **One database, one hydration cell** — a second is the same rule every block in this grammar
/// keeps.
#[test]
fn refuses_a_second_hydration_cell_for_one_database() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(
      persist(sqlite(try_into(error = "a::Error"), try_into(error = "b::Error"))),
      fields(title: String)
    )]
    pub enum Media { Video(Video) }
  });

  assert!(
    message.contains("`try_into(…)` is declared more than once"),
    "{message}"
  );
}

/// **A renamed refusal may not take a name the expansion already lands** — its own enum's, or
/// either contract trait's.
#[test]
fn refuses_a_refusal_named_after_something_the_expansion_declares() {
  for name in ["Media", "MediaFields", "MediaDerivations"] {
    let rename = syn::LitStr::new(name, proc_macro2::Span::call_site());
    let message = refusal(&syn::parse_quote! {
      #[ingraph(unwrap_error(rename = #rename), fields(title: String))]
      pub enum Media { Video(Video) }
    });
    assert!(message.contains("and it is already"), "{name}: {message}");
  }
}

/// **The SHAPE refusals are the union's family, in this declaration's own terms** — one walk, two
/// laws, and the sentence a reader gets is about the declaration they wrote.
#[test]
fn the_shape_refusals_state_the_interfaces_own_law() {
  let empty = refusal(&syn::parse_quote! {
    #[ingraph(fields(title: String))]
    pub enum Media {}
  });
  assert!(
    empty.contains("an enum with no variants declares no interface"),
    "{empty}"
  );
  assert!(empty.contains("a promise ABOUT its members"), "{empty}");

  let duplicated = refusal(&syn::parse_quote! {
    #[ingraph(fields(title: String))]
    pub enum Media { Video(Video), Second(Video) }
  });
  assert!(duplicated.contains("carry ONE member type"), "{duplicated}");
  assert!(
    duplicated.contains("no fan-out could say which variant it answered from"),
    "{duplicated}"
  );

  let generic = refusal(&syn::parse_quote! {
    #[ingraph(fields(title: String))]
    pub enum Media<T> { Video(T) }
  });
  assert!(
    generic.contains("generic interfaces are not supported"),
    "{generic}"
  );
}

/// **One pass reports the grammar and the shape together**, so a declaration with mistakes in both
/// halves costs one compile.
#[test]
fn one_pass_reports_the_grammar_and_the_shape_together() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(nonsense, fields(title(copy)))]
    pub enum Media { Video { id: u64 } }
  });

  assert!(
    message.contains("unknown entry in `#[ingraph(…)]`"),
    "{message}"
  );
  assert!(message.contains("a field names its type"), "{message}");
  assert!(
    message.contains("takes the member POSITIONALLY"),
    "{message}"
  );
}

/// **A member block names the column ONE member carries a field under**, and its key is the
/// VARIANT — checked token-for-token against the enum's own, verbatim case.
///
/// The axis extends one step and the step is this grammar's alone: interface field block ▸
/// `members(…)` ▸ one block per variant ▸ entries. A record grows no member axis, having no
/// members.
#[test]
fn a_member_block_names_what_one_member_calls_the_field() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(fields(
      created_at(type = "Timestamp", members(Audio(field = "imported_at"))),
      title: String,
    ))]
    pub enum Media {
      Video(Video),
      Audio(Audio),
    }
  })
  .expect("a member set and its contract arrive in one derive input");

  let created_at = &model.fields[0];
  assert_eq!(*created_at.column(&ident("Audio")), "imported_at");
  assert_eq!(
    *created_at.column(&ident("Video")),
    "created_at",
    "a member with no block carries the interface's own name"
  );
  assert_eq!(*model.fields[1].column(&ident("Audio")), "title");
}

/// **A RAW variant is matched unraw'd**, the `r#` being Rust's escape for a word that collides with
/// its grammar and no part of the name — and inside `members(…)` it is a key like any other, where
/// a rule reading the first letter would have had to decide about the escape first.
#[test]
fn a_raw_variant_is_a_member_block_key_too() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(fields(kind(type = "u8", members(r#Type(field = "code")))))]
    pub enum Media {
      r#Type(Marker),
    }
  })
  .expect("the escape is not part of the name");

  assert_eq!(*model.fields[0].column(&ident("Type")), "code");
}

/// **A block naming no variant is refused AS a member**, listing the ones there are — rather than
/// as a word nobody recognised, which is what its POSITION says it is.
#[test]
fn refuses_a_member_block_that_names_no_variant() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(fields(title(type = "String", members(Sound(field = "name")))))]
    pub enum Media { Video(Video), Audio(Audio) }
  });

  assert!(
    message.contains("`Sound` is not a member variant of this interface"),
    "{message}"
  );
  assert!(message.contains("`Video` and `Audio`"), "{message}");
}

/// **One member, one column.** A variant that carried a field under two names would carry it under
/// neither.
#[test]
fn refuses_a_member_declared_twice_on_one_field() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(fields(title(type = "String", members(Video(field = "a"), Video(field = "b")))))]
    pub enum Media { Video(Video) }
  });

  assert!(
    message.contains("is declared more than once on `title`"),
    "{message}"
  );
}

/// **A computed field has no column for a member to call anything**, which is the tier collision
/// one level in.
#[test]
fn refuses_a_member_block_on_a_computed_field() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(fields(label(type = "String", graphql(computed), members(Video(field = "name")))))]
    pub enum Media { Video(Video) }
  });

  assert!(
    message.contains("is COMPUTED and names a member's column"),
    "{message}"
  );
}

/// **`field = "…"` is the only entry a member block takes**, and it must be an identifier: what it
/// names is a RUST FIELD, on the member's own struct and on its row, and both are reached by field
/// access.
#[test]
fn refuses_a_member_block_that_names_no_column_or_names_it_wrongly() {
  let empty = refusal(&syn::parse_quote! {
    #[ingraph(fields(title(type = "String", members(Video))))]
    pub enum Media { Video(Video) }
  });
  assert!(
    empty.contains("a member block is `<Variant>(field = \"…\")`"),
    "{empty}"
  );

  let unknown = refusal(&syn::parse_quote! {
    #[ingraph(fields(title(type = "String", members(Video(field = "name", type = "u8")))))]
    pub enum Media { Video(Video) }
  });
  assert!(
    unknown.contains("unknown entry in a member block"),
    "{unknown}"
  );

  let mangled = refusal(&syn::parse_quote! {
    #[ingraph(fields(title(type = "String", members(Video(field = "not an ident")))))]
    pub enum Media { Video(Video) }
  });
  assert!(
    mangled.contains("as an identifier in a string literal"),
    "{mangled}"
  );
}

/// **The old spelling is the same NAMED MIGRATION here**, read through the same shared knob — one
/// grammar, so the second member set invents no wording for a rule the first already has.
#[test]
fn refuses_the_old_spelling_of_the_refusals_knob() {
  let moved = refusal(&syn::parse_quote! {
    #[ingraph(error(rename = "NoSuchMedia"), fields(title: String))]
    pub enum Media { Video(Video) }
  });

  assert!(
    moved.contains("`error` names CONVERSION CELLS now"),
    "{moved}"
  );
  assert!(moved.contains("`unwrap_error(rename = \"…\")`"), "{moved}");
}

/// **POSITION decides what a key is, and the case rule is gone.**
///
/// A variant in LOWER CASE is addressable inside the container — the corner a first-letter rule
/// could not reach — and a variant whose spelling collides with one of this grammar's own words is
/// two different things in the two scopes: `type = "<Type>"` outside it, and that member's block
/// inside.
#[test]
fn position_decides_what_a_key_is_and_case_decides_nothing() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(fields(
      title(type = "String", members(quiet(field = "name"))),
      kind(type = "u8", members(r#type(field = "tag"))),
    ))]
    pub enum Media {
      quiet(Audio),
      r#type(Marker),
    }
  })
  .expect("a variant is whatever the enum spells, and the container is where it is a key");

  assert_eq!(*model.fields[0].column(&ident("quiet")), "name");
  assert_eq!(*model.fields[1].column(&ident("type")), "tag");
  assert_eq!(
    tight(&model.fields[1].ty),
    "u8",
    "and `type = …` outside the container is still the field's own type"
  );
}

/// **A member block written OUTSIDE the container is a MIGRATION**, not an unknown word — refused
/// by naming the member and the container it belongs in.
///
/// What tells it apart is that it names a VARIANT, asked of the enum's own list. Nothing about the
/// key's spelling is consulted, which is what makes the rule survive a lower-case variant.
#[test]
fn refuses_a_member_block_outside_the_container_by_naming_where_it_goes() {
  let message = refusal(&syn::parse_quote! {
    #[ingraph(fields(title(type = "String", Audio(field = "name"))))]
    pub enum Media { Video(Video), Audio(Audio) }
  });

  assert!(
    message.contains("`Audio` is a MEMBER and this is the field's own scope"),
    "{message}"
  );
  assert!(
    message.contains("write `members(Audio(field = \"…\"))`"),
    "{message}"
  );
}

/// **One `members(…)` per field, and never an empty one.**
#[test]
fn refuses_a_second_members_block_and_one_naming_nobody() {
  let twice = refusal(&syn::parse_quote! {
    #[ingraph(fields(title(type = "String", members(Video(field = "a")), members(Audio(field = "b")))))]
    pub enum Media { Video(Video), Audio(Audio) }
  });
  assert!(
    twice.contains("`members(…)` is declared more than once on a field"),
    "{twice}"
  );

  for empty in [
    syn::parse_quote! {
      #[ingraph(fields(title(type = "String", members())))]
      pub enum Media { Video(Video) }
    },
    syn::parse_quote! {
      #[ingraph(fields(title(type = "String", members)))]
      pub enum Media { Video(Video) }
    },
  ] {
    let refused: syn::DeriveInput = empty;
    let message = refusal(&refused);
    assert!(
      message.contains("`members(…)` names no member"),
      "{message}"
    );
  }
}