relate_parser/ast.rs
1use relate_names::SmallName;
2
3mod clause;
4pub use clause::*;
5mod expr;
6pub use expr::*;
7mod graph_type;
8pub use graph_type::*;
9mod pattern;
10pub use pattern::*;
11mod schema;
12pub use schema::*;
13mod search;
14pub use search::*;
15mod show;
16pub use show::*;
17
18/// The statement preamble mode (CIP-150): which of `EXPLAIN`/`PROFILE`
19/// heads the statement, or neither. The preamble grammar is top-level
20/// only and each keyword is admitted at most once, so exactly one mode
21/// heads a statement — never a pair of flags that could disagree.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub enum PreambleMode {
24 /// No preamble keyword: the statement executes.
25 #[default]
26 Execute,
27 /// An `EXPLAIN` preamble: the statement compiles and its plan renders,
28 /// never executes.
29 Explain,
30 /// A `PROFILE` preamble: the statement executes with per-operator
31 /// metrics attached.
32 Profile,
33}
34
35/// AST node types for the Cypher parser.
36///
37/// The AST uses enums for Clause, Expr, and PatternElement to avoid trait objects.
38/// Literal values use native Rust types (not CypherValue) since the AST is a compile-time concept.
39///
40/// Top-level AST node for a Cypher statement.
41#[derive(Debug, Clone, Default)]
42pub struct Statement {
43 pub clauses: Vec<Clause>,
44 pub union: Option<Box<UnionPart>>,
45 /// The CIP-150 preamble mode — top-level only; every nested body
46 /// carries [`PreambleMode::Execute`].
47 pub preamble: PreambleMode,
48 /// CIP-213 `<statement block> ::= <statement> [<next statement>...]`,
49 /// `<next statement> ::= NEXT <statement>`. `next` chains this
50 /// statement (which may itself carry its own `.union` chain, or be a
51 /// sole `Clause::Conditional`) to the following NEXT stage's own
52 /// statement (which may in turn have a `.next` of its own). `None`
53 /// means this is either not part of a NEXT chain, or is its final
54 /// stage. Deliberately a *sibling* field to `union`/`Conditional`
55 /// rather than nested inside them: per the CIP grammar, NEXT operates
56 /// on a whole `<statement>` (union-chain-or-conditional), one level
57 /// above where UNION/WHEN operate, so it's threaded through the
58 /// outermost `Statement` of each stage only -- a stage's own `.union`
59 /// arms never carry their own independent `.next` chain.
60 pub next: Option<Box<Statement>>,
61 /// CIP-146/CIP-242: true when this `SingleQuery` was written as
62 /// `[ USE <graph-expr> ] '{' <RegularQuery> '}'` -- top-level braces --
63 /// rather than the plain unbraced form. The brace form's *content* is
64 /// otherwise indistinguishable from an unbraced statement (same clause
65 /// list, same `.union` chain) once parsed, but CIP-242's SHOW/TERMINATE
66 /// composability rule ("Composing a SHOW command without YIELD fails")
67 /// treats an explicitly brace-wrapped bare `SHOW` (e.g. `{ SHOW INDEXES
68 /// }`) as *composed*, requiring `YIELD`, even though the identical
69 /// clause list unbraced (`SHOW INDEXES` alone) is the lenient
70 /// "canonical standalone" form that doesn't need one -- so this needs
71 /// its own marker distinct from clause shape. Set only by
72 /// `parse_braced_single_query`; every other `Statement` constructor
73 /// leaves it `false` (via `#[derive(Default)]` field-by-field
74 /// construction elsewhere).
75 pub brace_wrapped: bool,
76 /// CIP-231: the `DEFINE <procedure definition> | <function
77 /// definition>` block parsed at the head of this statement block (only
78 /// the top-level statement and braced nested bodies carry definitions;
79 /// every statement-block parse site funnels through
80 /// `parse_statement_block`, where they are parsed). Rewritten away --
81 /// definitions and their call sites eliminated -- by the front-end
82 /// resolver (`relate-front`'s `local_callables`) before lowering;
83 /// the planner/executor never see local callables. `Default`-empty so
84 /// the derived and hand-written constructors of un-gated statements
85 /// are unchanged.
86 pub definitions: Vec<LocalDefinition>,
87}
88
89/// Manual `PartialEq`: deliberately ignores `brace_wrapped`. The unwrap
90/// rule -- and the parser tests pinning it (`test_brace_enclosed_top_level_query_is_transparent` and friends) --
91/// treat a brace-wrapped `SingleQuery` as producing an AST indistinguishable
92/// from its unbraced spelling; `brace_wrapped` is out-of-band provenance a
93/// couple of CIP-242 composability checks read directly off the field
94/// (`validate_show_composability`), not part of that observable-content
95/// equivalence.
96impl Statement {
97 /// The end of this statement's `NEXT` chain: its true terminal stage
98 /// (CIP-213), not its own first stage.
99 pub fn tail_stage(&self) -> &Statement {
100 let mut stage = self;
101 while let Some(next) = &stage.next {
102 stage = next;
103 }
104 stage
105 }
106
107 /// The stage whose clauses decide what the statement projects (CIP-213):
108 /// a UNION head owns the whole composite, so it stands for itself; every
109 /// other statement projects through the tail of its own `NEXT` chain
110 /// (`A UNION B NEXT C` parses as `(A UNION B) NEXT C`).
111 pub fn projection_stage(&self) -> &Statement {
112 if self.union.is_some() {
113 self
114 } else {
115 self.tail_stage()
116 }
117 }
118
119 /// The result shape of the statement's projection stage — the one
120 /// derivation, over [`Self::projection_stage`] and [`branch_shape`],
121 /// that the result-header naming paths read (the facade's
122 /// authored-column restore, ADR-0663), never a hand-rolled walk
123 /// beside it. A UNION head's own arm is the shape the composite
124 /// stands for; a sole conditional's is its representative body's.
125 pub fn projection_shape(&self) -> BranchShape<'_> {
126 branch_shape(&self.projection_stage().clauses)
127 }
128
129 /// Whether the statement's final stage projects columns: it ends in a
130 /// `RETURN`, or in a conditional / nested `CALL` subquery that does. A
131 /// unit subquery call with no `RETURN` makes the enclosing arm a
132 /// no-column arm.
133 pub fn projects_columns(&self) -> bool {
134 match self.projection_stage().clauses.last() {
135 Some(Clause::Return(_)) => true,
136 Some(Clause::Conditional(cc)) => {
137 // The grammar guarantees at least one WHEN branch
138 // (`parse_when_query` pushes one before its loop can
139 // break), so an empty branch list is a broken invariant to
140 // surface -- never a fabricated "does not project" verdict.
141 cc.branches
142 .first()
143 .expect("a WHEN clause has at least one branch")
144 .body
145 .projects_columns()
146 }
147 Some(Clause::CallSubquery(inner)) => inner.statement.projects_columns(),
148 _ => false,
149 }
150 }
151}
152
153impl PartialEq for Statement {
154 fn eq(&self, other: &Self) -> bool {
155 self.clauses == other.clauses
156 && self.union == other.union
157 && self.preamble == other.preamble
158 && self.next == other.next
159 && self.definitions == other.definitions
160 }
161}
162
163/// CIP-231 `DEFINE` block entry: one local callable definition, parsed at
164/// the head of a `<statement block>` (top level or a braced nested body)
165/// and rewritten away by the front-end resolver
166/// (`relate-front`'s `local_callables`) before lowering -- the
167/// planner/executor never see local callables.
168#[derive(Debug, Clone, PartialEq)]
169pub struct LocalDefinition {
170 /// `PROCEDURE` or `FUNCTION`.
171 pub kind: LocalCallableKind,
172 /// The fully-qualified callable name as written (`foo.bar`), namespace
173 /// segments joined on `.`. Matched against call-site names verbatim.
174 pub name: SmallName,
175 /// The `<callable input signature>`: parameters in declaration order.
176 pub params: Vec<LocalParam>,
177 /// The declared `<procedure output type>` (`(field :: T, ...)`) or
178 /// `<function output type>` (`:: T`), when written.
179 pub output: Option<LocalOutput>,
180 /// `= <value expression>` (simple function body) or a braced
181 /// `<procedure specification>` (procedure body or subquery function
182 /// body).
183 pub body: LocalDefinitionBody,
184}
185
186/// `DEFINE PROCEDURE` vs `DEFINE FUNCTION` (CIP-231). The two namespaces
187/// are independent (CIP-230: a procedure and a function may share a name).
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
189pub enum LocalCallableKind {
190 Procedure,
191 Function,
192}
193
194/// One `<input field signature>` of a local callable (CIP-231): a field
195/// name, an optional `[<typed>] <value type>`, and an optional
196/// `= <value expression>` default (which makes the parameter optional).
197#[derive(Debug, Clone, PartialEq)]
198pub struct LocalParam {
199 pub name: SmallName,
200 /// The written value type, `None` when omitted (implicitly ANY).
201 /// Parsed and syntactically validated, deliberately not enforced at
202 /// runtime (ADR-0382).
203 pub type_expr: Option<TypeExpr>,
204 /// `= <value expression>`; `None` for a mandatory parameter. Defaults
205 /// may not reference variables (checked at parse time).
206 pub default: Option<Expr>,
207}
208
209/// A declared output type of a local callable (CIP-231): the procedure
210/// form `:: (a :: INT, ...)` or the function form `:: STRING`.
211#[derive(Debug, Clone, PartialEq)]
212pub enum LocalOutput {
213 /// `:: (<mandatory field signature>, ...)` on a procedure.
214 Fields(Vec<LocalOutputField>),
215 /// `:: <value type>` on a function.
216 Type(TypeExpr),
217}
218
219/// One field of a procedure's `:: (a :: INT, ...)` output signature.
220#[derive(Debug, Clone, PartialEq)]
221pub struct LocalOutputField {
222 pub name: SmallName,
223 pub type_expr: Option<TypeExpr>,
224}
225
226/// The body of a local callable definition (CIP-231).
227#[derive(Debug, Clone, PartialEq)]
228pub enum LocalDefinitionBody {
229 /// `FUNCTION f(...) = <value expression>` (simple function body).
230 Expression(Expr),
231 /// A braced `<procedure specification>`: a procedure body, or a
232 /// subquery function body.
233 Query(Statement),
234}
235
236/// Represents a UNION or UNION ALL between statements.
237#[derive(Debug, Clone, PartialEq)]
238pub struct UnionPart {
239 pub all: bool,
240 pub statement: Statement,
241}
242
243/// All clause types in the Cypher language.
244#[derive(Debug, Clone, PartialEq)]
245pub enum Clause {
246 Match(MatchClause),
247 Create(CreateClause),
248 Merge(MergeClause),
249 Delete(DeleteClause),
250 Set(SetClause),
251 Remove(RemoveClause),
252 Return(ReturnClause),
253 With(WithClause),
254 Unwind(UnwindClause),
255 CreateIndex(CreateIndexClause),
256 DropIndex(DropIndexClause),
257 CreateConstraint(CreateConstraintClause),
258 DropConstraint(DropConstraintClause),
259 Foreach(ForeachClause),
260 LoadCSV(LoadCSVClause),
261 CallSubquery(CallSubqueryClause),
262 CallProcedure(CallProcedureClause),
263 ShowFunctions(ShowFunctionsClause),
264 ShowConstraints(ShowConstraintsClause),
265 ShowIndexes(ShowIndexesClause),
266 /// `SHOW DATABASE[S] [<name>] [YIELD ...] [WHERE ...]` / `SHOW DEFAULT
267 /// DATABASE` / `SHOW HOME DATABASE` (CIP-68's singular/plural KIND
268 /// acceptance; CIP-42's four non-default columns). A minimal virtual
269 /// catalog -- Relate is a single-database engine, so this reports a
270 /// small set of deterministic built-in databases rather than modeling
271 /// real multi-database administration.
272 ShowDatabases(ShowDatabasesClause),
273 /// `SHOW [ALL|POPULATED] ROLE[S] [WITH USER[S]] [YIELD ...] [WHERE ...]`
274 /// (CIP-68). A minimal virtual catalog of built-in roles.
275 ShowRoles(ShowRolesClause),
276 /// `SHOW SERVER[S] [YIELD ...] [WHERE ...]` (CIP-68). Reports a single
277 /// row, matching a single-process embedded engine.
278 ShowServers(ShowServersClause),
279 /// `SHOW USER[S] [YIELD ...] [WHERE ...]` / `SHOW CURRENT USER`
280 /// (CIP-68). A minimal virtual catalog of a single built-in user.
281 ShowUsers(ShowUsersClause),
282 /// `SHOW PROCEDURE[S] [YIELD ...] [WHERE ...]` (CIP-68 grammar
283 /// foundation). Lists the built-in procedure names the engine's `CALL`
284 /// handler recognizes.
285 ShowProcedures(ShowProceduresClause),
286 /// `SHOW SETTING[S] [<names>] [YIELD ...] [WHERE ...]` (CIP-68 grammar
287 /// foundation). Relate has no configurable settings surface, so
288 /// this always reports an empty catalog.
289 ShowSettings(ShowSettingsClause),
290 /// `SHOW TRANSACTION[S] [<ids>] [YIELD ...] [WHERE ...]` (CIP-68
291 /// grammar foundation). Relate executes each statement to
292 /// completion without exposing concurrent transaction identifiers, so
293 /// this always reports an empty catalog.
294 ShowTransactions(ShowTransactionsClause),
295 /// `TERMINATE TRANSACTION[S] <ids> [YIELD ...]` (CIP-68 grammar
296 /// foundation). Since `ShowTransactions` never reports a live
297 /// transaction, every requested id is reported as not found.
298 TerminateTransactions(TerminateTransactionsClause),
299 /// `USE <graph-expr>` (CIP-141 feature-interaction scenarios) -- a
300 /// graph-selector clause. Relate is a single-database engine, so
301 /// this is parsed and scope-checked (its expression's variables must
302 /// be in scope, same as any other clause) but has no runtime effect
303 /// beyond that: there is no composite/multi-graph database to switch
304 /// to.
305 Use(UseClause),
306 /// `FINISH` (CIP-140) -- a terminal clause producing a truly empty
307 /// result (0 rows, 0 columns) instead of RETURN's projected rows,
308 /// while still running any earlier updating clauses. Only the minimal
309 /// semantics needed by CIP-218's `CALL (a) { FINISH }` scenario are
310 /// implemented: cardinality is preserved (one output row per input
311 /// row) but that row carries no columns, so it contributes nothing
312 /// when merged back into an enclosing CALL's outer row.
313 Finish,
314 /// CIP-168: a standalone `<order by and page statement>` -- e.g.
315 /// `ORDER BY n.name SKIP 1 LIMIT 3` appearing as its own clause, not
316 /// attached to WITH/RETURN/YIELD. Acts as an implicit `WITH *`
317 /// horizon clause: changes row order/count but never the column set,
318 /// and may sit between any two other clauses (including two write
319 /// clauses). See `StandaloneOrderByClause` for why this is a sequence
320 /// of stages rather than three fixed fields.
321 StandaloneOrderBy(StandaloneOrderByClause),
322 /// CIP-135: a standalone conditional clause chain --
323 /// `<when query> ::= <when>, {<when>}, [<else>]`. This is a *sibling*
324 /// alternative to `<union query>`/`<single query>` at the `<regular
325 /// query>` grammar level (see `parse_regular_query`), not an ordinary
326 /// mid-statement clause -- so this variant only ever appears as the
327 /// sole element of a `Statement.clauses` vec, never alongside other
328 /// clauses in the same statement.
329 Conditional(ConditionalClause),
330 /// `ALTER CURRENT GRAPH TYPE SET/ADD/ALTER/DROP { <graph type
331 /// specification body> }` (CIP-176/182/183's mechanism; CIP-187's
332 /// constraint derivation builds on it). `body` is the full CIP-178
333 /// `<graph type specification body>` grammar (node/edge type specs,
334 /// property types, and constraint specs) -- see `GraphTypeBody`.
335 AlterCurrentGraphType(AlterCurrentGraphTypeClause),
336 /// `CREATE GRAPH TYPE <name> [AS] { <graph type specification body> }`
337 /// (CIP-178 grammar; the `AS` keyword is CIP-180's spelling of the same
338 /// body-introducing form). Registers a *named* graph type, independent
339 /// of the database's single unnamed "current" graph type that `ALTER
340 /// CURRENT GRAPH TYPE` manages.
341 CreateGraphType(CreateGraphTypeClause),
342 /// `SHOW GRAPH TYPE <name> [YIELD ...]` (CIP-180's SHOW surface): a
343 /// single-row catalog whose `name`/`body` columns report the named
344 /// graph type's own name and its CIP-180 canonical specification
345 /// string.
346 ShowGraphType(ShowGraphTypeClause),
347 /// `SHOW CURRENT GRAPH TYPE [YIELD ...]` (CIP-176 overview / CIP-184):
348 /// the database's persistent current graph type, reported as a single
349 /// `specification` column (the CIP-180 canonical body string wrapped in
350 /// `{ }`, or the literal `{}` when empty).
351 ShowCurrentGraphType(ShowCurrentGraphTypeClause),
352 /// `ALTER DATABASE <name> [IF EXISTS] SET DEFAULT LANGUAGE CYPHER
353 /// <n>` (CIP-170). Under ADR-0116 §2's fixed namespaces this is the
354 /// only supported `ALTER DATABASE` form; every other form is
355 /// recognized and rejected at parse time with CE's
356 /// `UnsupportedAdministrationCommand`.
357 AlterDatabase(AlterDatabaseClause),
358}
359
360impl Clause {
361 /// The clause's predicate-position `WHERE` root — the `WHERE` that
362 /// filters the clause's own rows and so is a boolean position: the
363 /// `WHERE` of a `MATCH`, a `WITH` or a `CALL … YIELD … WHERE`. The
364 /// `SHOW` forms' `WHERE` is a catalogue filter, not a row predicate,
365 /// and no other clause carries one. This is the one table of which
366 /// clauses carry a predicate root: walkers and validators read it
367 /// instead of re-matching the vocabulary.
368 pub fn predicate_where(&self) -> Option<&Expr> {
369 match self {
370 Clause::Match(m) => m.where_expr.as_ref(),
371 Clause::With(w) => w.where_expr.as_ref(),
372 Clause::CallProcedure(c) => c.where_expr.as_ref(),
373 _ => None,
374 }
375 }
376
377 /// The Cypher clause keyword(s) for this clause — e.g. `"MATCH"`,
378 /// `"SHOW INDEXES"`, `"LOAD CSV"`. Exhaustive over the enum, so a new
379 /// clause cannot ship without a renderable name; the planner's
380 /// `clause_keyword` delegates here rather than keeping a second table.
381 pub fn keyword(&self) -> &'static str {
382 match self {
383 Clause::Match(_) => "MATCH",
384 Clause::Create(_) => "CREATE",
385 Clause::Merge(_) => "MERGE",
386 Clause::Delete(_) => "DELETE",
387 Clause::Set(_) => "SET",
388 Clause::Remove(_) => "REMOVE",
389 Clause::Return(_) => "RETURN",
390 Clause::With(_) => "WITH",
391 Clause::Unwind(_) => "UNWIND",
392 Clause::CreateIndex(_) => "CREATE INDEX",
393 Clause::DropIndex(_) => "DROP INDEX",
394 Clause::CreateConstraint(_) => "CREATE CONSTRAINT",
395 Clause::DropConstraint(_) => "DROP CONSTRAINT",
396 Clause::Foreach(_) => "FOREACH",
397 Clause::LoadCSV(_) => "LOAD CSV",
398 Clause::CallSubquery(_) | Clause::CallProcedure(_) => "CALL",
399 Clause::ShowFunctions(_) => "SHOW FUNCTIONS",
400 Clause::ShowConstraints(_) => "SHOW CONSTRAINTS",
401 Clause::ShowIndexes(_) => "SHOW INDEXES",
402 Clause::ShowDatabases(_) => "SHOW DATABASES",
403 Clause::ShowRoles(_) => "SHOW ROLES",
404 Clause::ShowServers(_) => "SHOW SERVERS",
405 Clause::ShowUsers(_) => "SHOW USERS",
406 Clause::ShowProcedures(_) => "SHOW PROCEDURES",
407 Clause::ShowSettings(_) => "SHOW SETTINGS",
408 Clause::ShowTransactions(_) => "SHOW TRANSACTIONS",
409 Clause::TerminateTransactions(_) => "TERMINATE TRANSACTIONS",
410 Clause::Use(_) => "USE",
411 Clause::Finish => "FINISH",
412 Clause::StandaloneOrderBy(_) => "ORDER BY",
413 Clause::Conditional(_) => "WHEN",
414 Clause::AlterCurrentGraphType(_) => "ALTER CURRENT GRAPH TYPE",
415 Clause::CreateGraphType(_) => "CREATE GRAPH TYPE",
416 Clause::ShowGraphType(_) => "SHOW GRAPH TYPE",
417 Clause::ShowCurrentGraphType(_) => "SHOW CURRENT GRAPH TYPE",
418 Clause::AlterDatabase(_) => "ALTER DATABASE",
419 }
420 }
421}
422
423mod expr_children;
424pub use expr_children::{ExprEdge, ExprEdgeMut};