libgraphql-parser 0.0.5

A blazing fast, error-focused, lossless GraphQL parser for schema, executable, and mixed documents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
//! Shared helper functions for converting between
//! libgraphql AST types and `graphql_parser` v0.4 types.
//!
//! This module contains position converters, value
//! mappers, and sub-node converters used by both the
//! `to_*` (libgraphql → graphql_parser) and `from_*`
//! (graphql_parser → libgraphql) directions.

use std::borrow::Cow;

use crate::ByteSpan;
use crate::ast;

// ───────────────────────────────────────────────────
// Position converters
// ───────────────────────────────────────────────────

/// Convert a `ByteSpan`'s start byte offset to a
/// `graphql_parser` `Pos`.
///
/// When a `SourceMap` with source text is provided,
/// the byte offset is resolved to accurate
/// `(line, column)` values. Otherwise falls back to
/// `Pos { line: 1, column: 1 }`.
pub(super) fn pos_from_span(
    span: ByteSpan,
    source_map: &crate::SourceMap<'_>,
) -> graphql_parser::Pos {
    source_map
        .resolve_offset(span.start)
        .map(|p| graphql_parser::Pos {
            line: p.line() + 1,
            column: p.col_utf8() + 1,
        })
        .unwrap_or(graphql_parser::Pos {
            line: 1,
            column: 1,
        })
}

/// Convert a `ByteSpan`'s exclusive end byte offset
/// to a `graphql_parser` `Pos`.
///
/// Our `span.end` is an exclusive byte offset (one
/// past the last character), but `graphql_parser`
/// records end positions as inclusive (pointing at the
/// last character). We subtract 1 before resolving to
/// get the correct position.
pub(super) fn end_pos_from_span(
    span: ByteSpan,
    source_map: &crate::SourceMap<'_>,
) -> graphql_parser::Pos {
    let end_inclusive =
        span.end.saturating_sub(1);
    source_map
        .resolve_offset(end_inclusive)
        .map(|p| graphql_parser::Pos {
            line: p.line() + 1,
            column: p.col_utf8() + 1,
        })
        .unwrap_or(graphql_parser::Pos {
            line: 1,
            column: 1,
        })
}

/// Compute the position that `graphql_parser` records
/// for type extensions.
///
/// `graphql_parser` captures `position()` after consuming
/// the `extend` keyword, landing on the type keyword that
/// follows (e.g., `type`, `enum`, `scalar`, `interface`,
/// `union`, or `input`). We scan forward from the end of
/// `extend` (6 bytes) past any whitespace to find the
/// start of the next keyword.
///
/// Falls back to `span.start + 7` (assuming a single
/// space) when source text is unavailable.
pub(super) fn type_ext_pos_from_span(
    span: ByteSpan,
    source_map: &crate::SourceMap<'_>,
) -> graphql_parser::Pos {
    // "extend" is 6 bytes. Scan past whitespace from
    // byte offset span.start + 6 to find the type keyword.
    let keyword_offset = source_map.source()
        .map(|source| {
            let start = (span.start as usize) + 6;
            let rest = &source[start..];
            let ws_len = rest.len() - rest.trim_start().len();
            (start + ws_len) as u32
        })
        .unwrap_or(span.start + 7);

    source_map
        .resolve_offset(keyword_offset)
        .map(|p| graphql_parser::Pos {
            line: p.line() + 1,
            column: p.col_utf8() + 1,
        })
        .unwrap_or(graphql_parser::Pos {
            line: 1,
            column: 1,
        })
}

// ───────────────────────────────────────────────────
// to_gp helpers: libgraphql AST → graphql_parser
// ───────────────────────────────────────────────────

/// Convert an `ast::Value` to a
/// `graphql_parser::query::Value`.
///
/// All semantic content is preserved. Ownership changes
/// from `Cow<str>` to `String` (Loss Inventory item 6).
/// `ObjectValue` field ordering becomes alphabetical via
/// `BTreeMap` (Loss Inventory item 4).
pub(crate) fn value_to_gp(
    val: &ast::Value<'_>,
) -> graphql_parser::query::Value<'static, String> {
    use graphql_parser::query::Value as GpValue;
    match val {
        ast::Value::Boolean(b) => {
            GpValue::Boolean(b.value)
        },
        ast::Value::Enum(e) => {
            GpValue::Enum(e.value.to_string())
        },
        ast::Value::Float(f) => {
            GpValue::Float(f.value)
        },
        ast::Value::Int(i) => {
            GpValue::Int(i.value.into())
        },
        ast::Value::List(l) => GpValue::List(
            l.values.iter().map(value_to_gp).collect(),
        ),
        ast::Value::Null(_) => GpValue::Null,
        ast::Value::Object(o) => {
            let mut map =
                std::collections::BTreeMap::new();
            for field in &o.fields {
                map.insert(
                    field.name.value.to_string(),
                    value_to_gp(&field.value),
                );
            }
            GpValue::Object(map)
        },
        ast::Value::String(s) => {
            GpValue::String(s.value.to_string())
        },
        ast::Value::Variable(var) => {
            GpValue::Variable(
                var.name.value.to_string(),
            )
        },
    }
}

/// Convert an `ast::TypeAnnotation` to a
/// `graphql_parser::schema::Type`.
///
/// Our AST flattens non-null into a `Nullability` field
/// on each annotation node, while `graphql_parser` wraps
/// with a recursive `NonNullType` variant. This function
/// reconstructs the recursive form.
pub(crate) fn type_annotation_to_gp(
    ta: &ast::TypeAnnotation<'_>,
) -> graphql_parser::schema::Type<'static, String> {
    use graphql_parser::schema::Type as GpType;
    match ta {
        ast::TypeAnnotation::Named(n) => {
            let inner = GpType::NamedType(
                n.name.value.to_string(),
            );
            match &n.nullability {
                ast::Nullability::NonNull { .. } => {
                    GpType::NonNullType(Box::new(inner))
                },
                ast::Nullability::Nullable => inner,
            }
        },
        ast::TypeAnnotation::List(l) => {
            let inner = GpType::ListType(Box::new(
                type_annotation_to_gp(&l.element_type),
            ));
            match &l.nullability {
                ast::Nullability::NonNull { .. } => {
                    GpType::NonNullType(Box::new(inner))
                },
                ast::Nullability::Nullable => inner,
            }
        },
    }
}

/// Convert an `ast::DirectiveAnnotation` to a
/// `graphql_parser` `Directive`.
///
/// Arguments become `(String, Value)` tuples.
pub(crate) fn directive_to_gp(
    dir: &ast::DirectiveAnnotation<'_>,
    source_map: &crate::SourceMap<'_>,
) -> graphql_parser::query::Directive<'static, String> {
    graphql_parser::query::Directive {
        position: pos_from_span(dir.span, source_map),
        name: dir.name.value.to_string(),
        arguments: dir
            .arguments
            .iter()
            .map(|arg| {
                (
                    arg.name.value.to_string(),
                    value_to_gp(&arg.value),
                )
            })
            .collect(),
    }
}

/// Convert a slice of `DirectiveAnnotation` to a vec
/// of `graphql_parser` `Directive`.
pub(super) fn directives_to_gp(
    dirs: &[ast::DirectiveAnnotation<'_>],
    source_map: &crate::SourceMap<'_>,
) -> Vec<
    graphql_parser::query::Directive<'static, String>,
> {
    dirs.iter()
        .map(|d| directive_to_gp(d, source_map))
        .collect()
}

/// Convert an optional `StringValue` description to an
/// `Option<String>`.
pub(crate) fn description_to_gp(
    desc: &Option<ast::StringValue<'_>>,
) -> Option<String> {
    desc.as_ref().map(|s| s.value.to_string())
}

/// Convert an `ast::InputValueDefinition` to a
/// `graphql_parser::schema::InputValue`.
pub(crate) fn input_value_def_to_gp(
    ivd: &ast::InputValueDefinition<'_>,
    source_map: &crate::SourceMap<'_>,
) -> graphql_parser::schema::InputValue<'static, String>
{
    graphql_parser::schema::InputValue {
        position: match &ivd.description {
            Some(desc) => {
                pos_from_span(desc.span, source_map)
            },
            None => {
                pos_from_span(ivd.span, source_map)
            },
        },
        description: description_to_gp(
            &ivd.description,
        ),
        name: ivd.name.value.to_string(),
        value_type: type_annotation_to_gp(
            &ivd.value_type,
        ),
        default_value: ivd
            .default_value
            .as_ref()
            .map(value_to_gp),
        directives: directives_to_gp(
            &ivd.directives, source_map,
        ),
    }
}

/// Convert an `ast::FieldDefinition` to a
/// `graphql_parser::schema::Field`.
pub(crate) fn field_def_to_gp(
    fd: &ast::FieldDefinition<'_>,
    source_map: &crate::SourceMap<'_>,
) -> graphql_parser::schema::Field<'static, String> {
    graphql_parser::schema::Field {
        position: match &fd.description {
            Some(desc) => {
                pos_from_span(desc.span, source_map)
            },
            None => {
                pos_from_span(fd.span, source_map)
            },
        },
        description: description_to_gp(&fd.description),
        name: fd.name.value.to_string(),
        arguments: fd
            .parameters
            .iter()
            .map(|ivd| {
                input_value_def_to_gp(ivd, source_map)
            })
            .collect(),
        field_type: type_annotation_to_gp(&fd.field_type),
        directives: directives_to_gp(
            &fd.directives, source_map,
        ),
    }
}

/// Convert an `ast::EnumValueDefinition` to a
/// `graphql_parser::schema::EnumValue`.
pub(crate) fn enum_value_def_to_gp(
    evd: &ast::EnumValueDefinition<'_>,
    source_map: &crate::SourceMap<'_>,
) -> graphql_parser::schema::EnumValue<'static, String> {
    graphql_parser::schema::EnumValue {
        position: match &evd.description {
            Some(desc) => {
                pos_from_span(desc.span, source_map)
            },
            None => {
                pos_from_span(evd.span, source_map)
            },
        },
        description: description_to_gp(
            &evd.description,
        ),
        name: evd.name.value.to_string(),
        directives: directives_to_gp(
            &evd.directives, source_map,
        ),
    }
}

/// Convert an `ast::DirectiveLocationKind` to a
/// `graphql_parser::schema::DirectiveLocation`.
pub(super) fn directive_location_to_gp(
    kind: &ast::DirectiveLocationKind,
) -> graphql_parser::schema::DirectiveLocation {
    use graphql_parser::schema::DirectiveLocation as Gp;
    match kind {
        ast::DirectiveLocationKind::ArgumentDefinition => {
            Gp::ArgumentDefinition
        },
        ast::DirectiveLocationKind::Enum => Gp::Enum,
        ast::DirectiveLocationKind::EnumValue => {
            Gp::EnumValue
        },
        ast::DirectiveLocationKind::Field => Gp::Field,
        ast::DirectiveLocationKind::FieldDefinition => {
            Gp::FieldDefinition
        },
        ast::DirectiveLocationKind::FragmentDefinition => {
            Gp::FragmentDefinition
        },
        ast::DirectiveLocationKind::FragmentSpread => {
            Gp::FragmentSpread
        },
        ast::DirectiveLocationKind::InlineFragment => {
            Gp::InlineFragment
        },
        ast::DirectiveLocationKind::InputFieldDefinition => {
            Gp::InputFieldDefinition
        },
        ast::DirectiveLocationKind::InputObject => {
            Gp::InputObject
        },
        ast::DirectiveLocationKind::Interface => {
            Gp::Interface
        },
        ast::DirectiveLocationKind::Mutation => {
            Gp::Mutation
        },
        ast::DirectiveLocationKind::Object => Gp::Object,
        ast::DirectiveLocationKind::Query => Gp::Query,
        ast::DirectiveLocationKind::Scalar => Gp::Scalar,
        ast::DirectiveLocationKind::Schema => Gp::Schema,
        ast::DirectiveLocationKind::Subscription => {
            Gp::Subscription
        },
        ast::DirectiveLocationKind::Union => Gp::Union,
        ast::DirectiveLocationKind::VariableDefinition => {
            Gp::VariableDefinition
        },
    }
}

// ───────────────────────────────────────────────────
// from_* helpers: graphql_parser → libgraphql AST
// ───────────────────────────────────────────────────

/// Conversion context for `graphql_parser` →
/// libgraphql AST conversions.
///
/// When constructed with `with_source`, byte offsets in
/// produced `ByteSpan`s are computed from the original
/// source text. Without source, byte offsets default
/// to 0.
pub(super) struct FromGpContext<'src> {
    source: Option<&'src str>,
    line_starts: Vec<usize>,
}

impl<'src> FromGpContext<'src> {
    /// Create a context without source text. All byte
    /// offsets will be 0.
    pub(super) fn without_source() -> Self {
        Self {
            source: None,
            line_starts: vec![],
        }
    }

    /// Create a context with source text. Byte offsets
    /// will be computed from (line, col) using the
    /// source.
    pub(super) fn with_source(
        source: &'src str,
    ) -> Self {
        let bytes = source.as_bytes();
        let len = bytes.len();
        let mut line_starts = vec![0usize];
        let mut i = 0;
        while i < len {
            match bytes[i] {
                b'\n' => {
                    line_starts.push(i + 1);
                },
                b'\r' => {
                    // \r\n is a single line terminator
                    if i + 1 < len
                        && bytes[i + 1] == b'\n'
                    {
                        line_starts.push(i + 2);
                        i += 1; // skip the \n
                    } else {
                        line_starts.push(i + 1);
                    }
                },
                _ => {},
            }
            i += 1;
        }
        Self {
            source: Some(source),
            line_starts,
        }
    }

    /// Compute the byte offset for a 0-based
    /// (line, col_utf8) pair.
    fn byte_offset_for(
        &self,
        line: usize,
        col_utf8: usize,
    ) -> usize {
        match self.source {
            Some(src)
                if line < self.line_starts.len() =>
            {
                let line_start =
                    self.line_starts[line];
                src[line_start..]
                    .char_indices()
                    .nth(col_utf8)
                    .map(|(off, _)| line_start + off)
                    .unwrap_or(line_start)
            },
            _ => 0,
        }
    }

    /// Create a zero-width `ByteSpan` from a
    /// `graphql_parser` `Pos` (1-based → 0-based).
    /// When source is available, byte offsets are
    /// computed from (line, col).
    pub(super) fn span_from_pos(
        &self,
        pos: graphql_parser::Pos,
    ) -> ByteSpan {
        let byte_off = self.byte_offset_from_gp(pos);
        ByteSpan::new(byte_off as u32, byte_off as u32)
    }

    /// Create a `ByteSpan` from a start
    /// and end `graphql_parser` `Pos` pair.
    ///
    /// The `graphql_parser` end position is 1-based
    /// inclusive, while our span uses 0-based exclusive
    /// for `end`. The identity
    ///   1-based inclusive column == 0-based exclusive column
    /// means only the line needs -1 for the end.
    pub(super) fn span_from_pos_pair(
        &self,
        start: graphql_parser::Pos,
        end: graphql_parser::Pos,
    ) -> ByteSpan {
        let end_line = end.line.saturating_sub(1);
        // 1-based inclusive column = 0-based exclusive
        let end_col_exclusive = end.column;
        let end_byte_off = self
            .byte_offset_for(end_line, end_col_exclusive);
        let start_byte_off =
            self.byte_offset_from_gp(start);
        ByteSpan::new(
            start_byte_off as u32,
            end_byte_off as u32,
        )
    }

    /// Compute the byte offset for a `graphql_parser`
    /// `Pos` (1-based → 0-based).
    fn byte_offset_from_gp(
        &self,
        pos: graphql_parser::Pos,
    ) -> usize {
        let line = pos.line.saturating_sub(1);
        let col = pos.column.saturating_sub(1);
        self.byte_offset_for(line, col)
    }

    /// Create a zero-width span at the origin (byte 0).
    /// Used for synthetic nodes that have no position in
    /// graphql_parser (e.g. descriptions, argument
    /// sub-nodes).
    pub(super) fn zero_span(
        &self,
    ) -> ByteSpan {
        ByteSpan::new(0, 0)
    }

    /// Convert a string to an owned `Name<'static>`
    /// with a zero-width span at the origin.
    pub(super) fn string_to_name(
        &self,
        value: &str,
    ) -> ast::Name<'static> {
        ast::Name {
            span: self.zero_span(),
            syntax: None,
            value: Cow::Owned(value.to_owned()),
        }
    }

    /// Convert a string to an owned `Name<'static>`
    /// with a zero-width span derived from `pos`.
    pub(super) fn string_to_name_at(
        &self,
        value: &str,
        pos: graphql_parser::Pos,
    ) -> ast::Name<'static> {
        ast::Name {
            span: self.span_from_pos(pos),
            syntax: None,
            value: Cow::Owned(value.to_owned()),
        }
    }
}

/// Convert an `Option<String>` description to an
/// `Option<StringValue<'static>>`.
pub(super) fn gp_description_to_ast(
    desc: &Option<String>,
    ctx: &FromGpContext<'_>,
) -> Option<ast::StringValue<'static>> {
    desc.as_ref().map(|s| ast::StringValue {
        is_block: false,
        span: ctx.zero_span(),
        syntax: None,
        value: Cow::Owned(s.clone()),
    })
}

/// Convert a `graphql_parser::query::Value` to an
/// `ast::Value<'static>`.
pub(super) fn gp_value_to_ast(
    val: &graphql_parser::query::Value<'static, String>,
    ctx: &FromGpContext<'_>,
) -> ast::Value<'static> {
    use graphql_parser::query::Value as GpValue;
    let zs = ctx.zero_span();
    match val {
        GpValue::Boolean(b) => {
            ast::Value::Boolean(ast::BooleanValue {
                span: zs,
                syntax: None,
                value: *b,
            })
        },
        GpValue::Enum(e) => {
            ast::Value::Enum(ast::EnumValue {
                span: zs,
                syntax: None,
                value: Cow::Owned(e.clone()),
            })
        },
        GpValue::Float(f) => {
            ast::Value::Float(ast::FloatValue {
                span: zs,
                syntax: None,
                value: *f,
            })
        },
        GpValue::Int(n) => {
            let i64_val =
                n.as_i64().unwrap_or(0);
            ast::Value::Int(ast::IntValue {
                span: zs,
                syntax: None,
                value: i64_val as i32,
            })
        },
        GpValue::List(items) => {
            ast::Value::List(ast::ListValue {
                span: zs,
                syntax: None,
                values: items
                    .iter()
                    .map(|v| gp_value_to_ast(v, ctx))
                    .collect(),
            })
        },
        GpValue::Null => {
            ast::Value::Null(ast::NullValue {
                span: zs,
                syntax: None,
            })
        },
        GpValue::Object(map) => {
            ast::Value::Object(ast::ObjectValue {
                fields: map
                    .iter()
                    .map(|(key, val)| {
                        ast::ObjectField {
                            name: ctx
                                .string_to_name(key),
                            span: ctx.zero_span(),
                            syntax: None,
                            value: gp_value_to_ast(
                                val, ctx,
                            ),
                        }
                    })
                    .collect(),
                span: zs,
                syntax: None,
            })
        },
        GpValue::String(s) => {
            ast::Value::String(ast::StringValue {
                is_block: false,
                span: zs,
                syntax: None,
                value: Cow::Owned(s.clone()),
            })
        },
        GpValue::Variable(name) => {
            ast::Value::Variable(ast::VariableReference {
                name: ctx.string_to_name(name),
                span: zs,
                syntax: None,
            })
        },
    }
}

/// Convert a `graphql_parser::schema::Type` to an
/// `ast::TypeAnnotation<'static>`.
pub(super) fn gp_type_to_ast(
    ty: &graphql_parser::schema::Type<'static, String>,
    ctx: &FromGpContext<'_>,
) -> ast::TypeAnnotation<'static> {
    use graphql_parser::schema::Type as GpType;
    let zs = ctx.zero_span();
    match ty {
        GpType::NamedType(name) => {
            ast::TypeAnnotation::Named(
                ast::NamedTypeAnnotation {
                    name: ctx.string_to_name(name),
                    nullability:
                        ast::Nullability::Nullable,
                    span: zs,
                },
            )
        },
        GpType::ListType(inner) => {
            ast::TypeAnnotation::List(
                ast::ListTypeAnnotation {
                    element_type: Box::new(
                        gp_type_to_ast(inner, ctx),
                    ),
                    nullability:
                        ast::Nullability::Nullable,
                    span: zs,
                    syntax: None,
                },
            )
        },
        GpType::NonNullType(inner) => {
            match inner.as_ref() {
                GpType::NamedType(name) => {
                    ast::TypeAnnotation::Named(
                        ast::NamedTypeAnnotation {
                            name: ctx
                                .string_to_name(name),
                            nullability:
                                ast::Nullability::NonNull {
                                    syntax: None,
                                },
                            span: zs,
                        },
                    )
                },
                GpType::ListType(elem) => {
                    ast::TypeAnnotation::List(
                        ast::ListTypeAnnotation {
                            element_type: Box::new(
                                gp_type_to_ast(
                                    elem, ctx,
                                ),
                            ),
                            nullability:
                                ast::Nullability::NonNull {
                                    syntax: None,
                                },
                            span: zs,
                            syntax: None,
                        },
                    )
                },
                GpType::NonNullType(_) => {
                    // Invalid per GraphQL spec but we
                    // handle it gracefully.
                    gp_type_to_ast(inner, ctx)
                },
            }
        },
    }
}

/// Convert a `graphql_parser` `Directive` to an
/// `ast::DirectiveAnnotation<'static>`.
fn gp_directive_to_ast(
    dir: &graphql_parser::query::Directive<
        'static,
        String,
    >,
    ctx: &FromGpContext<'_>,
) -> ast::DirectiveAnnotation<'static> {
    ast::DirectiveAnnotation {
        name: ctx
            .string_to_name_at(&dir.name, dir.position),
        span: ctx.span_from_pos(dir.position),
        syntax: None,
        arguments: dir
            .arguments
            .iter()
            .map(|(name, val)| ast::Argument {
                name: ctx.string_to_name(name),
                span: ctx.zero_span(),
                syntax: None,
                value: gp_value_to_ast(val, ctx),
            })
            .collect(),
    }
}

/// Convert a slice of `graphql_parser` `Directive` to
/// a `Vec<ast::DirectiveAnnotation<'static>>`.
pub(super) fn gp_directives_to_ast(
    dirs: &[graphql_parser::query::Directive<
        'static,
        String,
    >],
    ctx: &FromGpContext<'_>,
) -> Vec<ast::DirectiveAnnotation<'static>> {
    dirs.iter()
        .map(|d| gp_directive_to_ast(d, ctx))
        .collect()
}

/// Convert a `graphql_parser::schema::InputValue` to an
/// `ast::InputValueDefinition<'static>`.
pub(super) fn gp_input_value_to_ast(
    iv: &graphql_parser::schema::InputValue<
        'static,
        String,
    >,
    ctx: &FromGpContext<'_>,
) -> ast::InputValueDefinition<'static> {
    ast::InputValueDefinition {
        default_value: iv
            .default_value
            .as_ref()
            .map(|v| gp_value_to_ast(v, ctx)),
        description: gp_description_to_ast(
            &iv.description,
            ctx,
        ),
        directives: gp_directives_to_ast(
            &iv.directives,
            ctx,
        ),
        name: ctx
            .string_to_name_at(&iv.name, iv.position),
        span: ctx.span_from_pos(iv.position),
        syntax: None,
        value_type: gp_type_to_ast(
            &iv.value_type,
            ctx,
        ),
    }
}

/// Convert a `graphql_parser::schema::Field` to an
/// `ast::FieldDefinition<'static>`.
pub(super) fn gp_field_def_to_ast(
    field: &graphql_parser::schema::Field<
        'static,
        String,
    >,
    ctx: &FromGpContext<'_>,
) -> ast::FieldDefinition<'static> {
    ast::FieldDefinition {
        parameters: field
            .arguments
            .iter()
            .map(|iv| gp_input_value_to_ast(iv, ctx))
            .collect(),
        description: gp_description_to_ast(
            &field.description,
            ctx,
        ),
        directives: gp_directives_to_ast(
            &field.directives,
            ctx,
        ),
        field_type: gp_type_to_ast(
            &field.field_type,
            ctx,
        ),
        name: ctx.string_to_name_at(
            &field.name,
            field.position,
        ),
        span: ctx.span_from_pos(field.position),
        syntax: None,
    }
}

/// Convert a `graphql_parser::schema::EnumValue` to an
/// `ast::EnumValueDefinition<'static>`.
pub(super) fn gp_enum_value_to_ast(
    ev: &graphql_parser::schema::EnumValue<
        'static,
        String,
    >,
    ctx: &FromGpContext<'_>,
) -> ast::EnumValueDefinition<'static> {
    ast::EnumValueDefinition {
        description: gp_description_to_ast(
            &ev.description,
            ctx,
        ),
        directives: gp_directives_to_ast(
            &ev.directives,
            ctx,
        ),
        name: ctx
            .string_to_name_at(&ev.name, ev.position),
        span: ctx.span_from_pos(ev.position),
    }
}

/// Convert a `graphql_parser::schema::DirectiveLocation`
/// to an `ast::DirectiveLocationKind`.
pub(super) fn gp_directive_location_to_ast(
    loc: &graphql_parser::schema::DirectiveLocation,
) -> ast::DirectiveLocationKind {
    use graphql_parser::schema::DirectiveLocation as Gp;
    match loc {
        Gp::ArgumentDefinition => {
            ast::DirectiveLocationKind::ArgumentDefinition
        },
        Gp::Enum => {
            ast::DirectiveLocationKind::Enum
        },
        Gp::EnumValue => {
            ast::DirectiveLocationKind::EnumValue
        },
        Gp::Field => {
            ast::DirectiveLocationKind::Field
        },
        Gp::FieldDefinition => {
            ast::DirectiveLocationKind::FieldDefinition
        },
        Gp::FragmentDefinition => {
            ast::DirectiveLocationKind::FragmentDefinition
        },
        Gp::FragmentSpread => {
            ast::DirectiveLocationKind::FragmentSpread
        },
        Gp::InlineFragment => {
            ast::DirectiveLocationKind::InlineFragment
        },
        Gp::InputFieldDefinition => {
            ast::DirectiveLocationKind::InputFieldDefinition
        },
        Gp::InputObject => {
            ast::DirectiveLocationKind::InputObject
        },
        Gp::Interface => {
            ast::DirectiveLocationKind::Interface
        },
        Gp::Mutation => {
            ast::DirectiveLocationKind::Mutation
        },
        Gp::Object => {
            ast::DirectiveLocationKind::Object
        },
        Gp::Query => {
            ast::DirectiveLocationKind::Query
        },
        Gp::Scalar => {
            ast::DirectiveLocationKind::Scalar
        },
        Gp::Schema => {
            ast::DirectiveLocationKind::Schema
        },
        Gp::Subscription => {
            ast::DirectiveLocationKind::Subscription
        },
        Gp::Union => {
            ast::DirectiveLocationKind::Union
        },
        Gp::VariableDefinition => {
            ast::DirectiveLocationKind::VariableDefinition
        },
    }
}