relate-ir 1.4.0

Planner IR (lowered Cypher AST)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! The expression model: [`Expr`] and the two small types its variants
//! carry ([`MapProjectionItem`], [`VectorMetric`]), with the methods that
//! answer questions about an expression itself, plus the binary-operator
//! vocabulary's shared facts ([`BinaryOp`]'s token spelling, boolean
//! connectives, and absorbing-constant fold). Split from [`super`] so the
//! statement/clause vocabulary and the expression vocabulary stay one
//! concern per file; [`super`] re-exports every item, so the public path is
//! unchanged (`ast::call` sets the same precedent).

use super::{BinaryOp, ChronoOp, LabelExpr, PathPattern, QuantifierKind, Query, TypeExpr, UnaryOp};
use relate_names::{SmallName, Token};

#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    /// Executor-internal eager value; never produced by either parser.
    RuntimeValue(relate_core::Value),
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    String(String),
    Parameter(String),
    Variable(SmallName),
    Star,
    Property {
        expr: Box<Expr>,
        key: SmallName,
        /// Token of `key`, set when planning resolves it against a store
        /// (ADR-0541); `Unresolved` before.
        key_id: relate_names::Token,
    },
    DynamicProperty {
        expr: Box<Expr>,
        key: Box<Expr>,
    },
    LabelPredicate {
        expr: Box<Expr>,
        label_expr: LabelExpr,
        strict: bool,
    },
    Map(Vec<(String, Expr)>),
    List(Vec<Expr>),
    /// `PATH [n1, r1, n2, ...]`: the path constructor over its element list.
    PathConstruct {
        elements: Vec<Expr>,
    },
    Unary {
        op: UnaryOp,
        expr: Box<Expr>,
    },
    Binary {
        op: BinaryOp,
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Function {
        name: SmallName,
        distinct: bool,
        args: Vec<Expr>,
    },
    CountStar,
    Case {
        /// `(predicate, result)` pairs, evaluated as booleans in order. The
        /// parser lowers a simple-CASE test operand into each arm's equality
        /// comparison, so the searched form is the only one that reaches the
        /// executor.
        when_then: Vec<(Expr, Expr)>,
        else_expr: Option<Box<Expr>>,
    },
    Subscript {
        expr: Box<Expr>,
        index: Box<Expr>,
    },
    Slice {
        expr: Box<Expr>,
        start: Option<Box<Expr>>,
        end: Option<Box<Expr>>,
    },
    ListComp {
        ident: SmallName,
        list: Box<Expr>,
        predicate: Option<Box<Expr>>,
        projection: Box<Expr>,
    },
    /// CIP-272 map comprehension (lowered from the parser's
    /// `MapComprehension`).
    MapComp {
        /// Key binding of a map source (`None` for a list source).
        key_ident: Option<SmallName>,
        value_ident: SmallName,
        source: Box<Expr>,
        predicate: Option<Box<Expr>>,
        key_expr: Box<Expr>,
        value_expr: Box<Expr>,
    },
    Quantifier {
        kind: QuantifierKind,
        ident: SmallName,
        list: Box<Expr>,
        predicate: Box<Expr>,
    },
    Reduce {
        accumulator: SmallName,
        initial: Box<Expr>,
        ident: SmallName,
        list: Box<Expr>,
        expression: Box<Expr>,
    },
    AllReduce {
        accumulator: SmallName,
        initial: Box<Expr>,
        ident: SmallName,
        list: Box<Expr>,
        expression: Box<Expr>,
        predicate: Box<Expr>,
    },
    IsType {
        expr: Box<Expr>,
        type_expr: TypeExpr,
        negated: bool,
    },
    IsNormalized {
        expr: Box<Expr>,
        form: Option<String>,
        negated: bool,
    },
    ChronoCompare {
        left: Box<Expr>,
        op: ChronoOp,
        right: Box<Expr>,
        negated: bool,
    },
    /// Map projection `expr { key: value, .key, var, .* }`. Typed form of
    /// what used to be tunnelled through a `__map_projection` pseudo-call.
    MapProjection {
        expr: Box<Expr>,
        items: Vec<MapProjectionItem>,
    },
    /// CIP-214 distance-metric keyword (e.g. the `EUCLIDEAN` in
    /// `vector_distance(a, b, EUCLIDEAN)`), resolved at lowering from the
    /// bare identifier in the final argument of `vector_distance` /
    /// `vector_norm`. Only meaningful as an argument to those functions.
    DistanceMetric(VectorMetric),
    PatternPred {
        path: PathPattern,
    },
    ShortestPath {
        all: bool,
        path: PathPattern,
    },
    ExistsSubquery {
        query: Query,
    },
    CountSubquery {
        query: Query,
    },
    CollectSubquery {
        query: Query,
        /// The body's own path-variable binding, when the front
        /// synthesized the body from a pattern comprehension (ADR-0685):
        /// a comprehension's path variable shadows any outer name of the
        /// same spelling for the body's whole scope, so the nested seed
        /// must not import it — the one difference from a user-written
        /// `collect { … }`, whose rebinding of an outer name is the
        /// `VariableAlreadyBound` error.
        path_shadow: Option<SmallName>,
    },
}

/// One entry of a map projection (`Expr::MapProjection`).
#[derive(Debug, Clone, PartialEq)]
pub enum MapProjectionItem {
    /// Explicit `key: value` entry.
    KeyValue { key: SmallName, value: Expr },
    /// `.key` property shorthand, read from the projection target.
    Property { key: SmallName },
    /// Bare variable entry: `var` shorthand for `var: var`.
    Variable { name: SmallName },
    /// `.*`: every property of the target.
    AllProperties,
}

/// CIP-214 distance metric for `vector_distance` / `vector_norm`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VectorMetric {
    Euclidean,
    EuclideanSquared,
    Manhattan,
    Cosine,
    Dot,
    Hamming,
}

impl VectorMetric {
    /// Every metric with its keyword — the one vocabulary table
    /// [`from_name`](Self::from_name) parses and [`name`](Self::name)
    /// renders, so a new variant cannot parse without also rendering.
    /// Public beyond the crate so downstream storable-subset tests
    /// iterate the table itself: a new variant is covered by
    /// construction, never by a re-derived literal list.
    pub const ALL: [(&'static str, Self); 6] = [
        ("EUCLIDEAN", Self::Euclidean),
        ("EUCLIDEAN_SQUARED", Self::EuclideanSquared),
        ("MANHATTAN", Self::Manhattan),
        ("COSINE", Self::Cosine),
        ("DOT", Self::Dot),
        ("HAMMING", Self::Hamming),
    ];

    /// Parse the bare metric keyword (case-insensitive). `None` when the
    /// identifier is not a known metric, in which case lowering leaves it as
    /// an ordinary variable reference for the binder to reject.
    pub fn from_name(name: &str) -> Option<Self> {
        let upper = name.to_ascii_uppercase();
        Self::ALL
            .into_iter()
            .find(|(keyword, _)| *keyword == upper)
            .map(|(_, metric)| metric)
    }

    pub fn name(self) -> &'static str {
        Self::ALL
            .into_iter()
            .find(|(_, metric)| *metric == self)
            .map(|(keyword, _)| keyword)
            .expect("every VectorMetric is listed in ALL")
    }
}

/// One scope-bearing payload: the subquery body or the pattern payload
/// a scope-bearing variant carries — the two halves
/// [`Expr::bearing`](Expr::bearing) unifies for the payload-bearing
/// walkers.
// `Eq` stays off: the payloads it borrows (`Query`, `PathPattern`)
// implement `PartialEq` only.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Bearing<'a> {
    Subquery(&'a Query),
    Pattern(&'a PathPattern),
}

impl Expr {
    /// A static property access `expr.key`, its key token minted
    /// [`Token::Unresolved`] (planning resolves it, ADR-0541).
    pub fn property(expr: Expr, key: SmallName) -> Expr {
        Expr::Property {
            expr: Box::new(expr),
            key,
            key_id: Token::Unresolved,
        }
    }

    /// One boolean expression folded from `parts` as a left-associative
    /// `AND` chain — the one constructor every conjunct-list folder calls
    /// (the planner's WHERE conjunct folding, the SEARCH window split's
    /// score half), nesting exactly the way the planner's original fold
    /// did so plans are unchanged. `None` when `parts` is empty: no
    /// conjuncts are no expression, never a fabricated `true`.
    pub fn conjunction(parts: impl IntoIterator<Item = Expr>) -> Option<Expr> {
        let mut parts = parts.into_iter();
        let first = parts.next()?;
        Some(parts.fold(first, |combined, next| Expr::Binary {
            op: BinaryOp::And,
            left: Box::new(combined),
            right: Box::new(next),
        }))
    }

    /// Fold a seek predicate into a value. Literals fold directly.
    /// Parameters resolve through `params`. `RuntimeValue` is already a
    /// value. `None` means the expression is not a seek constant.
    pub fn seek_value(
        &self,
        params: &std::collections::BTreeMap<String, relate_core::Value>,
    ) -> Option<relate_core::Value> {
        use relate_core::Value;
        match self {
            Expr::Null => Some(Value::Null),
            Expr::Bool(value) => Some(Value::Bool(*value)),
            Expr::Int(value) => Some(Value::Int(*value)),
            Expr::Float(value) => Some(Value::Float(*value)),
            Expr::String(value) => Some(Value::String(std::sync::Arc::from(value.as_str()))),
            Expr::Parameter(name) => params.get(name).cloned(),
            Expr::RuntimeValue(value) => Some(value.clone()),
            _ => None,
        }
    }

    /// A literal or parameter that a planner may store on a pattern
    /// property map: the value forms [`seek_value`](Self::seek_value) folds
    /// without a runtime row. `Parameter` is a seek constant even though its
    /// value is only known at run time; `RuntimeValue` folds through
    /// `seek_value` but is too late for the planner.
    ///
    /// The set is stated directly instead of probed through `seek_value`,
    /// so a future parameterless arm there does not silently widen what the
    /// planner folds.
    pub fn is_seek_const(&self) -> bool {
        matches!(
            self,
            Expr::Null
                | Expr::Bool(_)
                | Expr::Int(_)
                | Expr::Float(_)
                | Expr::String(_)
                | Expr::Parameter(_)
        )
    }

    /// The one scope-bearing payload classification: the subquery body
    /// or the pattern payload a scope-bearing variant carries, so a
    /// payload-bearing walker's prologue is one exhaustive match on
    /// [`bearing`](Self::bearing) instead of one accessor probe per half.
    pub fn bearing(&self) -> Option<Bearing<'_>> {
        if let Some(path) = self.pattern_path() {
            Some(Bearing::Pattern(path))
        } else {
            self.subquery_body().map(Bearing::Subquery)
        }
    }

    /// The pattern payload this expression carries, if it is a
    /// pattern-carrying variant (a pattern predicate, or the
    /// expression-form `shortestPath`), else `None` — the pattern half's
    /// twin of [`subquery_body`](Self::subquery_body), so a fold needing
    /// the path consults one accessor instead of re-listing the variants
    /// in every consumer's match.
    pub fn pattern_path(&self) -> Option<&PathPattern> {
        match self {
            Expr::PatternPred { path } | Expr::ShortestPath { path, .. } => Some(path),
            _ => None,
        }
    }

    /// The subquery body this expression opens, if it is an
    /// expression-subquery variant (`EXISTS`/`COUNT`/`COLLECT`), else
    /// `None` — the one published answer to "which expressions open a
    /// subquery body", beside [`seek_value`](Self::seek_value), so a
    /// future variant extends this accessor instead of being hunted down
    /// in every consumer's match.
    pub fn subquery_body(&self) -> Option<&Query> {
        match self {
            Expr::ExistsSubquery { query }
            | Expr::CountSubquery { query }
            | Expr::CollectSubquery { query, .. } => Some(query),
            _ => None,
        }
    }
}

/// The binary-operator vocabulary's shared facts, beside the operators they
/// name: the token spelling every rendering and operator-naming message
/// reads, the boolean-connective set, and the absorbing-constant fold.
impl BinaryOp {
    /// The operator's Cypher token — the one spelling every message naming
    /// an operator reads (ADR-0511's boolean-operand rejection among them)
    /// and the one expression rendering spells, so no site re-spells the
    /// vocabulary.
    pub fn as_str(self) -> &'static str {
        match self {
            BinaryOp::Or => "OR",
            BinaryOp::Xor => "XOR",
            BinaryOp::And => "AND",
            BinaryOp::Eq => "=",
            BinaryOp::Neq => "<>",
            BinaryOp::Lt => "<",
            BinaryOp::Gt => ">",
            BinaryOp::Lte => "<=",
            BinaryOp::Gte => ">=",
            BinaryOp::Add => "+",
            BinaryOp::Sub => "-",
            BinaryOp::Mul => "*",
            BinaryOp::Div => "/",
            BinaryOp::Mod => "%",
            BinaryOp::Pow => "^",
            BinaryOp::Concat => "+",
            BinaryOp::In => "IN",
            BinaryOp::StartsWith => "STARTS WITH",
            BinaryOp::EndsWith => "ENDS WITH",
            BinaryOp::Contains => "CONTAINS",
            BinaryOp::Regex => "=~",
        }
    }

    /// Whether the operator is a boolean connective (`AND`/`OR`/`XOR`):
    /// exactly the operators whose operands are predicate positions.
    pub fn is_boolean(self) -> bool {
        matches!(self, BinaryOp::And | BinaryOp::Or | BinaryOp::Xor)
    }

    /// The constant this binary node folds to when an operand is the
    /// operator's absorbing boolean constant (`x OR true` → `true`,
    /// `x AND false` → `false`), or `None` when it does not fold: the
    /// reference engine's rewriter discards the whole node — operands
    /// included — before variable resolution (`MiscAcceptance` "IN
    /// predicate with undefined variable is accepted when it can be
    /// rewritten away"). Exact under Cypher's three-valued logic
    /// (`null OR true` is `true`, `null AND false` is `false`).
    pub fn absorbing_constant(self, left: &Expr, right: &Expr) -> Option<bool> {
        match (self, left, right) {
            (BinaryOp::Or, Expr::Bool(true), _) | (BinaryOp::Or, _, Expr::Bool(true)) => Some(true),
            (BinaryOp::And, Expr::Bool(false), _) | (BinaryOp::And, _, Expr::Bool(false)) => {
                Some(false)
            }
            _ => None,
        }
    }
}