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
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;

use apollo_parser::ast::AstChildren;
use apollo_parser::ast::AstNode;
use apollo_parser::ast::{self};
use apollo_parser::SyntaxNode;
use indexmap::IndexMap;

use crate::database::document;
use crate::database::FileId;
use crate::hir::*;
use crate::AstDatabase;
use crate::InputDatabase;

const INTROSPECTION_OBJECT_TYS: [&str; 6] = [
    "__Schema",
    "__Type",
    "__Field",
    "__InputValue",
    "__EnumValue",
    "__Directive",
];

const INTROSPECTION_ENUM_TYS: [&str; 2] = ["__TypeKind", "__DirectiveLocation"];

// HIR creators *ignore* missing data entirely. *Only* missing data
// as a result of parser errors should be ignored.

#[salsa::query_group(HirStorage)]
pub trait HirDatabase: InputDatabase + AstDatabase {
    /// Return all type system definitions defined in the compiler.
    #[salsa::invoke(type_system_definitions)]
    fn type_system_definitions(&self) -> Arc<TypeSystemDefinitions>;

    /// Return a [`TypeSystem`] containing definitions and more.
    ///
    /// This can be used with [`set_type_system_hir`][crate::ApolloCompiler::set_type_system_hir]
    /// on another compiler.
    #[salsa::invoke(type_system)]
    fn type_system(&self) -> Arc<TypeSystem>;

    /// Return all the extensions defined in the type system.
    #[salsa::invoke(extensions)]
    fn extensions(&self) -> Arc<Vec<TypeExtension>>;

    /// Return all the operations defined in a file.
    #[salsa::invoke(operations)]
    fn operations(&self, file_id: FileId) -> Arc<Vec<Arc<OperationDefinition>>>;

    /// Return all the fragments defined in a file.
    #[salsa::invoke(fragments)]
    fn fragments(&self, file_id: FileId) -> ByName<FragmentDefinition>;

    /// Return all the operations defined in any file.
    #[salsa::invoke(all_operations)]
    fn all_operations(&self) -> Arc<Vec<Arc<OperationDefinition>>>;

    /// Return all the fragments defined in any file.
    #[salsa::invoke(all_fragments)]
    fn all_fragments(&self) -> ByName<FragmentDefinition>;

    /// Return schema definition defined in the compiler.
    #[salsa::invoke(schema)]
    fn schema(&self) -> Arc<SchemaDefinition>;

    /// Return all object type definitions defined in the compiler.
    #[salsa::invoke(object_types)]
    fn object_types(&self) -> ByName<ObjectTypeDefinition>;

    /// Return all object type definitions, including instrospection types like
    /// `__Schema`, defined in the compiler.
    fn object_types_with_built_ins(&self) -> ByName<ObjectTypeDefinition>;

    /// Return all scalar type definitions defined in the compiler.
    #[salsa::invoke(scalars)]
    fn scalars(&self) -> ByName<ScalarTypeDefinition>;

    /// Return all enum type definitions defined in the compiler.
    #[salsa::invoke(enums)]
    fn enums(&self) -> ByName<EnumTypeDefinition>;

    /// Return all enums, including introspection types like `__TypeKind`, defined
    /// in the compiler.
    fn enums_with_built_ins(&self) -> ByName<EnumTypeDefinition>;

    /// Return all union type definitions defined in the compiler.
    #[salsa::invoke(unions)]
    fn unions(&self) -> ByName<UnionTypeDefinition>;

    /// Return all interface type definitions defined in the compiler.
    #[salsa::invoke(interfaces)]
    fn interfaces(&self) -> ByName<InterfaceTypeDefinition>;

    /// Return all directive definitions defined in the compiler.
    #[salsa::invoke(directive_definitions)]
    fn directive_definitions(&self) -> ByName<DirectiveDefinition>;

    /// Return all input object type definitions defined in the compiler.
    #[salsa::invoke(input_objects)]
    fn input_objects(&self) -> ByName<InputObjectTypeDefinition>;

    // Derived from above queries:

    /// Return an operation definition corresponding to the name and file id.
    /// If `name` is `None`, and there is only one operation, that operation will
    /// be returned.
    /// If `name` is `None`, and there is more than one operation, `None` will
    /// be returned.
    #[salsa::invoke(document::find_operation)]
    fn find_operation(
        &self,
        file_id: FileId,
        name: Option<String>,
    ) -> Option<Arc<OperationDefinition>>;

    /// Return an fragment definition corresponding to the name and file id.
    /// Result of this query is not cached internally.
    #[salsa::transparent]
    #[salsa::invoke(document::find_fragment_by_name)]
    fn find_fragment_by_name(
        &self,
        file_id: FileId,
        name: String,
    ) -> Option<Arc<FragmentDefinition>>;

    /// Return an object type definition corresponding to the name.
    /// Result of this query is not cached internally.
    #[salsa::transparent]
    #[salsa::invoke(document::find_object_type_by_name)]
    fn find_object_type_by_name(&self, name: String) -> Option<Arc<ObjectTypeDefinition>>;

    /// Return an union type definition corresponding to the name.
    /// Result of this query is not cached internally.
    #[salsa::transparent]
    #[salsa::invoke(document::find_union_by_name)]
    fn find_union_by_name(&self, name: String) -> Option<Arc<UnionTypeDefinition>>;

    /// Return an enum type definition corresponding to the name.
    /// Result of this query is not cached internally.
    #[salsa::transparent]
    #[salsa::invoke(document::find_enum_by_name)]
    fn find_enum_by_name(&self, name: String) -> Option<Arc<EnumTypeDefinition>>;

    /// Return a scalar type definition corresponding to the name.
    /// Result of this query is not cached internally.
    #[salsa::transparent]
    #[salsa::invoke(document::find_scalar_by_name)]
    fn find_scalar_by_name(&self, name: String) -> Option<Arc<ScalarTypeDefinition>>;

    /// Return an interface type definition corresponding to the name.
    /// Result of this query is not cached internally.
    #[salsa::transparent]
    #[salsa::invoke(document::find_interface_by_name)]
    fn find_interface_by_name(&self, name: String) -> Option<Arc<InterfaceTypeDefinition>>;

    /// Return an directive definition corresponding to the name.
    /// Result of this query is not cached internally.
    #[salsa::transparent]
    #[salsa::invoke(document::find_directive_definition_by_name)]
    fn find_directive_definition_by_name(&self, name: String) -> Option<Arc<DirectiveDefinition>>;

    /// Return any type definitions that contain the corresponding directive
    #[salsa::invoke(document::find_types_with_directive)]
    fn find_types_with_directive(&self, directive: String) -> Arc<Vec<TypeDefinition>>;

    /// Return an input object type definition corresponding to the name.
    /// Result of this query is not cached internally.
    #[salsa::transparent]
    #[salsa::invoke(document::find_input_object_by_name)]
    fn find_input_object_by_name(&self, name: String) -> Option<Arc<InputObjectTypeDefinition>>;

    #[salsa::invoke(document::types_definitions_by_name)]
    fn types_definitions_by_name(&self) -> Arc<IndexMap<String, TypeDefinition>>;

    /// Return a type definition corresponding to the name.
    /// Result of this query is not cached internally.
    #[salsa::transparent]
    #[salsa::invoke(document::find_type_definition_by_name)]
    fn find_type_definition_by_name(&self, name: String) -> Option<TypeDefinition>;

    /// Return all query operations in a corresponding file.
    #[salsa::invoke(document::query_operations)]
    fn query_operations(&self, file_id: FileId) -> Arc<Vec<Arc<OperationDefinition>>>;

    /// Return all mutation operations in a corresponding file.
    #[salsa::invoke(document::mutation_operations)]
    fn mutation_operations(&self, file_id: FileId) -> Arc<Vec<Arc<OperationDefinition>>>;

    /// Return all subscription operations in a corresponding file.
    #[salsa::invoke(document::subscription_operations)]
    fn subscription_operations(&self, file_id: FileId) -> Arc<Vec<Arc<OperationDefinition>>>;

    /// Return the fields in a selection set, not including fragments.
    #[salsa::invoke(document::operation_fields)]
    fn operation_fields(&self, selection_set: SelectionSet) -> Arc<Vec<Field>>;

    /// Return all operation inline fragment fields in a corresponding selection set.
    #[salsa::invoke(document::operation_inline_fragment_fields)]
    fn operation_inline_fragment_fields(&self, selection_set: SelectionSet) -> Arc<Vec<Field>>;

    /// Return all operation fragment spread fields in a corresponding selection set.
    #[salsa::invoke(document::operation_fragment_spread_fields)]
    fn operation_fragment_spread_fields(&self, selection_set: SelectionSet) -> Arc<Vec<Field>>;

    /// Return the fields that `selection_set` selects including visiting fragments and inline fragments.
    #[salsa::invoke(document::flattened_operation_fields)]
    fn flattened_operation_fields(&self, selection_set: SelectionSet) -> Vec<Arc<Field>>;

    /// Return all variables in a corresponding selection set.
    #[salsa::invoke(document::selection_variables)]
    fn selection_variables(&self, selection_set: SelectionSet) -> Arc<HashSet<Variable>>;

    /// Return all variables in corresponding variable definitions.
    #[salsa::invoke(document::operation_definition_variables)]
    fn operation_definition_variables(
        &self,
        variables: Arc<Vec<VariableDefinition>>,
    ) -> Arc<HashSet<Variable>>;

    /// Return a subtype map of the current compiler's type system.
    ///
    /// Given the following schema,
    /// ```graphql
    /// type Query {
    ///   me: String
    /// }
    /// type Foo {
    ///   me: String
    /// }
    /// type Bar {
    ///   me: String
    /// }
    /// union UnionType = Foo | Bar
    ///
    /// interface Baz {
    ///   me: String,
    /// }
    /// type ObjectType implements Baz { me: String }
    /// interface InterfaceType implements Baz { me: String }
    /// ```
    /// we can say that:
    ///
    /// - `Foo` and `Bar` are a subtypes of `UnionType`.
    /// - `ObjectType` and `InterfaceType` are subtypes of `Baz`.

    #[salsa::invoke(document::subtype_map)]
    fn subtype_map(&self) -> Arc<HashMap<String, HashSet<String>>>;

    /// Return `true` if the provided `maybe_subtype` is a subtype of the
    /// corresponding `abstract_type`.
    ///
    /// Given the following schema,
    /// ```graphql
    /// type Query {
    ///   me: String
    /// }
    /// type Foo {
    ///   me: String
    /// }
    /// type Bar {
    ///   me: String
    /// }
    /// union UnionType = Foo | Bar
    ///
    /// interface Baz {
    ///   me: String,
    /// }
    /// type ObjectType implements Baz { me: String }
    /// interface InterfaceType implements Baz { me: String }
    /// ```
    /// we can say that:
    ///
    /// - `db.is_subtype("UnionType".into(), "Foo".into()) // true`
    /// - `db.is_subtype("UnionType".into(), "Bar".into()) // true`
    /// - `db.is_subtype("Baz".into(), "ObjectType".into()) // true`
    /// - `db.is_subtype("Baz".into(), "InterfaceType".into()) // true`
    #[salsa::transparent]
    #[salsa::invoke(document::is_subtype)]
    fn is_subtype(&self, abstract_type: String, maybe_subtype: String) -> bool;
}

fn type_system_definitions(db: &dyn HirDatabase) -> Arc<TypeSystemDefinitions> {
    Arc::new(TypeSystemDefinitions {
        schema: db.schema(),
        scalars: db.scalars(),
        objects: db.object_types_with_built_ins(),
        interfaces: db.interfaces(),
        unions: db.unions(),
        enums: db.enums(),
        input_objects: db.input_objects(),
        directives: db.directive_definitions(),
    })
}

fn type_system(db: &dyn HirDatabase) -> Arc<TypeSystem> {
    if let Some(precomputed_input) = db.type_system_hir_input() {
        // Panics in `ApolloCompiler` methods ensure `type_definition_files().is_empty()`
        return precomputed_input;
    }
    Arc::new(TypeSystem {
        definitions: db.type_system_definitions(),
        type_definitions_by_name: db.types_definitions_by_name(),
        subtype_map: db.subtype_map(),
        inputs: db
            .type_definition_files()
            .into_iter()
            .map(|file_id| (file_id, db.input(file_id)))
            .collect(),
    })
}

fn extensions(db: &dyn HirDatabase) -> Arc<Vec<TypeExtension>> {
    let mut extensions = vec![];
    for file_id in db.type_definition_files() {
        extensions.extend(
            db.ast(file_id)
                .document()
                .syntax()
                .children()
                .filter_map(ast::Definition::cast)
                .filter_map(|def| extension(db, def, file_id)),
        );
    }

    Arc::new(extensions)
}

fn operations(db: &dyn HirDatabase, file_id: FileId) -> Arc<Vec<Arc<OperationDefinition>>> {
    Arc::new(
        db.ast(file_id)
            .document()
            .syntax()
            .children()
            .filter_map(ast::OperationDefinition::cast)
            .filter_map(|def| operation_definition(db, def, file_id))
            .map(Arc::new)
            .collect(),
    )
}

fn fragments(db: &dyn HirDatabase, file_id: FileId) -> ByName<FragmentDefinition> {
    let mut map = IndexMap::new();
    for def in db
        .ast(file_id)
        .document()
        .syntax()
        .children()
        .filter_map(ast::FragmentDefinition::cast)
        .filter_map(|def| fragment_definition(db, def, file_id))
    {
        let name = def.name().to_owned();
        map.entry(name).or_insert_with(|| Arc::new(def));
    }
    Arc::new(map)
}

fn all_operations(db: &dyn HirDatabase) -> Arc<Vec<Arc<OperationDefinition>>> {
    let mut operations = Vec::new();
    for file_id in db.executable_definition_files() {
        operations.extend(db.operations(file_id).iter().cloned())
    }
    Arc::new(operations)
}

fn all_fragments(db: &dyn HirDatabase) -> ByName<FragmentDefinition> {
    let mut fragments = IndexMap::new();
    for file_id in db.executable_definition_files() {
        for (name, def) in db.fragments(file_id).iter() {
            fragments.entry(name.clone()).or_insert_with(|| def.clone());
        }
    }
    Arc::new(fragments)
}

/// Takes a fallible conversion from a specific AST type to an HIR type,
/// finds matching top-level AST nodes in type definition files,
/// and returns an iterator of successful conversion results.
///
/// Failed conversions are ignored.
fn type_definitions<'db, AstType, TryConvert, HirType>(
    db: &'db dyn HirDatabase,
    try_convert: TryConvert,
) -> impl Iterator<Item = HirType> + 'db
where
    AstType: 'db + ast::AstNode,
    TryConvert: 'db + Copy + Fn(&dyn HirDatabase, AstType, FileId) -> Option<HirType>,
{
    db.type_definition_files()
        .into_iter()
        .flat_map(move |file_id| {
            db.ast(file_id)
                .document()
                .syntax()
                .children()
                .filter_map(AstNode::cast)
                .filter_map(move |def| try_convert(db, def, file_id))
        })
}

// FIXME(@lrlna): if our compiler is composed of multiple documents that for
// some reason have more than one schema definition, we should be raising an
// error.
//
// This implementation currently just finds the first schema definition, which
// means we can't really diagnose the "multiple schema definitions" errors.
fn schema(db: &dyn HirDatabase) -> Arc<SchemaDefinition> {
    if let Some(precomputed) = db.type_system_hir_input() {
        // Panics in `ApolloCompiler` methods ensure `type_definition_files().is_empty()`
        return precomputed.definitions.schema.clone();
    }
    Arc::new(
        type_definitions(db, schema_definition)
            .next()
            .unwrap_or_else(|| implicit_schema_definition(db)),
    )
}

macro_rules! by_name {
    ($db: ident, $convert: expr) => {{
        let mut map = IndexMap::new();
        for def in type_definitions($db, $convert) {
            let name = def.name().to_owned();
            map.entry(name).or_insert_with(|| Arc::new(def));
        }
        map
    }};
}

macro_rules! by_name_extensible {
    ($db: ident, $convert: expr, $extension_type: ident) => {{
        let mut map = by_name!($db, $convert);
        for ext in $db.extensions().iter() {
            // Orphan or incorrect extensions are reported by validation.
            if let TypeExtension::$extension_type(ext) = ext {
                if let Some(def) = map.get_mut(ext.name()) {
                    Arc::get_mut(def).unwrap().push_extension(Arc::clone(ext))
                }
            }
        }
        map
    }};
}

fn object_types_with_built_ins(db: &dyn HirDatabase) -> ByName<ObjectTypeDefinition> {
    if let Some(precomputed) = db.type_system_hir_input() {
        // Panics in `ApolloCompiler` methods ensure `type_definition_files().is_empty()`
        return precomputed.definitions.objects.clone();
    }
    Arc::new(by_name_extensible!(
        db,
        object_type_definition,
        ObjectTypeExtension
    ))
}

fn object_types(db: &dyn HirDatabase) -> ByName<ObjectTypeDefinition> {
    let mut objs = db.object_types_with_built_ins().as_ref().clone();

    objs.retain(|_k, v| !v.is_introspection());
    Arc::new(objs)
}

fn scalars(db: &dyn HirDatabase) -> ByName<ScalarTypeDefinition> {
    if let Some(precomputed) = db.type_system_hir_input() {
        // Panics in `ApolloCompiler` methods ensure `type_definition_files().is_empty()`
        return precomputed.definitions.scalars.clone();
    }
    Arc::new(by_name_extensible!(
        db,
        scalar_definition,
        ScalarTypeExtension
    ))
}
fn enums_with_built_ins(db: &dyn HirDatabase) -> ByName<EnumTypeDefinition> {
    if let Some(precomputed) = db.type_system_hir_input() {
        // Panics in `ApolloCompiler` methods ensure `type_definition_files().is_empty()`
        return precomputed.definitions.enums.clone();
    }
    Arc::new(by_name_extensible!(db, enum_definition, EnumTypeExtension))
}

fn enums(db: &dyn HirDatabase) -> ByName<EnumTypeDefinition> {
    let mut enums = db.enums_with_built_ins().as_ref().clone();

    enums.retain(|_k, v| !v.is_introspection());
    Arc::new(enums)
}

fn unions(db: &dyn HirDatabase) -> ByName<UnionTypeDefinition> {
    if let Some(precomputed) = db.type_system_hir_input() {
        // Panics in `ApolloCompiler` methods ensure `type_definition_files().is_empty()`
        return precomputed.definitions.unions.clone();
    }
    Arc::new(by_name_extensible!(
        db,
        union_definition,
        UnionTypeExtension
    ))
}

fn interfaces(db: &dyn HirDatabase) -> ByName<InterfaceTypeDefinition> {
    Arc::new(by_name_extensible!(
        db,
        interface_definition,
        InterfaceTypeExtension
    ))
}

fn input_objects(db: &dyn HirDatabase) -> ByName<InputObjectTypeDefinition> {
    if let Some(precomputed) = db.type_system_hir_input() {
        // Panics in `ApolloCompiler` methods ensure `type_definition_files().is_empty()`
        return precomputed.definitions.input_objects.clone();
    }
    Arc::new(by_name_extensible!(
        db,
        input_object_definition,
        InputObjectTypeExtension
    ))
}

fn directive_definitions(db: &dyn HirDatabase) -> ByName<DirectiveDefinition> {
    if let Some(precomputed) = db.type_system_hir_input() {
        // Panics in `ApolloCompiler` methods ensure `type_definition_files().is_empty()`
        return precomputed.definitions.directives.clone();
    }
    Arc::new(by_name!(db, directive_definition))
}

fn operation_definition(
    db: &dyn HirDatabase,
    op_def: ast::OperationDefinition,
    file_id: FileId,
) -> Option<OperationDefinition> {
    // check if there are already operations
    // if there are operations, they must have names
    // if there are no names, an error must be raised that all operations must have a name
    let name = op_def.name().map(|n| name_hir_node(n, file_id));
    let ty = operation_type(op_def.operation_type());
    let variables = variable_definitions(op_def.variable_definitions(), file_id);
    let parent_object_ty = db.schema().self_root_operations().iter().find_map(|op| {
        if op.operation_ty() == ty {
            Some(op.named_type().name())
        } else {
            None
        }
    });
    let selection_set = selection_set(db, op_def.selection_set(), parent_object_ty, file_id);
    let directives = directives(op_def.directives(), file_id);
    let loc = location(file_id, op_def.syntax());

    Some(OperationDefinition {
        operation_ty: ty,
        name,
        variables,
        selection_set,
        directives,
        loc,
    })
}

fn fragment_definition(
    db: &dyn HirDatabase,
    fragment_def: ast::FragmentDefinition,
    file_id: FileId,
) -> Option<FragmentDefinition> {
    let name = name(fragment_def.fragment_name()?.name(), file_id)?;
    let type_condition = fragment_def
        .type_condition()?
        .named_type()?
        .name()?
        .text()
        .to_string();
    let selection_set = selection_set(
        db,
        fragment_def.selection_set(),
        Some(type_condition.clone()),
        file_id,
    );
    let directives = directives(fragment_def.directives(), file_id);
    let loc = location(file_id, fragment_def.syntax());

    Some(FragmentDefinition {
        name,
        type_condition,
        selection_set,
        directives,
        loc,
    })
}

fn schema_definition(
    db: &dyn HirDatabase,
    schema_def: ast::SchemaDefinition,
    file_id: FileId,
) -> Option<SchemaDefinition> {
    let description = description(schema_def.description());
    let directives = directives(schema_def.directives(), file_id);
    let mut operations =
        root_operation_type_definition(schema_def.root_operation_type_definitions(), file_id);
    let loc = location(file_id, schema_def.syntax());
    let extensions = schema_extensions(db);
    let mut root_operation_names = root_operations_names(&operations, &extensions);
    add_implicit_operations(db, &mut operations, &mut root_operation_names);

    Some(SchemaDefinition {
        description,
        directives,
        root_operation_type_definition: Arc::new(operations),
        loc: Some(loc),
        extensions,
        root_operation_names,
    })
}

fn implicit_schema_definition(db: &dyn HirDatabase) -> SchemaDefinition {
    let extensions = schema_extensions(db);
    let mut operations = Vec::new();
    let mut root_operation_names = root_operations_names(&operations, &extensions);
    add_implicit_operations(db, &mut operations, &mut root_operation_names);
    SchemaDefinition {
        description: None,
        directives: Arc::new(Vec::new()),
        root_operation_type_definition: Arc::new(operations),
        loc: None,
        extensions,
        root_operation_names,
    }
}

fn schema_extensions(db: &dyn HirDatabase) -> Vec<Arc<SchemaExtension>> {
    type_definitions(db, |_db, def: ast::SchemaExtension, file_id| {
        let directives = directives(def.directives(), file_id);
        let root_operation_type_definition = Arc::new(root_operation_type_definition(
            def.root_operation_type_definitions(),
            file_id,
        ));
        let loc = location(file_id, def.syntax());
        Some(Arc::new(SchemaExtension {
            directives,
            root_operation_type_definition,
            loc,
        }))
    })
    .collect()
}

fn root_operations_names(
    root_operation_type_definition: &[RootOperationTypeDefinition],
    extensions: &[Arc<SchemaExtension>],
) -> RootOperationNames {
    let mut names = RootOperationNames::default();
    let mut add_operations = |ops: &[RootOperationTypeDefinition]| {
        for op in ops {
            let name_field = match op.operation_ty() {
                OperationType::Query => &mut names.query,
                OperationType::Mutation => &mut names.mutation,
                OperationType::Subscription => &mut names.subscription,
            };
            if name_field.is_none() {
                *name_field = Some(op.named_type().name());
            }
        }
    };
    add_operations(root_operation_type_definition);
    for extension in extensions {
        add_operations(extension.root_operations());
    }
    names
}

/// https://spec.graphql.org/October2021/#sec-Root-Operation-Types.Default-Root-Operation-Type-Names
///
/// To distinguish between implicit and explicit definitions for validation purposes,
/// check `operation.loc.is_none()`.
///
/// NOTE(@lrlna):
/// "Query", "Subscription", "Mutation" object type definitions do not need
/// to be explicitly defined in a schema definition, but are implicitly
/// added.
fn add_implicit_operations(
    db: &dyn HirDatabase,
    operations: &mut Vec<RootOperationTypeDefinition>,
    names: &mut RootOperationNames,
) {
    for (name_field, operation_ty) in [
        (&mut names.query, OperationType::Query),
        (&mut names.mutation, OperationType::Mutation),
        (&mut names.subscription, OperationType::Subscription),
    ] {
        let name = operation_ty.into();
        if name_field.is_none() && db.object_types_with_built_ins().contains_key(name) {
            *name_field = Some(name.to_owned());
            operations.push(RootOperationTypeDefinition {
                operation_ty,
                named_type: Type::Named {
                    name: name.to_owned(),
                    loc: None,
                },
                loc: None,
            })
        }
    }
}

fn object_type_definition(
    _db: &dyn HirDatabase,
    obj_def: ast::ObjectTypeDefinition,
    file_id: FileId,
) -> Option<ObjectTypeDefinition> {
    let description = description(obj_def.description());
    let name = name(obj_def.name(), file_id)?;
    let implements_interfaces = implements_interfaces(obj_def.implements_interfaces(), file_id);
    let directives = directives(obj_def.directives(), file_id);
    let fields_definition = fields_definition(obj_def.fields_definition(), file_id);
    let loc = location(file_id, obj_def.syntax());
    let fields_by_name = ByNameWithExtensions::new(&fields_definition, FieldDefinition::name);
    let implements_interfaces_by_name =
        ByNameWithExtensions::new(&implements_interfaces, ImplementsInterface::interface);
    let is_introspection = INTROSPECTION_OBJECT_TYS.contains(&obj_def.name()?.text().as_str());
    let implicit_fields = Arc::new(vec![type_field(), typename_field(), schema_field()]);

    // TODO(@goto-bus-stop) when a name is missing on this,
    // we might still want to produce a HIR node, so we can validate other parts of the definition
    Some(ObjectTypeDefinition {
        description,
        name,
        implements_interfaces,
        directives,
        fields_definition,
        loc,
        extensions: Vec::new(),
        fields_by_name,
        implements_interfaces_by_name,
        is_introspection,
        implicit_fields,
    })
}

fn object_type_extension(
    _db: &dyn HirDatabase,
    def: ast::ObjectTypeExtension,
    file_id: FileId,
) -> Option<Arc<ObjectTypeExtension>> {
    Some(Arc::new(ObjectTypeExtension {
        directives: directives(def.directives(), file_id),
        name: name(def.name(), file_id)?,
        implements_interfaces: implements_interfaces(def.implements_interfaces(), file_id),
        fields_definition: fields_definition(def.fields_definition(), file_id),
        loc: location(file_id, def.syntax()),
    }))
}

fn scalar_definition(
    db: &dyn HirDatabase,
    scalar_def: ast::ScalarTypeDefinition,
    file_id: FileId,
) -> Option<ScalarTypeDefinition> {
    let description = description(scalar_def.description());
    let name = name(scalar_def.name(), file_id)?;
    let directives = directives(scalar_def.directives(), file_id);
    let loc = location(file_id, scalar_def.syntax());
    let built_in = db.input(file_id).source_type().is_built_in();

    // TODO(@goto-bus-stop) when a name is missing on this,
    // we might still want to produce a HIR node, so we can validate other parts of the definition
    Some(ScalarTypeDefinition {
        description,
        name,
        directives,
        loc,
        built_in,
        extensions: Vec::new(),
    })
}

fn scalar_extension(
    _db: &dyn HirDatabase,
    def: ast::ScalarTypeExtension,
    file_id: FileId,
) -> Option<Arc<ScalarTypeExtension>> {
    Some(Arc::new(ScalarTypeExtension {
        directives: directives(def.directives(), file_id),
        name: name(def.name(), file_id)?,
        loc: location(file_id, def.syntax()),
    }))
}

fn enum_definition(
    _db: &dyn HirDatabase,
    enum_def: ast::EnumTypeDefinition,
    file_id: FileId,
) -> Option<EnumTypeDefinition> {
    let description = description(enum_def.description());
    let name = name(enum_def.name(), file_id)?;
    let directives = directives(enum_def.directives(), file_id);
    let enum_values_definition = enum_values_definition(enum_def.enum_values_definition(), file_id);
    let loc = location(file_id, enum_def.syntax());
    let values_by_name =
        ByNameWithExtensions::new(&enum_values_definition, EnumValueDefinition::enum_value);
    let is_introspection = INTROSPECTION_ENUM_TYS.contains(&enum_def.name()?.text().as_str());

    // TODO(@goto-bus-stop) when a name is missing on this,
    // we might still want to produce a HIR node, so we can validate other parts of the definition
    Some(EnumTypeDefinition {
        description,
        name,
        directives,
        enum_values_definition,
        loc,
        extensions: Vec::new(),
        values_by_name,
        is_introspection,
    })
}

fn enum_extension(
    _db: &dyn HirDatabase,
    def: ast::EnumTypeExtension,
    file_id: FileId,
) -> Option<Arc<EnumTypeExtension>> {
    Some(Arc::new(EnumTypeExtension {
        directives: directives(def.directives(), file_id),
        name: name(def.name(), file_id)?,
        enum_values_definition: enum_values_definition(def.enum_values_definition(), file_id),
        loc: location(file_id, def.syntax()),
    }))
}

fn enum_values_definition(
    enum_values_def: Option<ast::EnumValuesDefinition>,
    file_id: FileId,
) -> Arc<Vec<EnumValueDefinition>> {
    match enum_values_def {
        Some(enum_values) => {
            let enum_values = enum_values
                .enum_value_definitions()
                .filter_map(|e| enum_value_definition(e, file_id))
                .collect();
            Arc::new(enum_values)
        }
        None => Arc::new(Vec::new()),
    }
}

fn enum_value_definition(
    enum_value_def: ast::EnumValueDefinition,
    file_id: FileId,
) -> Option<EnumValueDefinition> {
    let description = description(enum_value_def.description());
    let enum_value = enum_value(enum_value_def.enum_value(), file_id)?;
    let directives = directives(enum_value_def.directives(), file_id);
    let loc = location(file_id, enum_value_def.syntax());

    Some(EnumValueDefinition {
        description,
        enum_value,
        directives,
        loc,
    })
}

fn union_definition(
    _db: &dyn HirDatabase,
    union_def: ast::UnionTypeDefinition,
    file_id: FileId,
) -> Option<UnionTypeDefinition> {
    let description = description(union_def.description());
    let name = name(union_def.name(), file_id)?;
    let directives = directives(union_def.directives(), file_id);
    let union_members = union_members(union_def.union_member_types(), file_id);
    let loc = location(file_id, union_def.syntax());
    let members_by_name = ByNameWithExtensions::new(&union_members, UnionMember::name);
    let implicit_fields = Arc::new(vec![typename_field()]);

    // TODO(@goto-bus-stop) when a name is missing on this,
    // we might still want to produce a HIR node, so we can validate other parts of the definition
    Some(UnionTypeDefinition {
        description,
        name,
        directives,
        union_members,
        loc,
        extensions: Vec::new(),
        members_by_name,
        implicit_fields,
    })
}

fn union_extension(
    _db: &dyn HirDatabase,
    def: ast::UnionTypeExtension,
    file_id: FileId,
) -> Option<Arc<UnionTypeExtension>> {
    let directives = directives(def.directives(), file_id);
    let name = name(def.name(), file_id)?;
    let union_members = union_members(def.union_member_types(), file_id);
    let loc = location(file_id, def.syntax());
    let members_by_name = ByNameWithExtensions::new(&union_members, UnionMember::name);
    Some(Arc::new(UnionTypeExtension {
        directives,
        name,
        union_members,
        loc,
        members_by_name,
    }))
}

fn union_members(
    union_members: Option<ast::UnionMemberTypes>,
    file_id: FileId,
) -> Arc<Vec<UnionMember>> {
    match union_members {
        Some(members) => {
            let mems = members
                .named_types()
                .filter_map(|u| union_member(u, file_id))
                .collect();
            Arc::new(mems)
        }
        None => Arc::new(Vec::new()),
    }
}

fn union_member(member: ast::NamedType, file_id: FileId) -> Option<UnionMember> {
    let name = name(member.name(), file_id)?;
    let loc = location(file_id, member.syntax());

    Some(UnionMember { name, loc })
}

fn interface_definition(
    _db: &dyn HirDatabase,
    interface_def: ast::InterfaceTypeDefinition,
    file_id: FileId,
) -> Option<InterfaceTypeDefinition> {
    let description = description(interface_def.description());
    let name = name(interface_def.name(), file_id)?;
    let implements_interfaces =
        implements_interfaces(interface_def.implements_interfaces(), file_id);
    let directives = directives(interface_def.directives(), file_id);
    let fields_definition = fields_definition(interface_def.fields_definition(), file_id);
    let loc = location(file_id, interface_def.syntax());
    let fields_by_name = ByNameWithExtensions::new(&fields_definition, FieldDefinition::name);
    let implements_interfaces_by_name =
        ByNameWithExtensions::new(&implements_interfaces, ImplementsInterface::interface);
    let implicit_fields = Arc::new(vec![typename_field()]);

    // TODO(@goto-bus-stop) when a name is missing on this,
    // we might still want to produce a HIR node, so we can validate other parts of the definition
    Some(InterfaceTypeDefinition {
        description,
        name,
        implements_interfaces,
        directives,
        fields_definition,
        loc,
        extensions: Vec::new(),
        fields_by_name,
        implements_interfaces_by_name,
        implicit_fields,
    })
}

fn interface_extension(
    _db: &dyn HirDatabase,
    def: ast::InterfaceTypeExtension,
    file_id: FileId,
) -> Option<Arc<InterfaceTypeExtension>> {
    Some(Arc::new(InterfaceTypeExtension {
        directives: directives(def.directives(), file_id),
        name: name(def.name(), file_id)?,
        implements_interfaces: implements_interfaces(def.implements_interfaces(), file_id),
        fields_definition: fields_definition(def.fields_definition(), file_id),
        loc: location(file_id, def.syntax()),
    }))
}

fn directive_definition(
    _db: &dyn HirDatabase,
    directive_def: ast::DirectiveDefinition,
    file_id: FileId,
) -> Option<DirectiveDefinition> {
    let name = name(directive_def.name(), file_id)?;
    let description = description(directive_def.description());
    let arguments = arguments_definition(directive_def.arguments_definition(), file_id);
    let repeatable = directive_def.repeatable_token().is_some();
    let directive_locations = directive_locations(directive_def.directive_locations());
    let loc = location(file_id, directive_def.syntax());

    // TODO(@goto-bus-stop) when a name is missing on this,
    // we might still want to produce a HIR node, so we can validate other parts of the definition
    Some(DirectiveDefinition {
        description,
        name,
        arguments,
        repeatable,
        directive_locations,
        loc,
    })
}

fn input_object_definition(
    _db: &dyn HirDatabase,
    input_obj: ast::InputObjectTypeDefinition,
    file_id: FileId,
) -> Option<InputObjectTypeDefinition> {
    let description = description(input_obj.description());
    let name = name(input_obj.name(), file_id)?;
    let directives = directives(input_obj.directives(), file_id);
    let input_fields_definition =
        input_fields_definition(input_obj.input_fields_definition(), file_id);
    let loc = location(file_id, input_obj.syntax());
    let input_fields_by_name =
        ByNameWithExtensions::new(&input_fields_definition, InputValueDefinition::name);

    // TODO(@goto-bus-stop) when a name is missing on this,
    // we might still want to produce a HIR node, so we can validate other parts of the definition
    Some(InputObjectTypeDefinition {
        description,
        name,
        directives,
        input_fields_definition,
        loc,
        extensions: Vec::new(),
        input_fields_by_name,
    })
}

fn input_object_extension(
    _db: &dyn HirDatabase,
    def: ast::InputObjectTypeExtension,
    file_id: FileId,
) -> Option<Arc<InputObjectTypeExtension>> {
    Some(Arc::new(InputObjectTypeExtension {
        directives: directives(def.directives(), file_id),
        name: name(def.name(), file_id)?,
        input_fields_definition: input_fields_definition(def.input_fields_definition(), file_id),
        loc: location(file_id, def.syntax()),
    }))
}

fn extension(db: &dyn HirDatabase, def: ast::Definition, file_id: FileId) -> Option<TypeExtension> {
    match def {
        ast::Definition::ScalarTypeExtension(def) => {
            scalar_extension(db, def, file_id).map(TypeExtension::ScalarTypeExtension)
        }
        ast::Definition::ObjectTypeExtension(def) => {
            object_type_extension(db, def, file_id).map(TypeExtension::ObjectTypeExtension)
        }
        ast::Definition::InterfaceTypeExtension(def) => {
            interface_extension(db, def, file_id).map(TypeExtension::InterfaceTypeExtension)
        }
        ast::Definition::UnionTypeExtension(def) => {
            union_extension(db, def, file_id).map(TypeExtension::UnionTypeExtension)
        }
        ast::Definition::EnumTypeExtension(def) => {
            enum_extension(db, def, file_id).map(TypeExtension::EnumTypeExtension)
        }
        ast::Definition::InputObjectTypeExtension(def) => {
            input_object_extension(db, def, file_id).map(TypeExtension::InputObjectTypeExtension)
        }
        _ => None,
    }
}

fn type_field() -> FieldDefinition {
    FieldDefinition {
        description: None,
        name: Name {
            src: "__type".into(),
            loc: None,
        },
        arguments: ArgumentsDefinition {
            input_values: Arc::new(vec![InputValueDefinition {
                description: None,
                name: Name {
                    src: "name".into(),
                    loc: None,
                },
                ty: Type::NonNull {
                    ty: Box::new(Type::Named {
                        name: "String".into(),
                        loc: None,
                    }),
                    loc: None,
                },
                default_value: None,
                directives: Arc::new(Vec::new()),
                loc: None,
            }]),
            loc: None,
        },
        ty: Type::Named {
            name: "__Type".into(),
            loc: None,
        },
        directives: Arc::new(Vec::new()),
        loc: None,
    }
}

fn schema_field() -> FieldDefinition {
    FieldDefinition {
        description: None,
        name: Name {
            src: "__schema".into(),
            loc: None,
        },
        arguments: ArgumentsDefinition {
            input_values: Arc::new(Vec::new()),
            loc: None,
        },
        ty: Type::NonNull {
            ty: Box::new(Type::Named {
                name: "__Schema".into(),
                loc: None,
            }),
            loc: None,
        },
        directives: Arc::new(Vec::new()),
        loc: None,
    }
}

fn typename_field() -> FieldDefinition {
    FieldDefinition {
        description: None,
        name: Name {
            src: "__typename".into(),
            loc: None,
        },
        arguments: ArgumentsDefinition {
            input_values: Arc::new(Vec::new()),
            loc: None,
        },
        ty: Type::NonNull {
            ty: Box::new(Type::Named {
                name: "String".into(),
                loc: None,
            }),
            loc: None,
        },
        directives: Arc::new(Vec::new()),
        loc: None,
    }
}

fn implements_interfaces(
    implements_interfaces: Option<ast::ImplementsInterfaces>,
    file_id: FileId,
) -> Arc<Vec<ImplementsInterface>> {
    let interfaces: Vec<ImplementsInterface> = implements_interfaces
        .iter()
        .flat_map(|interfaces| {
            let types: Vec<ImplementsInterface> = interfaces
                .named_types()
                .filter_map(|n| {
                    let name = n.name()?;
                    Some(ImplementsInterface {
                        interface: name_hir_node(name, file_id),
                        loc: location(file_id, n.syntax()),
                    })
                })
                .collect();
            types
        })
        .collect();

    Arc::new(interfaces)
}

fn fields_definition(
    fields_definition: Option<ast::FieldsDefinition>,
    file_id: FileId,
) -> Arc<Vec<FieldDefinition>> {
    match fields_definition {
        Some(fields_def) => {
            let fields: Vec<FieldDefinition> = fields_def
                .field_definitions()
                .filter_map(|f| field_definition(f, file_id))
                .collect();
            Arc::new(fields)
        }
        None => Arc::new(Vec::new()),
    }
}

fn field_definition(field: ast::FieldDefinition, file_id: FileId) -> Option<FieldDefinition> {
    let description = description(field.description());
    let name = name(field.name(), file_id)?;
    let arguments = arguments_definition(field.arguments_definition(), file_id);
    let ty = ty(field.ty()?, file_id)?;
    let directives = directives(field.directives(), file_id);
    let loc = location(file_id, field.syntax());

    Some(FieldDefinition {
        description,
        name,
        arguments,
        ty,
        directives,
        loc: Some(loc),
    })
}

fn arguments_definition(
    arguments_definition: Option<ast::ArgumentsDefinition>,
    file_id: FileId,
) -> ArgumentsDefinition {
    match arguments_definition {
        Some(arguments) => {
            let input_values =
                input_value_definitions(arguments.input_value_definitions(), file_id);
            let loc = location(file_id, arguments.syntax());

            ArgumentsDefinition {
                input_values,
                loc: Some(loc),
            }
        }
        None => ArgumentsDefinition {
            input_values: Arc::new(Vec::new()),
            loc: None,
        },
    }
}

fn input_fields_definition(
    input_fields: Option<ast::InputFieldsDefinition>,
    file_id: FileId,
) -> Arc<Vec<InputValueDefinition>> {
    match input_fields {
        Some(fields) => input_value_definitions(fields.input_value_definitions(), file_id),
        None => Arc::new(Vec::new()),
    }
}

fn input_value_definitions(
    input_values: AstChildren<ast::InputValueDefinition>,
    file_id: FileId,
) -> Arc<Vec<InputValueDefinition>> {
    let input_values: Vec<InputValueDefinition> = input_values
        .filter_map(|input| {
            let description = description(input.description());
            let name = name(input.name(), file_id)?;
            let ty = ty(input.ty()?, file_id)?;
            let default_value = default_value(input.default_value(), file_id);
            let directives = directives(input.directives(), file_id);
            let loc = location(file_id, input.syntax());

            Some(InputValueDefinition {
                description,
                name,
                ty,
                default_value,
                directives,
                loc: Some(loc),
            })
        })
        .collect();
    Arc::new(input_values)
}

fn default_value(
    default_value: Option<ast::DefaultValue>,
    file_id: FileId,
) -> Option<DefaultValue> {
    default_value
        .and_then(|val| val.value())
        .and_then(|val| value(val, file_id))
}

fn root_operation_type_definition(
    root_type_def: AstChildren<ast::RootOperationTypeDefinition>,
    file_id: FileId,
) -> Vec<RootOperationTypeDefinition> {
    root_type_def
        .into_iter()
        .filter_map(|ty| {
            if let Some(named_ty) = ty.named_type() {
                let operation_type = operation_type(ty.operation_type());
                let named_type = named_type(named_ty.name()?, file_id);
                let loc = location(file_id, ty.syntax());

                Some(RootOperationTypeDefinition {
                    operation_ty: operation_type,
                    named_type,
                    loc: Some(loc),
                })
            } else {
                None
            }
        })
        .collect()
}

fn operation_type(op_type: Option<ast::OperationType>) -> OperationType {
    match op_type {
        Some(ty) => {
            if ty.query_token().is_some() {
                OperationType::Query
            } else if ty.mutation_token().is_some() {
                OperationType::Mutation
            } else if ty.subscription_token().is_some() {
                OperationType::Subscription
            } else {
                OperationType::Query
            }
        }
        None => OperationType::Query,
    }
}

fn variable_definitions(
    variable_definitions: Option<ast::VariableDefinitions>,
    file_id: FileId,
) -> Arc<Vec<VariableDefinition>> {
    match variable_definitions {
        Some(vars) => {
            let variable_definitions = vars
                .variable_definitions()
                .filter_map(|v| variable_definition(v, file_id))
                .collect();
            Arc::new(variable_definitions)
        }
        None => Arc::new(Vec::new()),
    }
}

fn variable_definition(
    var: ast::VariableDefinition,
    file_id: FileId,
) -> Option<VariableDefinition> {
    let name = name(var.variable()?.name(), file_id)?;
    let directives = directives(var.directives(), file_id);
    let default_value = default_value(var.default_value(), file_id);
    let ty = ty(var.ty()?, file_id)?;
    let loc = location(file_id, var.syntax());

    Some(VariableDefinition {
        name,
        directives,
        ty,
        default_value,
        loc,
    })
}

fn ty(ty_: ast::Type, file_id: FileId) -> Option<Type> {
    match ty_ {
        ast::Type::NamedType(name) => name.name().map(|name| named_type(name, file_id)),
        ast::Type::ListType(list) => Some(Type::List {
            ty: Box::new(ty(list.ty()?, file_id)?),
            loc: Some(location(file_id, list.syntax())),
        }),
        ast::Type::NonNullType(non_null) => {
            if let Some(n) = non_null.named_type() {
                let named_type = n.name().map(|name| named_type(name, file_id))?;
                Some(Type::NonNull {
                    ty: Box::new(named_type),
                    loc: Some(location(file_id, n.syntax())),
                })
            } else if let Some(list) = non_null.list_type() {
                let list_type = Type::List {
                    ty: Box::new(ty(list.ty()?, file_id)?),
                    loc: Some(location(file_id, list.syntax())),
                };
                Some(Type::NonNull {
                    ty: Box::new(list_type),
                    loc: Some(location(file_id, list.syntax())),
                })
            } else {
                // TODO: parser should have caught an error if there wasn't
                // either a named type or list type. Figure out a graceful way
                // to surface this error from the parser.
                panic!("Parser should have caught this error");
            }
        }
    }
}

fn named_type(name: ast::Name, file_id: FileId) -> Type {
    Type::Named {
        name: name.text().to_string(),
        loc: Some(location(file_id, name.syntax())),
    }
}

fn directive_locations(
    directive_locations: Option<ast::DirectiveLocations>,
) -> Arc<Vec<DirectiveLocation>> {
    match directive_locations {
        Some(directive_loc) => {
            let locations: Vec<DirectiveLocation> = directive_loc
                .directive_locations()
                .map(|loc| loc.into())
                .collect();
            Arc::new(locations)
        }
        None => Arc::new(Vec::new()),
    }
}

fn directives(directives: Option<ast::Directives>, file_id: FileId) -> Arc<Vec<Directive>> {
    match directives {
        Some(directives) => {
            let directives = directives
                .directives()
                .filter_map(|d| directive(d, file_id))
                .collect();
            Arc::new(directives)
        }
        None => Arc::new(Vec::new()),
    }
}

fn directive(directive: ast::Directive, file_id: FileId) -> Option<Directive> {
    let name = name(directive.name(), file_id)?;
    let arguments = arguments(directive.arguments(), file_id);
    let loc = location(file_id, directive.syntax());

    Some(Directive {
        name,
        arguments,
        loc,
    })
}

fn arguments(arguments: Option<ast::Arguments>, file_id: FileId) -> Arc<Vec<Argument>> {
    match arguments {
        Some(arguments) => {
            let arguments = arguments
                .arguments()
                .filter_map(|a| argument(a, file_id))
                .collect();
            Arc::new(arguments)
        }
        None => Arc::new(Vec::new()),
    }
}

fn argument(argument: ast::Argument, file_id: FileId) -> Option<Argument> {
    let name = name(argument.name(), file_id)?;
    let value = value(argument.value()?, file_id)?;
    let loc = location(file_id, argument.syntax());

    Some(Argument { name, value, loc })
}

fn value(val: ast::Value, file_id: FileId) -> Option<Value> {
    let hir_val = match val {
        ast::Value::Variable(var) => Value::Variable(Variable {
            name: var.name()?.text().to_string(),
            loc: location(file_id, var.syntax()),
        }),
        ast::Value::StringValue(string_val) => Value::String(string_val.into()),
        // TODO(@goto-bus-stop) do not unwrap
        ast::Value::FloatValue(float) => Value::Float(Float::new(float.try_into().unwrap())),
        ast::Value::IntValue(int) => Value::Int(Float::new(f64::try_from(int).unwrap())),
        ast::Value::BooleanValue(bool) => Value::Boolean(bool.try_into().unwrap()),
        ast::Value::NullValue(_) => Value::Null,
        ast::Value::EnumValue(enum_) => Value::Enum(name(enum_.name(), file_id)?),
        ast::Value::ListValue(list) => {
            let list: Vec<Value> = list.values().filter_map(|v| value(v, file_id)).collect();
            Value::List(list)
        }
        ast::Value::ObjectValue(object) => {
            let object_values: Vec<(Name, Value)> = object
                .object_fields()
                .filter_map(|o| {
                    let name = name(o.name(), file_id)?;
                    let value = value(o.value()?, file_id)?;
                    Some((name, value))
                })
                .collect();
            Value::Object(object_values)
        }
    };
    Some(hir_val)
}

fn selection_set(
    db: &dyn HirDatabase,
    selections: Option<ast::SelectionSet>,
    parent_obj_ty: Option<String>,
    file_id: FileId,
) -> SelectionSet {
    let selection_set = match selections {
        Some(sel) => sel
            .selections()
            .filter_map(|sel| selection(db, sel, parent_obj_ty.as_ref().cloned(), file_id))
            .collect(),
        None => Vec::new(),
    };

    SelectionSet {
        selection: Arc::new(selection_set),
    }
}

fn selection(
    db: &dyn HirDatabase,
    selection: ast::Selection,
    parent_obj_ty: Option<String>,
    file_id: FileId,
) -> Option<Selection> {
    match selection {
        ast::Selection::Field(sel_field) => {
            field(db, sel_field, parent_obj_ty, file_id).map(Selection::Field)
        }
        ast::Selection::FragmentSpread(fragment) => {
            fragment_spread(fragment, file_id).map(Selection::FragmentSpread)
        }
        ast::Selection::InlineFragment(fragment) => Some(Selection::InlineFragment(
            inline_fragment(db, fragment, parent_obj_ty, file_id),
        )),
    }
}

fn inline_fragment(
    db: &dyn HirDatabase,
    fragment: ast::InlineFragment,
    parent_obj: Option<String>,
    file_id: FileId,
) -> Arc<InlineFragment> {
    let type_condition = fragment.type_condition().and_then(|tc| {
        let tc = tc.named_type()?.name()?;
        Some(name_hir_node(tc, file_id))
    });
    let directives = directives(fragment.directives(), file_id);
    let new_parent_obj = if let Some(type_condition) = type_condition.clone() {
        Some(type_condition.src().to_string())
    } else {
        parent_obj
    };
    let selection_set: SelectionSet =
        selection_set(db, fragment.selection_set(), new_parent_obj, file_id);
    let loc = location(file_id, fragment.syntax());

    let fragment_data = InlineFragment {
        type_condition,
        directives,
        selection_set,
        loc,
    };
    Arc::new(fragment_data)
}

fn fragment_spread(fragment: ast::FragmentSpread, file_id: FileId) -> Option<Arc<FragmentSpread>> {
    let name = name(fragment.fragment_name()?.name(), file_id)?;
    let directives = directives(fragment.directives(), file_id);
    let loc = location(file_id, fragment.syntax());

    let fragment_data = FragmentSpread {
        name,
        directives,
        loc,
    };
    Some(Arc::new(fragment_data))
}

fn field(
    db: &dyn HirDatabase,
    field: ast::Field,
    parent_obj: Option<String>,
    file_id: FileId,
) -> Option<Arc<Field>> {
    let name = name(field.name(), file_id)?;
    let alias = alias(field.alias());
    let new_parent_obj = parent_ty(db, name.src(), parent_obj.clone());
    let selection_set = selection_set(db, field.selection_set(), new_parent_obj, file_id);
    let directives = directives(field.directives(), file_id);
    let arguments = arguments(field.arguments(), file_id);
    let loc = location(file_id, field.syntax());

    let field_data = Field {
        name,
        alias,
        selection_set,
        parent_obj,
        directives,
        arguments,
        loc,
    };
    Some(Arc::new(field_data))
}

fn parent_ty(db: &dyn HirDatabase, field_name: &str, parent_obj: Option<String>) -> Option<String> {
    Some(
        db.find_type_definition_by_name(parent_obj?)?
            .field(db, field_name)?
            .ty()
            .name(),
    )
}

fn name(name: Option<ast::Name>, file_id: FileId) -> Option<Name> {
    name.map(|name| name_hir_node(name, file_id))
}

fn name_hir_node(name: ast::Name, file_id: FileId) -> Name {
    Name {
        src: name.text().to_string(),
        loc: Some(location(file_id, name.syntax())),
    }
}

fn enum_value(enum_value: Option<ast::EnumValue>, file_id: FileId) -> Option<Name> {
    let name = enum_value?.name()?;
    Some(name_hir_node(name, file_id))
}

fn description(description: Option<ast::Description>) -> Option<String> {
    description.and_then(|desc| Some(desc.string_value()?.into()))
}

fn alias(alias: Option<ast::Alias>) -> Option<Arc<Alias>> {
    alias.and_then(|alias| {
        let name = alias.name()?.text().to_string();
        let alias_data = Alias(name);
        Some(Arc::new(alias_data))
    })
}

fn location(file_id: FileId, syntax_node: &SyntaxNode) -> HirNodeLocation {
    HirNodeLocation::new(file_id, syntax_node)
}