gqlparser 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gqlparser/parser.py ADDED
@@ -0,0 +1,581 @@
1
+ """GQL parser: tokens to a `Query` syntax tree, by recursive descent.
2
+
3
+ Constructs this release recognises but does not support raise
4
+ `GqlNotSupportedError` naming the construct. Anything else the parser cannot
5
+ read raises `GqlSyntaxError`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from gqlparser import ast
11
+ from gqlparser.ast import Span
12
+ from gqlparser.errors import GqlNotSupportedError
13
+ from gqlparser.errors import GqlSyntaxError
14
+ from gqlparser.lexer import Token
15
+ from gqlparser.lexer import TokenKind
16
+ from gqlparser.lexer import tokenize
17
+
18
+ # Words with a meaning inside expressions: never read as a variable or alias name.
19
+ _EXPRESSION_KEYWORDS = frozenset(
20
+ {"AND", "OR", "XOR", "NOT", "IS", "NULL", "TRUE", "FALSE", "UNKNOWN", "CASE", "WHEN",
21
+ "THEN", "ELSE", "END", "DISTINCT", "ALL", "AS", "EXISTS", "WHERE"}
22
+ ) # fmt: skip
23
+ _TEMPORAL_LITERAL_TYPES = frozenset({"DATE", "TIME", "DATETIME", "TIMESTAMP", "DURATION"})
24
+ _CURRENT_TEMPORAL = frozenset({"CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP"})
25
+ # GQL statements that may appear where this release expects MATCH or RETURN.
26
+ _STATEMENTS_NOT_SUPPORTED = frozenset(
27
+ {"LET", "FILTER", "FOR", "ORDER", "OFFSET", "SKIP", "LIMIT", "CALL", "OPTIONAL", "USE",
28
+ "SELECT", "INSERT", "SET", "REMOVE", "DELETE", "DETACH", "NODETACH", "CREATE", "DROP",
29
+ "SESSION", "START", "COMMIT", "ROLLBACK", "FINISH", "AT", "YIELD"}
30
+ ) # fmt: skip
31
+ _COMPOSITION_NOT_SUPPORTED = frozenset({"NEXT", "UNION", "EXCEPT", "INTERSECT", "OTHERWISE"})
32
+ _PATH_PREFIXES_NOT_SUPPORTED = frozenset(
33
+ {"ANY", "ALL", "SHORTEST", "WALK", "TRAIL", "SIMPLE", "ACYCLIC"}
34
+ )
35
+ _MATCH_MODES_NOT_SUPPORTED = frozenset({"DIFFERENT", "REPEATABLE"})
36
+ _COMPARISON_OPERATORS = frozenset({"=", "<>", "<", "<=", ">", ">="})
37
+ _QUANTIFIER_STARTS = frozenset({"{", "*", "+", "?"})
38
+ _NAME_KINDS = frozenset({TokenKind.WORD, TokenKind.ACCENT_QUOTED, TokenKind.DOUBLE_QUOTED})
39
+ # Each nested expression costs ~18 Python frames (one per precedence level), so refuse
40
+ # cleanly at 32 (~600 frames), leaving room under Python's default limit (1000) for the
41
+ # caller's own stack.
42
+ # shortcut: one function per precedence level caps nesting at 32; upgrade to precedence
43
+ # climbing (~3 frames per level) if real queries nest deeper.
44
+ _MAX_NESTING = 32
45
+
46
+
47
+ def parse(text: str) -> ast.Query:
48
+ """Parse one GQL query into a syntax tree."""
49
+ return _Parser(tokenize(text)).query()
50
+
51
+
52
+ def _found(token: Token) -> str:
53
+ kind = token.kind
54
+ if kind is TokenKind.END:
55
+ return "the end of the query"
56
+ if kind is TokenKind.SINGLE_QUOTED:
57
+ return f"'{token.value}'"
58
+ if kind is TokenKind.DOUBLE_QUOTED:
59
+ return f'"{token.value}"'
60
+ if kind is TokenKind.PARAMETER:
61
+ return f"`${token.value}`"
62
+ return f"`{token.value}`"
63
+
64
+
65
+ class _Parser:
66
+ __slots__ = ("tokens", "index", "previous_end", "depth")
67
+
68
+ def __init__(self, tokens: list[Token]):
69
+ self.tokens = tokens
70
+ self.index = 0
71
+ self.previous_end = 0
72
+ self.depth = 0
73
+
74
+ # --- token helpers ---------------------------------------------------------
75
+
76
+ def peek(self, offset: int = 0) -> Token:
77
+ return self.tokens[min(self.index + offset, len(self.tokens) - 1)]
78
+
79
+ def advance(self) -> Token:
80
+ token = self.tokens[self.index]
81
+ if token.kind is not TokenKind.END:
82
+ self.index += 1
83
+ self.previous_end = token.span.end
84
+ return token
85
+
86
+ def is_word(self, word: str, offset: int = 0) -> bool:
87
+ token = self.peek(offset)
88
+ return token.kind is TokenKind.WORD and token.value.upper() == word
89
+
90
+ def is_punct(self, punctuation: str, offset: int = 0) -> bool:
91
+ token = self.peek(offset)
92
+ return token.kind is TokenKind.PUNCTUATION and token.value == punctuation
93
+
94
+ def accept_word(self, word: str) -> Token | None:
95
+ return self.advance() if self.is_word(word) else None
96
+
97
+ def accept_punct(self, punctuation: str) -> Token | None:
98
+ return self.advance() if self.is_punct(punctuation) else None
99
+
100
+ def expect_word(self, word: str) -> Token:
101
+ if not self.is_word(word):
102
+ self.syntax(f"expected `{word}`, found {_found(self.peek())}")
103
+ return self.advance()
104
+
105
+ def expect_punct(self, punctuation: str, purpose: str = "") -> Token:
106
+ if not self.is_punct(punctuation):
107
+ self.syntax(f"expected `{punctuation}`{purpose}, found {_found(self.peek())}")
108
+ return self.advance()
109
+
110
+ def span_from(self, start: Span) -> Span:
111
+ return Span(start.start, self.previous_end, start.line, start.column)
112
+
113
+ def syntax(self, message: str, token: Token | None = None):
114
+ token = token or self.peek()
115
+ raise GqlSyntaxError(message, token.span.line, token.span.column)
116
+
117
+ def unsupported(self, message: str, token: Token | None = None):
118
+ token = token or self.peek()
119
+ raise GqlNotSupportedError(message, token.span.line, token.span.column)
120
+
121
+ def require_adjacent(self, first: Token, second: Token) -> None:
122
+ if first.span.end != second.span.start:
123
+ self.syntax(f"write `{first.value}{second.value}` without spaces", second)
124
+
125
+ # --- names -----------------------------------------------------------------
126
+
127
+ def name(self, what: str) -> ast.Identifier:
128
+ """A graph, label or property name: any word or delimited identifier."""
129
+ token = self.peek()
130
+ if token.kind not in _NAME_KINDS:
131
+ self.syntax(f"expected {what}, found {_found(token)}")
132
+ self.advance()
133
+ return ast.Identifier(token.value, token.span)
134
+
135
+ def binding_name(self, what: str) -> ast.Identifier:
136
+ """A variable or alias: a word that is not an expression keyword, or a delimited identifier."""
137
+ token = self.peek()
138
+ if token.kind is TokenKind.WORD and token.value.upper() in _EXPRESSION_KEYWORDS:
139
+ self.syntax(
140
+ f"`{token.value}` is a reserved word and cannot be {what}; "
141
+ f"quote it as `{token.value}` with accents (`` ` ``)"
142
+ )
143
+ return self.name(what)
144
+
145
+ # --- query -----------------------------------------------------------------
146
+
147
+ def query(self) -> ast.Query:
148
+ first = self.peek()
149
+ graph = None
150
+ if self.accept_word("USE"):
151
+ graph = self.name("a graph name")
152
+ if self.is_punct("."):
153
+ self.unsupported("qualified graph names are not supported yet")
154
+ statements = []
155
+ while not self.is_word("RETURN"):
156
+ if self.is_word("MATCH") or (self.is_word("OPTIONAL") and self.is_word("MATCH", 1)):
157
+ statements.append(self.match_statement())
158
+ else:
159
+ self.refuse_statement()
160
+ if not statements:
161
+ self.unsupported("queries without `MATCH` are not supported yet")
162
+ return_statement = self.return_statement()
163
+ token = self.peek()
164
+ if token.kind is not TokenKind.END:
165
+ if token.kind is TokenKind.WORD and token.value.upper() in _COMPOSITION_NOT_SUPPORTED:
166
+ self.unsupported(f"`{token.value.upper()}` (composite queries) is not supported yet")
167
+ self.syntax(f"expected the end of the query, found {_found(token)}")
168
+ return ast.Query(graph, tuple(statements), return_statement, self.span_from(first.span))
169
+
170
+ def refuse_statement(self):
171
+ token = self.peek()
172
+ if token.kind is TokenKind.WORD:
173
+ word = token.value.upper()
174
+ if word == "OPTIONAL":
175
+ if self.is_punct("{", 1) or self.is_punct("(", 1):
176
+ self.unsupported("`OPTIONAL` blocks are not supported yet; write `OPTIONAL MATCH`")
177
+ self.syntax(f"expected `MATCH` or `RETURN`, found {_found(token)}")
178
+ if word in _STATEMENTS_NOT_SUPPORTED:
179
+ self.unsupported(f"the `{word}` statement here is not supported yet")
180
+ self.syntax(f"expected `MATCH` or `RETURN`, found {_found(token)}")
181
+
182
+ # --- MATCH -----------------------------------------------------------------
183
+
184
+ def match_statement(self) -> ast.MatchStatement:
185
+ first = self.peek()
186
+ optional = self.accept_word("OPTIONAL") is not None
187
+ self.expect_word("MATCH")
188
+ token = self.peek()
189
+ if token.kind is TokenKind.WORD and token.value.upper() in _MATCH_MODES_NOT_SUPPORTED:
190
+ self.unsupported("match modes (`DIFFERENT EDGES`, `REPEATABLE ELEMENTS`) are not supported yet")
191
+ paths = [self.path_pattern()]
192
+ while self.accept_punct(","):
193
+ paths.append(self.path_pattern())
194
+ if self.is_word("KEEP"):
195
+ self.unsupported("`KEEP` is not supported yet")
196
+ where = self.expression() if self.accept_word("WHERE") else None
197
+ if self.is_word("YIELD"):
198
+ self.unsupported("`YIELD` is not supported yet")
199
+ return ast.MatchStatement(optional, tuple(paths), where, self.span_from(first.span))
200
+
201
+ def path_pattern(self) -> ast.PathPattern:
202
+ first = self.peek()
203
+ if first.kind in _NAME_KINDS and self.is_punct("=", 1):
204
+ self.unsupported("path variables (`p = ...`) are not supported yet")
205
+ if first.kind is TokenKind.WORD and first.value.upper() in _PATH_PREFIXES_NOT_SUPPORTED:
206
+ self.unsupported(f"path search prefixes and path modes (`{first.value.upper()}`) are not supported yet")
207
+ elements: list[ast.NodePattern | ast.EdgePattern] = [self.node_pattern()]
208
+ while (edge := self.edge_pattern_or_none()) is not None:
209
+ elements.append(edge)
210
+ elements.append(self.node_pattern())
211
+ return ast.PathPattern(tuple(elements), self.span_from(first.span))
212
+
213
+ def node_pattern(self) -> ast.NodePattern:
214
+ first = self.expect_punct("(", " to start a node pattern")
215
+ if self.is_punct("("):
216
+ self.unsupported("parenthesized path patterns are not supported yet")
217
+ variable, label, where = self.element_filler()
218
+ self.expect_punct(")", " to close the node pattern")
219
+ return ast.NodePattern(variable, label, where, self.span_from(first.span))
220
+
221
+ def element_filler(self):
222
+ """The inside of `( )` or `[ ]`: [variable] [:label] [WHERE expression]."""
223
+ variable = None
224
+ token = self.peek()
225
+ if token.kind in _NAME_KINDS and not (self.is_word("WHERE") or self.is_word("IS")):
226
+ variable = self.binding_name("a variable name")
227
+ if self.is_word("IS"):
228
+ self.unsupported("`IS` label expressions are not supported yet; write `:Label`")
229
+ label = None
230
+ if self.accept_punct(":"):
231
+ if self.is_punct("!") or self.is_punct("%") or self.is_punct("("):
232
+ self.unsupported("label expressions are not supported yet")
233
+ label = self.name("a label")
234
+ if self.is_punct("|") or self.is_punct("&"):
235
+ self.unsupported("label expressions are not supported yet")
236
+ if self.is_punct(":"):
237
+ self.unsupported("more than one label on an element is not supported yet")
238
+ if self.is_punct("{"):
239
+ self.unsupported("property specifications (`{key: value}`) are not supported yet")
240
+ where = self.expression() if self.accept_word("WHERE") else None
241
+ return variable, label, where
242
+
243
+ def edge_pattern_or_none(self) -> ast.EdgePattern | None:
244
+ first = self.peek()
245
+ if self.is_punct("-"):
246
+ if not self.is_punct("[", 1):
247
+ self.unsupported("abbreviated edge patterns (`-`) are not supported yet")
248
+ pointing_right = True
249
+ elif self.is_punct("<-"):
250
+ if not self.is_punct("[", 1):
251
+ self.unsupported("abbreviated edge patterns (`<-`, `<->`) are not supported yet")
252
+ pointing_right = False
253
+ elif self.is_punct("->"):
254
+ self.unsupported("abbreviated edge patterns (`->`) are not supported yet")
255
+ elif self.is_punct("~") or (self.is_punct("<") and self.is_punct("~", 1)):
256
+ self.unsupported("undirected edge patterns (`~`) are not supported yet")
257
+ else:
258
+ return None
259
+ self.require_adjacent(first, self.peek(1))
260
+ self.advance()
261
+ self.advance()
262
+ variable, label, where = self.element_filler()
263
+ close = self.expect_punct("]", " to close the edge pattern")
264
+ arrow = self.peek()
265
+ if pointing_right:
266
+ if self.is_punct("-"):
267
+ self.unsupported("edges in any direction (`-[...]-`) are not supported yet")
268
+ if not self.is_punct("->"):
269
+ self.syntax(f"expected `]->` to close the edge pattern, found {_found(arrow)}")
270
+ direction = ast.EdgeDirection.POINTING_RIGHT
271
+ else:
272
+ if self.is_punct("->"):
273
+ self.unsupported("edges pointing left or right (`<-[...]->`) are not supported yet")
274
+ if not self.is_punct("-"):
275
+ self.syntax(f"expected `]-` to close the edge pattern, found {_found(arrow)}")
276
+ direction = ast.EdgeDirection.POINTING_LEFT
277
+ self.require_adjacent(close, arrow)
278
+ self.advance()
279
+ following = self.peek()
280
+ if following.kind is TokenKind.PUNCTUATION and following.value in _QUANTIFIER_STARTS:
281
+ self.unsupported("quantified paths are not supported yet")
282
+ return ast.EdgePattern(variable, label, where, direction, self.span_from(first.span))
283
+
284
+ # --- RETURN ----------------------------------------------------------------
285
+
286
+ def return_statement(self) -> ast.ReturnStatement:
287
+ first = self.expect_word("RETURN")
288
+ distinct = self.accept_word("DISTINCT") is not None
289
+ if not distinct:
290
+ self.accept_word("ALL") # ALL is the default
291
+ if self.is_punct("*"):
292
+ self.unsupported("`RETURN *` is not supported yet")
293
+ items = [self.return_item()]
294
+ while self.accept_punct(","):
295
+ items.append(self.return_item())
296
+
297
+ group_by = []
298
+ if self.accept_word("GROUP"):
299
+ self.expect_word("BY")
300
+ if self.is_punct("("):
301
+ self.unsupported("the empty grouping set `GROUP BY ()` is not supported yet")
302
+ group_by.append(self.binding_name("a grouping name"))
303
+ while self.accept_punct(","):
304
+ group_by.append(self.binding_name("a grouping name"))
305
+
306
+ order_by = []
307
+ if self.accept_word("ORDER"):
308
+ self.expect_word("BY")
309
+ order_by.append(self.sort_specification())
310
+ while self.accept_punct(","):
311
+ order_by.append(self.sort_specification())
312
+
313
+ offset = limit = None
314
+ if self.accept_word("OFFSET") or self.accept_word("SKIP"):
315
+ offset = self.count()
316
+ if self.accept_word("LIMIT"):
317
+ limit = self.count()
318
+ if self.is_word("OFFSET") or self.is_word("SKIP"):
319
+ self.unsupported("`OFFSET` after `LIMIT` is not supported yet")
320
+
321
+ return ast.ReturnStatement(
322
+ distinct,
323
+ tuple(items),
324
+ tuple(group_by),
325
+ tuple(order_by),
326
+ offset,
327
+ limit,
328
+ self.span_from(first.span),
329
+ )
330
+
331
+ def return_item(self) -> ast.ReturnItem:
332
+ first = self.peek()
333
+ expression = self.expression()
334
+ alias = self.binding_name("an alias") if self.accept_word("AS") else None
335
+ return ast.ReturnItem(expression, alias, self.span_from(first.span))
336
+
337
+ def sort_specification(self) -> ast.SortSpecification:
338
+ first = self.peek()
339
+ expression = self.expression()
340
+ descending = False
341
+ if self.accept_word("DESC") or self.accept_word("DESCENDING"):
342
+ descending = True
343
+ else:
344
+ self.accept_word("ASC") or self.accept_word("ASCENDING")
345
+ if self.is_word("NULLS"):
346
+ self.unsupported("`NULLS FIRST` / `NULLS LAST` is not supported yet")
347
+ return ast.SortSpecification(expression, descending, self.span_from(first.span))
348
+
349
+ def count(self) -> ast.IntegerLiteral | ast.Parameter:
350
+ token = self.peek()
351
+ if token.kind is TokenKind.INTEGER:
352
+ self.advance()
353
+ return ast.IntegerLiteral(token.value, token.span)
354
+ if token.kind is TokenKind.PARAMETER:
355
+ self.advance()
356
+ return ast.Parameter(token.value, token.span)
357
+ self.syntax(f"expected a whole number or a parameter, found {_found(token)}")
358
+
359
+ # --- expressions, lowest precedence first ----------------------------------
360
+
361
+ def nest(self) -> None:
362
+ """Count one level of expression nesting; the caller decrements on the way out."""
363
+ self.depth += 1
364
+ if self.depth > _MAX_NESTING:
365
+ self.unsupported(
366
+ f"expressions nested more than {_MAX_NESTING} deep are not supported yet"
367
+ )
368
+
369
+ def expression(self) -> ast.Expression:
370
+ self.nest()
371
+ result = self.disjunction()
372
+ self.depth -= 1
373
+ return result
374
+
375
+ def binary_level(self, words: tuple[str, ...], operand) -> ast.Expression:
376
+ left = operand()
377
+ while True:
378
+ word = next((w for w in words if self.is_word(w)), None)
379
+ if word is None:
380
+ return left
381
+ self.advance()
382
+ right = operand()
383
+ left = ast.BinaryOperation(word, left, right, self.span_from(left.span))
384
+
385
+ def disjunction(self) -> ast.Expression:
386
+ return self.binary_level(("OR",), self.exclusive_disjunction)
387
+
388
+ def exclusive_disjunction(self) -> ast.Expression:
389
+ return self.binary_level(("XOR",), self.conjunction)
390
+
391
+ def conjunction(self) -> ast.Expression:
392
+ return self.binary_level(("AND",), self.negation)
393
+
394
+ def negation(self) -> ast.Expression:
395
+ first = self.accept_word("NOT")
396
+ if first is None:
397
+ return self.comparison()
398
+ self.nest()
399
+ operand = self.negation()
400
+ self.depth -= 1
401
+ return ast.UnaryOperation("NOT", operand, self.span_from(first.span))
402
+
403
+ def comparison(self) -> ast.Expression:
404
+ left = self.concatenation()
405
+ if self.is_word("IS"):
406
+ return self.is_predicate(left)
407
+ if self.is_punct("!") and self.is_punct("=", 1):
408
+ self.unsupported("`!=` is not supported yet; write `<>`")
409
+ operator = self.peek()
410
+ if operator.kind is not TokenKind.PUNCTUATION or operator.value not in _COMPARISON_OPERATORS:
411
+ return left
412
+ self.advance()
413
+ right = self.concatenation()
414
+ following = self.peek()
415
+ if self.is_word("IS") or (
416
+ following.kind is TokenKind.PUNCTUATION and following.value in _COMPARISON_OPERATORS
417
+ ):
418
+ self.unsupported("chained comparisons are not supported yet; add parentheses")
419
+ return ast.BinaryOperation(operator.value, left, right, self.span_from(left.span))
420
+
421
+ def is_predicate(self, operand: ast.Expression) -> ast.Expression:
422
+ self.advance() # IS
423
+ negated = self.accept_word("NOT") is not None
424
+ if self.accept_word("NULL"):
425
+ return ast.IsNull(operand, negated, self.span_from(operand.span))
426
+ token = self.peek()
427
+ if token.kind is TokenKind.WORD:
428
+ not_ = "NOT " if negated else ""
429
+ self.unsupported(f"`IS {not_}{token.value.upper()}` is not supported yet")
430
+ self.syntax(f"expected `NULL` after `IS`, found {_found(token)}")
431
+
432
+ def concatenation(self) -> ast.Expression:
433
+ return self.punct_level(("||",), self.additive)
434
+
435
+ def additive(self) -> ast.Expression:
436
+ return self.punct_level(("+", "-"), self.multiplicative)
437
+
438
+ def multiplicative(self) -> ast.Expression:
439
+ return self.punct_level(("*", "/", "%"), self.unary)
440
+
441
+ def punct_level(self, operators: tuple[str, ...], operand) -> ast.Expression:
442
+ left = operand()
443
+ while True:
444
+ token = self.peek()
445
+ if token.kind is not TokenKind.PUNCTUATION or token.value not in operators:
446
+ return left
447
+ self.advance()
448
+ right = operand()
449
+ left = ast.BinaryOperation(token.value, left, right, self.span_from(left.span))
450
+
451
+ def unary(self) -> ast.Expression:
452
+ token = self.peek()
453
+ if token.kind is TokenKind.PUNCTUATION and token.value in ("-", "+"):
454
+ self.advance()
455
+ self.nest()
456
+ operand = self.unary()
457
+ self.depth -= 1
458
+ return ast.UnaryOperation(token.value, operand, self.span_from(token.span))
459
+ return self.property_access()
460
+
461
+ def property_access(self) -> ast.Expression:
462
+ subject = self.primary()
463
+ while self.accept_punct("."):
464
+ prop = self.name("a property name")
465
+ subject = ast.PropertyReference(subject, prop, self.span_from(subject.span))
466
+ return subject
467
+
468
+ def primary(self) -> ast.Expression:
469
+ token = self.peek()
470
+ kind = token.kind
471
+ if kind is TokenKind.INTEGER:
472
+ self.advance()
473
+ return ast.IntegerLiteral(token.value, token.span)
474
+ if kind is TokenKind.EXACT_NUMBER:
475
+ self.advance()
476
+ return ast.ExactNumberLiteral(token.value, token.span)
477
+ if kind is TokenKind.APPROXIMATE_NUMBER:
478
+ self.advance()
479
+ return ast.ApproximateNumberLiteral(token.value, token.span)
480
+ if kind is TokenKind.SINGLE_QUOTED:
481
+ self.advance()
482
+ return ast.StringLiteral(token.value, token.span)
483
+ if kind is TokenKind.DOUBLE_QUOTED:
484
+ self.unsupported(
485
+ "double-quoted text in an expression is not supported yet, because it can be "
486
+ "a string or a name; write '...' for a string or `...` for a name"
487
+ )
488
+ if kind is TokenKind.ACCENT_QUOTED:
489
+ self.advance()
490
+ return ast.Variable(token.value, token.span)
491
+ if kind is TokenKind.PARAMETER:
492
+ self.advance()
493
+ return ast.Parameter(token.value, token.span)
494
+ if self.is_punct("("):
495
+ self.advance()
496
+ inner = self.expression()
497
+ self.expect_punct(")", " to close the parenthesis")
498
+ return inner
499
+ if self.is_punct("["):
500
+ self.unsupported("list literals are not supported yet")
501
+ if self.is_punct("{"):
502
+ self.unsupported("record literals are not supported yet")
503
+ if kind is TokenKind.WORD:
504
+ return self.word_primary(token)
505
+ self.syntax(f"expected an expression, found {_found(token)}")
506
+
507
+ def word_primary(self, token: Token) -> ast.Expression:
508
+ word = token.value.upper()
509
+ if word in ("TRUE", "FALSE"):
510
+ self.advance()
511
+ return ast.BooleanLiteral(word == "TRUE", token.span)
512
+ if word == "NULL":
513
+ self.advance()
514
+ return ast.NullLiteral(token.span)
515
+ if word == "UNKNOWN":
516
+ self.unsupported("the `UNKNOWN` literal is not supported yet")
517
+ if word == "EXISTS":
518
+ self.unsupported("`EXISTS` is not supported yet")
519
+ if word == "CASE":
520
+ return self.case()
521
+ if word in _TEMPORAL_LITERAL_TYPES and self.peek(1).kind is TokenKind.SINGLE_QUOTED:
522
+ self.advance()
523
+ value = self.advance()
524
+ return ast.TemporalLiteral(word, value.value, self.span_from(token.span))
525
+ if word in _EXPRESSION_KEYWORDS:
526
+ self.syntax(f"expected an expression, found {_found(token)}")
527
+ if self.is_punct("(", 1):
528
+ return self.function_call()
529
+ if word in _CURRENT_TEMPORAL:
530
+ self.advance()
531
+ return ast.CurrentTemporal(word, token.span)
532
+ if word in _TEMPORAL_LITERAL_TYPES:
533
+ self.syntax(f"expected a quoted value after `{word}`, found {_found(self.peek(1))}")
534
+ self.advance()
535
+ return ast.Variable(token.value, token.span)
536
+
537
+ def function_call(self) -> ast.Expression:
538
+ name = self.advance()
539
+ self.advance() # (
540
+ if name.value.upper() == "COUNT" and self.is_punct("*"):
541
+ self.advance()
542
+ self.expect_punct(")", " to close `COUNT(*)`")
543
+ return ast.CountStar(self.span_from(name.span))
544
+ distinct = self.accept_word("DISTINCT") is not None
545
+ if not distinct:
546
+ self.accept_word("ALL") # ALL is the default
547
+ arguments = []
548
+ if not self.is_punct(")"):
549
+ arguments.append(self.expression())
550
+ while self.accept_punct(","):
551
+ arguments.append(self.expression())
552
+ elif distinct:
553
+ self.syntax("`DISTINCT` needs an argument")
554
+ self.expect_punct(")", f" to close the call to `{name.value}`")
555
+ return ast.FunctionCall(name.value, tuple(arguments), distinct, self.span_from(name.span))
556
+
557
+ def case(self) -> ast.Case:
558
+ first = self.advance() # CASE
559
+ if self.is_word("END"):
560
+ self.syntax("expected `WHEN`, found `END`")
561
+ operand = None if self.is_word("WHEN") else self.expression()
562
+ when_clauses = []
563
+ while self.is_word("WHEN"):
564
+ when = self.advance()
565
+ following = self.peek()
566
+ if operand is not None and (
567
+ self.is_word("IS")
568
+ or (following.kind is TokenKind.PUNCTUATION and following.value in _COMPARISON_OPERATORS)
569
+ ):
570
+ self.unsupported("comparisons in a simple `CASE` `WHEN` are not supported yet")
571
+ condition = self.expression()
572
+ if operand is not None and self.is_punct(","):
573
+ self.unsupported("several values in one `WHEN` are not supported yet")
574
+ self.expect_word("THEN")
575
+ result = self.expression()
576
+ when_clauses.append(ast.WhenClause(condition, result, self.span_from(when.span)))
577
+ if not when_clauses:
578
+ self.syntax(f"expected `WHEN`, found {_found(self.peek())}")
579
+ else_result = self.expression() if self.accept_word("ELSE") else None
580
+ self.expect_word("END")
581
+ return ast.Case(operand, tuple(when_clauses), else_result, self.span_from(first.span))
gqlparser/py.typed ADDED
File without changes