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