Skip to main content

dr_strange_parser/
ast.rs

1//! The parser-level AST. Deliberately *not* core's `LogicalPlan`: a Cypher
2//! pattern binds several variables, but core's linear-pipeline row model only
3//! ever sees a single "current node" (arch/03 §2). So property/label access
4//! here keeps its variable qualifier (`p.year`, `q:Paper`); the compiler
5//! ([`crate::compile`]) is what decides *where* in the pipeline each predicate
6//! belongs and drops the qualifier when it lands on that variable's slot.
7
8use dr_strange_core::AggFunc;
9use dr_strange_core::Metric;
10use dr_strange_core::PropValue;
11use dr_strange_core::compute::expr::{ArithOp, CmpOp, LogicOp, StrOp};
12use dr_strange_core::types::Dir;
13
14/// A whole parsed query: a source (a `MATCH` pattern or one of the retrieval
15/// seeds), zero or more `BEAM` hops, then `[WHERE …] RETURN … [ORDER BY …]
16/// [SKIP n] [LIMIT n] [AS OF …]`.
17#[derive(Debug, Clone, PartialEq)]
18pub struct Query {
19    pub source: QuerySource,
20    pub beams: Vec<BeamClause>,
21    pub where_clause: Option<PExpr>,
22    pub ret: Return,
23    pub order_by: Vec<OrderKey>,
24    pub skip: Option<u64>,
25    pub limit: Option<u64>,
26    /// `AS OF <seq|"timestamp">` — read a past snapshot. Not part of the
27    /// compiled plan: it addresses the *plane handle*, so it rides beside it.
28    pub as_of: Option<AsOfSpec>,
29}
30
31/// The point `AS OF` pins reads to. A bare integer is a commit sequence; a
32/// quoted RFC-3339 instant and `TIME <ms>` are both wall-clock addresses.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum AsOfSpec {
35    Seq(u64),
36    /// Unix-epoch milliseconds.
37    Time(i64),
38}
39
40/// `BEAM (result[:Label]) <OUT|IN|BOTH> [:TYPE] [ON prop] NEAR <query>
41/// [METRIC m] WIDTH w DEPTH d` — similarity-guided beam traversal from the
42/// current frontier (compiles to `Step::ExpandBeam`), binding `result` as the
43/// new current node.
44#[derive(Debug, Clone, PartialEq)]
45pub struct BeamClause {
46    pub node: NodePat,
47    pub dir: Dir,
48    pub edge_type: Option<String>,
49    /// `None` ⇒ the conventional embedding property (see [`crate::compile`]).
50    pub property: Option<String>,
51    pub query: VecArg,
52    pub metric: Metric,
53    pub width: u32,
54    pub depth: u32,
55}
56
57/// Where the query's rows originate. Every form binds exactly one node pattern
58/// (`first`) and may continue with a relationship tail (`rest`) — so a typed
59/// hop can follow a retrieval seed just as it follows a `MATCH` node, and the
60/// rest of the query (WHERE/RETURN/ORDER BY/…) is shared by all of them.
61#[derive(Debug, Clone, PartialEq)]
62pub struct QuerySource {
63    pub kind: SourceKind,
64    pub first: NodePat,
65    pub rest: Vec<(RelPat, NodePat)>,
66}
67
68/// What seeds a query's rows.
69#[derive(Debug, Clone, PartialEq)]
70pub enum SourceKind {
71    /// `MATCH (a:Label)…` — a scan of the first node's label.
72    Match,
73    /// `SEARCH (v:Label) [ON prop] NEAR "text"|[..] [METRIC m] [TOPK k]` — the
74    /// indexed vector seed (`Source::VectorTopK`).
75    Search {
76        /// `None` ⇒ the conventional embedding property (see [`crate::compile`]).
77        property: Option<String>,
78        query: VecArg,
79        metric: Metric,
80        k: u64,
81    },
82    /// `SEARCH (v:Label) ON prop MATCHING "text" [TOPK k]` — the BM25 keyword
83    /// seed (`Source::KeywordTopK`). `ON` is required here: keyword properties
84    /// follow no convention, so there is nothing sound to default to.
85    Keyword {
86        property: Option<String>,
87        query: String,
88        k: u64,
89    },
90    /// `HYBRID (v:Label) …` — fused retrieval (`Source::Hybrid`).
91    Hybrid(HybridClause),
92    /// `CALL name(args) ON (v:Label)` — a graph algorithm (`Source::Algo`).
93    Call(CallClause),
94}
95
96/// `HYBRID (v:Label) [VECTOR ON p NEAR q [METRIC m] [WEIGHT w]]
97/// [KEYWORD ON p MATCHING "text" [WEIGHT w]]
98/// [GRAPH HOPS h DECAY d [SEEDS n] [WEIGHT w]] [CANDIDATES n] [TOPK k]` —
99/// every channel optional, but at least one required.
100#[derive(Debug, Clone, PartialEq)]
101pub struct HybridClause {
102    pub vector: Option<HybridVector>,
103    pub keyword: Option<HybridKeyword>,
104    pub graph: Option<HybridGraph>,
105    pub candidates: Option<u64>,
106    pub k: Option<u64>,
107}
108
109#[derive(Debug, Clone, PartialEq)]
110pub struct HybridVector {
111    /// `None` ⇒ the conventional embedding property (see [`crate::compile`]).
112    pub property: Option<String>,
113    pub query: VecArg,
114    pub metric: Metric,
115    pub weight: Option<f32>,
116}
117
118#[derive(Debug, Clone, PartialEq)]
119pub struct HybridKeyword {
120    /// Required in practice — the compiler rejects `None` with a clear error,
121    /// since keyword properties follow no convention to default to.
122    pub property: Option<String>,
123    pub query: String,
124    pub weight: Option<f32>,
125}
126
127#[derive(Debug, Clone, PartialEq)]
128pub struct HybridGraph {
129    pub hops: u32,
130    /// `None` ⇒ the same default the RPC/MCP/CLI surfaces use (see
131    /// [`crate::compile`]).
132    pub decay: Option<f32>,
133    pub seeds: Option<u64>,
134    pub weight: Option<f32>,
135}
136
137/// `CALL name(arg: value, …)` — an algorithm invocation. The compiler checks
138/// the name and its arguments; the grammar accepts any named-argument list so
139/// a typo reports as an unknown algorithm/argument rather than a parse error.
140#[derive(Debug, Clone, PartialEq)]
141pub struct CallClause {
142    pub name: String,
143    pub args: Vec<(String, Val)>,
144}
145
146/// A query-vector argument: either a literal vector (programmatic) or text to
147/// embed server-side (the ergonomic default — no 1024-float client payload).
148#[derive(Debug, Clone, PartialEq)]
149pub enum VecArg {
150    Vector(Vec<f32>),
151    Text(String),
152}
153
154/// A single linear path: one node, then zero or more `(relationship, node)`
155/// hops. Branching patterns are not supported in this cut.
156#[derive(Debug, Clone, PartialEq)]
157pub struct Pattern {
158    pub first: NodePat,
159    pub rest: Vec<(RelPat, NodePat)>,
160}
161
162#[derive(Debug, Clone, PartialEq)]
163pub struct NodePat {
164    pub var: Option<String>,
165    pub label: Option<String>,
166}
167
168#[derive(Debug, Clone, PartialEq)]
169pub struct RelPat {
170    /// `-[r:T]->` binds the relationship, so its properties, type and
171    /// direction can be read. A hop is one edge, so the compiler refuses a
172    /// variable on a variable-length hop.
173    pub var: Option<String>,
174    pub dir: Dir,
175    pub ty: Option<String>,
176    /// `Some` for a variable-length relationship (`*`, `*n`, `*n..m`, `*..m`).
177    pub var_len: Option<VarLen>,
178}
179
180/// Variable-length bounds. `max = None` is an unbounded `*` / `*n..`, which the
181/// compiler rejects (core's `ExpandVar` needs a concrete upper bound).
182#[derive(Debug, Clone, Copy, PartialEq)]
183pub struct VarLen {
184    pub min: u32,
185    pub max: Option<u32>,
186}
187
188/// `RETURN [DISTINCT] <item> [, <item>]*`.
189///
190/// An item naming a node (`n`, `*`) returns node rows; anything else returns
191/// a table. The two cannot be mixed: a node is not a value (see
192/// [`crate::compile`]).
193#[derive(Debug, Clone, PartialEq)]
194pub struct Return {
195    pub distinct: bool,
196    pub items: Vec<ReturnItem>,
197}
198
199#[derive(Debug, Clone, PartialEq)]
200pub enum ReturnItem {
201    /// `RETURN *` — the matching rows themselves.
202    Star,
203    /// `RETURN n` — likewise, named by their variable.
204    Var(String),
205    /// `RETURN n.year [AS y]` — a projected column.
206    Value { expr: PExpr, name: String },
207    /// `RETURN count(*) [AS n]` — a column folded over each group.
208    Agg {
209        func: AggFunc,
210        /// `None` for `count(*)`, which reads no value.
211        arg: Option<PExpr>,
212        distinct: bool,
213        name: String,
214    },
215}
216
217/// `ORDER BY <key> [ASC|DESC]`. A projecting query orders by column, which
218/// `text` is what names.
219#[derive(Debug, Clone, PartialEq)]
220pub struct OrderKey {
221    pub target: SortTarget,
222    /// The key's source text, trimmed: the name an unaliased `RETURN` item
223    /// takes, so `ORDER BY count(*)` finds its column.
224    pub text: String,
225    pub descending: bool,
226}
227
228/// What an `ORDER BY` key names.
229#[derive(Debug, Clone, PartialEq)]
230pub enum SortTarget {
231    /// An expression — `ORDER BY n.year DESC`.
232    Expr(PExpr),
233    /// A bare name: a `RETURN` alias, which only a projecting query has. A
234    /// bare variable is not an expression in this language.
235    Name(String),
236    /// An aggregate — `ORDER BY count(*) DESC` — which names the projected
237    /// column that folds the same way, however that column was spelled.
238    Agg {
239        func: AggFunc,
240        arg: Option<PExpr>,
241        distinct: bool,
242    },
243}
244
245/// A parsed expression. Mirrors core's `Expr` but with variable-qualified
246/// property/label access so the compiler can attribute each term to a pattern
247/// variable. Reuses core's operator enums so compilation is a plain 1:1 map.
248#[derive(Debug, Clone, PartialEq)]
249pub enum PExpr {
250    Lit(PropValue),
251    /// A `$name` parameter placeholder used as a value — resolved from the
252    /// caller's params at parse time.
253    Param(String),
254    Prop {
255        var: String,
256        key: String,
257    },
258    HasLabel {
259        var: String,
260        label: String,
261    },
262    /// `key(v)` — the node's external key. An equality (or `IN`) on the
263    /// source variable compiles to a `SeekKeys` seek rather than a filter.
264    ExternalKey {
265        var: String,
266    },
267    /// `type(r)` — the bound relationship's type name.
268    EdgeTypeOf {
269        var: String,
270    },
271    /// `direction(r)` — which way the row walked the bound relationship,
272    /// `"OUT"` or `"IN"`. Never `"BOTH"`: a row's traversal is concrete even
273    /// when the pattern asked for `-[r]-`.
274    EdgeDirOf {
275        var: String,
276    },
277    /// `x IN [a, b, …]` — sugar for a chain of equalities.
278    In {
279        lhs: Box<PExpr>,
280        list: Vec<PExpr>,
281    },
282    /// `x IN <expr>` where the right side is not a literal list — membership
283    /// in a value only known per row (a `List` property, or a `Map`'s keys).
284    /// Kept apart from [`PExpr::In`] because that one is sugar the compiler
285    /// expands into equalities (and, on `key(n)`, into a seek); this one
286    /// cannot be, since the haystack isn't known until the row is.
287    InValue {
288        lhs: Box<PExpr>,
289        haystack: Box<PExpr>,
290    },
291    /// `a CONTAINS b`, `a STARTS WITH b`, `a ENDS WITH b`.
292    StringMatch {
293        op: StrOp,
294        lhs: Box<PExpr>,
295        rhs: Box<PExpr>,
296    },
297    IsNull(Box<PExpr>),
298    Not(Box<PExpr>),
299    Neg(Box<PExpr>),
300    Compare {
301        op: CmpOp,
302        lhs: Box<PExpr>,
303        rhs: Box<PExpr>,
304    },
305    Logic {
306        op: LogicOp,
307        lhs: Box<PExpr>,
308        rhs: Box<PExpr>,
309    },
310    Arith {
311        op: ArithOp,
312        lhs: Box<PExpr>,
313        rhs: Box<PExpr>,
314    },
315    // ---- scoring terms (vector search) ----
316    /// The row's similarity score channel — `score()`.
317    Score,
318    /// Hops taken to reach the current node — `hops()`.
319    Hops,
320    /// `similarity(v.prop, <query>, metric)` — higher is closer.
321    Similarity {
322        var: String,
323        property: String,
324        query: VecArg,
325        metric: Metric,
326    },
327    /// `distance(v.prop, <query>, metric)` — lower is closer.
328    Distance {
329        var: String,
330        property: String,
331        query: VecArg,
332        metric: Metric,
333    },
334}
335
336// ---- write statements -----------------------------------------------------
337
338/// A parsed top-level statement: a read (compiles to a `LogicalPlan`) or a
339/// write (executed against a `WriteTxn`).
340#[derive(Debug, Clone, PartialEq)]
341pub enum StmtAst {
342    // Boxed: a read `Query` is far larger than a `WriteAst`.
343    Read(Box<Query>),
344    Write(WriteAst),
345}
346
347/// A write statement: either a standalone `CREATE`, or a `MATCH … [WHERE …]`
348/// that binds the terminal node variable, followed by mutation ops that operate
349/// on it (`SET`/`REMOVE`/`DELETE`).
350#[derive(Debug, Clone, PartialEq)]
351pub struct WriteAst {
352    pub match_clause: Option<MatchClause>,
353    pub ops: Vec<WriteOp>,
354}
355
356/// The read half of a `MATCH … [WHERE …] SET/REMOVE/DELETE` — a pattern to find
357/// nodes to mutate. Compiled to a read `LogicalPlan` whose terminal node is the
358/// bound variable.
359#[derive(Debug, Clone, PartialEq)]
360pub struct MatchClause {
361    pub pattern: Pattern,
362    pub where_clause: Option<PExpr>,
363}
364
365#[derive(Debug, Clone, PartialEq)]
366pub enum WriteOp {
367    /// `CREATE (n:L {..}), (a)-[:T {..}]->(b), …`
368    Create(Vec<CreatePath>),
369    /// `MERGE (n:L {key:"k", ..}) [ON CREATE SET …] [ON MATCH SET …]`
370    Merge(MergeClause),
371    /// `SET n.p = v, n:Label, n += {..}`
372    Set(Vec<SetItem>),
373    /// `REMOVE n.p, n:Label`
374    Remove(Vec<RemoveItem>),
375    /// `[DETACH] DELETE n, m, …`
376    Delete { detach: bool, vars: Vec<String> },
377}
378
379/// `MERGE (a {key}) [ON CREATE SET …] [ON MATCH SET …]` — upsert one node by
380/// its external key — or `MERGE (a {key})-[:T]->(b {key})` — upsert each keyed
381/// node and ensure the edge (element-wise, idempotent). `path` reuses the CREATE
382/// path shape; `on_create`/`on_match` apply only to a single-node MERGE.
383#[derive(Debug, Clone, PartialEq)]
384pub struct MergeClause {
385    pub path: CreatePath,
386    pub on_create: Vec<SetItem>,
387    pub on_match: Vec<SetItem>,
388}
389
390/// A property value: a literal, or a `$name` parameter placeholder resolved
391/// from the caller's params at parse time.
392#[derive(Debug, Clone, PartialEq)]
393pub enum Val {
394    Lit(PropValue),
395    Param(String),
396}
397
398#[derive(Debug, Clone, PartialEq)]
399pub enum SetItem {
400    /// `n.key = value`
401    Prop {
402        var: String,
403        key: String,
404        value: Val,
405    },
406    /// `n:Label` — add a label.
407    Label { var: String, label: String },
408    /// `n += { .. }` — merge properties.
409    Merge {
410        var: String,
411        props: Vec<(String, Val)>,
412    },
413}
414
415#[derive(Debug, Clone, PartialEq)]
416pub enum RemoveItem {
417    /// `n.key` — remove a property.
418    Prop { var: String, key: String },
419    /// `n:Label` — remove a label.
420    Label { var: String, label: String },
421}
422
423/// One CREATE path: a node, then directed `[:TYPE {..}]` hops to more nodes.
424#[derive(Debug, Clone, PartialEq)]
425pub struct CreatePath {
426    pub first: CreateNode,
427    pub rest: Vec<(CreateRel, CreateNode)>,
428}
429
430/// A node in a CREATE: optional variable (to reference within the statement),
431/// optional label, optional external `key` (from an inline `key: "…"`), and the
432/// remaining inline properties.
433#[derive(Debug, Clone, PartialEq)]
434pub struct CreateNode {
435    pub var: Option<String>,
436    pub label: Option<String>,
437    /// The external key: a string literal, or a `$param` the write resolves
438    /// (and requires to be a string) before it runs.
439    pub key: Option<Val>,
440    pub props: Vec<(String, Val)>,
441}
442
443/// A relationship in a CREATE: a required type, a direction (`->`/`<-`; never
444/// undirected — dr-strange edges are directed), and inline properties.
445#[derive(Debug, Clone, PartialEq)]
446pub struct CreateRel {
447    pub dir: Dir,
448    pub ty: String,
449    pub props: Vec<(String, Val)>,
450}