relate_parser/ast.rs
1use relate_names::SmallName;
2
3/// The statement preamble mode (CIP-150): which of `EXPLAIN`/`PROFILE`
4/// heads the statement, or neither. The preamble grammar is top-level
5/// only and each keyword is admitted at most once, so exactly one mode
6/// heads a statement — never a pair of flags that could disagree.
7#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8pub enum PreambleMode {
9 /// No preamble keyword: the statement executes.
10 #[default]
11 Execute,
12 /// An `EXPLAIN` preamble: the statement compiles and its plan renders,
13 /// never executes.
14 Explain,
15 /// A `PROFILE` preamble: the statement executes with per-operator
16 /// metrics attached.
17 Profile,
18}
19
20/// AST node types for the Cypher parser.
21///
22/// The AST uses enums for Clause, Expr, and PatternElement to avoid trait objects.
23/// Literal values use native Rust types (not CypherValue) since the AST is a compile-time concept.
24///
25/// Top-level AST node for a Cypher statement.
26#[derive(Debug, Clone, Default)]
27pub struct Statement {
28 pub clauses: Vec<Clause>,
29 pub union: Option<Box<UnionPart>>,
30 /// The CIP-150 preamble mode — top-level only; every nested body
31 /// carries [`PreambleMode::Execute`].
32 pub preamble: PreambleMode,
33 /// CIP-213 `<statement block> ::= <statement> [<next statement>...]`,
34 /// `<next statement> ::= NEXT <statement>`. `next` chains this
35 /// statement (which may itself carry its own `.union` chain, or be a
36 /// sole `Clause::Conditional`) to the following NEXT stage's own
37 /// statement (which may in turn have a `.next` of its own). `None`
38 /// means this is either not part of a NEXT chain, or is its final
39 /// stage. Deliberately a *sibling* field to `union`/`Conditional`
40 /// rather than nested inside them: per the CIP grammar, NEXT operates
41 /// on a whole `<statement>` (union-chain-or-conditional), one level
42 /// above where UNION/WHEN operate, so it's threaded through the
43 /// outermost `Statement` of each stage only -- a stage's own `.union`
44 /// arms never carry their own independent `.next` chain.
45 pub next: Option<Box<Statement>>,
46 /// CIP-146/CIP-242: true when this `SingleQuery` was written as
47 /// `[ USE <graph-expr> ] '{' <RegularQuery> '}'` -- top-level braces --
48 /// rather than the plain unbraced form. The brace form's *content* is
49 /// otherwise indistinguishable from an unbraced statement (same clause
50 /// list, same `.union` chain) once parsed, but CIP-242's SHOW/TERMINATE
51 /// composability rule ("Composing a SHOW command without YIELD fails")
52 /// treats an explicitly brace-wrapped bare `SHOW` (e.g. `{ SHOW INDEXES
53 /// }`) as *composed*, requiring `YIELD`, even though the identical
54 /// clause list unbraced (`SHOW INDEXES` alone) is the lenient
55 /// "canonical standalone" form that doesn't need one -- so this needs
56 /// its own marker distinct from clause shape. Set only by
57 /// `parse_braced_single_query`; every other `Statement` constructor
58 /// leaves it `false` (via `#[derive(Default)]` field-by-field
59 /// construction elsewhere).
60 pub brace_wrapped: bool,
61 /// CIP-231: the `DEFINE <procedure definition> | <function
62 /// definition>` block parsed at the head of this statement block (only
63 /// the top-level statement and braced nested bodies carry definitions;
64 /// every statement-block parse site funnels through
65 /// `parse_statement_block`, where they are parsed). Rewritten away --
66 /// definitions and their call sites eliminated -- by the front-end
67 /// resolver (`relate-front`'s `local_callables`) before lowering;
68 /// the planner/executor never see local callables. `Default`-empty so
69 /// the derived and hand-written constructors of un-gated statements
70 /// are unchanged.
71 pub definitions: Vec<LocalDefinition>,
72}
73
74/// Manual `PartialEq`: deliberately ignores `brace_wrapped`. The unwrap
75/// rule -- and the parser tests pinning it (`test_brace_enclosed_top_level_query_is_transparent` and friends) --
76/// treat a brace-wrapped `SingleQuery` as producing an AST indistinguishable
77/// from its unbraced spelling; `brace_wrapped` is out-of-band provenance a
78/// couple of CIP-242 composability checks read directly off the field
79/// (`validate_show_composability`), not part of that observable-content
80/// equivalence.
81impl PartialEq for Statement {
82 fn eq(&self, other: &Self) -> bool {
83 self.clauses == other.clauses
84 && self.union == other.union
85 && self.preamble == other.preamble
86 && self.next == other.next
87 && self.definitions == other.definitions
88 }
89}
90
91/// CIP-231 `DEFINE` block entry: one local callable definition, parsed at
92/// the head of a `<statement block>` (top level or a braced nested body)
93/// and rewritten away by the front-end resolver
94/// (`relate-front`'s `local_callables`) before lowering -- the
95/// planner/executor never see local callables.
96#[derive(Debug, Clone, PartialEq)]
97pub struct LocalDefinition {
98 /// `PROCEDURE` or `FUNCTION`.
99 pub kind: LocalCallableKind,
100 /// The fully-qualified callable name as written (`foo.bar`), namespace
101 /// segments joined on `.`. Matched against call-site names verbatim.
102 pub name: SmallName,
103 /// The `<callable input signature>`: parameters in declaration order.
104 pub params: Vec<LocalParam>,
105 /// The declared `<procedure output type>` (`(field :: T, ...)`) or
106 /// `<function output type>` (`:: T`), when written.
107 pub output: Option<LocalOutput>,
108 /// `= <value expression>` (simple function body) or a braced
109 /// `<procedure specification>` (procedure body or subquery function
110 /// body).
111 pub body: LocalDefinitionBody,
112}
113
114/// `DEFINE PROCEDURE` vs `DEFINE FUNCTION` (CIP-231). The two namespaces
115/// are independent (CIP-230: a procedure and a function may share a name).
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
117pub enum LocalCallableKind {
118 Procedure,
119 Function,
120}
121
122/// One `<input field signature>` of a local callable (CIP-231): a field
123/// name, an optional `[<typed>] <value type>`, and an optional
124/// `= <value expression>` default (which makes the parameter optional).
125#[derive(Debug, Clone, PartialEq)]
126pub struct LocalParam {
127 pub name: SmallName,
128 /// The written value type, `None` when omitted (implicitly ANY).
129 /// Parsed and syntactically validated, deliberately not enforced at
130 /// runtime (ADR-0382).
131 pub type_expr: Option<TypeExpr>,
132 /// `= <value expression>`; `None` for a mandatory parameter. Defaults
133 /// may not reference variables (checked at parse time).
134 pub default: Option<Expr>,
135}
136
137/// A declared output type of a local callable (CIP-231): the procedure
138/// form `:: (a :: INT, ...)` or the function form `:: STRING`.
139#[derive(Debug, Clone, PartialEq)]
140pub enum LocalOutput {
141 /// `:: (<mandatory field signature>, ...)` on a procedure.
142 Fields(Vec<LocalOutputField>),
143 /// `:: <value type>` on a function.
144 Type(TypeExpr),
145}
146
147/// One field of a procedure's `:: (a :: INT, ...)` output signature.
148#[derive(Debug, Clone, PartialEq)]
149pub struct LocalOutputField {
150 pub name: SmallName,
151 pub type_expr: Option<TypeExpr>,
152}
153
154/// The body of a local callable definition (CIP-231).
155#[derive(Debug, Clone, PartialEq)]
156pub enum LocalDefinitionBody {
157 /// `FUNCTION f(...) = <value expression>` (simple function body).
158 Expression(Expr),
159 /// A braced `<procedure specification>`: a procedure body, or a
160 /// subquery function body.
161 Query(Statement),
162}
163
164/// Represents a UNION or UNION ALL between statements.
165#[derive(Debug, Clone, PartialEq)]
166pub struct UnionPart {
167 pub all: bool,
168 pub statement: Statement,
169}
170
171/// All clause types in the Cypher language.
172#[derive(Debug, Clone, PartialEq)]
173pub enum Clause {
174 Match(MatchClause),
175 Create(CreateClause),
176 Merge(MergeClause),
177 Delete(DeleteClause),
178 Set(SetClause),
179 Remove(RemoveClause),
180 Return(ReturnClause),
181 With(WithClause),
182 Unwind(UnwindClause),
183 CreateIndex(CreateIndexClause),
184 DropIndex(DropIndexClause),
185 CreateConstraint(CreateConstraintClause),
186 DropConstraint(DropConstraintClause),
187 Foreach(ForeachClause),
188 LoadCSV(LoadCSVClause),
189 CallSubquery(CallSubqueryClause),
190 CallProcedure(CallProcedureClause),
191 ShowFunctions(ShowFunctionsClause),
192 ShowConstraints(ShowConstraintsClause),
193 ShowIndexes(ShowIndexesClause),
194 /// `SHOW DATABASE[S] [<name>] [YIELD ...] [WHERE ...]` / `SHOW DEFAULT
195 /// DATABASE` / `SHOW HOME DATABASE` (CIP-68's singular/plural KIND
196 /// acceptance; CIP-42's four non-default columns). A minimal virtual
197 /// catalog -- Relate is a single-database engine, so this reports a
198 /// small set of deterministic built-in databases rather than modeling
199 /// real multi-database administration.
200 ShowDatabases(ShowDatabasesClause),
201 /// `SHOW [ALL|POPULATED] ROLE[S] [WITH USER[S]] [YIELD ...] [WHERE ...]`
202 /// (CIP-68). A minimal virtual catalog of built-in roles.
203 ShowRoles(ShowRolesClause),
204 /// `SHOW SERVER[S] [YIELD ...] [WHERE ...]` (CIP-68). Reports a single
205 /// row, matching a single-process embedded engine.
206 ShowServers(ShowServersClause),
207 /// `SHOW USER[S] [YIELD ...] [WHERE ...]` / `SHOW CURRENT USER`
208 /// (CIP-68). A minimal virtual catalog of a single built-in user.
209 ShowUsers(ShowUsersClause),
210 /// `SHOW PROCEDURE[S] [YIELD ...] [WHERE ...]` (CIP-68 grammar
211 /// foundation). Lists the built-in procedure names the engine's `CALL`
212 /// handler recognizes.
213 ShowProcedures(ShowProceduresClause),
214 /// `SHOW SETTING[S] [<names>] [YIELD ...] [WHERE ...]` (CIP-68 grammar
215 /// foundation). Relate has no configurable settings surface, so
216 /// this always reports an empty catalog.
217 ShowSettings(ShowSettingsClause),
218 /// `SHOW TRANSACTION[S] [<ids>] [YIELD ...] [WHERE ...]` (CIP-68
219 /// grammar foundation). Relate executes each statement to
220 /// completion without exposing concurrent transaction identifiers, so
221 /// this always reports an empty catalog.
222 ShowTransactions(ShowTransactionsClause),
223 /// `TERMINATE TRANSACTION[S] <ids> [YIELD ...]` (CIP-68 grammar
224 /// foundation). Since `ShowTransactions` never reports a live
225 /// transaction, every requested id is reported as not found.
226 TerminateTransactions(TerminateTransactionsClause),
227 /// `USE <graph-expr>` (CIP-141 feature-interaction scenarios) -- a
228 /// graph-selector clause. Relate is a single-database engine, so
229 /// this is parsed and scope-checked (its expression's variables must
230 /// be in scope, same as any other clause) but has no runtime effect
231 /// beyond that: there is no composite/multi-graph database to switch
232 /// to.
233 Use(UseClause),
234 /// `FINISH` (CIP-140) -- a terminal clause producing a truly empty
235 /// result (0 rows, 0 columns) instead of RETURN's projected rows,
236 /// while still running any earlier updating clauses. Only the minimal
237 /// semantics needed by CIP-218's `CALL (a) { FINISH }` scenario are
238 /// implemented: cardinality is preserved (one output row per input
239 /// row) but that row carries no columns, so it contributes nothing
240 /// when merged back into an enclosing CALL's outer row.
241 Finish,
242 /// CIP-168: a standalone `<order by and page statement>` -- e.g.
243 /// `ORDER BY n.name SKIP 1 LIMIT 3` appearing as its own clause, not
244 /// attached to WITH/RETURN/YIELD. Acts as an implicit `WITH *`
245 /// horizon clause: changes row order/count but never the column set,
246 /// and may sit between any two other clauses (including two write
247 /// clauses). See `StandaloneOrderByClause` for why this is a sequence
248 /// of stages rather than three fixed fields.
249 StandaloneOrderBy(StandaloneOrderByClause),
250 /// CIP-135: a standalone conditional clause chain --
251 /// `<when query> ::= <when>, {<when>}, [<else>]`. This is a *sibling*
252 /// alternative to `<union query>`/`<single query>` at the `<regular
253 /// query>` grammar level (see `parse_regular_query`), not an ordinary
254 /// mid-statement clause -- so this variant only ever appears as the
255 /// sole element of a `Statement.clauses` vec, never alongside other
256 /// clauses in the same statement.
257 Conditional(ConditionalClause),
258 /// `ALTER CURRENT GRAPH TYPE SET/ADD/ALTER/DROP { <graph type
259 /// specification body> }` (CIP-176/182/183's mechanism; CIP-187's
260 /// constraint derivation builds on it). `body` is the full CIP-178
261 /// `<graph type specification body>` grammar (node/edge type specs,
262 /// property types, and constraint specs) -- see `GraphTypeBody`.
263 AlterCurrentGraphType(AlterCurrentGraphTypeClause),
264 /// `CREATE GRAPH TYPE <name> [AS] { <graph type specification body> }`
265 /// (CIP-178 grammar; the `AS` keyword is CIP-180's spelling of the same
266 /// body-introducing form). Registers a *named* graph type, independent
267 /// of the database's single unnamed "current" graph type that `ALTER
268 /// CURRENT GRAPH TYPE` manages.
269 CreateGraphType(CreateGraphTypeClause),
270 /// `SHOW GRAPH TYPE <name> [YIELD ...]` (CIP-180's SHOW surface): a
271 /// single-row catalog whose `name`/`body` columns report the named
272 /// graph type's own name and its CIP-180 canonical specification
273 /// string.
274 ShowGraphType(ShowGraphTypeClause),
275 /// `SHOW CURRENT GRAPH TYPE [YIELD ...]` (CIP-176 overview / CIP-184):
276 /// the database's persistent current graph type, reported as a single
277 /// `specification` column (the CIP-180 canonical body string wrapped in
278 /// `{ }`, or the literal `{}` when empty).
279 ShowCurrentGraphType(ShowCurrentGraphTypeClause),
280 /// `ALTER DATABASE <name> [IF EXISTS] SET DEFAULT LANGUAGE CYPHER
281 /// <n>` (CIP-170). Under ADR-0116 §2's fixed namespaces this is the
282 /// only supported `ALTER DATABASE` form; every other form is
283 /// recognized and rejected at parse time with CE's
284 /// `UnsupportedAdministrationCommand`.
285 AlterDatabase(AlterDatabaseClause),
286}
287
288impl Clause {
289 /// The Cypher clause keyword(s) for this clause — e.g. `"MATCH"`,
290 /// `"SHOW INDEXES"`, `"LOAD CSV"`. Exhaustive over the enum, so a new
291 /// clause cannot ship without a renderable name; the planner's
292 /// `clause_keyword` delegates here rather than keeping a second table.
293 pub fn keyword(&self) -> &'static str {
294 match self {
295 Clause::Match(_) => "MATCH",
296 Clause::Create(_) => "CREATE",
297 Clause::Merge(_) => "MERGE",
298 Clause::Delete(_) => "DELETE",
299 Clause::Set(_) => "SET",
300 Clause::Remove(_) => "REMOVE",
301 Clause::Return(_) => "RETURN",
302 Clause::With(_) => "WITH",
303 Clause::Unwind(_) => "UNWIND",
304 Clause::CreateIndex(_) => "CREATE INDEX",
305 Clause::DropIndex(_) => "DROP INDEX",
306 Clause::CreateConstraint(_) => "CREATE CONSTRAINT",
307 Clause::DropConstraint(_) => "DROP CONSTRAINT",
308 Clause::Foreach(_) => "FOREACH",
309 Clause::LoadCSV(_) => "LOAD CSV",
310 Clause::CallSubquery(_) | Clause::CallProcedure(_) => "CALL",
311 Clause::ShowFunctions(_) => "SHOW FUNCTIONS",
312 Clause::ShowConstraints(_) => "SHOW CONSTRAINTS",
313 Clause::ShowIndexes(_) => "SHOW INDEXES",
314 Clause::ShowDatabases(_) => "SHOW DATABASES",
315 Clause::ShowRoles(_) => "SHOW ROLES",
316 Clause::ShowServers(_) => "SHOW SERVERS",
317 Clause::ShowUsers(_) => "SHOW USERS",
318 Clause::ShowProcedures(_) => "SHOW PROCEDURES",
319 Clause::ShowSettings(_) => "SHOW SETTINGS",
320 Clause::ShowTransactions(_) => "SHOW TRANSACTIONS",
321 Clause::TerminateTransactions(_) => "TERMINATE TRANSACTIONS",
322 Clause::Use(_) => "USE",
323 Clause::Finish => "FINISH",
324 Clause::StandaloneOrderBy(_) => "ORDER BY",
325 Clause::Conditional(_) => "WHEN",
326 Clause::AlterCurrentGraphType(_) => "ALTER CURRENT GRAPH TYPE",
327 Clause::CreateGraphType(_) => "CREATE GRAPH TYPE",
328 Clause::ShowGraphType(_) => "SHOW GRAPH TYPE",
329 Clause::ShowCurrentGraphType(_) => "SHOW CURRENT GRAPH TYPE",
330 Clause::AlterDatabase(_) => "ALTER DATABASE",
331 }
332 }
333}
334
335/// See `Clause::AlterDatabase`.
336#[derive(Debug, Clone, PartialEq)]
337pub struct AlterDatabaseClause {
338 pub name: SchemaName,
339 pub if_exists: bool,
340 /// The `SET DEFAULT LANGUAGE CYPHER <n>` digits (e.g. `5`, `25`, or an
341 /// unsupported value like `6`), unvalidated at parse time (CIP-170):
342 /// an out-of-range version here is a *runtime*
343 /// data exception (`22N04`), unlike the CIP-150 statement-preamble
344 /// `CYPHER <version>` prefix, which rejects at compile time.
345 pub default_language: u32,
346}
347
348/// See `Clause::AlterCurrentGraphType`.
349#[derive(Debug, Clone, PartialEq)]
350pub struct AlterCurrentGraphTypeClause {
351 pub verb: AlterGraphTypeVerb,
352 pub target: AlterCurrentGraphTypeTarget,
353}
354
355/// What an `ALTER CURRENT GRAPH TYPE` verb applies: an inline `{ <body> }`,
356/// or — ADR-0211's `ALTER CURRENT GRAPH TYPE SET GRAPH TYPE <name>` — a
357/// reference to a `CREATE GRAPH TYPE`-declared named type, promoted to
358/// current. The invalid combinations (a verb body *and* a named reference)
359/// are unrepresentable; no parser placeholder and no consumer-side doc
360/// invariant.
361#[derive(Debug, Clone, PartialEq)]
362pub enum AlterCurrentGraphTypeTarget {
363 Body(GraphTypeBody),
364 Named(SmallName),
365}
366
367/// One `YIELD <name> [AS <alias>]` item of a procedure call or catalog
368/// command. `alias` is `None` when no `AS` was written, so "no alias" is
369/// represented by the optional itself rather than an empty-string sentinel
370/// in a parallel array.
371#[derive(Debug, Clone, PartialEq, Eq)]
372pub struct YieldItem {
373 pub name: SmallName,
374 pub alias: Option<SmallName>,
375}
376
377impl YieldItem {
378 /// The name this item binds in the enclosing scope: the alias when one
379 /// was written, else the yielded column name. A `SmallName` copy (the
380 /// inline arm is a `u64` move, the spilled arm a refcount bump,
381 /// ADR-0509 §1) — consumers bridging into a `String`-keyed scope map
382 /// pay the text conversion at that one feed site.
383 pub fn effective_name(&self) -> SmallName {
384 self.alias.clone().unwrap_or_else(|| self.name.clone())
385 }
386}
387
388/// A clause's `YIELD` tail, modeled once: the explicit items in source
389/// order plus whether `YIELD *` was written. Empty `items` with `all ==
390/// false` means no `YIELD` at all (the grammar never reads an empty
391/// explicit list).
392#[derive(Debug, Clone, PartialEq, Eq, Default)]
393pub struct YieldList {
394 pub items: Vec<YieldItem>,
395 pub all: bool,
396}
397
398/// A clause's yield mode, derived once from its [`YieldList`]: `YIELD *`
399/// projects every column, a bare clause its default table, and an explicit
400/// list its named (post-alias) columns. Consumers select their behavior
401/// from this instead of each re-testing `(all, is_empty)`.
402#[derive(Debug, Clone, Copy, PartialEq, Eq)]
403pub enum YieldMode {
404 /// `YIELD *`: every column of the command.
405 Star,
406 /// No `YIELD` at all: the command's default table.
407 Default,
408 /// An explicit `YIELD` list: the named, post-alias columns.
409 Named,
410}
411
412impl YieldList {
413 /// The clause's yield mode — the one derivation.
414 pub fn mode(&self) -> YieldMode {
415 if self.all {
416 YieldMode::Star
417 } else if self.items.is_empty() {
418 YieldMode::Default
419 } else {
420 YieldMode::Named
421 }
422 }
423
424 /// Whether any `YIELD` tail was written (an explicit list or `*`).
425 pub fn present(&self) -> bool {
426 !matches!(self.mode(), YieldMode::Default)
427 }
428
429 /// Each item's raw yielded name, in source order.
430 pub fn names(&self) -> impl Iterator<Item = &SmallName> {
431 self.items.iter().map(|item| &item.name)
432 }
433
434 /// Each item's raw name, optional alias, and effective (post-alias)
435 /// name, in source order. Consumers that need both sides of the alias
436 /// rule read them from this one iterator instead of re-deriving the
437 /// precedence.
438 pub fn pairs(&self) -> impl Iterator<Item = (&SmallName, Option<&SmallName>, SmallName)> {
439 self.items
440 .iter()
441 .map(|item| (&item.name, item.alias.as_ref(), item.effective_name()))
442 }
443
444 /// Each item's effective (post-alias) name, in source order.
445 pub fn effective_names(&self) -> impl Iterator<Item = SmallName> + '_ {
446 self.items.iter().map(YieldItem::effective_name)
447 }
448}
449
450/// See `Clause::ShowCurrentGraphType`.
451#[derive(Debug, Clone, PartialEq, Default)]
452pub struct ShowCurrentGraphTypeClause {
453 pub yields: YieldList,
454 /// Paging stages following YIELD, preserved in source order.
455 pub stages: Vec<PageStage>,
456 /// CIP-184: an optional trailing `WHERE <expr>`, permitted with or
457 /// without an explicit `YIELD` (mirrors `ShowDatabasesClause`).
458 pub where_expr: Option<Expr>,
459 /// `AS GRAPH [SINGLE | SEPARATE]` -- renders the current graph
460 /// type as `nodes`/`relationships` columns instead of the plain
461 /// `specification` string column. `None` when `AS GRAPH` wasn't
462 /// written at all.
463 pub as_graph: Option<AnyNodeMode>,
464}
465
466/// CIP-257's "Future improvements" any-node keyword, controlling how many
467/// synthetic `(:AnyLabel {})` nodes an unconstrained relationship endpoint
468/// gets: `Separate` (the default, whether or not the keyword is written) --
469/// one any-node per relationship that needs one; `Single` -- every
470/// unconstrained endpoint across the whole graph type shares one any-node.
471#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
472pub enum AnyNodeMode {
473 #[default]
474 Separate,
475 Single,
476}
477
478/// The four `ALTER CURRENT GRAPH TYPE` verbs (CIP-176/CIP-182 overview
479/// scope): `SET` replaces the whole current graph type (and, as observed
480/// live, every constraint in the database); `ADD`
481/// extends it; `ALTER` replaces an existing element type (matched by
482/// identifying label) with a new declaration; `DROP` removes the element
483/// types named in its body.
484#[derive(Debug, Clone, Copy, PartialEq, Eq)]
485pub enum AlterGraphTypeVerb {
486 Set,
487 Add,
488 Alter,
489 Drop,
490}
491
492/// See `Clause::CreateGraphType`.
493#[derive(Debug, Clone, PartialEq)]
494pub struct CreateGraphTypeClause {
495 pub name: SmallName,
496 pub body: GraphTypeBody,
497 /// Whether the `AS` spelling was used (the scaffolding form,
498 /// `CREATE GRAPH TYPE <name> AS { <body> }`, vs. CIP-178's plain
499 /// `CREATE GRAPH TYPE <name> { <body> }`). The worked
500 /// example (`()-[:REL =>]->()`, no properties, both endpoints the any
501 /// type) is an ineffectual single-label edge
502 /// type -- the `AS` form exists to exercise the CIP-180 canonicalizer,
503 /// so the engine's `CreateGraphType` handler exempts it from the
504 /// ineffectual-type rejection and
505 /// the one-index-backing-per-subject clash (both shapes the canonicalizer's own
506 /// scenarios use), and validates every other body rule normally.
507 pub via_as: bool,
508}
509
510/// See `Clause::ShowGraphType`.
511#[derive(Debug, Clone, PartialEq)]
512pub struct ShowGraphTypeClause {
513 pub name: SmallName,
514 pub yields: YieldList,
515}
516
517/// A fully parsed `<graph type specification body>` (CIP-178): the `{
518/// ... }` contents shared by `CreateGraphTypeClause` and
519/// `AlterCurrentGraphTypeClause`. Parsing is grammar-only (always succeeds
520/// once the tokens match); the CIP-178 "shall" rules (alias/label
521/// uniqueness, reference resolution, ...) are enforced separately by
522/// `relate-executor`'s graph-type validator (`validate_graph_type_body`),
523/// which only `CREATE GRAPH
524/// TYPE` invokes -- `ALTER CURRENT GRAPH TYPE` bodies legitimately reference
525/// element types declared by an *earlier* statement (e.g. `ADD`), which a
526/// single-body validation pass cannot see.
527#[derive(Debug, Clone, PartialEq, Default)]
528pub struct GraphTypeBody {
529 pub node_types: Vec<GraphTypeNodeTypeSpec>,
530 pub edge_types: Vec<GraphTypeEdgeTypeSpec>,
531 pub constraints: Vec<GraphTypeConstraintSpec>,
532 /// `<constraint drop specification>` = `CONSTRAINT <name>` (bare,
533 /// no `FOR ...`) -- only allowed in an `ALTER CURRENT GRAPH TYPE DROP {
534 /// ... }` body. The parser reads it in any body, and every other verb
535 /// rejects a non-empty list as a parse error
536 /// (`Parser::reject_bare_constraint_drops`), so this is always empty for
537 /// `CREATE GRAPH TYPE`/`SET`/`ADD`/`ALTER` bodies.
538 pub drop_constraint_names: Vec<SmallName>,
539}
540
541/// `'(' [alias] (':'|IS) <identifying label> ('=>'|IMPLIES) [(':'|IS)
542/// <implied label> ('&' <implied label>)*] ['{' <property types> '}'] ')'`
543/// (`<node type specification>`).
544#[derive(Debug, Clone, PartialEq)]
545pub struct GraphTypeNodeTypeSpec {
546 pub alias: Option<SmallName>,
547 pub identifying_label: SmallName,
548 pub implied_labels: Vec<SmallName>,
549 pub properties: Vec<GraphTypePropertyType>,
550}
551
552/// `<source endpoint> '-' '[' [alias] (':'|IS) <identifying label>
553/// ('=>'|IMPLIES) ['{' <property types> '}'] ']' '->' <destination
554/// endpoint>` (`<edge type specification>`).
555#[derive(Debug, Clone, PartialEq)]
556pub struct GraphTypeEdgeTypeSpec {
557 pub alias: Option<SmallName>,
558 pub identifying_label: SmallName,
559 pub properties: Vec<GraphTypePropertyType>,
560 pub source: GraphTypeElementRef,
561 pub target: GraphTypeElementRef,
562}
563
564/// One `<property type>`: a name, its declared value type, an optional
565/// `DEFAULT ON COMMIT <value expression>` (CIP-262), and an optional
566/// inline `IS [NODE|REL|RELATIONSHIP] (KEY|UNIQUE)` constraint (CIP-178
567/// Rules 10-12 rewrite these into standalone `GraphTypeConstraintSpec`s
568/// during registration).
569///
570/// The default value is parsed as a full expression here (grammar-only,
571/// like the rest of the body): the CIP-262 shape restriction -- a literal
572/// or an allowed type constructor, never `null` -- is enforced by the
573/// graph-type semantic layer, and the construct itself sits behind the
574/// ADR-0371 `graph-type-default-values` preview gate at statement
575/// admission (the trio's decision: ADR-0388). `None` is the no-default
576/// case.
577#[derive(Debug, Clone, PartialEq)]
578pub struct GraphTypePropertyType {
579 pub name: SmallName,
580 pub value_type: TypeExpr,
581 pub default_value: Option<Expr>,
582 pub inline_constraint: Option<GraphTypeInlineConstraint>,
583}
584
585/// An inline property-type constraint (`{prop :: TYPE IS [qualifier]
586/// KEY|UNIQUE}`). `qualifier` records which (if any) `NODE`/`REL`/
587/// `RELATIONSHIP` keyword was written, so the graph-type validator can
588/// enforce that a node type must not contain `REL`/
589/// `RELATIONSHIP`; an edge type must not contain `NODE`.
590#[derive(Debug, Clone, Copy, PartialEq, Eq)]
591pub struct GraphTypeInlineConstraint {
592 pub verb: GraphTypeInlineVerb,
593 pub qualifier: Option<GraphTypeEntityQualifier>,
594}
595
596#[derive(Debug, Clone, Copy, PartialEq, Eq)]
597pub enum GraphTypeInlineVerb {
598 Key,
599 Unique,
600}
601
602#[derive(Debug, Clone, Copy, PartialEq, Eq)]
603pub enum GraphTypeEntityQualifier {
604 Node,
605 Rel,
606}
607
608/// A `<node type reference>` / `<edge type reference>` (CIP-178): how a
609/// node/edge type spec's endpoint, or a constraint specification's `FOR`
610/// target, names the element type it applies to.
611#[derive(Debug, Clone, PartialEq)]
612pub enum GraphTypeElementRef {
613 /// `()` -- the any node/edge type.
614 Any,
615 /// `(alias)` / `()-[alias]->()` -- resolves to a previously declared
616 /// node/edge type alias (it must already be declared).
617 AliasRef(SmallName),
618 /// `[alias] (':'|IS) <label> ['=>'|IMPLIES]` -- an in-situ reference.
619 /// `implies` (`=>`/`IMPLIES` present) requires `label` to name an
620 /// already-declared identifying label; without it, the
621 /// label need not be declared. `alias` is only legal in constraint
622 /// `FOR`-clause context (forbidden on an edge type's own
623 /// endpoint references).
624 InSitu {
625 alias: Option<SmallName>,
626 label: SmallName,
627 implies: bool,
628 },
629}
630
631/// `[CONSTRAINT [<name>]] FOR <node/edge type reference> REQUIRE
632/// <property name spec> <constraint verb> [OPTIONS <map>]` (CIP-178
633/// `<constraint specification>`) -- also the target of a node/edge type
634/// spec's trailing inline `REQUIRE ...` list and a property's own inline
635/// `IS KEY`/`IS UNIQUE` (both rewritten to this same shape at parse time,
636/// per Rules 10-12).
637#[derive(Debug, Clone, PartialEq)]
638pub struct GraphTypeConstraintSpec {
639 pub name: Option<SmallName>,
640 pub target: GraphTypeElementRef,
641 /// True when `target` is an edge type reference (`FOR ()-[...]->()`);
642 /// false for a node type reference (`FOR (...)`).
643 pub is_edge: bool,
644 pub properties: Vec<SmallName>,
645 pub kind: GraphTypeConstraintVerb,
646 /// The parsed `<value type>` for a `PropertyType`-kind constraint,
647 /// `None` for every other kind.
648 pub property_type: Option<TypeExpr>,
649 /// The `OPTIONS` tail: absent, a literal map, or a whole-map parameter
650 /// (resolved before the body is captured/persisted).
651 pub options: OptionsForm,
652}
653
654#[derive(Debug, Clone, PartialEq, Eq)]
655pub enum GraphTypeConstraintVerb {
656 Key,
657 Unique,
658 Exists,
659 PropertyType,
660}
661
662/// CIP-135 conditional clause: `WHEN <pred> THEN { <body> } [WHEN <pred>
663/// THEN { <body> }]* [ELSE { <body> }]`. Each branch's `body`/`else_body`
664/// is itself a `<single-query>` (own `Statement`, possibly carrying its own
665/// `.union` chain).
666#[derive(Debug, Clone, PartialEq)]
667pub struct ConditionalClause {
668 pub branches: Vec<WhenBranch>,
669 pub else_body: Option<Statement>,
670}
671
672/// One `WHEN <predicate> THEN <single-query>` branch of a `ConditionalClause`.
673#[derive(Debug, Clone, PartialEq)]
674pub struct WhenBranch {
675 pub predicate: Expr,
676 pub body: Statement,
677}
678
679/// MATCH clause.
680#[derive(Debug, Clone, PartialEq)]
681pub struct MatchClause {
682 pub optional: bool,
683 /// CIP-51/CIP-60 match mode: whether relationship uniqueness (the
684 /// default `DIFFERENT RELATIONSHIPS`) is enforced across the whole
685 /// comma-separated graph pattern, or relaxed (`REPEATABLE ELEMENTS`).
686 pub match_mode: MatchMode,
687 pub pattern: Vec<PatternPath>,
688 /// CIP-79 variables named by a `USING SCAN <var>:<Label>` hint.
689 /// Relate's planner is not cost-based, but a scan hint is not a
690 /// mere plan preference here: an indexed equality seek and a label
691 /// scan genuinely answer differently for a zoned-datetime DST overlap
692 /// (the index keys on instant plus zone, `=` on the wall clock), so
693 /// the hint must reach the executor — the one hint family that does;
694 /// `USING INDEX` stops at the front-end fulfillability check and
695 /// `USING JOIN ON` at the plan-time notification, per the two
696 /// fields below.
697 pub using_scan: Vec<ScanHint>,
698 /// CIP-79 `USING INDEX [SEEK] <var>:<Label>(<prop>[, …])` hints. The
699 /// planner is not cost-based so they steer nothing, but the front end
700 /// still validates that each hint is *fulfillable* — Neo4j rejects an
701 /// undefined hint variable and an unfulfillable hint at compile time
702 /// (SemanticErrorPart2 "An index hint … is rejected"), which needs the
703 /// hint preserved here.
704 pub using_index: Vec<IndexHint>,
705 /// CIP-79 `USING JOIN ON <var>[, <var>…]` hints. The planner is not
706 /// cost-based so a join hint steers nothing — every one is
707 /// unfulfillable, which the `01N30` plan-time notification reports
708 /// (ADR-0363); retaining the hint here is what lets the IR carry it
709 /// to that detector.
710 pub using_join: Vec<JoinHint>,
711 pub where_expr: Option<Expr>,
712 /// `<search clause>`: `SEARCH <binding var ref> IN (VECTOR
713 /// INDEX <index name> FOR <expr> LIMIT <expr>) [SCORE AS <var>]`, a
714 /// subclause of `<match statement>`. The grammar allows the `<graph
715 /// pattern where clause>` to appear either before or after the search
716 /// clause with no semantic difference (CIP-224 "Canonical syntax"), so
717 /// the parser folds both orderings into this same `where_expr` field --
718 /// the source order isn't tracked in the AST.
719 pub search: Option<SearchClause>,
720}
721
722/// One `USING SCAN <variable>:<Label>` hint. The label is retained at the
723/// same fidelity as [`IndexHint`]'s properties, so the hint family keeps
724/// one shape; the planner's scan fork keys on the variable.
725#[derive(Debug, Clone, PartialEq, Eq)]
726pub struct ScanHint {
727 pub variable: SmallName,
728 pub label: SmallName,
729}
730
731/// One `USING INDEX [SEEK] <variable>:<Label>(<property>[, …])` hint.
732#[derive(Debug, Clone, PartialEq, Eq)]
733pub struct IndexHint {
734 pub variable: SmallName,
735 pub label: SmallName,
736 pub properties: Vec<SmallName>,
737}
738
739impl IndexHint {
740 /// The hinted property list as one text — `name`, `name, surname` —
741 /// the one spelling both the front end's unfulfillable-hint error
742 /// (42N76) and the plan-time `01N31` description render.
743 pub fn properties_text(&self) -> String {
744 self.properties
745 .iter()
746 .map(|property| property.to_string())
747 .collect::<Vec<_>>()
748 .join(", ")
749 }
750}
751
752/// One `USING JOIN ON <variable>[, <variable>…]` hint: the join key
753/// identifiers, in written order.
754#[derive(Debug, Clone, PartialEq, Eq)]
755pub struct JoinHint {
756 pub variables: Vec<SmallName>,
757}
758
759/// `<search clause>`: the `SEARCH ... IN (<source specification
760/// clause>) [SCORE AS ...]` subclause of `MatchClause`.
761///
762/// `binding_var`/`score_var` (and each nested `index_name`) are plain
763/// identifiers (never a general expression, a parameter, or a property
764/// access -- Rules 1, 4, 5) rather than `Expr`, matching the grammar's own
765/// `<binding variable reference>` / `<index name specification>` /
766/// `<binding variable>` productions.
767#[derive(Debug, Clone, PartialEq)]
768pub struct SearchClause {
769 /// `<binding variable reference>`: must name a variable declared by the
770 /// same `<match statement>`'s own pattern.
771 pub binding_var: SmallName,
772 /// `<source specification clause>`: one index search, or a
773 /// `COMBINE` of two or more weighted sources fused with WRRF.
774 pub spec: SearchSpec,
775 /// `[SCORE AS <binding variable>]` -- `None` when the score column is
776 /// omitted (results are still ordered by descending score either way).
777 pub score_var: Option<SmallName>,
778}
779
780/// `<source specification clause>`:
781/// `<index specification clause> | <combined specification clause>`.
782#[derive(Debug, Clone, PartialEq)]
783pub enum SearchSpec {
784 Index(SearchIndexSpec),
785 Combine(SearchCombineSpec),
786}
787
788/// `<index specification clause>`: `{ VECTOR | FULLTEXT } INDEX
789/// <index name> <index for and control clause>`.
790#[derive(Debug, Clone, PartialEq)]
791pub struct SearchIndexSpec {
792 /// CIP-225: which index kind the specification names.
793 pub kind: SearchKind,
794 /// `<index name specification>`: the literal name of an existing index.
795 pub index_name: SmallName,
796 /// `<for clause>`'s `<value expression>` -- the search query.
797 pub for_expr: Expr,
798 /// `WITH ANALYZER <expr>` (fulltext only).
799 pub analyzer: Option<Expr>,
800 /// CIP-240 "Vector Search with Single-stage Filtering": the optional
801 /// inner `WHERE <search condition>` between `FOR <expr>` and `LIMIT
802 /// <expr>`. Its `<search condition>` must decompose into one or more
803 /// `<binding variable reference> <static property reference> <simple
804 /// comp op> <arithmetic value expression>` predicates joined by `AND`
805 /// (or a form rewritable into that, e.g. `NOT x.prop` or flipped
806 /// operands) -- enforced by `relate_front::search_filter`, not here;
807 /// the parser accepts any general `<expression>` here, exactly like
808 /// `MatchClause.where_expr`.
809 pub inner_where: Option<Expr>,
810 /// `<offset clause>` (`SKIP`/`OFFSET`).
811 pub offset_expr: Option<Expr>,
812 /// `<limit clause>`'s `<value expression>` (mandatory for an index
813 /// source, in and out of a COMBINE).
814 pub limit_expr: Expr,
815}
816
817/// `<index specification clause>`: `{ VECTOR | FULLTEXT } INDEX`.
818#[derive(Debug, Clone, Copy, PartialEq, Eq)]
819pub enum SearchKind {
820 Vector,
821 Fulltext,
822}
823
824/// `<combined specification clause>`: `COMBINE ( <weighted source
825/// clause>, ... ) USING WRRF [ WITH CONSTANT <expr> ] [ LIMIT <expr> ]`.
826///
827/// `sources` holds two or more weighted source clauses (fewer is a
828/// parse error, raised where the list is parsed). A source may itself be a
829/// nested `<combined specification clause>`.
830#[derive(Debug, Clone, PartialEq)]
831pub struct SearchCombineSpec {
832 pub sources: Vec<SearchWeightedSource>,
833 /// `<constant specification clause>`'s `<value expression>` -- the WRRF
834 /// dampening constant; `None` means the default 60.
835 pub constant_expr: Option<Expr>,
836 /// The optional `<limit clause>` of the combined specification -- the n
837 /// highest-scoring results kept; `None` keeps all.
838 pub limit_expr: Option<Expr>,
839}
840
841/// `<weighted source clause>`:
842/// `<source specification clause> [ WEIGHT <value expression> ]`.
843#[derive(Debug, Clone, PartialEq)]
844pub struct SearchWeightedSource {
845 pub spec: SearchSpec,
846 /// `None` means the default weight 1.
847 pub weight_expr: Option<Expr>,
848}
849
850/// CIP-51/CIP-60 match mode: governs the default relationship-uniqueness
851/// pool that spans one MATCH clause's entire comma-separated graph pattern.
852#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
853pub enum MatchMode {
854 /// `MATCH DIFFERENT RELATIONSHIPS ...` (also the implicit default): no
855 /// two relationship slots anywhere in the graph pattern may bind to the
856 /// same physical relationship.
857 #[default]
858 DifferentRelationships,
859 /// `MATCH REPEATABLE ELEMENTS ...`: relaxes the relationship-uniqueness
860 /// pool entirely -- nodes and relationships may repeat freely, subject
861 /// only to each path's own path mode (which must resolve to `WALK`
862 /// under this match mode).
863 RepeatableElements,
864}
865
866/// CIP-51 path mode: an explicit restrictor on one path pattern's candidate
867/// bindings. `PatternPath::mode` is `None` when no explicit keyword was
868/// written -- the resolved default is `Walk`.
869#[derive(Debug, Clone, Copy, PartialEq, Eq)]
870pub enum PathMode {
871 /// Nodes and relationships may repeat freely (subject to the enclosing
872 /// match mode's own relationship-uniqueness pool, which under the
873 /// default `DIFFERENT RELATIONSHIPS` match mode still applies).
874 Walk,
875 /// No two relationship bindings in this one path may bind the same
876 /// relationship (already the effective default under `DIFFERENT
877 /// RELATIONSHIPS`, since that pool subsumes a single path's own).
878 Trail,
879 /// No two node bindings in this one path may bind the same node, except
880 /// where two connectors are juxtaposed at a shared boundary node.
881 Acyclic,
882 /// Like `Acyclic`, but the very first and very last node of the path may
883 /// coincide (an equijoin on the endpoints).
884 Simple,
885}
886
887/// The `<number of paths>`/`<number of groups>` non-terminal (extended
888/// by CIP-191 to accept a `$parameter`). A literal is validated
889/// (`> 0`) at parse time; a parameter is validated at runtime once its value
890/// is known (CIP-191 "Non-negative integer" rule).
891#[derive(Debug, Clone, PartialEq)]
892pub enum PathCount {
893 Literal(u32),
894 Parameter(String),
895}
896
897/// CIP-73 path selector prefix (`<path search prefix>`). `PatternPath` has
898/// no selector when this is `None` -- the path pattern is then
899/// non-selective, equivalent to an implicit `ALL`.
900#[derive(Debug, Clone, PartialEq)]
901pub enum PathSelector {
902 /// `ALL [path mode] [PATH|PATHS]` -- also the implicit default.
903 All,
904 /// `ANY [<number of paths>] [path mode] [PATH|PATHS]`; `None` count
905 /// defaults to 1.
906 Any(Option<PathCount>),
907 /// `ANY SHORTEST [path mode] [PATH|PATHS]` -- normalizes to `SHORTEST 1
908 /// [path mode] PATH`.
909 AnyShortest,
910 /// `ALL SHORTEST [path mode] [PATH|PATHS]` -- normalizes to `SHORTEST 1
911 /// [path mode] GROUP`.
912 AllShortest,
913 /// `SHORTEST <number of paths> [path mode] [PATH|PATHS]` (`group` false)
914 /// or `SHORTEST [<number of groups>] [path mode] [PATH|PATHS]
915 /// (GROUP|GROUPS)` (`group` true); `count` is `None` only in the GROUP
916 /// form (defaults to 1).
917 Shortest {
918 count: Option<PathCount>,
919 group: bool,
920 },
921}
922
923/// CREATE clause.
924#[derive(Debug, Clone, PartialEq)]
925pub struct CreateClause {
926 pub pattern: Vec<PatternPath>,
927 /// True when this clause was written as `INSERT` (CIP-114) rather than
928 /// `CREATE` -- executed identically in every other respect, but the
929 /// `+labels` side-effect stat is *not* subject to CREATE's row-scoped
930 /// same-label-name dedup (empirically, INSERT counts every label
931 /// application on every node it creates, unlike CREATE/MERGE).
932 pub is_insert: bool,
933}
934
935/// MERGE clause.
936#[derive(Debug, Clone, PartialEq)]
937pub struct MergeClause {
938 pub pattern: PatternPath,
939 pub on_create: Vec<SetItem>,
940 pub on_match: Vec<SetItem>,
941}
942
943/// DELETE clause.
944#[derive(Debug, Clone, PartialEq)]
945pub struct DeleteClause {
946 pub detach: bool,
947 pub expressions: Vec<Expr>,
948}
949
950/// SET clause.
951#[derive(Debug, Clone, PartialEq)]
952pub struct SetClause {
953 pub items: Vec<SetItem>,
954}
955
956/// A single item in a SET clause.
957#[derive(Debug, Clone, PartialEq)]
958pub struct SetItem {
959 pub property: Option<PropertyAccess>,
960 pub variable: Option<SmallName>,
961 /// Each element is a `LabelExpr::Label` (static, `SET n:A`) or
962 /// `LabelExpr::Dynamic` (CIP-162, `SET n:$(<expr>)`/`SET n IS $(<expr>)`)
963 /// atom -- the parser never produces any other `LabelExpr` variant here
964 /// (no `&`/`|`/`!`/`%`/grouping). See `RemoveItem::labels`.
965 pub labels: Vec<LabelExpr>,
966 pub value: Option<Expr>,
967 pub merge: bool,
968 /// True if this label item used the CIP-126 `IS` keyword (`SET n IS A`)
969 /// rather than `:` (`SET n:A`). Only meaningful when `labels` is
970 /// non-empty. Used for the CIP-40/CIP-126 statement-level rule that
971 /// forbids mixing `IS` with a colon-conjunction (`:A:B`) anywhere in the
972 /// same statement.
973 pub is_keyword: bool,
974 /// CIP-162 "Alternatives" section: `SET labels(<expr>) = / += / -=
975 /// <expr>`. Per the proposal's own text this was never shipped in Neo4j
976 /// ("we have decided to implement the rest first, and leave this as a
977 /// potential future extension") -- Relate implements it anyway as
978 /// the CIP's stated target semantics. `Some((target_expr, op))` when
979 /// this item is that form, with `target_expr` the node expression
980 /// inside `labels(...)` and `value` (above) holding the RHS list
981 /// expression.
982 pub labels_function: Option<(Expr, LabelsFunctionOp)>,
983}
984
985/// The operator of a `SET labels(<expr>) <op> <expr>` item.
986#[derive(Debug, Clone, Copy, PartialEq, Eq)]
987pub enum LabelsFunctionOp {
988 /// `=` -- replace the full label set.
989 Overwrite,
990 /// `+=` -- add every listed label, keep existing ones.
991 Extend,
992 /// `-=` -- remove every listed label that is present.
993 Remove,
994}
995
996/// REMOVE clause.
997#[derive(Debug, Clone, PartialEq)]
998pub struct RemoveClause {
999 pub items: Vec<RemoveItem>,
1000}
1001
1002/// A single item in a REMOVE clause.
1003#[derive(Debug, Clone, PartialEq)]
1004pub struct RemoveItem {
1005 pub property: Option<PropertyAccess>,
1006 pub variable: Option<SmallName>,
1007 /// See `SetItem::labels` (CIP-162 dynamic-label atoms allowed here too).
1008 pub labels: Vec<LabelExpr>,
1009 /// See `SetItem::is_keyword`.
1010 pub is_keyword: bool,
1011}
1012
1013/// RETURN clause.
1014#[derive(Debug, Clone, PartialEq)]
1015pub struct ReturnClause {
1016 pub group_by: Option<GroupBySpec>,
1017 pub distinct: bool,
1018 pub items: Vec<ReturnItem>,
1019 pub order_by: Vec<OrderByItem>,
1020 pub skip: Option<Expr>,
1021 pub limit: Option<Expr>,
1022}
1023
1024/// A single item in a RETURN clause.
1025#[derive(Debug, Clone, PartialEq)]
1026pub struct ReturnItem {
1027 pub expr: Expr,
1028 pub alias: Option<SmallName>,
1029 pub all: bool,
1030 pub source_text: Option<String>,
1031}
1032
1033/// An item in ORDER BY.
1034#[derive(Debug, Clone, PartialEq)]
1035pub struct OrderByItem {
1036 pub expr: Expr,
1037 pub descending: bool,
1038}
1039
1040/// Which surface syntax produced a `WithClause`. Plain `WITH`, CIP-206's
1041/// `LET`, and CIP-203's `FILTER` all desugar into the same `WithClause` so
1042/// they share WITH's projection/aggregation/ORDER BY/SKIP/LIMIT/WHERE
1043/// execution machinery and its generic variable-scope tracking -- but LET
1044/// and FILTER each carry restrictions ordinary WITH does not (LET: no
1045/// shadowing of an in-scope variable, no sibling/forward/self reference
1046/// within one LET's item list, no aggregation function in a value
1047/// expression; FILTER: its search condition's declared type must be
1048/// Boolean). The origin is recorded so the validation passes enforcing
1049/// those extra rules only fire for the syntax that actually carries them.
1050#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1051pub enum WithOrigin {
1052 #[default]
1053 Explicit,
1054 Let,
1055 Filter,
1056}
1057
1058/// `<group by clause>` on RETURN/WITH.
1059#[derive(Debug, Clone, PartialEq)]
1060pub enum GroupBySpec {
1061 /// `GROUP BY <expr> [, <expr>...]`
1062 Keys(Vec<Expr>),
1063 /// `GROUP BY ()` -- the empty grouping set: one global group.
1064 Empty,
1065 /// `GROUP BY ALL` -- every non-aggregating return item is a key.
1066 All,
1067}
1068
1069/// WITH clause.
1070#[derive(Debug, Clone, PartialEq)]
1071pub struct WithClause {
1072 pub group_by: Option<GroupBySpec>,
1073 pub distinct: bool,
1074 pub items: Vec<ReturnItem>,
1075 pub order_by: Vec<OrderByItem>,
1076 pub skip: Option<Expr>,
1077 pub limit: Option<Expr>,
1078 pub where_expr: Option<Expr>,
1079 pub origin: WithOrigin,
1080}
1081
1082/// One stage of a CIP-168 standalone `<order by and page statement>`.
1083/// Neo4j 2026.05 accepts `ORDER BY`/`OFFSET`/`SKIP`/`LIMIT` in any order
1084/// at the start of the clause and applies them sequentially in the order
1085/// written -- not the fixed ORDER-BY-then-OFFSET-then-LIMIT semantic
1086/// order the CIP-168 text describes (e.g. `LIMIT 3 OFFSET 1` keeps 3
1087/// rows then drops the first 1 of those, rather than offsetting first).
1088/// A `Vec<PageStage>` records exactly the
1089/// written sequence so execution can replay it faithfully.
1090#[derive(Debug, Clone, PartialEq)]
1091pub enum PageStage {
1092 OrderBy(Vec<OrderByItem>),
1093 Skip(Expr),
1094 Limit(Expr),
1095}
1096
1097/// CIP-168: a standalone `<order by and page statement>`. See
1098/// `Clause::StandaloneOrderBy`.
1099#[derive(Debug, Clone, PartialEq)]
1100pub struct StandaloneOrderByClause {
1101 pub stages: Vec<PageStage>,
1102}
1103
1104/// UNWIND clause. A `FOR <variable> IN <expression>`
1105/// clause normalizes here at parse time -- the same expr/alias pair with
1106/// [`UnwindClause::for_syntax`] recording the source spelling -- so every
1107/// downstream consumer (validation, lowering, planning, execution) treats
1108/// the two spellings identically, exactly as the CIP requires (no new
1109/// operators). The flag is the parse-spelling record the FOREACH-body
1110/// renderer reads (`FOR`, not `UNWIND`, in the 42I01 text) — the one
1111/// consumer that must distinguish the spellings.
1112#[derive(Debug, Clone, PartialEq)]
1113pub struct UnwindClause {
1114 pub expr: Expr,
1115 pub alias: SmallName,
1116 /// True when the clause was written `FOR <variable> IN <expression>`
1117 /// (CIP-250) rather than `UNWIND <expression> AS <variable>`.
1118 pub for_syntax: bool,
1119}
1120
1121/// The DDL index kind (CIP-11 RANGE/POINT/TEXT, CIP-38 FULLTEXT, the
1122/// pre-existing VECTOR, and the label/type-token LOOKUP index).
1123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1124pub enum IndexKind {
1125 Range,
1126 Point,
1127 Text,
1128 Fulltext,
1129 Lookup,
1130 Vector,
1131}
1132
1133impl IndexKind {
1134 /// The canonical lowercase tag persisted in
1135 /// `relate_storage::Index::index_type` -- also the tag the engine
1136 /// switches on to decide which (if any) in-memory acceleration
1137 /// structure to build for a given index (`Engine::rebuild_indexes`).
1138 /// Unchanged for `Point`/`Vector` from before CIP-11 so existing
1139 /// vector/point index acceleration keeps working untouched; `Range`
1140 /// replaces the old ad hoc `"secondary"` tag (still accepted as a
1141 /// legacy alias when reading it back).
1142 pub fn storage_tag(&self) -> &'static str {
1143 match self {
1144 IndexKind::Range => "range",
1145 IndexKind::Point => "point",
1146 IndexKind::Text => "text",
1147 IndexKind::Fulltext => "fulltext",
1148 IndexKind::Lookup => "lookup",
1149 IndexKind::Vector => "vector",
1150 }
1151 }
1152
1153 /// The upper-case display name Neo4j's `SHOW INDEXES` `type` column
1154 /// uses.
1155 pub fn display_name(&self) -> &'static str {
1156 match self {
1157 IndexKind::Range => "RANGE",
1158 IndexKind::Point => "POINT",
1159 IndexKind::Text => "TEXT",
1160 IndexKind::Fulltext => "FULLTEXT",
1161 IndexKind::Lookup => "LOOKUP",
1162 IndexKind::Vector => "VECTOR",
1163 }
1164 }
1165}
1166
1167/// Which kind of graph element a CREATE INDEX / CREATE CONSTRAINT `FOR`
1168/// pattern targets (CIP-11's relationship-pattern generalization: `FOR
1169/// (n:Label)` vs. `FOR ()-[r:TYPE]-()` in all four direction spellings).
1170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1171pub enum SchemaEntityType {
1172 Node,
1173 Relationship,
1174}
1175
1176impl SchemaEntityType {
1177 /// The upper-case display value Neo4j's `SHOW INDEXES`/`SHOW
1178 /// CONSTRAINTS` `entityType` column uses.
1179 pub fn as_str(&self) -> &'static str {
1180 match self {
1181 SchemaEntityType::Node => "NODE",
1182 SchemaEntityType::Relationship => "RELATIONSHIP",
1183 }
1184 }
1185}
1186
1187/// The name of an index or constraint in CREATE INDEX / CREATE CONSTRAINT /
1188/// DROP INDEX / DROP CONSTRAINT: either a literal identifier or a `$param`
1189/// reference resolved against the query's parameter map at execution time
1190/// (CIP-134).
1191#[derive(Debug, Clone, PartialEq)]
1192pub enum SchemaName {
1193 Literal(String),
1194 Parameter(String),
1195}
1196
1197/// The optional `OPTIONS` tail of a schema DDL command (ADR-0489):
1198/// the three states the old `options` + `options_param` pair
1199/// encoded in a comment only.
1200#[derive(Debug, Clone, PartialEq)]
1201pub enum OptionsForm {
1202 /// No `OPTIONS` clause at all.
1203 Absent,
1204 /// `OPTIONS { key: <value expression>, ... }`: lowered and evaluated at
1205 /// execution time.
1206 Literal(Vec<(String, Expr)>),
1207 /// `OPTIONS $param`: the parameter must evaluate to a MAP at execution
1208 /// time, whose entries become the command's literal options.
1209 Parameter(String),
1210}
1211
1212impl OptionsForm {
1213 /// The literal map's entries — `None` for the two forms that carry no
1214 /// literal map, so no caller can mistake an absent clause or an
1215 /// unresolved `$param` for an empty map.
1216 pub fn literal(&self) -> Option<&[(String, Expr)]> {
1217 match self {
1218 Self::Literal(entries) => Some(entries),
1219 Self::Absent | Self::Parameter(_) => None,
1220 }
1221 }
1222
1223 /// The unresolved parameter's name, if this is that form.
1224 pub fn parameter(&self) -> Option<&str> {
1225 match self {
1226 Self::Parameter(name) => Some(name),
1227 Self::Absent | Self::Literal(_) => None,
1228 }
1229 }
1230
1231 /// The literal map's entries for in-place rewriting — `None` for the two
1232 /// forms that carry no literal map, the mutable twin of [`Self::literal`].
1233 pub fn literal_mut(&mut self) -> Option<&mut [(String, Expr)]> {
1234 match self {
1235 Self::Literal(entries) => Some(entries),
1236 Self::Absent | Self::Parameter(_) => None,
1237 }
1238 }
1239}
1240
1241/// CREATE INDEX clause.
1242#[derive(Debug, Clone, PartialEq)]
1243pub struct CreateIndexClause {
1244 pub name: Option<SchemaName>,
1245 pub entity_type: SchemaEntityType,
1246 /// Node labels, or (for a relationship index) relationship types, the
1247 /// index applies to. More than one entry only for the `A|B` disjunctive
1248 /// form (CIP-38/CIP-235); empty for a label-less/type-less LOOKUP index
1249 /// (`FOR (n)` / `FOR ()-[r]-()`).
1250 pub labels: Vec<SmallName>,
1251 pub properties: Vec<SmallName>,
1252 pub if_not_exists: bool,
1253 pub kind: IndexKind,
1254 /// True when the property list was written as `ON EACH [...]` (CIP-38
1255 /// FULLTEXT) rather than a plain `ON (...)` / paren-less `ON ...` list.
1256 pub on_each: bool,
1257 /// `WITH [var.prop1, var.prop2, ...]` (CIP-235): additional properties
1258 /// available for single-stage filtering on a VECTOR index, following
1259 /// the `ON` vector property. Always empty for every other index kind
1260 /// and for a vector index that doesn't use the clause.
1261 pub with_properties: Vec<SmallName>,
1262 /// The `OPTIONS` tail: absent, a literal map, or a whole-map parameter
1263 /// (resolved at execution time).
1264 pub options: OptionsForm,
1265}
1266
1267/// DROP INDEX clause.
1268#[derive(Debug, Clone, PartialEq)]
1269pub struct DropIndexClause {
1270 pub name: SchemaName,
1271 pub if_exists: bool,
1272 /// Legacy `DROP INDEX ON :Label(property)` target.
1273 pub legacy_target: Option<(SmallName, SmallName)>,
1274}
1275
1276/// `SHOW [ALL|RANGE|POINT|TEXT|FULLTEXT|VECTOR|LOOKUP] INDEXES [YIELD ...]
1277/// [WHERE ...]` (CIP-11). Mirrors `ShowConstraintsClause`; `kind_filter`
1278/// is `None` for bare `SHOW INDEXES`/`SHOW ALL INDEXES` (every index kind).
1279#[derive(Debug, Clone, PartialEq)]
1280pub struct ShowIndexesClause {
1281 pub kind_filter: Option<IndexKind>,
1282 pub yields: YieldList,
1283 pub where_expr: Option<Expr>,
1284 /// `ORDER BY`/`SKIP`/`LIMIT` written directly on the `YIELD` (before
1285 /// any trailing `WHERE`), same paging sub-grammar and rationale as
1286 /// `ShowConstraintsClause::stages`.
1287 pub stages: Vec<PageStage>,
1288}
1289
1290/// CREATE CONSTRAINT clause.
1291#[derive(Debug, Clone, PartialEq)]
1292pub struct CreateConstraintClause {
1293 pub name: Option<SchemaName>,
1294 pub entity_type: SchemaEntityType,
1295 pub label: SmallName,
1296 pub variable: SmallName,
1297 pub properties: Vec<SmallName>,
1298 pub constraint_type: String, // "unique", "exists", "key", "propertyType"
1299 pub if_not_exists: bool,
1300 /// The parsed `<value type>` for a `REQUIRE (n.prop) IS :: <type>` /
1301 /// `IS TYPED <type>` property type constraint (CIP-85), `None` for
1302 /// every other `constraint_type`.
1303 pub property_type: Option<TypeExpr>,
1304 /// The `OPTIONS` tail: absent, a literal map, or a whole-map parameter
1305 /// (resolved at execution time).
1306 pub options: OptionsForm,
1307 /// The target label for a `REQUIRE <alias>:<Label>` label
1308 /// existence constraint (`constraint_type` one of `"labelExistence"`/
1309 /// `"sourceLabelExistence"`/`"targetLabelExistence"`), `None` for
1310 /// every other `constraint_type`.
1311 pub enforced_label: Option<SmallName>,
1312}
1313
1314/// DROP CONSTRAINT clause.
1315#[derive(Debug, Clone, PartialEq)]
1316pub struct DropConstraintClause {
1317 pub name: SchemaName,
1318 pub if_exists: bool,
1319}
1320
1321/// FOREACH clause.
1322#[derive(Debug, Clone, PartialEq)]
1323pub struct ForeachClause {
1324 pub variable: SmallName,
1325 pub list_expr: Expr,
1326 pub clauses: Vec<Clause>,
1327}
1328
1329/// LOAD CSV clause.
1330#[derive(Debug, Clone, PartialEq)]
1331pub struct LoadCSVClause {
1332 pub with_headers: bool,
1333 pub source: Expr,
1334 pub alias: SmallName,
1335 pub field_terminator: Option<String>,
1336}
1337
1338/// CALL { ... } subquery clause.
1339#[derive(Debug, Clone, PartialEq)]
1340pub struct CallSubqueryClause {
1341 pub statement: Statement,
1342 /// CIP-141 variable scope clause: `None` for a naked `CALL { ... }`
1343 /// (the deprecated legacy form, where an `IMPORTING WITH` as the
1344 /// subquery's own first clause is the only way to correlate outer
1345 /// variables in); `Some(CallScope::...)` for `CALL (...) { ... }`.
1346 pub scope: CallScope,
1347 /// `OPTIONAL CALL { ... }` -- when the inline subquery yields
1348 /// zero rows for a given outer row, that outer row is null-padded
1349 /// (every column the subquery would export set to `NULL`) instead of
1350 /// being dropped.
1351 pub optional: bool,
1352 /// CIP-32/CIP-34/CIP-198/CIP-30 trailing `IN [<concExpr>] CONCURRENT?
1353 /// TRANSACTIONS [OF <n> ROW(S)] [ON ERROR ...] [REPORT STATUS AS
1354 /// <var>]` production. `None` for a plain `CALL { ... }` subquery.
1355 pub in_transactions: Option<InTransactionsClause>,
1356}
1357
1358/// The full `IN [<concExpr>] CONCURRENT? TRANSACTIONS [OF <n> ROW|ROWS] [ON
1359/// ERROR ...] [REPORT STATUS AS <var>]` production trailing a CALL
1360/// subquery. Parsed in its entirety (CIP-32 base batching, CIP-34
1361/// concurrency, CIP-198 retry, CIP-30 status/error) so later CIPs only need
1362/// to add validation/execution on top of this AST -- CIP-32 itself only
1363/// implements sequential batching plus the nesting/preceding-write
1364/// restrictions; concurrency and retry are parsed but currently execute as
1365/// plain sequential batching (see `Engine`'s `Clause::CallSubquery` arm).
1366#[derive(Debug, Clone, PartialEq)]
1367pub struct InTransactionsClause {
1368 /// `IN TRANSACTIONS` (no `CONCURRENT`) vs `IN [<expr>] CONCURRENT
1369 /// TRANSACTIONS` (CIP-34).
1370 pub concurrency: Concurrency,
1371 /// `OF <n> ROW|ROWS`. `None` means the batch size is
1372 /// implementation-chosen (batching[6]).
1373 pub batch_size: Option<Expr>,
1374 /// `ON ERROR CONTINUE|BREAK|FAIL|RETRY ...`. Defaults to `Fail` when
1375 /// `ON ERROR` is omitted.
1376 pub on_error: OnErrorMode,
1377 /// `REPORT STATUS AS <var>` (CIP-30).
1378 pub report_status: Option<SmallName>,
1379 /// CIP-260 `DISJOINT BY <exprs> | AUTO | NONE`. A concurrency hint that
1380 /// partitions the input rows by the listed key expressions (or lets the
1381 /// implementation choose / disables disjointness); it never changes the
1382 /// statement's result. Only legal on the `CONCURRENT` form.
1383 pub disjoint: Option<DisjointBy>,
1384}
1385
1386/// `DISJOINT BY` operand.
1387#[derive(Debug, Clone, PartialEq)]
1388pub enum DisjointBy {
1389 /// `DISJOINT BY (<expr>, ...)`: partition rows by these deterministic
1390 /// key expressions.
1391 Expressions(Vec<Expr>),
1392 /// `DISJOINT BY AUTO`: the implementation picks the partitioning.
1393 Auto,
1394 /// `DISJOINT BY NONE`: no disjointness requirement.
1395 None,
1396}
1397
1398impl InTransactionsClause {
1399 /// Every value expression of the `IN TRANSACTIONS` tail, in visit
1400 /// order: the CIP-34 concurrency value, the CIP-32 batch size, the
1401 /// CIP-198 retry duration and the `DISJOINT BY` key
1402 /// expressions. The exhaustive matches on the three operand enums are
1403 /// the slot list: a new operand variant is a compile error here until
1404 /// its expression is enumerated, so a consumer cannot drift from the
1405 /// parser shape.
1406 pub fn exprs(&self) -> Vec<&Expr> {
1407 let mut out = Vec::new();
1408 match &self.concurrency {
1409 Concurrency::Value(expr) => out.push(expr),
1410 Concurrency::Sequential | Concurrency::DefaultUnspecified => {}
1411 }
1412 out.extend(self.batch_size.as_ref());
1413 match &self.on_error {
1414 OnErrorMode::Retry { duration, .. } => out.extend(duration.as_ref()),
1415 OnErrorMode::Fail | OnErrorMode::Continue | OnErrorMode::Break => {}
1416 }
1417 match &self.disjoint {
1418 Some(DisjointBy::Expressions(keys)) => out.extend(keys),
1419 Some(DisjointBy::Auto | DisjointBy::None) | None => {}
1420 }
1421 out
1422 }
1423}
1424
1425/// CIP-34 `IN [<concExpr>] CONCURRENT? TRANSACTIONS` concurrency modifier.
1426#[derive(Debug, Clone, PartialEq)]
1427pub enum Concurrency {
1428 /// No `CONCURRENT` keyword -- sequential (base CIP-32 form).
1429 Sequential,
1430 /// `CONCURRENT` with no explicit value -- implementation-chosen
1431 /// concurrency.
1432 DefaultUnspecified,
1433 /// `<expr> CONCURRENT` -- an explicit concurrency value.
1434 Value(Expr),
1435}
1436
1437/// `ON ERROR ...` mode.
1438#[derive(Debug, Clone, PartialEq)]
1439pub enum OnErrorMode {
1440 /// The default when `ON ERROR` is omitted entirely.
1441 Fail,
1442 Continue,
1443 Break,
1444 /// CIP-198 `RETRY [FOR]? [<dur> SEC|SECOND|SECONDS]? [THEN
1445 /// CONTINUE|BREAK|FAIL]?`.
1446 Retry {
1447 /// `FOR <dur> SEC[OND[S]]`; `None` means the retry duration is
1448 /// implementation-chosen.
1449 duration: Option<Expr>,
1450 /// The mode to fall back to once retries are exhausted. Defaults to
1451 /// `Fail` when no `THEN` clause is given (CIP-198's documented
1452 /// deviation from a naive "defaults to CONTINUE" reading).
1453 fallback: RetryFallback,
1454 },
1455}
1456
1457/// The `THEN CONTINUE|BREAK|FAIL` fallback mode of `ON ERROR RETRY`.
1458#[derive(Debug, Clone, PartialEq)]
1459pub enum RetryFallback {
1460 Fail,
1461 Continue,
1462 Break,
1463}
1464
1465/// The `(...)` variable scope clause on a `CALL` subquery (CIP-141).
1466#[derive(Debug, Clone, PartialEq)]
1467pub enum CallScope {
1468 /// Naked `CALL { ... }` -- no scope clause at all.
1469 None,
1470 /// `CALL (*) { ... }` -- import every variable currently in scope.
1471 Wildcard,
1472 /// `CALL (a, b) { ... }` / `CALL () { ... }` -- import exactly these
1473 /// variables (the list may be empty).
1474 Vars(Vec<SmallName>),
1475}
1476
1477/// `USE <graph-expr>` clause.
1478#[derive(Debug, Clone, PartialEq)]
1479pub struct UseClause {
1480 pub graph_expr: Expr,
1481}
1482
1483/// `SHOW FUNCTIONS [YIELD ...] [WHERE ...]` — the built-in function catalog
1484/// (CIP-245/CIP-247/CIP-263 discoverability scenarios). A minimal, dedicated
1485/// clause rather than a generic SHOW-command framework: only the function
1486/// catalog is modeled, not indexes/constraints/databases (out of this
1487/// batch's scope). `where_expr` is embedded here (rather than requiring a
1488/// standalone `WHERE` clause, which this AST has no variant for — WHERE is
1489/// always embedded in the clause that produces its rows, matching
1490/// `MatchClause`) so `SHOW FUNCTIONS YIELD name WHERE name = 'x' RETURN
1491/// name` parses as a single clause producing already-filtered rows.
1492#[derive(Debug, Clone, PartialEq)]
1493pub struct ShowFunctionsClause {
1494 pub yields: YieldList,
1495 pub where_expr: Option<Expr>,
1496 /// The YIELD's own paging sub-grammar, written between the YIELD list
1497 /// and the trailing `WHERE` (live Neo4j
1498 /// accepts that order for every SHOW command).
1499 pub stages: Vec<PageStage>,
1500 /// `[ALL | BUILT IN | USER DEFINED]` scope filter (CIP-84/CIP-157
1501 /// `SHOW BUILT IN FUNCTIONS` / `SHOW USER DEFINED FUNCTIONS`
1502 /// scenarios). `All` (the default) and `BuiltIn` are equivalent for
1503 /// Relate, which ships only built-in functions; `UserDefined`
1504 /// always yields an empty catalog (no way to register a UDF).
1505 pub scope: FunctionScope,
1506 /// `EXECUTABLE [BY <user>]`, when written.
1507 pub executable: Option<ExecutableBy>,
1508}
1509
1510/// The `EXECUTABLE BY <user>` selector of `SHOW FUNCTIONS`/`SHOW
1511/// PROCEDURES`: the commands a user may execute. The bare `EXECUTABLE` form
1512/// applies no privilege filter, so it is the same state as writing no
1513/// selector at all (`None` on the clause) and has no variant of its own.
1514#[derive(Debug, Clone, PartialEq)]
1515pub enum ExecutableBy {
1516 /// `EXECUTABLE BY <user>` -- the named user.
1517 User(String),
1518 /// `EXECUTABLE BY CURRENT USER` -- the session's own user.
1519 Current,
1520}
1521
1522/// Scope filter for `SHOW [ALL | BUILT IN | USER DEFINED] FUNCTIONS`
1523/// (CIP-84/CIP-157). See `ShowFunctionsClause::scope`.
1524#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1525pub enum FunctionScope {
1526 #[default]
1527 All,
1528 BuiltIn,
1529 UserDefined,
1530}
1531
1532/// `SHOW [<type filter>] CONSTRAINTS [YIELD ...] [WHERE ...]` (CIP-85's
1533/// observation surface, needed by CIP-100 to expose a property type
1534/// constraint's normalized `propertyType`; the `<type filter>` grammar is
1535/// CIP-62/CIP-64/CIP-74's `[ALL] [NODE|REL[ATIONSHIP]] [PROPERTY]?
1536/// (UNIQUE[NESS]|KEY|EXIST[ENCE]|TYPE)` surface). Mirrors
1537/// `ShowFunctionsClause` otherwise.
1538#[derive(Debug, Clone, PartialEq)]
1539pub struct ShowConstraintsClause {
1540 pub yields: YieldList,
1541 pub where_expr: Option<Expr>,
1542 pub type_filter: ConstraintTypeFilter,
1543 /// `ORDER BY`/`SKIP`/`LIMIT` written directly on the `YIELD` (before
1544 /// any trailing `WHERE`) as part of the `YIELD`'s own paging
1545 /// sub-grammar, e.g. `YIELD name ORDER BY
1546 /// name WHERE ... RETURN ...` -- distinct from a `SHOW ... YIELD ...`
1547 /// followed by a separate top-level `ORDER BY`/`RETURN ... ORDER BY`
1548 /// clause, which parses as its own `StandaloneOrderBy`/`Return` clause
1549 /// instead and never populates this field.
1550 pub stages: Vec<PageStage>,
1551}
1552
1553/// The entity half of a `SHOW <type filter> CONSTRAINTS` filter -- `Any`
1554/// for bare `SHOW CONSTRAINTS`/`SHOW ALL CONSTRAINTS` or a kind-only
1555/// filter with no `NODE`/`REL[ATIONSHIP]` prefix.
1556#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1557pub enum ConstraintEntityFilter {
1558 Any,
1559 Node,
1560 Relationship,
1561}
1562
1563/// The constraint-kind half of a `SHOW <type filter> CONSTRAINTS` filter.
1564/// `None` (on `ConstraintTypeFilter::kind`) means every kind (bare `SHOW
1565/// CONSTRAINTS`/`SHOW ALL CONSTRAINTS`/`SHOW NODE CONSTRAINTS`).
1566#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1567pub enum ConstraintKindFilter {
1568 /// `UNIQUE`/`UNIQUENESS`, optionally `PROPERTY`-prefixed (CIP-74) --
1569 /// matches `constraint_type == "unique"`.
1570 Unique,
1571 /// `KEY` -- matches `constraint_type == "key"`. Never combines with
1572 /// `PROPERTY`.
1573 Key,
1574 /// `TYPE`, optionally `PROPERTY`-prefixed -- matches `constraint_type
1575 /// == "propertyType"` (CIP-85/CIP-100).
1576 PropertyType,
1577 /// `EXIST`/`EXISTENCE` -- property existence plus the four
1578 /// label/endpoint-label kinds (CIP-187's filtering table: a bare
1579 /// `EXIST[ENCE]`/`NODE EXIST[ENCE]` matches `NODE_LABEL_EXISTENCE`
1580 /// too).
1581 Existence,
1582 /// `PROPERTY EXIST[ENCE]` (CIP-187) -- property existence only
1583 /// (`constraint_type == "exists"`), never the label/endpoint-label
1584 /// kinds the bare [`Self::Existence`] also admits. Its own variant —
1585 /// the grammar distinguishes the two spellings at parse time, so the
1586 /// AST carries the distinction typed, never as a side-channel bool
1587 /// beside the kind.
1588 PropertyExistence,
1589}
1590
1591/// `SHOW <type filter> CONSTRAINTS` -- `entity` narrows by `entityType`,
1592/// `kind` narrows by constraint kind. `ConstraintTypeFilter::all()` (empty
1593/// entity, no kind) is the default for bare `SHOW CONSTRAINTS`/`SHOW ALL
1594/// CONSTRAINTS`, matching every constraint.
1595#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1596pub struct ConstraintTypeFilter {
1597 pub entity: ConstraintEntityFilter,
1598 pub kind: Option<ConstraintKindFilter>,
1599}
1600
1601impl ConstraintTypeFilter {
1602 pub fn all() -> Self {
1603 ConstraintTypeFilter {
1604 entity: ConstraintEntityFilter::Any,
1605 kind: None,
1606 }
1607 }
1608}
1609
1610/// `SHOW DATABASE[S] [<filter>] [YIELD ...] [WHERE ...]` (CIP-42/CIP-68).
1611#[derive(Debug, Clone, PartialEq)]
1612pub struct ShowDatabasesClause {
1613 pub filter: DatabaseFilter,
1614 pub yields: YieldList,
1615 pub where_expr: Option<Expr>,
1616 pub stages: Vec<PageStage>,
1617}
1618
1619/// Which database(s) a `SHOW DATABASE[S]` clause reports (CIP-68's
1620/// `DEFAULT`/`HOME` singular-only forms).
1621#[derive(Debug, Clone, PartialEq)]
1622pub enum DatabaseFilter {
1623 /// Bare `SHOW DATABASE[S]` -- every database.
1624 All,
1625 /// `SHOW DEFAULT DATABASE` -- singular only, CIP-68 rejects the plural
1626 /// `SHOW DEFAULT DATABASES`.
1627 Default,
1628 /// `SHOW HOME DATABASE` -- singular only, same restriction as `Default`.
1629 Home,
1630 /// `SHOW DATABASE[S] <name>` -- one named database.
1631 Named(SchemaName),
1632}
1633
1634/// `SHOW [ALL|POPULATED] ROLE[S] [WITH USER[S]] [YIELD ...] [WHERE ...]`
1635/// (CIP-68).
1636#[derive(Debug, Clone, PartialEq)]
1637pub struct ShowRolesClause {
1638 pub modifier: RoleModifier,
1639 /// `WITH USER[S]` -- when true, the catalog carries one row per
1640 /// (role, member) pair (adding the `member` column) instead of one row
1641 /// per role.
1642 pub with_users: bool,
1643 pub yields: YieldList,
1644 pub where_expr: Option<Expr>,
1645 pub stages: Vec<PageStage>,
1646}
1647
1648/// The `[ALL|POPULATED]` modifier of `SHOW ROLE[S]` -- `Any` (bare `SHOW
1649/// ROLE[S]`) and `All` (`SHOW ALL ROLE[S]`) report the identical row set
1650/// (every role); `Populated` narrows to roles with at least one member.
1651#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1652pub enum RoleModifier {
1653 Any,
1654 All,
1655 Populated,
1656}
1657
1658/// `SHOW SERVER[S] [YIELD ...] [WHERE ...]` (CIP-68).
1659#[derive(Debug, Clone, PartialEq)]
1660pub struct ShowServersClause {
1661 pub yields: YieldList,
1662 pub where_expr: Option<Expr>,
1663 pub stages: Vec<PageStage>,
1664}
1665
1666/// `SHOW USER[S] [YIELD ...] [WHERE ...]` / `SHOW CURRENT USER` (CIP-68).
1667#[derive(Debug, Clone, PartialEq)]
1668pub struct ShowUsersClause {
1669 /// `SHOW CURRENT USER` -- singular only, CIP-68 rejects the plural
1670 /// `SHOW CURRENT USERS`.
1671 pub current_only: bool,
1672 pub yields: YieldList,
1673 pub where_expr: Option<Expr>,
1674 pub stages: Vec<PageStage>,
1675}
1676
1677/// `SHOW PROCEDURE[S] [YIELD ...] [WHERE ...]` (CIP-68 grammar
1678/// foundation).
1679#[derive(Debug, Clone, PartialEq)]
1680pub struct ShowProceduresClause {
1681 pub yields: YieldList,
1682 pub where_expr: Option<Expr>,
1683 pub stages: Vec<PageStage>,
1684 /// `EXECUTABLE [BY <user>]`, when written.
1685 pub executable: Option<ExecutableBy>,
1686}
1687
1688/// `SHOW SETTING[S] [<names>] [YIELD ...] [WHERE ...]` (CIP-68 grammar
1689/// foundation). `names` is the optional expression naming the setting(s) to
1690/// filter to: a STRING or a LIST<STRING> (or a `null`/parameter resolving to
1691/// either). The executor selects from its own fixed settings catalog -- a
1692/// null selects nothing, an empty list means "no filter" (CIP-253), and any
1693/// other shape is a `TypeError`.
1694#[derive(Debug, Clone, PartialEq)]
1695pub struct ShowSettingsClause {
1696 pub names: Option<Expr>,
1697 pub yields: YieldList,
1698 pub where_expr: Option<Expr>,
1699 pub stages: Vec<PageStage>,
1700}
1701
1702/// `SHOW TRANSACTION[S] [<id-list>] [YIELD ...] [WHERE ...]` (CIP-68
1703/// grammar foundation). `ids` is the optional comma-separated list of
1704/// transaction-id expressions to filter to (empty = no filter) --
1705/// Relate has no live-transaction catalog, so it's parsed but never
1706/// changes the (always empty) result.
1707#[derive(Debug, Clone, PartialEq)]
1708pub struct ShowTransactionsClause {
1709 pub ids: Vec<Expr>,
1710 pub yields: YieldList,
1711 pub where_expr: Option<Expr>,
1712 pub stages: Vec<PageStage>,
1713}
1714
1715/// `TERMINATE TRANSACTION[S] <id-list> [YIELD ...]` (CIP-68 grammar
1716/// foundation). Since `ShowTransactions` never reports a live transaction,
1717/// every requested id is reported as not found.
1718#[derive(Debug, Clone, PartialEq)]
1719pub struct TerminateTransactionsClause {
1720 pub ids: Vec<Expr>,
1721 pub yields: YieldList,
1722}
1723
1724/// CALL db.procedure() YIELD ... clause.
1725#[derive(Debug, Clone, PartialEq)]
1726pub struct CallProcedureClause {
1727 pub procedure: SmallName,
1728 pub args: Vec<Expr>,
1729 /// Whether the procedure name was followed by an explicit argument list,
1730 /// including an empty `()`. Relate needs this to distinguish `CALL p`
1731 /// (implicit arguments) from `CALL p()` (no arguments).
1732 pub explicit_args: bool,
1733 pub yields: YieldList,
1734 /// CIP-159: `OPTIONAL CALL proc(...)` -- when the procedure call yields
1735 /// zero rows (after any `WHERE` in `YIELD`) for a given outer row, that
1736 /// outer row is null-padded instead of being dropped. Void-procedure
1737 /// and zero-outer-row semantics are handled by the engine.
1738 pub optional: bool,
1739 /// CIP-159: `WHERE` inside the `YIELD` clause -- part of the
1740 /// `<procedure call>` production, filtering the procedure's own result
1741 /// rows (may reference the outer row's variables) before they're
1742 /// merged into the pipeline.
1743 pub where_expr: Option<Expr>,
1744}
1745
1746// -- Pattern nodes --
1747
1748/// A path pattern like (a)-[r]->(b), optionally named: p = (a)-[r]->(b).
1749#[derive(Debug, Clone, PartialEq)]
1750pub struct PatternPath {
1751 pub variable: Option<SmallName>,
1752 /// CIP-73: the subpath variable of a named parenthesized group that is
1753 /// itself the whole path body (`MATCH p = ANY SHORTEST (q = (:A)-->+(:B))`,
1754 /// `MATCH ANY SHORTEST (q = (:A)-->+(:B))`). [`Self::variable`] carries
1755 /// only the enclosing `p = …` name; both names bind the same path value
1756 /// and [`Self::path_names`] lists them. A lone group name (no enclosing
1757 /// path name) stays here, not in `variable`, so a group reading its own
1758 /// name inside its `WHERE` stays distinguishable from an enclosing path
1759 /// variable read there (42I21).
1760 pub subpath_variable: Option<SmallName>,
1761 pub elements: Vec<PatternElement>,
1762 /// The trailing `WHERE` of a parenthesized path pattern, e.g.
1763 /// `((n)-[r]->(m) WHERE n.p > m.q AND r:S)` (CIP-14 "parenthesized path
1764 /// pattern" location). Evaluated once every element in the path is
1765 /// bound, ANDed with the pattern match itself.
1766 pub where_expr: Option<Expr>,
1767 /// CIP-51 explicit path mode prefix (`WALK`/`TRAIL`/`ACYCLIC`/`SIMPLE`),
1768 /// written directly or nested inside a `selector`'s own `[path mode]`
1769 /// slot. `None` means no explicit keyword (resolves to `Walk`).
1770 pub mode: Option<PathMode>,
1771 /// CIP-73/CIP-191 path selector prefix (`ALL`/`ANY`/`SHORTEST`/...).
1772 /// `None` means no explicit selector (equivalent to an implicit `ALL`).
1773 pub selector: Option<PathSelector>,
1774 /// True if this path pattern is sugar for the pre-GPM
1775 /// `shortestPath(...)`/`allShortestPaths(...)` function (CIP-40/CIP-73),
1776 /// rather than an explicit `SHORTEST`/`ALL SHORTEST`
1777 /// selector keyword -- even though both normalize to the same
1778 /// `selector` value. The two are NOT interchangeable for CIP-40's
1779 /// mixing rules: the legacy function forms are exempt from the
1780 /// explicit-match-mode and multiple-selective-path-pattern
1781 /// restrictions that apply to the keyword selector syntax (see
1782 /// `Parser::parse_match`).
1783 pub is_shortest_path_function: bool,
1784}
1785
1786impl PatternPath {
1787 /// The names this path binds its path value under, in declaration order:
1788 /// the outer path variable, then a named parenthesized subpath. The two
1789 /// name the same path value; the IR twin is `PathPattern::path_names`.
1790 pub fn path_names(&self) -> impl Iterator<Item = &SmallName> {
1791 [self.variable.as_ref(), self.subpath_variable.as_ref()]
1792 .into_iter()
1793 .flatten()
1794 }
1795}
1796
1797/// A pattern element is either a node pattern, a relationship pattern, or a
1798/// quantified path pattern (CIP-28).
1799#[derive(Debug, Clone, PartialEq)]
1800pub enum PatternElement {
1801 Node(NodePattern),
1802 Relationship(RelPattern),
1803 Quantified(QuantifiedPathPattern),
1804}
1805
1806/// The `{min, max}` bounds of a CIP-28 quantifier (`*`, `+`, `{m,n}`, `{m,}`,
1807/// `{,n}`, `{,}`, `{n}`). `max = None` means unbounded. Bounds are already
1808/// normalized and validated by the parser: `{,}` -> `{0,}` and the
1809/// bounds checks (upper bound > 0, lower bound <= upper bound) are
1810/// enforced at parse time, so every `PathQuantifier` that reaches the AST
1811/// is legal.
1812#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1813pub struct PathQuantifier {
1814 pub min: u32,
1815 pub max: Option<u32>,
1816}
1817
1818/// A quantified path pattern: a parenthesized subpath (`elements`),
1819/// optionally assigned a subpath variable (e.g. `(p2 = (x)-->(y))*`) and/or a trailing `WHERE` evaluated once per
1820/// iteration, followed by a quantifier. Appears as a `PatternElement`
1821/// alongside plain `Node`/`Relationship` elements so it composes freely with
1822/// them by concatenation.
1823///
1824/// A bare quantified relationship (`-[r]->*`, Form 5) does *not* produce this
1825/// variant: it normalizes directly into the ordinary variable-length
1826/// `RelPattern` (`min_hops`/`max_hops`), since it declares no element
1827/// variables of its own to expose as a group and its matching semantics are
1828/// identical to the legacy `-[*min..max]->` matcher (only the quantifier's
1829/// own zero-inclusive defaults differ, e.g. bare `*` means 0 or more here
1830/// versus 1 or more for legacy bare `*`). See `Parser::parse_rel_pattern`.
1831#[derive(Debug, Clone, PartialEq)]
1832pub struct QuantifiedPathPattern {
1833 pub subpath_variable: Option<SmallName>,
1834 pub elements: Vec<PatternElement>,
1835 pub where_expr: Option<Expr>,
1836 pub quantifier: PathQuantifier,
1837}
1838
1839/// A node pattern like (n:Label {prop: value}).
1840#[derive(Debug, Clone, PartialEq)]
1841pub struct NodePattern {
1842 pub variable: Option<SmallName>,
1843 pub label_expr: Option<LabelExpr>,
1844 pub properties: Vec<(SmallName, Expr)>,
1845 pub has_properties: bool,
1846 /// The `$paramName` whole-property-map shorthand (an alternative to
1847 /// `{...}`), e.g. `CREATE (n:Label $props)`. Mutually exclusive with
1848 /// `properties`/`has_properties` -- the parser only ever populates one
1849 /// property-map form per pattern element.
1850 pub properties_param: Option<Expr>,
1851 /// The element-pattern `WHERE` of `(n WHERE <expr>)` (CIP-14 "node
1852 /// element pattern" location), evaluated once `variable` is bound.
1853 pub where_expr: Option<Expr>,
1854}
1855
1856/// A relationship pattern like -[r:TYPE {prop: value}]->.
1857#[derive(Debug, Clone, PartialEq)]
1858pub struct RelPattern {
1859 pub variable: Option<SmallName>,
1860 pub type_expr: Option<LabelExpr>,
1861 pub properties: Vec<(SmallName, Expr)>,
1862 /// Whether a property specification was *written*, in either spelling.
1863 /// The rel twin of [`NodePattern`]'s field: set for `{}` too, so
1864 /// `-[] {}]-` and `(a {})` agree wherever "has predicates" is asked
1865 /// (42N56) — live-verified against Neo4j.
1866 pub has_properties: bool,
1867 /// The `$paramName` whole-property-map shorthand -- see
1868 /// `NodePattern::properties_param`.
1869 pub properties_param: Option<Expr>,
1870 pub direction: Direction,
1871 pub min_hops: Option<u32>,
1872 pub max_hops: Option<u32>,
1873 /// The element-pattern `WHERE` of `[r WHERE <expr>]`.
1874 pub where_expr: Option<Expr>,
1875 /// True when `min_hops`/`max_hops` came from a CIP-28 postfix quantifier
1876 /// (`-[r]->*`, `-->+`, `-[]->{1,6}`, Form 5) rather than the legacy
1877 /// bracket-internal `[r*min..max]` syntax. Distinguishes the two so the
1878 /// engine can apply `where_expr` per traversed edge for the CIP-28 form
1879 /// without changing the legacy matcher's (TCK-tested) behavior.
1880 pub quantified: bool,
1881}
1882
1883impl RelPattern {
1884 /// Whether the relationship is variable-length: either hop bound was
1885 /// written (`*m..n`, or a CIP-28 quantifier lowered onto the bounds).
1886 /// The one predicate every consumer consults instead of re-spelling
1887 /// the two `is_some` checks.
1888 pub fn is_variable_length(&self) -> bool {
1889 self.min_hops.is_some() || self.max_hops.is_some()
1890 }
1891}
1892
1893/// A GQL label/relationship-type expression (CIP-14): `&` (conjunction),
1894/// `|` (disjunction), `!` (negation), `%` (wildcard -- matches any non-empty
1895/// label set, or any relationship since every relationship has exactly one
1896/// type), parenthesized grouping (folded directly into the tree, so no
1897/// explicit `Group` variant is needed), and CIP-249's dynamic label name
1898/// `$(expr)`. The legacy colon-conjunction shorthand `:A:B:C` lowers to
1899/// `And([Label(A), Label(B), Label(C)])`, and the legacy relationship-type
1900/// disjunction shorthand `:A|B` lowers to `Or([Label(A), Label(B)])`,
1901/// preserving pre-CIP-14 behavior exactly.
1902#[derive(Debug, Clone, PartialEq)]
1903pub enum LabelExpr {
1904 /// A single label/type name.
1905 Label(SmallName),
1906 /// `%`
1907 Wildcard,
1908 /// `$(expr)` / `$all(expr)` / `$any(expr)` -- a label/type name (or, for
1909 /// list-valued `expr`, a set of label/type names) resolved at runtime
1910 /// (CIP-249 / CIP-156 / CIP-221).
1911 Dynamic(DynamicLabelExpr),
1912 /// `!<label-expr>` -- negates only the following primary.
1913 Not(Box<LabelExpr>),
1914 /// `<label-expr> & <label-expr> & ...`
1915 And(Vec<LabelExpr>),
1916 /// `<label-expr> | <label-expr> | ...`
1917 Or(Vec<LabelExpr>),
1918}
1919
1920/// A dynamic label/type expression's quantifier: `$(expr)` (`Default`),
1921/// `$all(expr)` (`All`), or `$any(expr)` (`Any`). `Default` and `All` share
1922/// conjunction semantics for list-valued `expr` (and are otherwise
1923/// interchangeable); `Any` is disjunction. Kept distinct from `All` so
1924/// callers (e.g. `CREATE`/`MERGE` label resolution) can reject the explicit
1925/// `$any(...)` form while still accepting the implicit-all `$(...)` form.
1926#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1927pub enum DynamicLabelQuantifier {
1928 Default,
1929 All,
1930 Any,
1931}
1932
1933/// The payload of `LabelExpr::Dynamic`: the value expression plus its
1934/// quantifier.
1935#[derive(Debug, Clone, PartialEq)]
1936pub struct DynamicLabelExpr {
1937 pub expr: Box<Expr>,
1938 pub quantifier: DynamicLabelQuantifier,
1939}
1940
1941impl LabelExpr {
1942 /// Returns the flat list of label names if this expression is a plain
1943 /// label list: a single label, or an `And` of only plain labels (as
1944 /// produced by legacy colon-conjunction `:A:B:C`, or a comma-separated
1945 /// SET/REMOVE label item). Returns `None` for anything using `|`, `!`,
1946 /// `%`, or a dynamic label -- those aren't valid label lists (CREATE /
1947 /// MERGE / SET / REMOVE label specifications, per CIP-14's "DML
1948 /// statements" exclusion and CIP-126).
1949 pub fn as_label_list(&self) -> Option<Vec<SmallName>> {
1950 match self {
1951 LabelExpr::Label(name) => Some(vec![name.clone()]),
1952 LabelExpr::And(items) => {
1953 let mut out = Vec::with_capacity(items.len());
1954 for item in items {
1955 match item {
1956 LabelExpr::Label(name) => out.push(name.clone()),
1957 _ => return None,
1958 }
1959 }
1960 Some(out)
1961 }
1962 _ => None,
1963 }
1964 }
1965
1966 /// True if this expression contains `!` (negation) or `%` (wildcard)
1967 /// anywhere, recursively. Used to reject a variable-length quantifier
1968 /// combined with negation/wildcard (CIP-14).
1969 pub fn contains_not_or_wildcard(&self) -> bool {
1970 match self {
1971 LabelExpr::Label(_) | LabelExpr::Dynamic(_) => false,
1972 LabelExpr::Wildcard | LabelExpr::Not(_) => true,
1973 LabelExpr::And(items) | LabelExpr::Or(items) => {
1974 items.iter().any(LabelExpr::contains_not_or_wildcard)
1975 }
1976 }
1977 }
1978
1979 /// Returns the flat list of label/type names if this expression is a
1980 /// plain label or `|`-disjunction list: a single label, or an `Or` of
1981 /// only plain labels (as produced by `A|B|C`). Returns `None` for
1982 /// anything using `&`, `!`, `%`, or a dynamic label. Used by the
1983 /// CREATE INDEX / CREATE CONSTRAINT `FOR` target (CIP-11/CIP-38/
1984 /// CIP-235's `FOR (n:A|B)` multi-label DDL surface) -- a narrower
1985 /// grammar than general MATCH label expressions.
1986 pub fn as_ddl_list(&self) -> Option<Vec<SmallName>> {
1987 match self {
1988 LabelExpr::Label(name) => Some(vec![name.clone()]),
1989 LabelExpr::Or(items) => {
1990 let mut out = Vec::with_capacity(items.len());
1991 for item in items {
1992 match item {
1993 LabelExpr::Label(name) => out.push(name.clone()),
1994 _ => return None,
1995 }
1996 }
1997 Some(out)
1998 }
1999 _ => None,
2000 }
2001 }
2002
2003 /// True if this expression contains a `$(...)`/`$all(...)`/`$any(...)`
2004 /// dynamic label/type atom anywhere, recursively (CIP-156). Used by
2005 /// CREATE/MERGE's static "exactly one relationship type" check to defer
2006 /// to runtime resolution when the count can't be known until the
2007 /// dynamic expression is evaluated.
2008 pub fn contains_dynamic(&self) -> bool {
2009 match self {
2010 LabelExpr::Label(_) | LabelExpr::Wildcard => false,
2011 LabelExpr::Dynamic(_) => true,
2012 LabelExpr::Not(inner) => inner.contains_dynamic(),
2013 LabelExpr::And(items) | LabelExpr::Or(items) => {
2014 items.iter().any(LabelExpr::contains_dynamic)
2015 }
2016 }
2017 }
2018}
2019
2020/// Direction of a relationship.
2021#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2022pub enum Direction {
2023 Right, // (a)-[]->(b)
2024 Left, // (a)<-[]-(b)
2025 Both, // (a)-[]-(b)
2026}
2027
2028// -- Expression nodes --
2029
2030mod expr_children;
2031pub use expr_children::{ExprEdge, ExprEdgeMut};
2032
2033/// One segment of a CIP-261 interpolated string literal.
2034#[derive(Debug, Clone, PartialEq)]
2035pub enum InterpPart {
2036 /// Literal text (escaped braces already resolved to plain braces).
2037 Text(String),
2038 /// An `{expression}` embed.
2039 Interp(Box<Expr>),
2040}
2041
2042/// All expression types.
2043#[derive(Debug, Clone, PartialEq)]
2044pub enum Expr {
2045 Literal(LiteralValue),
2046 List(Vec<Expr>),
2047 Map(Vec<MapPair>),
2048 /// CIP-261 interpolated string literal: text segments interleaved with
2049 /// `{expression}` embeds, lowered to the internal `string.interp`
2050 /// function (see `relate/relate-front/src/lower.rs`).
2051 StringInterp(Vec<InterpPart>),
2052 Variable(SmallName),
2053 Parameter(String),
2054 Property(Box<PropertyAccess>),
2055 FunctionCall(FunctionCallExpr),
2056 Binary(Box<BinaryExpr>),
2057 Unary(Box<UnaryExpr>),
2058 Comparison(Box<ComparisonExpr>),
2059 In(Box<InExpr>),
2060 IsNull(Box<IsNullExpr>),
2061 IsType(Box<IsTypeExpr>),
2062 IsNormalized(Box<IsNormalizedExpr>),
2063 ChronologicalCompare(Box<ChronologicalCompareExpr>),
2064 StringMatch(Box<StringMatchExpr>),
2065 CountStar,
2066 Star,
2067 Case(Box<CaseExpr>),
2068 ExistsSubquery(Box<ExistsSubqueryExpr>),
2069 CountSubquery(Box<CountSubqueryExpr>),
2070 CollectSubquery(Box<CollectSubqueryExpr>),
2071 ListComprehension(Box<ListComprehensionExpr>),
2072 MapComprehension(Box<MapComprehensionExpr>),
2073 PatternComprehension(Box<PatternComprehensionExpr>),
2074 Reduce(Box<ReduceExpr>),
2075 AllReduce(Box<AllReduceExpr>),
2076 ShortestPath(Box<ShortestPathExpr>),
2077 Subscript(Box<SubscriptExpr>),
2078 Quantifier(Box<QuantifierExpr>),
2079 HasLabel(Box<HasLabelExpr>),
2080 Paren(Box<Expr>),
2081 PatternPredicate(Box<PatternPredicateExpr>),
2082 MapProjection(Box<MapProjectionExpr>),
2083 /// The canonical `?` marker for an `OPTIONS` value outside the persisted
2084 /// five-literal vocabulary (a list, map, temporal, …), produced only when
2085 /// a whole-map `OPTIONS $param` is resolved into literal entries. The
2086 /// parser never produces it and it references nothing, so no walker can
2087 /// mistake it for a variable.
2088 OptionValuePlaceholder,
2089}
2090
2091/// A literal value in the AST.
2092#[derive(Debug, Clone, PartialEq)]
2093pub enum LiteralValue {
2094 Null,
2095 Bool(bool),
2096 Integer(i64),
2097 Float(f64),
2098 String(String),
2099}
2100
2101/// A key-value pair in a map literal.
2102#[derive(Debug, Clone, PartialEq)]
2103pub struct MapPair {
2104 pub key: SmallName,
2105 pub value: Expr,
2106}
2107
2108/// `<variable> <map projection>` (`n {.foo, bar, baz: qux}`): openCypher's
2109/// map projection, syntactically always rooted at a plain variable
2110/// (`expr` is always an `Expr::Variable`). Needed for CIP-190's
2111/// near-ambiguity coverage: `exists {name: exists.name}` etc. must parse
2112/// as a map projection on a variable named `exists`, not as
2113/// `EXISTS { <subquery> }`, when the filler between the braces looks like
2114/// projection items rather than subquery content (near-ambiguities.feature).
2115#[derive(Debug, Clone, PartialEq)]
2116pub struct MapProjectionExpr {
2117 pub expr: Expr,
2118 pub items: Vec<MapProjectionItem>,
2119}
2120
2121/// One item of a `<map projection>`.
2122#[derive(Debug, Clone, PartialEq)]
2123pub enum MapProjectionItem {
2124 /// `.*` -- every property of the base entity.
2125 AllProperties,
2126 /// `.prop` -- shorthand for `prop: <base>.prop`.
2127 Property(SmallName),
2128 /// A bare `variable` selector -- shorthand for `variable: variable`,
2129 /// pulling a same-named variable from the surrounding scope (*not* a
2130 /// property of the base expression).
2131 Variable(SmallName),
2132 /// `key: <expr>` -- a literal entry.
2133 KeyValue(SmallName, Expr),
2134}
2135
2136/// Property access like n.prop.
2137#[derive(Debug, Clone, PartialEq)]
2138pub struct PropertyAccess {
2139 pub expr: Expr,
2140 pub property: SmallName,
2141 /// CIP-131: when a SET/REMOVE target uses the dynamic-property bracket
2142 /// form (`n[<expr>]`) instead of the static `n.prop` form, the property
2143 /// key is computed at runtime from this expression rather than being the
2144 /// statically-known `property` string (which is left empty). `None` for
2145 /// every static `.prop` access, keeping `property` back-compatible for
2146 /// all existing (non-SET/REMOVE) uses of `PropertyAccess`.
2147 pub key_expr: Option<Expr>,
2148}
2149
2150/// Function call like count(x).
2151#[derive(Debug, Clone, PartialEq)]
2152pub struct FunctionCallExpr {
2153 pub name: SmallName,
2154 pub args: Vec<Expr>,
2155 pub distinct: bool,
2156}
2157
2158/// Binary expression like a + b. `op` is the operator's AST spelling, a
2159/// `&'static str` drawn from the parser's operator-constant table
2160/// (`parser/mod.rs`, ADR-0505 §2) — never a runtime-built `String`.
2161#[derive(Debug, Clone, PartialEq)]
2162pub struct BinaryExpr {
2163 pub left: Expr,
2164 pub op: &'static str,
2165 pub right: Expr,
2166}
2167
2168/// Unary expression like NOT x or -x. `op` is the operator's AST spelling,
2169/// a `&'static str` drawn from the parser's operator-constant table
2170/// (`parser/mod.rs`, ADR-0505 §2) — never a runtime-built `String`.
2171#[derive(Debug, Clone, PartialEq)]
2172pub struct UnaryExpr {
2173 pub op: &'static str,
2174 pub expr: Expr,
2175}
2176
2177/// Comparison expression like a > b. `op` is the operator's AST spelling, a
2178/// `&'static str` from the `comparison_op` token-to-spelling table
2179/// (`parser/mod.rs`, ADR-0505 §2) — never a runtime-built `String`.
2180#[derive(Debug, Clone, PartialEq)]
2181pub struct ComparisonExpr {
2182 pub left: Expr,
2183 pub op: &'static str,
2184 pub right: Expr,
2185}
2186
2187/// x IN list.
2188#[derive(Debug, Clone, PartialEq)]
2189pub struct InExpr {
2190 pub expr: Expr,
2191 pub list: Expr,
2192}
2193
2194/// x IS NULL or x IS NOT NULL.
2195#[derive(Debug, Clone, PartialEq)]
2196pub struct IsNullExpr {
2197 pub expr: Expr,
2198 pub negated: bool,
2199}
2200
2201/// x IS [NOT] :: <value type> (CIP-86/CIP-87 type predicate expression);
2202/// also produced by the `IS [NOT] TYPED <value type>` and bare `x :: <value
2203/// type>` surface forms, which are equivalent.
2204#[derive(Debug, Clone, PartialEq)]
2205pub struct IsTypeExpr {
2206 pub expr: Expr,
2207 pub type_expr: TypeExpr,
2208 pub negated: bool,
2209}
2210
2211/// A parsed `<value type>` per the CIP-86 grammar: the vocabulary used by
2212/// the CIP-87 type predicate expression (`IS [NOT] :: <type>`) and, once
2213/// CIP-90 ships, by `valueType()`.
2214#[derive(Debug, Clone, PartialEq)]
2215pub enum TypeExpr {
2216 /// A predefined leaf type: a scalar, temporal, reference, point, map,
2217 /// nothing/null, or the open `ANY` type. `not_null` reflects an
2218 /// explicit `NOT NULL` suffix directly on this leaf's own grammar
2219 /// production (e.g. `INTEGER NOT NULL`).
2220 Predefined {
2221 kind: PredefinedKind,
2222 not_null: bool,
2223 },
2224 /// `LIST<T>` / `T LIST` / `ARRAY<T>` / `T ARRAY`, with an optional
2225 /// `NOT NULL` on the list value itself (not on its elements -- element
2226 /// nullability lives in `element`).
2227 List {
2228 element: Box<TypeExpr>,
2229 not_null: bool,
2230 },
2231 /// `[ANY] PROPERTY VALUE [NOT NULL]`: the dynamic union of every
2232 /// property-storable scalar type and lists thereof.
2233 PropertyValue { not_null: bool },
2234 /// A closed dynamic union -- `ANY [VALUE] <A | B | ...>` or the bare
2235 /// `A | B | ...` form (equivalent). The grammar gives closed unions no
2236 /// `[NOT NULL]` production of their own, so the parser never attaches
2237 /// one here; a trailing `NOT NULL` after a union is a syntax error.
2238 Union(Vec<TypeExpr>),
2239 /// `VECTOR<TYPE [NOT NULL]>(DIM)` (Cypher style) or `VECTOR(DIM, TYPE
2240 /// [NOT NULL])` (GQL style) (CIP-216). Either the coordinate type or
2241 /// the dimension may be grammatically omitted (`VECTOR(3)`,
2242 /// `VECTOR<INTEGER32>`) -- both parse fine but are rejected at
2243 /// constraint-creation time, since a property type constraint requires
2244 /// both. The coordinate type's own `NOT NULL` is mandatory/implicit
2245 /// (always rendered NOT NULL in canonical form) and so isn't tracked
2246 /// separately here; `not_null` is the *outer* NOT NULL on the whole
2247 /// vector type (valid grammatically, but rejected for independent
2248 /// property type constraints -- CIP-216 doc, "for dependent property
2249 /// type constraints only").
2250 Vector {
2251 coord: Option<VectorCoordKind>,
2252 dimension: Option<i64>,
2253 not_null: bool,
2254 },
2255}
2256
2257impl TypeExpr {
2258 /// The `NOT NULL` flag attached directly to this node's own grammar
2259 /// production. Used only to check that a closed union's components all
2260 /// agree on nullability (CIP-86 "Not Null Uses"); closed unions have no
2261 /// such production of their own, so they report `false`.
2262 pub fn direct_not_null(&self) -> bool {
2263 match self {
2264 TypeExpr::Predefined { not_null, .. } => *not_null,
2265 TypeExpr::List { not_null, .. } => *not_null,
2266 TypeExpr::PropertyValue { not_null } => *not_null,
2267 TypeExpr::Vector { not_null, .. } => *not_null,
2268 TypeExpr::Union(_) => false,
2269 }
2270 }
2271}
2272
2273/// A vector coordinate type (CIP-216): the six numeric types valid inside
2274/// `VECTOR<...>`/`VECTOR(...)`. `Int64`/`Float64` double as ordinary plain
2275/// property types (aliases for `INTEGER`/`FLOAT`, see `PredefinedKind`)
2276/// outside a vector type; the other four (`Float32`, `Int8`/`Int16`/
2277/// `Int32`) are valid only as a vector coordinate type.
2278///
2279/// Defined in `relate-model` (so the runtime `CypherValue::Vector`
2280/// variant can carry it without a circular crate dependency) and
2281/// re-exported here under its original name/location.
2282pub use relate_model::VectorCoordKind;
2283
2284/// The predefined leaf type names from the `<value type>` grammar.
2285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2286pub enum PredefinedKind {
2287 Nothing,
2288 Null,
2289 Any,
2290 Boolean,
2291 String,
2292 Integer,
2293 Float,
2294 Date,
2295 Duration,
2296 Point,
2297 LocalTime,
2298 ZonedTime,
2299 LocalDateTime,
2300 ZonedDateTime,
2301 Node,
2302 Relationship,
2303 Path,
2304 Map,
2305 /// `UUID [NOT NULL]`.
2306 Uuid,
2307}
2308
2309/// x IS [NOT] [<normal form>] NORMALIZED (CIP-133). `form` is one of
2310/// "NFC"/"NFD"/"NFKC"/"NFKD", or None when the form is omitted (defaults to
2311/// NFC at evaluation time).
2312#[derive(Debug, Clone, PartialEq)]
2313pub struct IsNormalizedExpr {
2314 pub expr: Expr,
2315 pub form: Option<String>,
2316 pub negated: bool,
2317}
2318
2319/// The four chronological comparison operators (Cypher 25):
2320/// `a IS [NOT] BEFORE | AFTER | SAME INSTANT | SAME REPRESENTATION b`.
2321/// The four words stay non-reserved identifiers everywhere else
2322/// (TemporalChronologicalCompare's non-reserved-identifier scenario), so
2323/// the parser recognizes them contextually after an `IS` introducer, the
2324/// same policy as `TYPED`/`NORMALIZED`/`LABELED`.
2325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2326pub enum ChronologicalOp {
2327 Before,
2328 After,
2329 SameInstant,
2330 SameRepresentation,
2331}
2332
2333/// `a IS [NOT] <chronological operator> b` (Cypher 25). `SameInstant`
2334/// compares UTC instants, `SameRepresentation` the local clock plus zone
2335/// identity (the `=` relation), and `Before`/`After` the instant ordering;
2336/// the executor owns the null/mixed-kind policy.
2337#[derive(Debug, Clone, PartialEq)]
2338pub struct ChronologicalCompareExpr {
2339 pub left: Expr,
2340 pub op: ChronologicalOp,
2341 pub right: Expr,
2342 pub negated: bool,
2343}
2344
2345/// STARTS WITH, ENDS WITH, CONTAINS. `op` is the operator's AST spelling, a
2346/// `&'static str` drawn from the parser's operator-constant table
2347/// (`parser/mod.rs`, ADR-0505 §2) — never a runtime-built `String`.
2348#[derive(Debug, Clone, PartialEq)]
2349pub struct StringMatchExpr {
2350 pub left: Expr,
2351 pub op: &'static str,
2352 pub right: Expr,
2353}
2354
2355/// CASE expression. The simple form's test operand is lowered at parse time
2356/// into each `WHEN`'s equality comparison (`parser/case.rs`), so the stored
2357/// model is the searched form only: every condition is a predicate.
2358#[derive(Debug, Clone, PartialEq)]
2359pub struct CaseExpr {
2360 pub whens: Vec<WhenClause>,
2361 pub else_expr: Option<Expr>,
2362}
2363
2364/// WHEN ... THEN ... part of a CASE: the condition is always a predicate
2365/// (the simple form's `operand = value` lowering included).
2366#[derive(Debug, Clone, PartialEq)]
2367pub struct WhenClause {
2368 pub condition: Expr,
2369 pub result: Expr,
2370}
2371
2372/// EXISTS { ... } subquery expression.
2373#[derive(Debug, Clone, PartialEq)]
2374pub struct ExistsSubqueryExpr {
2375 pub statement: Statement,
2376}
2377
2378/// COUNT { ... } subquery expression: evaluates to the number of rows the
2379/// subquery produces against the current row, run independently per row
2380/// (like `EXISTS { ... }`, just returning a count instead of a boolean).
2381#[derive(Debug, Clone, PartialEq)]
2382pub struct CountSubqueryExpr {
2383 pub statement: Statement,
2384}
2385
2386/// `COLLECT { <RegularQuery> }` subquery expression (CIP-71): evaluates the
2387/// inner `<RegularQuery>` once per outer row and collects the single
2388/// projected column's value from every inner row into a list. Unlike
2389/// `EXISTS`/`COUNT`, `COLLECT` has no bare-pattern shorthand -- the inner
2390/// query is always a full `<RegularQuery>` (any read clause, including
2391/// UNION) and must end in a `RETURN` with exactly one non-`*` return item.
2392#[derive(Debug, Clone, PartialEq)]
2393pub struct CollectSubqueryExpr {
2394 pub statement: Statement,
2395}
2396
2397/// CIP-272 map comprehension: `{k : v IN map [WHERE p] | keyExpr : valueExpr}`
2398/// (map source) or `{item IN list [WHERE p] | keyExpr : valueExpr}` (list
2399/// source).
2400#[derive(Debug, Clone, PartialEq)]
2401pub struct MapComprehensionExpr {
2402 /// The key binding variable of a map source (`None` for a list source).
2403 pub key_var: Option<SmallName>,
2404 /// The value binding variable (map source) or the item variable (list
2405 /// source).
2406 pub value_var: SmallName,
2407 pub source_expr: Expr,
2408 pub where_expr: Option<Expr>,
2409 pub key_expr: Expr,
2410 pub value_expr: Expr,
2411}
2412
2413/// [x IN list WHERE pred | expr]
2414#[derive(Debug, Clone, PartialEq)]
2415pub struct ListComprehensionExpr {
2416 pub variable: SmallName,
2417 pub list_expr: Expr,
2418 pub where_expr: Option<Expr>,
2419 pub map_expr: Option<Expr>,
2420}
2421
2422/// [p = (n)-->() | expr] or [(n)-->() | expr]
2423#[derive(Debug, Clone, PartialEq)]
2424pub struct PatternComprehensionExpr {
2425 pub path_variable: Option<SmallName>,
2426 pub pattern: PatternPath,
2427 pub where_expr: Option<Expr>,
2428 pub map_expr: Expr,
2429}
2430
2431/// reduce(accumulator = init, x IN list | expression)
2432#[derive(Debug, Clone, PartialEq)]
2433pub struct ReduceExpr {
2434 pub accumulator: SmallName,
2435 pub init_expr: Expr,
2436 pub variable: SmallName,
2437 pub list_expr: Expr,
2438 pub expression: Expr,
2439}
2440
2441/// allReduce(accumulator = init, x IN list | expression, predicate)
2442#[derive(Debug, Clone, PartialEq)]
2443pub struct AllReduceExpr {
2444 pub accumulator: SmallName,
2445 pub init_expr: Expr,
2446 pub variable: SmallName,
2447 pub list_expr: Expr,
2448 pub expression: Expr,
2449 pub predicate: Expr,
2450}
2451
2452/// shortestPath() / allShortestPaths()
2453#[derive(Debug, Clone, PartialEq)]
2454pub struct ShortestPathExpr {
2455 pub pattern: PatternPath,
2456 pub all: bool,
2457}
2458
2459/// expr[index] or expr[from..to]
2460#[derive(Debug, Clone, PartialEq)]
2461pub struct SubscriptExpr {
2462 pub expr: Expr,
2463 pub index: Option<Expr>,
2464 pub from: Option<Expr>,
2465 pub to: Option<Expr>,
2466 pub slice: bool,
2467}
2468
2469/// all/any/none/single(x IN list WHERE pred)
2470#[derive(Debug, Clone, PartialEq)]
2471pub struct QuantifierExpr {
2472 pub quantifier: String,
2473 pub variable: SmallName,
2474 pub list: Expr,
2475 pub predicate: Option<Expr>,
2476}
2477
2478/// A label/type predicate: `n:Label`, `n IS Label` (CIP-14), or
2479/// `n IS [NOT] LABELED <label-expr>` / the `n IS NOT <label-expr>` shorthand
2480/// (CIP-249).
2481#[derive(Debug, Clone, PartialEq)]
2482pub struct HasLabelExpr {
2483 pub expr: Expr,
2484 pub label_expr: LabelExpr,
2485 /// True for `IS NOT LABELED <LE>` and its `IS NOT <LE>` shorthand, which
2486 /// negate the *whole* expression (unlike an inline `!` inside `label_expr`,
2487 /// which negates only the following primary).
2488 pub negated: bool,
2489 /// True for the `IS [NOT] LABELED <LE>` forms (and the `IS NOT
2490 /// <LE>` shorthand), which raise a runtime type error for a non-node/
2491 /// relationship LHS. False for the pre-existing `:`/bare `IS <LE>`
2492 /// forms (CIP-14), which fall back to `false` for a non-entity LHS,
2493 /// preserving their original behavior.
2494 pub strict: bool,
2495}
2496
2497/// Pattern used as boolean predicate in WHERE, e.g. (n)-[:REL]->(m)
2498#[derive(Debug, Clone, PartialEq)]
2499pub struct PatternPredicateExpr {
2500 pub pattern: PatternPath,
2501}