cypher2sql 0.1.0__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.
- cypher2sql/__init__.py +36 -0
- cypher2sql/_ast.py +426 -0
- cypher2sql/_bind/__init__.py +46 -0
- cypher2sql/_bind/_base.py +437 -0
- cypher2sql/_bind/_binder.py +387 -0
- cypher2sql/_bind/_build.py +701 -0
- cypher2sql/_bind/_edges.py +354 -0
- cypher2sql/_bind/_names.py +72 -0
- cypher2sql/_bind/_patterns.py +633 -0
- cypher2sql/_bind/_predicates.py +560 -0
- cypher2sql/_bind/_values.py +664 -0
- cypher2sql/_compare.py +265 -0
- cypher2sql/_emit/__init__.py +42 -0
- cypher2sql/_emit/_core.py +362 -0
- cypher2sql/_emit/_walks.py +622 -0
- cypher2sql/_errors.py +396 -0
- cypher2sql/_infer.py +287 -0
- cypher2sql/_ir.py +663 -0
- cypher2sql/_lexer.py +557 -0
- cypher2sql/_limits.py +79 -0
- cypher2sql/_parser/__init__.py +90 -0
- cypher2sql/_parser/_base.py +234 -0
- cypher2sql/_parser/_clauses.py +404 -0
- cypher2sql/_parser/_grammar.py +680 -0
- cypher2sql/_plan/__init__.py +143 -0
- cypher2sql/_plan/_groups.py +282 -0
- cypher2sql/_plan/_nodes.py +562 -0
- cypher2sql/_plan/_planner.py +794 -0
- cypher2sql/_plan/_rows.py +803 -0
- cypher2sql/_plan/_scopes.py +104 -0
- cypher2sql/_plan/_uniqueness.py +84 -0
- cypher2sql/_plan/_working.py +99 -0
- cypher2sql/_schema.py +519 -0
- cypher2sql/_template.py +61 -0
- cypher2sql/_unsupported.py +170 -0
- cypher2sql/py.typed +0 -0
- cypher2sql-0.1.0.dist-info/METADATA +95 -0
- cypher2sql-0.1.0.dist-info/RECORD +40 -0
- cypher2sql-0.1.0.dist-info/WHEEL +4 -0
- cypher2sql-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,680 @@
|
|
|
1
|
+
"""Pattern elements, expressions and the pattern predicates an `EXISTS` body asks.
|
|
2
|
+
|
|
3
|
+
The grammar is one recursive cycle — a pattern's property map holds expressions, an expression may
|
|
4
|
+
be a pattern predicate or an `EXISTS` body, and that body holds patterns again — so these methods
|
|
5
|
+
stay in one class on top of `_base`; only the clauses above them add anything. A path is parsed
|
|
6
|
+
element by element and an expression by fixed precedence levels, and every construct this compiler
|
|
7
|
+
does not compile is refused here, by name, before the binder ever sees it.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
from typing import cast
|
|
14
|
+
|
|
15
|
+
from cypher2sql._ast import (
|
|
16
|
+
And,
|
|
17
|
+
Cmp,
|
|
18
|
+
Direction,
|
|
19
|
+
ExistsMatch,
|
|
20
|
+
ExistsSubquery,
|
|
21
|
+
Expr,
|
|
22
|
+
HasLabel,
|
|
23
|
+
In,
|
|
24
|
+
IsNull,
|
|
25
|
+
LabelRef,
|
|
26
|
+
Length,
|
|
27
|
+
ListLit,
|
|
28
|
+
Lit,
|
|
29
|
+
Name,
|
|
30
|
+
NodePat,
|
|
31
|
+
Not,
|
|
32
|
+
Or,
|
|
33
|
+
Param,
|
|
34
|
+
Path,
|
|
35
|
+
PatternPredicate,
|
|
36
|
+
Prop,
|
|
37
|
+
PropEntry,
|
|
38
|
+
Regex,
|
|
39
|
+
RelPat,
|
|
40
|
+
StringOp,
|
|
41
|
+
StringPredicate,
|
|
42
|
+
Var,
|
|
43
|
+
Where,
|
|
44
|
+
Xor,
|
|
45
|
+
)
|
|
46
|
+
from cypher2sql._errors import (
|
|
47
|
+
CypherSyntaxError,
|
|
48
|
+
UnsupportedCypherError,
|
|
49
|
+
bounded_text,
|
|
50
|
+
)
|
|
51
|
+
from cypher2sql._lexer import (
|
|
52
|
+
Token,
|
|
53
|
+
TokenKind,
|
|
54
|
+
describe,
|
|
55
|
+
)
|
|
56
|
+
from cypher2sql._unsupported import hint_for
|
|
57
|
+
|
|
58
|
+
from ._base import (
|
|
59
|
+
_ARITHMETIC,
|
|
60
|
+
_COMPARISONS,
|
|
61
|
+
_EXISTS_RETURN_HINT,
|
|
62
|
+
_EXISTS_RETURN_LAST_HINT,
|
|
63
|
+
_INT64_MAX,
|
|
64
|
+
_INT64_MIN,
|
|
65
|
+
_LITERAL_KEYWORDS,
|
|
66
|
+
_OPERATOR_KEYWORDS,
|
|
67
|
+
_UNSUPPORTED_CLAUSES,
|
|
68
|
+
_ParserBase,
|
|
69
|
+
_token_name,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class _Grammar(_ParserBase):
|
|
74
|
+
"""The pattern, expression and `EXISTS` grammar; one class, because it is one cycle."""
|
|
75
|
+
|
|
76
|
+
# ---------------------------------------------------------------- patterns
|
|
77
|
+
|
|
78
|
+
def _paths(self) -> list[Path]:
|
|
79
|
+
paths = [self._path()]
|
|
80
|
+
while self._peek().kind is TokenKind.COMMA:
|
|
81
|
+
self._advance()
|
|
82
|
+
paths.append(self._path())
|
|
83
|
+
return paths
|
|
84
|
+
|
|
85
|
+
def _path(self) -> Path:
|
|
86
|
+
elements: list[NodePat | RelPat] = [self._node_pattern()]
|
|
87
|
+
while self._peek().kind in (TokenKind.MINUS, TokenKind.LT):
|
|
88
|
+
elements.append(self._relationship())
|
|
89
|
+
elements.append(self._node_pattern())
|
|
90
|
+
return Path(tuple(elements), (elements[0].span[0], elements[-1].span[1]))
|
|
91
|
+
|
|
92
|
+
def _relationship(self) -> RelPat:
|
|
93
|
+
"""`--`, `-->`, `<--`, `-[...]-`, `-[...]->`, `<-...]-` or a bounded `*a..b` length."""
|
|
94
|
+
opening = self._peek()
|
|
95
|
+
left = opening.kind is TokenKind.LT
|
|
96
|
+
if left:
|
|
97
|
+
self._advance()
|
|
98
|
+
self._expect(TokenKind.MINUS)
|
|
99
|
+
else:
|
|
100
|
+
self._expect(TokenKind.MINUS)
|
|
101
|
+
var: Name | None = None
|
|
102
|
+
types: tuple[LabelRef, ...] = ()
|
|
103
|
+
length: Length | None = None
|
|
104
|
+
props: tuple[PropEntry, ...] = ()
|
|
105
|
+
if self._peek().kind is TokenKind.LBRACKET:
|
|
106
|
+
self._advance()
|
|
107
|
+
if self._peek().kind is TokenKind.INTERPOLATION:
|
|
108
|
+
raise self._interpolation_in_name(self._peek())
|
|
109
|
+
if self._peek().kind in (TokenKind.IDENT, TokenKind.KEYWORD):
|
|
110
|
+
var = self._name("a relationship variable")
|
|
111
|
+
if self._peek().kind is TokenKind.COLON:
|
|
112
|
+
self._advance()
|
|
113
|
+
types = (self._label_ref("a relationship type"),)
|
|
114
|
+
if self._peek().kind is TokenKind.PIPE:
|
|
115
|
+
raise self._unsupported(self._peek(), "a relationship with several types")
|
|
116
|
+
if self._peek().kind is TokenKind.STAR:
|
|
117
|
+
length = self._length()
|
|
118
|
+
if self._peek().kind is TokenKind.LBRACE:
|
|
119
|
+
props = self._property_map()
|
|
120
|
+
self._expect(TokenKind.RBRACKET)
|
|
121
|
+
self._expect(TokenKind.MINUS)
|
|
122
|
+
else:
|
|
123
|
+
self._expect(TokenKind.MINUS)
|
|
124
|
+
right = False
|
|
125
|
+
if self._peek().kind is TokenKind.GT:
|
|
126
|
+
self._advance()
|
|
127
|
+
right = True
|
|
128
|
+
if left and right:
|
|
129
|
+
raise self._syntax(
|
|
130
|
+
"a relationship cannot point both ways", (opening.span[0], opening.span[1])
|
|
131
|
+
)
|
|
132
|
+
if left:
|
|
133
|
+
direction = Direction.IN
|
|
134
|
+
elif right:
|
|
135
|
+
direction = Direction.OUT
|
|
136
|
+
else:
|
|
137
|
+
direction = Direction.BOTH
|
|
138
|
+
return RelPat(
|
|
139
|
+
var, types, direction, length, props, (opening.span[0], self._previous().span[1])
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
def _length(self) -> Length:
|
|
143
|
+
"""`*`, `*a`, `*a..b`, `*..b`, `*a..`, parsed into two hop bounds.
|
|
144
|
+
|
|
145
|
+
A bound is structure, never a value: it must be integer text, so a `$param` or an
|
|
146
|
+
interpolation here is a syntax error, and an integer outside int64 is refused by name.
|
|
147
|
+
"""
|
|
148
|
+
star = self._advance()
|
|
149
|
+
minimum = 1
|
|
150
|
+
maximum: int | None = None
|
|
151
|
+
last = star
|
|
152
|
+
if self._peek().kind is TokenKind.INTEGER:
|
|
153
|
+
token = self._advance()
|
|
154
|
+
minimum = self._length_int(token)
|
|
155
|
+
maximum = minimum
|
|
156
|
+
last = token
|
|
157
|
+
else:
|
|
158
|
+
self._reject_length_token()
|
|
159
|
+
if self._peek().kind is TokenKind.DOT and self._peek(1).kind is TokenKind.DOT:
|
|
160
|
+
self._advance()
|
|
161
|
+
last = self._advance()
|
|
162
|
+
maximum = None
|
|
163
|
+
if self._peek().kind is TokenKind.INTEGER:
|
|
164
|
+
token = self._advance()
|
|
165
|
+
maximum = self._length_int(token)
|
|
166
|
+
last = token
|
|
167
|
+
else:
|
|
168
|
+
self._reject_length_token()
|
|
169
|
+
return Length(minimum, maximum, (star.span[0], last.span[1]))
|
|
170
|
+
|
|
171
|
+
def _reject_length_token(self) -> None:
|
|
172
|
+
"""Whatever is not an integer bound is a syntax error with its own reason."""
|
|
173
|
+
token = self._peek()
|
|
174
|
+
if token.kind in (TokenKind.PARAM, TokenKind.INTERPOLATION):
|
|
175
|
+
raise self._syntax(
|
|
176
|
+
"a path length must be written as a number; a $parameter cannot supply it",
|
|
177
|
+
token.span,
|
|
178
|
+
)
|
|
179
|
+
if token.kind is TokenKind.MINUS:
|
|
180
|
+
raise self._syntax("a path length must be a non-negative integer", token.span)
|
|
181
|
+
if token.kind is TokenKind.FLOAT:
|
|
182
|
+
raise self._syntax("a path length must be an integer", token.span)
|
|
183
|
+
|
|
184
|
+
def _length_int(self, token: Token) -> int:
|
|
185
|
+
"""A hop bound is a real int64; an out-of-range literal is named, never echoed whole."""
|
|
186
|
+
value = cast(int, token.value)
|
|
187
|
+
if not 0 <= value <= _INT64_MAX:
|
|
188
|
+
raise self._syntax(
|
|
189
|
+
f"path length {bounded_text(token.text)} is out of range", token.span
|
|
190
|
+
)
|
|
191
|
+
return value
|
|
192
|
+
|
|
193
|
+
def _previous(self) -> Token:
|
|
194
|
+
return self._tokens[self._index - 1]
|
|
195
|
+
|
|
196
|
+
def _node_pattern(self) -> NodePat:
|
|
197
|
+
opening = self._expect(TokenKind.LPAREN)
|
|
198
|
+
if self._peek().kind is TokenKind.INTERPOLATION:
|
|
199
|
+
raise self._interpolation_in_name(self._peek())
|
|
200
|
+
var = (
|
|
201
|
+
self._name("a variable")
|
|
202
|
+
if self._peek().kind
|
|
203
|
+
in (
|
|
204
|
+
TokenKind.IDENT,
|
|
205
|
+
TokenKind.KEYWORD,
|
|
206
|
+
)
|
|
207
|
+
else None
|
|
208
|
+
)
|
|
209
|
+
labels: list[LabelRef] = []
|
|
210
|
+
while self._peek().kind is TokenKind.COLON:
|
|
211
|
+
self._advance()
|
|
212
|
+
labels.append(self._label_ref("a label"))
|
|
213
|
+
props = self._property_map() if self._peek().kind is TokenKind.LBRACE else ()
|
|
214
|
+
closing = self._expect(TokenKind.RPAREN)
|
|
215
|
+
return NodePat(var, tuple(labels), props, (opening.span[0], closing.span[1]))
|
|
216
|
+
|
|
217
|
+
def _property_map(self) -> tuple[PropEntry, ...]:
|
|
218
|
+
self._expect(TokenKind.LBRACE)
|
|
219
|
+
entries: list[PropEntry] = []
|
|
220
|
+
while self._peek().kind is not TokenKind.RBRACE:
|
|
221
|
+
key = self._name("a property name")
|
|
222
|
+
self._expect(TokenKind.COLON)
|
|
223
|
+
value = self._expression()
|
|
224
|
+
entries.append(PropEntry(key, value, (key.span[0], value.span[1])))
|
|
225
|
+
if self._peek().kind is not TokenKind.COMMA:
|
|
226
|
+
break
|
|
227
|
+
self._advance()
|
|
228
|
+
if self._peek().kind is TokenKind.RBRACE:
|
|
229
|
+
raise self._syntax(
|
|
230
|
+
f"expected a property name, found {describe(self._peek())}",
|
|
231
|
+
self._peek().span,
|
|
232
|
+
)
|
|
233
|
+
self._expect(TokenKind.RBRACE)
|
|
234
|
+
return tuple(entries)
|
|
235
|
+
|
|
236
|
+
# ---------------------------------------------------------------- expressions
|
|
237
|
+
|
|
238
|
+
def _expression(self) -> Expr:
|
|
239
|
+
return self._or_expression()
|
|
240
|
+
|
|
241
|
+
def _or_expression(self) -> Expr:
|
|
242
|
+
items = [self._xor_expression()]
|
|
243
|
+
while self._at_keyword("OR"):
|
|
244
|
+
self._advance()
|
|
245
|
+
items.append(self._xor_expression())
|
|
246
|
+
if len(items) == 1:
|
|
247
|
+
return items[0]
|
|
248
|
+
return Or(tuple(items), (items[0].span[0], items[-1].span[1]))
|
|
249
|
+
|
|
250
|
+
def _xor_expression(self) -> Expr:
|
|
251
|
+
items = [self._and_expression()]
|
|
252
|
+
while self._at_keyword("XOR"):
|
|
253
|
+
self._advance()
|
|
254
|
+
items.append(self._and_expression())
|
|
255
|
+
if len(items) == 1:
|
|
256
|
+
return items[0]
|
|
257
|
+
return Xor(tuple(items), (items[0].span[0], items[-1].span[1]))
|
|
258
|
+
|
|
259
|
+
def _and_expression(self) -> Expr:
|
|
260
|
+
items = [self._not_expression()]
|
|
261
|
+
while self._at_keyword("AND"):
|
|
262
|
+
self._advance()
|
|
263
|
+
items.append(self._not_expression())
|
|
264
|
+
if len(items) == 1:
|
|
265
|
+
return items[0]
|
|
266
|
+
return And(tuple(items), (items[0].span[0], items[-1].span[1]))
|
|
267
|
+
|
|
268
|
+
def _not_expression(self) -> Expr:
|
|
269
|
+
if self._at_keyword("NOT"):
|
|
270
|
+
token = self._advance()
|
|
271
|
+
with self._nested(token.span):
|
|
272
|
+
operand = self._not_expression()
|
|
273
|
+
return Not(operand, (token.span[0], operand.span[1]))
|
|
274
|
+
return self._comparison()
|
|
275
|
+
|
|
276
|
+
def _comparison(self) -> Expr:
|
|
277
|
+
left = self._primary()
|
|
278
|
+
if self._peek().kind in _ARITHMETIC:
|
|
279
|
+
raise self._unsupported(self._peek(), "arithmetic")
|
|
280
|
+
matched = self._predicate_tail(left)
|
|
281
|
+
if matched is not left:
|
|
282
|
+
left = matched
|
|
283
|
+
else:
|
|
284
|
+
op = _COMPARISONS.get(self._peek().kind)
|
|
285
|
+
if op is not None:
|
|
286
|
+
operator = self._advance()
|
|
287
|
+
right = self._primary()
|
|
288
|
+
left = Cmp(op, left, right, operator.span, (left.span[0], right.span[1]))
|
|
289
|
+
elif isinstance(left, Var) and self._peek().kind is TokenKind.COLON:
|
|
290
|
+
self._advance()
|
|
291
|
+
label = self._name("a label")
|
|
292
|
+
left = HasLabel(left, label, (left.span[0], label.span[1]))
|
|
293
|
+
if self._at_keyword("IS"):
|
|
294
|
+
self._advance()
|
|
295
|
+
negated = False
|
|
296
|
+
if self._at_keyword("NOT"):
|
|
297
|
+
self._advance()
|
|
298
|
+
negated = True
|
|
299
|
+
closing = self._expect_keyword("NULL")
|
|
300
|
+
return IsNull(left, negated, (left.span[0], closing.span[1]))
|
|
301
|
+
return left
|
|
302
|
+
|
|
303
|
+
def _predicate_tail(self, left: Expr) -> Expr:
|
|
304
|
+
"""The infix predicates that may follow one operand: `IN`, the three string ones, `=~`.
|
|
305
|
+
|
|
306
|
+
Cypher binds them tighter than `=`; this compiler accepts one of them per operand, which
|
|
307
|
+
is every shape a key set filters with, and never chains two into one condition.
|
|
308
|
+
"""
|
|
309
|
+
if self._at_keyword("IN"):
|
|
310
|
+
return self._in(left)
|
|
311
|
+
if self._at_keyword("STARTS", "ENDS", "CONTAINS"):
|
|
312
|
+
return self._string_predicate(left)
|
|
313
|
+
if self._peek().kind is TokenKind.REGEX:
|
|
314
|
+
operator = self._advance()
|
|
315
|
+
pattern = self._primary()
|
|
316
|
+
return Regex(left, pattern, operator.span, (left.span[0], pattern.span[1]))
|
|
317
|
+
return left
|
|
318
|
+
|
|
319
|
+
def _in(self, left: Expr) -> In:
|
|
320
|
+
"""`left IN [items]` or `left IN $parameter`; the list itself is always one token."""
|
|
321
|
+
operator = self._advance()
|
|
322
|
+
token = self._peek()
|
|
323
|
+
if token.kind is TokenKind.LBRACKET:
|
|
324
|
+
items: ListLit | Param = self._list_literal()
|
|
325
|
+
elif token.kind in (TokenKind.PARAM, TokenKind.INTERPOLATION):
|
|
326
|
+
self._advance()
|
|
327
|
+
items = Param(cast(str, token.value), token.span)
|
|
328
|
+
else:
|
|
329
|
+
raise self._syntax(
|
|
330
|
+
f"expected a list literal or a $parameter after IN, found {describe(token)}",
|
|
331
|
+
token.span,
|
|
332
|
+
)
|
|
333
|
+
return In(left, items, operator.span, (left.span[0], items.span[1]))
|
|
334
|
+
|
|
335
|
+
def _list_literal(self) -> ListLit:
|
|
336
|
+
"""`[item, ...]`, possibly empty; each item is an expression this compiler can bind."""
|
|
337
|
+
opening = self._expect(TokenKind.LBRACKET)
|
|
338
|
+
if self._list_is_comprehension():
|
|
339
|
+
raise UnsupportedCypherError(
|
|
340
|
+
"a list or pattern comprehension is not supported yet",
|
|
341
|
+
query=self._query,
|
|
342
|
+
span=opening.span,
|
|
343
|
+
hint=hint_for("comprehension"),
|
|
344
|
+
)
|
|
345
|
+
items: list[Expr] = []
|
|
346
|
+
with self._nested(opening.span):
|
|
347
|
+
if self._peek().kind is not TokenKind.RBRACKET:
|
|
348
|
+
items.append(self._expression())
|
|
349
|
+
while self._peek().kind is TokenKind.COMMA:
|
|
350
|
+
self._advance()
|
|
351
|
+
items.append(self._expression())
|
|
352
|
+
closing = self._expect(TokenKind.RBRACKET)
|
|
353
|
+
return ListLit(tuple(items), (opening.span[0], closing.span[1]))
|
|
354
|
+
|
|
355
|
+
def _list_is_comprehension(self) -> bool:
|
|
356
|
+
"""Whether the `[` just consumed opens `[head IN tail | projection]` or `[pattern | p]`.
|
|
357
|
+
|
|
358
|
+
A pipe or a `WHERE` at the bracket's own depth is the comprehension marker; either can
|
|
359
|
+
only belong to the list form, because the list items this compiler parses are expressions
|
|
360
|
+
and never contain an unparenthesised pipe. This is a token scan, not a second parser,
|
|
361
|
+
used only to name the construct before its head would fail as an ordinary expression.
|
|
362
|
+
"""
|
|
363
|
+
depth = 0
|
|
364
|
+
index = self._index
|
|
365
|
+
while index < len(self._tokens):
|
|
366
|
+
token = self._tokens[index]
|
|
367
|
+
if token.kind in (TokenKind.LPAREN, TokenKind.LBRACKET, TokenKind.LBRACE):
|
|
368
|
+
depth += 1
|
|
369
|
+
elif token.kind in (TokenKind.RPAREN, TokenKind.RBRACKET, TokenKind.RBRACE):
|
|
370
|
+
if token.kind is TokenKind.RBRACKET and depth == 0:
|
|
371
|
+
return False
|
|
372
|
+
depth -= 1
|
|
373
|
+
elif depth == 0 and (
|
|
374
|
+
token.kind is TokenKind.PIPE
|
|
375
|
+
or (token.kind is TokenKind.KEYWORD and token.text.upper() == "WHERE")
|
|
376
|
+
):
|
|
377
|
+
return True
|
|
378
|
+
elif token.kind is TokenKind.EOF:
|
|
379
|
+
return False
|
|
380
|
+
index += 1
|
|
381
|
+
return False
|
|
382
|
+
|
|
383
|
+
def _string_predicate(self, left: Expr) -> StringPredicate:
|
|
384
|
+
"""`STARTS WITH`, `ENDS WITH` and `CONTAINS`, each taking one operand."""
|
|
385
|
+
token = self._advance()
|
|
386
|
+
word = token.text.upper()
|
|
387
|
+
match word:
|
|
388
|
+
case "CONTAINS":
|
|
389
|
+
op = StringOp.CONTAINS
|
|
390
|
+
case "STARTS" | "ENDS":
|
|
391
|
+
self._expect_keyword("WITH")
|
|
392
|
+
op = StringOp.STARTS_WITH if word == "STARTS" else StringOp.ENDS_WITH
|
|
393
|
+
case _:
|
|
394
|
+
raise AssertionError(f"internal error: {word} is not a string predicate")
|
|
395
|
+
right = self._primary()
|
|
396
|
+
return StringPredicate(op, left, right, token.span, (left.span[0], right.span[1]))
|
|
397
|
+
|
|
398
|
+
def _primary(self) -> Expr:
|
|
399
|
+
token = self._peek()
|
|
400
|
+
match token.kind:
|
|
401
|
+
case TokenKind.INTEGER:
|
|
402
|
+
self._advance()
|
|
403
|
+
return Lit(self._integer(token), token.span)
|
|
404
|
+
case TokenKind.FLOAT:
|
|
405
|
+
self._advance()
|
|
406
|
+
return Lit(self._float(token), token.span)
|
|
407
|
+
case TokenKind.STRING:
|
|
408
|
+
self._advance()
|
|
409
|
+
return Lit(cast(str, token.value), token.span)
|
|
410
|
+
case TokenKind.PARAM:
|
|
411
|
+
self._advance()
|
|
412
|
+
return Param(cast(str, token.value), token.span)
|
|
413
|
+
case TokenKind.INTERPOLATION:
|
|
414
|
+
self._advance()
|
|
415
|
+
return Param(cast(str, token.value), token.span)
|
|
416
|
+
case TokenKind.LBRACKET:
|
|
417
|
+
return self._list_literal()
|
|
418
|
+
case TokenKind.LBRACE:
|
|
419
|
+
raise UnsupportedCypherError(
|
|
420
|
+
"a map literal is not supported yet",
|
|
421
|
+
query=self._query,
|
|
422
|
+
span=token.span,
|
|
423
|
+
hint=hint_for("map-literal"),
|
|
424
|
+
)
|
|
425
|
+
case TokenKind.MINUS:
|
|
426
|
+
return self._negative_number()
|
|
427
|
+
case TokenKind.LPAREN:
|
|
428
|
+
if self._starts_path():
|
|
429
|
+
return self._pattern_predicate()
|
|
430
|
+
self._advance()
|
|
431
|
+
with self._nested(token.span):
|
|
432
|
+
inner = self._expression()
|
|
433
|
+
self._expect(TokenKind.RPAREN)
|
|
434
|
+
return inner
|
|
435
|
+
case TokenKind.IDENT | TokenKind.KEYWORD:
|
|
436
|
+
if token.kind is TokenKind.KEYWORD and token.text.upper() in _LITERAL_KEYWORDS:
|
|
437
|
+
self._advance()
|
|
438
|
+
return Lit(self._literal_keyword(token), token.span)
|
|
439
|
+
if token.kind is TokenKind.KEYWORD and token.text.upper() == "CASE":
|
|
440
|
+
raise self._case_error(token)
|
|
441
|
+
if (
|
|
442
|
+
token.kind is TokenKind.KEYWORD
|
|
443
|
+
and token.text.upper() == "EXISTS"
|
|
444
|
+
and self._peek(1).kind is TokenKind.LBRACE
|
|
445
|
+
):
|
|
446
|
+
return self._exists_subquery()
|
|
447
|
+
if token.kind is TokenKind.KEYWORD and token.text.upper() in _OPERATOR_KEYWORDS:
|
|
448
|
+
raise self._syntax(f"expected a value, found {describe(token)}", token.span)
|
|
449
|
+
return self._var_or_property()
|
|
450
|
+
case _:
|
|
451
|
+
raise self._syntax(f"expected a value, found {describe(token)}", token.span)
|
|
452
|
+
|
|
453
|
+
def _negative_number(self) -> Expr:
|
|
454
|
+
minus = self._advance()
|
|
455
|
+
token = self._peek()
|
|
456
|
+
if token.kind is TokenKind.INTEGER:
|
|
457
|
+
self._advance()
|
|
458
|
+
return Lit(self._integer(token, sign=-1), (minus.span[0], token.span[1]))
|
|
459
|
+
if token.kind is TokenKind.FLOAT:
|
|
460
|
+
self._advance()
|
|
461
|
+
return Lit(-self._float(token), (minus.span[0], token.span[1]))
|
|
462
|
+
raise self._syntax(f"expected a number, found {describe(token)}", token.span)
|
|
463
|
+
|
|
464
|
+
def _float(self, token: Token) -> float:
|
|
465
|
+
value = cast(float, token.value)
|
|
466
|
+
if math.isinf(value):
|
|
467
|
+
raise self._syntax("float literal is out of range", token.span)
|
|
468
|
+
return value
|
|
469
|
+
|
|
470
|
+
def _integer(self, token: Token, *, sign: int = 1) -> int:
|
|
471
|
+
value = cast(int, token.value) * sign
|
|
472
|
+
if not _INT64_MIN <= value <= _INT64_MAX:
|
|
473
|
+
raise self._syntax("integer literal is out of range", token.span)
|
|
474
|
+
return value
|
|
475
|
+
|
|
476
|
+
def _literal_keyword(self, token: Token) -> bool | None:
|
|
477
|
+
match token.text.upper():
|
|
478
|
+
case "TRUE":
|
|
479
|
+
return True
|
|
480
|
+
case "FALSE":
|
|
481
|
+
return False
|
|
482
|
+
case _:
|
|
483
|
+
return None
|
|
484
|
+
|
|
485
|
+
def _var_or_property(self) -> Expr:
|
|
486
|
+
token = self._advance()
|
|
487
|
+
owner = _token_name(token)
|
|
488
|
+
if self._peek().kind is TokenKind.LPAREN:
|
|
489
|
+
raise UnsupportedCypherError(
|
|
490
|
+
"a function call is not supported yet",
|
|
491
|
+
query=self._query,
|
|
492
|
+
span=(token.span[0], self._peek().span[1]),
|
|
493
|
+
hint=hint_for("function-call"),
|
|
494
|
+
)
|
|
495
|
+
if self._peek().kind is not TokenKind.DOT:
|
|
496
|
+
return Var(owner, token.span)
|
|
497
|
+
self._advance()
|
|
498
|
+
key = self._name("a property name")
|
|
499
|
+
return Prop(owner, key.text, key.span, (token.span[0], key.span[1]))
|
|
500
|
+
|
|
501
|
+
# ---------------------------------------------------------------- patterns in WHERE
|
|
502
|
+
|
|
503
|
+
def _starts_path(self) -> bool:
|
|
504
|
+
"""Whether the `(` at the cursor opens a pattern path rather than a parenthesised value.
|
|
505
|
+
|
|
506
|
+
Only a node pattern followed by a relationship starts one: `(n)-->(m)`, `(n)-[:T]->()`,
|
|
507
|
+
`(n)<-[:T]-(m)`. Everything else — `(a = b)`, `(a) - 1` — stays an expression, so an
|
|
508
|
+
arithmetic operator keeps its own teaching error.
|
|
509
|
+
"""
|
|
510
|
+
depth = 0
|
|
511
|
+
index = self._index
|
|
512
|
+
while index < len(self._tokens):
|
|
513
|
+
token = self._tokens[index]
|
|
514
|
+
if token.kind is TokenKind.LPAREN:
|
|
515
|
+
depth += 1
|
|
516
|
+
elif token.kind is TokenKind.RPAREN:
|
|
517
|
+
depth -= 1
|
|
518
|
+
if depth == 0:
|
|
519
|
+
return self._continues_pattern(index + 1)
|
|
520
|
+
elif token.kind is TokenKind.EOF:
|
|
521
|
+
return False
|
|
522
|
+
index += 1
|
|
523
|
+
return False
|
|
524
|
+
|
|
525
|
+
def _continues_pattern(self, index: int) -> bool:
|
|
526
|
+
"""Whether the token after a node pattern's `)` opens a relationship."""
|
|
527
|
+
if index >= len(self._tokens):
|
|
528
|
+
return False
|
|
529
|
+
token = self._tokens[index]
|
|
530
|
+
following = self._tokens[index + 1] if index + 1 < len(self._tokens) else None
|
|
531
|
+
if token.kind is TokenKind.MINUS:
|
|
532
|
+
return following is not None and following.kind in (
|
|
533
|
+
TokenKind.MINUS,
|
|
534
|
+
TokenKind.LBRACKET,
|
|
535
|
+
TokenKind.GT,
|
|
536
|
+
)
|
|
537
|
+
if token.kind is TokenKind.LT:
|
|
538
|
+
return following is not None and following.kind is TokenKind.MINUS
|
|
539
|
+
return False
|
|
540
|
+
|
|
541
|
+
def _pattern_predicate(self) -> PatternPredicate:
|
|
542
|
+
"""`(n)-[:T]->()` inside a `WHERE`: one path, asked as a condition."""
|
|
543
|
+
start = self._peek()
|
|
544
|
+
path = self._path()
|
|
545
|
+
return PatternPredicate(path, (start.span[0], path.span[1]))
|
|
546
|
+
|
|
547
|
+
def _exists_subquery(self) -> ExistsSubquery:
|
|
548
|
+
"""`EXISTS { [MATCH] paths [WHERE ...] ... [RETURN <literal>] }`.
|
|
549
|
+
|
|
550
|
+
Every clause of the body is a pattern the subquery requires; an optional trailing
|
|
551
|
+
`RETURN <literal>` is read and dropped, because an `EXISTS` body only asks whether a row
|
|
552
|
+
exists. Anything that would change the answer (an aggregate, a projection, `WITH`, a
|
|
553
|
+
write, another clause) is refused here, in the subquery's own words.
|
|
554
|
+
"""
|
|
555
|
+
start = self._advance()
|
|
556
|
+
self._expect(TokenKind.LBRACE)
|
|
557
|
+
clauses: list[ExistsMatch] = []
|
|
558
|
+
with self._nested(start.span):
|
|
559
|
+
while self._peek().kind is not TokenKind.RBRACE:
|
|
560
|
+
clause = self._exists_clause()
|
|
561
|
+
if clause is not None:
|
|
562
|
+
clauses.append(clause)
|
|
563
|
+
elif self._peek().kind is not TokenKind.RBRACE:
|
|
564
|
+
raise CypherSyntaxError(
|
|
565
|
+
"RETURN must be the last clause of an EXISTS body",
|
|
566
|
+
query=self._query,
|
|
567
|
+
span=self._peek().span,
|
|
568
|
+
hint=_EXISTS_RETURN_LAST_HINT,
|
|
569
|
+
)
|
|
570
|
+
if not clauses:
|
|
571
|
+
raise self._syntax("expected a pattern or MATCH inside EXISTS", self._peek().span)
|
|
572
|
+
closing = self._expect(TokenKind.RBRACE)
|
|
573
|
+
return ExistsSubquery(tuple(clauses), (start.span[0], closing.span[1]))
|
|
574
|
+
|
|
575
|
+
def _exists_clause(self) -> ExistsMatch | None:
|
|
576
|
+
"""One pattern clause of a subquery body, or `None` for the dropped literal `RETURN`."""
|
|
577
|
+
token = self._peek()
|
|
578
|
+
if self._at_keyword("OPTIONAL"):
|
|
579
|
+
raise UnsupportedCypherError(
|
|
580
|
+
"OPTIONAL MATCH inside EXISTS is not supported yet",
|
|
581
|
+
query=self._query,
|
|
582
|
+
span=token.span,
|
|
583
|
+
hint="a subquery asks whether a row exists; an optional side cannot change that",
|
|
584
|
+
)
|
|
585
|
+
if self._at_keyword("MATCH"):
|
|
586
|
+
start = self._advance()
|
|
587
|
+
return self._exists_match(start.span[0])
|
|
588
|
+
if self._at_keyword("RETURN"):
|
|
589
|
+
self._exists_return()
|
|
590
|
+
return None
|
|
591
|
+
if token.kind is TokenKind.LPAREN:
|
|
592
|
+
return self._exists_match(token.span[0])
|
|
593
|
+
if token.kind is TokenKind.KEYWORD and token.text.upper() in _UNSUPPORTED_CLAUSES:
|
|
594
|
+
raise UnsupportedCypherError(
|
|
595
|
+
f"{_UNSUPPORTED_CLAUSES[token.text.upper()].construct} inside EXISTS is not "
|
|
596
|
+
"supported yet",
|
|
597
|
+
query=self._query,
|
|
598
|
+
span=token.span,
|
|
599
|
+
hint="an EXISTS body may contain MATCH and WHERE only",
|
|
600
|
+
)
|
|
601
|
+
if self._at_keyword("WITH"):
|
|
602
|
+
raise UnsupportedCypherError(
|
|
603
|
+
"WITH inside EXISTS is not supported yet",
|
|
604
|
+
query=self._query,
|
|
605
|
+
span=token.span,
|
|
606
|
+
hint="filter with WHERE; a subquery has no variable scope of its own to project",
|
|
607
|
+
)
|
|
608
|
+
raise self._syntax(
|
|
609
|
+
f"expected a pattern, MATCH or RETURN, found {describe(token)}", token.span
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
def _exists_match(self, start: int) -> ExistsMatch:
|
|
613
|
+
self._reject_named_path()
|
|
614
|
+
if self._peek().kind is not TokenKind.LPAREN:
|
|
615
|
+
raise self._syntax(
|
|
616
|
+
f"expected a pattern, found {describe(self._peek())}", self._peek().span
|
|
617
|
+
)
|
|
618
|
+
paths = tuple(self._paths())
|
|
619
|
+
where = self._where() if self._at_keyword("WHERE") else None
|
|
620
|
+
end = where.span[1] if where is not None else paths[-1].span[1]
|
|
621
|
+
return ExistsMatch(paths, where, (start, end))
|
|
622
|
+
|
|
623
|
+
def _exists_return(self) -> None:
|
|
624
|
+
"""`RETURN <literal>` in an `EXISTS` body: read, then dropped (it changes no answer).
|
|
625
|
+
|
|
626
|
+
The body returns no value, so anything that is not one literal is refused here, with the
|
|
627
|
+
`RETURN`'s own hint: an expression such as `1 + 1`, `NOT true` or a list would otherwise
|
|
628
|
+
fall through to the expression parser's WHERE-shaped error and lose the reason.
|
|
629
|
+
"""
|
|
630
|
+
self._advance()
|
|
631
|
+
token = self._peek()
|
|
632
|
+
if token.kind in (TokenKind.IDENT, TokenKind.KEYWORD) and (
|
|
633
|
+
self._peek(1).kind is TokenKind.LPAREN
|
|
634
|
+
):
|
|
635
|
+
raise UnsupportedCypherError(
|
|
636
|
+
"a function call is not supported yet",
|
|
637
|
+
query=self._query,
|
|
638
|
+
span=(token.span[0], self._peek(1).span[1]),
|
|
639
|
+
hint=_EXISTS_RETURN_HINT,
|
|
640
|
+
)
|
|
641
|
+
if not self._starts_literal(token):
|
|
642
|
+
raise UnsupportedCypherError(
|
|
643
|
+
"only a literal may be returned inside EXISTS",
|
|
644
|
+
query=self._query,
|
|
645
|
+
span=token.span,
|
|
646
|
+
hint=_EXISTS_RETURN_HINT,
|
|
647
|
+
)
|
|
648
|
+
try:
|
|
649
|
+
expr = self._expression()
|
|
650
|
+
except UnsupportedCypherError as error:
|
|
651
|
+
raise UnsupportedCypherError(
|
|
652
|
+
"only a literal may be returned inside EXISTS",
|
|
653
|
+
query=self._query,
|
|
654
|
+
span=error.span,
|
|
655
|
+
hint=_EXISTS_RETURN_HINT,
|
|
656
|
+
) from None
|
|
657
|
+
if not isinstance(expr, Lit):
|
|
658
|
+
raise UnsupportedCypherError(
|
|
659
|
+
"only a literal may be returned inside EXISTS",
|
|
660
|
+
query=self._query,
|
|
661
|
+
span=expr.span,
|
|
662
|
+
hint=_EXISTS_RETURN_HINT,
|
|
663
|
+
)
|
|
664
|
+
|
|
665
|
+
def _starts_literal(self, token: Token) -> bool:
|
|
666
|
+
"""Whether `token` opens a literal and nothing else: a number, string, sign or keyword.
|
|
667
|
+
|
|
668
|
+
`-` is included because a negative number is one literal; `(` is not, so `(1)`, `(n)` and a
|
|
669
|
+
pattern all reach the `RETURN`'s own refusal instead of the expression parser's.
|
|
670
|
+
"""
|
|
671
|
+
if token.kind in (TokenKind.INTEGER, TokenKind.FLOAT, TokenKind.STRING, TokenKind.MINUS):
|
|
672
|
+
return True
|
|
673
|
+
return token.kind is TokenKind.KEYWORD and token.text.upper() in _LITERAL_KEYWORDS
|
|
674
|
+
|
|
675
|
+
# ---------------------------------------------------------------- a WHERE clause
|
|
676
|
+
|
|
677
|
+
def _where(self) -> Where:
|
|
678
|
+
start = self._advance()
|
|
679
|
+
expr = self._expression()
|
|
680
|
+
return Where(expr, (start.span[0], expr.span[1]))
|