Skip to main content

relate_ir/
ast.rs

1//! OpenCypher AST (ADR-0007): the statement and clause model, with the pure
2//! `Expr`-shape recognizers beside it. The expression model itself
3//! ([`Expr`] and its two carried types) lives in [`expr`], the pattern
4//! model ([`PathPattern`] and its element, label and type vocabularies) in
5//! [`pattern`], the shared body-descent classification fold
6//! ([`ConcludingVerdict`] and its two entries) in [`body_descent`], and
7//! all three are re-exported here, so the public path stays `ast::*`.
8
9use relate_names::SmallName;
10
11use crate::search::SearchSpec;
12
13mod body_descent;
14#[cfg(any(test, feature = "test-hooks"))]
15#[doc(hidden)]
16pub mod body_descent_fixtures;
17#[cfg(test)]
18mod body_descent_tests;
19mod call;
20mod expr;
21mod pattern;
22pub use body_descent::*;
23pub use call::*;
24pub use expr::*;
25pub use pattern::*;
26
27#[derive(Debug, Clone, PartialEq)]
28pub struct Query {
29    pub parts: Vec<SingleQuery>,
30    /// `union_all[i]` applies between `parts[i]` and `parts[i+1]`.
31    pub union_all: Vec<bool>,
32    /// CIP-213 sequential statement composition.
33    pub next: Option<Box<Query>>,
34}
35
36impl Query {
37    /// The end of this query's `NEXT` chain — its true terminal stage
38    /// (CIP-213), not its own first stage. UNION arms are `parts` *inside*
39    /// one `Query`, so the chain walk needs no union guard. The one
40    /// IR-level spelling of the cursor the planner's projection checks and
41    /// the executor's stage handling mirror.
42    pub fn final_stage(&self) -> &Query {
43        let mut tail = self;
44        while let Some(next) = tail.next.as_deref() {
45            tail = next;
46        }
47        tail
48    }
49
50    /// Whether this query is one flat part with no `NEXT` stage — no
51    /// UNION arms, no stage chain. The one IR spelling of the fact, read
52    /// by the subquery fast paths that need a single clause list (the
53    /// import-invariant shared execution, the `IN TRANSACTIONS` batch
54    /// pass, ADR-0669), so none re-spells the two conjuncts.
55    pub fn is_single_flat_part(&self) -> bool {
56        self.next.is_none() && self.parts.len() == 1
57    }
58}
59
60#[derive(Debug, Clone, PartialEq)]
61pub struct SingleQuery {
62    pub clauses: Vec<Clause>,
63}
64
65impl SingleQuery {
66    /// The clause a CALL subquery body opens with, when it is an
67    /// *importing WITH*: the first non-`USE` clause, and only if it is an
68    /// explicit `WITH` (`LET`/`FILTER` desugar to `With` but are ordinary
69    /// projections, never importing WITHs). One derivation for both the
70    /// planner's 42I28 rule and the notification layer's import-set
71    /// analysis; the typed payload saves every caller re-discriminating the
72    /// clause variant.
73    pub fn leading_importing_with(&self) -> Option<LeadingWith<'_>> {
74        let clause = self
75            .clauses
76            .iter()
77            .find(|clause| !matches!(clause, Clause::Use { .. }))?;
78        let Clause::With {
79            distinct,
80            items,
81            order,
82            skip,
83            limit,
84            where_clause,
85            origin: WithOrigin::Explicit,
86            ..
87        } = clause
88        else {
89            return None;
90        };
91        Some(LeadingWith {
92            distinct: *distinct,
93            items,
94            order,
95            skip: skip.as_ref(),
96            limit: limit.as_ref(),
97            where_clause: where_clause.as_ref(),
98        })
99    }
100
101    /// The names this part's importing WITH pulls in from `outer` — the
102    /// plain-`WITH` half of [`LeadingWith::imports`], `BTreeSet::new` when
103    /// the part has none. One import policy ([`LeadingWith::imports`]), one
104    /// spelling of "this part has an importing WITH at all".
105    pub fn leading_imports(
106        &self,
107        outer: &std::collections::BTreeSet<String>,
108    ) -> std::collections::BTreeSet<String> {
109        self.leading_importing_with()
110            .map_or_else(Default::default, |with| with.imports(outer))
111    }
112}
113
114impl LeadingWith<'_> {
115    /// The names this importing `WITH` pulls in from `outer` — the one home
116    /// for the import policy: a bare item imports its variable
117    /// ([`Projection::imported_name`]), a `*` imports the whole outer
118    /// scope, and anything else (the aliased forms 42I28 rejects) imports
119    /// nothing. A consumer already holding the payload ([`SingleQuery::leading_importing_with`])
120    /// reads the names off it instead of classifying the clause twice.
121    pub fn imports(
122        &self,
123        outer: &std::collections::BTreeSet<String>,
124    ) -> std::collections::BTreeSet<String> {
125        use std::collections::BTreeSet;
126        let mut imports = BTreeSet::new();
127        for item in self.items {
128            if matches!(item.expr, Expr::Star) {
129                imports.extend(outer.iter().cloned());
130            } else if let Some(name) = item.imported_name() {
131                // Map-bridge: the import sets stay String-keyed because
132                // their consumer, the notification layer's import-set
133                // analysis (`statement_notifications/shape.rs`), is a
134                // String scope-domain sink; the typed sink switch is
135                // tracked as LABS-936.
136                imports.insert(name.to_string());
137            }
138        }
139        imports
140    }
141}
142
143/// The typed payload of [`SingleQuery::leading_importing_with`]: the
144/// importing WITH's fields, borrowed from the clause.
145pub struct LeadingWith<'a> {
146    pub distinct: bool,
147    pub items: &'a [Projection],
148    pub order: &'a [OrderItem],
149    pub skip: Option<&'a Expr>,
150    pub limit: Option<&'a Expr>,
151    pub where_clause: Option<&'a Expr>,
152}
153
154/// A `CALL … YIELD` tail: no `YIELD` at all, `YIELD *`, or an explicit
155/// list of (procedure output name, optional alias) pairs. The typed shape
156/// replaces the old `"*"`-string sentinel, so a real column named `*`
157/// cannot be confused with the wildcard.
158#[derive(Debug, Clone, PartialEq)]
159pub enum YieldItems {
160    /// No `YIELD` clause: the procedure's default yields apply.
161    Default,
162    /// `YIELD *`: every output the procedure declares.
163    Star,
164    /// An explicit `YIELD a [AS x], b ...` list, in source order.
165    Named(Vec<(SmallName, Option<SmallName>)>),
166}
167
168impl YieldItems {
169    /// The explicit items, or an empty slice for `Default`/`Star`.
170    pub fn items(&self) -> &[(SmallName, Option<SmallName>)] {
171        match self {
172            YieldItems::Named(items) => items,
173            YieldItems::Default | YieldItems::Star => &[],
174        }
175    }
176
177    /// Raw output names of an explicit list, in order (empty otherwise).
178    pub fn names(&self) -> impl Iterator<Item = &SmallName> {
179        self.items().iter().map(|(name, _)| name)
180    }
181
182    /// Each explicit item's raw name and effective (alias-else-name) name.
183    pub fn effective_pairs(&self) -> impl Iterator<Item = (&SmallName, &SmallName)> {
184        self.items()
185            .iter()
186            .map(|(name, alias)| (name, alias.as_ref().unwrap_or(name)))
187    }
188
189    /// Effective (post-alias) output names of an explicit list.
190    pub fn effective_names(&self) -> impl Iterator<Item = &SmallName> {
191        self.effective_pairs().map(|(_, effective)| effective)
192    }
193
194    /// Whether any `YIELD` tail was written (`Star` or `Named`).
195    pub fn has_yield(&self) -> bool {
196        !matches!(self, YieldItems::Default)
197    }
198
199    /// The yield tail resolved against a procedure's `default` output
200    /// columns: `YIELD *` takes every default (the same as no `YIELD`),
201    /// an explicit list is itself. The one classification for callers that
202    /// need the resolved pairs — never a boolean collapsed to `items()`
203    /// (Star's items are empty by definition).
204    pub fn resolved_pairs(&self, defaults: &[&str]) -> Vec<(String, Option<String>)> {
205        // Map-bridge: the executor's procedure-call column handling stays
206        // String-keyed (catalog-facing output columns), so both arms render
207        // text here — the one feed the stage-2 scope-map change (ADR-0509)
208        // does not touch.
209        match self {
210            YieldItems::Named(items) => items
211                .iter()
212                .map(|(name, alias)| {
213                    (
214                        name.to_string(),
215                        // allocation-free read of the optional alias
216                        alias.as_ref().map(SmallName::to_string),
217                    )
218                })
219                .collect(),
220            YieldItems::Star | YieldItems::Default => defaults
221                .iter()
222                .map(|column| (column.to_string(), None))
223                .collect(),
224        }
225    }
226}
227
228#[derive(Debug, Clone, PartialEq)]
229pub enum Clause {
230    /// Relate's rich catalog/admin AST, retained losslessly by the
231    /// Relate front-end and executed against Relate metadata.
232    Catalog(Box<relate_parser::Clause>),
233    Match {
234        optional: bool,
235        match_mode: MatchMode,
236        patterns: Vec<PathPattern>,
237        where_clause: Option<Expr>,
238        /// `USING INDEX [SEEK]` hints, carried for the plan-time
239        /// notification that reports a hint no catalog index can serve
240        /// (`01N31`, ADR-0363); the planner itself steers nothing by them.
241        using_index: Vec<relate_parser::IndexHint>,
242        /// `USING JOIN ON` hints, carried for the same purpose: the
243        /// planner never fulfils one, so the `01N30` notification reports
244        /// each.
245        using_join: Vec<relate_parser::JoinHint>,
246        /// CIP-224/CIP-240 vector index search attached to this MATCH.
247        search: Option<Box<SearchClause>>,
248    },
249    Create {
250        patterns: Vec<PathPattern>,
251    },
252    Merge {
253        pattern: PathPattern,
254        on_create: Vec<SetItem>,
255        on_match: Vec<SetItem>,
256    },
257    Call {
258        name: SmallName,
259        args: CallArgs,
260        yield_items: YieldItems,
261        optional: bool,
262        where_clause: Option<Expr>,
263    },
264    Delete {
265        detach: bool,
266        expressions: Vec<Expr>,
267    },
268    Set {
269        items: Vec<SetItem>,
270    },
271    Remove {
272        items: Vec<RemoveItem>,
273    },
274    With {
275        distinct: bool,
276        /// CIP-236: explicit grouping keys (Some(vec![]) = `GROUP BY ()`
277        /// empty set; None = infer from the non-aggregating items).
278        group_by: Option<Vec<Expr>>,
279        items: Vec<Projection>,
280        order: Vec<OrderItem>,
281        skip: Option<Expr>,
282        limit: Option<Expr>,
283        where_clause: Option<Expr>,
284        origin: WithOrigin,
285    },
286    Unwind {
287        expression: Expr,
288        alias: SmallName,
289    },
290    Return {
291        distinct: bool,
292        /// CIP-236 explicit grouping keys (same encoding as `With`).
293        group_by: Option<Vec<Expr>>,
294        items: Vec<Projection>,
295        order: Vec<OrderItem>,
296        skip: Option<Expr>,
297        limit: Option<Expr>,
298    },
299    /// Named `(label, property)` catalog entry (ADR-0040).
300    CreateIndex {
301        name: Option<String>,
302        if_not_exists: bool,
303        label: SmallName,
304        property: SmallName,
305    },
306    DropIndex {
307        if_exists: bool,
308        target: DropIndexTarget,
309    },
310    ShowIndexes,
311    /// CIP-140: terminal empty projection (0 columns).
312    Finish,
313    /// `LOAD CSV [WITH HEADERS] FROM … AS …`.
314    LoadCsv {
315        with_headers: bool,
316        url: Expr,
317        variable: SmallName,
318        field_terminator: Option<String>,
319    },
320    /// `CALL { … }` / `OPTIONAL CALL { … }` (CIP-141 / CIP-32).
321    CallSubquery {
322        query: Box<Query>,
323        optional: bool,
324        scope: CallScope,
325        in_transactions: Option<InTransactions>,
326    },
327    /// CIP-135 top-level WHEN/THEN/ELSE.
328    Conditional {
329        branches: Vec<(Expr, Query)>,
330        else_query: Option<Box<Query>>,
331    },
332    /// Updating FOREACH loop.
333    Foreach {
334        variable: SmallName,
335        list: Expr,
336        clauses: Vec<Clause>,
337    },
338    /// Single-graph runtime: validates scope, then acts as a no-op.
339    Use {
340        graph: Expr,
341    },
342}
343
344/// Native Relate representation of a SEARCH subclause (CIP-224, the
345/// `<source specification clause>` extension).
346#[derive(Debug, Clone, PartialEq)]
347pub struct SearchClause {
348    pub binding_var: SmallName,
349    /// `<source specification clause>`: one index search, or a
350    /// `COMBINE` of two or more weighted sources fused with WRRF.
351    pub spec: SearchSpec,
352    pub score_var: Option<SmallName>,
353    /// The outer WHERE's score-referencing conjuncts, split from the
354    /// MATCH's `where_clause` at lowering (ADR-0678's window rule): the
355    /// entity-side conjuncts stay in the MATCH's `where_clause` — they
356    /// restrict the candidate set the SKIP/LIMIT window pages over —
357    /// while these post-filter the kept rows, because the score is a
358    /// product of the ranking itself and cannot join the index-side
359    /// filter. `None` whenever the clause carries no score variable, or
360    /// a WHERE that never reads it.
361    pub post_where: Option<Expr>,
362}
363
364/// `DROP INDEX name` or `DROP INDEX ON :Label(prop)` (ADR-0040).
365#[derive(Debug, Clone, PartialEq)]
366pub enum DropIndexTarget {
367    Name(String),
368    Schema {
369        label: SmallName,
370        property: SmallName,
371    },
372}
373
374impl Clause {
375    /// The body of a `CALL { … } IN TRANSACTIONS` clause, `None` on every
376    /// other clause — the one reading of the batched form's body, so the
377    /// planner's in-transactions classifiers (`clause_is_in_transactions`)
378    /// and the plan tree's body-children rule both derive it here rather
379    /// than re-matching the variant.
380    pub fn in_transactions_body(&self) -> Option<&Query> {
381        match self {
382            Clause::CallSubquery {
383                query,
384                in_transactions: Some(_),
385                ..
386            } => Some(query),
387            _ => None,
388        }
389    }
390}
391
392#[derive(Debug, Clone, PartialEq)]
393pub struct Projection {
394    pub expr: Expr,
395    pub alias: Option<SmallName>,
396    /// Verbatim source text of the unaliased projection expression, as
397    /// captured by the parser. Used by [`Projection::output_name`] as the
398    /// column name for expression shapes without a dedicated label
399    /// (`count{()}`, list/map literals, `CASE`, etc.). Synthetic
400    /// projections built after parsing leave this `None`.
401    pub source_text: Option<String>,
402}
403
404#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
405pub enum WithOrigin {
406    #[default]
407    Explicit,
408    Let,
409    Filter,
410    /// The horizon a standalone `<order by and page statement>` lowers to:
411    /// a `WITH *` carrying the clause's `ORDER BY`/`SKIP`/`LIMIT`.
412    ///
413    /// Distinct from [`WithOrigin::Explicit`] because the two are not the
414    /// same clause to a reader of the plan — a body opening with a page
415    /// statement imports nothing *by name*, while a user-written `WITH *`
416    /// does pull the enclosing scope in. Live keeps them apart
417    /// (`CALL { ORDER BY 1 RETURN 1 AS x }` is accepted, with the
418    /// scopeless-subquery deprecation; `CALL { WITH * ORDER BY 1 RETURN 1
419    /// AS x }` is the importing-`WITH` rejection), and this origin is what
420    /// lets the rules see that difference after lowering.
421    Page,
422}
423
424#[derive(Debug, Clone, PartialEq)]
425pub struct OrderItem {
426    pub expr: Expr,
427    pub ascending: bool,
428}
429
430#[derive(Debug, Clone, PartialEq)]
431pub enum SetItem {
432    /// `SET n.k = v` / `SET n[expr] = v` -- one property assignment; the
433    /// target is always a property access (`Expr::Property` /
434    /// `Expr::DynamicProperty`).
435    Property { target: Expr, value: Expr },
436    /// `SET n = <map>` -- full property replacement; the target is always
437    /// a bare variable. The front mints this where the parser already
438    /// keeps the fact (`SetItem.property` is `None`), so no consumer
439    /// re-derives the split by sniffing the target expression's shape.
440    ReplaceAll { target: Expr, value: Expr },
441    /// `SET n += <map>` -- merge the map into the target's existing
442    /// properties; the target is always a bare variable (the parser only
443    /// sets `merge` on the bare-variable form).
444    MergeMap { target: Expr, value: Expr },
445    Labels {
446        target: Expr,
447        labels: Vec<LabelExpr>,
448    },
449    LabelsFunction {
450        target: Expr,
451        value: Expr,
452        op: LabelsFunctionOp,
453    },
454}
455
456#[derive(Debug, Clone, Copy, PartialEq, Eq)]
457pub enum LabelsFunctionOp {
458    Overwrite,
459    Extend,
460    Remove,
461}
462
463#[derive(Debug, Clone, PartialEq)]
464pub enum RemoveItem {
465    Property {
466        target: Expr,
467    },
468    Labels {
469        target: Expr,
470        labels: Vec<LabelExpr>,
471    },
472}
473
474/// The `<var>.<key>` property access shape: the variable's and the
475/// property key's borrowed names, or `None` for any other expression.
476/// The seek/fold/vector operand recognizers derive from here.
477pub fn var_prop(expr: &Expr) -> Option<(&SmallName, &SmallName)> {
478    let Expr::Property { expr, key, .. } = expr else {
479        return None;
480    };
481    let Expr::Variable(v) = expr.as_ref() else {
482        return None;
483    };
484    Some((v, key))
485}
486
487/// [`var_prop`] with the key as the shared [`relate_names::NamedToken`]:
488/// the written name beside its plan-resolved token, for the executor reads
489/// that skip the by-name interner lookup.
490pub fn var_prop_named(expr: &Expr) -> Option<(&SmallName, relate_names::NamedToken)> {
491    let Expr::Property { key_id, .. } = expr else {
492        return None;
493    };
494    var_prop(expr).map(|(var, key)| (var, (key.clone(), *key_id)))
495}
496
497/// The owned spelling of the `<var>.<key>` pair (filters and plan
498/// items own their strings). A cross-crate contract, not a local
499/// convenience: the planner passes it as the recognizer fn to
500/// `orient_side` and the executor's `unwind` builds owned plan items
501/// from it, so the public owned spelling stays named rather than
502/// mapped inline at each call site.
503pub fn var_prop_owned(expr: &Expr) -> Option<(String, String)> {
504    // Map-bridge: plan items and filters own their strings (the planner's
505    // plan structures stay String-keyed until their own SmallName stage);
506    // the text render happens once, here, not per lookup.
507    var_prop(expr).map(|(var, key)| (var.to_string(), key.to_string()))
508}
509
510/// The four Cypher 25 chronological comparison operators, the one
511/// vocabulary shared by the lowering and the executor's evaluation.
512#[derive(Debug, Clone, Copy, PartialEq, Eq)]
513pub enum ChronoOp {
514    Before,
515    After,
516    SameInstant,
517    SameRepresentation,
518}
519
520#[derive(Debug, Clone, Copy, PartialEq, Eq)]
521pub enum UnaryOp {
522    Not,
523    Plus,
524    Minus,
525    IsNull,
526    IsNotNull,
527}
528
529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530pub enum BinaryOp {
531    Or,
532    Xor,
533    And,
534    Eq,
535    Neq,
536    Lt,
537    Gt,
538    Lte,
539    Gte,
540    Add,
541    Sub,
542    Mul,
543    Div,
544    Mod,
545    Pow,
546    Concat,
547    In,
548    StartsWith,
549    EndsWith,
550    Contains,
551    Regex,
552}
553
554/// The comparison-operator vocabulary every predicate consumer shares —
555/// aggregate folds, the batch scan-filter chain, the contracted kernel
556/// programs, the scan-predicate specialization, and the flat node-predicate
557/// bytecode evaluator — one table, every consumer, never a second list.
558pub fn is_pred_op(op: BinaryOp) -> bool {
559    matches!(
560        op,
561        BinaryOp::Eq
562            | BinaryOp::Neq
563            | BinaryOp::Lt
564            | BinaryOp::Gt
565            | BinaryOp::Lte
566            | BinaryOp::Gte
567            | BinaryOp::In
568            | BinaryOp::StartsWith
569            | BinaryOp::EndsWith
570            | BinaryOp::Contains
571            | BinaryOp::Regex
572    )
573}
574
575impl Projection {
576    /// Column name of this projection item.
577    ///
578    /// Resolution order (matches Neo4j):
579    /// 1. explicit `AS alias`
580    /// 2. [`canonical_name`] — `*`, a bare variable (`RETURN n` → `n`), or
581    ///    a map projection on a variable (`RETURN n {.name}` → `n`; the map
582    ///    is a view of that variable, and a CALL subquery exports it under
583    ///    the variable's name), the shapes Neo4j names regardless of source
584    ///    formatting
585    /// 3. the verbatim source text captured by the parser — a property
586    ///    access (`RETURN n.name` → `n.name`) and every other expression
587    ///    shape (`RETURN 1+2` → `1+2`, `RETURN count{()}` → `count{()}`)
588    ///    without a parser-synthesized name
589    /// 4. `column_<idx>` for synthetic post-parse projections that have
590    ///    no `source_text`
591    pub fn output_name(&self, idx: usize) -> String {
592        if let Some(a) = &self.alias {
593            // Rendering (a user-visible column name), not a lookup: the
594            // text arms resolve through Display (ADR-0509 §2).
595            return a.to_string();
596        }
597        if let Some(name) = canonical_name(&self.expr) {
598            return name;
599        }
600        if let Some(src) = &self.source_text {
601            return src.clone();
602        }
603        format!("column_{idx}")
604    }
605
606    /// The name this item imports from the enclosing scope, when it is a
607    /// legal *importing-WITH* item: a bare, unaliased variable reference.
608    /// `None` for an aliased item — a shape 42I28 rejects, never an import
609    /// under a silently different name. The one home for that policy: the
610    /// planner's 42I28 classifier and the notification layer's import-set
611    /// analysis both read it.
612    pub fn imported_name(&self) -> Option<&SmallName> {
613        match (&self.expr, &self.alias) {
614            (Expr::Variable(name), None) => Some(name),
615            _ => None,
616        }
617    }
618}
619
620/// The canonical names Neo4j spells identically regardless of source
621/// formatting: a bare variable (`n`, and a parenthesized one — `(n)`
622/// names its column `n`), `*`, and a map projection on a variable
623/// (`n {.name, .age}` → `n`, parenthesized included). `None` for any
624/// other expression shape — a property access included: Neo4j (2026.10,
625/// probed live) names `n.name`, `n . name`, `n.` + backtick + `name` +
626/// backtick and `(n.name)` each by its verbatim source text, so every
627/// property spelling beyond the plain one is its own column name, and
628/// the verbatim `source_text` fallback owns it.
629///
630/// Doubles as the alias-gate vocabulary: an unaliased projection item
631/// whose expression is named here carries its own column name, so the
632/// planner's `WITH` and conditional-`RETURN` alias rules test it instead
633/// of re-spelling the shape list — an unaliased `WITH n {.*}` passes
634/// exactly like `WITH n` (Neo4j 2026.10 live-confirmed, REL8-1866). The
635/// parser-AST twin of this vocabulary is relate-front's
636/// `implicit_name` (the front's alias gates read that one); the drift
637/// test beside it in relate-front lowers the canonical shapes and pins
638/// the two spellings' agreement, so a shape admitted in one but not
639/// the other fails a test instead of silently splitting WITH acceptance
640/// from planner naming.
641pub fn canonical_name(expr: &Expr) -> Option<String> {
642    // Rendering (a user-visible column name): the text arms resolve
643    // through Display (ADR-0509 §2), once per name, not per lookup.
644    match expr {
645        Expr::Star => Some("*".into()),
646        Expr::Variable(v) => Some(v.to_string()),
647        Expr::MapProjection { expr, .. } => match expr.as_ref() {
648            Expr::Variable(v) => Some(v.to_string()),
649            _ => None,
650        },
651        _ => None,
652    }
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658
659    #[test]
660    fn vector_metric_names_round_trip_through_from_name() {
661        // `ALL` is the one table `from_name` parses and `name` renders, so
662        // this fails when a variant is added to one side only.
663        for (keyword, metric) in VectorMetric::ALL {
664            assert_eq!(metric.name(), keyword);
665            assert_eq!(VectorMetric::from_name(keyword), Some(metric));
666        }
667        let names: std::collections::BTreeSet<_> = VectorMetric::ALL
668            .iter()
669            .map(|(keyword, _)| *keyword)
670            .collect();
671        assert_eq!(names.len(), VectorMetric::ALL.len(), "names are unique");
672        // Parsing is case-insensitive; an unknown identifier is not a metric.
673        assert_eq!(
674            VectorMetric::from_name("euclidean_squared"),
675            Some(VectorMetric::EuclideanSquared)
676        );
677        assert_eq!(VectorMetric::from_name("not-a-metric"), None);
678    }
679
680    fn path(variable: Option<&str>, subpath_variable: Option<&str>) -> PathPattern {
681        PathPattern {
682            variable: variable.map(SmallName::from_name),
683            subpath_variable: subpath_variable.map(SmallName::from_name),
684            elements: vec![],
685            nodes: vec![],
686            rels: vec![],
687            where_clause: None,
688            mode: None,
689            selector: None,
690            is_shortest_path_function: false,
691        }
692    }
693
694    #[test]
695    fn path_names_lists_outer_then_subpath_variable() {
696        let both = path(Some("p"), Some("q"));
697        assert_eq!(
698            both.path_names()
699                .map(SmallName::to_string)
700                .collect::<Vec<_>>(),
701            ["p", "q"]
702        );
703        assert!(both.has_path_name());
704
705        let subpath_only = path(None, Some("q"));
706        assert_eq!(
707            subpath_only
708                .path_names()
709                .map(SmallName::to_string)
710                .collect::<Vec<_>>(),
711            ["q"]
712        );
713        assert!(subpath_only.has_path_name());
714
715        let outer_only = path(Some("p"), None);
716        assert_eq!(
717            outer_only
718                .path_names()
719                .map(SmallName::to_string)
720                .collect::<Vec<_>>(),
721            ["p"]
722        );
723        assert!(outer_only.has_path_name());
724
725        let unnamed = path(None, None);
726        assert!(unnamed.path_names().next().is_none());
727        assert!(!unnamed.has_path_name());
728    }
729}