trilean-json-shape-derive 3.1.7

The derive macro of trilean-json-shape, reading the serde attributes a type already carries.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
//! `#[derive(Shape)]` for the `trilean-json-shape` crate.
//!
//! The derive reads the serde attributes a type already carries, so one declaration serves serde and the shape:
//! `tag`, `untagged`, `rename`, `rename_all`, `deny_unknown_fields`, `default` and `flatten`, plus
//! `skip_serializing_if`, which only affects how a value is written and so is accepted and ignored. The shape adds
//! `#[shape(...)]` for what serde cannot say.
//!
//! On a container: `strict` (the same as `deny_unknown_fields`), `name = "..."` (the definition name, which is the
//! type's identifier otherwise), `together(a, b)` (each named field requires the others) and `min_properties = n`.
//! On a field, a tuple variant's field, and a variant of an untagged enum: `min = n`, `max = n`, `min_length = n`,
//! `min_items = n`, `max_items = n`, `unique_items`, `min_properties = n`, `pattern = "..."`,
//! `property_names = "..."` (a pattern the keys of a map match) and `constant = true` or `constant = "text"`. Doc
//! comments become descriptions.
//!
//! Supported types: a struct with named fields (an object), an enum of unit variants (a string enum), an enum with
//! `#[serde(tag = "...")]` whose variants are unit, struct or newtype variants over a struct (an internally tagged
//! union), and an enum with `#[serde(untagged)]` whose variants are struct or newtype variants, and at most one unit
//! variant, which is `null` (a union that matches exactly one). Anything else, any attribute that is not read at
//! the position it is written, and any generic parameter is a compile error that names it. A constraint on a type
//! it does not apply to, a flattened or tagged newtype field that is not a struct, a pattern outside the supported
//! subset and a property key used twice are compile errors too.

use std::collections::BTreeSet;

use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{quote, quote_spanned};
use syn::ext::IdentExt;
use syn::spanned::Spanned;
use syn::{
    Attribute, Data, DeriveInput, Expr, ExprLit, ExprUnary, Fields, FieldsNamed, Ident, Lit,
    LitStr, Meta, Token, Type, UnOp, Variant, parse_macro_input,
};

// The one source of the pattern grammar, which trilean-json-shape matches with, so the derive and the validator cannot
// disagree about which patterns exist. The derive only compiles patterns, never matches with them.
use trilean_json_shape_pattern as pattern;

#[proc_macro_derive(Shape, attributes(shape, serde))]
pub fn derive_shape(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand(&input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

type Result<T> = syn::Result<T>;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Case {
    Lower,
    Upper,
    Camel,
    Pascal,
    Snake,
    ScreamingSnake,
    Kebab,
    ScreamingKebab,
}

fn parse_case(text: &LitStr) -> Result<Case> {
    match text.value().as_str() {
        "lowercase" => Ok(Case::Lower),
        "UPPERCASE" => Ok(Case::Upper),
        "camelCase" => Ok(Case::Camel),
        "PascalCase" => Ok(Case::Pascal),
        "snake_case" => Ok(Case::Snake),
        "SCREAMING_SNAKE_CASE" => Ok(Case::ScreamingSnake),
        "kebab-case" => Ok(Case::Kebab),
        "SCREAMING-KEBAB-CASE" => Ok(Case::ScreamingKebab),
        other => Err(syn::Error::new(
            text.span(),
            format!("rename_all = \"{other}\" is not supported by trilean_json_shape::Shape"),
        )),
    }
}

/// The name of a variant (written in PascalCase) under a `rename_all` rule, as serde writes it.
fn variant_name(name: &str, case: Option<Case>) -> String {
    fn snake(name: &str) -> String {
        let mut snake = String::new();
        for (position, letter) in name.char_indices() {
            if position > 0 && letter.is_uppercase() {
                snake.push('_');
            }
            snake.push(letter.to_ascii_lowercase());
        }
        snake
    }
    match case {
        None | Some(Case::Pascal) => name.to_owned(),
        Some(Case::Lower) => name.to_ascii_lowercase(),
        Some(Case::Upper) => name.to_ascii_uppercase(),
        Some(Case::Camel) => name[..1].to_ascii_lowercase() + &name[1..],
        Some(Case::Snake) => snake(name),
        Some(Case::ScreamingSnake) => snake(name).to_ascii_uppercase(),
        Some(Case::Kebab) => snake(name).replace('_', "-"),
        Some(Case::ScreamingKebab) => snake(name).to_ascii_uppercase().replace('_', "-"),
    }
}

/// The name of a field (written in snake_case) under a `rename_all` rule, as serde writes it. `tests/serde_names.rs`
/// in `trilean-json-shape` compares both name functions with serde's own derive.
fn field_name(name: &str, case: Option<Case>) -> String {
    fn pascal(name: &str) -> String {
        let mut pascal = String::new();
        let mut capitalise = true;
        for letter in name.chars() {
            if letter == '_' {
                capitalise = true;
            } else if capitalise {
                pascal.push(letter.to_ascii_uppercase());
                capitalise = false;
            } else {
                pascal.push(letter);
            }
        }
        pascal
    }
    match case {
        // serde leaves a field name as written under `lowercase` and `snake_case`, since a field is already snake_case.
        None | Some(Case::Snake | Case::Lower) => name.to_owned(),
        Some(Case::Upper | Case::ScreamingSnake) => name.to_ascii_uppercase(),
        Some(Case::Pascal) => pascal(name),
        Some(Case::Camel) => {
            let pascal = pascal(name);
            if pascal.is_empty() {
                pascal
            } else {
                pascal[..1].to_ascii_lowercase() + &pascal[1..]
            }
        }
        Some(Case::Kebab) => name.replace('_', "-"),
        Some(Case::ScreamingKebab) => name.to_ascii_uppercase().replace('_', "-"),
    }
}

fn name_of(ident: &Ident) -> String {
    ident.unraw().to_string()
}

/// The doc comment of an item as one line, or none when it has no text.
fn description(attributes: &[Attribute]) -> Option<String> {
    let lines: Vec<String> = attributes
        .iter()
        .filter(|attribute| attribute.path().is_ident("doc"))
        .filter_map(|attribute| match &attribute.meta {
            Meta::NameValue(pair) => match &pair.value {
                Expr::Lit(ExprLit {
                    lit: Lit::Str(text),
                    ..
                }) => Some(text.value().trim().to_owned()),
                _ => None,
            },
            _ => None,
        })
        .filter(|line| !line.is_empty())
        .collect();
    if lines.is_empty() {
        None
    } else {
        Some(lines.join(" "))
    }
}

/// Where an attribute is written, which decides which keys it may hold.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Position {
    Container,
    Variant,
    Field,
    TupleField,
}

impl Position {
    fn describe(self) -> &'static str {
        match self {
            Position::Container => "a struct or enum",
            Position::Variant => "a variant",
            Position::Field => "a named field",
            Position::TupleField => "the field of a tuple variant",
        }
    }
}

/// A constraint a `#[shape(...)]` attribute adds, with the classes of type it may apply to.
#[derive(Clone)]
enum Spec {
    Min(f64),
    ExclusiveMin(f64),
    Max(f64),
    MinLength(usize),
    Pattern(String),
    MinItems(usize),
    MaxItems(usize),
    UniqueItems,
    MinProperties(usize),
    KeyPattern(String),
}

impl Spec {
    fn name(&self) -> &'static str {
        match self {
            Spec::Min(_) => "min",
            Spec::ExclusiveMin(_) => "exclusive_min",
            Spec::Max(_) => "max",
            Spec::MinLength(_) => "min_length",
            Spec::Pattern(_) => "pattern",
            Spec::MinItems(_) => "min_items",
            Spec::MaxItems(_) => "max_items",
            Spec::UniqueItems => "unique_items",
            Spec::MinProperties(_) => "min_properties",
            Spec::KeyPattern(_) => "property_names",
        }
    }

    /// The `Class` variants a type may have for this constraint to apply to it.
    fn classes(&self) -> &'static [&'static str] {
        match self {
            Spec::Min(_) | Spec::ExclusiveMin(_) | Spec::Max(_) => &["Integer", "Number"],
            Spec::MinLength(_) | Spec::Pattern(_) => &["String"],
            Spec::MinItems(_) | Spec::MaxItems(_) | Spec::UniqueItems => &["Array"],
            Spec::MinProperties(_) => &["Map", "OpenObject"],
            Spec::KeyPattern(_) => &["Map"],
        }
    }

    fn tokens(&self) -> TokenStream2 {
        match self {
            Spec::Min(bound) => quote! { ::trilean_json_shape::Constraint::Min(#bound) },
            Spec::ExclusiveMin(bound) => {
                quote! { ::trilean_json_shape::Constraint::ExclusiveMin(#bound) }
            }
            Spec::Max(bound) => quote! { ::trilean_json_shape::Constraint::Max(#bound) },
            Spec::MinLength(length) => {
                quote! { ::trilean_json_shape::Constraint::MinLength(#length) }
            }
            Spec::Pattern(source) => {
                quote! { ::trilean_json_shape::Constraint::Pattern(#source.to_owned()) }
            }
            Spec::MinItems(count) => quote! { ::trilean_json_shape::Constraint::MinItems(#count) },
            Spec::MaxItems(count) => quote! { ::trilean_json_shape::Constraint::MaxItems(#count) },
            Spec::UniqueItems => quote! { ::trilean_json_shape::Constraint::UniqueItems },
            Spec::MinProperties(count) => {
                quote! { ::trilean_json_shape::Constraint::MinProperties(#count) }
            }
            Spec::KeyPattern(source) => {
                quote! { ::trilean_json_shape::Constraint::KeyPattern(#source.to_owned()) }
            }
        }
    }
}

#[derive(Clone)]
struct Constrained {
    span: Span,
    spec: Spec,
}

/// A constant and where it was written.
type Located = (Span, Constant);

#[derive(Clone)]
enum Constant {
    Bool(bool),
    Text(String),
}

/// Everything a `serde` or `shape` attribute can say at any position. Which keys a position may hold is checked
/// once, in [`read`], and nothing outside it reads an attribute.
#[derive(Default)]
struct Attrs {
    tag: Option<String>,
    untagged: bool,
    rename_all: Option<Case>,
    strict: bool,
    name: Option<String>,
    together: Vec<(Span, Vec<Ident>)>,
    any_of: Vec<(Span, Vec<Ident>)>,
    one_of: Vec<(Span, Vec<Ident>)>,
    container_min_properties: Option<usize>,
    rename: Option<String>,
    default: bool,
    flatten: bool,
    constraints: Vec<Constrained>,
    constant: Option<Located>,
}

fn number_of(expression: &Expr) -> Result<f64> {
    match expression {
        Expr::Lit(ExprLit {
            lit: Lit::Int(number),
            ..
        }) => number.base10_parse(),
        Expr::Lit(ExprLit {
            lit: Lit::Float(number),
            ..
        }) => number.base10_parse(),
        Expr::Unary(ExprUnary {
            op: UnOp::Neg(_),
            expr,
            ..
        }) => number_of(expr).map(|number| -number),
        other => Err(syn::Error::new(other.span(), "expected a number")),
    }
}

fn count_of(literal: &Lit) -> Result<usize> {
    match literal {
        Lit::Int(number) => number.base10_parse(),
        other => Err(syn::Error::new(other.span(), "expected a whole number")),
    }
}

/// A pattern literal, refused here when the validator could not compile it.
fn pattern_of(literal: &LitStr) -> Result<String> {
    let source = literal.value();
    pattern::Pattern::new(&source)
        .map_err(|error| syn::Error::new(literal.span(), error.to_string()))?;
    Ok(source)
}

/// Reads every `serde` and `shape` attribute of one syntactic position. Every key is read here or is an error, so an
/// attribute can neither be ignored where it was written by mistake nor given twice.
fn read(attributes: &[Attribute], position: Position) -> Result<Attrs> {
    let mut attrs = Attrs::default();
    let mut seen = BTreeSet::new();
    for attribute in attributes {
        let from_serde = attribute.path().is_ident("serde");
        if !from_serde && !attribute.path().is_ident("shape") {
            continue;
        }
        attribute.parse_nested_meta(|meta| {
            let Some(ident) = meta.path.get_ident() else {
                return Err(meta.error("expected an attribute name"));
            };
            let key = name_of(ident);
            let source = if from_serde { "serde" } else { "shape" };
            if !matches!(key.as_str(), "together" | "any_of" | "one_of") && !seen.insert(format!("{source}:{key}")) {
                return Err(meta.error(format!("`{key}` is given twice")));
            }
            let span = meta.path.span();
            let applies_to = |positions: &[Position]| -> Result<()> {
                if positions.contains(&position) {
                    Ok(())
                } else {
                    Err(meta.error(format!("`{key}` does not apply to {}", position.describe())))
                }
            };
            let constrained = |spec: Spec| Constrained { span, spec };
            let on_member = [Position::Variant, Position::Field, Position::TupleField];
            if from_serde {
                match key.as_str() {
                    "tag" => {
                        applies_to(&[Position::Container])?;
                        attrs.tag = Some(meta.value()?.parse::<LitStr>()?.value());
                    }
                    "untagged" => {
                        applies_to(&[Position::Container])?;
                        attrs.untagged = true;
                    }
                    "rename_all" => {
                        applies_to(&[Position::Container])?;
                        attrs.rename_all = Some(parse_case(&meta.value()?.parse::<LitStr>()?)?);
                    }
                    "deny_unknown_fields" => {
                        applies_to(&[Position::Container])?;
                        attrs.strict = true;
                    }
                    "rename" => {
                        applies_to(&[Position::Variant, Position::Field])?;
                        attrs.rename = Some(meta.value()?.parse::<LitStr>()?.value());
                    }
                    "default" => {
                        applies_to(&[Position::Field])?;
                        if meta.input.peek(Token![=]) {
                            return Err(meta.error("default = \"path\" is not supported; use a type that implements Default"));
                        }
                        attrs.default = true;
                    }
                    "flatten" => {
                        applies_to(&[Position::Field])?;
                        attrs.flatten = true;
                    }
                    "skip_serializing_if" => {
                        applies_to(&[Position::Field])?;
                        meta.value()?.parse::<LitStr>()?;
                    }
                    _ => return Err(meta.error(format!("the serde attribute `{key}` is not supported by trilean_json_shape::Shape"))),
                }
                return Ok(());
            }
            match key.as_str() {
                "strict" => {
                    applies_to(&[Position::Container])?;
                    attrs.strict = true;
                }
                "name" => {
                    applies_to(&[Position::Container])?;
                    attrs.name = Some(meta.value()?.parse::<LitStr>()?.value());
                }
                "together" | "any_of" | "one_of" => {
                    applies_to(&[Position::Container])?;
                    let mut names = Vec::new();
                    meta.parse_nested_meta(|inner| {
                        let ident = inner
                            .path
                            .get_ident()
                            .ok_or_else(|| inner.error("expected a field name"))?;
                        names.push(ident.clone());
                        Ok(())
                    })?;
                    match key.as_str() {
                        "together" => attrs.together.push((span, names)),
                        "any_of" => attrs.any_of.push((span, names)),
                        _ => attrs.one_of.push((span, names)),
                    }
                }
                "min_properties" if position == Position::Container => {
                    attrs.container_min_properties = Some(count_of(&meta.value()?.parse::<Lit>()?)?);
                }
                "min_properties" => {
                    applies_to(&on_member)?;
                    let count = count_of(&meta.value()?.parse::<Lit>()?)?;
                    attrs.constraints.push(constrained(Spec::MinProperties(count)));
                }
                "min" | "max" | "exclusive_min" => {
                    applies_to(&on_member)?;
                    let bound = number_of(&meta.value()?.parse::<Expr>()?)?;
                    attrs.constraints.push(constrained(match key.as_str() {
                        "min" => Spec::Min(bound),
                        "max" => Spec::Max(bound),
                        _ => Spec::ExclusiveMin(bound),
                    }));
                }
                "min_length" | "min_items" | "max_items" => {
                    applies_to(&on_member)?;
                    let count = count_of(&meta.value()?.parse::<Lit>()?)?;
                    attrs.constraints.push(constrained(match key.as_str() {
                        "min_length" => Spec::MinLength(count),
                        "min_items" => Spec::MinItems(count),
                        _ => Spec::MaxItems(count),
                    }));
                }
                "unique_items" => {
                    applies_to(&on_member)?;
                    attrs.constraints.push(constrained(Spec::UniqueItems));
                }
                "pattern" | "property_names" => {
                    applies_to(&on_member)?;
                    let source = pattern_of(&meta.value()?.parse::<LitStr>()?)?;
                    attrs.constraints.push(constrained(if key == "pattern" {
                        Spec::Pattern(source)
                    } else {
                        Spec::KeyPattern(source)
                    }));
                }
                "constant" => {
                    applies_to(&on_member)?;
                    attrs.constant = Some((
                        span,
                        match meta.value()?.parse::<Lit>()? {
                            Lit::Bool(flag) => Constant::Bool(flag.value),
                            Lit::Str(text) => Constant::Text(text.value()),
                            other => return Err(syn::Error::new(other.span(), "constant takes a boolean or a string")),
                        },
                    ));
                }
                _ => return Err(meta.error(format!("the `{key}` attribute is not supported by trilean_json_shape::Shape"))),
            }
            Ok(())
        })?;
    }
    Ok(attrs)
}

/// One named field with everything the generated code needs.
struct Member {
    ident: Ident,
    key: String,
    ty: Type,
    attrs: Attrs,
    description: Option<String>,
    span: Span,
}

fn members(fields: &FieldsNamed, rename_all: Option<Case>) -> Result<Vec<Member>> {
    let mut found = Vec::new();
    for field in &fields.named {
        let Some(ident) = &field.ident else {
            return Err(syn::Error::new(field.span(), "a field must be named"));
        };
        let attrs = read(&field.attrs, Position::Field)?;
        if attrs.flatten
            && (attrs.rename.is_some()
                || attrs.default
                || !attrs.constraints.is_empty()
                || attrs.constant.is_some())
        {
            return Err(syn::Error::new(
                ident.span(),
                "a flattened field takes no other attribute: its fields are the object's own",
            ));
        }
        let key = attrs
            .rename
            .clone()
            .unwrap_or_else(|| field_name(&name_of(ident), rename_all));
        found.push(Member {
            ident: ident.clone(),
            key,
            ty: field.ty.clone(),
            attrs,
            description: description(&field.attrs),
            span: field.span(),
        });
    }
    let mut keys = BTreeSet::new();
    for member in &found {
        if !member.attrs.flatten && !keys.insert(member.key.clone()) {
            return Err(syn::Error::new(
                member.ident.span(),
                format!("the key \"{}\" is used by two fields", member.key),
            ));
        }
    }
    Ok(found)
}

/// The compile-time assertions that a constraint or constant applies to the type it is written on.
fn constraint_assertions(
    ty: &Type,
    constraints: &[Constrained],
    constant: Option<&Located>,
) -> TokenStream2 {
    let mut assertions = Vec::new();
    for constrained in constraints {
        let classes: Vec<Ident> = constrained
            .spec
            .classes()
            .iter()
            .map(|class| Ident::new(class, constrained.span))
            .collect();
        let message = format!(
            "#[shape({})] applies only to a type whose shape is {}",
            constrained.spec.name(),
            constrained.spec.classes().join(" or ").to_lowercase()
        );
        assertions.push(quote_spanned! { constrained.span =>
            const _: () = ::core::assert!(
                ::trilean_json_shape::private::class_in(<#ty as ::trilean_json_shape::Shape>::CLASS, &[#(::trilean_json_shape::Class::#classes),*]),
                #message
            );
        });
    }
    if let Some((span, constant)) = constant {
        let (class, message) = match constant {
            Constant::Bool(_) => (
                "Bool",
                "#[shape(constant = true or false)] applies only to a boolean",
            ),
            Constant::Text(_) => (
                "String",
                "#[shape(constant = \"text\")] applies only to a string",
            ),
        };
        let class = Ident::new(class, *span);
        assertions.push(quote_spanned! { *span =>
            const _: () = ::core::assert!(
                ::trilean_json_shape::private::class_in(<#ty as ::trilean_json_shape::Shape>::CLASS, &[::trilean_json_shape::Class::#class]),
                #message
            );
        });
    }
    quote! { #(#assertions)* }
}

/// The key lists a duplicate-key assertion and the `KEYS` constant are built from: an optional leading key (the
/// tag), the own keys, then the keys of every flattened field.
fn key_parts(head: Option<&str>, members: &[Member]) -> Vec<TokenStream2> {
    let own: Vec<&String> = members
        .iter()
        .filter(|member| !member.attrs.flatten)
        .map(|member| &member.key)
        .collect();
    let mut parts = Vec::new();
    if let Some(tag) = head {
        parts.push(quote! { (&[#tag] as &[&str]) });
    }
    parts.push(quote! { (&[#(#own),*] as &[&str]) });
    for member in members.iter().filter(|member| member.attrs.flatten) {
        let ty = &member.ty;
        parts.push(quote! { <#ty as ::trilean_json_shape::Shape>::KEYS });
    }
    parts
}

fn member_assertions(members: &[Member]) -> TokenStream2 {
    let assertions = members.iter().map(|member| {
        let ty = &member.ty;
        if member.attrs.flatten {
            let span = member.span;
            quote_spanned! { span =>
                const _: () = ::core::assert!(
                    <#ty as ::trilean_json_shape::Shape>::IS_OBJECT || <#ty as ::trilean_json_shape::Shape>::CATCH_ALL,
                    "a flattened field must be a struct that derives Shape, or a Map or OpenObject that takes the other members"
                );
            }
        } else {
            constraint_assertions(
                ty,
                &member.attrs.constraints,
                member.attrs.constant.as_ref(),
            )
        }
    });
    quote! { #(#assertions)* }
}

fn unique_keys_assertion(head: Option<&str>, members: &[Member], span: Span) -> TokenStream2 {
    let parts = key_parts(head, members);
    quote_spanned! { span =>
        const _: () = ::core::assert!(
            ::trilean_json_shape::private::keys_unique(&[#(#parts),*]),
            "a property key is used twice, counting the tag and the flattened fields"
        );
    }
}

/// Statements that push every field into `__fields` and `__dependent`.
fn fields_definition(members: &[Member]) -> TokenStream2 {
    let steps = members.iter().map(|member| {
        let ty = &member.ty;
        let key = &member.key;
        if member.attrs.flatten {
            return quote! {
                if <#ty as ::trilean_json_shape::Shape>::CATCH_ALL {
                    __additional = <#ty as ::trilean_json_shape::Shape>::catch_all_shape().map(::std::boxed::Box::new);
                } else {
                    match <#ty as ::trilean_json_shape::Shape>::definition().kind {
                        ::trilean_json_shape::Kind::Object(__inner) => {
                            __fields.extend(__inner.fields);
                            __dependent.extend(__inner.dependent_required);
                        }
                        _ => ::core::unreachable!("a flattened field is checked to be a struct at compile time"),
                    }
                }
            };
        }
        let constraints: Vec<TokenStream2> = member
            .attrs
            .constraints
            .iter()
            .map(|constrained| constrained.spec.tokens())
            .collect();
        let described = member
            .description
            .as_ref()
            .map(|text| quote! { __shape = __shape.described(#text); });
        let constant = match &member.attrs.constant {
            Some((_, Constant::Bool(flag))) => Some(quote! { __shape = __shape.constant_bool(#flag); }),
            Some((_, Constant::Text(text))) => Some(quote! { __shape = __shape.constant_string(#text); }),
            None => None,
        };
        let optional = member.attrs.default;
        quote! {
            {
                let mut __shape = <#ty as ::trilean_json_shape::Shape>::reference();
                #( __shape = __shape.constrained(#constraints); )*
                #constant
                #described
                __fields.push(::trilean_json_shape::FieldDef {
                    name: #key.to_owned(),
                    shape: __shape,
                    required: !<#ty as ::trilean_json_shape::Shape>::OPTIONAL && !#optional,
                });
            }
        }
    });
    quote! { #(#steps)* }
}

/// The groups of fields a container attribute names.
#[derive(Clone, Copy)]
struct Groups<'a> {
    together: &'a [(Span, Vec<Ident>)],
    any_of: &'a [(Span, Vec<Ident>)],
    one_of: &'a [(Span, Vec<Ident>)],
}

impl<'a> Groups<'a> {
    const NONE: Groups<'static> = Groups {
        together: &[],
        any_of: &[],
        one_of: &[],
    };

    fn of(attrs: &'a Attrs) -> Self {
        Groups {
            together: &attrs.together,
            any_of: &attrs.any_of,
            one_of: &attrs.one_of,
        }
    }
}

/// The keys of the fields a group names, each group at least two fields, none flattened.
fn group_keys(
    groups: &[(Span, Vec<Ident>)],
    what: &str,
    members: &[Member],
) -> Result<Vec<Vec<String>>> {
    let mut found = Vec::new();
    for (span, names) in groups {
        let mut keys = Vec::new();
        for name in names {
            let Some(member) = members.iter().find(|member| member.ident == *name) else {
                return Err(syn::Error::new(
                    name.span(),
                    format!("{what} names {name}, which is not a field"),
                ));
            };
            if member.attrs.flatten {
                return Err(syn::Error::new(
                    name.span(),
                    format!("{what} names {name}, which is flattened"),
                ));
            }
            keys.push(member.key.clone());
        }
        if keys.len() < 2 {
            return Err(syn::Error::new(
                *span,
                format!("{what} needs at least two fields"),
            ));
        }
        found.push(keys);
    }
    Ok(found)
}

/// An expression that is the `ObjectDef` of the members, after `fields_definition`'s statements.
fn object_definition(
    strict: bool,
    min_properties: Option<usize>,
    groups: Groups<'_>,
    members: &[Member],
) -> Result<TokenStream2> {
    let together_groups = group_keys(groups.together, "together", members)?;
    let any_of = group_keys(groups.any_of, "any_of", members)?;
    let one_of = group_keys(groups.one_of, "one_of", members)?;
    if any_of.len() > 1 || one_of.len() > 1 {
        return Err(syn::Error::new(
            Span::call_site(),
            "any_of and one_of each name one group of fields",
        ));
    }
    let any_of_keys = any_of.into_iter().next().unwrap_or_default();
    let one_of_keys = one_of.into_iter().next().unwrap_or_default();
    let minimum = match min_properties {
        Some(count) => quote! { ::core::option::Option::Some(#count) },
        None => quote! { ::core::option::Option::None },
    };
    let together = together_groups.iter().map(|keys| {
        let entries = keys.iter().map(|key| {
            let others: Vec<&String> = keys.iter().filter(|other| *other != key).collect();
            quote! { __dependent.push((#key.to_owned(), vec![#(#others.to_owned()),*])); }
        });
        quote! { #(#entries)* }
    });
    // A flattened catch-all sets `__additional`; that it never meets `deny_unknown_fields` is a compile-time
    // assertion on the field's type (see `expand_struct`).
    Ok(quote! {
        {
            #(#together)*
            ::trilean_json_shape::ObjectDef {
                fields: __fields,
                closed: #strict && __additional.is_none(),
                strips: false,
                additional: __additional,
                any_of_keys: ::std::vec![#(#any_of_keys.to_owned()),*],
                one_of_keys: ::std::vec![#(#one_of_keys.to_owned()),*],
                min_properties: #minimum,
                dependent_required: __dependent,
            }
        }
    })
}

/// The fields of a struct literal that read the members out of `__value`.
fn member_builds(members: &[Member], tag: Option<&str>) -> Vec<TokenStream2> {
    let own: Vec<&String> = members
        .iter()
        .filter(|member| !member.attrs.flatten)
        .map(|member| &member.key)
        .collect();
    let flattened: Vec<&Type> = members
        .iter()
        .filter(|member| member.attrs.flatten)
        .map(|member| &member.ty)
        .collect();
    let tag: Vec<&str> = tag.into_iter().collect();
    members
        .iter()
        .map(|member| {
            let ident = &member.ident;
            let ty = &member.ty;
            let key = &member.key;
            if member.attrs.flatten {
                return quote! {
                    #ident: if <#ty as ::trilean_json_shape::Shape>::CATCH_ALL {
                        let mut __known: ::std::vec::Vec<&str> = ::std::vec![#(#tag,)* #(#own,)*];
                        #( __known.extend(<#flattened as ::trilean_json_shape::Shape>::KEYS.iter().copied()); )*
                        <#ty as ::trilean_json_shape::Shape>::build_rest(__value, __path, &__known)?
                    } else {
                        <#ty as ::trilean_json_shape::Shape>::build(__value, __path)?
                    }
                };
            }
            let missing = if member.attrs.default {
                quote! { ::core::default::Default::default() }
            } else {
                quote! {
                    return ::core::result::Result::Err(::trilean_json_shape::Issues::at(
                        __path,
                        ::std::format!("missing the required property {}", #key),
                    ))
                }
            };
            quote! {
                #ident: match __value.get(#key) {
                    ::core::option::Option::Some(__entry) => {
                        __path.push_key(#key);
                        let __built = <#ty as ::trilean_json_shape::Shape>::build(__entry, __path);
                        __path.pop();
                        __built?
                    }
                    ::core::option::Option::None => match <#ty as ::trilean_json_shape::Shape>::absent() {
                        ::core::option::Option::Some(__absent) => __absent,
                        ::core::option::Option::None => #missing,
                    },
                }
            }
        })
        .collect()
}

fn member_registers(members: &[Member]) -> Vec<TokenStream2> {
    members
        .iter()
        .map(|member| {
            let ty = &member.ty;
            if member.attrs.flatten {
                quote! { <#ty as ::trilean_json_shape::Shape>::register_members(__registry); }
            } else {
                quote! { <#ty as ::trilean_json_shape::Shape>::register(__registry); }
            }
        })
        .collect()
}

/// A definition expression for a set of named fields, building an object shape.
fn object_shape(
    strict: bool,
    min_properties: Option<usize>,
    groups: Groups<'_>,
    members: &[Member],
    doc: Option<&String>,
    head: Option<TokenStream2>,
) -> Result<TokenStream2> {
    let steps = fields_definition(members);
    let object = object_definition(strict, min_properties, groups, members)?;
    let described = doc.map(|text| quote! { .described(#text) });
    Ok(quote! {
        {
            let mut __fields: ::std::vec::Vec<::trilean_json_shape::FieldDef> = ::std::vec::Vec::new();
            let mut __dependent: ::std::vec::Vec<(::std::string::String, ::std::vec::Vec<::std::string::String>)> =
                ::std::vec::Vec::new();
            let mut __additional: ::core::option::Option<::std::boxed::Box<::trilean_json_shape::ShapeDef>> =
                ::core::option::Option::None;
            #head
            #steps
            ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::Object(#object)) #described
        }
    })
}

/// What an expansion produces beyond the shared parts.
struct Parts {
    definition: TokenStream2,
    register_members: TokenStream2,
    build: TokenStream2,
    constants: TokenStream2,
    assertions: TokenStream2,
}

fn expand(input: &DeriveInput) -> Result<TokenStream2> {
    if !input.generics.params.is_empty() {
        return Err(syn::Error::new(
            input.generics.span(),
            "trilean_json_shape::Shape does not support generic types",
        ));
    }
    let container = read(&input.attrs, Position::Container)?;
    let name = &input.ident;
    let label = container.name.clone().unwrap_or_else(|| name_of(name));
    let doc = description(&input.attrs);
    let parts = match &input.data {
        Data::Struct(data) => {
            let Fields::Named(fields) = &data.fields else {
                return Err(syn::Error::new(
                    input.span(),
                    "trilean_json_shape::Shape needs a struct with named fields",
                ));
            };
            if container.tag.is_some() || container.untagged {
                return Err(syn::Error::new(
                    input.span(),
                    "tag and untagged apply to enums",
                ));
            }
            expand_struct(&container, fields, doc.as_ref(), input.span())?
        }
        Data::Enum(data) => expand_enum(
            &container,
            doc.as_ref(),
            name,
            &data.variants.iter().collect::<Vec<_>>(),
        )?,
        Data::Union(_) => {
            return Err(syn::Error::new(
                input.span(),
                "trilean_json_shape::Shape does not support unions",
            ));
        }
    };
    let Parts {
        definition,
        register_members,
        build,
        constants,
        assertions,
    } = parts;
    Ok(quote! {
        #assertions

        impl ::trilean_json_shape::Shape for #name {
            #constants

            fn reference() -> ::trilean_json_shape::ShapeDef {
                ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::Ref(#label.to_owned()))
            }

            fn definition() -> ::trilean_json_shape::ShapeDef {
                #definition
            }

            fn register(__registry: &mut ::trilean_json_shape::Registry) {
                if __registry.reserve(
                    #label,
                    ::std::any::TypeId::of::<Self>(),
                    ::std::any::type_name::<Self>(),
                ) {
                    __registry.define(#label, <Self as ::trilean_json_shape::Shape>::definition());
                    <Self as ::trilean_json_shape::Shape>::register_members(__registry);
                }
            }

            fn register_members(__registry: &mut ::trilean_json_shape::Registry) {
                #register_members
            }

            fn definitions() -> ::std::borrow::Cow<'static, ::trilean_json_shape::Definitions> {
                static DEFINITIONS: ::std::sync::OnceLock<::trilean_json_shape::Definitions> = ::std::sync::OnceLock::new();
                ::std::borrow::Cow::Borrowed(DEFINITIONS.get_or_init(::trilean_json_shape::Definitions::of::<Self>))
            }

            fn build(
                __value: &::trilean_json_shape::Value,
                __path: &mut ::trilean_json_shape::Path,
            ) -> ::core::result::Result<Self, ::trilean_json_shape::Issues> {
                #build
            }
        }

        impl<'de> ::trilean_json_shape::private::serde::Deserialize<'de> for #name {
            fn deserialize<D>(__deserializer: D) -> ::core::result::Result<Self, D::Error>
            where
                D: ::trilean_json_shape::private::serde::Deserializer<'de>,
            {
                let __value = <::trilean_json_shape::Value as ::trilean_json_shape::private::serde::Deserialize>::deserialize(
                    __deserializer,
                )?;
                <Self as ::trilean_json_shape::Shape>::from_json(&__value)
                    .map_err(<D::Error as ::trilean_json_shape::private::serde::de::Error>::custom)
            }
        }
    })
}

fn expand_struct(
    container: &Attrs,
    fields: &FieldsNamed,
    doc: Option<&String>,
    span: Span,
) -> Result<Parts> {
    let members = members(fields, container.rename_all)?;
    let definition = object_shape(
        container.strict,
        container.container_min_properties,
        Groups::of(container),
        &members,
        doc,
        None,
    )?;
    let registers = member_registers(&members);
    let builds = member_builds(&members, None);
    let parts = key_parts(None, &members);
    let own = members
        .iter()
        .filter(|member| !member.attrs.flatten)
        .count();
    let flattened_lengths: Vec<TokenStream2> = members
        .iter()
        .filter(|member| member.attrs.flatten)
        .map(|member| {
            let ty = &member.ty;
            quote! { <#ty as ::trilean_json_shape::Shape>::KEYS.len() }
        })
        .collect();
    let mut assertions = vec![
        member_assertions(&members),
        unique_keys_assertion(None, &members, span),
    ];
    if container.strict {
        for member in members.iter().filter(|member| member.attrs.flatten) {
            let ty = &member.ty;
            assertions.push(quote_spanned! { member.span =>
                const _: () = ::core::assert!(
                    !<#ty as ::trilean_json_shape::Shape>::CATCH_ALL,
                    "a flattened Map or OpenObject takes the other members, so the struct cannot also deny unknown fields"
                );
            });
        }
    }
    assertions.retain(|assertion| !assertion.is_empty());
    Ok(Parts {
        definition,
        register_members: quote! { #(#registers)* },
        build: quote! { ::core::result::Result::Ok(Self { #(#builds),* }) },
        constants: quote! {
            const CLASS: ::trilean_json_shape::Class = ::trilean_json_shape::Class::Named;
            const IS_OBJECT: bool = true;
            const KEYS: &'static [&'static str] = {
                const LENGTH: usize = #own #( + #flattened_lengths )*;
                const JOINED: [&'static str; LENGTH] = ::trilean_json_shape::private::concat_keys::<LENGTH>(&[#(#parts),*]);
                &JOINED
            };
        },
        assertions: quote! { #(#assertions)* },
    })
}

/// The key of a variant, and the attributes of the variant and of its tuple field.
struct VariantInfo<'a> {
    variant: &'a Variant,
    key: String,
    attrs: Attrs,
    description: Option<String>,
}

fn variant_info<'a>(variant: &'a Variant, rename_all: Option<Case>) -> Result<VariantInfo<'a>> {
    let attrs = read(&variant.attrs, Position::Variant)?;
    let key = attrs
        .rename
        .clone()
        .unwrap_or_else(|| variant_name(&name_of(&variant.ident), rename_all));
    Ok(VariantInfo {
        variant,
        key,
        attrs,
        description: description(&variant.attrs),
    })
}

/// The type of a newtype variant and the attributes written on its field.
fn newtype(variant: &Variant) -> Result<Option<(&Type, Attrs)>> {
    match &variant.fields {
        Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
            let field = &fields.unnamed[0];
            Ok(Some((&field.ty, read(&field.attrs, Position::TupleField)?)))
        }
        Fields::Unnamed(_) => Err(syn::Error::new(
            variant.span(),
            "a tuple variant must hold exactly one field",
        )),
        _ => Ok(None),
    }
}

/// The constraints written on a variant and on its tuple field, which together describe the newtype's type.
fn newtype_constraints(
    info: &VariantInfo<'_>,
    field: &Attrs,
) -> Result<(Vec<Constrained>, Option<Located>)> {
    let mut constraints = info.attrs.constraints.clone();
    for constrained in &field.constraints {
        if constraints
            .iter()
            .any(|known| known.spec.name() == constrained.spec.name())
        {
            return Err(syn::Error::new(
                constrained.span,
                format!("`{}` is given twice", constrained.spec.name()),
            ));
        }
        constraints.push(constrained.clone());
    }
    if info.attrs.constant.is_some() && field.constant.is_some() {
        return Err(syn::Error::new(
            info.variant.span(),
            "`constant` is given twice",
        ));
    }
    Ok((
        constraints,
        info.attrs
            .constant
            .clone()
            .or_else(|| field.constant.clone()),
    ))
}

/// The shape of one variant of a tagged enum, as an object holding the tag as a constant.
fn tagged_variant(
    info: &VariantInfo<'_>,
    tag: &str,
    strict: bool,
    parts: &mut VariantParts,
) -> Result<TokenStream2> {
    let span = info.variant.span();
    let info_key = &info.key;
    let tag_field = quote! {
        __fields.push(::trilean_json_shape::FieldDef {
            name: #tag.to_owned(),
            shape: ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::ConstString(#info_key.to_owned())),
            required: true,
        });
    };
    let doc = info.description.as_ref();
    match &info.variant.fields {
        Fields::Unit => {
            let described = doc.map(|text| quote! { .described(#text) });
            Ok(quote! {
                {
                    let mut __fields: ::std::vec::Vec<::trilean_json_shape::FieldDef> = ::std::vec::Vec::new();
                    #tag_field
                    ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::Object(::trilean_json_shape::ObjectDef {
                        fields: __fields,
                        closed: #strict,
                        strips: false,
                        additional: ::core::option::Option::None,
                        any_of_keys: ::std::vec::Vec::new(),
                        one_of_keys: ::std::vec::Vec::new(),
                        min_properties: ::core::option::Option::None,
                        dependent_required: ::std::vec::Vec::new(),
                    })) #described
                }
            })
        }
        Fields::Named(fields) => {
            let members = members(fields, None)?;
            parts.assertions.push(member_assertions(&members));
            parts
                .assertions
                .push(unique_keys_assertion(Some(tag), &members, span));
            parts.registers.extend(member_registers(&members));
            object_shape(strict, None, Groups::NONE, &members, doc, Some(tag_field))
        }
        Fields::Unnamed(_) => {
            let Some((ty, field)) = newtype(info.variant)? else {
                return Err(syn::Error::new(span, "unreachable"));
            };
            if !info.attrs.constraints.is_empty()
                || info.attrs.constant.is_some()
                || !field.constraints.is_empty()
                || field.constant.is_some()
            {
                return Err(syn::Error::new(
                    span,
                    "no constraint applies to a newtype variant of a tagged enum: its struct carries its own",
                ));
            }
            parts.assertions.push(quote_spanned! { span =>
                const _: () = ::core::assert!(
                    <#ty as ::trilean_json_shape::Shape>::IS_OBJECT,
                    "a newtype variant of a tagged enum must hold a struct that derives Shape"
                );
                const _: () = ::core::assert!(
                    ::trilean_json_shape::private::keys_unique(&[(&[#tag] as &[&str]), <#ty as ::trilean_json_shape::Shape>::KEYS]),
                    "a property key is used twice, counting the tag and the flattened fields"
                );
            });
            parts.registers.push(
                quote! { <#ty as ::trilean_json_shape::Shape>::register_members(__registry); },
            );
            let described = doc.map(|text| quote! { __shape = __shape.described(#text); });
            Ok(quote! {
                {
                    let mut __shape = <#ty as ::trilean_json_shape::Shape>::definition();
                    match &mut __shape.kind {
                        ::trilean_json_shape::Kind::Object(__object) => {
                            __object.closed = __object.closed || #strict;
                            let __rest = ::std::mem::take(&mut __object.fields);
                            let mut __fields: ::std::vec::Vec<::trilean_json_shape::FieldDef> = ::std::vec::Vec::new();
                            #tag_field
                            __fields.extend(__rest);
                            __object.fields = __fields;
                        }
                        _ => ::core::unreachable!("a newtype variant is checked to hold a struct at compile time"),
                    }
                    #described
                    __shape
                }
            })
        }
    }
}

#[derive(Default)]
struct VariantParts {
    registers: Vec<TokenStream2>,
    assertions: Vec<TokenStream2>,
}

/// The definition, member registration and build expression of an enum.
fn expand_enum(
    container: &Attrs,
    doc: Option<&String>,
    name: &Ident,
    variants: &[&Variant],
) -> Result<Parts> {
    let described = doc.map(|text| quote! { .described(#text) });
    if !container.together.is_empty()
        || !container.any_of.is_empty()
        || !container.one_of.is_empty()
        || container.container_min_properties.is_some()
    {
        return Err(syn::Error::new(
            name.span(),
            "together, any_of, one_of and min_properties describe one object, so they apply to structs",
        ));
    }
    if variants.is_empty() {
        return Err(syn::Error::new(
            name.span(),
            "an enum needs at least one variant",
        ));
    }
    if container.tag.is_some() && container.untagged {
        return Err(syn::Error::new(
            name.span(),
            "tag and untagged cannot be combined",
        ));
    }
    let mut infos = Vec::new();
    let mut keys = BTreeSet::new();
    for variant in variants {
        let info = variant_info(variant, container.rename_all)?;
        if !keys.insert(info.key.clone()) {
            return Err(syn::Error::new(
                variant.span(),
                format!("the variant key \"{}\" is used twice", info.key),
            ));
        }
        infos.push(info);
    }
    let constants = quote! {
        const CLASS: ::trilean_json_shape::Class = ::trilean_json_shape::Class::Named;
    };
    let all_unit = variants
        .iter()
        .all(|variant| matches!(variant.fields, Fields::Unit));
    if all_unit && container.tag.is_none() && !container.untagged {
        for info in &infos {
            if !info.attrs.constraints.is_empty() || info.attrs.constant.is_some() {
                return Err(syn::Error::new(
                    info.variant.span(),
                    "no constraint applies to a unit variant",
                ));
            }
        }
        let idents: Vec<&Ident> = variants.iter().map(|variant| &variant.ident).collect();
        let texts: Vec<&String> = infos.iter().map(|info| &info.key).collect();
        return Ok(Parts {
            definition: quote! {
                ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::Enum(::std::vec![#(#texts.to_owned()),*])) #described
            },
            register_members: quote! {},
            build: quote! {
                match __value.as_str() {
                    #( ::core::option::Option::Some(#texts) => ::core::result::Result::Ok(Self::#idents), )*
                    _ => ::core::result::Result::Err(::trilean_json_shape::Issues::at(__path, "not one of the variants")),
                }
            },
            constants,
            assertions: quote! {},
        });
    }
    let mut parts = VariantParts::default();
    if let Some(tag) = &container.tag {
        let mut definitions = Vec::new();
        let mut arms = Vec::new();
        for info in &infos {
            if !info.attrs.constraints.is_empty() || info.attrs.constant.is_some() {
                return Err(syn::Error::new(
                    info.variant.span(),
                    "#[shape] constraints on a variant apply only to a newtype variant of an untagged enum",
                ));
            }
            definitions.push(tagged_variant(info, tag, container.strict, &mut parts)?);
            let (ident, key) = (&info.variant.ident, &info.key);
            match &info.variant.fields {
                Fields::Unit => {
                    arms.push(quote! { #key => ::core::result::Result::Ok(Self::#ident), })
                }
                Fields::Named(fields) => {
                    let members = members(fields, None)?;
                    let builds = member_builds(&members, Some(tag));
                    arms.push(quote! { #key => ::core::result::Result::Ok(Self::#ident { #(#builds),* }), });
                }
                Fields::Unnamed(_) => {
                    let Some((ty, _)) = newtype(info.variant)? else {
                        return Err(syn::Error::new(info.variant.span(), "unreachable"));
                    };
                    arms.push(quote! {
                        #key => <#ty as ::trilean_json_shape::Shape>::build(__value, __path).map(Self::#ident),
                    });
                }
            }
        }
        let keys: Vec<&String> = infos.iter().map(|info| &info.key).collect();
        let registers = &parts.registers;
        let assertions = &parts.assertions;
        return Ok(Parts {
            definition: quote! {
                ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::Tagged {
                    tag: #tag.to_owned(),
                    variants: ::std::vec![#( (#keys.to_owned(), #definitions) ),*],
                }) #described
            },
            register_members: quote! { #(#registers)* },
            build: quote! {
                let ::core::option::Option::Some(__kind) = __value.get(#tag).and_then(::trilean_json_shape::Value::as_str) else {
                    return ::core::result::Result::Err(::trilean_json_shape::Issues::at(__path, "expected a string naming the kind"));
                };
                match __kind {
                    #(#arms)*
                    _ => ::core::result::Result::Err(::trilean_json_shape::Issues::at(__path, "not a known kind")),
                }
            },
            constants,
            assertions: quote! { #(#assertions)* },
        });
    }
    if container.untagged {
        let units = variants
            .iter()
            .filter(|variant| matches!(variant.fields, Fields::Unit))
            .count();
        if units > 1 {
            return Err(syn::Error::new(
                name.span(),
                "an untagged enum can have one unit variant, which is null: with two, null matches both",
            ));
        }
        let mut alternatives = Vec::new();
        let mut arms = Vec::new();
        for (position, info) in infos.iter().enumerate() {
            let (ident, doc) = (&info.variant.ident, info.description.as_ref());
            let described = doc.map(|text| quote! { .described(#text) });
            match &info.variant.fields {
                Fields::Unit => {
                    if !info.attrs.constraints.is_empty() || info.attrs.constant.is_some() {
                        return Err(syn::Error::new(
                            info.variant.span(),
                            "no constraint applies to a unit variant",
                        ));
                    }
                    alternatives.push(
                        quote! { ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::Null) #described },
                    );
                    arms.push(quote! { #position => ::core::result::Result::Ok(Self::#ident), });
                }
                Fields::Named(fields) => {
                    if !info.attrs.constraints.is_empty() || info.attrs.constant.is_some() {
                        return Err(syn::Error::new(
                            info.variant.span(),
                            "#[shape] constraints on a variant apply only to a newtype variant",
                        ));
                    }
                    let members = members(fields, None)?;
                    parts.assertions.push(member_assertions(&members));
                    parts.assertions.push(unique_keys_assertion(
                        None,
                        &members,
                        info.variant.span(),
                    ));
                    parts.registers.extend(member_registers(&members));
                    alternatives.push(object_shape(
                        container.strict,
                        None,
                        Groups::NONE,
                        &members,
                        doc,
                        None,
                    )?);
                    let builds = member_builds(&members, None);
                    arms.push(quote! { #position => ::core::result::Result::Ok(Self::#ident { #(#builds),* }), });
                }
                Fields::Unnamed(_) => {
                    let Some((ty, field)) = newtype(info.variant)? else {
                        return Err(syn::Error::new(info.variant.span(), "unreachable"));
                    };
                    let (constraints, constant) = newtype_constraints(info, &field)?;
                    parts.assertions.push(constraint_assertions(
                        ty,
                        &constraints,
                        constant.as_ref(),
                    ));
                    let tokens: Vec<TokenStream2> = constraints
                        .iter()
                        .map(|constrained| constrained.spec.tokens())
                        .collect();
                    let constant = match constant {
                        Some((_, Constant::Bool(flag))) => {
                            Some(quote! { __shape = __shape.constant_bool(#flag); })
                        }
                        Some((_, Constant::Text(text))) => {
                            Some(quote! { __shape = __shape.constant_string(#text); })
                        }
                        None => None,
                    };
                    alternatives.push(quote! {
                        {
                            let mut __shape = <#ty as ::trilean_json_shape::Shape>::reference();
                            #( __shape = __shape.constrained(#tokens); )*
                            #constant
                            __shape #described
                        }
                    });
                    parts.registers.push(
                        quote! { <#ty as ::trilean_json_shape::Shape>::register(__registry); },
                    );
                    arms.push(quote! {
                        #position => <#ty as ::trilean_json_shape::Shape>::build(__value, __path).map(Self::#ident),
                    });
                }
            }
        }
        let registers = &parts.registers;
        let assertions = &parts.assertions;
        return Ok(Parts {
            definition: quote! {
                ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::OneOf(::std::vec![#(#alternatives),*])) #described
            },
            register_members: quote! { #(#registers)* },
            build: quote! {
                static ALTERNATIVES: ::std::sync::OnceLock<::std::vec::Vec<::trilean_json_shape::ShapeDef>> =
                    ::std::sync::OnceLock::new();
                let __alternatives = ALTERNATIVES.get_or_init(|| match <Self as ::trilean_json_shape::Shape>::definition().kind {
                    ::trilean_json_shape::Kind::OneOf(__alternatives) => __alternatives,
                    _ => ::core::unreachable!("an untagged enum is a union"),
                });
                let __definitions = <Self as ::trilean_json_shape::Shape>::definitions();
                for (__index, __alternative) in __alternatives.iter().enumerate() {
                    if ::trilean_json_shape::private::decide(__path, &__definitions, __alternative, __value) {
                        return match __index {
                            #(#arms)*
                            _ => ::core::result::Result::Err(::trilean_json_shape::Issues::at(__path, "no such alternative")),
                        };
                    }
                }
                ::core::result::Result::Err(::trilean_json_shape::Issues::at(__path, "matches no alternative"))
            },
            constants,
            assertions: quote! { #(#assertions)* },
        });
    }
    Err(syn::Error::new(
        name.span(),
        "an enum with data needs #[serde(tag = \"...\")] or #[serde(untagged)]; trilean_json_shape::Shape does not support externally tagged enums",
    ))
}

#[cfg(test)]
mod tests {
    use syn::DeriveInput;

    use super::{Case, expand, field_name, variant_name};

    fn parse(source: &str) -> DeriveInput {
        syn::parse_str(source).unwrap_or_else(|error| panic!("{source}: {error}"))
    }

    fn refusal(source: &str) -> String {
        match expand(&parse(source)) {
            Ok(_) => panic!("{source} was accepted"),
            Err(error) => error.to_string(),
        }
    }

    #[test]
    fn every_position_refuses_what_it_does_not_read() {
        let cases = [
            // container
            (
                "#[shape(bogus)] struct A { a: u8 }",
                "the `bogus` attribute is not supported",
            ),
            (
                "#[shape(min = 1)] struct A { a: u8 }",
                "`min` does not apply to a struct or enum",
            ),
            (
                "#[serde(rename = \"X\")] struct A { a: u8 }",
                "`rename` does not apply to a struct or enum",
            ),
            (
                "#[serde(alias = \"X\")] struct A { a: u8 }",
                "the serde attribute `alias` is not supported",
            ),
            (
                "#[serde(rename_all = \"weird\")] struct A { a: u8 }",
                "rename_all = \"weird\" is not supported",
            ),
            (
                "#[serde(deny_unknown_fields, deny_unknown_fields)] struct A { a: u8 }",
                "`deny_unknown_fields` is given twice",
            ),
            (
                "#[serde(tag = \"k\")] struct A { a: u8 }",
                "tag and untagged apply to enums",
            ),
            (
                "#[shape(together(a))] struct A { a: u8 }",
                "together needs at least two fields",
            ),
            (
                "#[shape(together(a, z))] struct A { a: u8 }",
                "together names z, which is not a field",
            ),
            (
                "#[shape(together(a, b))] enum E { A { a: u8, b: u8 } }",
                "apply to structs",
            ),
            (
                "#[shape(any_of(a, b))] enum E { A { a: u8, b: u8 } }",
                "apply to structs",
            ),
            (
                "#[shape(any_of(a))] struct A { a: u8 }",
                "any_of needs at least two fields",
            ),
            (
                "#[shape(one_of(a, z))] struct A { a: u8 }",
                "one_of names z, which is not a field",
            ),
            (
                "#[shape(any_of(a, b), any_of(a, b))] struct A { a: u8, b: u8 }",
                "any_of and one_of each name one group of fields",
            ),
            (
                "#[shape(any_of(a, b))] struct A { a: u8, #[serde(flatten)] b: B }",
                "any_of names b, which is flattened",
            ),
            (
                "struct A { #[shape(exclusive_min = 1, exclusive_min = 2)] a: u8 }",
                "`exclusive_min` is given twice",
            ),
            (
                "struct A { #[shape(exclusive_min = \"x\")] a: u8 }",
                "expected a number",
            ),
            (
                "#[shape(one_of(a, z))] struct A { a: u8 }",
                "one_of names z, which is not a field",
            ),
            (
                "#[shape(any_of(a, b), any_of(a, b))] struct A { a: u8, b: u8 }",
                "any_of and one_of each name one group of fields",
            ),
            (
                "#[shape(any_of(a, b))] struct A { a: u8, #[serde(flatten)] b: B }",
                "any_of names b, which is flattened",
            ),
            (
                "struct A { #[shape(exclusive_min = 1, exclusive_min = 2)] a: u8 }",
                "`exclusive_min` is given twice",
            ),
            (
                "struct A { #[shape(exclusive_min = \"x\")] a: u8 }",
                "expected a number",
            ),
            // named field
            (
                "struct A { #[shape(strict)] a: u8 }",
                "`strict` does not apply to a named field",
            ),
            (
                "struct A { #[serde(tag = \"x\")] a: u8 }",
                "`tag` does not apply to a named field",
            ),
            (
                "struct A { #[serde(alias = \"x\")] a: u8 }",
                "the serde attribute `alias` is not supported",
            ),
            (
                "struct A { #[serde(default = \"f\")] a: u8 }",
                "default = \"path\" is not supported",
            ),
            (
                "struct A { #[shape(min = 1, min = 2)] a: u8 }",
                "`min` is given twice",
            ),
            (
                "struct A { #[shape(constant = true)] #[shape(constant = false)] a: bool }",
                "`constant` is given twice",
            ),
            (
                "struct A { #[serde(rename = \"a\", rename = \"b\")] a: u8 }",
                "`rename` is given twice",
            ),
            (
                "struct A { #[shape(pattern = \"a{2}\")] a: String }",
                "is not supported",
            ),
            (
                "struct A { #[shape(property_names = \"(\")] a: u8 }",
                "a group is not closed",
            ),
            (
                "struct A { #[shape(constant = 1)] a: u8 }",
                "constant takes a boolean or a string",
            ),
            (
                "struct A { #[shape(min = \"x\")] a: u8 }",
                "expected a number",
            ),
            (
                "struct A { #[shape(zzz)] a: u8 }",
                "the `zzz` attribute is not supported",
            ),
            (
                "struct A { #[serde(flatten, rename = \"x\")] a: B }",
                "takes no other attribute",
            ),
            (
                "struct A { a: u8, #[serde(rename = \"a\")] b: u8 }",
                "the key \"a\" is used by two fields",
            ),
            // variant
            (
                "#[serde(untagged)] enum E { #[shape(bogus_typo)] U, V { a: u8 } }",
                "the `bogus_typo` attribute is not supported",
            ),
            (
                "#[serde(untagged)] enum E { #[serde(default)] U, V { a: u8 } }",
                "`default` does not apply to a variant",
            ),
            (
                "#[serde(untagged)] enum E { #[shape(min_properties = 5)] N { a: u8 }, M(String) }",
                "apply only to a newtype variant",
            ),
            (
                "#[serde(untagged)] enum E { #[shape(min_length = 1)] U, V { a: u8 } }",
                "no constraint applies to a unit variant",
            ),
            (
                "#[serde(tag = \"k\")] enum E { #[shape(min_items = 1)] A { a: u8 } }",
                "apply only to a newtype variant of an untagged enum",
            ),
            (
                "enum E { A, #[serde(rename = \"A\")] B }",
                "the variant key \"A\" is used twice",
            ),
            (
                "#[serde(tag = \"k\", untagged)] enum E { A }",
                "tag and untagged cannot be combined",
            ),
            ("#[serde(untagged)] enum E { A, B }", "one unit variant"),
            ("enum E { A(u8), B }", "externally tagged"),
            ("enum E {}", "at least one variant"),
            // tuple variant field
            (
                "#[serde(untagged)] enum E { One(#[serde(flatten)] String) }",
                "`flatten` does not apply to the field of a tuple variant",
            ),
            (
                "#[serde(untagged)] enum E { One(#[shape(zzz)] String) }",
                "the `zzz` attribute is not supported",
            ),
            (
                "#[serde(untagged)] enum E { #[shape(min_length = 1)] One(#[shape(min_length = 2)] String) }",
                "`min_length` is given twice",
            ),
            (
                "#[serde(untagged)] enum E { One(u8, u8) }",
                "exactly one field",
            ),
            (
                "#[serde(tag = \"k\")] enum E { A(#[shape(min = 1)] B) }",
                "no constraint applies to a newtype variant of a tagged enum",
            ),
            // the item itself
            ("struct A<T> { a: T }", "does not support generic types"),
            ("struct A(u8);", "needs a struct with named fields"),
            ("union A { a: u8 }", "does not support unions"),
        ];
        for (source, expected) in cases {
            let message = refusal(source);
            assert!(
                message.contains(expected),
                "{source}: {message:?} lacks {expected:?}"
            );
        }
    }

    #[test]
    fn what_the_type_system_decides_is_asserted_in_the_expansion() {
        let wrong_kind = expand(&parse("struct A { #[shape(min = 1)] a: String }"))
            .expect("the kind is checked by the compiler")
            .to_string();
        assert!(wrong_kind.contains("class_in"), "{wrong_kind}");
        assert!(
            wrong_kind.contains("Integer") && wrong_kind.contains("Number"),
            "{wrong_kind}"
        );
        let flattened = expand(&parse("struct A { #[serde(flatten)] a: B }"))
            .expect("the type is checked by the compiler")
            .to_string();
        assert!(flattened.contains("IS_OBJECT"), "{flattened}");
        let tagged = expand(&parse("#[serde(tag = \"k\")] enum E { A(B) }"))
            .expect("the type is checked by the compiler")
            .to_string();
        assert!(
            tagged.contains("IS_OBJECT") && tagged.contains("keys_unique"),
            "{tagged}"
        );
        let constant = expand(&parse("struct A { #[shape(constant = \"x\")] a: u8 }"))
            .expect("the kind is checked by the compiler")
            .to_string();
        assert!(
            constant.contains("class_in") && constant.contains("String"),
            "{constant}"
        );
    }

    #[test]
    fn variant_names_follow_serde() {
        let table = [
            ("HTTPServer", Case::Snake, "h_t_t_p_server"),
            ("HTTPServer", Case::Kebab, "h-t-t-p-server"),
            ("HTTPServer", Case::ScreamingSnake, "H_T_T_P_SERVER"),
            ("HTTPServer", Case::ScreamingKebab, "H-T-T-P-SERVER"),
            ("HTTPServer", Case::Camel, "hTTPServer"),
            ("HTTPServer", Case::Lower, "httpserver"),
            ("HTTPServer", Case::Upper, "HTTPSERVER"),
            ("HTTPServer", Case::Pascal, "HTTPServer"),
            ("Utf8Bom", Case::Snake, "utf8_bom"),
            ("Utf8Bom", Case::Kebab, "utf8-bom"),
            ("A", Case::Snake, "a"),
            ("RegexParse", Case::Kebab, "regex-parse"),
            ("RegexParse", Case::Camel, "regexParse"),
            ("V2Api", Case::Snake, "v2_api"),
        ];
        for (name, case, expected) in table {
            assert_eq!(
                variant_name(name, Some(case)),
                expected,
                "{name} as {case:?}"
            );
        }
        assert_eq!(variant_name("RegexParse", None), "RegexParse");
    }

    #[test]
    fn field_names_follow_serde() {
        let table = [
            ("code_unit", Case::Camel, "codeUnit"),
            ("code_unit", Case::Pascal, "CodeUnit"),
            ("code_unit", Case::Kebab, "code-unit"),
            ("code_unit", Case::ScreamingSnake, "CODE_UNIT"),
            ("code_unit", Case::ScreamingKebab, "CODE-UNIT"),
            ("code_unit", Case::Upper, "CODE_UNIT"),
            ("code_unit", Case::Lower, "code_unit"),
            ("Mixed_Case", Case::Lower, "Mixed_Case"),
            ("Mixed_Case", Case::Snake, "Mixed_Case"),
            ("code_unit", Case::Snake, "code_unit"),
            ("x_1_y", Case::Pascal, "X1Y"),
            ("x_1_y", Case::Camel, "x1Y"),
            ("_leading", Case::Pascal, "Leading"),
            ("_leading", Case::Camel, "leading"),
            ("trailing_", Case::Pascal, "Trailing"),
            ("a__b", Case::Pascal, "AB"),
            ("a__b", Case::Kebab, "a--b"),
            ("http_server", Case::Camel, "httpServer"),
        ];
        for (name, case, expected) in table {
            assert_eq!(field_name(name, Some(case)), expected, "{name} as {case:?}");
        }
        assert_eq!(field_name("code_unit", None), "code_unit");
    }
}