Skip to main content

dr_strange_parser/
lib.rs

1//! dr-strange's query language: an openCypher subset that parses into core's
2//! `LogicalPlan` (arch/00 §5 — "a Cypher/GQL-subset parser lands in v2 on top
3//! of the same logical plan layer"). The `nom` grammar and the plan compiler
4//! live here so the parser-combinator dependency never reaches the lean core;
5//! the crate depends on core only for the plan types it targets.
6//!
7//! ```text
8//! MATCH (p:Paper)-[:CITES]->(q:Paper)
9//! WHERE p.year >= 2020
10//! RETURN q
11//! ORDER BY q.year DESC
12//! LIMIT 10
13//! ```
14//!
15//! # Supported
16//! Every source below binds one node pattern and may continue with a
17//! relationship tail, so a typed hop chains off a retrieval seed exactly as it
18//! does off a `MATCH` node (ROADMAP §7).
19//! - `MATCH` one linear path: `(a:Label)`, `-[:TYPE]->` / `<-[:TYPE]-` / `-[:T]-`
20//!   (in/out/both), bare `-->`/`--`, and bounded variable-length `-[:T*1..3]->`.
21//! - **`SEARCH (v:Label) [ON prop] NEAR "text"|[..] [METRIC m] [TOPK k]`** — an
22//!   indexed vector seed (`Source::VectorTopK`). `"text"` is embedded server-side
23//!   via [`parse_with_embedder`]; `[..]` is a literal escape hatch. `ON` may be
24//!   omitted: every `NEAR` defaults to the `embedding` property, which is what
25//!   the digest pipeline writes.
26//! - **`SEARCH (v:Label) ON prop MATCHING "text" [TOPK k]`** — a BM25 keyword
27//!   seed (`Source::KeywordTopK`) over a declared keyword index. Same verb as
28//!   the vector seed, different operator: `NEAR` compares meaning, `MATCHING`
29//!   compares words.
30//! - **`HYBRID (v:Label) [VECTOR [ON p] NEAR q [METRIC m] [WEIGHT w]]
31//!   [KEYWORD ON p MATCHING "text" [WEIGHT w]]
32//!   [GRAPH HOPS h [DECAY d] [SEEDS n] [WEIGHT w]] [CANDIDATES n] [TOPK k]`** —
33//!   fused retrieval (`Source::Hybrid`); channels in any order, at least one of
34//!   VECTOR/KEYWORD.
35//! - **`CALL <pagerank|components|shortest_path|louvain>(arg: v, …) ON (v[:Label])`**
36//!   — a graph algorithm as a source (`Source::Algo`). `ON` both scopes the
37//!   algorithm and binds the variable; the per-node result rides `score()`.
38//! - **`BEAM (result[:Label]) <OUT|IN|BOTH> [:TYPE] ON prop NEAR "text"|[..]
39//!   [METRIC m] WIDTH w DEPTH d`** — similarity-guided beam traversal
40//!   (`Step::ExpandBeam`) from the current frontier; chains after any source.
41//! - `WHERE` over `=,<>,!=,<,<=,>,>=`, `AND`/`OR`/`NOT`, `+ - * /`, `IS [NOT] NULL`,
42//!   `x IN [a, b]`, property access `a.key`, the label predicate `a:Label`, the
43//!   external key `key(a)`, and the scoring terms `score()`, `hops()`,
44//!   `similarity(a.prop, "text"|[..][, metric])`, `distance(...)` (usable in
45//!   `ORDER BY` too — a brute-force rank).
46//! - **A bound relationship** — `-[r:T]->` — read with `r.key`, `type(r)` and
47//!   `direction(r)` (`"OUT"`/`"IN"`, the way the row walked it, never
48//!   `"BOTH"`). A relationship is addressed by which hop it is, so a variable
49//!   is refused where that would not name one edge: on a variable-length hop,
50//!   bound twice, or sharing a node's name.
51//! - `RETURN [DISTINCT] <var|*>` — node records — or a **projection**:
52//!   `RETURN a.name, count(*) AS n, …`, each item a column named by its alias
53//!   or its own text, over any variable the pattern bound (an earlier one
54//!   compiles to `Expr::At`). Folds: `count`/`sum`/`avg`/`min`/`max`/`collect`,
55//!   each optionally `DISTINCT`, grouped by every column that isn't one.
56//! - `ORDER BY expr [ASC|DESC], …`, `SKIP n`, `LIMIT n` — steps over node rows;
57//!   on the projection tail otherwise, where `ORDER BY` names a returned column
58//!   (by alias, by the expression it returned, or by the aggregate it folds:
59//!   `ORDER BY count(*)`).
60//! - **`AS OF <seq|"RFC-3339"|TIME <ms>>`** — last clause; reads a past
61//!   snapshot (native backend). Not a plan node: it rides on [`ReadQuery`] for
62//!   the surface to apply with `PlaneHandle::as_of`.
63//!
64//! `key(n) = "…"` (or `key(n) IN […]`) on a scanned source compiles to a
65//! `SeekKeys` seek rather than a scan-and-filter — an index lookup, so an LLM
66//! can anchor on an entity it knows by key.
67//!
68//! # Writes (via [`parse_statement`], applied with [`WriteStatement::apply`])
69//! - `CREATE (n:L {k: v, …}), (a)-[:T {…}]->(b), …` — a string `key:` sets the
70//!   external key; edges are directed (`->`/`<-`).
71//! - `MERGE (n:L {key: "…", …}) [ON CREATE SET …] [ON MATCH SET …]` — upsert a
72//!   node by its external key; a path `MERGE (a {key})-[:T]->(b {key})` upserts
73//!   each keyed node and ensures the edge (idempotent, element-wise — also
74//!   against what earlier clauses of the same statement created).
75//! - `MATCH pattern [WHERE …] SET n.p = v, n:Label, n += {…}` /
76//!   `REMOVE n.p, n:Label` / `[DETACH] DELETE n` — find-then-mutate on the
77//!   pattern's terminal variable, once per distinct matched node however many
78//!   paths reach it (plain `DELETE` refuses a connected node).
79//! - `MATCH pattern [WHERE …] CREATE (n)-[:T]->(x {…})` /
80//!   `MERGE (n)-[:T]->(x {key})` — once per matched row, with the terminal
81//!   variable pre-bound so `(n)` anchors to the matched node.
82//!
83//! # Parameters
84//! `$name` placeholders in value positions (WHERE/ORDER literals, SET/CREATE/
85//! MERGE props, and a node's `key:`) are resolved from a caller-supplied
86//! [`Params`] map via [`parse_statement_full`] — the SDK-safe way to pass
87//! values (no string interpolation).
88//!
89//! # Null
90//! Core's evaluator is two-valued: a missing property makes a predicate
91//! false, so left alone `n.p <> 1`, `NOT n.p = 1` and `NOT n.p IN [..]` would
92//! be *true* for a node with no `p`. The compiler guards those — `<>`, `NOT`,
93//! and `=` with no constant side — with `IS NOT NULL` on every property (or
94//! channel, or literal `null`) they read, so for a predicate over one
95//! property the rows match openCypher: a missing value satisfies neither the
96//! test nor its negation, `n.p = null` keeps nothing, and `IS [NOT] NULL` is
97//! how absence is asked about. Where this is stricter than openCypher: under
98//! `NOT`, a compound predicate whose false branch would have absorbed a null
99//! (`NOT (n.a = 1 AND n.b = 2)` keeps a node with `b = 3` and no `a` there,
100//! not here); and `x IN [1, null]` is null here even when `x = 1`. Ordered
101//! comparisons, `IN` and the string predicates are already false on a
102//! missing value and stay unguarded.
103//!
104//! # Lexical rules
105//! Keywords and function names are case-insensitive. Identifiers are Unicode
106//! words, or anything between backticks. Strings take either quote with the
107//! escapes `\'` `\"` `\\` `\n` `\t` `\r` `\b` `\f` `\uXXXX`; numbers are
108//! ints or floats (`1.5`, `1e9`). Expressions nest at most
109//! `parse::MAX_NESTING` levels, an operator of an `AND`/`OR`/arithmetic chain
110//! counting one; deeper is a syntax error, not a stack overflow.
111//!
112//! # Not yet (each a clear error naming the rewrite, never a silent miscompile)
113//! - cross-variable predicates (`p.year < q.year`);
114//! - returning the *rows* of a non-terminal variable (`RETURN p` after a hop);
115//!   its values project (`RETURN p.name`);
116//! - `WITH` pipelining: a projection is a tail, so nothing follows it;
117//! - unbounded variable-length (`*`, `*n..`);
118//! - a second `MATCH`, `OPTIONAL MATCH`, `UNION`, `UNWIND`, and a pattern with
119//!   several paths (`(a)-->(b), (a)-->(c)`): a query holds one linear path —
120//!   run one query per pattern or branch;
121//! - returning a bound relationship (`RETURN r`): its values project
122//!   (`RETURN r.key, type(r)`);
123//! - inline property predicates in a `MATCH` node (`(n {name: "x"})`): write
124//!   them in `WHERE`;
125//! - list and map literals as values (`RETURN [1, 2]`, `n.x = {a: 1}`); a
126//!   list is only sugar after `IN` (and a vector after `NEAR`), a map only a
127//!   `CREATE`/`SET` property map;
128//! - the `%` and `^` operators.
129//!
130//! Errors point at the fault: a mistyped clause is reported from the reading
131//! of the statement that got furthest, not from the first token.
132//!
133//! # Completing a prefix
134//! [`complete`] answers the other question an editor asks: not "is this a
135//! statement" but "what could this become". It reads a half-typed query
136//! against a plane's [`Vocab`] — its labels, edge types and properties, with
137//! the counts — so the guess after `MATCH ` is the label that plane holds most
138//! of, and the guess after a node is the edge that most often leaves it. It is
139//! a second, smaller reading of this same grammar; see [`complete`] for why a
140//! `nom` parser cannot do it.
141
142mod ast;
143mod compile;
144mod complete;
145mod hint;
146mod parse;
147mod write;
148
149use ahash::AHashMap;
150
151use dr_strange_core::{LogicalPlan, PropValue};
152
153pub use ast::AsOfSpec;
154pub use complete::{
155    Completion, Connection, EdgeInfo, Expect, Kind, LabelInfo, Suggestion, Vocab, complete,
156};
157pub use hint::grammar_hint;
158pub use write::{WriteStatement, WriteSummary};
159
160/// Values for `$name` placeholders in a query, supplied by the caller and
161/// resolved at parse time (so no string interpolation — the SDK-safe way to
162/// pass values). Keyed by the bare name (no `$`).
163pub type Params = AHashMap<String, PropValue>;
164
165/// Resolve a `$name` placeholder against the caller's params.
166pub(crate) fn resolve_param(params: &Params, name: &str) -> Result<PropValue, String> {
167    params
168        .get(name)
169        .cloned()
170        .ok_or_else(|| format!("unbound parameter `${name}`"))
171}
172
173/// A parsed statement: a read (a runnable plan) or a write (applied with
174/// [`WriteStatement::apply`]). Surfaces branch on this to run a query.
175#[derive(Debug)]
176pub enum Statement {
177    Read(ReadQuery),
178    Write(WriteStatement),
179}
180
181/// A compiled read: the plan to run, and the snapshot to run it against.
182///
183/// `AS OF` is not a plan node — it addresses the *plane handle* — so it rides
184/// alongside. A surface applies it with `PlaneHandle::as_of` before running
185/// the plan; `None` reads the latest commit.
186#[derive(Debug, Clone, PartialEq)]
187pub struct ReadQuery {
188    pub plan: LogicalPlan,
189    pub as_of: Option<AsOfSpec>,
190}
191
192/// Resolves the text in a `SEARCH … NEAR "text"` (or `similarity(p, "text")`)
193/// into a query vector. The pure parser owns no embedding machinery — a
194/// surface (web/MCP/CLI) supplies this, backed by the server's configured
195/// provider (API key from the environment, never the client). Keeping it a
196/// one-method trait keeps `dr-strange-parser` dependency-free.
197pub trait Embedder {
198    fn embed(&self, text: &str) -> Result<Vec<f32>, String>;
199}
200
201/// Why a query didn't turn into a plan.
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub enum ParseError {
204    /// The text didn't match the grammar.
205    Syntax(String),
206    /// The text is understood, but the pattern/clauses can't map onto a
207    /// `LogicalPlan` (e.g. a cross-variable predicate, an unbounded `*`, a
208    /// text `NEAR` with no embedder configured) — or it uses an openCypher
209    /// clause this cut recognises and refuses (`WITH`, `UNION`, `OPTIONAL
210    /// MATCH`, …). The message names the rewrite that works.
211    Compile(String),
212}
213
214impl std::fmt::Display for ParseError {
215    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216        match self {
217            ParseError::Syntax(m) => write!(f, "syntax error: {m}"),
218            ParseError::Compile(m) => write!(f, "unsupported query: {m}"),
219        }
220    }
221}
222
223impl std::error::Error for ParseError {}
224
225/// Parse a *read* query into a runnable [`ReadQuery`]. A write statement
226/// (`CREATE`, …) is an error here — use [`parse_statement`]. A text
227/// `SEARCH … NEAR "…"` also errors (no embedder); use [`parse_with_embedder`]
228/// or a literal vector.
229pub fn parse(input: &str) -> Result<ReadQuery, ParseError> {
230    read_only(parse_statement_inner(input, None, &Params::new())?)
231}
232
233/// Like [`parse`], but resolves text `NEAR "…"` terms into query vectors via
234/// `embedder` — the semantic-search entry point the surfaces use for reads.
235pub fn parse_with_embedder(input: &str, embedder: &dyn Embedder) -> Result<ReadQuery, ParseError> {
236    read_only(parse_statement_inner(
237        input,
238        Some(embedder),
239        &Params::new(),
240    )?)
241}
242
243/// Parse a statement — either a read query or a write (`CREATE`, …). This is the
244/// entry point a surface uses when it wants to run *either*.
245pub fn parse_statement(input: &str) -> Result<Statement, ParseError> {
246    parse_statement_inner(input, None, &Params::new())
247}
248
249/// Like [`parse_statement`], but resolves a text `SEARCH … NEAR "…"` via `embedder`.
250pub fn parse_statement_with_embedder(
251    input: &str,
252    embedder: &dyn Embedder,
253) -> Result<Statement, ParseError> {
254    parse_statement_inner(input, Some(embedder), &Params::new())
255}
256
257/// The general entry point: parse a statement, resolving text `SEARCH` via an
258/// optional `embedder` and `$name` placeholders via `params`. The surfaces that
259/// accept parameters (CLI/MCP/plane.cypher) use this.
260pub fn parse_statement_full(
261    input: &str,
262    embedder: Option<&dyn Embedder>,
263    params: &Params,
264) -> Result<Statement, ParseError> {
265    parse_statement_inner(input, embedder, params)
266}
267
268fn read_only(stmt: Statement) -> Result<ReadQuery, ParseError> {
269    match stmt {
270        Statement::Read(read) => Ok(read),
271        Statement::Write(_) => Err(ParseError::Compile(
272            "this is a write statement; run it with parse_statement, not a read query".to_string(),
273        )),
274    }
275}
276
277fn parse_statement_inner(
278    input: &str,
279    embedder: Option<&dyn Embedder>,
280    params: &Params,
281) -> Result<Statement, ParseError> {
282    let (rest, stmt) = parse::statement(input).map_err(diagnose)?;
283    // Everything must be consumed — trailing tokens mean a mistyped clause.
284    let rest = rest.trim_start();
285    if !rest.trim_end().is_empty() {
286        return Err(ParseError::Syntax(format!(
287            "unexpected trailing input near `{}`",
288            snippet(rest.trim_end())
289        )));
290    }
291    Ok(match stmt {
292        ast::StmtAst::Read(query) => {
293            let as_of = query.as_of;
294            let plan = compile::compile(*query, embedder, params).map_err(ParseError::Compile)?;
295            Statement::Read(ReadQuery { plan, as_of })
296        }
297        ast::StmtAst::Write(w) => {
298            Statement::Write(write::compile(w, params.clone()).map_err(ParseError::Compile)?)
299        }
300    })
301}
302
303/// Turn the grammar's failure into the error a caller sees. A recognised but
304/// unsupported shape (`parse::unsupported`) is a `Compile` error carrying its
305/// rewrite hint; anything else is a `Syntax` error located by `describe`.
306fn diagnose(e: nom::Err<nom::error::Error<&str>>) -> ParseError {
307    if let nom::Err::Failure(er) = &e
308        && er.code == nom::error::ErrorKind::Fail
309        && let Some(msg) = parse::take_unsupported()
310    {
311        return ParseError::Compile(msg);
312    }
313    ParseError::Syntax(describe(e))
314}
315
316fn describe(e: nom::Err<nom::error::Error<&str>>) -> String {
317    match e {
318        // The one failure that is about the query's shape, not its text.
319        nom::Err::Failure(er) if er.code == nom::error::ErrorKind::TooLarge => format!(
320            "expression nested deeper than {} levels near `{}`",
321            parse::MAX_NESTING,
322            snippet(er.input.trim())
323        ),
324        nom::Err::Error(er) | nom::Err::Failure(er) => {
325            let at = er.input.trim();
326            if at.is_empty() {
327                "unexpected end of query".to_string()
328            } else {
329                format!("near `{}`", snippet(at))
330            }
331        }
332        nom::Err::Incomplete(_) => "incomplete query".to_string(),
333    }
334}
335
336fn snippet(s: &str) -> &str {
337    let end = s.char_indices().nth(40).map_or(s.len(), |(i, _)| i);
338    &s[..end]
339}