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
use std::{borrow::Cow, collections::VecDeque, fmt, iter};
use compact_str::{CompactString, format_compact};
use derive_more::with_trait::{Display, Error, From};
use crate::parser::{
Lexer, LexerError, ScalarToken, Spanning, StringLiteral, Token, UnicodeCodePoint,
};
/// Error while parsing a GraphQL query
#[derive(Clone, Debug, Display, Eq, Error, From, PartialEq)]
pub enum ParseError {
/// An unexpected token occurred in the source
// TODO: Previously was `Token<'a>`.
// Revisit on `graphql-parser` integration.
#[display("Unexpected \"{_0}\"")]
UnexpectedToken(#[error(not(source))] CompactString),
/// The input source abruptly ended
#[display("Unexpected end of input")]
UnexpectedEndOfFile,
/// An error during tokenization occurred
#[from]
LexerError(LexerError),
/// A scalar of unexpected type occurred in the source
ExpectedScalarError(#[error(not(source))] &'static str),
/// The document nests deeper than the depth limit of the schema.
#[display("Document nesting exceeds the limit of {_0} levels")]
DepthLimitExceeded(#[error(not(source))] usize),
/// The document contains more tokens than the token limit of the schema.
#[display("Document exceeds the limit of {_0} tokens")]
TokenLimitExceeded(#[error(not(source))] usize),
/// An operation of the document expands into more fields than the field limit of the schema.
#[display("Document exceeds the limit of {_0} fields")]
FieldLimitExceeded(#[error(not(source))] usize),
}
/// Document limits of a [`Parser`].
///
/// The limits bound the work of a server to parse, validate, and execute a document.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Limits {
/// Maximum nesting depth of selection sets, fragments, input values, and list types.
pub(crate) max_depth: usize,
/// Maximum number of tokens in a document.
pub(crate) max_tokens: usize,
/// Maximum number of fields in an operation.
///
/// The count includes the fields of a fragment once for each spread of the fragment.
pub(crate) max_fields: usize,
}
impl Limits {
/// Default value of [`Limits::max_depth`].
///
/// Real documents rarely nest deeper than 20 levels. A debug build of the parser overflows a
/// 2 MiB thread stack at about 300 levels.
pub(crate) const DEFAULT_MAX_DEPTH: usize = 64;
/// Default value of [`Limits::max_tokens`].
///
/// graphql-java uses the same default token limit.
pub(crate) const DEFAULT_MAX_TOKENS: usize = 15_000;
/// Default value of [`Limits::max_fields`].
///
/// Each field takes at least one token. A document without fragments thus reaches the default
/// token limit before the default field limit.
pub(crate) const DEFAULT_MAX_FIELDS: usize = Self::DEFAULT_MAX_TOKENS;
}
impl Default for Limits {
fn default() -> Self {
Self {
max_depth: Self::DEFAULT_MAX_DEPTH,
max_tokens: Self::DEFAULT_MAX_TOKENS,
max_fields: Self::DEFAULT_MAX_FIELDS,
}
}
}
impl ParseError {
/// Creates a [`ParseError::UnexpectedToken`] out of the provided [`Token`].
#[must_use]
pub fn unexpected_token(token: Token<'_>) -> Self {
Self::UnexpectedToken(format_compact!("{token}"))
}
}
#[doc(hidden)]
pub type ParseResult<T> = Result<Spanning<T>, Spanning<ParseError>>;
#[doc(hidden)]
pub type UnlocatedParseResult<T> = Result<T, Spanning<ParseError>>;
#[doc(hidden)]
pub type OptionParseResult<T> = Result<Option<Spanning<T>>, Spanning<ParseError>>;
#[doc(hidden)]
#[derive(Debug)]
pub struct Parser<'a> {
tokens: VecDeque<Spanning<Token<'a>>>,
limits: Limits,
/// Nesting depth of the current part of the document.
///
/// [`Parser::nested()`] keeps the depth within [`Limits::max_depth`].
depth: usize,
}
impl<'a> Parser<'a> {
#[doc(hidden)]
pub fn new(lexer: &mut Lexer<'a>) -> Result<Self, Spanning<ParseError>> {
Self::with_limits(lexer, Limits::default())
}
/// Collects the tokens of `lexer` for parsing within `limits`.
///
/// Fails with [`ParseError::TokenLimitExceeded`] as soon as `lexer` produces more tokens than
/// [`Limits::max_tokens`].
pub(crate) fn with_limits(
lexer: &mut Lexer<'a>,
limits: Limits,
) -> Result<Self, Spanning<ParseError>> {
let mut tokens = VecDeque::new();
for token in lexer {
let token = token.map_err(|e| e.map(ParseError::LexerError))?;
if token.item != Token::EndOfFile && tokens.len() >= limits.max_tokens {
return Err(token.map(|_| ParseError::TokenLimitExceeded(limits.max_tokens)));
}
tokens.push_back(token);
}
Ok(Self {
tokens,
limits,
depth: 0,
})
}
#[doc(hidden)]
pub fn peek(&self) -> &Spanning<Token<'a>> {
&self.tokens[0]
}
#[doc(hidden)]
pub fn next_token(&mut self) -> ParseResult<Token<'a>> {
if self.tokens.len() == 1 {
Err(Spanning::new(
self.peek().span,
ParseError::UnexpectedEndOfFile,
))
} else {
Ok(self
.tokens
.pop_front()
.expect("`Token::EndOfFile` always remains in `self.tokens`"))
}
}
/// Parses a nested part of the document with `parse`.
///
/// Fails with [`ParseError::DepthLimitExceeded`] instead of calling `parse` if the nested part
/// exceeds [`Limits::max_depth`]. The parser is recursive. The depth limit keeps the parser
/// from overflowing the stack.
pub(crate) fn nested<T>(
&mut self,
parse: impl FnOnce(&mut Self) -> Result<T, Spanning<ParseError>>,
) -> Result<T, Spanning<ParseError>> {
if self.depth >= self.limits.max_depth {
return Err(Spanning::new(
self.peek().span,
ParseError::DepthLimitExceeded(self.limits.max_depth),
));
}
self.depth += 1;
let parsed = parse(self);
self.depth -= 1;
parsed
}
#[doc(hidden)]
pub fn expect(&mut self, expected: &Token) -> ParseResult<Token<'a>> {
if &self.peek().item != expected {
Err(self.next_token()?.map(ParseError::unexpected_token))
} else {
self.next_token()
}
}
#[doc(hidden)]
pub fn skip(
&mut self,
expected: &Token,
) -> Result<Option<Spanning<Token<'a>>>, Spanning<ParseError>> {
if &self.peek().item == expected {
Ok(Some(self.next_token()?))
} else if self.peek().item == Token::EndOfFile {
Err(Spanning::zero_width(
&self.peek().span.start,
ParseError::UnexpectedEndOfFile,
))
} else {
Ok(None)
}
}
#[doc(hidden)]
pub fn delimited_list<T, F>(
&mut self,
opening: &Token,
parser: F,
closing: &Token,
) -> ParseResult<Vec<Spanning<T>>>
where
T: fmt::Debug,
F: Fn(&mut Parser<'a>) -> ParseResult<T>,
{
let start_pos = &self.expect(opening)?.span.start;
let mut items = Vec::new();
loop {
if let Some(Spanning { span, .. }) = self.skip(closing)? {
return Ok(Spanning::start_end(start_pos, &span.end, items));
}
items.push(parser(self)?);
}
}
#[doc(hidden)]
pub fn delimited_nonempty_list<T, F>(
&mut self,
opening: &Token,
parser: F,
closing: &Token,
) -> ParseResult<Vec<Spanning<T>>>
where
T: fmt::Debug,
F: Fn(&mut Parser<'a>) -> ParseResult<T>,
{
let start_pos = &self.expect(opening)?.span.start;
let mut items = Vec::new();
loop {
items.push(parser(self)?);
if let Some(end_spanning) = self.skip(closing)? {
return Ok(Spanning::start_end(start_pos, &end_spanning.end(), items));
}
}
}
#[doc(hidden)]
pub fn unlocated_delimited_nonempty_list<T, F>(
&mut self,
opening: &Token,
parser: F,
closing: &Token,
) -> ParseResult<Vec<T>>
where
T: fmt::Debug,
F: Fn(&mut Parser<'a>) -> UnlocatedParseResult<T>,
{
let start_pos = &self.expect(opening)?.span.start;
let mut items = Vec::new();
loop {
items.push(parser(self)?);
if let Some(end_spanning) = self.skip(closing)? {
return Ok(Spanning::start_end(start_pos, &end_spanning.end(), items));
}
}
}
#[doc(hidden)]
pub fn expect_name(&mut self) -> ParseResult<&'a str> {
match *self.peek() {
Spanning {
item: Token::Name(_),
..
} => Ok(self.next_token()?.map(|token| {
if let Token::Name(name) = token {
name
} else {
panic!("Internal parse error in `expect_name`");
}
})),
Spanning {
item: Token::EndOfFile,
..
} => Err(Spanning::new(
self.peek().span,
ParseError::UnexpectedEndOfFile,
)),
_ => Err(self.next_token()?.map(ParseError::unexpected_token)),
}
}
}
impl<'a> StringLiteral<'a> {
/// Parses this [`StringLiteral`] returning an unescaped and unquoted string value.
///
/// # Errors
///
/// If this [`StringLiteral`] is invalid.
pub fn parse(self) -> Result<Cow<'a, str>, ParseError> {
match self {
Self::Quoted(lit) => {
if !lit.starts_with('"') {
return Err(ParseError::unexpected_token(Token::Scalar(
ScalarToken::String(self),
)));
}
if !lit.ends_with('"') {
return Err(LexerError::UnterminatedString.into());
}
let unquoted = &lit[1..lit.len() - 1];
if !unquoted.contains('\\') {
return Ok(unquoted.into());
}
let mut unescaped = String::with_capacity(unquoted.len());
let mut char_iter = unquoted.chars();
while let Some(ch) = char_iter.next() {
match ch {
// StringCharacter ::
// SourceCharacter but not " or \ or LineTerminator
// \uEscapedUnicode
// \EscapedCharacter
'\\' => match char_iter.next() {
// EscapedCharacter :: one of
// " \ / b f n r t
Some('"') => unescaped.push('"'),
Some('\\') => unescaped.push('\\'),
Some('/') => unescaped.push('/'),
Some('b') => unescaped.push('\u{0008}'),
Some('f') => unescaped.push('\u{000C}'),
Some('n') => unescaped.push('\n'),
Some('r') => unescaped.push('\r'),
Some('t') => unescaped.push('\t'),
// EscapedUnicode ::
// {HexDigit[list]}
// HexDigit HexDigit HexDigit HexDigit
Some('u') => {
let mut code_point =
UnicodeCodePoint::parse_escaped(&mut char_iter)?;
if code_point.is_high_surrogate() {
let (Some('\\'), Some('u')) =
(char_iter.next(), char_iter.next())
else {
return Err(LexerError::UnknownEscapeSequence(
code_point.to_string(),
)
.into());
};
let trailing_code_point =
UnicodeCodePoint::parse_escaped(&mut char_iter)?;
if !trailing_code_point.is_low_surrogate() {
return Err(LexerError::UnknownEscapeSequence(
code_point.to_string(),
)
.into());
}
code_point = UnicodeCodePoint::from_surrogate_pair(
code_point,
trailing_code_point,
);
}
unescaped.push(code_point.try_into_char()?);
}
Some(s) => {
return Err(
LexerError::UnknownEscapeSequence(format!(r"\{s}")).into()
);
}
None => {
return Err(LexerError::UnterminatedString.into());
}
},
ch => {
unescaped.push(ch);
}
}
}
Ok(unescaped.into())
}
Self::Block(lit) => {
if !lit.starts_with(r#"""""#) {
return Err(ParseError::unexpected_token(Token::Scalar(
ScalarToken::String(self),
)));
}
if !lit.ends_with(r#"""""#) {
return Err(LexerError::UnterminatedBlockString.into());
}
let unquoted = &lit[3..lit.len() - 3];
let (mut indent, mut total_lines) = (usize::MAX, 0);
let (mut first_text_line, mut last_text_line) = (None, 0);
for (n, line) in unquoted.lines().enumerate() {
total_lines += 1;
let trimmed = line.trim_start();
if trimmed.is_empty() {
continue;
}
_ = first_text_line.get_or_insert(n);
last_text_line = n;
if n != 0 {
indent = indent.min(line.len() - trimmed.len());
}
}
let Some(first_text_line) = first_text_line else {
return Ok("".into()); // no text, only whitespaces
};
if (indent == 0 || total_lines == 1) && !unquoted.contains(r#"\""""#) {
return Ok(unquoted.into()); // nothing to dedent or unescape
}
let mut unescaped = String::with_capacity(unquoted.len());
let mut lines = unquoted
.lines()
.enumerate()
.skip(first_text_line)
.take(last_text_line - first_text_line + 1)
.map(|(n, line)| {
if n != 0 && line.len() >= indent {
&line[indent..]
} else {
line
}
})
.map(|x| x.replace(r#"\""""#, r#"""""#));
if let Some(line) = lines.next() {
unescaped.push_str(&line);
for line in lines {
unescaped.push('\n');
unescaped.push_str(&line);
}
}
Ok(unescaped.into())
}
}
}
}
impl UnicodeCodePoint {
/// Parses a [`UnicodeCodePoint`] from an [escaped] value in the provided [`Iterator`].
///
/// [escaped]: https://spec.graphql.org/September2025#EscapedUnicode
pub(crate) fn parse_escaped(
char_iter: &mut impl Iterator<Item = char>,
) -> Result<Self, ParseError> {
// EscapedUnicode ::
// {HexDigit[list]}
// HexDigit HexDigit HexDigit HexDigit
let Some(mut curr_ch) = char_iter.next() else {
return Err(LexerError::UnknownEscapeSequence(r"\u".into()).into());
};
let mut escaped_code_point = String::with_capacity(6); // `\u{10FFFF}` is max code point
let is_variable_width = curr_ch == '{';
if is_variable_width {
loop {
curr_ch = char_iter.next().ok_or_else(|| {
LexerError::UnknownEscapeSequence(format!(r"\u{{{escaped_code_point}"))
})?;
if curr_ch == '}' {
break;
} else if !curr_ch.is_alphanumeric() {
return Err(LexerError::UnknownEscapeSequence(format!(
r"\u{{{escaped_code_point}"
))
.into());
}
escaped_code_point.push(curr_ch);
}
} else {
let mut char_iter = iter::once(curr_ch).chain(char_iter);
for _ in 0..4 {
curr_ch = char_iter.next().ok_or_else(|| {
LexerError::UnknownEscapeSequence(format!(r"\u{escaped_code_point}"))
})?;
if !curr_ch.is_alphanumeric() {
return Err(LexerError::UnknownEscapeSequence(format!(
r"\u{escaped_code_point}"
))
.into());
}
escaped_code_point.push(curr_ch);
}
}
let Ok(code) = u32::from_str_radix(&escaped_code_point, 16) else {
return Err(LexerError::UnknownEscapeSequence(if is_variable_width {
format!(r"\u{{{escaped_code_point}}}")
} else {
format!(r"\u{escaped_code_point}")
})
.into());
};
Ok(Self {
code,
is_variable_width,
})
}
}
#[cfg(test)]
mod string_literal_tests {
use super::StringLiteral;
#[test]
fn quoted() {
for (input, expected) in [
(r#""""#, ""),
(r#""simple""#, "simple"),
(r#"" white space ""#, " white space "),
(r#""quote \"""#, r#"quote ""#),
(r#""escaped \n\r\b\t\f""#, "escaped \n\r\u{0008}\t\u{000c}"),
(r#""slashes \\ \/""#, r"slashes \ /"),
(
r#""unicode \u1234\u5678\u90AB\uCDEF""#,
"unicode \u{1234}\u{5678}\u{90ab}\u{cdef}",
),
(
r#""string with unicode escape outside BMP \u{1F600}""#,
"string with unicode escape outside BMP \u{1F600}",
),
(
r#""string with minimal unicode escape \u{0}""#,
"string with minimal unicode escape \u{0}",
),
(
r#""string with maximal unicode escape \u{10FFFF}""#,
"string with maximal unicode escape \u{10FFFF}",
),
(
r#""string with maximal minimal unicode escape \u{000000}""#,
"string with maximal minimal unicode escape \u{000000}",
),
(
r#""string with unicode surrogate pair escape \uD83D\uDE00""#,
"string with unicode surrogate pair escape \u{1f600}",
),
(
r#""string with minimal surrogate pair escape \uD800\uDC00""#,
"string with minimal surrogate pair escape \u{10000}",
),
(
r#""string with maximal surrogate pair escape \uDBFF\uDFFF""#,
"string with maximal surrogate pair escape \u{10FFFF}",
),
] {
let res = StringLiteral::Quoted(input).parse();
assert!(
res.is_ok(),
"parsing error occurred on {input}: {}",
res.unwrap_err(),
);
assert_eq!(res.unwrap(), expected);
}
}
#[test]
fn quoted_errors() {
for (input, expected) in [
(
r#""bad surrogate \uDEAD""#,
r#"Unknown escape sequence "\uDEAD" in string"#,
),
(
r#""bad low surrogate pair \uD800\uD800""#,
r#"Unknown escape sequence "\uD800" in string"#,
),
] {
let res = StringLiteral::Quoted(input).parse();
assert!(res.is_err(), "parsing error doesn't occur on {input}");
let err = res.unwrap_err();
assert!(
err.to_string().contains(expected),
"returned error `{err}` doesn't contain `{expected}`",
);
}
}
#[test]
fn block() {
for (input, expected) in [
(r#""""""""#, ""),
(r#""""simple""""#, "simple"),
(r#"""" white space """"#, " white space "),
(r#""""contains " quote""""#, r#"contains " quote"#),
(
r#""""contains \""" triple quote""""#,
r#"contains """ triple quote"#,
),
(
r#""""contains \"" double quote""""#,
r#"contains \"" double quote"#,
),
(
r#""""contains \\""" triple quote""""#,
r#"contains \""" triple quote"#,
),
(r#""""\"""quote" """"#, r#""""quote" "#),
(r#""""multi\nline""""#, r"multi\nline"),
(
r#""""multi\rline\r\nnormalized""""#,
r"multi\rline\r\nnormalized",
),
(
r#""""unescaped \\n\\r\\b\\t\\f\\u1234""""#,
r"unescaped \\n\\r\\b\\t\\f\\u1234",
),
(
r#""""unescaped unicode outside BMP \u{1f600}""""#,
r"unescaped unicode outside BMP \u{1f600}",
),
(r#""""slashes \\\\ \\/""""#, r"slashes \\\\ \\/"),
(
r#""""
spans
multiple
lines
""""#,
"spans\n multiple\n lines",
),
// removes uniform indentation
(
r#""""
Hello,
World!
Yours,
GraphQL.""""#,
"Hello,\n World!\n\nYours,\n GraphQL.",
),
// removes empty leading and trailing lines
(
r#""""
Hello,
World!
Yours,
GraphQL.
""""#,
"Hello,\n World!\n\nYours,\n GraphQL.",
),
// retains indentation from first line
(
r#"""" Hello,
World!
Yours,
GraphQL.""""#,
" Hello,\n World!\n\nYours,\n GraphQL.",
),
// does not alter trailing spaces
(
r#""""
Hello,
World!
Yours,
GraphQL. """"#,
"Hello,\n World!\n\nYours,\n GraphQL. ",
),
] {
let res = StringLiteral::Block(input).parse();
assert!(
res.is_ok(),
"parsing error occurred on {input}: {}",
res.unwrap_err(),
);
assert_eq!(res.unwrap(), expected);
}
}
}