Skip to main content

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    /// Whether the statement's final stage projects columns: it ends in a
120    /// `RETURN`, or in a conditional / nested `CALL` subquery that does. A
121    /// unit subquery call with no `RETURN` makes the enclosing arm a
122    /// no-column arm.
123    pub fn projects_columns(&self) -> bool {
124        match self.projection_stage().clauses.last() {
125            Some(Clause::Return(_)) => true,
126            Some(Clause::Conditional(cc)) => {
127                // The grammar guarantees at least one WHEN branch
128                // (`parse_when_query` pushes one before its loop can
129                // break), so an empty branch list is a broken invariant to
130                // surface -- never a fabricated "does not project" verdict.
131                cc.branches
132                    .first()
133                    .expect("a WHEN clause has at least one branch")
134                    .body
135                    .projects_columns()
136            }
137            Some(Clause::CallSubquery(inner)) => inner.statement.projects_columns(),
138            _ => false,
139        }
140    }
141}
142
143impl PartialEq for Statement {
144    fn eq(&self, other: &Self) -> bool {
145        self.clauses == other.clauses
146            && self.union == other.union
147            && self.preamble == other.preamble
148            && self.next == other.next
149            && self.definitions == other.definitions
150    }
151}
152
153/// CIP-231 `DEFINE` block entry: one local callable definition, parsed at
154/// the head of a `<statement block>` (top level or a braced nested body)
155/// and rewritten away by the front-end resolver
156/// (`relate-front`'s `local_callables`) before lowering -- the
157/// planner/executor never see local callables.
158#[derive(Debug, Clone, PartialEq)]
159pub struct LocalDefinition {
160    /// `PROCEDURE` or `FUNCTION`.
161    pub kind: LocalCallableKind,
162    /// The fully-qualified callable name as written (`foo.bar`), namespace
163    /// segments joined on `.`. Matched against call-site names verbatim.
164    pub name: SmallName,
165    /// The `<callable input signature>`: parameters in declaration order.
166    pub params: Vec<LocalParam>,
167    /// The declared `<procedure output type>` (`(field :: T, ...)`) or
168    /// `<function output type>` (`:: T`), when written.
169    pub output: Option<LocalOutput>,
170    /// `= <value expression>` (simple function body) or a braced
171    /// `<procedure specification>` (procedure body or subquery function
172    /// body).
173    pub body: LocalDefinitionBody,
174}
175
176/// `DEFINE PROCEDURE` vs `DEFINE FUNCTION` (CIP-231). The two namespaces
177/// are independent (CIP-230: a procedure and a function may share a name).
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
179pub enum LocalCallableKind {
180    Procedure,
181    Function,
182}
183
184/// One `<input field signature>` of a local callable (CIP-231): a field
185/// name, an optional `[<typed>] <value type>`, and an optional
186/// `= <value expression>` default (which makes the parameter optional).
187#[derive(Debug, Clone, PartialEq)]
188pub struct LocalParam {
189    pub name: SmallName,
190    /// The written value type, `None` when omitted (implicitly ANY).
191    /// Parsed and syntactically validated, deliberately not enforced at
192    /// runtime (ADR-0382).
193    pub type_expr: Option<TypeExpr>,
194    /// `= <value expression>`; `None` for a mandatory parameter. Defaults
195    /// may not reference variables (checked at parse time).
196    pub default: Option<Expr>,
197}
198
199/// A declared output type of a local callable (CIP-231): the procedure
200/// form `:: (a :: INT, ...)` or the function form `:: STRING`.
201#[derive(Debug, Clone, PartialEq)]
202pub enum LocalOutput {
203    /// `:: (<mandatory field signature>, ...)` on a procedure.
204    Fields(Vec<LocalOutputField>),
205    /// `:: <value type>` on a function.
206    Type(TypeExpr),
207}
208
209/// One field of a procedure's `:: (a :: INT, ...)` output signature.
210#[derive(Debug, Clone, PartialEq)]
211pub struct LocalOutputField {
212    pub name: SmallName,
213    pub type_expr: Option<TypeExpr>,
214}
215
216/// The body of a local callable definition (CIP-231).
217#[derive(Debug, Clone, PartialEq)]
218pub enum LocalDefinitionBody {
219    /// `FUNCTION f(...) = <value expression>` (simple function body).
220    Expression(Expr),
221    /// A braced `<procedure specification>`: a procedure body, or a
222    /// subquery function body.
223    Query(Statement),
224}
225
226/// Represents a UNION or UNION ALL between statements.
227#[derive(Debug, Clone, PartialEq)]
228pub struct UnionPart {
229    pub all: bool,
230    pub statement: Statement,
231}
232
233/// All clause types in the Cypher language.
234#[derive(Debug, Clone, PartialEq)]
235pub enum Clause {
236    Match(MatchClause),
237    Create(CreateClause),
238    Merge(MergeClause),
239    Delete(DeleteClause),
240    Set(SetClause),
241    Remove(RemoveClause),
242    Return(ReturnClause),
243    With(WithClause),
244    Unwind(UnwindClause),
245    CreateIndex(CreateIndexClause),
246    DropIndex(DropIndexClause),
247    CreateConstraint(CreateConstraintClause),
248    DropConstraint(DropConstraintClause),
249    Foreach(ForeachClause),
250    LoadCSV(LoadCSVClause),
251    CallSubquery(CallSubqueryClause),
252    CallProcedure(CallProcedureClause),
253    ShowFunctions(ShowFunctionsClause),
254    ShowConstraints(ShowConstraintsClause),
255    ShowIndexes(ShowIndexesClause),
256    /// `SHOW DATABASE[S] [<name>] [YIELD ...] [WHERE ...]` / `SHOW DEFAULT
257    /// DATABASE` / `SHOW HOME DATABASE` (CIP-68's singular/plural KIND
258    /// acceptance; CIP-42's four non-default columns). A minimal virtual
259    /// catalog -- Relate is a single-database engine, so this reports a
260    /// small set of deterministic built-in databases rather than modeling
261    /// real multi-database administration.
262    ShowDatabases(ShowDatabasesClause),
263    /// `SHOW [ALL|POPULATED] ROLE[S] [WITH USER[S]] [YIELD ...] [WHERE ...]`
264    /// (CIP-68). A minimal virtual catalog of built-in roles.
265    ShowRoles(ShowRolesClause),
266    /// `SHOW SERVER[S] [YIELD ...] [WHERE ...]` (CIP-68). Reports a single
267    /// row, matching a single-process embedded engine.
268    ShowServers(ShowServersClause),
269    /// `SHOW USER[S] [YIELD ...] [WHERE ...]` / `SHOW CURRENT USER`
270    /// (CIP-68). A minimal virtual catalog of a single built-in user.
271    ShowUsers(ShowUsersClause),
272    /// `SHOW PROCEDURE[S] [YIELD ...] [WHERE ...]` (CIP-68 grammar
273    /// foundation). Lists the built-in procedure names the engine's `CALL`
274    /// handler recognizes.
275    ShowProcedures(ShowProceduresClause),
276    /// `SHOW SETTING[S] [<names>] [YIELD ...] [WHERE ...]` (CIP-68 grammar
277    /// foundation). Relate has no configurable settings surface, so
278    /// this always reports an empty catalog.
279    ShowSettings(ShowSettingsClause),
280    /// `SHOW TRANSACTION[S] [<ids>] [YIELD ...] [WHERE ...]` (CIP-68
281    /// grammar foundation). Relate executes each statement to
282    /// completion without exposing concurrent transaction identifiers, so
283    /// this always reports an empty catalog.
284    ShowTransactions(ShowTransactionsClause),
285    /// `TERMINATE TRANSACTION[S] <ids> [YIELD ...]` (CIP-68 grammar
286    /// foundation). Since `ShowTransactions` never reports a live
287    /// transaction, every requested id is reported as not found.
288    TerminateTransactions(TerminateTransactionsClause),
289    /// `USE <graph-expr>` (CIP-141 feature-interaction scenarios) -- a
290    /// graph-selector clause. Relate is a single-database engine, so
291    /// this is parsed and scope-checked (its expression's variables must
292    /// be in scope, same as any other clause) but has no runtime effect
293    /// beyond that: there is no composite/multi-graph database to switch
294    /// to.
295    Use(UseClause),
296    /// `FINISH` (CIP-140) -- a terminal clause producing a truly empty
297    /// result (0 rows, 0 columns) instead of RETURN's projected rows,
298    /// while still running any earlier updating clauses. Only the minimal
299    /// semantics needed by CIP-218's `CALL (a) { FINISH }` scenario are
300    /// implemented: cardinality is preserved (one output row per input
301    /// row) but that row carries no columns, so it contributes nothing
302    /// when merged back into an enclosing CALL's outer row.
303    Finish,
304    /// CIP-168: a standalone `<order by and page statement>` -- e.g.
305    /// `ORDER BY n.name SKIP 1 LIMIT 3` appearing as its own clause, not
306    /// attached to WITH/RETURN/YIELD. Acts as an implicit `WITH *`
307    /// horizon clause: changes row order/count but never the column set,
308    /// and may sit between any two other clauses (including two write
309    /// clauses). See `StandaloneOrderByClause` for why this is a sequence
310    /// of stages rather than three fixed fields.
311    StandaloneOrderBy(StandaloneOrderByClause),
312    /// CIP-135: a standalone conditional clause chain --
313    /// `<when query> ::= <when>, {<when>}, [<else>]`. This is a *sibling*
314    /// alternative to `<union query>`/`<single query>` at the `<regular
315    /// query>` grammar level (see `parse_regular_query`), not an ordinary
316    /// mid-statement clause -- so this variant only ever appears as the
317    /// sole element of a `Statement.clauses` vec, never alongside other
318    /// clauses in the same statement.
319    Conditional(ConditionalClause),
320    /// `ALTER CURRENT GRAPH TYPE SET/ADD/ALTER/DROP { <graph type
321    /// specification body> }` (CIP-176/182/183's mechanism; CIP-187's
322    /// constraint derivation builds on it). `body` is the full CIP-178
323    /// `<graph type specification body>` grammar (node/edge type specs,
324    /// property types, and constraint specs) -- see `GraphTypeBody`.
325    AlterCurrentGraphType(AlterCurrentGraphTypeClause),
326    /// `CREATE GRAPH TYPE <name> [AS] { <graph type specification body> }`
327    /// (CIP-178 grammar; the `AS` keyword is CIP-180's spelling of the same
328    /// body-introducing form). Registers a *named* graph type, independent
329    /// of the database's single unnamed "current" graph type that `ALTER
330    /// CURRENT GRAPH TYPE` manages.
331    CreateGraphType(CreateGraphTypeClause),
332    /// `SHOW GRAPH TYPE <name> [YIELD ...]` (CIP-180's SHOW surface): a
333    /// single-row catalog whose `name`/`body` columns report the named
334    /// graph type's own name and its CIP-180 canonical specification
335    /// string.
336    ShowGraphType(ShowGraphTypeClause),
337    /// `SHOW CURRENT GRAPH TYPE [YIELD ...]` (CIP-176 overview / CIP-184):
338    /// the database's persistent current graph type, reported as a single
339    /// `specification` column (the CIP-180 canonical body string wrapped in
340    /// `{ }`, or the literal `{}` when empty).
341    ShowCurrentGraphType(ShowCurrentGraphTypeClause),
342    /// `ALTER DATABASE <name> [IF EXISTS] SET DEFAULT LANGUAGE CYPHER
343    /// <n>` (CIP-170). Under ADR-0116 ยง2's fixed namespaces this is the
344    /// only supported `ALTER DATABASE` form; every other form is
345    /// recognized and rejected at parse time with CE's
346    /// `UnsupportedAdministrationCommand`.
347    AlterDatabase(AlterDatabaseClause),
348}
349
350impl Clause {
351    /// The Cypher clause keyword(s) for this clause โ€” e.g. `"MATCH"`,
352    /// `"SHOW INDEXES"`, `"LOAD CSV"`. Exhaustive over the enum, so a new
353    /// clause cannot ship without a renderable name; the planner's
354    /// `clause_keyword` delegates here rather than keeping a second table.
355    pub fn keyword(&self) -> &'static str {
356        match self {
357            Clause::Match(_) => "MATCH",
358            Clause::Create(_) => "CREATE",
359            Clause::Merge(_) => "MERGE",
360            Clause::Delete(_) => "DELETE",
361            Clause::Set(_) => "SET",
362            Clause::Remove(_) => "REMOVE",
363            Clause::Return(_) => "RETURN",
364            Clause::With(_) => "WITH",
365            Clause::Unwind(_) => "UNWIND",
366            Clause::CreateIndex(_) => "CREATE INDEX",
367            Clause::DropIndex(_) => "DROP INDEX",
368            Clause::CreateConstraint(_) => "CREATE CONSTRAINT",
369            Clause::DropConstraint(_) => "DROP CONSTRAINT",
370            Clause::Foreach(_) => "FOREACH",
371            Clause::LoadCSV(_) => "LOAD CSV",
372            Clause::CallSubquery(_) | Clause::CallProcedure(_) => "CALL",
373            Clause::ShowFunctions(_) => "SHOW FUNCTIONS",
374            Clause::ShowConstraints(_) => "SHOW CONSTRAINTS",
375            Clause::ShowIndexes(_) => "SHOW INDEXES",
376            Clause::ShowDatabases(_) => "SHOW DATABASES",
377            Clause::ShowRoles(_) => "SHOW ROLES",
378            Clause::ShowServers(_) => "SHOW SERVERS",
379            Clause::ShowUsers(_) => "SHOW USERS",
380            Clause::ShowProcedures(_) => "SHOW PROCEDURES",
381            Clause::ShowSettings(_) => "SHOW SETTINGS",
382            Clause::ShowTransactions(_) => "SHOW TRANSACTIONS",
383            Clause::TerminateTransactions(_) => "TERMINATE TRANSACTIONS",
384            Clause::Use(_) => "USE",
385            Clause::Finish => "FINISH",
386            Clause::StandaloneOrderBy(_) => "ORDER BY",
387            Clause::Conditional(_) => "WHEN",
388            Clause::AlterCurrentGraphType(_) => "ALTER CURRENT GRAPH TYPE",
389            Clause::CreateGraphType(_) => "CREATE GRAPH TYPE",
390            Clause::ShowGraphType(_) => "SHOW GRAPH TYPE",
391            Clause::ShowCurrentGraphType(_) => "SHOW CURRENT GRAPH TYPE",
392            Clause::AlterDatabase(_) => "ALTER DATABASE",
393        }
394    }
395}
396
397mod expr_children;
398pub use expr_children::{ExprEdge, ExprEdgeMut};