juniper 0.17.2

GraphQL server library.
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
use std::collections::{HashMap, HashSet};

use crate::ast::{
    Arguments, Definition, Directive, Field, Fragment, FragmentSpread, InlineFragment, InputValue,
    Operation, OperationType, OwnedDocument, Selection, Type, VariableDefinition,
    VariableDefinitions,
};

use crate::{
    parser::{
        Lexer, Limits, OptionParseResult, ParseError, ParseResult, Parser, Span, Spanning, Token,
        UnlocatedParseResult, value::parse_value_literal,
    },
    schema::{
        meta::{Argument, Field as MetaField},
        model::SchemaType,
    },
    value::ScalarValue,
};

#[doc(hidden)]
pub fn parse_document_source<'a, S>(
    s: &'a str,
    schema: &SchemaType<S>,
) -> UnlocatedParseResult<OwnedDocument<'a, S>>
where
    S: ScalarValue,
{
    let mut lexer = Lexer::new(s);
    let mut parser = Parser::with_limits(&mut lexer, schema.limits)?;
    let document = parse_document(&mut parser, schema)?;
    ExpansionCheck::new(&document, schema.limits).run()?;
    Ok(document)
}

/// Check of a document with its fragment spreads expanded.
///
/// A fragment spread nests the selections of its fragment one level deeper. The parser limits the
/// depth of each definition separately. Chained fragments can nest much deeper than any single
/// definition. Validation and execution follow fragment spreads recursively. The depth limit keeps
/// validation and execution from overflowing the stack.
///
/// A fragment that spreads another fragment more than once multiplies the fields of the other
/// fragment. A document of a few hundred tokens can expand into billions of fields. The field
/// limit bounds the work of execution.
struct ExpansionCheck<'a, 'd, S> {
    document: &'d [Definition<'a, S>],
    fragments: HashMap<&'a str, &'d [Selection<'a, S>]>,
    limits: Limits,

    /// Expansions of the checked fragments, with depths relative to the depth of their spreads.
    ///
    /// The check visits each fragment once and reuses the stored expansion for repeated spreads.
    /// The check thus takes linear time in the size of the document.
    fragment_expansions: HashMap<&'a str, Expansion>,

    /// Fragments on the current check path.
    ///
    /// A spread of a fragment on this path forms a cycle. The check skips such a spread because
    /// validation reports fragment cycles.
    open_fragments: HashSet<&'a str>,
}

/// Depth and field count of a part of a document with its fragment spreads expanded.
#[derive(Clone, Copy)]
struct Expansion {
    /// Deepest nesting depth in the part.
    depth: usize,

    /// Number of fields in the part. The count saturates at [`usize::MAX`].
    fields: usize,
}

impl<'a, 'd, S> ExpansionCheck<'a, 'd, S> {
    fn new(document: &'d [Definition<'a, S>], limits: Limits) -> Self {
        let fragments = document
            .iter()
            .filter_map(|definition| match definition {
                Definition::Fragment(fragment) => Some((
                    fragment.item.name.item,
                    fragment.item.selection_set.as_slice(),
                )),
                Definition::Operation(_) => None,
            })
            .collect();
        Self {
            document,
            fragments,
            limits,
            fragment_expansions: HashMap::new(),
            open_fragments: HashSet::new(),
        }
    }

    /// Checks every operation and fragment of the document.
    ///
    /// The field limit applies only to operations because only operations execute. The depth limit
    /// also applies to unused fragments because validation follows their spreads.
    fn run(mut self) -> Result<(), Spanning<ParseError>> {
        for definition in self.document {
            match definition {
                Definition::Operation(operation) => {
                    let expansion = self.selection_set(&operation.item.selection_set, 1)?;
                    if expansion.fields > self.limits.max_fields {
                        return Err(Spanning::new(
                            operation.span,
                            ParseError::FieldLimitExceeded(self.limits.max_fields),
                        ));
                    }
                }
                Definition::Fragment(fragment) => {
                    self.fragment(fragment.item.name.item, 0, fragment.span)?;
                }
            }
        }
        Ok(())
    }

    /// Returns the expansion of `selection_set` at nesting `depth`.
    fn selection_set(
        &mut self,
        selection_set: &'d [Selection<'a, S>],
        depth: usize,
    ) -> Result<Expansion, Spanning<ParseError>> {
        let mut expansion = Expansion { depth, fields: 0 };
        for selection in selection_set {
            let nested = match selection {
                Selection::Field(field) => {
                    expansion.fields = expansion.fields.saturating_add(1);
                    match &field.item.selection_set {
                        Some(nested) => self.nested(nested, depth, field.span)?,
                        None => continue,
                    }
                }
                Selection::InlineFragment(fragment) => {
                    self.nested(&fragment.item.selection_set, depth, fragment.span)?
                }
                Selection::FragmentSpread(spread) => {
                    self.fragment(spread.item.name.item, depth, spread.span)?
                }
            };
            expansion.depth = expansion.depth.max(nested.depth);
            expansion.fields = expansion.fields.saturating_add(nested.fields);
        }
        Ok(expansion)
    }

    /// Returns the expansion of `selection_set` one nesting level below `depth`.
    ///
    /// Fails at `span` if `selection_set` exceeds the depth limit.
    fn nested(
        &mut self,
        selection_set: &'d [Selection<'a, S>],
        depth: usize,
        span: Span,
    ) -> Result<Expansion, Spanning<ParseError>> {
        if depth >= self.limits.max_depth {
            return Err(Spanning::new(
                span,
                ParseError::DepthLimitExceeded(self.limits.max_depth),
            ));
        }
        self.selection_set(selection_set, depth + 1)
    }

    /// Returns the expansion of the `name`d fragment for a spread at `depth`.
    ///
    /// Fails at `span` if the fragment exceeds the depth limit. The expansion of an undefined
    /// fragment or a fragment cycle is empty because validation reports undefined fragments and
    /// fragment cycles.
    fn fragment(
        &mut self,
        name: &'a str,
        depth: usize,
        span: Span,
    ) -> Result<Expansion, Spanning<ParseError>> {
        if let Some(&relative) = self.fragment_expansions.get(name) {
            let depth = depth + relative.depth;
            if depth > self.limits.max_depth {
                return Err(Spanning::new(
                    span,
                    ParseError::DepthLimitExceeded(self.limits.max_depth),
                ));
            }
            return Ok(Expansion {
                depth,
                fields: relative.fields,
            });
        }
        let nothing = Expansion { depth, fields: 0 };
        let Some(&selection_set) = self.fragments.get(name) else {
            return Ok(nothing);
        };
        if !self.open_fragments.insert(name) {
            return Ok(nothing);
        }
        let expansion = self.nested(selection_set, depth, span)?;
        self.open_fragments.remove(name);
        self.fragment_expansions.insert(
            name,
            Expansion {
                depth: expansion.depth - depth,
                fields: expansion.fields,
            },
        );
        Ok(expansion)
    }
}

fn parse_document<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
) -> UnlocatedParseResult<OwnedDocument<'a, S>>
where
    S: ScalarValue,
{
    let mut defs = Vec::new();

    loop {
        defs.push(parse_definition(parser, schema)?);

        if parser.peek().item == Token::EndOfFile {
            return Ok(defs);
        }
    }
}

fn parse_definition<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
) -> UnlocatedParseResult<Definition<'a, S>>
where
    S: ScalarValue,
{
    match parser.peek().item {
        Token::CurlyOpen
        | Token::Name("query")
        | Token::Name("mutation")
        | Token::Name("subscription") => Ok(Definition::Operation(parse_operation_definition(
            parser, schema,
        )?)),
        Token::Name("fragment") => Ok(Definition::Fragment(parse_fragment_definition(
            parser, schema,
        )?)),
        _ => Err(parser.next_token()?.map(ParseError::unexpected_token)),
    }
}

fn parse_operation_definition<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
) -> ParseResult<Operation<'a, S>>
where
    S: ScalarValue,
{
    if parser.peek().item == Token::CurlyOpen {
        let fields = schema.concrete_query_type().fields(schema);
        let fields = fields.as_ref().map(|c| c as &[_]);
        let selection_set = parse_selection_set(parser, schema, fields)?;

        Ok(Spanning::new(
            selection_set.span,
            Operation {
                operation_type: OperationType::Query,
                name: None,
                variable_definitions: None,
                directives: None,
                selection_set: selection_set.item,
            },
        ))
    } else {
        let start_pos = parser.peek().span.start;
        let operation_type = parse_operation_type(parser)?;
        let op = match operation_type.item {
            OperationType::Query => Some(schema.concrete_query_type()),
            OperationType::Mutation => schema.concrete_mutation_type(),
            OperationType::Subscription => schema.concrete_subscription_type(),
        };
        let fields = op.and_then(|m| m.fields(schema));
        let fields = fields.as_ref().map(|c| c as &[_]);

        let name = match parser.peek().item {
            Token::Name(_) => Some(parser.expect_name()?),
            _ => None,
        };
        let variable_definitions = parse_variable_definitions(parser, schema)?;
        let directives = parse_directives(parser, schema)?;
        let selection_set = parse_selection_set(parser, schema, fields)?;

        Ok(Spanning::start_end(
            &start_pos,
            &selection_set.span.end,
            Operation {
                operation_type: operation_type.item,
                name,
                variable_definitions,
                directives: directives.map(|s| s.item),
                selection_set: selection_set.item,
            },
        ))
    }
}

fn parse_fragment_definition<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
) -> ParseResult<Fragment<'a, S>>
where
    S: ScalarValue,
{
    let start_pos = parser.expect(&Token::Name("fragment"))?.span.start;
    let name = match parser.expect_name() {
        Ok(n) => {
            if n.item == "on" {
                return Err(n.map(|_| ParseError::UnexpectedToken("on".into())));
            } else {
                n
            }
        }
        Err(e) => return Err(e),
    };

    parser.expect(&Token::Name("on"))?;
    let type_cond = parser.expect_name()?;

    let fields = schema
        .concrete_type_by_name(type_cond.item)
        .and_then(|m| m.fields(schema));
    let fields = fields.as_ref().map(|c| c as &[_]);

    let directives = parse_directives(parser, schema)?;
    let selection_set = parse_selection_set(parser, schema, fields)?;

    Ok(Spanning::start_end(
        &start_pos,
        &selection_set.span.end,
        Fragment {
            name,
            type_condition: type_cond,
            directives: directives.map(|s| s.item),
            selection_set: selection_set.item,
        },
    ))
}

fn parse_optional_selection_set<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
    fields: Option<&[&MetaField<S>]>,
) -> OptionParseResult<Vec<Selection<'a, S>>>
where
    S: ScalarValue,
{
    if parser.peek().item == Token::CurlyOpen {
        Ok(Some(parse_selection_set(parser, schema, fields)?))
    } else {
        Ok(None)
    }
}

fn parse_selection_set<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
    fields: Option<&[&MetaField<S>]>,
) -> ParseResult<Vec<Selection<'a, S>>>
where
    S: ScalarValue,
{
    parser.nested(|parser| {
        parser.unlocated_delimited_nonempty_list(
            &Token::CurlyOpen,
            |p| parse_selection(p, schema, fields),
            &Token::CurlyClose,
        )
    })
}

fn parse_selection<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
    fields: Option<&[&MetaField<S>]>,
) -> UnlocatedParseResult<Selection<'a, S>>
where
    S: ScalarValue,
{
    match parser.peek().item {
        Token::Ellipsis => parse_fragment(parser, schema, fields),
        _ => parse_field(parser, schema, fields).map(Selection::Field),
    }
}

fn parse_fragment<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
    fields: Option<&[&MetaField<S>]>,
) -> UnlocatedParseResult<Selection<'a, S>>
where
    S: ScalarValue,
{
    let start_pos = parser.expect(&Token::Ellipsis)?.span.start;

    match parser.peek().item {
        Token::Name("on") => {
            parser.next_token()?;
            let name = parser.expect_name()?;

            let fields = schema
                .concrete_type_by_name(name.item)
                .and_then(|m| m.fields(schema));
            let fields = fields.as_ref().map(|c| c as &[_]);
            let directives = parse_directives(parser, schema)?;
            let selection_set = parse_selection_set(parser, schema, fields)?;

            Ok(Selection::InlineFragment(Spanning::start_end(
                &start_pos,
                &selection_set.span.end,
                InlineFragment {
                    type_condition: Some(name),
                    directives: directives.map(|s| s.item),
                    selection_set: selection_set.item,
                },
            )))
        }
        Token::CurlyOpen => {
            let selection_set = parse_selection_set(parser, schema, fields)?;

            Ok(Selection::InlineFragment(Spanning::start_end(
                &start_pos,
                &selection_set.span.end,
                InlineFragment {
                    type_condition: None,
                    directives: None,
                    selection_set: selection_set.item,
                },
            )))
        }
        Token::Name(_) => {
            let frag_name = parser.expect_name()?;
            let directives = parse_directives(parser, schema)?;

            Ok(Selection::FragmentSpread(Spanning::start_end(
                &start_pos.clone(),
                &directives
                    .as_ref()
                    .map_or(&frag_name.span.end, |s| &s.span.end)
                    .clone(),
                FragmentSpread {
                    name: frag_name,
                    directives: directives.map(|s| s.item),
                },
            )))
        }
        Token::At => {
            let directives = parse_directives(parser, schema)?;
            let selection_set = parse_selection_set(parser, schema, fields)?;

            Ok(Selection::InlineFragment(Spanning::start_end(
                &start_pos,
                &selection_set.span.end,
                InlineFragment {
                    type_condition: None,
                    directives: directives.map(|s| s.item),
                    selection_set: selection_set.item,
                },
            )))
        }
        _ => Err(parser.next_token()?.map(ParseError::unexpected_token)),
    }
}

fn parse_field<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
    fields: Option<&[&MetaField<S>]>,
) -> ParseResult<Field<'a, S>>
where
    S: ScalarValue,
{
    let mut alias = Some(parser.expect_name()?);

    let name = if parser.skip(&Token::Colon)?.is_some() {
        parser.expect_name()?
    } else {
        alias.take().unwrap()
    };

    let field = fields.and_then(|f| f.iter().find(|f| f.name == name.item));
    let args = field
        .as_ref()
        .and_then(|f| f.arguments.as_ref().map(|a| a as &[_]));

    let fields = field
        .as_ref()
        .and_then(|f| schema.lookup_type(&f.field_type))
        .and_then(|m| m.fields(schema));
    let fields = fields.as_ref().map(|c| c as &[_]);

    let arguments = parse_arguments(parser, schema, args)?;

    let directives = parse_directives(parser, schema)?;
    let selection_set = parse_optional_selection_set(parser, schema, fields)?;

    Ok(Spanning::start_end(
        &alias.as_ref().unwrap_or(&name).span.start,
        &selection_set
            .as_ref()
            .map(|s| &s.span.end)
            .or_else(|| directives.as_ref().map(|s| &s.span.end))
            .or_else(|| arguments.as_ref().map(|s| &s.span.end))
            .unwrap_or(&name.span.end)
            .clone(),
        Field {
            alias,
            name,
            arguments,
            directives: directives.map(|s| s.item),
            selection_set: selection_set.map(|s| s.item),
        },
    ))
}

fn parse_arguments<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
    arguments: Option<&[Argument<S>]>,
) -> OptionParseResult<Arguments<'a, S>>
where
    S: ScalarValue,
{
    if parser.peek().item != Token::ParenOpen {
        Ok(None)
    } else {
        Ok(Some(
            parser
                .delimited_nonempty_list(
                    &Token::ParenOpen,
                    |p| parse_argument(p, schema, arguments),
                    &Token::ParenClose,
                )?
                .map(|args| Arguments {
                    items: args.into_iter().map(|s| s.item).collect(),
                }),
        ))
    }
}

fn parse_argument<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
    arguments: Option<&[Argument<S>]>,
) -> ParseResult<(Spanning<&'a str>, Spanning<InputValue<S>>)>
where
    S: ScalarValue,
{
    let name = parser.expect_name()?;
    let tpe = arguments
        .and_then(|args| args.iter().find(|a| a.name == name.item))
        .and_then(|arg| schema.lookup_type(&arg.arg_type));

    parser.expect(&Token::Colon)?;
    let value = parse_value_literal(parser, false, schema, tpe)?;

    Ok(Spanning::start_end(
        &name.span.start,
        &value.span.end.clone(),
        (name, value),
    ))
}

fn parse_operation_type(parser: &mut Parser<'_>) -> ParseResult<OperationType> {
    match parser.peek().item {
        Token::Name("query") => Ok(parser.next_token()?.map(|_| OperationType::Query)),
        Token::Name("mutation") => Ok(parser.next_token()?.map(|_| OperationType::Mutation)),
        Token::Name("subscription") => {
            Ok(parser.next_token()?.map(|_| OperationType::Subscription))
        }
        _ => Err(parser.next_token()?.map(ParseError::unexpected_token)),
    }
}

fn parse_variable_definitions<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
) -> OptionParseResult<VariableDefinitions<'a, S>>
where
    S: ScalarValue,
{
    if parser.peek().item != Token::ParenOpen {
        Ok(None)
    } else {
        Ok(Some(
            parser
                .delimited_nonempty_list(
                    &Token::ParenOpen,
                    |p| parse_variable_definition(p, schema),
                    &Token::ParenClose,
                )?
                .map(|defs| VariableDefinitions {
                    items: defs.into_iter().map(|s| s.item).collect(),
                }),
        ))
    }
}

fn parse_variable_definition<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
) -> ParseResult<(Spanning<&'a str>, VariableDefinition<'a, S>)>
where
    S: ScalarValue,
{
    let start_pos = parser.expect(&Token::Dollar)?.span.start;
    let var_name = parser.expect_name()?;
    parser.expect(&Token::Colon)?;
    let var_type = parse_type(parser)?;
    let tpe = schema.lookup_type(&var_type.item);

    let default_value = if parser.skip(&Token::Equals)?.is_some() {
        Some(parse_value_literal(parser, true, schema, tpe)?)
    } else {
        None
    };

    let directives = parse_directives(parser, schema)?;

    Ok(Spanning::start_end(
        &start_pos,
        &default_value
            .as_ref()
            .map_or(&var_type.span.end, |s| &s.span.end)
            .clone(),
        (
            Spanning::start_end(&start_pos, &var_name.span.end, var_name.item),
            VariableDefinition {
                var_type,
                default_value,
                directives: directives.map(|s| s.item),
            },
        ),
    ))
}

fn parse_directives<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
) -> OptionParseResult<Vec<Spanning<Directive<'a, S>>>>
where
    S: ScalarValue,
{
    if parser.peek().item != Token::At {
        Ok(None)
    } else {
        let mut items = Vec::new();
        while parser.peek().item == Token::At {
            items.push(parse_directive(parser, schema)?);
        }

        Ok(Spanning::spanning(items))
    }
}

fn parse_directive<'a, S>(
    parser: &mut Parser<'a>,
    schema: &SchemaType<S>,
) -> ParseResult<Directive<'a, S>>
where
    S: ScalarValue,
{
    let start_pos = parser.expect(&Token::At)?.span.start;
    let name = parser.expect_name()?;

    let directive = schema.directive_by_name(name.item);

    let arguments = parse_arguments(
        parser,
        schema,
        directive.as_ref().map(|d| &d.arguments as &[_]),
    )?;

    Ok(Spanning::start_end(
        &start_pos,
        &arguments
            .as_ref()
            .map_or(&name.span.end, |s| &s.span.end)
            .clone(),
        Directive { name, arguments },
    ))
}

pub fn parse_type<'a>(parser: &mut Parser<'a>) -> ParseResult<Type<&'a str>> {
    let parsed_type = if let Some(Spanning {
        span: start_span, ..
    }) = parser.skip(&Token::BracketOpen)?
    {
        let inner_type = parser.nested(parse_type)?;
        let end_pos = parser.expect(&Token::BracketClose)?.span.end;
        Spanning::start_end(&start_span.start, &end_pos, inner_type.item.wrap_list(None))
    } else {
        parser.expect_name()?.map(Type::nullable)
    };

    Ok(match *parser.peek() {
        Spanning {
            item: Token::ExclamationMark,
            ..
        } => wrap_non_null(parser, parsed_type)?,
        _ => parsed_type,
    })
}

fn wrap_non_null<'a>(
    parser: &mut Parser<'a>,
    mut inner: Spanning<Type<&'a str>>,
) -> ParseResult<Type<&'a str>> {
    let end_pos = &parser.expect(&Token::ExclamationMark)?.span.end;

    if !inner.item.is_non_null() {
        inner.item = inner.item.wrap_non_null();
    }

    Ok(Spanning::start_end(&inner.span.start, end_pos, inner.item))
}