-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathmod.rs
1079 lines (954 loc) · 33.3 KB
/
mod.rs
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
//! High-level representation of a GraphQL schema
use crate::ast;
use crate::validation::ValidationOptions;
use crate::FileId;
use crate::Node;
use crate::NodeLocation;
use crate::NodeStr;
use crate::Parser;
use indexmap::IndexMap;
use indexmap::IndexSet;
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Path;
use std::sync::OnceLock;
mod component;
mod from_ast;
mod serialize;
mod validation;
pub use self::component::{Component, ComponentName, ComponentOrigin, ExtensionId};
pub use self::from_ast::SchemaBuilder;
pub use crate::ast::{
Directive, DirectiveDefinition, DirectiveLocation, EnumValueDefinition, FieldDefinition,
InputValueDefinition, Name, NamedType, Type, Value,
};
use crate::name;
use crate::ty;
use crate::validation::DiagnosticList;
/// High-level representation of a GraphQL schema
#[derive(Clone)]
pub struct Schema {
/// Source files, if any, that were parsed to contribute to this schema.
///
/// The schema (including parsed definitions) may have been modified since parsing.
pub sources: crate::SourceMap,
/// Errors that occurred when building this schema,
/// either parsing a source file or converting from AST.
build_errors: Vec<BuildError>,
/// The `schema` definition and its extensions, defining root operations
pub schema_definition: Node<SchemaDefinition>,
/// Built-in and explicit directive definitions
pub directive_definitions: IndexMap<Name, Node<DirectiveDefinition>>,
/// Definitions and extensions of built-in scalars, introspection types,
/// and explicit types
pub types: IndexMap<NamedType, ExtendedType>,
}
/// The `schema` definition and its extensions, defining root operations
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SchemaDefinition {
pub description: Option<NodeStr>,
pub directives: DirectiveList,
/// Name of the object type for the `query` root operation
pub query: Option<ComponentName>,
/// Name of the object type for the `mutation` root operation
pub mutation: Option<ComponentName>,
/// Name of the object type for the `subscription` root operation
pub subscription: Option<ComponentName>,
}
#[derive(Clone, Eq, PartialEq, Hash, Default)]
pub struct DirectiveList(pub Vec<Component<Directive>>);
/// The definition of a named type, with all information from type extensions folded in.
///
/// The source location is that of the "main" definition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExtendedType {
Scalar(Node<ScalarType>),
Object(Node<ObjectType>),
Interface(Node<InterfaceType>),
Union(Node<UnionType>),
Enum(Node<EnumType>),
InputObject(Node<InputObjectType>),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ScalarType {
pub description: Option<NodeStr>,
pub name: Name,
pub directives: DirectiveList,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectType {
pub description: Option<NodeStr>,
pub name: Name,
pub implements_interfaces: IndexSet<ComponentName>,
pub directives: DirectiveList,
/// Explicit field definitions.
///
/// When looking up a definition,
/// consider using [`Schema::type_field`] instead to include meta-fields.
pub fields: IndexMap<Name, Component<FieldDefinition>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterfaceType {
pub description: Option<NodeStr>,
pub name: Name,
pub implements_interfaces: IndexSet<ComponentName>,
pub directives: DirectiveList,
/// Explicit field definitions.
///
/// When looking up a definition,
/// consider using [`Schema::type_field`] instead to include meta-fields.
pub fields: IndexMap<Name, Component<FieldDefinition>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnionType {
pub description: Option<NodeStr>,
pub name: Name,
pub directives: DirectiveList,
/// * Key: name of a member object type
/// * Value: which union type extension defined this implementation,
/// or `None` for the union type definition.
pub members: IndexSet<ComponentName>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnumType {
pub description: Option<NodeStr>,
pub name: Name,
pub directives: DirectiveList,
pub values: IndexMap<Name, Component<EnumValueDefinition>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InputObjectType {
pub description: Option<NodeStr>,
pub name: Name,
pub directives: DirectiveList,
pub fields: IndexMap<Name, Component<InputValueDefinition>>,
}
/// AST node that has been skipped during conversion to `Schema`
#[derive(thiserror::Error, Debug, Clone)]
pub(crate) enum BuildError {
#[error("a schema document must not contain {describe}")]
ExecutableDefinition {
location: Option<NodeLocation>,
describe: &'static str,
},
#[error("must not have multiple `schema` definitions")]
SchemaDefinitionCollision {
location: Option<NodeLocation>,
previous_location: Option<NodeLocation>,
},
#[error("the directive `@{name}` is defined multiple times in the schema")]
DirectiveDefinitionCollision {
location: Option<NodeLocation>,
previous_location: Option<NodeLocation>,
name: Name,
},
#[error("the type `{name}` is defined multiple times in the schema")]
TypeDefinitionCollision {
location: Option<NodeLocation>,
previous_location: Option<NodeLocation>,
name: Name,
},
#[error("built-in scalar definitions must be omitted")]
BuiltInScalarTypeRedefinition { location: Option<NodeLocation> },
#[error("schema extension without a schema definition")]
OrphanSchemaExtension { location: Option<NodeLocation> },
#[error("type extension for undefined type `{name}`")]
OrphanTypeExtension {
location: Option<NodeLocation>,
name: Name,
},
#[error("adding {describe_ext}, but `{name}` is {describe_def}")]
TypeExtensionKindMismatch {
location: Option<NodeLocation>,
name: Name,
describe_ext: &'static str,
def_location: Option<NodeLocation>,
describe_def: &'static str,
},
#[error("duplicate definitions for the `{operation_type}` root operation type")]
DuplicateRootOperation {
location: Option<NodeLocation>,
previous_location: Option<NodeLocation>,
operation_type: &'static str,
},
#[error(
"object type `{type_name}` implements interface `{name_at_previous_location}` \
more than once"
)]
DuplicateImplementsInterfaceInObject {
location: Option<NodeLocation>,
name_at_previous_location: Name,
type_name: Name,
},
#[error(
"interface type `{type_name}` implements interface `{name_at_previous_location}` \
more than once"
)]
DuplicateImplementsInterfaceInInterface {
location: Option<NodeLocation>,
name_at_previous_location: Name,
type_name: Name,
},
#[error(
"duplicate definitions for the `{name_at_previous_location}` \
field of object type `{type_name}`"
)]
ObjectFieldNameCollision {
location: Option<NodeLocation>,
name_at_previous_location: Name,
type_name: Name,
},
#[error(
"duplicate definitions for the `{name_at_previous_location}` \
field of interface type `{type_name}`"
)]
InterfaceFieldNameCollision {
location: Option<NodeLocation>,
name_at_previous_location: Name,
type_name: Name,
},
#[error(
"duplicate definitions for the `{name_at_previous_location}` \
value of enum type `{type_name}`"
)]
EnumValueNameCollision {
location: Option<NodeLocation>,
name_at_previous_location: Name,
type_name: Name,
},
#[error(
"duplicate definitions for the `{name_at_previous_location}` \
member of union type `{type_name}`"
)]
UnionMemberNameCollision {
location: Option<NodeLocation>,
name_at_previous_location: Name,
type_name: Name,
},
#[error(
"duplicate definitions for the `{name_at_previous_location}` \
field of input object type `{type_name}`"
)]
InputFieldNameCollision {
location: Option<NodeLocation>,
name_at_previous_location: Name,
type_name: Name,
},
}
/// Could not find the requested field definition
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FieldLookupError<'schema> {
NoSuchType,
NoSuchField(&'schema NamedType, &'schema ExtendedType),
}
impl Schema {
/// Returns an (almost) empty schema.
///
/// It starts with built-in directives, built-in scalars, and introspection types.
/// It can then be filled programatically.
#[allow(clippy::new_without_default)] // not a great implicit default in generic contexts
pub fn new() -> Self {
SchemaBuilder::new().build()
}
/// Parse a single source file into a schema, with the default parser configuration.
///
/// Create a [`Parser`] to use different parser configuration.
/// Use [`builder()`][Self::builder] to build a schema from multiple parsed files.
pub fn parse(source_text: impl Into<String>, path: impl AsRef<Path>) -> Self {
Parser::default().parse_schema(source_text, path)
}
/// Returns a new builder for creating a Schema from AST documents,
/// initialized with built-in directives, built-in scalars, and introspection types
///
/// ```rust
/// use apollo_compiler::Schema;
///
/// let empty_schema = Schema::builder().build();
/// ```
pub fn builder() -> SchemaBuilder {
SchemaBuilder::new()
}
/// Returns `Err` if invalid, or `Ok` for potential warnings or advice
pub fn validate(&self, options: ValidationOptions) -> Result<DiagnosticList, DiagnosticList> {
let mut errors = DiagnosticList::new(None, self.sources.clone());
let warnings_and_advice = validation::validate_schema(&mut errors, self, options);
let valid = errors.is_empty();
for diagnostic in warnings_and_advice {
errors.push(
diagnostic.location,
crate::validation::Details::CompilerDiagnostic(diagnostic),
)
}
errors.sort();
if valid {
Ok(errors)
} else {
Err(errors)
}
}
/// Returns the type with the given name, if it is a scalar type
pub fn get_scalar(&self, name: &str) -> Option<&Node<ScalarType>> {
if let Some(ExtendedType::Scalar(ty)) = self.types.get(name) {
Some(ty)
} else {
None
}
}
/// Returns the type with the given name, if it is a object type
pub fn get_object(&self, name: &str) -> Option<&Node<ObjectType>> {
if let Some(ExtendedType::Object(ty)) = self.types.get(name) {
Some(ty)
} else {
None
}
}
/// Returns the type with the given name, if it is a interface type
pub fn get_interface(&self, name: &str) -> Option<&Node<InterfaceType>> {
if let Some(ExtendedType::Interface(ty)) = self.types.get(name) {
Some(ty)
} else {
None
}
}
/// Returns the type with the given name, if it is a union type
pub fn get_union(&self, name: &str) -> Option<&Node<UnionType>> {
if let Some(ExtendedType::Union(ty)) = self.types.get(name) {
Some(ty)
} else {
None
}
}
/// Returns the type with the given name, if it is a enum type
pub fn get_enum(&self, name: &str) -> Option<&Node<EnumType>> {
if let Some(ExtendedType::Enum(ty)) = self.types.get(name) {
Some(ty)
} else {
None
}
}
/// Returns the type with the given name, if it is a input object type
pub fn get_input_object(&self, name: &str) -> Option<&Node<InputObjectType>> {
if let Some(ExtendedType::InputObject(ty)) = self.types.get(name) {
Some(ty)
} else {
None
}
}
/// Returns the name of the object type for the root operation with the given operation kind
pub fn root_operation(&self, operation_type: ast::OperationType) -> Option<&NamedType> {
match operation_type {
ast::OperationType::Query => &self.schema_definition.query,
ast::OperationType::Mutation => &self.schema_definition.mutation,
ast::OperationType::Subscription => &self.schema_definition.subscription,
}
.as_ref()
.map(|component| &component.name)
}
/// Returns the definition of a type’s explicit field or meta-field.
pub fn type_field(
&self,
type_name: &str,
field_name: &str,
) -> Result<&Component<FieldDefinition>, FieldLookupError<'_>> {
let (ty_def_name, ty_def) = self
.types
.get_key_value(type_name)
.ok_or(FieldLookupError::NoSuchType)?;
self.meta_fields_definitions(type_name)
.iter()
.find(|def| def.name == field_name)
.or_else(|| match ty_def {
ExtendedType::Object(ty) => ty.fields.get(field_name),
ExtendedType::Interface(ty) => ty.fields.get(field_name),
ExtendedType::Scalar(_)
| ExtendedType::Union(_)
| ExtendedType::Enum(_)
| ExtendedType::InputObject(_) => None,
})
.ok_or(FieldLookupError::NoSuchField(ty_def_name, ty_def))
}
/// Returns a map of interface names to names of types that implement that interface
///
/// `Schema` only stores the inverse relationship
/// (in [`ObjectType::implements_interfaces`] and [`InterfaceType::implements_interfaces`]),
/// so iterating the implementers of an interface requires a linear scan
/// of all types in the schema.
/// If that is repeated for multiple interfaces,
/// gathering them all at once amorticizes that cost.
#[doc(hidden)] // use the Salsa query instead
pub fn implementers_map(&self) -> HashMap<Name, HashSet<Name>> {
let mut map = HashMap::<Name, HashSet<Name>>::new();
for (ty_name, ty) in &self.types {
let interfaces = match ty {
ExtendedType::Object(def) => &def.implements_interfaces,
ExtendedType::Interface(def) => &def.implements_interfaces,
ExtendedType::Scalar(_)
| ExtendedType::Union(_)
| ExtendedType::Enum(_)
| ExtendedType::InputObject(_) => continue,
};
for interface in interfaces {
map.entry(interface.name.clone())
.or_default()
.insert(ty_name.clone());
}
}
map
}
/// Returns whether `maybe_subtype` is a subtype of `abstract_type`, which means either:
///
/// * `maybe_subtype` implements the interface `abstract_type`
/// * `maybe_subtype` is a member of the union type `abstract_type`
pub fn is_subtype(&self, abstract_type: &str, maybe_subtype: &str) -> bool {
self.types.get(abstract_type).is_some_and(|ty| match ty {
ExtendedType::Interface(_) => self.types.get(maybe_subtype).is_some_and(|ty2| {
match ty2 {
ExtendedType::Object(def) => &def.implements_interfaces,
ExtendedType::Interface(def) => &def.implements_interfaces,
ExtendedType::Scalar(_)
| ExtendedType::Union(_)
| ExtendedType::Enum(_)
| ExtendedType::InputObject(_) => return false,
}
.contains(abstract_type)
}),
ExtendedType::Union(def) => def.members.contains(maybe_subtype),
ExtendedType::Scalar(_)
| ExtendedType::Object(_)
| ExtendedType::Enum(_)
| ExtendedType::InputObject(_) => false,
})
}
/// Return the meta-fields of the given type
pub(crate) fn meta_fields_definitions(
&self,
type_name: &str,
) -> &'static [Component<FieldDefinition>] {
static ROOT_QUERY_FIELDS: LazyLock<[Component<FieldDefinition>; 3]> = LazyLock::new(|| {
[
// __typename: String!
Component::new(FieldDefinition {
description: None,
name: name!("__typename"),
arguments: Vec::new(),
ty: ty!(String!),
directives: ast::DirectiveList::new(),
}),
// __schema: __Schema!
Component::new(FieldDefinition {
description: None,
name: name!("__schema"),
arguments: Vec::new(),
ty: ty!(__Schema!),
directives: ast::DirectiveList::new(),
}),
// __type(name: String!): __Type
Component::new(FieldDefinition {
description: None,
name: name!("__type"),
arguments: vec![InputValueDefinition {
description: None,
name: name!("name"),
ty: ty!(String!).into(),
default_value: None,
directives: ast::DirectiveList::new(),
}
.into()],
ty: ty!(__Type),
directives: ast::DirectiveList::new(),
}),
]
});
if self
.schema_definition
.query
.as_ref()
.is_some_and(|n| n == type_name)
{
// __typename: String!
// __schema: __Schema!
// __type(name: String!): __Type
ROOT_QUERY_FIELDS.get()
} else {
// __typename: String!
std::slice::from_ref(&ROOT_QUERY_FIELDS.get()[0])
}
}
/// Returns whether the type `ty` is defined as is an input type
///
/// <https://spec.graphql.org/October2021/#sec-Input-and-Output-Types>
pub fn is_input_type(&self, ty: &Type) -> bool {
match self.types.get(ty.inner_named_type()) {
Some(ExtendedType::Scalar(_))
| Some(ExtendedType::Enum(_))
| Some(ExtendedType::InputObject(_)) => true,
Some(ExtendedType::Object(_))
| Some(ExtendedType::Interface(_))
| Some(ExtendedType::Union(_))
| None => false,
}
}
/// Returns whether the type `ty` is defined as is an output type
///
/// <https://spec.graphql.org/October2021/#sec-Input-and-Output-Types>
pub fn is_output_type(&self, ty: &Type) -> bool {
match self.types.get(ty.inner_named_type()) {
Some(ExtendedType::Scalar(_))
| Some(ExtendedType::Object(_))
| Some(ExtendedType::Interface(_))
| Some(ExtendedType::Union(_))
| Some(ExtendedType::Enum(_)) => true,
Some(ExtendedType::InputObject(_)) | None => false,
}
}
serialize_method!();
}
impl SchemaDefinition {
/// Collect `schema` extensions that contribute any component
///
/// The order of the returned set is unspecified but deterministic
/// for a given apollo-compiler version.
pub fn extensions(&self) -> IndexSet<&ExtensionId> {
self.directives
.iter()
.flat_map(|dir| dir.origin.extension_id())
.chain(
self.query
.as_ref()
.and_then(|name| name.origin.extension_id()),
)
.chain(
self.mutation
.as_ref()
.and_then(|name| name.origin.extension_id()),
)
.chain(
self.subscription
.as_ref()
.and_then(|name| name.origin.extension_id()),
)
.collect()
}
}
impl ExtendedType {
pub fn name(&self) -> &Name {
match self {
Self::Scalar(def) => &def.name,
Self::Object(def) => &def.name,
Self::Interface(def) => &def.name,
Self::Union(def) => &def.name,
Self::Enum(def) => &def.name,
Self::InputObject(def) => &def.name,
}
}
/// Return the source location of the type's base definition.
///
/// If the type has extensions, those are not covered by this location.
pub fn location(&self) -> Option<NodeLocation> {
match self {
Self::Scalar(ty) => ty.location(),
Self::Object(ty) => ty.location(),
Self::Interface(ty) => ty.location(),
Self::Union(ty) => ty.location(),
Self::Enum(ty) => ty.location(),
Self::InputObject(ty) => ty.location(),
}
}
pub(crate) fn describe(&self) -> &'static str {
match self {
Self::Scalar(_) => "a scalar type",
Self::Object(_) => "an object type",
Self::Interface(_) => "an interface type",
Self::Union(_) => "a union type",
Self::Enum(_) => "an enum type",
Self::InputObject(_) => "an input object type",
}
}
pub fn is_scalar(&self) -> bool {
matches!(self, Self::Scalar(_))
}
pub fn is_object(&self) -> bool {
matches!(self, Self::Object(_))
}
pub fn is_interface(&self) -> bool {
matches!(self, Self::Interface(_))
}
pub fn is_union(&self) -> bool {
matches!(self, Self::Union(_))
}
pub fn is_enum(&self) -> bool {
matches!(self, Self::Enum(_))
}
pub fn is_input_object(&self) -> bool {
matches!(self, Self::InputObject(_))
}
/// Returns true if a value of this type can be used as an input value.
///
/// # Spec
/// This implements spec function
/// [`IsInputType(type)`](https://spec.graphql.org/draft/#IsInputType())
pub fn is_input_type(&self) -> bool {
matches!(self, Self::Scalar(_) | Self::Enum(_) | Self::InputObject(_))
}
/// Returns true if a value of this type can be used as an output value.
///
/// # Spec
/// This implements spec function
/// [`IsOutputType(type)`](https://spec.graphql.org/draft/#IsOutputType())
pub fn is_output_type(&self) -> bool {
matches!(
self,
Self::Scalar(_) | Self::Enum(_) | Self::Object(_) | Self::Interface(_) | Self::Union(_)
)
}
/// Returns whether this is a built-in scalar or introspection type
pub fn is_built_in(&self) -> bool {
match self {
Self::Scalar(ty) => ty.is_built_in(),
Self::Object(ty) => ty.is_built_in(),
Self::Interface(ty) => ty.is_built_in(),
Self::Union(ty) => ty.is_built_in(),
Self::Enum(ty) => ty.is_built_in(),
Self::InputObject(ty) => ty.is_built_in(),
}
}
pub fn directives(&self) -> &DirectiveList {
match self {
Self::Scalar(ty) => &ty.directives,
Self::Object(ty) => &ty.directives,
Self::Interface(ty) => &ty.directives,
Self::Union(ty) => &ty.directives,
Self::Enum(ty) => &ty.directives,
Self::InputObject(ty) => &ty.directives,
}
}
pub fn description(&self) -> Option<&NodeStr> {
match self {
Self::Scalar(ty) => ty.description.as_ref(),
Self::Object(ty) => ty.description.as_ref(),
Self::Interface(ty) => ty.description.as_ref(),
Self::Union(ty) => ty.description.as_ref(),
Self::Enum(ty) => ty.description.as_ref(),
Self::InputObject(ty) => ty.description.as_ref(),
}
}
serialize_method!();
}
impl ScalarType {
/// Collect scalar type extensions that contribute any component
///
/// The order of the returned set is unspecified but deterministic
/// for a given apollo-compiler version.
pub fn extensions(&self) -> IndexSet<&ExtensionId> {
self.directives
.iter()
.flat_map(|dir| dir.origin.extension_id())
.collect()
}
serialize_method!();
}
impl ObjectType {
/// Collect object type extensions that contribute any component
///
/// The order of the returned set is unspecified but deterministic
/// for a given apollo-compiler version.
pub fn extensions(&self) -> IndexSet<&ExtensionId> {
self.directives
.iter()
.flat_map(|dir| dir.origin.extension_id())
.chain(
self.implements_interfaces
.iter()
.flat_map(|component| component.origin.extension_id()),
)
.chain(
self.fields
.values()
.flat_map(|field| field.origin.extension_id()),
)
.collect()
}
serialize_method!();
}
impl InterfaceType {
/// Collect interface type extensions that contribute any component
///
/// The order of the returned set is unspecified but deterministic
/// for a given apollo-compiler version.
pub fn extensions(&self) -> IndexSet<&ExtensionId> {
self.directives
.iter()
.flat_map(|dir| dir.origin.extension_id())
.chain(
self.implements_interfaces
.iter()
.flat_map(|component| component.origin.extension_id()),
)
.chain(
self.fields
.values()
.flat_map(|field| field.origin.extension_id()),
)
.collect()
}
serialize_method!();
}
impl UnionType {
/// Collect union type extensions that contribute any component
///
/// The order of the returned set is unspecified but deterministic
/// for a given apollo-compiler version.
pub fn extensions(&self) -> IndexSet<&ExtensionId> {
self.directives
.iter()
.flat_map(|dir| dir.origin.extension_id())
.chain(
self.members
.iter()
.flat_map(|component| component.origin.extension_id()),
)
.collect()
}
serialize_method!();
}
impl EnumType {
/// Collect enum type extensions that contribute any component
///
/// The order of the returned set is unspecified but deterministic
/// for a given apollo-compiler version.
pub fn extensions(&self) -> IndexSet<&ExtensionId> {
self.directives
.iter()
.flat_map(|dir| dir.origin.extension_id())
.chain(
self.values
.values()
.flat_map(|value| value.origin.extension_id()),
)
.collect()
}
serialize_method!();
}
impl InputObjectType {
/// Collect input object type extensions that contribute any component
///
/// The order of the returned set is unspecified but deterministic
/// for a given apollo-compiler version.
pub fn extensions(&self) -> IndexSet<&ExtensionId> {
self.directives
.iter()
.flat_map(|dir| dir.origin.extension_id())
.chain(
self.fields
.values()
.flat_map(|field| field.origin.extension_id()),
)
.collect()
}
serialize_method!();
}
impl DirectiveList {
pub const fn new() -> Self {
Self(Vec::new())
}
/// Returns an iterator of directives with the given name.
///
/// This method is best for repeatable directives.
/// See also [`get`][Self::get] for non-repeatable directives.
pub fn get_all<'def: 'name, 'name>(
&'def self,
name: &'name str,
) -> impl Iterator<Item = &'def Component<Directive>> + 'name {
self.0.iter().filter(move |dir| dir.name == name)
}
/// Returns the first directive with the given name, if any.
///
/// This method is best for non-repeatable directives.
/// See also [`get_all`][Self::get_all] for repeatable directives.
pub fn get(&self, name: &str) -> Option<&Component<Directive>> {
self.get_all(name).next()
}
/// Returns whether there is a directive with the given name
pub fn has(&self, name: &str) -> bool {
self.get(name).is_some()
}
serialize_method!();
}
impl std::fmt::Debug for DirectiveList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::ops::Deref for DirectiveList {
type Target = Vec<Component<Directive>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for DirectiveList {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<'a> IntoIterator for &'a DirectiveList {
type Item = &'a Component<Directive>;
type IntoIter = std::slice::Iter<'a, Component<Directive>>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl<'a> IntoIterator for &'a mut DirectiveList {
type Item = &'a mut Component<Directive>;
type IntoIter = std::slice::IterMut<'a, Component<Directive>>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter_mut()
}
}
impl<D> FromIterator<D> for DirectiveList
where
D: Into<Component<Directive>>,
{
fn from_iter<T: IntoIterator<Item = D>>(iter: T) -> Self {
Self(iter.into_iter().map(Into::into).collect())
}
}
impl Eq for Schema {}
impl PartialEq for Schema {
fn eq(&self, other: &Self) -> bool {
let Self {
sources: _, // ignored
build_errors: _, // ignored
schema_definition: root_operations,
directive_definitions,
types,
} = self;
*root_operations == other.schema_definition
&& *directive_definitions == other.directive_definitions
&& *types == other.types
}
}
impl From<Node<ScalarType>> for ExtendedType {
fn from(ty: Node<ScalarType>) -> Self {
Self::Scalar(ty)
}
}
impl From<Node<ObjectType>> for ExtendedType {
fn from(ty: Node<ObjectType>) -> Self {
Self::Object(ty)
}
}
impl From<Node<InterfaceType>> for ExtendedType {
fn from(ty: Node<InterfaceType>) -> Self {
Self::Interface(ty)
}
}
impl From<Node<UnionType>> for ExtendedType {
fn from(ty: Node<UnionType>) -> Self {
Self::Union(ty)
}
}
impl From<Node<EnumType>> for ExtendedType {
fn from(ty: Node<EnumType>) -> Self {
Self::Enum(ty)
}
}
impl From<Node<InputObjectType>> for ExtendedType {
fn from(ty: Node<InputObjectType>) -> Self {
Self::InputObject(ty)
}
}
impl From<ScalarType> for ExtendedType {
fn from(ty: ScalarType) -> Self {
Self::Scalar(ty.into())
}
}
impl From<ObjectType> for ExtendedType {
fn from(ty: ObjectType) -> Self {
Self::Object(ty.into())
}
}
impl From<InterfaceType> for ExtendedType {
fn from(ty: InterfaceType) -> Self {
Self::Interface(ty.into())
}
}
impl From<UnionType> for ExtendedType {
fn from(ty: UnionType) -> Self {
Self::Union(ty.into())
}
}
impl From<EnumType> for ExtendedType {
fn from(ty: EnumType) -> Self {
Self::Enum(ty.into())
}
}