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
use std::fmt::Debug;

use crate::compat::graphql_parser_v0_4::to_graphql_parser_query_ast;
use crate::compat::graphql_parser_v0_4::to_graphql_parser_schema_ast;
use crate::GraphQLParser;

/// Compares two `Debug`-formattable values and, on
/// mismatch, prints a readable line-by-line diff of
/// their pretty-printed representations.
fn assert_ast_eq<T: Debug + PartialEq>(
    actual: &T,
    expected: &T,
    source: &str,
    kind: &str,
) {
    if actual == expected {
        return;
    }

    let actual_lines: Vec<&str> =
        format!("{actual:#?}").leak().lines().collect();
    let expected_lines: Vec<&str> =
        format!("{expected:#?}").leak().lines().collect();

    let mut diff = String::new();
    let max_lines = actual_lines.len().max(expected_lines.len());
    for i in 0..max_lines {
        let a = actual_lines.get(i).copied().unwrap_or("");
        let e = expected_lines.get(i).copied().unwrap_or("");
        if a != e {
            diff.push_str(&format!(
                "  line {i}:\n\
                 \x20   ours:     {a}\n\
                 \x20   expected: {e}\n",
            ));
        }
    }

    panic!(
        "\n\nGround-truth {kind} mismatch.\n\n\
         Source:\n{source}\n\n\
         Differing lines:\n{diff}",
    );
}

/// Parses `source` with both `graphql_parser` and our
/// parser (via the compat layer), then asserts the two
/// schema-document ASTs are structurally identical.
///
/// This validates the entire pipeline: lexer, parser,
/// AST construction, and compat-layer conversion.
fn assert_schema_ground_truth(source: &str) {
    let expected =
        graphql_parser::schema::parse_schema::<String>(source)
            .unwrap_or_else(|e| {
                panic!(
                    "graphql_parser failed to parse \
                     schema:\n{e}\n\nSource:\n{source}",
                )
            })
            .into_static();

    let our_ast = GraphQLParser::new(source)
        .parse_schema_document();
    assert!(
        !our_ast.has_errors(),
        "Our parser reported errors:\n{}\n\nSource:\n{source}",
        our_ast.formatted_errors(),
    );
    let (our_doc, _) = our_ast.into_valid().expect(
        "valid_ast should be Some when no errors",
    );
    let sm = crate::SourceMap::new_with_source(
        source, None,
    );
    let actual = to_graphql_parser_schema_ast(
        &our_doc, &sm,
    )
    .into_ast();

    assert_ast_eq(&actual, &expected, source, "schema");
}

/// Parses `source` with both `graphql_parser` and our
/// parser (via the compat layer), then asserts the two
/// executable-document ASTs are structurally identical.
fn assert_query_ground_truth(source: &str) {
    let expected =
        graphql_parser::query::parse_query::<String>(source)
            .unwrap_or_else(|e| {
                panic!(
                    "graphql_parser failed to parse \
                     query:\n{e}\n\nSource:\n{source}",
                )
            })
            .into_static();

    let our_ast = GraphQLParser::new(source)
        .parse_executable_document();
    assert!(
        !our_ast.has_errors(),
        "Our parser reported errors:\n{}\n\nSource:\n{source}",
        our_ast.formatted_errors(),
    );
    let (our_doc, _) = our_ast.into_valid().expect(
        "valid_ast should be Some when no errors",
    );
    let sm = crate::SourceMap::new_with_source(
        source, None,
    );
    let actual = to_graphql_parser_query_ast(
        &our_doc, &sm,
    )
    .into_ast();

    assert_ast_eq(&actual, &expected, source, "query");
}

// ─────────────────────────────────────────────
// Schema ground-truth tests
// ─────────────────────────────────────────────

/// Simple object type with fields and no descriptions.
///
/// Validates basic type/field parsing and position
/// tracking against `graphql_parser`.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_simple_object() {
    assert_schema_ground_truth(
        "\
type User {
  id: ID!
  name: String
  age: Int
}
",
    );
}

/// Object type with described fields — exercises the
/// Part 1 position fix where `graphql_parser` captures
/// position before the description on `Field` sub-nodes.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_described_fields() {
    assert_schema_ground_truth(
        "\
type User {
  \"The unique identifier\"
  id: ID!
  \"The user's display name\"
  name: String
}
",
    );
}

/// Scalar type with a directive.
///
/// Validates scalar definition + directive argument
/// conversion.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_scalar_with_directive() {
    assert_schema_ground_truth(
        "\
scalar DateTime @specifiedBy(url: \"https://scalars.graphql.org/andimarek/date-time\")
",
    );
}

/// Enum type with described values — exercises the
/// Part 1 position fix for `EnumValue` sub-nodes.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_enum_with_descriptions() {
    assert_schema_ground_truth(
        "\
enum Status {
  \"Currently active\"
  ACTIVE
  \"No longer active\"
  INACTIVE
  PENDING
}
",
    );
}

/// Union type definition.
///
/// Validates union member parsing against
/// `graphql_parser`.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_union() {
    assert_schema_ground_truth(
        "\
union SearchResult = User | Post | Comment
",
    );
}

/// Input object type with described arguments —
/// exercises the Part 1 position fix for `InputValue`
/// sub-nodes.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_input_with_descriptions() {
    assert_schema_ground_truth(
        "\
input CreateUserInput {
  \"The user's name\"
  name: String!
  \"Optional email\"
  email: String
  age: Int = 0
}
",
    );
}

/// Interface type that implements another interface.
///
/// Validates interface parsing including the
/// `implements` clause.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_interface() {
    assert_schema_ground_truth(
        "\
interface Node {
  id: ID!
}

interface NamedNode implements Node {
  id: ID!
  name: String
}
",
    );
}

/// Directive definition with arguments, locations, and
/// the `repeatable` keyword.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_directive_definition() {
    assert_schema_ground_truth(
        "\
directive @cacheControl(maxAge: Int, scope: CacheControlScope) repeatable on FIELD_DEFINITION | OBJECT | INTERFACE
",
    );
}

/// Schema definition with root operation types.
///
/// Validates `schema { query: ... mutation: ... }`
/// syntax.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_schema_definition() {
    assert_schema_ground_truth(
        "\
schema {
  query: Query
  mutation: Mutation
  subscription: Subscription
}
",
    );
}

/// Type extensions for object, enum, union, interface,
/// scalar, and input object.
///
/// Validates all six type-extension forms.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_type_extensions() {
    assert_schema_ground_truth(
        "\
extend type User {
  email: String
}

extend enum Status {
  ARCHIVED
}

extend union SearchResult = Comment

extend interface Node {
  createdAt: DateTime
}

extend scalar DateTime @specifiedBy(url: \"https://scalars.graphql.org/andimarek/date-time\")

extend input CreateUserInput {
  role: String
}
",
    );
}

/// Complex multi-definition document containing
/// several type kinds, descriptions, directives, and
/// arguments.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_complex_document() {
    assert_schema_ground_truth(
        "\
\"The root query type\"
type Query {
  \"Fetch a user by ID\"
  user(id: ID!): User
  users(first: Int = 10, after: String): [User!]!
}

type User implements Node {
  id: ID!
  name: String!
  email: String
  role: Role!
}

interface Node {
  id: ID!
}

enum Role {
  ADMIN
  USER
  GUEST
}

union SearchResult = User | Post

input CreateUserInput {
  name: String!
  email: String
  role: Role = USER
}

scalar DateTime

directive @deprecated(reason: String = \"No longer supported\") on FIELD_DEFINITION | ENUM_VALUE
",
    );
}

// ─────────────────────────────────────────────
// Query ground-truth tests
// ─────────────────────────────────────────────

/// Simple named query with nested fields.
///
/// Validates basic operation + selection set parsing.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_query_ground_truth_simple_query() {
    assert_query_ground_truth(
        "\
query GetUser {
  user {
    id
    name
  }
}
",
    );
}

/// Shorthand query (`{ field }`) — verifies the
/// `SelectionSet` operation variant.
///
/// Per the GraphQL spec, a shorthand query is an
/// anonymous query operation written without the
/// `query` keyword.
/// https://spec.graphql.org/September2025/#sec-Language.Operations
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_query_ground_truth_shorthand() {
    assert_query_ground_truth(
        "\
{
  viewer {
    name
  }
}
",
    );
}

/// Mutation operation.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_query_ground_truth_mutation() {
    assert_query_ground_truth(
        "\
mutation CreateUser {
  createUser(name: \"Alice\") {
    id
    name
  }
}
",
    );
}

/// Subscription operation.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_query_ground_truth_subscription() {
    assert_query_ground_truth(
        "\
subscription OnMessageAdded {
  messageAdded {
    id
    content
    author {
      name
    }
  }
}
",
    );
}

/// Query with variable definitions and default values.
///
/// Validates variable syntax including type annotations,
/// nullability, and defaults.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_query_ground_truth_variables() {
    assert_query_ground_truth(
        "\
query GetUsers($first: Int = 10, $after: String, $includeEmail: Boolean!) {
  users(first: $first, after: $after) {
    id
    name
  }
}
",
    );
}

/// Fragment definition and fragment spreads.
///
/// Validates fragment definition syntax and the
/// `...FragmentName` spread syntax.
/// https://spec.graphql.org/September2025/#sec-Language.Fragments
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_query_ground_truth_fragments() {
    assert_query_ground_truth(
        "\
query GetUser {
  user(id: 1) {
    ...UserFields
  }
}

fragment UserFields on User {
  id
  name
  email
}
",
    );
}

/// Inline fragments with type conditions.
///
/// Validates `... on Type { }` syntax.
/// https://spec.graphql.org/September2025/#sec-Inline-Fragments
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_query_ground_truth_inline_fragments() {
    assert_query_ground_truth(
        "\
query Search {
  search(query: \"test\") {
    ... on User {
      name
      email
    }
    ... on Post {
      title
      body
    }
  }
}
",
    );
}

/// Aliases and arguments with various value types:
/// int, float, string, boolean, null, enum, list,
/// and object.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_query_ground_truth_aliases_and_value_types() {
    assert_query_ground_truth(
        "\
query ValueTypes {
  intVal: field(arg: 42)
  floatVal: field(arg: 3.14)
  stringVal: field(arg: \"hello\")
  boolTrue: field(arg: true)
  boolFalse: field(arg: false)
  nullVal: field(arg: null)
  enumVal: field(arg: ACTIVE)
  listVal: field(arg: [1, 2, 3])
  objectVal: field(arg: {key: \"value\", nested: {a: 1}})
}
",
    );
}

/// Nested selection sets (3+ levels deep).
///
/// Validates deeply nested field selections.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_query_ground_truth_deep_nesting() {
    assert_query_ground_truth(
        "\
query DeepQuery {
  viewer {
    organization {
      teams {
        members {
          name
        }
      }
    }
  }
}
",
    );
}

/// Fields with varied type annotations: nullable list,
/// non-null list of non-null, and nested list types.
///
/// Validates that `[String]`, `[String!]!`, `[[Int]]`,
/// and `[[Int!]!]!` all produce identical AST structures
/// in both parsers.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_type_annotation_variety() {
    assert_schema_ground_truth(
        "\
type TypeAnnotations {
  nullableList: [String]
  nonNullList: [String!]!
  nestedList: [[Int]]
  complexNested: [[Int!]!]!
}
",
    );
}

/// Block string descriptions on types and fields.
///
/// Validates that triple-quoted block strings are parsed
/// and normalised identically by both parsers (whitespace
/// stripping, indentation removal per GraphQL spec
/// §2.9.4).
/// https://spec.graphql.org/September2025/#sec-String-Value
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_schema_ground_truth_block_string_descriptions() {
    assert_schema_ground_truth(
        r#"
"""
A user in the system.

Represents an authenticated account with profile data.
"""
type User {
  """The unique identifier."""
  id: ID!
  """
  The user's display name.
  May contain unicode characters.
  """
  name: String
}
"#,
    );
}

/// Query with variable values passed as arguments,
/// negative integer, and negative float.
///
/// Validates that `$varName` references in argument
/// positions are correctly represented, and that
/// negative numeric literals round-trip through both
/// parsers identically.
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_query_ground_truth_variable_refs_and_negative_numbers() {
    assert_query_ground_truth(
        "\
query Fetch($id: ID!, $limit: Int) {
  user(id: $id) {
    posts(limit: $limit, offset: -5) {
      score(threshold: -1.5)
    }
  }
}
",
    );
}

/// Directives on operations, fields, and fragments.
///
/// Validates directive parsing and positioning across
/// different directive locations.
/// https://spec.graphql.org/September2025/#sec-Language.Directives
///
/// Written by Claude Code, reviewed by a human.
#[test]
fn test_query_ground_truth_directives() {
    assert_query_ground_truth(
        "\
query GetUser($withEmail: Boolean!) @cacheControl(maxAge: 60) {
  user(id: 1) {
    id
    name
    email @include(if: $withEmail)
    ...UserExtra @skip(if: true)
  }
}

fragment UserExtra on User {
  age
  role
}
",
    );
}