-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathSection 2 -- Language.md
More file actions
1559 lines (1166 loc) · 47.5 KB
/
Section 2 -- Language.md
File metadata and controls
1559 lines (1166 loc) · 47.5 KB
Edit and raw actions
OlderNewer
1
# Language
2
3
Clients use the GraphQL query language to make requests to a GraphQL service. We
4
refer to these _request_ sources as documents. A document may contain operations
5
(queries, mutations, and subscriptions) as well as fragments, a common unit of
6
composition allowing for data requirement reuse.
7
8
A GraphQL document is defined as a syntactic grammar where terminal symbols are
9
tokens (indivisible lexical units). These tokens are defined in a lexical
10
grammar which matches patterns of source characters. In this document, syntactic
11
grammar productions are distinguished with a colon `:` while lexical grammar
12
productions are distinguished with a double-colon `::`.
13
14
The source text of a GraphQL document must be a sequence of {SourceCharacter}.
15
The character sequence must be described by a sequence of {Token} and {Ignored}
16
lexical grammars. The lexical token sequence, omitting {Ignored}, must be
17
described by a single {Document} syntactic grammar.
18
19
Note: See [Appendix A](#sec-Appendix-Notation-Conventions) for more information
20
about the lexical and syntactic grammar and other notational conventions used
21
throughout this document.
22
23
**Lexical Analysis & Syntactic Parse**
24
25
The source text of a GraphQL document is first converted into a sequence of
26
lexical tokens ({Token}) and ignored tokens ({Ignored}). The source text is
27
scanned from left to right, repeatedly taking the next possible sequence of code
28
points allowed by the lexical grammar productions as the next token. This
29
sequence of lexical tokens is then scanned from left to right to produce an
30
abstract syntax tree (AST) according to the {Document} syntactic grammar.
31
32
Lexical grammar productions in this document use _lookahead restrictions_ to
33
remove ambiguity and ensure a single valid lexical analysis. A lexical token is
34
only valid if not followed by a character in its lookahead restriction.
35
36
For example, an {IntValue} has the restriction {[lookahead != Digit]}, so cannot
37
be followed by a {Digit}. Because of this, the sequence {`123`} cannot represent
38
the tokens ({`12`}, {`3`}) since {`12`} is followed by the {Digit} {`3`} and so
39
must only represent a single token. Use {Whitespace} or other {Ignored} between
40
characters to represent multiple tokens.
41
42
Note: This typically has the same behavior as a
43
"[maximal munch](https://en.wikipedia.org/wiki/Maximal_munch)" longest possible
44
match, however some lookahead restrictions include additional constraints.
45
46
## Source Text
47
48
SourceCharacter :: "Any Unicode scalar value"
49
50
GraphQL documents are interpreted from a source text, which is a sequence of
51
{SourceCharacter}, each {SourceCharacter} being a _Unicode scalar value_ which
52
may be any Unicode code point from U+0000 to U+D7FF or U+E000 to U+10FFFF
53
(informally referred to as _"characters"_ through most of this specification).
54
55
A GraphQL document may be expressed only in the ASCII range to be as widely
56
compatible with as many existing tools, languages, and serialization formats as
57
possible and avoid display issues in text editors and source control. Non-ASCII
58
Unicode scalar values may appear within {StringValue} and {Comment}.
59
60
Note: An implementation which uses _UTF-16_ to represent GraphQL documents in
61
memory (for example, JavaScript or Java) may encounter a _surrogate pair_. This
62
encodes one _supplementary code point_ and is a single valid source character,
63
however an unpaired _surrogate code point_ is not a valid source character.
64
65
### White Space
66
67
Whitespace ::
68
69
- "Horizontal Tab (U+0009)"
70
- "Space (U+0020)"
71
72
Whitespace is used to improve legibility of source text and separates other
73
tokens. Any amount of whitespace may appear before or after any token.
74
Whitespace between tokens is not significant to the semantic meaning of a
75
GraphQL document, however whitespace characters may appear within a {String} or
76
{Comment} token.
77
78
Note: GraphQL intentionally does not consider Unicode "Zs" category characters
79
as whitespace, avoiding misinterpretation by text editors and source control
80
tools.
81
82
### Line Terminators
83
84
LineTerminator ::
85
86
- "New Line (U+000A)"
87
- "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"]
88
- "Carriage Return (U+000D)" "New Line (U+000A)"
89
90
Like whitespace, line terminators are used to improve the legibility of source
91
text and separate lexical tokens, any amount may appear before or after any
92
other token and have no significance to the semantic meaning of a GraphQL
93
Document.
94
95
Note: Any error reporting which provides the line number in the source of the
96
offending syntax should use the preceding amount of {LineTerminator} to produce
97
the line number.
98
99
### Comments
100
101
Comment :: `#` CommentChar\* [lookahead != CommentChar]
102
103
CommentChar :: SourceCharacter but not LineTerminator
104
105
GraphQL source documents may contain single-line comments, starting with the
106
{`#`} marker.
107
108
A comment may contain any {SourceCharacter} except {LineTerminator} so a comment
109
always consists of all {SourceCharacter} starting with the {`#`} character up to
110
but not including the {LineTerminator} (or end of the source).
111
112
Comments are {Ignored} like whitespace and may appear after any token, or before
113
a {LineTerminator}, and have no significance to the semantic meaning of a
114
GraphQL document.
115
116
### Insignificant Commas
117
118
Comma :: ,
119
120
Similar to whitespace and line terminators, commas ({`,`}) are used to improve
121
the legibility of source text and separate lexical tokens but are otherwise
122
syntactically and semantically insignificant within GraphQL documents.
123
124
Non-significant comma characters ensure that the absence or presence of a comma
125
does not meaningfully alter the interpreted syntax of the document, as this can
126
be a common user error in other languages. It also allows for the stylistic use
127
of either trailing commas or line terminators as list delimiters which are both
128
often desired for legibility and maintainability of source code.
129
130
### Lexical Tokens
131
132
Token ::
133
134
- Punctuator
135
- Name
136
- IntValue
137
- FloatValue
138
- StringValue
139
140
A GraphQL document is composed of several kinds of indivisible lexical tokens
141
defined here in a lexical grammar by patterns of source Unicode characters.
142
Lexical tokens may be separated by {Ignored} tokens.
143
144
Tokens are later used as terminal symbols in GraphQL syntactic grammar rules.
145
146
### Ignored Tokens
147
148
Ignored ::
149
150
- UnicodeBOM
151
- Whitespace
152
- LineTerminator
153
- Comment
154
- Comma
155
156
{Ignored} tokens are used to improve readability and provide separation between
157
lexical tokens, but are otherwise insignificant and not referenced in syntactic
158
grammar productions.
159
160
Any amount of {Ignored} may appear before and after every lexical token. No
161
ignored regions of a source document are significant, however {SourceCharacter}
162
which appear in {Ignored} may also appear within a lexical {Token} in a
163
significant way, for example a {StringValue} may contain whitespace characters.
164
No {Ignored} may appear _within_ a {Token}, for example no whitespace characters
165
are permitted between the characters defining a {FloatValue}.
166
167
**Byte Order Mark**
168
169
UnicodeBOM :: "Byte Order Mark (U+FEFF)"
170
171
The _Byte Order Mark_ is a special Unicode code point which may appear at the
172
beginning of a file which programs may use to determine the fact that the text
173
stream is Unicode, and what specific encoding has been used. As files are often
174
concatenated, a _Byte Order Mark_ may appear before or after any lexical token
175
and is {Ignored}.
176
177
### Punctuators
178
179
Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | }
180
181
GraphQL documents include punctuation in order to describe structure. GraphQL is
182
a data description language and not a programming language; therefore, GraphQL
183
lacks the punctuation often used to describe mathematical expressions.
184
185
### Names
186
187
Name ::
188
189
- NameStart NameContinue\* [lookahead != NameContinue]
190
191
NameStart ::
192
193
- Letter
194
- `_`
195
196
NameContinue ::
197
198
- Letter
199
- Digit
200
- `_`
201
202
Letter :: one of
203
204
- `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M`
205
- `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z`
206
- `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m`
207
- `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z`
208
209
Digit :: one of
210
211
- `0` `1` `2` `3` `4` `5` `6` `7` `8` `9`
212
213
GraphQL documents are full of named things: operations, fields, arguments,
214
types, directives, fragments, and variables. All names must follow the same
215
grammatical form.
216
217
Names in GraphQL are case-sensitive. That is to say `name`, `Name`, and `NAME`
218
all refer to different names. Underscores are significant, which means
219
`other_name` and `othername` are two different names.
220
221
A {Name} must not be followed by a {NameContinue}. In other words, a {Name}
222
token is always the longest possible valid sequence. The source characters
223
{`a1`} cannot be interpreted as two tokens since {`a`} is followed by the
224
{NameContinue} {`1`}.
225
226
Note: Names in GraphQL are limited to the Latin <acronym>ASCII</acronym> subset
227
of {SourceCharacter} in order to support interoperation with as many other
228
systems as possible.
229
230
**Reserved Names**
231
232
Any {Name} within a GraphQL type system must not start with two underscores
233
{"\_\_"} unless it is part of the [introspection system](#sec-Introspection) as
234
defined by this specification.
235
236
## Descriptions
237
238
Description : StringValue
239
240
Documentation is a first-class feature of GraphQL by including written
241
descriptions on all named definitions in executable {Document} and GraphQL type
242
systems, which is also made available via introspection ensuring the
243
documentation of a GraphQL service remains consistent with its capabilities (see
244
[Type System Descriptions](#sec-Type-System-Descriptions)).
245
246
GraphQL descriptions are provided as Markdown (as specified by
247
[CommonMark](https://commonmark.org/)). Description strings (often
248
{BlockString}) occur immediately before the definition they describe.
249
250
Descriptions in GraphQL executable documents are purely for documentation
251
purposes. They MUST NOT affect the execution, validation, or response of a
252
GraphQL document. It is safe to remove all descriptions and comments from
253
executable documents without changing their behavior or results.
254
255
This is an example of a well-described operation:
256
257
```graphql example
258
"""
259
Request the current status of a time machine and its operator.
260
You can also check the status for a particular year.
261
**Warning:** certain years may trigger an anomaly in the space-time continuum.
262
"""
263
query GetTimeMachineStatus(
264
"The unique serial number of the time machine to inspect."
265
$machineId: ID!
266
"The year to check the status for."
267
$year: Int
268
) {
269
timeMachine(id: $machineId) {
270
...TimeMachineDetails
271
status(year: $year)
272
}
273
}
274
275
"Details about a time machine and its operator."
276
fragment TimeMachineDetails on TimeMachine {
277
id
278
model
279
lastMaintenance
280
operator {
281
name
282
licenseLevel
283
}
284
}
285
```
286
287
## Document
288
289
Document : Definition+
290
291
Definition :
292
293
- ExecutableDefinition
294
- TypeSystemDefinitionOrExtension
295
296
ExecutableDocument : ExecutableDefinition+
297
298
ExecutableDefinition :
299
300
- OperationDefinition
301
- FragmentDefinition
302
303
A GraphQL document describes a complete file or request string operated on by a
304
GraphQL service or client. A document contains multiple definitions, either
305
executable or representative of a GraphQL type system.
306
307
Documents are only executable by a GraphQL service if they are
308
{ExecutableDocument} and contain at least one {OperationDefinition}. A Document
309
which contains {TypeSystemDefinitionOrExtension} must not be executed; GraphQL
310
execution services which receive a Document containing these should return a
311
descriptive error.
312
313
GraphQL services which only seek to execute GraphQL requests and not construct a
314
new GraphQL schema may choose to only permit {ExecutableDocument}.
315
316
Documents which do not contain {OperationDefinition} or do contain
317
{TypeSystemDefinitionOrExtension} may still be parsed and validated to allow
318
client tools to represent many GraphQL uses which may appear across many
319
individual files.
320
321
If a Document contains only one operation, that operation may be unnamed. If
322
that operation is a query without variables or directives then it may also be
323
represented in the shorthand form, omitting both the {`query`} keyword as well
324
as the operation name. Otherwise, if a GraphQL document contains multiple
325
operations, each operation must be named. When submitting a Document with
326
multiple operations to a GraphQL service, the name of the desired operation to
327
be executed must also be provided.
328
329
## Operations
330
331
OperationDefinition :
332
333
- Description? OperationType Name? VariablesDefinition? Directives? SelectionSet
334
- SelectionSet
335
336
OperationType : one of `query` `mutation` `subscription`
337
338
There are three types of operations that GraphQL models:
339
340
- query - a read-only fetch.
341
- mutation - a write followed by a fetch.
342
- subscription - a long-lived request that fetches data in response to a
343
sequence of events over time.
344
345
Each operation is represented by an optional operation name and a _selection
346
set_.
347
348
For example, this mutation operation might "like" a story and then retrieve the
349
new number of likes:
350
351
```graphql example
352
"""
353
Mark story 12345 as "liked"
354
and return the updated number of likes on the story
355
"""
356
mutation {
357
likeStory(storyID: 12345) {
358
story {
359
likeCount
360
}
361
}
362
}
363
```
364
365
**Query Shorthand**
366
367
If a document contains only one operation and that operation is a query which
368
defines no variables and has no directives applied to it then that operation may
369
be represented in a shorthand form which omits the {`query`} keyword and
370
operation name.
371
372
For example, this unnamed query operation is written via query shorthand.
373
374
```graphql example
375
{
376
field
377
}
378
```
379
380
Descriptions are not permitted on query shorthand.
381
382
Note: many examples below will use the query shorthand syntax.
383
384
## Selection Sets
385
386
SelectionSet : { Selection+ }
387
388
Selection :
389
390
- Field
391
- FragmentSpread
392
- InlineFragment
393
394
An operation selects the set of information it needs, and will receive exactly
395
that information and nothing more, avoiding over-fetching and under-fetching
396
data.
397
398
:: A _selection set_ defines an ordered set of selections (fields, fragment
399
spreads and inline fragments) against an object, union or interface type.
400
401
```graphql example
402
{
403
id
404
firstName
405
lastName
406
}
407
```
408
409
In this query operation, the `id`, `firstName`, and `lastName` fields form a
410
_selection set_. Selection sets may also contain fragment references.
411
412
## Fields
413
414
Field : Alias? Name Arguments? Directives? SelectionSet?
415
416
A _selection set_ is primarily composed of fields. A field describes one
417
discrete piece of information available to request within a selection set.
418
419
Some fields describe complex data or relationships to other data. In order to
420
further explore this data, a field may itself contain a selection set, allowing
421
for deeply nested requests. All GraphQL operations must specify their selections
422
down to _leaf fields_ to ensure an unambiguously shaped response.
423
424
For example, this operation selects fields of complex data and relationships
425
down to scalar values.
426
427
```graphql example
428
{
429
me {
430
id
431
firstName
432
lastName
433
birthday {
434
month
435
day
436
}
437
friends {
438
name
439
}
440
}
441
}
442
```
443
444
Fields in the top-level _selection set_ of an operation often represent some
445
information that is globally accessible to your application and its current
446
viewer. Some typical examples of these top fields include references to a
447
current logged-in viewer, or accessing certain types of data referenced by a
448
unique identifier.
449
450
```graphql example
451
# `me` could represent the currently logged in viewer.
452
{
453
me {
454
name
455
}
456
}
457
458
# `user` represents one of many users in a graph of data, referred to by a
459
# unique identifier.
460
{
461
user(id: 4) {
462
name
463
}
464
}
465
```
466
467
## Arguments
468
469
Arguments[Const] : ( Argument[?Const]+ )
470
471
Argument[Const] : Name : Value[?Const]
472
473
Fields are conceptually functions which return values, and occasionally accept
474
arguments which alter their behavior. These arguments often map directly to
475
function arguments within a GraphQL service's implementation.
476
477
In this example, we want to query a specific user (requested via the `id`
478
argument) and their profile picture of a specific `size`:
479
480
```graphql example
481
{
482
user(id: 4) {
483
id
484
name
485
profilePic(size: 100)
486
}
487
}
488
```
489
490
Many arguments can exist for a given field:
491
492
```graphql example
493
{
494
user(id: 4) {
495
id
496
name
497
profilePic(width: 100, height: 50)
498
}
499
}
500
```
501
502
**Arguments Are Unordered**
503
504
Arguments may be provided in any syntactic order and maintain identical semantic
505
meaning.
506
507
These two operations are semantically identical:
508
509
```graphql example
510
{
511
picture(width: 200, height: 100)
512
}
513
```
514
515
```graphql example
516
{
517
picture(height: 100, width: 200)
518
}
519
```
520
521
## Field Alias
522
523
Alias : Name :
524
525
:: A _response name_ is the key in the response object which correlates with a
526
field's result. By default the response name will use the field's name; however,
527
you can define a different response name by specifying an alias.
528
529
In this example, we can fetch two profile pictures of different sizes and ensure
530
the resulting response object will not have duplicate keys:
531
532
```graphql example
533
{
534
user(id: 4) {
535
id
536
name
537
smallPic: profilePic(size: 64)
538
bigPic: profilePic(size: 1024)
539
}
540
}
541
```
542
543
which returns the result:
544
545
```json example
546
{
547
"user": {
548
"id": 4,
549
"name": "Mark Zuckerberg",
550
"smallPic": "https://cdn.site.io/pic-4-64.jpg",
551
"bigPic": "https://cdn.site.io/pic-4-1024.jpg"
552
}
553
}
554
```
555
556
The fields at the top level of an operation can also be given an alias:
557
558
```graphql example
559
{
560
zuck: user(id: 4) {
561
id
562
name
563
}
564
}
565
```
566
567
which returns the result:
568
569
```json example
570
{
571
"zuck": {
572
"id": 4,
573
"name": "Mark Zuckerberg"
574
}
575
}
576
```
577
578
## Fragments
579
580
FragmentSpread : ... FragmentName Directives?
581
582
FragmentDefinition : Description? fragment FragmentName TypeCondition
583
Directives? SelectionSet
584
585
FragmentName : Name but not `on`
586
587
Fragments are the primary unit of composition in GraphQL.
588
589
Each data-consuming component (function, class, UI element, and so on) of a
590
client application should declare its data needs in a dedicated fragment. These
591
fragments may then be composed, following the usage of the components
592
themselves, to form a GraphQL operation to issue to the server.
593
594
For example, if we have some logic that requires `id`, `name`, and `profilePic`
595
to render a profile, and we want to apply that logic to the friends and mutual
596
friends of a user:
597
598
```graphql example
599
query noFragments {
600
user(id: 4) {
601
friends(first: 10) {
602
id
603
name
604
profilePic(size: 50)
605
}
606
mutualFriends(first: 10) {
607
id
608
name
609
profilePic(size: 50)
610
}
611
}
612
}
613
```
614
615
The fields required to render a profile can be extracted into a fragment and
616
composed by a parent fragment or operation.
617
618
```graphql example
619
query withFragments {
620
user(id: 4) {
621
friends(first: 10) {
622
...friendProfile
623
}
624
mutualFriends(first: 10) {
625
...friendProfile
626
}
627
}
628
}
629
```
630
631
```graphql example
632
"Fields required to render a friend's profile"
633
fragment friendProfile on User {
634
id
635
name
636
profilePic(size: 50)
637
}
638
```
639
640
If the profile rendering logic no longer needs `name`, the `name` field can be
641
removed from the `friendProfile` fragment and it will no longer be fetched in
642
both locations the fragment is consumed.
643
644
Fragments are consumed by using the spread operator (`...`). All fields selected
645
by the fragment will be added to the field selection at the same level as the
646
fragment invocation. This happens through multiple levels of fragment spreads.
647
648
For example:
649
650
```graphql example
651
query withNestedFragments {
652
user(id: 4) {
653
friends(first: 10) {
654
...friendFields
655
}
656
mutualFriends(first: 10) {
657
...friendFields
658
}
659
}
660
}
661
662
fragment friendFields on User {
663
id
664
name
665
...standardProfilePic
666
}
667
668
fragment standardProfilePic on User {
669
profilePic(size: 50)
670
}
671
```
672
673
The operations `noFragments`, `withFragments`, and `withNestedFragments` all
674
produce the same response object.
675
676
### Type Conditions
677
678
TypeCondition : on NamedType
679
680
Fragments must specify the type they apply to. In this example, `friendFields`
681
can be used in the context of querying a `User`.
682
683
Fragments cannot be specified on any input value (scalar, enumeration, or input
684
object).
685
686
Fragments can be specified on object types, interfaces, and unions.
687
688
Selections within fragments only return values when the concrete type of the
689
object it is operating on matches the type of the fragment.
690
691
For example in this operation using the Facebook data model:
692
693
```graphql example
694
query FragmentTyping {
695
profiles(handles: ["zuck", "coca-cola"]) {
696
handle
697
...userFragment
698
...pageFragment
699
}
700
}
701
702
fragment userFragment on User {
703
friends {
704
count
705
}
706
}
707
708
fragment pageFragment on Page {
709
likers {
710
count
711
}
712
}
713
```
714
715
The `profiles` root field returns a list where each element could be a `Page` or
716
a `User`. When the object in the `profiles` result is a `User`, `friends` will
717
be present and `likers` will not. Conversely when the result is a `Page`,
718
`likers` will be present and `friends` will not.
719
720
```json example
721
{
722
"profiles": [
723
{
724
"handle": "zuck",
725
"friends": { "count": 1234 }
726
},
727
{
728
"handle": "coca-cola",
729
"likers": { "count": 90234512 }
730
}
731
]
732
}
733
```
734
735
### Inline Fragments
736
737
InlineFragment : ... TypeCondition? Directives? SelectionSet
738
739
Fragments can also be defined inline within a _selection set_. This is useful
740
for conditionally including fields based on a type condition or applying a
741
directive to a selection set.
742
743
This feature of standard fragment inclusion was demonstrated in the
744
`query FragmentTyping` example above. We could accomplish the same thing using
745
inline fragments.
746
747
```graphql example
748
query inlineFragmentTyping {
749
profiles(handles: ["zuck", "coca-cola"]) {
750
handle
751
... on User {
752
friends {
753
count
754
}
755
}
756
... on Page {
757
likers {
758
count
759
}
760
}
761
}
762
}
763
```
764
765
Inline fragments may also be used to apply a directive to a group of fields. If
766
the TypeCondition is omitted, an inline fragment is considered to be of the same
767
type as the enclosing context.
768
769
```graphql example
770
query inlineFragmentNoType($expandedInfo: Boolean) {
771
user(handle: "zuck") {
772
id
773
name
774
... @include(if: $expandedInfo) {
775
firstName
776
lastName
777
birthday
778
}
779
}
780
}
781
```
782
783
## Input Values
784
785
Value[Const] :
786
787
- [~Const] Variable
788
- IntValue
789
- FloatValue
790
- StringValue
791
- BooleanValue
792
- NullValue
793
- EnumValue
794
- ListValue[?Const]
795
- ObjectValue[?Const]
796
797
Field and directive arguments accept input values of various literal primitives;
798
input values can be scalars, enumeration values, lists, or input objects.
799
800
If not defined as constant (for example, in {DefaultValue}), input values can be
801
specified as a variable. List and inputs objects may also contain variables
802
(unless defined to be constant).
803
804
### Int Value
805
806
IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}]
807
808
IntegerPart ::
809
810
- NegativeSign? 0
811
- NegativeSign? NonZeroDigit Digit\*
812
813
NegativeSign :: -
814
815
NonZeroDigit :: Digit but not `0`
816
817
An {IntValue} is specified without a decimal point or exponent but may be
818
negative (e.g. {-123}). It must not have any leading {0}.
819
820
An {IntValue} must not be followed by a {Digit}. In other words, an {IntValue}
821
token is always the longest possible valid sequence. The source characters {12}
822
cannot be interpreted as two tokens since {1} is followed by the {Digit} {2}.
823
This also means the source {00} is invalid since it can neither be interpreted
824
as a single token nor two {0} tokens.
825
826
An {IntValue} must not be followed by a {`.`} or {NameStart}. If either {`.`} or
827
{ExponentIndicator} follows then the token must only be interpreted as a
828
possible {FloatValue}. No other {NameStart} character can follow. For example
829
the sequences `0x123` and `123L` have no valid lexical representations.
830
831
### Float Value
832
833
FloatValue ::
834
835
- IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}]
836
- IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}]
837
- IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}]
838
839
FractionalPart :: . Digit+
840
841
ExponentPart :: ExponentIndicator Sign? Digit+
842
843
ExponentIndicator :: one of `e` `E`
844
845
Sign :: one of + -
846
847
A {FloatValue} includes either a decimal point (e.g. {1.0}) or an exponent (e.g.
848
{1e50}) or both (e.g. {6.0221413e23}) and may be negative. Like {IntValue}, it
849
also must not have any leading {0}.
850
851
A {FloatValue} must not be followed by a {Digit}. In other words, a {FloatValue}
852
token is always the longest possible valid sequence. The source characters
853
{1.23} cannot be interpreted as two tokens since {1.2} is followed by the
854
{Digit} {3}.
855
856
A {FloatValue} must not be followed by a {.}. For example, the sequence {1.23.4}
857
cannot be interpreted as two tokens ({1.2}, {3.4}).
858
859
A {FloatValue} must not be followed by a {NameStart}. For example the sequence
860
`0x1.2p3` has no valid lexical representation.
861
862
Note: The numeric literals {IntValue} and {FloatValue} both restrict being
863
immediately followed by a letter (or other {NameStart}) to reduce confusion or
864
unexpected behavior since GraphQL only supports decimal numbers.
865
866
### Boolean Value
867
868
BooleanValue : one of `true` `false`
869
870
The two keywords `true` and `false` represent the two boolean values.
871
872
### String Value
873
874
StringValue ::
875
876
- `""` [lookahead != `"`]
877
- `"` StringCharacter+ `"`
878
- BlockString
879
880
StringCharacter ::
881
882
- SourceCharacter but not `"` or `\` or LineTerminator
883
- `\u` EscapedUnicode
884
- `\` EscapedCharacter
885
886
EscapedUnicode ::
887
888
- `{` HexDigit+ `}`
889
- HexDigit HexDigit HexDigit HexDigit
890
891
HexDigit :: one of
892
893
- `0` `1` `2` `3` `4` `5` `6` `7` `8` `9`
894
- `A` `B` `C` `D` `E` `F`
895
- `a` `b` `c` `d` `e` `f`
896
897
EscapedCharacter :: one of `"` `\` `/` `b` `f` `n` `r` `t`
898
899
BlockString :: `"""` BlockStringCharacter\* `"""`
900
901
BlockStringCharacter ::
902
903
- SourceCharacter but not `"""` or `\"""`
904
- `\"""`
905
906
A {StringValue} is evaluated to a _Unicode text_ value, a sequence of _Unicode
907
scalar value_, by interpreting all escape sequences using the static semantics
908
defined below. Whitespace and other characters ignored between lexical tokens
909
are significant within a string value.
910
911
The empty string {`""`} must not be followed by another {`"`} otherwise it would
912
be interpreted as the beginning of a block string. As an example, the source
913
{`""""""`} can only be interpreted as a single empty block string and not three
914
empty strings.
915
916
**Escape Sequences**
917
918
In a single-quoted {StringValue}, any _Unicode scalar value_ may be expressed
919
using an escape sequence. GraphQL strings allow both C-style escape sequences
920
(for example `\n`) and two forms of Unicode escape sequences: one with a
921
fixed-width of 4 hexadecimal digits (for example `\u000A`) and one with a
922
variable-width most useful for representing a _supplementary character_ such as
923
an Emoji (for example `\u{1F4A9}`).
924
925
The hexadecimal number encoded by a Unicode escape sequence must describe a
926
_Unicode scalar value_, otherwise must result in a parse error. For example both
927
sources `"\uDEAD"` and `"\u{110000}"` should not be considered valid
928
{StringValue}.
929
930
Escape sequences are only meaningful within a single-quoted string. Within a
931
block string, they are simply that sequence of characters (for example
932
`"""\n"""` represents the _Unicode text_ [U+005C, U+006E]). Within a comment an
933
escape sequence is not a significant sequence of characters. They may not appear
934
elsewhere in a GraphQL document.
935
936
Since {StringCharacter} must not contain some code points directly (for example,
937
a {LineTerminator}), escape sequences must be used to represent them. All other
938
escape sequences are optional and unescaped non-ASCII Unicode characters are
939
allowed within strings. If using GraphQL within a system which only supports
940
ASCII, then escape sequences may be used to represent all Unicode characters
941
outside of the ASCII range.
942
943
For legacy reasons, a _supplementary character_ may be escaped by two
944
fixed-width unicode escape sequences forming a _surrogate pair_. For example the
945
input `"\uD83D\uDCA9"` is a valid {StringValue} which represents the same
946
_Unicode text_ as `"\u{1F4A9}"`. While this legacy form is allowed, it should be
947
avoided as a variable-width unicode escape sequence is a clearer way to encode
948
such code points.
949
950
When producing a {StringValue}, implementations should use escape sequences to
951
represent non-printable control characters (U+0000 to U+001F and U+007F to
952
U+009F). Other escape sequences are not necessary, however an implementation may
953
use escape sequences to represent any other range of code points (for example,
954
when producing ASCII-only output). If an implementation chooses to escape a
955
_supplementary character_, it should only use a variable-width unicode escape
956
sequence.
957
958
**Block Strings**
959
960
Block strings are sequences of characters wrapped in triple-quotes (`"""`).
961
Whitespace, line terminators, quote, and backslash characters may all be used
962
unescaped to enable verbatim text. Characters must all be valid
963
{SourceCharacter}.
964
965
Since block strings represent freeform text often used in indented positions,
966
the string value semantics of a block string excludes uniform indentation and
967
blank initial and trailing lines via {BlockStringValue()}.
968
969
For example, the following operation containing a block string:
970
971
```raw graphql example
972
mutation {
973
sendEmail(message: """
974
Hello,
975
World!
976
977
Yours,
978
GraphQL.
979
""")
980
}
981
```
982
983
Is identical to the standard quoted string:
984
985
```graphql example
986
mutation {
987
sendEmail(message: "Hello,\n World!\n\nYours,\n GraphQL.")
988
}
989
```
990
991
Since block string values strip leading and trailing empty lines, there is no
992
single canonical printed block string for a given value. Because block strings
993
typically represent freeform text, it is considered easier to read if they begin
994
and end with an empty line.
995
996
```graphql example
997
"""
998
This starts with and ends with an empty line,
999
which makes it easier to read.
1000
"""