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        // Rust's `f64` grammar is wider than the dialect's number literal
58        // (`inf`, `nan`, `infinity`): only a token that opens like a numeric
59        // literal is a number; a bare word falls through to `NonNumeric`.
60        let opens_numeric = token
61            .trim_start_matches(['+', '-'])
62            .starts_with(|c: char| c.is_ascii_digit() || c == '.');
63        if opens_numeric {
64            if let Ok(value) = token.replace('_', "").parse::<f64>() {
65                return VectorCoordToken::Number(value);
66            }
67        }
68        let quoted = token.starts_with('\'') || token.starts_with('"');
69        let word = token
70            .chars()
71            .next()
72            .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
73            && token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
74        if quoted || word {
75            VectorCoordToken::NonNumeric
76        } else {
77            VectorCoordToken::Malformed
78        }
79    }
80}
81
82/// The CIP-216 vector dimension domain — the one bound the parser's type
83/// annotation and the front end's `vector()` construction check consult.
84pub const VECTOR_DIMENSION_RANGE: std::ops::RangeInclusive<i64> = 1..=4096;
85
86/// The authored rendering of [`VECTOR_DIMENSION_RANGE`], derived from its
87/// endpoints so moving the bound moves the message with it.
88pub fn dimension_range_text() -> String {
89    format!(
90        "{} to {}",
91        VECTOR_DIMENSION_RANGE.start(),
92        VECTOR_DIMENSION_RANGE.end()
93    )
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn numeric_literals_classify_as_numbers() {
102        for token in ["1", "-2.5", " 1_000 ", ".5", "+3", "1e3"] {
103            assert!(
104                matches!(
105                    VectorCoordToken::classify(token),
106                    VectorCoordToken::Number(_)
107                ),
108                "{token}"
109            );
110        }
111    }
112
113    #[test]
114    fn rust_only_float_spellings_are_not_numbers() {
115        for token in ["inf", "NaN", "infinity"] {
116            assert_eq!(
117                VectorCoordToken::classify(token),
118                VectorCoordToken::NonNumeric,
119                "{token}"
120            );
121        }
122    }
123
124    #[test]
125    fn a_signed_word_is_malformed() {
126        assert_eq!(
127            VectorCoordToken::classify("-inf"),
128            VectorCoordToken::Malformed
129        );
130    }
131
132    #[test]
133    fn parse_coordinates_rejects_non_numbers() {
134        assert_eq!(
135            VectorCoordKind::parse_coordinates("[1, 2.5]"),
136            Some(vec![1.0, 2.5])
137        );
138        assert_eq!(VectorCoordKind::parse_coordinates("[1, inf]"), None);
139        assert_eq!(VectorCoordKind::parse_coordinates("1, 2"), None);
140    }
141}