Skip to main content

relate_ir/ast/
expr.rs

1//! The expression model: [`Expr`] and the two small types its variants
2//! carry ([`MapProjectionItem`], [`VectorMetric`]), with the methods that
3//! answer questions about an expression itself, plus the binary-operator
4//! vocabulary's shared facts ([`BinaryOp`]'s token spelling, boolean
5//! connectives, and absorbing-constant fold). Split from [`super`] so the
6//! statement/clause vocabulary and the expression vocabulary stay one
7//! concern per file; [`super`] re-exports every item, so the public path is
8//! unchanged (`ast::call` sets the same precedent).
9
10use super::{BinaryOp, ChronoOp, LabelExpr, PathPattern, QuantifierKind, Query, TypeExpr, UnaryOp};
11use relate_names::{SmallName, Token};
12
13#[derive(Debug, Clone, PartialEq)]
14pub enum Expr {
15    /// Executor-internal eager value; never produced by either parser.
16    RuntimeValue(relate_core::Value),
17    Null,
18    Bool(bool),
19    Int(i64),
20    Float(f64),
21    String(String),
22    Parameter(String),
23    Variable(SmallName),
24    Star,
25    Property {
26        expr: Box<Expr>,
27        key: SmallName,
28        /// Token of `key`, set when planning resolves it against a store
29        /// (ADR-0541); `Unresolved` before.
30        key_id: relate_names::Token,
31    },
32    DynamicProperty {
33        expr: Box<Expr>,
34        key: Box<Expr>,
35    },
36    LabelPredicate {
37        expr: Box<Expr>,
38        label_expr: LabelExpr,
39        strict: bool,
40    },
41    Map(Vec<(String, Expr)>),
42    List(Vec<Expr>),
43    /// `PATH [n1, r1, n2, ...]`: the path constructor over its element list.
44    PathConstruct {
45        elements: Vec<Expr>,
46    },
47    Unary {
48        op: UnaryOp,
49        expr: Box<Expr>,
50    },
51    Binary {
52        op: BinaryOp,
53        left: Box<Expr>,
54        right: Box<Expr>,
55    },
56    Function {
57        name: SmallName,
58        distinct: bool,
59        args: Vec<Expr>,
60    },
61    CountStar,
62    Case {
63        /// `(predicate, result)` pairs, evaluated as booleans in order. The
64        /// parser lowers a simple-CASE test operand into each arm's equality
65        /// comparison, so the searched form is the only one that reaches the
66        /// executor.
67        when_then: Vec<(Expr, Expr)>,
68        else_expr: Option<Box<Expr>>,
69    },
70    Subscript {
71        expr: Box<Expr>,
72        index: Box<Expr>,
73    },
74    Slice {
75        expr: Box<Expr>,
76        start: Option<Box<Expr>>,
77        end: Option<Box<Expr>>,
78    },
79    ListComp {
80        ident: SmallName,
81        list: Box<Expr>,
82        predicate: Option<Box<Expr>>,
83        projection: Box<Expr>,
84    },
85    /// CIP-272 map comprehension (lowered from the parser's
86    /// `MapComprehension`).
87    MapComp {
88        /// Key binding of a map source (`None` for a list source).
89        key_ident: Option<SmallName>,
90        value_ident: SmallName,
91        source: Box<Expr>,
92        predicate: Option<Box<Expr>>,
93        key_expr: Box<Expr>,
94        value_expr: Box<Expr>,
95    },
96    Quantifier {
97        kind: QuantifierKind,
98        ident: SmallName,
99        list: Box<Expr>,
100        predicate: Box<Expr>,
101    },
102    Reduce {
103        accumulator: SmallName,
104        initial: Box<Expr>,
105        ident: SmallName,
106        list: Box<Expr>,
107        expression: Box<Expr>,
108    },
109    AllReduce {
110        accumulator: SmallName,
111        initial: Box<Expr>,
112        ident: SmallName,
113        list: Box<Expr>,
114        expression: Box<Expr>,
115        predicate: Box<Expr>,
116    },
117    IsType {
118        expr: Box<Expr>,
119        type_expr: TypeExpr,
120        negated: bool,
121    },
122    IsNormalized {
123        expr: Box<Expr>,
124        form: Option<String>,
125        negated: bool,
126    },
127    ChronoCompare {
128        left: Box<Expr>,
129        op: ChronoOp,
130        right: Box<Expr>,
131        negated: bool,
132    },
133    /// Map projection `expr { key: value, .key, var, .* }`. Typed form of
134    /// what used to be tunnelled through a `__map_projection` pseudo-call.
135    MapProjection {
136        expr: Box<Expr>,
137        items: Vec<MapProjectionItem>,
138    },
139    /// CIP-214 distance-metric keyword (e.g. the `EUCLIDEAN` in
140    /// `vector_distance(a, b, EUCLIDEAN)`), resolved at lowering from the
141    /// bare identifier in the final argument of `vector_distance` /
142    /// `vector_norm`. Only meaningful as an argument to those functions.
143    DistanceMetric(VectorMetric),
144    PatternPred {
145        path: PathPattern,
146    },
147    ShortestPath {
148        all: bool,
149        path: PathPattern,
150    },
151    ExistsSubquery {
152        query: Query,
153    },
154    CountSubquery {
155        query: Query,
156    },
157    CollectSubquery {
158        query: Query,
159        /// The body's own path-variable binding, when the front
160        /// synthesized the body from a pattern comprehension (ADR-0685):
161        /// a comprehension's path variable shadows any outer name of the
162        /// same spelling for the body's whole scope, so the nested seed
163        /// must not import it — the one difference from a user-written
164        /// `collect { … }`, whose rebinding of an outer name is the
165        /// `VariableAlreadyBound` error.
166        path_shadow: Option<SmallName>,
167    },
168}
169
170/// One entry of a map projection (`Expr::MapProjection`).
171#[derive(Debug, Clone, PartialEq)]
172pub enum MapProjectionItem {
173    /// Explicit `key: value` entry.
174    KeyValue { key: SmallName, value: Expr },
175    /// `.key` property shorthand, read from the projection target.
176    Property { key: SmallName },
177    /// Bare variable entry: `var` shorthand for `var: var`.
178    Variable { name: SmallName },
179    /// `.*`: every property of the target.
180    AllProperties,
181}
182
183/// CIP-214 distance metric for `vector_distance` / `vector_norm`.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum VectorMetric {
186    Euclidean,
187    EuclideanSquared,
188    Manhattan,
189    Cosine,
190    Dot,
191    Hamming,
192}
193
194impl VectorMetric {
195    /// Every metric with its keyword — the one vocabulary table
196    /// [`from_name`](Self::from_name) parses and [`name`](Self::name)
197    /// renders, so a new variant cannot parse without also rendering.
198    /// Public beyond the crate so downstream storable-subset tests
199    /// iterate the table itself: a new variant is covered by
200    /// construction, never by a re-derived literal list.
201    pub const ALL: [(&'static str, Self); 6] = [
202        ("EUCLIDEAN", Self::Euclidean),
203        ("EUCLIDEAN_SQUARED", Self::EuclideanSquared),
204        ("MANHATTAN", Self::Manhattan),
205        ("COSINE", Self::Cosine),
206        ("DOT", Self::Dot),
207        ("HAMMING", Self::Hamming),
208    ];
209
210    /// Parse the bare metric keyword (case-insensitive). `None` when the
211    /// identifier is not a known metric, in which case lowering leaves it as
212    /// an ordinary variable reference for the binder to reject.
213    pub fn from_name(name: &str) -> Option<Self> {
214        let upper = name.to_ascii_uppercase();
215        Self::ALL
216            .into_iter()
217            .find(|(keyword, _)| *keyword == upper)
218            .map(|(_, metric)| metric)
219    }
220
221    pub fn name(self) -> &'static str {
222        Self::ALL
223            .into_iter()
224            .find(|(_, metric)| *metric == self)
225            .map(|(keyword, _)| keyword)
226            .expect("every VectorMetric is listed in ALL")
227    }
228}
229
230/// One scope-bearing payload: the subquery body or the pattern payload
231/// a scope-bearing variant carries — the two halves
232/// [`Expr::bearing`](Expr::bearing) unifies for the payload-bearing
233/// walkers.
234// `Eq` stays off: the payloads it borrows (`Query`, `PathPattern`)
235// implement `PartialEq` only.
236#[derive(Debug, Clone, Copy, PartialEq)]
237pub enum Bearing<'a> {
238    Subquery(&'a Query),
239    Pattern(&'a PathPattern),
240}
241
242impl Expr {
243    /// A static property access `expr.key`, its key token minted
244    /// [`Token::Unresolved`] (planning resolves it, ADR-0541).
245    pub fn property(expr: Expr, key: SmallName) -> Expr {
246        Expr::Property {
247            expr: Box::new(expr),
248            key,
249            key_id: Token::Unresolved,
250        }
251    }
252
253    /// One boolean expression folded from `parts` as a left-associative
254    /// `AND` chain — the one constructor every conjunct-list folder calls
255    /// (the planner's WHERE conjunct folding, the SEARCH window split's
256    /// score half), nesting exactly the way the planner's original fold
257    /// did so plans are unchanged. `None` when `parts` is empty: no
258    /// conjuncts are no expression, never a fabricated `true`.
259    pub fn conjunction(parts: impl IntoIterator<Item = Expr>) -> Option<Expr> {
260        let mut parts = parts.into_iter();
261        let first = parts.next()?;
262        Some(parts.fold(first, |combined, next| Expr::Binary {
263            op: BinaryOp::And,
264            left: Box::new(combined),
265            right: Box::new(next),
266        }))
267    }
268
269    /// Fold a seek predicate into a value. Literals fold directly.
270    /// Parameters resolve through `params`. `RuntimeValue` is already a
271    /// value. `None` means the expression is not a seek constant.
272    pub fn seek_value(
273        &self,
274        params: &std::collections::BTreeMap<String, relate_core::Value>,
275    ) -> Option<relate_core::Value> {
276        use relate_core::Value;
277        match self {
278            Expr::Null => Some(Value::Null),
279            Expr::Bool(value) => Some(Value::Bool(*value)),
280            Expr::Int(value) => Some(Value::Int(*value)),
281            Expr::Float(value) => Some(Value::Float(*value)),
282            Expr::String(value) => Some(Value::String(std::sync::Arc::from(value.as_str()))),
283            Expr::Parameter(name) => params.get(name).cloned(),
284            Expr::RuntimeValue(value) => Some(value.clone()),
285            _ => None,
286        }
287    }
288
289    /// A literal or parameter that a planner may store on a pattern
290    /// property map: the value forms [`seek_value`](Self::seek_value) folds
291    /// without a runtime row. `Parameter` is a seek constant even though its
292    /// value is only known at run time; `RuntimeValue` folds through
293    /// `seek_value` but is too late for the planner.
294    ///
295    /// The set is stated directly instead of probed through `seek_value`,
296    /// so a future parameterless arm there does not silently widen what the
297    /// planner folds.
298    pub fn is_seek_const(&self) -> bool {
299        matches!(
300            self,
301            Expr::Null
302                | Expr::Bool(_)
303                | Expr::Int(_)
304                | Expr::Float(_)
305                | Expr::String(_)
306                | Expr::Parameter(_)
307        )
308    }
309
310    /// The one scope-bearing payload classification: the subquery body
311    /// or the pattern payload a scope-bearing variant carries, so a
312    /// payload-bearing walker's prologue is one exhaustive match on
313    /// [`bearing`](Self::bearing) instead of one accessor probe per half.
314    pub fn bearing(&self) -> Option<Bearing<'_>> {
315        if let Some(path) = self.pattern_path() {
316            Some(Bearing::Pattern(path))
317        } else {
318            self.subquery_body().map(Bearing::Subquery)
319        }
320    }
321
322    /// The pattern payload this expression carries, if it is a
323    /// pattern-carrying variant (a pattern predicate, or the
324    /// expression-form `shortestPath`), else `None` — the pattern half's
325    /// twin of [`subquery_body`](Self::subquery_body), so a fold needing
326    /// the path consults one accessor instead of re-listing the variants
327    /// in every consumer's match.
328    pub fn pattern_path(&self) -> Option<&PathPattern> {
329        match self {
330            Expr::PatternPred { path } | Expr::ShortestPath { path, .. } => Some(path),
331            _ => None,
332        }
333    }
334
335    /// The subquery body this expression opens, if it is an
336    /// expression-subquery variant (`EXISTS`/`COUNT`/`COLLECT`), else
337    /// `None` — the one published answer to "which expressions open a
338    /// subquery body", beside [`seek_value`](Self::seek_value), so a
339    /// future variant extends this accessor instead of being hunted down
340    /// in every consumer's match.
341    pub fn subquery_body(&self) -> Option<&Query> {
342        match self {
343            Expr::ExistsSubquery { query }
344            | Expr::CountSubquery { query }
345            | Expr::CollectSubquery { query, .. } => Some(query),
346            _ => None,
347        }
348    }
349}
350
351/// The binary-operator vocabulary's shared facts, beside the operators they
352/// name: the token spelling every rendering and operator-naming message
353/// reads, the boolean-connective set, and the absorbing-constant fold.
354impl BinaryOp {
355    /// The operator's Cypher token — the one spelling every message naming
356    /// an operator reads (ADR-0511's boolean-operand rejection among them)
357    /// and the one expression rendering spells, so no site re-spells the
358    /// vocabulary.
359    pub fn as_str(self) -> &'static str {
360        match self {
361            BinaryOp::Or => "OR",
362            BinaryOp::Xor => "XOR",
363            BinaryOp::And => "AND",
364            BinaryOp::Eq => "=",
365            BinaryOp::Neq => "<>",
366            BinaryOp::Lt => "<",
367            BinaryOp::Gt => ">",
368            BinaryOp::Lte => "<=",
369            BinaryOp::Gte => ">=",
370            BinaryOp::Add => "+",
371            BinaryOp::Sub => "-",
372            BinaryOp::Mul => "*",
373            BinaryOp::Div => "/",
374            BinaryOp::Mod => "%",
375            BinaryOp::Pow => "^",
376            BinaryOp::Concat => "+",
377            BinaryOp::In => "IN",
378            BinaryOp::StartsWith => "STARTS WITH",
379            BinaryOp::EndsWith => "ENDS WITH",
380            BinaryOp::Contains => "CONTAINS",
381            BinaryOp::Regex => "=~",
382        }
383    }
384
385    /// Whether the operator is a boolean connective (`AND`/`OR`/`XOR`):
386    /// exactly the operators whose operands are predicate positions.
387    pub fn is_boolean(self) -> bool {
388        matches!(self, BinaryOp::And | BinaryOp::Or | BinaryOp::Xor)
389    }
390
391    /// The constant this binary node folds to when an operand is the
392    /// operator's absorbing boolean constant (`x OR true` → `true`,
393    /// `x AND false` → `false`), or `None` when it does not fold: the
394    /// reference engine's rewriter discards the whole node — operands
395    /// included — before variable resolution (`MiscAcceptance` "IN
396    /// predicate with undefined variable is accepted when it can be
397    /// rewritten away"). Exact under Cypher's three-valued logic
398    /// (`null OR true` is `true`, `null AND false` is `false`).
399    pub fn absorbing_constant(self, left: &Expr, right: &Expr) -> Option<bool> {
400        match (self, left, right) {
401            (BinaryOp::Or, Expr::Bool(true), _) | (BinaryOp::Or, _, Expr::Bool(true)) => Some(true),
402            (BinaryOp::And, Expr::Bool(false), _) | (BinaryOp::And, _, Expr::Bool(false)) => {
403                Some(false)
404            }
405            _ => None,
406        }
407    }
408}