trustfall_core 0.1.1

The trustfall query engine, empowering you to query everything.
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
#![allow(dead_code)]
use std::{
    collections::{btree_map::Entry, BTreeMap, BTreeSet, HashMap, HashSet, VecDeque},
    ops::Add,
    sync::Arc,
};

use async_graphql_parser::{
    parse_schema,
    types::{
        BaseType, DirectiveDefinition, FieldDefinition, ObjectType, SchemaDefinition,
        ServiceDocument, Type, TypeDefinition, TypeKind, TypeSystemDefinition,
    },
    Positioned,
};

pub use ::async_graphql_parser::Error;
use async_graphql_value::Name;
use itertools::Itertools;
use serde::{Deserialize, Serialize};

use crate::ir::types::{get_base_named_type, is_argument_type_valid, is_scalar_only_subtype};
use crate::util::{BTreeMapTryInsertExt, HashMapTryInsertExt};

use self::error::InvalidSchemaError;

pub mod error;

#[derive(Debug, Clone)]
pub struct Schema {
    pub(crate) schema: SchemaDefinition,
    pub(crate) query_type: ObjectType,
    pub(crate) directives: HashMap<Arc<str>, DirectiveDefinition>,
    pub(crate) scalars: HashMap<Arc<str>, TypeDefinition>,
    pub(crate) vertex_types: HashMap<Arc<str>, TypeDefinition>,
    pub(crate) fields: HashMap<(Arc<str>, Arc<str>), FieldDefinition>,
    pub(crate) field_origins: BTreeMap<(Arc<str>, Arc<str>), FieldOrigin>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum FieldOrigin {
    SingleAncestor(Arc<str>), // the name of the parent (super) type that first defined this field
    MultipleAncestors(BTreeSet<Arc<str>>),
}

impl Add for &FieldOrigin {
    type Output = FieldOrigin;

    fn add(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (FieldOrigin::SingleAncestor(l), FieldOrigin::SingleAncestor(r)) => {
                if l == r {
                    self.clone()
                } else {
                    FieldOrigin::MultipleAncestors(btreeset![l.clone(), r.clone()])
                }
            }
            (FieldOrigin::SingleAncestor(single), FieldOrigin::MultipleAncestors(multi))
            | (FieldOrigin::MultipleAncestors(multi), FieldOrigin::SingleAncestor(single)) => {
                let mut new_set = multi.clone();
                new_set.insert(single.clone());
                FieldOrigin::MultipleAncestors(new_set)
            }
            (FieldOrigin::MultipleAncestors(l_set), FieldOrigin::MultipleAncestors(r_set)) => {
                let mut new_set = l_set.clone();
                new_set.extend(r_set.iter().cloned());
                FieldOrigin::MultipleAncestors(new_set)
            }
        }
    }
}

lazy_static! {
    pub(crate) static ref BUILTIN_SCALARS: HashSet<&'static str> = hashset! {
        "Int",
        "Float",
        "String",
        "Boolean",
        "ID",
    };
}

const RESERVED_PREFIX: &str = "__";

impl Schema {
    pub const ALL_DIRECTIVE_DEFINITIONS: &'static str = "
directive @filter(op: String!, value: [String!]) on FIELD | INLINE_FRAGMENT
directive @tag(name: String) on FIELD
directive @output(name: String) on FIELD
directive @optional on FIELD
directive @recurse(depth: Int!) on FIELD
directive @fold on FIELD
directive @transform(op: String!) on FIELD
";

    pub fn parse(input: impl AsRef<str>) -> Result<Self, InvalidSchemaError> {
        let doc = parse_schema(input)?;
        Self::new(doc)
    }

    pub fn new(doc: ServiceDocument) -> Result<Self, InvalidSchemaError> {
        let mut schema: Option<SchemaDefinition> = None;
        let mut directives: HashMap<Arc<str>, DirectiveDefinition> = Default::default();
        let mut scalars: HashMap<Arc<str>, TypeDefinition> = Default::default();

        // The schema is mostly type definitions, except for one schema definition, and
        // perhaps a small number of other definitions like custom scalars or directives.
        let mut vertex_types: HashMap<Arc<str>, TypeDefinition> =
            HashMap::with_capacity(doc.definitions.len() - 1);

        // Each type has probably at least one field.
        let mut fields: HashMap<(Arc<str>, Arc<str>), FieldDefinition> =
            HashMap::with_capacity(doc.definitions.len() - 1);

        for definition in doc.definitions {
            match definition {
                TypeSystemDefinition::Schema(s) => {
                    assert!(schema.is_none());
                    if s.node.extend {
                        unimplemented!();
                    }

                    schema = Some(s.node);
                }
                TypeSystemDefinition::Directive(d) => {
                    directives
                        .insert_or_error(Arc::from(d.node.name.node.to_string()), d.node)
                        .unwrap();
                }
                TypeSystemDefinition::Type(t) => {
                    let node = t.node;
                    let type_name: Arc<str> = Arc::from(node.name.node.to_string());
                    assert!(!BUILTIN_SCALARS.contains(type_name.as_ref()));

                    if node.extend {
                        unimplemented!();
                    }

                    match &node.kind {
                        TypeKind::Scalar => {
                            scalars
                                .insert_or_error(type_name.clone(), node.clone())
                                .unwrap();
                        }
                        TypeKind::Object(_) | TypeKind::Interface(_) => {
                            vertex_types
                                .insert_or_error(type_name.clone(), node.clone())
                                .unwrap();
                        }
                        TypeKind::Enum(_) => unimplemented!(),
                        TypeKind::Union(_) => unimplemented!(),
                        TypeKind::InputObject(_) => unimplemented!(),
                    }

                    let field_defs = match node.kind {
                        TypeKind::Object(object) => Some(object.fields),

                        TypeKind::Interface(interface) => Some(interface.fields),
                        _ => None,
                    };
                    if let Some(field_defs) = field_defs {
                        for field in field_defs {
                            let field_node = field.node;
                            let field_name = Arc::from(field_node.name.node.to_string());

                            fields
                                .insert_or_error((type_name.clone(), field_name), field_node)
                                .unwrap();
                        }
                    }
                }
            }
        }

        let schema = schema.expect("Schema definition was not present.");
        let query_type_name = schema
            .query
            .as_ref()
            .expect("No query type was declared in the schema")
            .node
            .as_ref();
        let query_type_definition = vertex_types
            .get(query_type_name)
            .expect("The query type set in the schema object was never defined.");
        let query_type = match &query_type_definition.kind {
            TypeKind::Object(o) => o.clone(),
            _ => unreachable!(),
        };

        let field_origins = get_field_origins(&vertex_types)?;

        let mut errors = vec![];
        if let Err(e) = check_required_transitive_implementations(&vertex_types) {
            errors.extend(e.into_iter());
        }
        if let Err(e) = check_field_type_narrowing(&vertex_types, &fields) {
            errors.extend(e.into_iter());
        }
        if let Err(e) = check_fields_required_by_interface_implementations(&vertex_types, &fields) {
            errors.extend(e.into_iter());
        }
        if let Err(e) = check_ambiguous_field_origins(&fields, &field_origins) {
            errors.extend(e.into_iter());
        }
        if let Err(e) =
            check_type_and_property_and_edge_invariants(query_type_definition, &vertex_types)
        {
            errors.extend(e.into_iter());
        }
        if let Err(e) =
            check_root_query_type_invariants(query_type_definition, &query_type, &vertex_types)
        {
            errors.extend(e.into_iter());
        }
        if errors.is_empty() {
            Ok(Self {
                schema,
                query_type,
                directives,
                scalars,
                vertex_types,
                fields,
                field_origins,
            })
        } else {
            Err(errors.into())
        }
    }

    /// If the named type is defined, iterate through the names of its subtypes including itself.
    /// Otherwise, return None.
    pub fn subtypes<'slf, 'a: 'slf>(
        &'slf self,
        type_name: &'a str,
    ) -> Option<impl Iterator<Item = &'slf str> + 'slf> {
        if !self.vertex_types.contains_key(type_name) {
            return None;
        }

        Some(self.vertex_types.iter().filter_map(move |(name, defn)| {
            if name.as_ref() == type_name
                || get_vertex_type_implements(defn)
                    .iter()
                    .any(|x| x.node.as_ref() == type_name)
            {
                Some(name.as_ref())
            } else {
                None
            }
        }))
    }

    pub(crate) fn query_type_name(&self) -> &str {
        self.schema.query.as_ref().unwrap().node.as_ref()
    }

    pub(crate) fn vertex_type_implements(&self, vertex_type: &str) -> &[Positioned<Name>] {
        get_vertex_type_implements(&self.vertex_types[vertex_type])
    }

    pub(crate) fn is_subtype(&self, parent_type: &Type, maybe_subtype: &Type) -> bool {
        is_subtype(&self.vertex_types, parent_type, maybe_subtype)
    }

    pub(crate) fn is_named_type_subtype(&self, parent_type: &str, maybe_subtype: &str) -> bool {
        is_named_type_subtype(&self.vertex_types, parent_type, maybe_subtype)
    }
}

fn check_root_query_type_invariants(
    query_type_definition: &TypeDefinition,
    query_type: &ObjectType,
    vertex_types: &HashMap<Arc<str>, TypeDefinition>,
) -> Result<(), Vec<InvalidSchemaError>> {
    let mut errors: Vec<InvalidSchemaError> = vec![];

    for field_defn in &query_type.fields {
        let field_type = &field_defn.node.ty.node;
        let base_named_type = get_base_named_type(field_type);
        if BUILTIN_SCALARS.contains(base_named_type) {
            errors.push(InvalidSchemaError::PropertyFieldOnRootQueryType(
                query_type_definition.name.node.to_string(),
                field_defn.node.name.node.to_string(),
                field_type.to_string(),
            ));
        } else if !vertex_types.contains_key(base_named_type) {
            // Somehow the base named type is neither a vertex nor a scalar,
            // and this field is neither an edge nor a property.
            unreachable!()
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

fn check_type_and_property_and_edge_invariants(
    query_type_definition: &TypeDefinition,
    vertex_types: &HashMap<Arc<str>, TypeDefinition>,
) -> Result<(), Vec<InvalidSchemaError>> {
    let mut errors: Vec<InvalidSchemaError> = vec![];

    for (type_name, type_defn) in vertex_types {
        if type_name.as_ref().starts_with(RESERVED_PREFIX) {
            errors.push(InvalidSchemaError::ReservedTypeName(type_name.to_string()));
        }

        let type_fields = get_vertex_type_fields(type_defn);

        for defn in type_fields {
            let field_defn = &defn.node;
            let field_type = &field_defn.ty.node;

            if field_defn.name.node.as_ref().starts_with(RESERVED_PREFIX) {
                errors.push(InvalidSchemaError::ReservedFieldName(
                    type_name.to_string(),
                    field_defn.name.node.to_string(),
                ));
            }

            let base_named_type = get_base_named_type(field_type);
            if BUILTIN_SCALARS.contains(base_named_type) {
                // We're looking at a property field.
                if !field_defn.arguments.is_empty() {
                    errors.push(InvalidSchemaError::PropertyFieldWithParameters(
                        type_name.to_string(),
                        field_defn.name.node.to_string(),
                        field_type.to_string(),
                        field_defn
                            .arguments
                            .iter()
                            .map(|x| x.node.name.node.to_string())
                            .collect(),
                    ));
                }
            } else if vertex_types.contains_key(base_named_type) {
                // We're looking at an edge field.
                if base_named_type == query_type_definition.name.node.as_ref() {
                    // This edge points to the root query type. That's not supported.
                    errors.push(InvalidSchemaError::EdgePointsToRootQueryType(
                        type_name.to_string(),
                        field_defn.name.node.to_string(),
                        field_type.to_string(),
                    ));
                } else {
                    // Check if the parameters this edge accepts (if any) have valid default values.
                    for param_defn in &field_defn.arguments {
                        if let Some(value) = &param_defn.node.default_value {
                            let param_type = &param_defn.node.ty.node;
                            #[allow(clippy::needless_borrow)]
                            match (&value.node).try_into() {
                                Ok(value) => {
                                    if !is_argument_type_valid(param_type, &value) {
                                        errors.push(InvalidSchemaError::InvalidDefaultValueForFieldParameter(
                                            type_name.to_string(),
                                            field_defn.name.node.to_string(),
                                            param_defn.node.name.node.to_string(),
                                            param_type.to_string(),
                                            format!("{:?}", value),
                                        ));
                                    }
                                }
                                Err(_) => {
                                    errors.push(
                                        InvalidSchemaError::InvalidDefaultValueForFieldParameter(
                                            type_name.to_string(),
                                            field_defn.name.node.to_string(),
                                            param_defn.node.name.node.to_string(),
                                            param_type.to_string(),
                                            value.node.to_string(),
                                        ),
                                    );
                                }
                            }
                        }
                    }

                    // Check that the edge field doesn't have
                    // a list-of-list or more nested list type.
                    match &field_type.base {
                        BaseType::Named(_) => {}
                        BaseType::List(inner) => match &inner.base {
                            BaseType::Named(_) => {}
                            BaseType::List(_) => {
                                errors.push(InvalidSchemaError::InvalidEdgeType(
                                    type_name.to_string(),
                                    field_defn.name.node.to_string(),
                                    field_type.to_string(),
                                ));
                            }
                        },
                    }
                }
            } else {
                // Somehow the base named type is neither a vertex nor a scalar,
                // and this field is neither an edge nor a property.
                unreachable!(
                    "field {} (type {}) appears to represent neither an edge nor a property",
                    field_defn.name.node.as_ref(),
                    field_type.to_string(),
                )
            }
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

fn is_named_type_subtype(
    vertex_types: &HashMap<Arc<str>, TypeDefinition>,
    parent_type: &str,
    maybe_subtype: &str,
) -> bool {
    let parent_is_vertex = vertex_types.contains_key(parent_type);
    let maybe_sub = vertex_types.get(maybe_subtype);

    match (parent_is_vertex, maybe_sub) {
        (false, None) => {
            // The types could both be scalars, which have no inheritance hierarchy.
            // Any type is a subtype of itself, so we check equality.
            parent_type == maybe_subtype
        }
        (true, Some(maybe_subtype_vertex)) => {
            // Both types are vertex types. We have a subtype relationship if
            // - the two types are actually the same type, or if
            // - the "maybe subtype" implements the parent type.
            parent_type == maybe_subtype
                || get_vertex_type_implements(maybe_subtype_vertex)
                    .iter()
                    .any(|pos| pos.node.as_ref() == parent_type)
        }
        _ => {
            // One type is a vertex type, the other should be a scalar.
            // No subtype relationship is possible between them.
            false
        }
    }
}

fn is_subtype(
    vertex_types: &HashMap<Arc<str>, TypeDefinition>,
    parent_type: &Type,
    maybe_subtype: &Type,
) -> bool {
    // If the parent type is non-nullable, all its subtypes must be non-nullable as well.
    // If the parent type is nullable, it can have both nullable and non-nullable subtypes.
    if !parent_type.nullable && maybe_subtype.nullable {
        return false;
    }

    match (&parent_type.base, &maybe_subtype.base) {
        (BaseType::Named(parent), BaseType::Named(subtype)) => {
            is_named_type_subtype(vertex_types, parent.as_ref(), subtype.as_ref())
        }
        (BaseType::List(parent_type), BaseType::List(maybe_subtype)) => {
            is_subtype(vertex_types, parent_type, maybe_subtype)
        }
        (BaseType::Named(..), BaseType::List(..)) | (BaseType::List(..), BaseType::Named(..)) => {
            false
        }
    }
}

fn check_ambiguous_field_origins(
    fields: &HashMap<(Arc<str>, Arc<str>), FieldDefinition>,
    field_origins: &BTreeMap<(Arc<str>, Arc<str>), FieldOrigin>,
) -> Result<(), Vec<InvalidSchemaError>> {
    let mut errors = vec![];

    for (key, origin) in field_origins {
        let (type_name, field_name) = key;
        if let FieldOrigin::MultipleAncestors(ancestors) = &origin {
            let field_type = fields[key].ty.node.to_string();
            errors.push(InvalidSchemaError::AmbiguousFieldOrigin(
                type_name.to_string(),
                field_name.to_string(),
                field_type,
                ancestors.iter().map(|x| x.to_string()).collect(),
            ))
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

/// If type X implements interface A, and A implements interface B,
/// then X must also implement B by transitivity.
fn check_required_transitive_implementations(
    vertex_types: &HashMap<Arc<str>, TypeDefinition>,
) -> Result<(), Vec<InvalidSchemaError>> {
    let mut errors: Vec<InvalidSchemaError> = vec![];

    for (type_name, type_defn) in vertex_types {
        let implementations: BTreeSet<&str> = get_vertex_type_implements(type_defn)
            .iter()
            .map(|x| x.node.as_ref())
            .collect();

        for impl_name in implementations.iter().copied() {
            let implementation_defn = vertex_types.get(impl_name).expect("implemented interface was not defined in schema; bug since it should have been caught earlier");

            for expected_impl in get_vertex_type_implements(implementation_defn) {
                let expected_impl_name = expected_impl.node.as_ref();

                if implementations.get(expected_impl_name).is_none() {
                    errors.push(
                        InvalidSchemaError::MissingTransitiveInterfaceImplementation(
                            type_name.to_string(),
                            impl_name.to_string(),
                            expected_impl_name.to_string(),
                        ),
                    );
                }
            }
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

fn check_fields_required_by_interface_implementations(
    vertex_types: &HashMap<Arc<str>, TypeDefinition>,
    fields: &HashMap<(Arc<str>, Arc<str>), FieldDefinition>,
) -> Result<(), Vec<InvalidSchemaError>> {
    let mut errors: Vec<InvalidSchemaError> = vec![];

    for (type_name, type_defn) in vertex_types {
        let implementations = get_vertex_type_implements(type_defn);

        for implementation in implementations {
            let implementation = implementation.node.as_ref();

            let implementation_fields = get_vertex_type_fields(&vertex_types[implementation]);
            for field in implementation_fields {
                let field_name = field.node.name.node.as_ref();

                // If the current type does not contain the implemented interface's field,
                // that's an error.
                if !fields.contains_key(&(type_name.clone(), Arc::from(field_name))) {
                    errors.push(InvalidSchemaError::MissingRequiredField(
                        type_name.to_string(),
                        implementation.to_string(),
                        field_name.to_string(),
                        field.node.ty.node.to_string(),
                    ))
                }
            }
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

fn check_field_type_narrowing(
    vertex_types: &HashMap<Arc<str>, TypeDefinition>,
    fields: &HashMap<(Arc<str>, Arc<str>), FieldDefinition>,
) -> Result<(), Vec<InvalidSchemaError>> {
    let mut errors: Vec<InvalidSchemaError> = vec![];

    for (type_name, type_defn) in vertex_types {
        let implementations = get_vertex_type_implements(type_defn);
        let type_fields = get_vertex_type_fields(type_defn);

        for field in type_fields {
            let field_name = field.node.name.node.as_ref();
            let field_type = &field.node.ty.node;
            let field_parameters: BTreeMap<_, _> = field
                .node
                .arguments
                .iter()
                .map(|arg| (arg.node.name.node.as_ref(), &arg.node.ty.node))
                .collect();

            for implementation in implementations {
                let implementation = implementation.node.as_ref();

                // The parent type might not contain this field. But if it does,
                // ensure that the parent field's type is a supertype of the current field's type.
                if let Some(parent_field) =
                    fields.get(&(Arc::from(implementation), Arc::from(field_name)))
                {
                    let parent_field_type = &parent_field.ty.node;
                    if !is_subtype(vertex_types, parent_field_type, field_type) {
                        errors.push(InvalidSchemaError::InvalidTypeWideningOfInheritedField(
                            field_name.to_string(),
                            type_name.to_string(),
                            implementation.to_string(),
                            field_type.to_string(),
                            parent_field_type.to_string(),
                        ));
                    }

                    let parent_field_parameters: BTreeMap<_, _> = parent_field
                        .arguments
                        .iter()
                        .map(|arg| (arg.node.name.node.as_ref(), &arg.node.ty.node))
                        .collect();

                    // Check for field parameters that the parent type requires but
                    // the child type does not accept.
                    let missing_parameters = parent_field_parameters
                        .keys()
                        .copied()
                        .filter(|name| !field_parameters.contains_key(*name))
                        .collect_vec();
                    if !missing_parameters.is_empty() {
                        errors.push(InvalidSchemaError::InheritedFieldMissingParameters(
                            field_name.to_owned(),
                            type_name.to_string(),
                            implementation.to_owned(),
                            missing_parameters
                                .into_iter()
                                .map(ToOwned::to_owned)
                                .collect_vec(),
                        ));
                    }

                    // Check for field parameters that the parent type does not accept,
                    // but the child type defines anyway.
                    let unexpected_parameters = field_parameters
                        .keys()
                        .copied()
                        .filter(|name| !parent_field_parameters.contains_key(*name))
                        .collect_vec();
                    if !unexpected_parameters.is_empty() {
                        errors.push(InvalidSchemaError::InheritedFieldUnexpectedParameters(
                            field_name.to_owned(),
                            type_name.to_string(),
                            implementation.to_owned(),
                            unexpected_parameters
                                .into_iter()
                                .map(ToOwned::to_owned)
                                .collect_vec(),
                        ));
                    }

                    // Check that all field parameters defined by the child have types
                    // that are legal widenings of the corresponding field parameter's type
                    // on the parent type. Field parameters are contravariant, hence widenings.
                    for (&field_parameter, &field_type) in &field_parameters {
                        if let Some(&parent_field_type) =
                            parent_field_parameters.get(field_parameter)
                        {
                            if !is_scalar_only_subtype(field_type, parent_field_type) {
                                errors.push(InvalidSchemaError::InvalidTypeNarrowingOfInheritedFieldParameter(
                                    field_name.to_owned(),
                                    type_name.to_string(),
                                    implementation.to_owned(),
                                    field_parameter.to_string(),
                                    field_type.to_string(),
                                    parent_field_type.to_string(),
                                ));
                            }
                        }
                    }
                }
            }
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

fn get_vertex_type_fields(vertex: &TypeDefinition) -> &[Positioned<FieldDefinition>] {
    match &vertex.kind {
        TypeKind::Object(obj) => &obj.fields,
        TypeKind::Interface(iface) => &iface.fields,
        _ => unreachable!(),
    }
}

fn get_vertex_type_implements(vertex: &TypeDefinition) -> &[Positioned<Name>] {
    match &vertex.kind {
        TypeKind::Object(obj) => &obj.implements,
        TypeKind::Interface(iface) => &iface.implements,
        _ => unreachable!(),
    }
}

#[allow(clippy::type_complexity)]
fn get_field_origins(
    vertex_types: &HashMap<Arc<str>, TypeDefinition>,
) -> Result<BTreeMap<(Arc<str>, Arc<str>), FieldOrigin>, InvalidSchemaError> {
    let mut field_origins: BTreeMap<(Arc<str>, Arc<str>), FieldOrigin> = Default::default();
    let mut queue = VecDeque::new();

    // for each type, which types have yet to have their field origins resolved first
    let mut required_resolutions: BTreeMap<&str, BTreeSet<&str>> = vertex_types
        .iter()
        .map(|(name, defn)| {
            let resolutions: BTreeSet<&str> = get_vertex_type_implements(defn)
                .iter()
                .map(|x| x.node.as_ref())
                .collect();
            if resolutions.is_empty() {
                queue.push_back(name);
            }
            (name.as_ref(), resolutions)
        })
        .collect();

    // for each type, which types does it enable resolution of
    let resolvers: BTreeMap<&str, BTreeSet<Arc<str>>> = vertex_types
        .iter()
        .flat_map(|(name, defn)| {
            get_vertex_type_implements(defn)
                .iter()
                .map(|x| (x.node.as_ref(), Arc::from(name.as_ref())))
        })
        .fold(Default::default(), |mut acc, (interface, implementer)| {
            match acc.entry(interface) {
                Entry::Vacant(v) => {
                    v.insert(btreeset![implementer]);
                }
                Entry::Occupied(occ) => {
                    occ.into_mut().insert(implementer);
                }
            }
            acc
        });

    while let Some(type_name) = queue.pop_front() {
        let defn = &vertex_types[type_name];
        let implements = get_vertex_type_implements(defn);
        let fields = get_vertex_type_fields(defn);

        let mut implemented_fields: BTreeMap<&str, FieldOrigin> = Default::default();
        for implemented_interface in implements {
            let implemented_interface = implemented_interface.node.as_ref();
            let parent_fields = get_vertex_type_fields(&vertex_types[implemented_interface]);
            for field in parent_fields {
                let parent_field_origin = &field_origins[&(
                    Arc::from(implemented_interface),
                    Arc::from(field.node.name.node.as_ref()),
                )];

                implemented_fields
                    .entry(field.node.name.node.as_ref())
                    .and_modify(|origin| *origin = (origin as &FieldOrigin) + parent_field_origin)
                    .or_insert_with(|| parent_field_origin.clone());
            }
        }

        for field in fields {
            let field = &field.node;
            let field_name = &field.name.node;

            let origin = implemented_fields
                .remove(field_name.as_ref())
                .unwrap_or_else(|| FieldOrigin::SingleAncestor(type_name.clone()));
            field_origins
                .insert_or_error((type_name.clone(), Arc::from(field_name.as_ref())), origin)
                .unwrap();
        }

        if let Some(next_types) = resolvers.get(type_name.as_ref()) {
            for next_type in next_types.iter() {
                let remaining = required_resolutions.get_mut(next_type.as_ref()).unwrap();
                if remaining.remove(type_name.as_ref()) && remaining.is_empty() {
                    queue.push_back(next_type);
                }
            }
        }
    }

    for (required, mut remaining) in required_resolutions.into_iter() {
        if !remaining.is_empty() {
            remaining.insert(required);
            let circular_implementations =
                remaining.into_iter().map(|x| x.to_string()).collect_vec();
            return Err(InvalidSchemaError::CircularImplementsRelationships(
                circular_implementations,
            ));
        }
    }

    Ok(field_origins)
}

#[cfg(test)]
mod tests {
    use std::{
        fs,
        path::{Path, PathBuf},
    };

    use async_graphql_parser::parse_schema;
    use itertools::Itertools;
    use trustfall_filetests_macros::parameterize;

    use super::{error::InvalidSchemaError, Schema};

    #[parameterize("trustfall_core/src/resources/test_data/schema_errors", "*.graphql")]
    fn schema_errors(base: &Path, stem: &str) {
        let mut input_path = PathBuf::from(base);
        input_path.push(format!("{}.graphql", stem));

        let input_data = fs::read_to_string(input_path).unwrap();

        let mut error_path = PathBuf::from(base);
        error_path.push(format!("{}.schema-error.ron", stem));
        let error_data = fs::read_to_string(error_path).unwrap();
        let expected_error: InvalidSchemaError = ron::from_str(&error_data).unwrap();

        let schema_doc = parse_schema(input_data).unwrap();

        match Schema::new(schema_doc) {
            Err(e) => {
                assert_eq!(e, expected_error);
            }
            Ok(_) => panic!("Expected an error but got valid schema."),
        }
    }

    #[parameterize("trustfall_core/src/resources/test_data/valid_schemas", "*.graphql")]
    fn valid_schemas(base: &Path, stem: &str) {
        let mut input_path = PathBuf::from(base);
        input_path.push(format!("{}.graphql", stem));

        let input_data = fs::read_to_string(input_path).unwrap();

        // Ensure all test schemas contain the directive definitions this module promises are valid.
        assert!(input_data.contains(Schema::ALL_DIRECTIVE_DEFINITIONS));

        match Schema::parse(input_data) {
            Ok(_) => {}
            Err(e) => {
                panic!("{}", e);
            }
        }
    }

    #[test]
    fn schema_subtypes() {
        let input_data = include_str!("../resources/schemas/numbers.graphql");
        let schema = Schema::parse(input_data).expect("valid schema");

        assert!(schema.subtypes("Nonexistent").is_none());

        let composite_subtypes = schema.subtypes("Composite").unwrap().collect_vec();
        assert_eq!(vec!["Composite"], composite_subtypes);

        let mut number_subtypes = schema.subtypes("Number").unwrap().collect_vec();
        number_subtypes.sort_unstable();
        assert_eq!(
            vec!["Composite", "Neither", "Number", "Prime"],
            number_subtypes
        );
    }
}