gql 0.2.0

A GraphQL reference implementation for Rust.
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
//! The GraphQL type system.
//!
//! Definitions are immutable once a [`Schema`](crate::Schema) is built. They are wrapped in
//! `Arc`s so cloning a field definition (for example while building an introspection result) is
//! cheap and does not duplicate resolver state.
//!
//! A schema is *name based*: a field's type is a [`TypeRef`] holding the name of another
//! definition. That is what makes recursive and mutually recursive types possible without
//! interior mutability. The schema builder resolves and validates every name once, at build
//! time.

use core::fmt;
use std::sync::Arc;

use futures::stream::BoxStream;
use indexmap::IndexMap;

use crate::{
    Value, ast,
    error::{GraphQLError, PathSegment},
    execution::ExecutionContext,
    fragments::Fragments,
    schema::Schema,
};

/// An interned GraphQL name.
pub type Name = Arc<str>;

/// Above this many entries, a name-keyed definition map hashes instead of scanning.
///
/// Every lookup hashes otherwise, and almost every GraphQL type declares fewer fields, enum
/// values or arguments than this.
pub(crate) const SMALL_MAP_LIMIT: usize = 12;

/// Compare two GraphQL names.
///
/// Names are short and compared constantly — every field completion, every schema lookup and
/// every field collection compares one — and `str == str` compiles to a `memcmp` call whose
/// overhead dominates the handful of bytes actually compared. Walking the bytes inline is faster
/// for the lengths real documents use, and falls back to the slice comparison for the rare long
/// name.
#[inline]
pub(crate) fn names_eq(left: &str, right: &str) -> bool {
    let left = left.as_bytes();
    let right = right.as_bytes();
    if left.len() != right.len() {
        return false;
    }
    if left.len() > 8 {
        return left == right;
    }
    let mut index = 0;
    while index < left.len() {
        if left[index] != right[index] {
            return false;
        }
        index += 1;
    }
    true
}

/// Look up a name in a definition map, scanning instead of hashing while the map is small.
///
/// Execution performs these lookups for every field it completes and every argument it coerces,
/// and schema definitions overwhelmingly hold fewer entries than [`SMALL_MAP_LIMIT`].
pub(crate) fn map_get<'m, V>(map: &'m IndexMap<Name, V>, name: &str) -> Option<&'m V> {
    if map.len() <= SMALL_MAP_LIMIT {
        return map
            .iter()
            .find(|(key, _)| names_eq(key, name))
            .map(|(_, value)| value);
    }
    map.get(name)
}

/// The result of resolving a field.
pub type FieldResult = Result<Value, GraphQLError>;

/// A boxed future returned by an asynchronous resolver.
pub type ResolveFuture<'a> = futures::future::BoxFuture<'a, FieldResult>;

/// A boxed stream returned by a subscription resolver.
pub type SubscriptionStream = BoxStream<'static, FieldResult>;

/// A directive applied to a schema element.
///
/// `arguments` holds the directive's arguments in source order. Values parsed from SDL start as
/// the literal's runtime shape and code-first callers supply a runtime [`Value`]; when the schema
/// is built every argument is coerced to the input type declared by the directive definition,
/// using the same rules as field arguments (`ID` renders integers as strings, `Float` widens
/// integers, a custom scalar's `parse_value` runs, and built-in `Int` rejects values outside 32
/// bits). A wrong-typed argument makes the build fail.
///
/// Applied directives are preserved so `Schema::from_sdl` round-trips through
/// [`Schema::sdl`](crate::Schema::sdl), and so code-first schemas can describe directives that
/// have no dedicated field in the type model.
///
/// The built-in `@deprecated`, `@specifiedBy` and `@oneOf` directives are also recorded here
/// when they are parsed, but their authoritative data lives in the dedicated
/// `deprecation_reason`, `specified_by_url` and `one_of` fields.
/// [`SchemaBuilder`](crate::SchemaBuilder) copies a code-first application into those fields as
/// well, and the SDL printer reads the fields, so a built-in application is never lost or printed
/// twice.
#[derive(Clone, Debug, PartialEq)]
pub struct AppliedDirective {
    /// The directive's name without `@`.
    pub name: Name,
    /// Arguments in source order.
    pub arguments: IndexMap<Name, Value>,
}

impl AppliedDirective {
    /// Start defining an applied directive.
    #[must_use]
    pub fn new(name: impl Into<Name>) -> Self {
        Self {
            name: name.into(),
            arguments: IndexMap::new(),
        }
    }

    /// Add an argument.
    ///
    /// Directive arguments are ordered, so arguments print in the order they are added.
    #[must_use]
    pub fn argument(mut self, name: impl Into<Name>, value: impl Into<Value>) -> Self {
        self.arguments.insert(name.into(), value.into());
        self
    }

    /// Look up an argument by name.
    #[must_use]
    pub fn get_argument(&self, name: &str) -> Option<&Value> {
        map_get(&self.arguments, name)
    }
}

/// The kind of a named GraphQL type.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TypeKind {
    /// A scalar type.
    Scalar,
    /// An object type.
    Object,
    /// An interface type.
    Interface,
    /// A union type.
    Union,
    /// An enum type.
    Enum,
    /// An input object type.
    InputObject,
}

impl TypeKind {
    /// The name used by introspection.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Scalar => "SCALAR",
            Self::Object => "OBJECT",
            Self::Interface => "INTERFACE",
            Self::Union => "UNION",
            Self::Enum => "ENUM",
            Self::InputObject => "INPUT_OBJECT",
        }
    }
}

impl fmt::Display for TypeKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A reference to a type, possibly wrapped in list and non-null modifiers.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum TypeRef {
    /// A named type.
    Named(Name),
    /// A list of another type.
    List(Box<TypeRef>),
    /// A non-null version of another type.
    NonNull(Box<TypeRef>),
}

/// The interned name of a built-in type, when `name` is one.
///
/// Schema building and variable coercion turn type names from the document into `Arc<str>`s for
/// every request. The built-in names never change, so sharing one allocation for each of them
/// removes a handful of allocations (and their frees) from every request.
pub(crate) fn interned_builtin(name: &str) -> Option<Name> {
    static NAMES: [std::sync::OnceLock<Name>; 6] = [
        std::sync::OnceLock::new(),
        std::sync::OnceLock::new(),
        std::sync::OnceLock::new(),
        std::sync::OnceLock::new(),
        std::sync::OnceLock::new(),
        std::sync::OnceLock::new(),
    ];
    let index = match name {
        "String" => 0,
        "Int" => 1,
        "Float" => 2,
        "Boolean" => 3,
        "ID" => 4,
        "__Type" => 5,
        _ => return None,
    };
    Some(NAMES[index].get_or_init(|| Name::from(name)).clone())
}

impl TypeRef {
    /// A reference to a named type.
    #[must_use]
    pub fn named(name: impl Into<Name>) -> Self {
        Self::Named(name.into())
    }

    /// A reference to a named type, reusing the interned allocation for built-in names.
    pub(crate) fn named_str(name: &str) -> Self {
        Self::Named(interned_builtin(name).unwrap_or_else(|| Name::from(name)))
    }

    /// The built-in `String` type.
    #[must_use]
    pub fn string() -> Self {
        Self::Named("String".into())
    }

    /// The built-in `Int` type.
    #[must_use]
    pub fn int() -> Self {
        Self::Named("Int".into())
    }

    /// The built-in `Float` type.
    #[must_use]
    pub fn float() -> Self {
        Self::Named("Float".into())
    }

    /// The built-in `Boolean` type.
    #[must_use]
    pub fn boolean() -> Self {
        Self::Named("Boolean".into())
    }

    /// The built-in `ID` type.
    #[must_use]
    pub fn id() -> Self {
        Self::Named("ID".into())
    }

    /// Wrap this type in a list.
    #[must_use]
    pub fn list(self) -> Self {
        Self::List(Box::new(self))
    }

    /// Mark this type as non-null.
    #[must_use]
    pub fn non_null(self) -> Self {
        match self {
            Self::NonNull(_) => self,
            other => Self::NonNull(Box::new(other)),
        }
    }

    /// Remove a non-null wrapper, if present.
    #[must_use]
    pub fn nullable(self) -> Self {
        match self {
            Self::NonNull(inner) => *inner,
            other => other,
        }
    }

    /// The innermost named type.
    #[must_use]
    pub fn named_type(&self) -> &Name {
        match self {
            Self::Named(name) => name,
            Self::List(inner) | Self::NonNull(inner) => inner.named_type(),
        }
    }

    /// Whether the outermost modifier is non-null.
    #[must_use]
    pub const fn is_non_null(&self) -> bool {
        matches!(self, Self::NonNull(_))
    }

    /// Whether the outermost modifier is a list.
    #[must_use]
    pub const fn is_list(&self) -> bool {
        matches!(self, Self::List(_))
    }

    /// Whether this is a bare named type with no modifiers.
    #[must_use]
    pub const fn is_named(&self) -> bool {
        matches!(self, Self::Named(_))
    }

    /// The type of one list item, or `None` when this is not a list.
    #[must_use]
    pub fn list_item(&self) -> Option<&TypeRef> {
        match self {
            Self::List(inner) => Some(inner),
            Self::NonNull(inner) => inner.list_item(),
            Self::Named(_) => None,
        }
    }
}

impl fmt::Display for TypeRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Named(name) => f.write_str(name),
            Self::List(inner) => write!(f, "[{inner}]"),
            Self::NonNull(inner) => write!(f, "{inner}!"),
        }
    }
}

impl From<Name> for TypeRef {
    fn from(value: Name) -> Self {
        Self::Named(value)
    }
}

impl From<&str> for TypeRef {
    fn from(value: &str) -> Self {
        Self::Named(value.into())
    }
}

impl From<String> for TypeRef {
    fn from(value: String) -> Self {
        Self::Named(value.into())
    }
}

/// The signature of a scalar's output coercion function.
pub type ScalarSerializeFn = Arc<dyn Fn(&Value) -> Result<Value, String> + Send + Sync>;

/// The signature of a scalar's input coercion function for already-parsed runtime values.
pub type ScalarParseValueFn = Arc<dyn Fn(&Value) -> Result<Value, String> + Send + Sync>;

/// The signature of a scalar's input coercion function for literals.
pub type ScalarParseLiteralFn =
    Arc<dyn for<'a> Fn(&ast::Value<'a>) -> Result<Value, String> + Send + Sync>;

/// A scalar type.
#[derive(Clone)]
pub struct ScalarType {
    /// The scalar's name.
    pub name: Name,
    /// An optional description.
    pub description: Option<Arc<str>>,
    /// An optional `@specifiedBy` URL.
    pub specified_by_url: Option<Arc<str>>,
    /// Directives applied to the scalar, in application order.
    pub directives: Vec<AppliedDirective>,
    pub(crate) serialize: Option<ScalarSerializeFn>,
    pub(crate) parse_value: Option<ScalarParseValueFn>,
    pub(crate) parse_literal: Option<ScalarParseLiteralFn>,
    /// Whether `serialize` is one of the specification's built-in coercion functions.
    ///
    /// Execution may run the built-in functions more than once (a fast path that later falls back
    /// re-completes a field), which is only sound for code the engine owns. Any scalar built or
    /// customised by the user is not marked, so its function runs exactly once.
    pub(crate) builtin: bool,
}

impl fmt::Debug for ScalarType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScalarType")
            .field("name", &self.name)
            .field("description", &self.description)
            .field("specified_by_url", &self.specified_by_url)
            .field("directives", &self.directives)
            .finish_non_exhaustive()
    }
}

impl ScalarType {
    /// Start defining a custom scalar.
    ///
    /// By default the scalar is transparent: values pass through unchanged. Attach coercion
    /// functions with [`ScalarType::parse_value`], [`ScalarType::parse_literal`] and
    /// [`ScalarType::serialize`] when the representation needs validating.
    #[must_use]
    pub fn new(name: impl Into<Name>) -> Self {
        Self {
            name: name.into(),
            description: None,
            specified_by_url: None,
            directives: Vec::new(),
            serialize: None,
            parse_value: None,
            parse_literal: None,
            builtin: false,
        }
    }

    /// Mark this scalar as carrying one of the specification's built-in coercion functions.
    ///
    /// Only the built-in constructors call this, and only after installing their own `serialize`.
    fn builtin(mut self) -> Self {
        self.builtin = true;
        self
    }

    /// Set the description.
    #[must_use]
    pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set the `@specifiedBy` URL.
    #[must_use]
    pub fn specified_by_url(mut self, url: impl Into<Arc<str>>) -> Self {
        self.specified_by_url = Some(url.into());
        self
    }

    /// Add an applied directive.
    #[must_use]
    pub fn directive(mut self, directive: AppliedDirective) -> Self {
        self.directives.push(directive);
        self
    }

    /// Set the output coercion function.
    #[must_use]
    pub fn serialize(
        mut self,
        function: impl Fn(&Value) -> Result<Value, String> + Send + Sync + 'static,
    ) -> Self {
        self.serialize = Some(Arc::new(function));
        // A user-provided (or user-replaced) function is not the built-in one, so the fast paths
        // must not run it speculatively.
        self.builtin = false;
        self
    }

    /// Set the input coercion function for runtime values.
    #[must_use]
    pub fn parse_value(
        mut self,
        function: impl Fn(&Value) -> Result<Value, String> + Send + Sync + 'static,
    ) -> Self {
        self.parse_value = Some(Arc::new(function));
        self
    }

    /// Set the input coercion function for literals.
    #[must_use]
    pub fn parse_literal(
        mut self,
        function: impl for<'a> Fn(&ast::Value<'a>) -> Result<Value, String> + Send + Sync + 'static,
    ) -> Self {
        self.parse_literal = Some(Arc::new(function));
        self
    }

    /// The built-in `String` scalar.
    #[must_use]
    pub fn string() -> Self {
        Self::new("String")
            .description("The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.")
            .serialize(|value| match value {
                Value::String(value) => Ok(Value::String(value.clone())),
                _ => Err(format!("String cannot represent a value of type {}", value.kind())),
            })
            .parse_value(|value| match value {
                Value::String(value) => Ok(Value::String(value.clone())),
                _ => Err(format!("String cannot represent a value of type {}", value.kind())),
            })
            .parse_literal(|value| match value {
                ast::Value::String(value) => Ok(Value::String(Arc::from(value.as_ref()))),
                _ => Err("String cannot represent a non-string literal".into()),
            })
            .builtin()
    }

    /// The built-in `Int` scalar.
    #[must_use]
    pub fn int() -> Self {
        Self::new("Int")
            .description("The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.")
            .serialize(|value| match value {
                Value::Int(value) => Ok(Value::Int(*value)),
                Value::BigInt(value) => i32::try_from(**value)
                    .map(Value::Int)
                    .map_err(|_| "Int cannot represent non 32-bit signed integer value".into()),
                _ => Err(format!("Int cannot represent a value of type {}", value.kind())),
            })
            .parse_value(|value| match value {
                Value::Int(value) => Ok(Value::Int(*value)),
                Value::BigInt(value) => i32::try_from(**value)
                    .map(Value::Int)
                    .map_err(|_| "Int cannot represent non 32-bit signed integer value".into()),
                _ => Err(format!("Int cannot represent a value of type {}", value.kind())),
            })
            .parse_literal(|value| match value {
                ast::Value::Int(value) => i32::try_from(*value)
                    .map(Value::Int)
                    .map_err(|_| "Int cannot represent non 32-bit signed integer value".into()),
                _ => Err("Int cannot represent a non-integer literal".into()),
            })
            .builtin()
    }

    /// The built-in `Float` scalar.
    #[must_use]
    pub fn float() -> Self {
        Self::new("Float")
            .description("The `Float` scalar type represents signed double-precision fractional values as specified by IEEE 754.")
            .serialize(|value| match value {
                Value::Float(value) if value.is_finite() => Ok(Value::Float(*value)),
                Value::Int(value) => Ok(Value::Float(f64::from(*value))),
                Value::BigInt(value) => Ok(Value::Float(**value as f64)),
                Value::Float(_) => Err("Float cannot represent a non-finite value".into()),
                _ => Err(format!("Float cannot represent a value of type {}", value.kind())),
            })
            .parse_value(|value| match value {
                Value::Float(value) if value.is_finite() => Ok(Value::Float(*value)),
                Value::Int(value) => Ok(Value::Float(f64::from(*value))),
                Value::BigInt(value) => Ok(Value::Float(**value as f64)),
                Value::Float(_) => Err("Float cannot represent a non-finite value".into()),
                _ => Err(format!("Float cannot represent a value of type {}", value.kind())),
            })
            .parse_literal(|value| match value {
                ast::Value::Float(value) if value.is_finite() => Ok(Value::Float(*value)),
                ast::Value::Float(_) => Err("Float cannot represent a non-finite value".into()),
                ast::Value::Int(value) => Ok(Value::Float(*value as f64)),
                _ => Err("Float cannot represent a non-numeric literal".into()),
            })
            .builtin()
    }

    /// The built-in `Boolean` scalar.
    #[must_use]
    pub fn boolean() -> Self {
        Self::new("Boolean")
            .description("The `Boolean` scalar type represents `true` or `false`.")
            .serialize(|value| match value {
                Value::Boolean(value) => Ok(Value::Boolean(*value)),
                _ => Err(format!(
                    "Boolean cannot represent a value of type {}",
                    value.kind()
                )),
            })
            .parse_value(|value| match value {
                Value::Boolean(value) => Ok(Value::Boolean(*value)),
                _ => Err(format!(
                    "Boolean cannot represent a value of type {}",
                    value.kind()
                )),
            })
            .parse_literal(|value| match value {
                ast::Value::Boolean(value) => Ok(Value::Boolean(*value)),
                _ => Err("Boolean cannot represent a non-boolean literal".into()),
            })
            .builtin()
    }

    /// The built-in `ID` scalar.
    ///
    /// The specification serializes IDs as strings even when provided as integers.
    #[must_use]
    pub fn id() -> Self {
        Self::new("ID")
            .description("The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `\"4\"`) or integer (such as `4`) input value will be accepted as an ID.")
            .serialize(|value| match value {
                Value::String(value) | Value::Enum(value) => Ok(Value::String(value.clone())),
                Value::Int(value) => Ok(Value::String(Arc::from(value.to_string()))),
                Value::BigInt(value) => Ok(Value::String(Arc::from(value.to_string()))),
                _ => Err(format!("ID cannot represent a value of type {}", value.kind())),
            })
            .parse_value(|value| match value {
                Value::String(value) | Value::Enum(value) => Ok(Value::String(value.clone())),
                Value::Int(value) => Ok(Value::String(Arc::from(value.to_string()))),
                Value::BigInt(value) => Ok(Value::String(Arc::from(value.to_string()))),
                _ => Err(format!("ID cannot represent a value of type {}", value.kind())),
            })
            .parse_literal(|value| match value {
                ast::Value::String(value) => Ok(Value::String(Arc::from(value.as_ref()))),
                ast::Value::Int(value) => Ok(Value::String(Arc::from(value.to_string()))),
                _ => Err("ID cannot represent a non-string and non-integer literal".into()),
            })
            .builtin()
    }

    /// The output coercion function, if one was registered.
    #[must_use]
    pub fn serialize_fn(&self) -> Option<&ScalarSerializeFn> {
        self.serialize.as_ref()
    }

    /// The runtime input coercion function, if one was registered.
    #[must_use]
    pub fn parse_value_fn(&self) -> Option<&ScalarParseValueFn> {
        self.parse_value.as_ref()
    }

    /// The literal input coercion function, if one was registered.
    #[must_use]
    pub fn parse_literal_fn(&self) -> Option<&ScalarParseLiteralFn> {
        self.parse_literal.as_ref()
    }
}

/// One value of an enum type.
///
/// This is `PartialEq` but not `Eq`, because [`Self::directives`] holds [`Value`]s and
/// [`Value::Float`] contains an `f64`. Equality is therefore the usual IEEE-754 comparison
/// (`NaN != NaN`) and cannot honestly implement `Eq`.
#[derive(Clone, Debug, PartialEq)]
pub struct EnumValue {
    /// The value's name.
    pub name: Name,
    /// An optional description.
    pub description: Option<Arc<str>>,
    /// Why the value is deprecated, when it is.
    pub deprecation_reason: Option<Arc<str>>,
    /// Directives applied to the value, in application order.
    pub directives: Vec<AppliedDirective>,
}

impl EnumValue {
    /// Add an applied directive.
    #[must_use]
    pub fn directive(mut self, directive: AppliedDirective) -> Self {
        self.directives.push(directive);
        self
    }
}

/// An enum type.
#[derive(Clone, Debug)]
pub struct EnumType {
    /// The enum's name.
    pub name: Name,
    /// An optional description.
    pub description: Option<Arc<str>>,
    /// Values in definition order.
    pub values: IndexMap<Name, EnumValue>,
    /// Directives applied to the enum, in application order.
    pub directives: Vec<AppliedDirective>,
    /// Duplicate value names encountered while building, reported by schema validation.
    pub(crate) duplicates: Vec<Name>,
}

impl EnumType {
    /// Start defining an enum.
    #[must_use]
    pub fn new(name: impl Into<Name>) -> Self {
        Self {
            name: name.into(),
            description: None,
            values: IndexMap::new(),
            directives: Vec::new(),
            duplicates: Vec::new(),
        }
    }

    /// Set the description.
    #[must_use]
    pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Add an applied directive.
    #[must_use]
    pub fn directive(mut self, directive: AppliedDirective) -> Self {
        self.directives.push(directive);
        self
    }

    /// Add a value.
    #[must_use]
    pub fn value(mut self, name: impl Into<Name>) -> Self {
        let name = name.into();
        if self.values.contains_key(&name) {
            self.duplicates.push(name.clone());
        }
        self.values.insert(
            name.clone(),
            EnumValue {
                name,
                description: None,
                deprecation_reason: None,
                directives: Vec::new(),
            },
        );
        self
    }

    /// Add a described value.
    #[must_use]
    pub fn value_with(
        mut self,
        name: impl Into<Name>,
        description: Option<Arc<str>>,
        deprecation_reason: Option<Arc<str>>,
    ) -> Self {
        let name = name.into();
        if self.values.contains_key(&name) {
            self.duplicates.push(name.clone());
        }
        self.values.insert(
            name.clone(),
            EnumValue {
                name,
                description,
                deprecation_reason,
                directives: Vec::new(),
            },
        );
        self
    }

    /// Whether a value name is defined.
    #[must_use]
    pub fn has_value(&self, name: &str) -> bool {
        map_get(&self.values, name).is_some()
    }
}

/// An input value: a field argument or an input object field.
#[derive(Clone, Debug)]
pub struct InputValue {
    /// The name.
    pub name: Name,
    /// An optional description.
    pub description: Option<Arc<str>>,
    /// The input type.
    pub ty: TypeRef,
    /// The default value, already in runtime form.
    pub default_value: Option<Value>,
    /// Whether the input value is deprecated.
    pub deprecation_reason: Option<Arc<str>>,
    /// Directives applied to the input value, in application order.
    pub directives: Vec<AppliedDirective>,
}

impl InputValue {
    /// Start defining an input value.
    #[must_use]
    pub fn new(name: impl Into<Name>, ty: TypeRef) -> Self {
        Self {
            name: name.into(),
            description: None,
            ty,
            default_value: None,
            deprecation_reason: None,
            directives: Vec::new(),
        }
    }

    /// Set the description.
    #[must_use]
    pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Add an applied directive.
    #[must_use]
    pub fn directive(mut self, directive: AppliedDirective) -> Self {
        self.directives.push(directive);
        self
    }

    /// Set the default value.
    #[must_use]
    pub fn default_value(mut self, value: impl Into<Value>) -> Self {
        self.default_value = Some(value.into());
        self
    }

    /// Mark the input value as deprecated.
    #[must_use]
    pub fn deprecation_reason(mut self, reason: impl Into<Arc<str>>) -> Self {
        self.deprecation_reason = Some(reason.into());
        self
    }
}

/// An input object type.
#[derive(Clone, Debug)]
pub struct InputObjectType {
    /// The type's name.
    pub name: Name,
    /// An optional description.
    pub description: Option<Arc<str>>,
    /// Fields in definition order.
    pub fields: IndexMap<Name, InputValue>,
    /// Whether this is a `@oneOf` input object.
    pub one_of: bool,
    /// Directives applied to the input object, in application order.
    pub directives: Vec<AppliedDirective>,
    /// Duplicate field names encountered while building, reported by schema validation.
    pub(crate) duplicates: Vec<Name>,
}

impl InputObjectType {
    /// Start defining an input object.
    #[must_use]
    pub fn new(name: impl Into<Name>) -> Self {
        Self {
            name: name.into(),
            description: None,
            fields: IndexMap::new(),
            one_of: false,
            directives: Vec::new(),
            duplicates: Vec::new(),
        }
    }

    /// Set the description.
    #[must_use]
    pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Add an applied directive.
    #[must_use]
    pub fn directive(mut self, directive: AppliedDirective) -> Self {
        self.directives.push(directive);
        self
    }

    /// Add a field.
    #[must_use]
    pub fn field(mut self, field: InputValue) -> Self {
        if self.fields.contains_key(&field.name) {
            self.duplicates.push(field.name.clone());
        }
        self.fields.insert(field.name.clone(), field);
        self
    }

    /// Insert a field into an existing input object definition, reporting duplicates through
    /// schema validation.
    pub fn insert_field(&mut self, field: InputValue) {
        if self.fields.contains_key(&field.name) {
            self.duplicates.push(field.name.clone());
        }
        self.fields.insert(field.name.clone(), field);
    }

    /// Mark the input object as `@oneOf`.
    #[must_use]
    pub fn one_of(mut self) -> Self {
        self.one_of = true;
        self
    }
}

/// A field definition.
#[derive(Clone)]
pub struct Field {
    /// The field's name.
    pub name: Name,
    /// An optional description.
    pub description: Option<Arc<str>>,
    /// Arguments in definition order.
    pub args: IndexMap<Name, InputValue>,
    /// The field's output type.
    pub ty: TypeRef,
    /// Why the field is deprecated, when it is.
    pub deprecation_reason: Option<Arc<str>>,
    /// Directives applied to the field, in application order.
    pub directives: Vec<AppliedDirective>,
    /// The field's resolver. `None` uses the default property resolver.
    pub resolve: Option<ResolveFn>,
    /// The field's subscription resolver, used when the field is a subscription root field.
    pub subscribe: Option<SubscribeFn>,
    /// An optional complexity estimator for this field.
    pub complexity: Option<ComplexityFn>,
    /// Duplicate argument names encountered while building, reported by schema validation.
    pub(crate) duplicate_args: Vec<Name>,
    /// Where the output type's innermost named type lives in the schema's type map.
    ///
    /// Execution needs the resolved type for every field it completes, and a positional lookup
    /// avoids hashing the type name each time. `None` means the reference was never resolved (the
    /// field does not belong to a built schema, or names a type the schema does not define).
    pub(crate) type_index: Option<u32>,
}

impl fmt::Debug for Field {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Field")
            .field("name", &self.name)
            .field("description", &self.description)
            .field("args", &self.args)
            .field("ty", &self.ty)
            .field("deprecation_reason", &self.deprecation_reason)
            .field("directives", &self.directives)
            .field("resolve", &self.resolve.is_some())
            .field("subscribe", &self.subscribe.is_some())
            .finish()
    }
}

impl Field {
    /// Start defining a field.
    #[must_use]
    pub fn new(name: impl Into<Name>, ty: TypeRef) -> Self {
        Self {
            name: name.into(),
            description: None,
            args: IndexMap::new(),
            ty,
            deprecation_reason: None,
            directives: Vec::new(),
            resolve: None,
            subscribe: None,
            complexity: None,
            duplicate_args: Vec::new(),
            type_index: None,
        }
    }

    /// Set the description.
    #[must_use]
    pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Add an argument.
    #[must_use]
    pub fn arg(mut self, argument: InputValue) -> Self {
        if self.args.contains_key(&argument.name) {
            self.duplicate_args.push(argument.name.clone());
        }
        self.args.insert(argument.name.clone(), argument);
        self
    }

    /// Mark the field as deprecated.
    #[must_use]
    pub fn deprecation_reason(mut self, reason: impl Into<Arc<str>>) -> Self {
        self.deprecation_reason = Some(reason.into());
        self
    }

    /// Add an applied directive.
    #[must_use]
    pub fn directive(mut self, directive: AppliedDirective) -> Self {
        self.directives.push(directive);
        self
    }

    /// Set the resolver.
    #[must_use]
    pub fn resolve(
        mut self,
        resolve: impl for<'a> Fn(ResolverContext<'a>) -> ResolveFuture<'a> + Send + Sync + 'static,
    ) -> Self {
        self.resolve = Some(Arc::new(resolve));
        self
    }

    /// Set the subscription resolver.
    #[must_use]
    pub fn subscribe(
        mut self,
        subscribe: impl for<'a> Fn(
            ResolverContext<'a>,
        ) -> futures::future::BoxFuture<
            'a,
            Result<SubscriptionStream, GraphQLError>,
        > + Send
        + Sync
        + 'static,
    ) -> Self {
        self.subscribe = Some(Arc::new(subscribe));
        self
    }

    /// Set the field's complexity estimator.
    #[must_use]
    pub fn complexity(
        mut self,
        estimator: impl Fn(&crate::Object) -> u32 + Send + Sync + 'static,
    ) -> Self {
        self.complexity = Some(Arc::new(estimator));
        self
    }
}

/// The signature of a field resolver.
pub type ResolveFn =
    Arc<dyn for<'a> Fn(ResolverContext<'a>) -> ResolveFuture<'a> + Send + Sync + 'static>;

/// The signature of a subscription resolver.
pub type SubscribeFn = Arc<
    dyn for<'a> Fn(
            ResolverContext<'a>,
        )
            -> futures::future::BoxFuture<'a, Result<SubscriptionStream, GraphQLError>>
        + Send
        + Sync
        + 'static,
>;

/// The signature of a field complexity estimator.
pub type ComplexityFn = Arc<dyn Fn(&crate::Object) -> u32 + Send + Sync + 'static>;

/// Information about the field being resolved.
#[derive(Debug)]
pub struct ResolveInfo<'a> {
    /// The field's name in the schema.
    pub field_name: &'a str,
    /// The name of the parent type.
    pub parent_type: &'a str,
    /// The field's declared return type.
    pub return_type: &'a TypeRef,
    /// The path from the response root to this field.
    pub path: &'a [PathSegment],
    /// The schema being executed.
    pub schema: &'a Schema,
    /// Every field node merged into the field currently being resolved.
    ///
    /// Duplicate selections, aliases and fields reached through fragments all contribute a node
    /// here, in document order. This is the selection information a resolver needs to implement
    /// projections, batched loaders or other selection-aware behaviour.
    ///
    /// The nodes are always value-correct. In ordinary execution they are the exact nodes of
    /// [`ResolveInfo::operation`]; prepared execution compiles a plan that owns its own cloned
    /// nodes, so there the nodes compare equal by value but are not pointer-identical to nodes
    /// reachable from `operation`. Resolvers should compare names, arguments and locations rather
    /// than addresses.
    pub field_nodes: ast::FieldNodes<'a>,
    /// The operation definition being executed.
    ///
    /// `None` only for the rare synthetic resolver context that has no document, such as a
    /// manually constructed [`ResolveInfo::new`] used by a test helper.
    pub operation: Option<&'a ast::OperationDefinition<'a>>,
    /// The document's fragment definitions, for resolving a spread named in
    /// [`ResolveInfo::field_nodes`].
    pub fragments: &'a Fragments<'a>,
    /// The operation's root value, as supplied by the request.
    ///
    /// Root field resolvers receive this same value as `parent`. Subscription events use the
    /// source event as their root value, matching the specification.
    pub root_value: &'a Value,
    /// The coerced variable values for this request, including defaults.
    pub variables: &'a crate::Object,
}

/// An empty root value used by [`ResolveInfo::new`].
static EMPTY_ROOT_VALUE: Value = Value::Null;
/// Empty variables used by [`ResolveInfo::new`].
static EMPTY_VARIABLES: std::sync::LazyLock<crate::Object> =
    std::sync::LazyLock::new(crate::Object::new);
/// An empty fragment lookup used by [`ResolveInfo::new`].
static EMPTY_FRAGMENTS: std::sync::LazyLock<Fragments<'static>> =
    std::sync::LazyLock::new(Fragments::empty);

impl<'a> ResolveInfo<'a> {
    /// Build field information without selection context.
    ///
    /// Execution populates the selection fields itself. This constructor is for callers that
    /// invoke a resolver directly (introspection tooling, tests, custom dispatchers); chain the
    /// `with_*` methods to attach context.
    #[must_use]
    pub fn new(
        field_name: &'a str,
        parent_type: &'a str,
        return_type: &'a TypeRef,
        path: &'a [PathSegment],
        schema: &'a Schema,
    ) -> Self {
        Self {
            field_name,
            parent_type,
            return_type,
            path,
            schema,
            field_nodes: ast::FieldNodes::empty(),
            operation: None,
            fragments: &EMPTY_FRAGMENTS,
            root_value: &EMPTY_ROOT_VALUE,
            variables: &EMPTY_VARIABLES,
        }
    }

    /// Attach the merged field nodes being resolved.
    #[must_use]
    pub fn with_field_nodes(mut self, field_nodes: ast::FieldNodes<'a>) -> Self {
        self.field_nodes = field_nodes;
        self
    }

    /// Attach the operation definition being executed.
    #[must_use]
    pub fn with_operation(mut self, operation: &'a ast::OperationDefinition<'a>) -> Self {
        self.operation = Some(operation);
        self
    }

    /// Attach the document's fragment definitions.
    #[must_use]
    pub fn with_fragments(mut self, fragments: &'a Fragments<'a>) -> Self {
        self.fragments = fragments;
        self
    }

    /// Attach the operation's root value.
    #[must_use]
    pub fn with_root_value(mut self, root_value: &'a Value) -> Self {
        self.root_value = root_value;
        self
    }

    /// Attach the request's coerced variables.
    #[must_use]
    pub fn with_variables(mut self, variables: &'a crate::Object) -> Self {
        self.variables = variables;
        self
    }
}

/// Everything a resolver can see about the current field.
pub struct ResolverContext<'a> {
    /// The value of the parent object, or the operation root value.
    pub parent: &'a Value,
    /// Coerced arguments, with defaults applied.
    pub args: &'a crate::Object,
    /// Per-request execution state.
    pub context: &'a ExecutionContext,
    /// Static and dynamic information about the field.
    pub info: &'a ResolveInfo<'a>,
}

impl fmt::Debug for ResolverContext<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ResolverContext")
            .field("parent", &self.parent)
            .field("args", &self.args)
            .field("info", &self.info)
            .finish_non_exhaustive()
    }
}

/// The signature of an abstract type resolver.
pub type ResolveTypeFn =
    Arc<dyn Fn(&Value, &ExecutionContext) -> Result<Name, GraphQLError> + Send + Sync + 'static>;

/// An object type.
#[derive(Clone)]
pub struct ObjectType {
    /// The type's name.
    pub name: Name,
    /// An optional description.
    pub description: Option<Arc<str>>,
    /// Fields in definition order.
    pub fields: IndexMap<Name, Field>,
    /// Names of interfaces implemented by this object.
    pub interfaces: Vec<Name>,
    /// Directives applied to the object, in application order.
    pub directives: Vec<AppliedDirective>,
    /// Optional runtime type check used when resolving abstract types.
    pub is_type_of: Option<Arc<dyn Fn(&Value) -> bool + Send + Sync>>,
    /// Duplicate field names encountered while building, reported by schema validation.
    pub(crate) duplicates: Vec<Name>,
}

impl fmt::Debug for ObjectType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ObjectType")
            .field("name", &self.name)
            .field("description", &self.description)
            .field("fields", &self.fields)
            .field("interfaces", &self.interfaces)
            .field("directives", &self.directives)
            .finish_non_exhaustive()
    }
}

impl ObjectType {
    /// Start defining an object type.
    #[must_use]
    pub fn new(name: impl Into<Name>) -> Self {
        Self {
            name: name.into(),
            description: None,
            fields: IndexMap::new(),
            interfaces: Vec::new(),
            directives: Vec::new(),
            is_type_of: None,
            duplicates: Vec::new(),
        }
    }

    /// Set the description.
    #[must_use]
    pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Add an applied directive.
    #[must_use]
    pub fn directive(mut self, directive: AppliedDirective) -> Self {
        self.directives.push(directive);
        self
    }

    /// Add a field.
    #[must_use]
    pub fn field(mut self, field: Field) -> Self {
        if self.fields.contains_key(&field.name) {
            self.duplicates.push(field.name.clone());
        }
        self.fields.insert(field.name.clone(), field);
        self
    }

    /// Add an implemented interface by name.
    #[must_use]
    pub fn implements(mut self, interface: impl Into<Name>) -> Self {
        self.interfaces.push(interface.into());
        self
    }

    /// Set the runtime type check.
    #[must_use]
    pub fn is_type_of(mut self, check: impl Fn(&Value) -> bool + Send + Sync + 'static) -> Self {
        self.is_type_of = Some(Arc::new(check));
        self
    }

    /// Insert a field into an existing object definition, reporting duplicates through schema
    /// validation.
    pub fn insert_field(&mut self, field: Field) {
        if self.fields.contains_key(&field.name) {
            self.duplicates.push(field.name.clone());
        }
        self.fields.insert(field.name.clone(), field);
    }

    /// Look up a field by name.
    ///
    /// Most object types declare a handful of fields, where comparing interned names in order
    /// beats computing a hash for every lookup — and execution looks up a field's definition for
    /// every field it completes. Larger types keep the hash map's constant lookup.
    #[must_use]
    pub fn get_field(&self, name: &str) -> Option<&Field> {
        map_get(&self.fields, name)
    }
}

/// An interface type.
#[derive(Clone)]
pub struct InterfaceType {
    /// The type's name.
    pub name: Name,
    /// An optional description.
    pub description: Option<Arc<str>>,
    /// Fields in definition order.
    pub fields: IndexMap<Name, Field>,
    /// Names of interfaces implemented by this interface.
    pub interfaces: Vec<Name>,
    /// Directives applied to the interface, in application order.
    pub directives: Vec<AppliedDirective>,
    /// Resolves a runtime value to the name of its concrete object type.
    pub resolve_type: Option<ResolveTypeFn>,
    /// Duplicate field names encountered while building, reported by schema validation.
    pub(crate) duplicates: Vec<Name>,
}

impl fmt::Debug for InterfaceType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InterfaceType")
            .field("name", &self.name)
            .field("description", &self.description)
            .field("fields", &self.fields)
            .field("interfaces", &self.interfaces)
            .field("directives", &self.directives)
            .finish_non_exhaustive()
    }
}

impl InterfaceType {
    /// Start defining an interface.
    #[must_use]
    pub fn new(name: impl Into<Name>) -> Self {
        Self {
            name: name.into(),
            description: None,
            fields: IndexMap::new(),
            interfaces: Vec::new(),
            directives: Vec::new(),
            resolve_type: None,
            duplicates: Vec::new(),
        }
    }

    /// Set the description.
    #[must_use]
    pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Add an applied directive.
    #[must_use]
    pub fn directive(mut self, directive: AppliedDirective) -> Self {
        self.directives.push(directive);
        self
    }

    /// Add a field definition.
    #[must_use]
    pub fn field(mut self, field: Field) -> Self {
        if self.fields.contains_key(&field.name) {
            self.duplicates.push(field.name.clone());
        }
        self.fields.insert(field.name.clone(), field);
        self
    }

    /// Add an implemented interface by name.
    #[must_use]
    pub fn implements(mut self, interface: impl Into<Name>) -> Self {
        self.interfaces.push(interface.into());
        self
    }

    /// Insert a field into an existing interface definition, reporting duplicates through schema
    /// validation.
    pub fn insert_field(&mut self, field: Field) {
        if self.fields.contains_key(&field.name) {
            self.duplicates.push(field.name.clone());
        }
        self.fields.insert(field.name.clone(), field);
    }

    /// Set the abstract type resolver.
    #[must_use]
    pub fn resolve_type(
        mut self,
        resolve: impl Fn(&Value, &ExecutionContext) -> Result<Name, GraphQLError>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.resolve_type = Some(Arc::new(resolve));
        self
    }
    /// Look up a field by name.
    #[must_use]
    pub fn get_field(&self, name: &str) -> Option<&Field> {
        map_get(&self.fields, name)
    }
}

/// A union type.
#[derive(Clone)]
pub struct UnionType {
    /// The type's name.
    pub name: Name,
    /// An optional description.
    pub description: Option<Arc<str>>,
    /// Member object type names.
    pub types: Vec<Name>,
    /// Directives applied to the union, in application order.
    pub directives: Vec<AppliedDirective>,
    /// Resolves a runtime value to the name of its concrete object type.
    pub resolve_type: Option<ResolveTypeFn>,
}

impl fmt::Debug for UnionType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("UnionType")
            .field("name", &self.name)
            .field("description", &self.description)
            .field("types", &self.types)
            .field("directives", &self.directives)
            .finish_non_exhaustive()
    }
}

impl UnionType {
    /// Start defining a union.
    #[must_use]
    pub fn new(name: impl Into<Name>) -> Self {
        Self {
            name: name.into(),
            description: None,
            types: Vec::new(),
            directives: Vec::new(),
            resolve_type: None,
        }
    }

    /// Set the description.
    #[must_use]
    pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Add an applied directive.
    #[must_use]
    pub fn directive(mut self, directive: AppliedDirective) -> Self {
        self.directives.push(directive);
        self
    }

    /// Add a member object type by name.
    #[must_use]
    pub fn member(mut self, ty: impl Into<Name>) -> Self {
        self.types.push(ty.into());
        self
    }

    /// Set the abstract type resolver.
    #[must_use]
    pub fn resolve_type(
        mut self,
        resolve: impl Fn(&Value, &ExecutionContext) -> Result<Name, GraphQLError>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.resolve_type = Some(Arc::new(resolve));
        self
    }
}

/// A named type definition.
#[derive(Clone, Debug)]
pub enum Type {
    /// A scalar.
    Scalar(Arc<ScalarType>),
    /// An object.
    Object(Arc<ObjectType>),
    /// An interface.
    Interface(Arc<InterfaceType>),
    /// A union.
    Union(Arc<UnionType>),
    /// An enum.
    Enum(Arc<EnumType>),
    /// An input object.
    InputObject(Arc<InputObjectType>),
}

impl Type {
    /// The type's name.
    #[must_use]
    pub fn name(&self) -> &Name {
        match self {
            Self::Scalar(ty) => &ty.name,
            Self::Object(ty) => &ty.name,
            Self::Interface(ty) => &ty.name,
            Self::Union(ty) => &ty.name,
            Self::Enum(ty) => &ty.name,
            Self::InputObject(ty) => &ty.name,
        }
    }

    /// The type's kind.
    #[must_use]
    pub const fn kind(&self) -> TypeKind {
        match self {
            Self::Scalar(_) => TypeKind::Scalar,
            Self::Object(_) => TypeKind::Object,
            Self::Interface(_) => TypeKind::Interface,
            Self::Union(_) => TypeKind::Union,
            Self::Enum(_) => TypeKind::Enum,
            Self::InputObject(_) => TypeKind::InputObject,
        }
    }

    /// Whether the type may be used as an input type.
    #[must_use]
    pub const fn is_input_type(&self) -> bool {
        matches!(self, Self::Scalar(_) | Self::Enum(_) | Self::InputObject(_))
    }

    /// Whether the type may be used as an output type.
    #[must_use]
    pub const fn is_output_type(&self) -> bool {
        !matches!(self, Self::InputObject(_))
    }

    /// Whether the type is a leaf type (scalar or enum).
    #[must_use]
    pub const fn is_leaf(&self) -> bool {
        matches!(self, Self::Scalar(_) | Self::Enum(_))
    }

    /// Whether the type is a composite type (object, interface or union).
    #[must_use]
    pub const fn is_composite(&self) -> bool {
        matches!(self, Self::Object(_) | Self::Interface(_) | Self::Union(_))
    }

    /// Borrow as a scalar, when this is one.
    #[must_use]
    pub fn as_scalar(&self) -> Option<&Arc<ScalarType>> {
        match self {
            Self::Scalar(ty) => Some(ty),
            _ => None,
        }
    }

    /// Borrow as an object, when this is one.
    #[must_use]
    pub fn as_object(&self) -> Option<&Arc<ObjectType>> {
        match self {
            Self::Object(ty) => Some(ty),
            _ => None,
        }
    }

    /// Borrow as an interface, when this is one.
    #[must_use]
    pub fn as_interface(&self) -> Option<&Arc<InterfaceType>> {
        match self {
            Self::Interface(ty) => Some(ty),
            _ => None,
        }
    }

    /// Borrow as a union, when this is one.
    #[must_use]
    pub fn as_union(&self) -> Option<&Arc<UnionType>> {
        match self {
            Self::Union(ty) => Some(ty),
            _ => None,
        }
    }

    /// Borrow as an enum, when this is one.
    #[must_use]
    pub fn as_enum(&self) -> Option<&Arc<EnumType>> {
        match self {
            Self::Enum(ty) => Some(ty),
            _ => None,
        }
    }

    /// Borrow as an input object, when this is one.
    #[must_use]
    pub fn as_input_object(&self) -> Option<&Arc<InputObjectType>> {
        match self {
            Self::InputObject(ty) => Some(ty),
            _ => None,
        }
    }
}

impl From<ScalarType> for Type {
    fn from(value: ScalarType) -> Self {
        Self::Scalar(Arc::new(value))
    }
}

impl From<ObjectType> for Type {
    fn from(value: ObjectType) -> Self {
        Self::Object(Arc::new(value))
    }
}

impl From<InterfaceType> for Type {
    fn from(value: InterfaceType) -> Self {
        Self::Interface(Arc::new(value))
    }
}

impl From<UnionType> for Type {
    fn from(value: UnionType) -> Self {
        Self::Union(Arc::new(value))
    }
}

impl From<EnumType> for Type {
    fn from(value: EnumType) -> Self {
        Self::Enum(Arc::new(value))
    }
}

impl From<InputObjectType> for Type {
    fn from(value: InputObjectType) -> Self {
        Self::InputObject(Arc::new(value))
    }
}

/// A directive definition.
#[derive(Clone, Debug)]
pub struct DirectiveDefinition {
    /// The directive's name without `@`.
    pub name: Name,
    /// An optional description.
    pub description: Option<Arc<str>>,
    /// Arguments in definition order.
    pub args: IndexMap<Name, InputValue>,
    /// Locations where the directive may appear.
    pub locations: Vec<ast::DirectiveLocation>,
    /// Whether the directive may be repeated in a single location.
    pub repeatable: bool,
    /// Directives applied to the definition itself, in application order.
    ///
    /// `@deprecated` is also recorded here; its authoritative reason lives in
    /// `deprecation_reason`. The SDL printer reads that field and skips the dedicated directive,
    /// so an application is never printed twice.
    pub directives: Vec<AppliedDirective>,
    /// Why the directive is deprecated, when it is.
    pub deprecation_reason: Option<Arc<str>>,
    /// Duplicate argument names encountered while building, reported by schema validation.
    pub(crate) duplicate_args: Vec<Name>,
}

impl DirectiveDefinition {
    /// Start defining a directive.
    #[must_use]
    pub fn new(name: impl Into<Name>) -> Self {
        Self {
            name: name.into(),
            description: None,
            args: IndexMap::new(),
            locations: Vec::new(),
            repeatable: false,
            directives: Vec::new(),
            deprecation_reason: None,
            duplicate_args: Vec::new(),
        }
    }

    /// Set the description.
    #[must_use]
    pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Add an argument.
    #[must_use]
    pub fn arg(mut self, argument: InputValue) -> Self {
        if self.args.contains_key(&argument.name) {
            self.duplicate_args.push(argument.name.clone());
        }
        self.args.insert(argument.name.clone(), argument);
        self
    }

    /// Add a permitted location.
    #[must_use]
    pub fn location(mut self, location: ast::DirectiveLocation) -> Self {
        self.locations.push(location);
        self
    }

    /// Mark the directive as repeatable.
    #[must_use]
    pub fn repeatable(mut self) -> Self {
        self.repeatable = true;
        self
    }

    /// Add an applied directive to the definition itself.
    #[must_use]
    pub fn directive(mut self, directive: AppliedDirective) -> Self {
        self.directives.push(directive);
        self
    }

    /// Mark the directive as deprecated.
    #[must_use]
    pub fn deprecation_reason(mut self, reason: impl Into<Arc<str>>) -> Self {
        self.deprecation_reason = Some(reason.into());
        self
    }

    /// The built-in `@skip` directive.
    #[must_use]
    pub fn skip() -> Self {
        Self::new("skip")
            .description("Directs the executor to skip this field or fragment when the `if` argument is true.")
            .arg(
                InputValue::new("if", TypeRef::boolean().non_null())
                    .description("Skipped when true."),
            )
            .location(ast::DirectiveLocation::Field)
            .location(ast::DirectiveLocation::FragmentSpread)
            .location(ast::DirectiveLocation::InlineFragment)
    }

    /// The built-in `@include` directive.
    #[must_use]
    pub fn include() -> Self {
        Self::new("include")
            .description("Directs the executor to include this field or fragment only when the `if` argument is true.")
            .arg(
                InputValue::new("if", TypeRef::boolean().non_null())
                    .description("Included when true."),
            )
            .location(ast::DirectiveLocation::Field)
            .location(ast::DirectiveLocation::FragmentSpread)
            .location(ast::DirectiveLocation::InlineFragment)
    }

    /// The built-in `@deprecated` directive.
    #[must_use]
    pub fn deprecated() -> Self {
        Self::new("deprecated")
            .description("Marks an element of a GraphQL schema as no longer supported.")
            .arg(
                InputValue::new("reason", TypeRef::string())
                    .description("Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).")
                    .default_value("No longer supported"),
            )
            .location(ast::DirectiveLocation::FieldDefinition)
            .location(ast::DirectiveLocation::ArgumentDefinition)
            .location(ast::DirectiveLocation::InputFieldDefinition)
            .location(ast::DirectiveLocation::EnumValue)
            .location(ast::DirectiveLocation::DirectiveDefinition)
    }

    /// The built-in `@specifiedBy` directive.
    #[must_use]
    pub fn specified_by() -> Self {
        Self::new("specifiedBy")
            .description("Exposes a URL that specifies the behavior of this scalar.")
            .arg(
                InputValue::new("url", TypeRef::string().non_null())
                    .description("The URL that specifies the behavior of this scalar."),
            )
            .location(ast::DirectiveLocation::Scalar)
    }

    /// The `@oneOf` directive for input objects.
    #[must_use]
    pub fn one_of() -> Self {
        Self::new("oneOf")
            .description(
                "Indicates exactly one field must be supplied and this field must not be `null`.",
            )
            .location(ast::DirectiveLocation::InputObject)
    }
}