oxc-graphql-parser 0.0.5

Spec-compliant GraphQL parser.
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
use crate::Allocator;
use crate::Lexer;
use crate::Parser;
use crate::TokenKind;
use crate::ast;
use std::fs;
use std::path::Path;
use std::path::PathBuf;

#[test]
fn lexer_tests() {
    let source = r#"
type Query {
  hello(name: String = "world"): String
}
"#;
    let (tokens, errors) = Lexer::new(source).lex();
    assert!(errors.is_empty());
    assert!(tokens.iter().any(|token| token.kind() == TokenKind::Name && token.data() == "Query"));
}

#[test]
fn parser_parses_object_type_definition() {
    let source = r#"
type Query {
  hello(name: String = "world"): String
}
"#;
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();

    assert_eq!(ast.errors().len(), 0);
    let document = ast.document();
    assert_eq!(document.definitions.len(), 1);

    let ast::Definition::ObjectType(object) = &document.definitions[0] else {
        panic!("expected object type definition");
    };
    assert_eq!(object.name.as_str(), "Query");
    assert_eq!(object.fields.len(), 1);
    assert_eq!(object.fields[0].name.as_str(), "hello");
    assert_eq!(object.fields[0].arguments[0].name.as_str(), "name");
}

#[test]
fn parser_parses_query_variables_and_used_variables() {
    let source = r#"
query GraphQuery($graph_id: ID!, $variant: String) {
  service(id: $graph_id) {
    schema(tag: $variant) {
      document
    }
  }
}
"#;
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();
    assert_eq!(ast.errors().len(), 0);

    let ast::Definition::Operation(operation) = &ast.document().definitions[0] else {
        panic!("expected operation definition");
    };
    assert_eq!(operation.name.as_ref().unwrap().as_str(), "GraphQuery");
    assert_eq!(operation.variable_definitions.len(), 2);

    let mut used = Vec::new();
    collect_variables(operation.selection_set.as_ref().unwrap(), &mut used);
    assert_eq!(used, ["graph_id", "variant"]);
}

#[test]
fn parser_parses_selection_set_and_type_roots() {
    let allocator = Allocator::default();
    let selection = Parser::new(&allocator, "{ product { name } }").parse_selection_set();
    assert_eq!(selection.errors().len(), 0);
    assert_eq!(selection.field_set().selections.len(), 1);

    let ty = Parser::new(&allocator, "[String!]!").parse_type();
    assert_eq!(ty.errors().len(), 0);
    assert!(matches!(ty.ty(), ast::Type::NonNull(_)));
}

#[test]
fn parser_parses_experimental_fragment_arguments() {
    let source = r#"
fragment variableProfilePic($size: Int) on User {
  profilePic(size: $size)
}

query Q {
  user {
    ...variableProfilePic(size: 100)
  }
}
"#;
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).experimental_fragment_arguments(true).parse();
    assert_eq!(ast.errors().len(), 0);

    let ast::Definition::Fragment(fragment) = &ast.document().definitions[0] else {
        panic!("expected fragment definition");
    };
    assert_eq!(fragment.name.as_str(), "variableProfilePic");
    assert_eq!(fragment.variable_definitions.len(), 1);
    assert_eq!(fragment.variable_definitions[0].variable.name.as_str(), "size");

    let ast::Definition::Operation(operation) = &ast.document().definitions[1] else {
        panic!("expected operation definition");
    };
    let ast::Selection::Field(user) = &operation.selection_set.as_ref().unwrap().selections[0]
    else {
        panic!("expected field");
    };
    let ast::Selection::FragmentSpread(spread) =
        &user.selection_set.as_ref().unwrap().selections[0]
    else {
        panic!("expected fragment spread");
    };
    assert_eq!(spread.name.as_str(), "variableProfilePic");
    assert_eq!(spread.arguments.len(), 1);
    assert_eq!(spread.arguments[0].name.as_str(), "size");
}

#[test]
fn parser_rejects_fragment_arguments_without_flag() {
    let source = "query Q { user { ...spread(size: 100) } }";
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();
    assert!(ast.errors().len() > 0);
}

#[test]
fn parser_collects_comment_spans_in_document_order() {
    let source = r#"# leading
query Q {
  # inside selection set
  field # trailing
  # before closing brace
}
# between definitions
type T {
  name: String
}
# at end of document"#;
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();
    assert_eq!(ast.errors().len(), 0);

    let comments = ast
        .comments()
        .iter()
        .map(|span| &source[span.start as usize..span.end as usize])
        .collect::<Vec<_>>();
    assert_eq!(
        comments,
        [
            "# leading",
            "# inside selection set",
            "# trailing",
            "# before closing brace",
            "# between definitions",
            "# at end of document",
        ]
    );
}

#[test]
fn parser_string_values() {
    // Escaped strings and block strings with `\r` line endings are unescaped
    // or normalized into arena-allocated values; strings that need no
    // rewriting are borrowed directly from the source text.
    let source = "\"plain\"\nscalar A\n\"esc\\u0041ped \\n\\\"quote\\\" end\"\nscalar B\n\"\"\"one\r\ntwo\rthree\nfour\"\"\"\nscalar C\n\"\"\"block unchanged\"\"\"\nscalar D";
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();
    assert_eq!(ast.errors().len(), 0);

    let descriptions = ast
        .document()
        .definitions
        .iter()
        .map(|definition| {
            let ast::Definition::ScalarType(scalar) = definition else {
                panic!("expected scalar definition");
            };
            scalar.description.as_ref().unwrap().value
        })
        .collect::<Vec<_>>();
    assert_eq!(
        descriptions,
        ["plain", "escAped \n\"quote\" end", "one\ntwo\nthree\nfour", "block unchanged"]
    );
}

#[test]
fn parser_collects_comments_without_duplicates_on_lookahead() {
    // `extend` parsing peeks ahead multiple times; comments in between must be
    // recorded only once.
    let source = "# before extend\nextend type T { name: String }";
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();
    assert_eq!(ast.errors().len(), 0);
    let end = u32::try_from("# before extend".len()).unwrap();
    assert_eq!(ast.comments(), [ast::Span::new(0, end)]);
}

#[test]
fn parser_collects_no_comments_when_absent() {
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, "type T { name: String }").parse();
    assert_eq!(ast.errors().len(), 0);
    assert!(ast.comments().is_empty());
}

#[test]
fn parser_comment_spans_end_before_line_terminators() {
    for line_terminator in ["\n", "\r\n", "\r"] {
        let source = format!("# comment{line_terminator}type T {{ name: String }}");
        let allocator = Allocator::default();
        let ast = Parser::new(&allocator, &source).parse();
        assert_eq!(ast.errors().len(), 0);
        let end = u32::try_from("# comment".len()).unwrap();
        assert_eq!(ast.comments(), [ast::Span::new(0, end)]);
    }
}

#[test]
fn lexer_roundtrip_corpus() {
    // For any input the lexer tokenizes without errors, concatenating all
    // token text must reproduce the source exactly.
    for dir in ["lexer/ok", "lexer/err", "parser/ok", "parser/err"] {
        for path in graphql_files(dir) {
            let source = fs::read_to_string(&path).unwrap();
            let (tokens, errors) = Lexer::new(&source).lex();
            if errors.is_empty() {
                let concatenated: String = tokens.iter().map(crate::Token::data).collect();
                assert_eq!(source, concatenated, "{}", path.display());
            }
        }
    }
}

#[test]
fn parser_collects_comments_for_selection_set_and_type_roots() {
    let allocator = Allocator::default();
    let selection = Parser::new(&allocator, "{ field # inside\n}").parse_selection_set();
    assert_eq!(selection.errors().len(), 0);
    assert_eq!(selection.comments().len(), 1);

    let ty = Parser::new(&allocator, "String").parse_type();
    assert_eq!(ty.errors().len(), 0);
    assert!(ty.comments().is_empty());
}

#[test]
fn definition_and_selection_spans_match_inner_nodes() {
    let source = r#"query Q {
  field
  ...spread
  ... on T {
    inline
  }
}
type T {
  name: String
}
extend type T {
  extra: String
}"#;
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();
    assert_eq!(ast.errors().len(), 0);

    let definitions = &ast.document().definitions;
    let ast::Definition::Operation(operation) = &definitions[0] else {
        panic!("expected operation definition");
    };
    assert_eq!(definitions[0].span(), operation.span);
    let ast::Definition::ObjectType(object) = &definitions[1] else {
        panic!("expected object type definition");
    };
    assert_eq!(definitions[1].span(), object.span);
    let ast::Definition::ObjectTypeExtension(extension) = &definitions[2] else {
        panic!("expected object type extension");
    };
    assert_eq!(definitions[2].span(), extension.span);

    let selections = &operation.selection_set.as_ref().unwrap().selections;
    let ast::Selection::Field(field) = &selections[0] else {
        panic!("expected field");
    };
    assert_eq!(selections[0].span(), field.span);
    let ast::Selection::FragmentSpread(spread) = &selections[1] else {
        panic!("expected fragment spread");
    };
    assert_eq!(selections[1].span(), spread.span);
    let ast::Selection::InlineFragment(inline) = &selections[2] else {
        panic!("expected inline fragment");
    };
    assert_eq!(selections[2].span(), inline.span);
}

#[test]
fn parser_parses_directives_on_directive_definitions() {
    let source = "directive @foo @bar @baz on FIELD";
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();
    assert_eq!(ast.errors().len(), 0);

    let ast::Definition::Directive(directive) = &ast.document().definitions[0] else {
        panic!("expected directive definition");
    };
    assert_eq!(directive.name.as_str(), "foo");
    assert_eq!(directive.directives.len(), 2);
    assert_eq!(directive.directives[0].name.as_str(), "bar");
    assert_eq!(directive.directives[1].name.as_str(), "baz");
}

#[test]
fn parser_parses_directive_extension() {
    let source = "extend directive @foo @bar @baz";
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();
    assert_eq!(ast.errors().len(), 0);

    let ast::Definition::DirectiveExtension(extension) = &ast.document().definitions[0] else {
        panic!("expected directive extension");
    };
    assert_eq!(extension.name.as_str(), "foo");
    assert_eq!(extension.directives.len(), 2);
    assert_eq!(extension.directives[0].name.as_str(), "bar");
    assert_eq!(extension.directives[1].name.as_str(), "baz");
}

#[test]
fn parser_rejects_empty_directive_extension() {
    let source = "extend directive @foo";
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();
    assert!(ast.errors().len() > 0);
}

#[test]
fn parser_parses_variable_definition_descriptions() {
    let source = r#"query Q("""the id""" $id: ID!) { node(id: $id) { name } }"#;
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();
    assert_eq!(ast.errors().len(), 0);

    let ast::Definition::Operation(operation) = &ast.document().definitions[0] else {
        panic!("expected operation definition");
    };
    assert_eq!(operation.variable_definitions.len(), 1);
    let description = operation.variable_definitions[0].description.as_ref().unwrap();
    assert_eq!(description.value, "the id");
}

#[test]
fn parser_rejects_description_on_shorthand_query() {
    let source = r#""""doc""" { f }"#;
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();
    assert!(ast.errors().len() > 0);
}

#[test]
fn parser_rejects_description_on_extension() {
    let source = r#""""doc""" extend type Foo @bar"#;
    let allocator = Allocator::default();
    let ast = Parser::new(&allocator, source).parse();
    assert!(ast.errors().len() > 0);
}

#[test]
fn parser_ok_fixtures_have_no_errors() {
    for path in graphql_files("parser/ok") {
        let source = fs::read_to_string(&path).unwrap();
        let allocator = Allocator::default();
        let ast = Parser::new(&allocator, &source).parse();
        let errors = ast.errors().collect::<Vec<_>>();
        assert!(errors.is_empty(), "{}: {errors:?}", path.display());
    }
}

#[test]
fn parser_err_fixtures_have_errors() {
    for path in graphql_files("parser/err") {
        let source = fs::read_to_string(&path).unwrap();
        let allocator = Allocator::default();
        let ast = Parser::new(&allocator, &source).parse();
        assert!(ast.errors().len() > 0, "{}", path.display());
    }
}

#[test]
#[ignore]
fn ecosystem_graphql_corpus_has_no_parse_errors() {
    let root = std::env::var_os("OXC_GRAPHQL_ECOSYSTEM_REPOS")
        .map(PathBuf::from)
        .expect("set OXC_GRAPHQL_ECOSYSTEM_REPOS to an ecosystem-ci repos directory");
    let mut files = Vec::new();
    collect_graphql_files(&root, &mut files);

    let mut failures = Vec::new();
    for path in &files {
        let source = fs::read_to_string(path).unwrap();
        let allocator = Allocator::default();
        let ast = Parser::new(&allocator, &source).parse();
        let errors = ast.errors().collect::<Vec<_>>();
        if !errors.is_empty() {
            failures.push(format!("{}: {errors:?}", path.display()));
        }
    }

    assert!(
        failures.is_empty(),
        "{} of {} ecosystem GraphQL files failed to parse:\n{}",
        failures.len(),
        files.len(),
        failures.join("\n")
    );
}

fn collect_variables<'a>(selection_set: &'a ast::SelectionSet<'_>, output: &mut Vec<&'a str>) {
    for selection in &selection_set.selections {
        if let ast::Selection::Field(field) = selection {
            for argument in &field.arguments {
                collect_variable_value(argument.value.as_ref(), output);
            }
            if let Some(selection_set) = &field.selection_set {
                collect_variables(selection_set, output);
            }
        }
    }
}

fn collect_variable_value<'a>(value: Option<&'a ast::Value<'_>>, output: &mut Vec<&'a str>) {
    match value {
        Some(ast::Value::Variable(variable)) => output.push(variable.name.as_str()),
        Some(ast::Value::List(list)) => {
            for value in &list.values {
                collect_variable_value(Some(value), output);
            }
        }
        Some(ast::Value::Object(object)) => {
            for field in &object.fields {
                collect_variable_value(field.value.as_ref(), output);
            }
        }
        _ => {}
    }
}

fn graphql_files(path: &str) -> Vec<PathBuf> {
    let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("test_data").join(path);
    let mut files = fs::read_dir(dir)
        .unwrap()
        .filter_map(Result::ok)
        .map(|entry| entry.path())
        .filter(|path| path.extension().is_some_and(|extension| extension == "graphql"))
        .collect::<Vec<_>>();
    files.sort();
    files
}

fn collect_graphql_files(dir: &Path, files: &mut Vec<PathBuf>) {
    for entry in fs::read_dir(dir).unwrap() {
        let path = entry.unwrap().path();
        if path.is_dir() {
            let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
                continue;
            };
            if matches!(name, ".git" | "node_modules" | "target") {
                continue;
            }
            collect_graphql_files(&path, files);
        } else if path
            .extension()
            .is_some_and(|extension| matches!(extension.to_str(), Some("gql" | "graphql")))
        {
            files.push(path);
        }
    }
    files.sort();
}