-
Notifications
You must be signed in to change notification settings - Fork 3
/
QueryParser.scala
532 lines (436 loc) · 18.6 KB
/
QueryParser.scala
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
package gql.parser
import cats.implicits._
import cats.parse.{Parser => P}
import cats.parse.Rfc5234
import cats.parse.Numbers
import cats.data.NonEmptyList
// https://spec.graphql.org/June2018/#sec-Source-Text
object QueryParser {
val whiteSpace = Rfc5234.wsp
val lineTerminator = Rfc5234.lf | Rfc5234.crlf | Rfc5234.cr
val sep = lineTerminator | whiteSpace | P.char(',')
val seps = sep.rep.void
val seps0 = sep.rep0.void
def w[A](p: P[A]): P[A] = p.surroundedBy((whiteSpace | lineTerminator).rep0)
def t(c: Char): P[Unit] = w(P.char(c))
def s(s: String): P[Unit] = w(P.string(s))
// if this is slow, use charWhile
val sourceCharacter: P[Char] =
P.charIn(('\u0020' to '\uFFFF') :+ '\u0009' :+ '\u000A' :+ '\u000D')
val unicodeBOM = P.char('\uFEFF')
val commentChar = (!lineTerminator *> sourceCharacter).void
val comment = (P.char('#') | Rfc5234.sp | commentChar).void
val comma = t(',')
sealed trait Punctuator
object Punctuator {
case object `!` extends Punctuator
case object `$` extends Punctuator
case object `(` extends Punctuator
case object `)` extends Punctuator
case object `...` extends Punctuator
case object `:` extends Punctuator
case object `=` extends Punctuator
case object `@` extends Punctuator
case object `[` extends Punctuator
case object `]` extends Punctuator
case object `{` extends Punctuator
case object `|` extends Punctuator
case object `}` extends Punctuator
}
lazy val punctuator: P[Punctuator] = w {
import Punctuator._
P.char('!').as(`!`) |
P.char('$').as(`$`) |
P.char('(').as(`(`) |
P.char(')').as(`)`) |
P.char('.').as(`...`) |
P.char(':').as(`:`) |
P.char('=').as(`=`) |
P.char('@').as(`@`) |
P.char('[').as(`[`) |
P.char(']').as(`]`) |
P.char('{').as(`{`) |
P.char('|').as(`|`)
}
lazy val name: P[String] = w {
val rng = ('a' to 'z') :++ ('A' to 'Z') :+ '_'
val begin = P.charIn(rng)
val tl = begin | Numbers.digit
(begin ~ tl.rep0).map { case (c, s) => s"$c${s.mkString}" }
}
final case class Document(nel: NonEmptyList[Definition])
val document = definition.rep
sealed trait Definition
object Definition {
final case class ExecutableDef(x: ExecutableDefinition) extends Definition
final case class TypeSystemDefinition(t: Any) extends Definition
final case class TypeSystemExt(t: Any) extends Definition
}
lazy val definition = {
import Definition._
executableDefinition.map(ExecutableDef(_)) |
typeSystemDefinition.map(TypeSystemDefinition(_)) |
typeSystemExtension.map(TypeSystemExt(_))
}
sealed trait ExecutableDefinition
object ExecutableDefinition {
final case class Operation(o: Pos[OperationDefinition]) extends ExecutableDefinition
final case class Fragment(f: Pos[FragmentDefinition]) extends ExecutableDefinition
}
lazy val executableDefinition = w {
import ExecutableDefinition._
Pos.pos(fragmentDefinition).map(Fragment(_)) |
Pos.pos(operationDefinition).map(Operation(_))
}
sealed trait OperationDefinition
object OperationDefinition {
final case class Detailed(
tpe: OperationType,
name: Option[String],
variableDefinitions: Option[VariableDefinitions],
directives: Option[Directives],
selectionSet: SelectionSet
) extends OperationDefinition
final case class Simple(selectionSet: SelectionSet) extends OperationDefinition
}
lazy val operationDefinition = {
import OperationDefinition._
P.backtrack(selectionSet).map(Simple(_)) |
(operationType ~ name.? ~ variableDefinitions.? ~ directives.? ~ selectionSet).map { case ((((opt, name), vars), ds), ss) =>
Detailed(opt, name, vars, ds, ss)
}
}
sealed trait OperationType
object OperationType {
case object Query extends OperationType
case object Mutation extends OperationType
case object Subscription extends OperationType
}
lazy val operationType = w {
import OperationType._
P.string("query").as(Query) |
P.string("mutation").as(Mutation) |
P.string("subscription").as(Subscription)
}
final case class SelectionSet(selections: NonEmptyList[Pos[Selection]])
lazy val selectionSet: P[SelectionSet] = P.defer {
Pos.pos(w(selection)).repSep(seps0).between(t('{'), t('}')).map(SelectionSet(_))
}
sealed trait Selection
object Selection {
final case class FieldSelection(field: Field) extends Selection
final case class FragmentSpreadSelection(fragmentSpread: FragmentSpread) extends Selection
final case class InlineFragmentSelection(inlineFragment: InlineFragment) extends Selection
}
lazy val selection: P[Selection] = {
import Selection._
field.map(FieldSelection(_)) |
// expects on, backtrack on failure
inlineFragment.map(InlineFragmentSelection(_)) |
fragmentSpread.map(FragmentSpreadSelection(_))
}
final case class Field(
alias: Option[String],
name: String,
arguments: Option[Arguments],
directives: Option[Directives],
selectionSet: Pos[Option[SelectionSet]]
)
lazy val field: P[Field] = P.defer {
(P.backtrack(alias).?.with1 ~ name ~ arguments.? ~ directives.? ~ Pos.pos0(selectionSet.?))
.map { case ((((a, n), args), d), s) => Field(a, n, args, d, s) }
}
lazy val alias = name <* t(':')
final case class Arguments(nel: NonEmptyList[Argument])
lazy val arguments =
argument.repSep(seps).between(t('('), t(')')).map(Arguments.apply)
final case class Argument(name: String, value: Value)
lazy val argument =
(name ~ (t(':') *> value)).map { case (n, v) => Argument(n, v) }
final case class FragmentSpread(fragmentName: String, directives: Option[Directives])
lazy val fragmentSpread =
(s("...") *> fragmentName ~ directives.?).map { case (n, d) => FragmentSpread(n, d) }
final case class InlineFragment(typeCondition: Option[String], directives: Option[Directives], selectionSet: SelectionSet)
lazy val inlineFragment =
((s("...") *> typeCondition.? ~ directives.?).soft ~ selectionSet).map { case ((t, d), s) => InlineFragment(t, d, s) }
final case class FragmentDefinition(
name: String,
typeCnd: String,
directives: Option[Directives],
selectionSet: SelectionSet
)
lazy val fragmentDefinition =
(P.string("fragment") *> fragmentName ~ typeCondition ~ directives.? ~ selectionSet).map { case (((n, t), d), s) =>
FragmentDefinition(n, t, d, s)
}
lazy val fragmentName: P[String] =
(!P.string("on")).with1 *> name
lazy val typeCondition: P[String] =
s("on") *> name
sealed trait Value
object Value {
final case class VariableValue(v: String) extends Value
final case class IntValue(v: BigInt) extends Value
final case class FloatValue(v: BigDecimal) extends Value
final case class StringValue(v: String) extends Value
final case class BooleanValue(v: Boolean) extends Value
case object NullValue extends Value
final case class EnumValue(v: String) extends Value
final case class ListValue(v: List[Value]) extends Value
final case class ObjectValue(v: List[(String, Value)]) extends Value
}
lazy val value: P[Value] = P.defer {
import Value._
variable.map(VariableValue(_)) |
intValue.map(IntValue(_)) |
floatValue.map(FloatValue(_)) |
stringValue.map(StringValue(_)) |
booleanValue.map(BooleanValue(_)) |
nullValue.as(NullValue) |
enumValue.map(EnumValue(_)) |
listValue.map(ListValue(_)) |
objectValue.map(ObjectValue(_))
}
lazy val booleanValue =
P.string("true").as(true) |
P.string("false").as(false)
lazy val nullValue: P[Unit] =
P.string("null")
lazy val enumValue: P[String] =
(!(booleanValue | nullValue)).with1 *> name
lazy val listValue =
(value <* seps0).rep0.with1.between(t('['), t(']')) |
(t('[') *> t(']')).as(Nil)
lazy val objectValue =
(objectField <* seps0).rep.between(t('{'), t('}')).map(_.toList) |
(t('{') *> t('}')).as(Nil)
lazy val objectField =
name ~ (t(':') *> value)
final case class VariableDefinitions(nel: NonEmptyList[Pos[VariableDefinition]])
lazy val variableDefinitions =
variableDefinition
.repSep(seps)
.between(t('('), t(')'))
.map(VariableDefinitions(_))
final case class VariableDefinition(name: String, tpe: Type, defaultValue: Option[Value])
lazy val variableDefinition = Pos.pos {
(variable ~ (t(':') *> `type`) ~ defaultValue.?).map { case ((n, t), d) => VariableDefinition(n, t, d) }
}
lazy val variable =
t('$') *> name
lazy val defaultValue = t('=') *> value
lazy val namedType = name.map(Type.Named(_))
lazy val nonNullType: P[Type] =
namedType <* t('!') |
listType <* t('!')
final case class Directives(nel: NonEmptyList[Directive])
lazy val directives: P[Directives] = directive.rep.map(Directives(_))
final case class Directive(name: String, arguments: Option[Arguments])
lazy val directive: P[Directive] = s("@") *> (name ~ arguments.?).map { case (n, a) => Directive(n, a) }
lazy val typeSystemDefinition =
schemaDefinition |
typeDefinition |
directiveDefinition
lazy val typeSystemExtension =
schemaExtension |
typeExtension
lazy val schemaDefinition =
P.string("schema") *> directives.? ~ operationTypeDefinition.rep.between(t('{'), t('}'))
lazy val schemaExtension =
P.string("extend") *> P.string("schema") *> directives.? ~ operationTypeDefinition.rep.between(t('{'), t('}')) |
P.string("extend") *> P.string("schema") *> directives.?
lazy val operationTypeDefinition =
operationType ~ (t(':') *> namedType)
lazy val description = stringValue
lazy val typeDefinition =
scalarTypeDefinition |
objectTypeDefinition |
interfaceTypeDefinition |
unionTypeDefinition |
enumTypeDefinition |
inputObjectTypeDefinition
lazy val typeExtension =
scalarTypeExtension |
objectTypeExtension |
interfaceTypeExtension |
unionTypeExtension |
enumTypeExtension |
inputObjectTypeExtension
lazy val directiveDefinition =
(defaultValue.?.with1 ~ (P.string("directive") *> t('@') *> name) ~ argumentsDefinition.? ~ (P.string("on") *> directiveLocations))
lazy val scalarTypeDefinition =
description.?.with1 ~ (P.string("scalar") *> name) ~ directives.?
lazy val scalarTypeExtension =
P.string("extend") *> P.string("scalar") *> (name ~ directives.?)
lazy val objectTypeDefinition =
description.?.with1 ~ (P.string("type") *> name) ~ implementsInterface.? ~ directives.? ~ fieldsDefinition.?
lazy val objectTypeExtension =
P.string("extend") *> P.string("type") *> name ~ implementsInterface.? ~ directives.? ~ fieldsDefinition |
P.string("extend") *> P.string("type") *> name ~ implementsInterface.? ~ directives |
P.string("extend") *> P.string("type") *> name ~ implementsInterface
lazy val implementsInterface =
P.string("implements") *> t('&').? *> namedType.rep.between(t('{'), t('}'))
lazy val fieldsDefinition =
fieldDefinition.rep.between(t('{'), t('}'))
final case class FieldDefinition(
description: Option[String],
name: String,
argumentsDefinition: Option[ArgumentsDefinition],
`type`: Type,
directives: Option[Directives]
)
lazy val fieldDefinition =
(description.?.with1 ~ name ~ argumentsDefinition.? ~ (t(':') *> `type`) ~ directives.?).map { case ((((d, n), a), t), ds) =>
FieldDefinition(d, n, a, t, ds)
}
final case class ArgumentsDefinition(nel: NonEmptyList[InputValueDefinition])
lazy val argumentsDefinition =
inputValueDefinition.rep.between(t('('), t(')')).map(ArgumentsDefinition(_))
final case class InputValueDefinition(
description: Option[String],
name: String,
`type`: Type,
defaultValue: Option[Value],
directives: Option[Directives]
)
lazy val inputValueDefinition =
(description.?.with1 ~ name ~ (t(':') *> `type`) ~ defaultValue.? ~ directives.?).map { case ((((d, n), t), v), dirs) =>
InputValueDefinition(d, n, t, v, dirs)
}
lazy val interfaceTypeDefinition =
description.?.with1 ~ (P.string("interface") *> name) ~ directives.? ~ fieldsDefinition.?
lazy val interfaceTypeExtension =
P.string("extend") *> P.string("interface") *> name ~ directives.? ~ fieldsDefinition |
P.string("extend") *> P.string("interface") *> name ~ directives.?
lazy val unionTypeDefinition =
description.?.with1 ~ (P.string("union") *> name) ~ directives.? ~ unionMemberTypes.?
lazy val unionMemberTypes: P[NonEmptyList[Type.Named]] = P.defer {
t('=') *> t('|').? *> namedType.map(NonEmptyList.one(_)) |
(unionMemberTypes ~ (t('|') *> namedType)).map { case (xs, x) => xs :+ x }
}
lazy val unionTypeExtension =
P.string("extend") *> P.string("union") *> name ~ directives.? ~ unionMemberTypes |
P.string("extend") *> P.string("union") *> name ~ directives
lazy val enumTypeDefinition =
description.?.with1 ~ (P.string("enum") *> name) ~ directives.? ~ enumValuesDefinition.?
lazy val enumValuesDefinition =
enumValueDefinition.rep.between(t('{'), t('}'))
lazy val enumValueDefinition =
description.?.with1 ~ name ~ directives.?
lazy val enumTypeExtension =
P.string("extend") *> P.string("enum") *> name ~ directives.? ~ enumValuesDefinition |
P.string("extend") *> P.string("enum") *> name ~ directives
lazy val inputObjectTypeDefinition =
description.?.with1 ~ (P.string("input") *> name) ~ directives.? ~ inputFieldsDefinition.?
lazy val inputFieldsDefinition =
inputValueDefinition.rep.between(t('{'), t('}'))
lazy val inputObjectTypeExtension =
P.string("extend") *> P.string("input") *> name ~ directives.? ~ inputFieldsDefinition |
P.string("extend") *> P.string("input") *> name ~ directives
final case class DirectivesDefinition(
description: Option[String],
name: String,
// arguments: Option[ArgumentsDefinition],
directiveLocations: NonEmptyList[DirectiveLocation]
)
lazy val directivesDefinition =
description.?.with1 ~ (P.string("directive") *> t('@') *> name) ~ argumentsDefinition.? ~ (P.string("on") *> directiveLocations)
lazy val directiveLocations: P[NonEmptyList[DirectiveLocation]] = P.defer {
t('|').?.with1 *> directiveLocation.map(NonEmptyList.one(_)) |
(directiveLocations ~ (t('|') *> directiveLocation)).map { case (xs, x) => xs :+ x }
}
sealed trait DirectiveLocation
object DirectiveLocation {
final case class Executable(x: ExecutableDirectiveLocation) extends DirectiveLocation
final case class Type(x: TypeSystemDirectiveLocation) extends DirectiveLocation
}
lazy val directiveLocation: P[DirectiveLocation] =
executableDirectiveLocation.map(DirectiveLocation.Executable(_)) |
typeSystemDirectiveLocation.map(DirectiveLocation.Type(_))
sealed trait ExecutableDirectiveLocation
object ExecutableDirectiveLocation {
case object QUERY extends ExecutableDirectiveLocation
case object MUTATION extends ExecutableDirectiveLocation
case object SUBSCRIPTION extends ExecutableDirectiveLocation
case object FIELD extends ExecutableDirectiveLocation
case object FRAGMENT_DEFINITION extends ExecutableDirectiveLocation
case object FRAGMENT_SPREAD extends ExecutableDirectiveLocation
case object INLINE_FRAGMENT extends ExecutableDirectiveLocation
}
lazy val executableDirectiveLocation = {
import ExecutableDirectiveLocation._
P.string("QUERY").as(QUERY) |
P.string("MUTATION").as(MUTATION) |
P.string("SUBSCRIPTION").as(SUBSCRIPTION) |
P.string("FIELD").as(FIELD) |
P.string("FRAGMENT_DEFINITION").as(FRAGMENT_DEFINITION) |
P.string("FRAGMENT_SPREAD").as(FRAGMENT_SPREAD) |
P.string("INLINE_FRAGMENT").as(INLINE_FRAGMENT)
}
sealed trait TypeSystemDirectiveLocation
object TypeSystemDirectiveLocation {
case object SCHEMA extends TypeSystemDirectiveLocation
case object SCALAR extends TypeSystemDirectiveLocation
case object OBJECT extends TypeSystemDirectiveLocation
case object FIELD_DEFINITION extends TypeSystemDirectiveLocation
case object ARGUMENT_DEFINITION extends TypeSystemDirectiveLocation
case object INTERFACE extends TypeSystemDirectiveLocation
case object UNION extends TypeSystemDirectiveLocation
case object ENUM extends TypeSystemDirectiveLocation
case object ENUM_VALUE extends TypeSystemDirectiveLocation
case object INPUT_OBJECT extends TypeSystemDirectiveLocation
case object INPUT_FIELD_DEFINITION extends TypeSystemDirectiveLocation
}
lazy val typeSystemDirectiveLocation = {
import TypeSystemDirectiveLocation._
P.string("SCHEMA").as(SCHEMA) |
P.string("SCALAR").as(SCALAR) |
P.string("OBJECT").as(OBJECT) |
P.string("FIELD_DEFINITION").as(FIELD_DEFINITION) |
P.string("ARGUMENT_DEFINITION").as(ARGUMENT_DEFINITION) |
P.string("INTERFACE").as(INTERFACE) |
P.string("UNION").as(UNION) |
P.string("ENUM").as(ENUM) |
P.string("ENUM_VALUE").as(ENUM_VALUE) |
P.string("INPUT_OBJECT").as(INPUT_OBJECT) |
P.string("INPUT_FIELD_DEFINITION").as(INPUT_FIELD_DEFINITION)
}
lazy val intValue: P[BigInt] = w(integerPart)
lazy val integerPart = Numbers.bigInt
lazy val floatValue: P[BigDecimal] = w(Numbers.jsonNumber).map(BigDecimal(_))
lazy val stringValue: P[String] = w {
val d = P.char('"')
val tripple = d.rep(3, 3)
blockStringCharacter.map(_.toString()).rep.surroundedBy(P.backtrack(tripple)) |
stringCharacter.rep.surroundedBy(d)
}.map(_.mkString_(""))
lazy val stringCharacter: P[String] =
((!(P.charIn('"', '\\') | lineTerminator)).with1 *> sourceCharacter.map(_.toString())) |
(P.string("\\u").as("\\u") ~ escapedUnicode).map { case (x, y) =>
x + y
} |
(P.charIn('\\') ~ escapedCharacter).map { case (x, y) => x.toString() + y }
lazy val escapedUnicode: P[String] =
P.charIn(('0' to '9') :++ ('a' to 'f') :++ ('A' to 'F')).rep(4, 4).map(_.mkString_(""))
lazy val escapedCharacter: P[Char] =
P.charIn('"', '\\', '/', 'b', 'f', 'n', 'r', 't')
lazy val blockStringCharacter: P[Char] = {
val qs = P.string("\"\"\"")
(!(qs | (P.char('\\') *> qs))).with1 *> sourceCharacter
}
sealed trait Type
object Type {
final case class Named(name: String) extends Type
final case class List(of: Type) extends Type
final case class NonNull(of: Type) extends Type
}
lazy val `type`: P[Type] = {
import Type._
(P.defer(namedType | listType.map(List(_))) ~ t('!').?).map {
case (x, Some(_)) => NonNull(x)
case (x, None) => x
}
}
lazy val listType: P[Type] =
`type`.between(t('['), t(']'))
}