Skip to main content

relate_model/vector/
coordinates.rs

1//! The `vector()` coordinate-string text layer: the bracketed coordinate
2//! list's tokenizer and classifier, its numeric parser, and the CIP-216
3//! dimension domain. Split from `value.rs` so the value model keeps the
4//! `VectorCoordKind` type and its narrowing, and this text handling lives
5//! beside its only consumers.
6
7use crate::value::VectorCoordKind;
8
9impl VectorCoordKind {
10    /// The bracketed coordinate-list spelling the `vector()` string
11    /// constructor accepts (`"[1, 2, 3]"`), token by token: `None` when the
12    /// text lacks its brackets. The one tokenizer the executor's construction
13    /// and the front end's compile-time check share; each layers its own
14    /// policy on the classification (the executor rejects every non-number,
15    /// the front end only [`VectorCoordToken::Malformed`], leaving
16    /// [`VectorCoordToken::NonNumeric`] to the runtime type error).
17    pub fn coordinate_tokens(text: &str) -> Option<Vec<VectorCoordToken>> {
18        let body = text.trim().strip_prefix('[')?.strip_suffix(']')?;
19        if body.trim().is_empty() {
20            return Some(Vec::new());
21        }
22        Some(body.split(',').map(VectorCoordToken::classify).collect())
23    }
24
25    /// Parse the bracketed coordinate-list spelling (`"[1, 2, 3]"`) to its
26    /// numbers: `None` when the text lacks its brackets or any token is not
27    /// a number.
28    pub fn parse_coordinates(text: &str) -> Option<Vec<f64>> {
29        Self::coordinate_tokens(text)?
30            .into_iter()
31            .map(|token| match token {
32                VectorCoordToken::Number(value) => Some(value),
33                VectorCoordToken::NonNumeric | VectorCoordToken::Malformed => None,
34            })
35            .collect()
36    }
37}
38
39/// One token of a bracketed `vector()` coordinate string, as the shared
40/// tokenizer reads it.
41#[derive(Debug, Clone, Copy, PartialEq)]
42pub enum VectorCoordToken {
43    /// A number (`1`, `-2.5`, `1_000`).
44    Number(f64),
45    /// A valid Cypher value spelling that is not a number — an identifier
46    /// word, a quoted string, a boolean/null keyword. A runtime type
47    /// mismatch, not an input error.
48    NonNumeric,
49    /// Neither a number nor a valid value spelling (`6 005`) — a
50    /// compile-time input error.
51    Malformed,
52}
53
54impl VectorCoordToken {
55    fn classify(token: &str) -> Self {
56        let token = token.trim();
57        if let Ok(value) = token.replace('_', "").parse::<f64>() {
58            return VectorCoordToken::Number(value);
59        }
60        let quoted = token.starts_with('\'') || token.starts_with('"');
61        let word = token
62            .chars()
63            .next()
64            .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
65            && token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
66        if quoted || word {
67            VectorCoordToken::NonNumeric
68        } else {
69            VectorCoordToken::Malformed
70        }
71    }
72}
73
74/// The CIP-216 vector dimension domain — the one bound the parser's type
75/// annotation and the front end's `vector()` construction check consult.
76pub const VECTOR_DIMENSION_RANGE: std::ops::RangeInclusive<i64> = 1..=4096;
77
78/// The authored rendering of [`VECTOR_DIMENSION_RANGE`], derived from its
79/// endpoints so moving the bound moves the message with it.
80pub fn dimension_range_text() -> String {
81    format!(
82        "{} to {}",
83        VECTOR_DIMENSION_RANGE.start(),
84        VECTOR_DIMENSION_RANGE.end()
85    )
86}