Skip to main content

relate_parser/ast/
expr.rs

1//! Expression nodes.
2
3use super::*;
4
5/// One segment of a CIP-261 interpolated string literal.
6#[derive(Debug, Clone, PartialEq)]
7pub enum InterpPart {
8    /// Literal text (escaped braces already resolved to plain braces).
9    Text(String),
10    /// An `{expression}` embed.
11    Interp(Box<Expr>),
12}
13
14/// All expression types.
15#[derive(Debug, Clone, PartialEq)]
16pub enum Expr {
17    Literal(LiteralValue),
18    List(Vec<Expr>),
19    Map(Vec<MapPair>),
20    /// CIP-261 interpolated string literal: text segments interleaved with
21    /// `{expression}` embeds, lowered to the internal `string.interp`
22    /// function (see `relate/relate-front/src/lower.rs`).
23    StringInterp(Vec<InterpPart>),
24    Variable(SmallName),
25    Parameter(String),
26    Property(Box<PropertyAccess>),
27    FunctionCall(FunctionCallExpr),
28    Binary(Box<BinaryExpr>),
29    Unary(Box<UnaryExpr>),
30    Comparison(Box<ComparisonExpr>),
31    In(Box<InExpr>),
32    IsNull(Box<IsNullExpr>),
33    IsType(Box<IsTypeExpr>),
34    IsNormalized(Box<IsNormalizedExpr>),
35    ChronologicalCompare(Box<ChronologicalCompareExpr>),
36    StringMatch(Box<StringMatchExpr>),
37    CountStar,
38    Star,
39    Case(Box<CaseExpr>),
40    ExistsSubquery(Box<ExistsSubqueryExpr>),
41    CountSubquery(Box<CountSubqueryExpr>),
42    CollectSubquery(Box<CollectSubqueryExpr>),
43    ListComprehension(Box<ListComprehensionExpr>),
44    MapComprehension(Box<MapComprehensionExpr>),
45    PatternComprehension(Box<PatternComprehensionExpr>),
46    Reduce(Box<ReduceExpr>),
47    AllReduce(Box<AllReduceExpr>),
48    ShortestPath(Box<ShortestPathExpr>),
49    Subscript(Box<SubscriptExpr>),
50    Quantifier(Box<QuantifierExpr>),
51    HasLabel(Box<HasLabelExpr>),
52    Paren(Box<Expr>),
53    PatternPredicate(Box<PatternPredicateExpr>),
54    MapProjection(Box<MapProjectionExpr>),
55    /// The canonical `?` marker for an `OPTIONS` value outside the persisted
56    /// five-literal vocabulary (a list, map, temporal, …), produced only when
57    /// a whole-map `OPTIONS $param` is resolved into literal entries. The
58    /// parser never produces it and it references nothing, so no walker can
59    /// mistake it for a variable.
60    OptionValuePlaceholder,
61}
62
63/// A literal value in the AST.
64#[derive(Debug, Clone, PartialEq)]
65pub enum LiteralValue {
66    Null,
67    Bool(bool),
68    Integer(i64),
69    Float(f64),
70    String(String),
71}
72
73/// A key-value pair in a map literal.
74#[derive(Debug, Clone, PartialEq)]
75pub struct MapPair {
76    pub key: SmallName,
77    pub value: Expr,
78}
79
80/// `<variable> <map projection>` (`n {.foo, bar, baz: qux}`): openCypher's
81/// map projection, syntactically always rooted at a plain variable
82/// (`expr` is always an `Expr::Variable`). Needed for CIP-190's
83/// near-ambiguity coverage: `exists {name: exists.name}` etc. must parse
84/// as a map projection on a variable named `exists`, not as
85/// `EXISTS { <subquery> }`, when the filler between the braces looks like
86/// projection items rather than subquery content (near-ambiguities.feature).
87#[derive(Debug, Clone, PartialEq)]
88pub struct MapProjectionExpr {
89    pub expr: Expr,
90    pub items: Vec<MapProjectionItem>,
91}
92
93/// One item of a `<map projection>`.
94#[derive(Debug, Clone, PartialEq)]
95pub enum MapProjectionItem {
96    /// `.*` -- every property of the base entity.
97    AllProperties,
98    /// `.prop` -- shorthand for `prop: <base>.prop`.
99    Property(SmallName),
100    /// A bare `variable` selector -- shorthand for `variable: variable`,
101    /// pulling a same-named variable from the surrounding scope (*not* a
102    /// property of the base expression).
103    Variable(SmallName),
104    /// `key: <expr>` -- a literal entry.
105    KeyValue(SmallName, Expr),
106}
107
108/// Property access like n.prop.
109#[derive(Debug, Clone, PartialEq)]
110pub struct PropertyAccess {
111    pub expr: Expr,
112    pub property: SmallName,
113    /// CIP-131: when a SET/REMOVE target uses the dynamic-property bracket
114    /// form (`n[<expr>]`) instead of the static `n.prop` form, the property
115    /// key is computed at runtime from this expression rather than being the
116    /// statically-known `property` string (which is left empty). `None` for
117    /// every static `.prop` access, keeping `property` back-compatible for
118    /// all existing (non-SET/REMOVE) uses of `PropertyAccess`.
119    pub key_expr: Option<Expr>,
120}
121
122/// Function call like count(x).
123#[derive(Debug, Clone, PartialEq)]
124pub struct FunctionCallExpr {
125    pub name: SmallName,
126    pub args: Vec<Expr>,
127    pub distinct: bool,
128}
129
130/// Binary expression like a + b. `op` is the operator's AST spelling, a
131/// `&'static str` drawn from the parser's operator-constant table
132/// (`parser/mod.rs`, ADR-0505 §2) — never a runtime-built `String`.
133#[derive(Debug, Clone, PartialEq)]
134pub struct BinaryExpr {
135    pub left: Expr,
136    pub op: &'static str,
137    pub right: Expr,
138}
139
140/// Unary expression like NOT x or -x. `op` is the operator's AST spelling,
141/// a `&'static str` drawn from the parser's operator-constant table
142/// (`parser/mod.rs`, ADR-0505 §2) — never a runtime-built `String`.
143#[derive(Debug, Clone, PartialEq)]
144pub struct UnaryExpr {
145    pub op: &'static str,
146    pub expr: Expr,
147}
148
149/// Comparison expression like a > b. `op` is the operator's AST spelling, a
150/// `&'static str` from the `comparison_op` token-to-spelling table
151/// (`parser/mod.rs`, ADR-0505 §2) — never a runtime-built `String`.
152#[derive(Debug, Clone, PartialEq)]
153pub struct ComparisonExpr {
154    pub left: Expr,
155    pub op: &'static str,
156    pub right: Expr,
157}
158
159/// x IN list.
160#[derive(Debug, Clone, PartialEq)]
161pub struct InExpr {
162    pub expr: Expr,
163    pub list: Expr,
164}
165
166/// x IS NULL or x IS NOT NULL.
167#[derive(Debug, Clone, PartialEq)]
168pub struct IsNullExpr {
169    pub expr: Expr,
170    pub negated: bool,
171}
172
173/// x IS [NOT] :: <value type> (CIP-86/CIP-87 type predicate expression);
174/// also produced by the `IS [NOT] TYPED <value type>` and bare `x :: <value
175/// type>` surface forms, which are equivalent.
176#[derive(Debug, Clone, PartialEq)]
177pub struct IsTypeExpr {
178    pub expr: Expr,
179    pub type_expr: TypeExpr,
180    pub negated: bool,
181}
182
183/// A parsed `<value type>` per the CIP-86 grammar: the vocabulary used by
184/// the CIP-87 type predicate expression (`IS [NOT] :: <type>`) and, once
185/// CIP-90 ships, by `valueType()`.
186#[derive(Debug, Clone, PartialEq)]
187pub enum TypeExpr {
188    /// A predefined leaf type: a scalar, temporal, reference, point, map,
189    /// nothing/null, or the open `ANY` type. `not_null` reflects an
190    /// explicit `NOT NULL` suffix directly on this leaf's own grammar
191    /// production (e.g. `INTEGER NOT NULL`).
192    Predefined {
193        kind: PredefinedKind,
194        not_null: bool,
195    },
196    /// `LIST<T>` / `T LIST` / `ARRAY<T>` / `T ARRAY`, with an optional
197    /// `NOT NULL` on the list value itself (not on its elements -- element
198    /// nullability lives in `element`).
199    List {
200        element: Box<TypeExpr>,
201        not_null: bool,
202    },
203    /// `[ANY] PROPERTY VALUE [NOT NULL]`: the dynamic union of every
204    /// property-storable scalar type and lists thereof.
205    PropertyValue { not_null: bool },
206    /// A closed dynamic union -- `ANY [VALUE] <A | B | ...>` or the bare
207    /// `A | B | ...` form (equivalent). The grammar gives closed unions no
208    /// `[NOT NULL]` production of their own, so the parser never attaches
209    /// one here; a trailing `NOT NULL` after a union is a syntax error.
210    Union(Vec<TypeExpr>),
211    /// `VECTOR<TYPE [NOT NULL]>(DIM)` (Cypher style) or `VECTOR(DIM, TYPE
212    /// [NOT NULL])` (GQL style) (CIP-216). Either the coordinate type or
213    /// the dimension may be grammatically omitted (`VECTOR(3)`,
214    /// `VECTOR<INTEGER32>`) -- both parse fine but are rejected at
215    /// constraint-creation time, since a property type constraint requires
216    /// both. The coordinate type's own `NOT NULL` is mandatory/implicit
217    /// (always rendered NOT NULL in canonical form) and so isn't tracked
218    /// separately here; `not_null` is the *outer* NOT NULL on the whole
219    /// vector type (valid grammatically, but rejected for independent
220    /// property type constraints -- CIP-216 doc, "for dependent property
221    /// type constraints only").
222    Vector {
223        coord: Option<VectorCoordKind>,
224        dimension: Option<i64>,
225        not_null: bool,
226    },
227}
228
229impl TypeExpr {
230    /// The `NOT NULL` flag attached directly to this node's own grammar
231    /// production. Used only to check that a closed union's components all
232    /// agree on nullability (CIP-86 "Not Null Uses"); closed unions have no
233    /// such production of their own, so they report `false`.
234    pub fn direct_not_null(&self) -> bool {
235        match self {
236            TypeExpr::Predefined { not_null, .. } => *not_null,
237            TypeExpr::List { not_null, .. } => *not_null,
238            TypeExpr::PropertyValue { not_null } => *not_null,
239            TypeExpr::Vector { not_null, .. } => *not_null,
240            TypeExpr::Union(_) => false,
241        }
242    }
243}
244
245/// A vector coordinate type (CIP-216): the six numeric types valid inside
246/// `VECTOR<...>`/`VECTOR(...)`. `Int64`/`Float64` double as ordinary plain
247/// property types (aliases for `INTEGER`/`FLOAT`, see `PredefinedKind`)
248/// outside a vector type; the other four (`Float32`, `Int8`/`Int16`/
249/// `Int32`) are valid only as a vector coordinate type.
250///
251/// Defined in `relate-model` (so the runtime `CypherValue::Vector`
252/// variant can carry it without a circular crate dependency) and
253/// re-exported here under its original name/location.
254pub use relate_model::VectorCoordKind;
255
256/// The predefined leaf type names from the `<value type>` grammar.
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub enum PredefinedKind {
259    Nothing,
260    Null,
261    Any,
262    Boolean,
263    String,
264    Integer,
265    Float,
266    Date,
267    Duration,
268    Point,
269    LocalTime,
270    ZonedTime,
271    LocalDateTime,
272    ZonedDateTime,
273    Node,
274    Relationship,
275    Path,
276    Map,
277    /// `UUID [NOT NULL]`.
278    Uuid,
279}
280
281/// x IS [NOT] [<normal form>] NORMALIZED (CIP-133). `form` is one of
282/// "NFC"/"NFD"/"NFKC"/"NFKD", or None when the form is omitted (defaults to
283/// NFC at evaluation time).
284#[derive(Debug, Clone, PartialEq)]
285pub struct IsNormalizedExpr {
286    pub expr: Expr,
287    pub form: Option<String>,
288    pub negated: bool,
289}
290
291/// The four chronological comparison operators (Cypher 25):
292/// `a IS [NOT] BEFORE | AFTER | SAME INSTANT | SAME REPRESENTATION b`.
293/// The four words stay non-reserved identifiers everywhere else
294/// (TemporalChronologicalCompare's non-reserved-identifier scenario), so
295/// the parser recognizes them contextually after an `IS` introducer, the
296/// same policy as `TYPED`/`NORMALIZED`/`LABELED`.
297#[derive(Debug, Clone, Copy, PartialEq, Eq)]
298pub enum ChronologicalOp {
299    Before,
300    After,
301    SameInstant,
302    SameRepresentation,
303}
304
305/// `a IS [NOT] <chronological operator> b` (Cypher 25). `SameInstant`
306/// compares UTC instants, `SameRepresentation` the local clock plus zone
307/// identity (the `=` relation), and `Before`/`After` the instant ordering;
308/// the executor owns the null/mixed-kind policy.
309#[derive(Debug, Clone, PartialEq)]
310pub struct ChronologicalCompareExpr {
311    pub left: Expr,
312    pub op: ChronologicalOp,
313    pub right: Expr,
314    pub negated: bool,
315}
316
317/// STARTS WITH, ENDS WITH, CONTAINS. `op` is the operator's AST spelling, a
318/// `&'static str` drawn from the parser's operator-constant table
319/// (`parser/mod.rs`, ADR-0505 §2) — never a runtime-built `String`.
320#[derive(Debug, Clone, PartialEq)]
321pub struct StringMatchExpr {
322    pub left: Expr,
323    pub op: &'static str,
324    pub right: Expr,
325}
326
327/// CASE expression. The simple form's test operand is lowered at parse time
328/// into each `WHEN`'s equality comparison (`parser/case.rs`), so the stored
329/// model is the searched form only: every condition is a predicate.
330#[derive(Debug, Clone, PartialEq)]
331pub struct CaseExpr {
332    pub whens: Vec<WhenClause>,
333    pub else_expr: Option<Expr>,
334}
335
336/// WHEN ... THEN ... part of a CASE: the condition is always a predicate
337/// (the simple form's `operand = value` lowering included).
338#[derive(Debug, Clone, PartialEq)]
339pub struct WhenClause {
340    pub condition: Expr,
341    pub result: Expr,
342}
343
344/// EXISTS { ... } subquery expression.
345#[derive(Debug, Clone, PartialEq)]
346pub struct ExistsSubqueryExpr {
347    pub statement: Statement,
348}
349
350/// COUNT { ... } subquery expression: evaluates to the number of rows the
351/// subquery produces against the current row, run independently per row
352/// (like `EXISTS { ... }`, just returning a count instead of a boolean).
353#[derive(Debug, Clone, PartialEq)]
354pub struct CountSubqueryExpr {
355    pub statement: Statement,
356}
357
358/// `COLLECT { <RegularQuery> }` subquery expression (CIP-71): evaluates the
359/// inner `<RegularQuery>` once per outer row and collects the single
360/// projected column's value from every inner row into a list. Unlike
361/// `EXISTS`/`COUNT`, `COLLECT` has no bare-pattern shorthand -- the inner
362/// query is always a full `<RegularQuery>` (any read clause, including
363/// UNION) and must end in a `RETURN` with exactly one non-`*` return item.
364#[derive(Debug, Clone, PartialEq)]
365pub struct CollectSubqueryExpr {
366    pub statement: Statement,
367}
368
369/// CIP-272 map comprehension: `{k : v IN map [WHERE p] | keyExpr : valueExpr}`
370/// (map source) or `{item IN list [WHERE p] | keyExpr : valueExpr}` (list
371/// source).
372#[derive(Debug, Clone, PartialEq)]
373pub struct MapComprehensionExpr {
374    /// The key binding variable of a map source (`None` for a list source).
375    pub key_var: Option<SmallName>,
376    /// The value binding variable (map source) or the item variable (list
377    /// source).
378    pub value_var: SmallName,
379    pub source_expr: Expr,
380    pub where_expr: Option<Expr>,
381    pub key_expr: Expr,
382    pub value_expr: Expr,
383}
384
385/// [x IN list WHERE pred | expr]
386#[derive(Debug, Clone, PartialEq)]
387pub struct ListComprehensionExpr {
388    pub variable: SmallName,
389    pub list_expr: Expr,
390    pub where_expr: Option<Expr>,
391    pub map_expr: Option<Expr>,
392}
393
394/// [p = (n)-->() | expr] or [(n)-->() | expr]
395#[derive(Debug, Clone, PartialEq)]
396pub struct PatternComprehensionExpr {
397    pub path_variable: Option<SmallName>,
398    pub pattern: PatternPath,
399    pub where_expr: Option<Expr>,
400    pub map_expr: Expr,
401}
402
403/// reduce(accumulator = init, x IN list | expression)
404#[derive(Debug, Clone, PartialEq)]
405pub struct ReduceExpr {
406    pub accumulator: SmallName,
407    pub init_expr: Expr,
408    pub variable: SmallName,
409    pub list_expr: Expr,
410    pub expression: Expr,
411}
412
413/// allReduce(accumulator = init, x IN list | expression, predicate)
414#[derive(Debug, Clone, PartialEq)]
415pub struct AllReduceExpr {
416    pub accumulator: SmallName,
417    pub init_expr: Expr,
418    pub variable: SmallName,
419    pub list_expr: Expr,
420    pub expression: Expr,
421    pub predicate: Expr,
422}
423
424/// shortestPath() / allShortestPaths()
425#[derive(Debug, Clone, PartialEq)]
426pub struct ShortestPathExpr {
427    pub pattern: PatternPath,
428    pub all: bool,
429}
430
431/// expr[index] or expr[from..to]
432#[derive(Debug, Clone, PartialEq)]
433pub struct SubscriptExpr {
434    pub expr: Expr,
435    pub index: Option<Expr>,
436    pub from: Option<Expr>,
437    pub to: Option<Expr>,
438    pub slice: bool,
439}
440
441/// all/any/none/single(x IN list WHERE pred)
442#[derive(Debug, Clone, PartialEq)]
443pub struct QuantifierExpr {
444    pub quantifier: String,
445    pub variable: SmallName,
446    pub list: Expr,
447    pub predicate: Option<Expr>,
448}
449
450/// A label/type predicate: `n:Label`, `n IS Label` (CIP-14), or
451/// `n IS [NOT] LABELED <label-expr>` / the `n IS NOT <label-expr>` shorthand
452/// (CIP-249).
453#[derive(Debug, Clone, PartialEq)]
454pub struct HasLabelExpr {
455    pub expr: Expr,
456    pub label_expr: LabelExpr,
457    /// True for `IS NOT LABELED <LE>` and its `IS NOT <LE>` shorthand, which
458    /// negate the *whole* expression (unlike an inline `!` inside `label_expr`,
459    /// which negates only the following primary).
460    pub negated: bool,
461    /// True for the `IS [NOT] LABELED <LE>` forms (and the `IS NOT
462    /// <LE>` shorthand), which raise a runtime type error for a non-node/
463    /// relationship LHS. False for the pre-existing `:`/bare `IS <LE>`
464    /// forms (CIP-14), which fall back to `false` for a non-entity LHS,
465    /// preserving their original behavior.
466    pub strict: bool,
467}
468
469/// Pattern used as boolean predicate in WHERE, e.g. (n)-[:REL]->(m)
470#[derive(Debug, Clone, PartialEq)]
471pub struct PatternPredicateExpr {
472    pub pattern: PatternPath,
473}