uni-cypher 1.1.0

OpenCypher query parser and AST for Uni graph database
Documentation
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
// ═══════════════════════════════════════════════════════════════════════════
// LOCY EXTENSIONS TO CYPHER PEST GRAMMAR
// ═══════════════════════════════════════════════════════════════════════════
//
// This file extends cypher.pest from the uni-cypher crate. Pest concatenates
// both grammars when multiple #[grammar] attributes are stacked:
//
//   #[derive(Parser)]
//   #[grammar = "../uni-cypher/src/cypher.pest"]
//   #[grammar = "src/locy.pest"]
//   struct LocyParser;
//
// All rules from cypher.pest are available here by name. This file defines
// only the Locy-specific extensions.
//
// ═══════════════════════════════════════════════════════════════════════════


// ═══════════════════════════════════════════════════════════════════════════
// LOCY KEYWORDS
// ═══════════════════════════════════════════════════════════════════════════

// Fully reserved — cannot be used as identifiers without backtick-quoting
RULE     = @{ ^"rule" ~ !ident_char }
ALONG    = @{ ^"along" ~ !ident_char }
PREV     = @{ ^"prev" ~ !ident_char }
FOLD     = @{ ^"fold" ~ !ident_char }
BEST     = @{ ^"best" ~ !ident_char }
DERIVE   = @{ ^"derive" ~ !ident_char }
ASSUME   = @{ ^"assume" ~ !ident_char }
ABDUCE   = @{ ^"abduce" ~ !ident_char }
QUERY_KW = @{ ^"query" ~ !ident_char }

// Contextual — already openCypher keywords, given additional meaning
// MODULE, USE, PRIORITY, NEW, EXPORT are not defined in cypher.pest,
// so we define them here. Others (CREATE, MATCH, WHERE, YIELD, MERGE,
// KEY, BY, TO, IS, NOT, THEN, EXPLAIN, AS, RETURN) are in cypher.pest.
MODULE   = @{ ^"module" ~ !ident_char }
USE      = @{ ^"use" ~ !ident_char }
PRIORITY = @{ ^"priority" ~ !ident_char }
NEW      = @{ ^"new" ~ !ident_char }
EXPORT   = @{ ^"export" ~ !ident_char }
PROB     = @{ ^"prob" ~ !ident_char }

// Locy reserved words — added to the reserved keyword set so that
// the Locy parser rejects them as bare identifiers.
locy_keyword_reserved = {
    RULE | ALONG | PREV | FOLD | BEST | DERIVE | ASSUME | ABDUCE | QUERY_KW
}

// Locy identifier: like cypher identifier, but also rejects Locy reserved words
locy_identifier = @{
    !keyword_reserved ~ !locy_keyword_reserved
    ~ (ASCII_ALPHA | "_") ~ (ASCII_ALPHANUMERIC | "_")*
    | "`" ~ (!"`" ~ ANY)* ~ "`"
}

// ═══════════════════════════════════════════════════════════════════════════
// TOP-LEVEL: LOCY PROGRAM
// ═══════════════════════════════════════════════════════════════════════════

// Entry point for the Locy parser. Replaces cypher.pest `query` as SOI/EOI.
locy_query = { SOI ~ module_declaration? ~ use_declaration* ~ locy_union_query ~ EOI }

locy_union_query = {
    locy_single_query ~ (union_operator ~ locy_single_query)*
}

locy_single_query = {
    explain_query                               // Cypher EXPLAIN (unchanged)
    | locy_statement_block
    | schema_command                             // Cypher schema commands (unchanged)
}

locy_statement_block = { locy_clause+ }

// A Locy clause is either a Locy extension or a standard Cypher clause.
// Locy-specific forms are tried first; Cypher clause is the fallback.
locy_clause = {
    rule_definition
    | goal_query
    | derive_command
    | assume_block
    | abduce_query
    | explain_rule_query
    | clause                                    // Fallback to cypher clause
}


// ═══════════════════════════════════════════════════════════════════════════
// MODULE SYSTEM
// ═══════════════════════════════════════════════════════════════════════════

module_declaration = { MODULE ~ locy_qualified_name }

use_declaration = { USE ~ locy_qualified_name ~ use_import_list? }

use_import_list = { "{" ~ locy_identifier ~ ("," ~ locy_identifier)* ~ "}" }

// Dotted name for modules and cross-module rule references
locy_qualified_name = { locy_identifier ~ ("." ~ locy_identifier)* }


// ═══════════════════════════════════════════════════════════════════════════
// RULE DEFINITION  (CREATE RULE ... AS ...)
// ═══════════════════════════════════════════════════════════════════════════

rule_definition = {
    CREATE ~ RULE ~ rule_name ~ priority_clause? ~ AS
    ~ rule_match_clause
    ~ rule_where_clause?
    ~ along_clause?
    ~ fold_clause?
    ~ fold_having_clause?
    ~ best_by_clause?
    ~ rule_terminal_clause
}

// Rule name: simple identifier or qualified (dotted) name
rule_name = { locy_qualified_name }

priority_clause = { PRIORITY ~ integer }

// ── Rule MATCH ──────────────────────────────────────────────────────────

rule_match_clause = { MATCH ~ pattern }

// ── Rule WHERE (extended with IS references) ────────────────────────────
//
// The rule WHERE clause accepts comma-separated conditions, where each
// condition may be an IS rule reference, an IS NOT reference, or a
// standard Cypher expression. Commas act as AND.
//
// Disambiguation with Cypher IS forms (IS NULL, IS NOT NULL, IS :Label):
//   - is_rule_reference requires IS followed by a rule_name (identifier).
//     Since NULL is a reserved keyword it cannot be a rule_name, so
//     "x IS NULL" falls through to expression. Same for IS :Label (colon).
//   - is_not_rule_reference requires IS NOT followed by a rule_name.
//     "x IS NOT NULL" falls through because NULL is not a rule_name.

rule_where_clause = { WHERE ~ rule_condition ~ ("," ~ rule_condition)* }

rule_condition = {
    is_not_rule_reference
    | is_rule_reference
    | expression
}

// ── IS rule reference (positive) ────────────────────────────────────────
//
// Forms:
//   x IS reachable
//   x IS reachable TO y
//   (x, y, cost) IS control

is_rule_reference = {
    "(" ~ locy_identifier ~ ("," ~ locy_identifier)* ~ ")" ~ IS ~ rule_name
    | locy_identifier ~ IS ~ rule_name ~ TO ~ locy_identifier
    | locy_identifier ~ IS ~ rule_name
}

// ── IS NOT rule reference (negative / stratified) ───────────────────────
//
// Both postfix NOT (IS NOT rule) and prefix NOT (NOT x IS rule) are
// supported for all forms: unary, binary (TO), and tuple.

is_not_rule_reference = {
    // Postfix NOT forms: x IS NOT rule, x IS NOT rule TO y, (x,y) IS NOT rule
    "(" ~ locy_identifier ~ ("," ~ locy_identifier)* ~ ")" ~ IS ~ NOT ~ rule_name
    | locy_identifier ~ IS ~ NOT ~ rule_name ~ TO ~ locy_identifier
    | locy_identifier ~ IS ~ NOT ~ rule_name
    // Prefix NOT forms: NOT x IS rule, NOT x IS rule TO y, NOT (x,y) IS rule
    | NOT ~ "(" ~ locy_identifier ~ ("," ~ locy_identifier)* ~ ")" ~ IS ~ rule_name
    | NOT ~ locy_identifier ~ IS ~ rule_name ~ TO ~ locy_identifier
    | NOT ~ locy_identifier ~ IS ~ rule_name
}

// ── Rule terminal: YIELD or DERIVE ──────────────────────────────────────

rule_terminal_clause = {
    locy_yield_clause
    | derive_clause
}


// ═══════════════════════════════════════════════════════════════════════════
// YIELD CLAUSE (Locy-specific, distinct from Cypher YIELD)
// ═══════════════════════════════════════════════════════════════════════════
//
// Locy YIELD defines the output schema of a rule. It supports KEY markers
// for grouping keys and expression-based projections with optional aliases.
// Cypher's YIELD (for CALL procedures) is unchanged.

locy_yield_clause = { YIELD ~ locy_yield_item ~ ("," ~ locy_yield_item)* }

locy_yield_item = {
    key_projection
    | prob_projection
    | expression ~ (AS ~ alias_identifier)?
}

// PROB annotation on yield items: marks column as containing probability values.
// Forms: `expr AS alias PROB`, `expr AS PROB`, `expr PROB`
prob_projection = {
    expression ~ AS ~ alias_identifier ~ PROB
    | expression ~ AS ~ PROB
    | expression ~ PROB
}

key_projection = { KEY ~ expression ~ (AS ~ alias_identifier)? }


// ═══════════════════════════════════════════════════════════════════════════
// PATH-CARRIED VALUES  (ALONG / prev)
// ═══════════════════════════════════════════════════════════════════════════
//
// ALONG declares variables whose values are computed hop-by-hop during
// recursive traversal.
//
// `prev.varname` references the value from the previous hop. At the pest
// level, `prev.cost` parses as an identifier followed by property access
// (since `expression` handles `primary ~ postfix*`). The Locy compiler
// recognizes PREV as a special reference in ALONG context.
//
// If a user has a variable literally named `prev`, it must be backtick-
// quoted in Locy mode since PREV is a fully reserved keyword.

along_clause = { ALONG ~ along_declaration ~ ("," ~ along_declaration)* }

along_declaration = { locy_identifier ~ eq ~ along_expression }

// Along expressions may contain prev references. We define prev_reference
// as an explicit rule so the AST builder can identify it directly, and
// thread it into the expression hierarchy via locy_primary_expression.
along_expression = { locy_or_expression }

// Locy expression chain: mirrors Cypher's chain but with locy_primary
// at the leaf level to include prev_reference.
locy_or_expression  = { locy_xor_expression ~ (OR ~ locy_xor_expression)* }
locy_xor_expression = { locy_and_expression ~ (XOR ~ locy_and_expression)* }
locy_and_expression = { locy_not_expression ~ (AND ~ locy_not_expression)* }
locy_not_expression = { NOT* ~ locy_comparison_expression }
locy_comparison_expression = { locy_additive_expression ~ comparison_tail* }
locy_additive_expression = { locy_multiplicative_expression ~ ((plus | minus) ~ locy_multiplicative_expression)* }
locy_multiplicative_expression = { locy_power_expression ~ ((star | slash | percent) ~ locy_power_expression)* }
locy_power_expression = { locy_unary_expression ~ (caret ~ locy_unary_expression)* }
locy_unary_expression = { minus? ~ locy_postfix_expression }
locy_postfix_expression = { locy_primary_expression ~ postfix_suffix* }

// Locy primary: adds prev_reference before falling back to Cypher primary
locy_primary_expression = {
    prev_reference
    | primary_expression
}

prev_reference = { PREV ~ "." ~ identifier_or_keyword }


// ═══════════════════════════════════════════════════════════════════════════
// AGGREGATION  (FOLD)
// ═══════════════════════════════════════════════════════════════════════════
//
// FOLD declares aggregate computations over rule results.
// The aggregate function (SUM, MSUM, MAX, MMAX, etc.) is parsed as a
// function invocation within the expression. Semantic analysis validates
// that monotonic aggregates (MSUM, MMAX, MMIN, MCOUNT) are used only
// within recursive strata.

fold_clause = { FOLD ~ fold_declaration ~ ("," ~ fold_declaration)* }

fold_declaration = { locy_identifier ~ eq ~ fold_expression }

fold_expression = { expression }

// Post-FOLD filter (HAVING semantics).  Uses the WHERE keyword positionally:
// the first WHERE in a rule filters rows pre-aggregation; this second WHERE
// (after FOLD) filters aggregated groups.
fold_having_clause = { WHERE ~ expression ~ ((AND | ",") ~ expression)* }


// ═══════════════════════════════════════════════════════════════════════════
// OPTIMIZED SELECTION  (BEST BY)
// ═══════════════════════════════════════════════════════════════════════════
//
// BEST BY retains the optimal derivation(s) per key group, preserving
// the full witness row. Ordering follows Cypher's ASC/DESC conventions.

best_by_clause = { BEST ~ BY ~ best_by_item ~ ("," ~ best_by_item)* }

best_by_item = { expression ~ (ASC | DESC)? }


// ═══════════════════════════════════════════════════════════════════════════
// GRAPH DERIVATION  (DERIVE in rule heads)
// ═══════════════════════════════════════════════════════════════════════════
//
// DERIVE clauses create graph structure (nodes and edges) as rule output.
// DERIVE MERGE triggers entity resolution between two nodes.

derive_clause = {
    DERIVE ~ MERGE ~ locy_identifier ~ "," ~ locy_identifier
    | DERIVE ~ derive_pattern ~ ("," ~ derive_pattern)*
}

derive_pattern = {
    derive_forward_pattern
    | derive_backward_pattern
}

// (a)-[:TYPE {props}]->(b)
derive_forward_pattern = {
    "(" ~ derive_node_spec ~ ")"
    ~ "-" ~ "[" ~ derive_edge_spec ~ "]" ~ "->"
    ~ "(" ~ derive_node_spec ~ ")"
}

// (a)<-[:TYPE {props}]-(b)
derive_backward_pattern = {
    "(" ~ derive_node_spec ~ ")"
    ~ "<-" ~ "[" ~ derive_edge_spec ~ "]" ~ "-"
    ~ "(" ~ derive_node_spec ~ ")"
}

derive_node_spec = {
    NEW? ~ locy_identifier ~ node_labels? ~ properties?
}

derive_edge_spec = {
    ":" ~ identifier_or_keyword ~ properties?
}


// ═══════════════════════════════════════════════════════════════════════════
// GOAL-DIRECTED EVALUATION  (QUERY)
// ═══════════════════════════════════════════════════════════════════════════
//
// QUERY evaluates a rule using SLG-resolution (top-down with tabling)
// instead of bottom-up fixpoint.

goal_query = {
    QUERY_KW ~ rule_name
    ~ (WHERE ~ expression)?
    ~ goal_return_clause?
}

goal_return_clause = {
    RETURN ~ DISTINCT? ~ return_items ~ order_clause? ~ skip_clause? ~ limit_clause?
}


// ═══════════════════════════════════════════════════════════════════════════
// TOP-LEVEL DERIVE COMMAND
// ═══════════════════════════════════════════════════════════════════════════
//
// Triggers bottom-up materialization of a named rule.

derive_command = { DERIVE ~ rule_name ~ where_clause? }


// ═══════════════════════════════════════════════════════════════════════════
// HYPOTHETICAL REASONING  (ASSUME ... THEN)
// ═══════════════════════════════════════════════════════════════════════════
//
// ASSUME creates a hypothetical context: mutations in the block are applied
// inside a transaction savepoint, the THEN body executes, then the
// savepoint is rolled back. Mutations never persist.

assume_block = {
    ASSUME ~ "{" ~ assume_mutation* ~ "}"
    ~ THEN ~ assume_body
}

assume_mutation = {
    match_clause
    | create_clause
    | merge_clause
    | set_clause
    | remove_clause
    | delete_clause
}

assume_body = {
    "{" ~ locy_clause+ ~ "}"
    | locy_clause
}


// ═══════════════════════════════════════════════════════════════════════════
// ABDUCTIVE REASONING  (ABDUCE)
// ═══════════════════════════════════════════════════════════════════════════
//
// ABDUCE asks: "what graph modifications would make this rule hold
// (or stop holding)?"

abduce_query = {
    ABDUCE ~ NOT? ~ rule_name
    ~ (WHERE ~ expression)?
    ~ abduce_return_clause?
}

abduce_return_clause = {
    RETURN ~ DISTINCT? ~ return_items ~ order_clause? ~ skip_clause? ~ limit_clause?
}


// ═══════════════════════════════════════════════════════════════════════════
// PROOF TRACES  (EXPLAIN RULE)
// ═══════════════════════════════════════════════════════════════════════════
//
// EXPLAIN RULE returns the derivation tree showing which rule clauses
// and base facts produced a given result.
//
// Note: Cypher's EXPLAIN (query plan) is `EXPLAIN <statement>`, defined
// in cypher.pest as `explain_query`. Locy's `EXPLAIN RULE` is
// unambiguous because of the intervening RULE keyword.

explain_rule_query = {
    EXPLAIN ~ RULE ~ rule_name
    ~ (WHERE ~ expression)?
    ~ explain_rule_return_clause?
}

explain_rule_return_clause = {
    RETURN ~ DISTINCT? ~ return_items ~ order_clause? ~ skip_clause? ~ limit_clause?
}