Skip to main content

relate_core/
dynamic.rs

1//! The one rule for dynamic property-key and label/type operands
2//! (CIP-131 bracket targets, CIP-156/CIP-162 dynamic labels/types): the
3//! value-type check and the token-name check (Neo4j GQLSTATUS 22N27 /
4//! 22NB1 / 42I11).
5//!
6//! Two layers call this rule over the same values: the front's compile-time
7//! fold (`relate-front/src/validate/dynamic.rs`) validates constant
8//! operands before execution — so a bad constant fails even when the driving
9//! `MATCH` matches zero rows — and the executor's runtime resolution
10//! (`relate-executor/src/eval/labels.rs`) validates per-row operands.
11//! Neither layer restates a message or a type rule.
12
13use std::fmt;
14
15use crate::error_kinds::ErrorKind;
16
17use crate::typename::bare_type_name;
18use crate::{Error, Value};
19
20/// Which token namespace a dynamic name belongs to (the `tokenType` slot of
21/// Neo4j's 42I11 "invalid name" status description). Owns the whole
22/// namespace vocabulary — the 42I11 token phrase, the 22N27/22NB1 operand
23/// position and accepted type — so neither layer spells any of them.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum DynamicNameToken {
26    PropertyKey,
27    Label,
28}
29
30impl DynamicNameToken {
31    /// The authored token-type phrase for the 42I11 detail text.
32    pub const fn as_str(self) -> &'static str {
33        match self {
34            Self::PropertyKey => "property key",
35            Self::Label => "label",
36        }
37    }
38
39    /// The authored operand position for the 22N27/22NB1 detail text.
40    pub const fn position(self) -> &'static str {
41        match self {
42            Self::PropertyKey => "node or relationship property key",
43            Self::Label => "dynamic label",
44        }
45    }
46
47    /// The authored accepted type for the 22N27/22NB1 detail text.
48    pub const fn expected(self) -> &'static str {
49        match self {
50            Self::PropertyKey => "STRING",
51            Self::Label => "STRING or LIST<STRING>",
52        }
53    }
54
55    /// The *type* half of [`Self::check`], against a statically known
56    /// operand's Cypher type class (`STRING`, `LIST`, … — a bare class, never
57    /// a parameterized list type): a property key takes a `STRING`; a
58    /// dynamic label/type a `STRING` or a `LIST`, whose elements the per-row
59    /// rule then checks. Content (a string's text, a list's elements) is the
60    /// other half, decided by [`Self::check`] per value.
61    pub fn accepts_type(self, type_name: &str) -> bool {
62        match self {
63            Self::PropertyKey => type_name == "STRING",
64            Self::Label => type_name == "STRING" || type_name == "LIST",
65        }
66    }
67
68    /// The dynamic-operand rule for this namespace: a property key is one
69    /// non-empty, NUL-free `STRING`; a label/type operand is a `STRING` or
70    /// a `LIST<STRING>` of such names. Validation-only callers (the front's
71    /// compile-time fold) use this token-keyed entry; callers that need the
72    /// resolved name(s) call [`dynamic_property_key`] /
73    /// [`dynamic_label_names`] directly.
74    pub fn check(self, value: &Value) -> Result<(), DynamicAccessError> {
75        match self {
76            Self::PropertyKey => dynamic_property_key(value).map(|_| ()),
77            Self::Label => dynamic_label_names(value).map(|_| ()),
78        }
79    }
80}
81
82/// One rejected dynamic operand, carrying the data both error channels need
83/// (the front renders it as an `EngineError` (`relate-error`),
84/// the executor as a [`Error`]). `Display` is the authored detail text.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum DynamicAccessError {
87    /// 22N27 / 22NB1: the operand is not of the required type.
88    WrongType {
89        token: DynamicNameToken,
90        /// The Cypher type name of the offending operand, e.g. `INTEGER`.
91        type_name: String,
92    },
93    /// 42I11: a name is empty or contains a null byte.
94    InvalidName {
95        token: DynamicNameToken,
96        input: String,
97    },
98}
99
100impl DynamicAccessError {
101    /// The 22N27/22NB1 rejection for `token`'s namespace: `type_name` is the
102    /// offending operand's Cypher type name. One constructor for both token
103    /// namespaces, so the position/expected vocabulary lives only on
104    /// [`DynamicNameToken`].
105    pub fn wrong_type(token: DynamicNameToken, type_name: impl Into<String>) -> Self {
106        Self::WrongType {
107            token,
108            type_name: type_name.into(),
109        }
110    }
111
112    /// The [`ErrorKind`] both channels classify the failure under: a wrong
113    /// type is `InvalidArgumentType` (22N27/22NB1), an invalid token name is
114    /// a `SyntaxError`-class violation (42I11).
115    pub fn kind(&self) -> ErrorKind {
116        match self {
117            Self::WrongType { .. } => ErrorKind::InvalidArgumentType,
118            Self::InvalidName { .. } => ErrorKind::SyntaxError,
119        }
120    }
121}
122
123impl fmt::Display for DynamicAccessError {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        match self {
126            Self::WrongType { token, type_name } => write!(
127                f,
128                "Invalid input '{type_name}' for {}. Expected to be {}.",
129                token.position(),
130                token.expected()
131            ),
132            Self::InvalidName { token, input } => write!(
133                f,
134                "invalid name. A {} name cannot be empty or contain any null-bytes: '{}'.",
135                token.as_str(),
136                escape_for_message(input)
137            ),
138        }
139    }
140}
141
142impl From<DynamicAccessError> for Error {
143    fn from(error: DynamicAccessError) -> Self {
144        let detail = error.to_string();
145        // Matched by variant, not through `kind()`: a wrong operand type is
146        // an argument-type violation (22N27/22NB1), an invalid token name a
147        // syntax violation (42I11). A new variant is therefore a compile
148        // error here — never a silent `Semantic` degradation the bindings'
149        // metadata scan cannot classify.
150        match error {
151            DynamicAccessError::WrongType { .. } => Error::invalid_argument_type(detail),
152            DynamicAccessError::InvalidName { .. } => Error::syntax(detail),
153        }
154    }
155}
156
157/// The one dynamic property-key rule: the key must be a non-empty, NUL-free
158/// `STRING`.
159pub fn dynamic_property_key(value: &Value) -> Result<String, DynamicAccessError> {
160    match value {
161        Value::String(key) => validated_name(DynamicNameToken::PropertyKey, key),
162        other => Err(DynamicAccessError::wrong_type(
163            DynamicNameToken::PropertyKey,
164            bare_type_name(other),
165        )),
166    }
167}
168
169/// The one dynamic label/type rule: the operand must be a `STRING` or a
170/// `LIST<STRING>`, and every name must be non-empty and NUL-free.
171pub fn dynamic_label_names(value: &Value) -> Result<Vec<String>, DynamicAccessError> {
172    match value {
173        Value::List(items) => items.iter().map(label_name).collect(),
174        other => label_name(other).map(|name| vec![name]),
175    }
176}
177
178/// The per-name rule a dynamic label/type operand applies at every position:
179/// a scalar operand is one name, a list operand applies it per element, so a
180/// wrong element and a wrong scalar report the identical 22NB1 detail.
181fn label_name(item: &Value) -> Result<String, DynamicAccessError> {
182    match item {
183        Value::String(name) => validated_name(DynamicNameToken::Label, name),
184        other => Err(DynamicAccessError::wrong_type(
185            DynamicNameToken::Label,
186            bare_type_name(other),
187        )),
188    }
189}
190
191/// The one token-name check: rejects an empty name or one carrying a NUL
192/// byte (42I11), and returns the owned spelling of a valid name.
193fn validated_name(token: DynamicNameToken, name: &str) -> Result<String, DynamicAccessError> {
194    if name.is_empty() || name.contains('\0') {
195        Err(DynamicAccessError::InvalidName {
196            token,
197            input: name.to_string(),
198        })
199    } else {
200        Ok(name.to_string())
201    }
202}
203
204/// The input as it can sit inside a single-quoted detail message: a NUL byte
205/// renders as `\0` instead of breaking the line.
206fn escape_for_message(input: &str) -> String {
207    input.chars().flat_map(char::escape_default).collect()
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use crate::temporal::Temporal;
214
215    #[test]
216    fn string_property_key_is_accepted_by_reference() {
217        assert_eq!(
218            dynamic_property_key(&Value::String("name".into())).unwrap(),
219            "name"
220        );
221    }
222
223    #[test]
224    fn wrong_property_key_type_names_the_input_and_the_expected_type() {
225        let error = dynamic_property_key(&Value::Int(1)).unwrap_err();
226        assert_eq!(error.kind(), ErrorKind::InvalidArgumentType);
227        assert_eq!(
228            error.to_string(),
229            "Invalid input 'INTEGER' for node or relationship property key. Expected to be STRING."
230        );
231    }
232
233    #[test]
234    fn empty_and_nul_property_keys_are_invalid_names() {
235        for key in ["", "a\0b"] {
236            let error = dynamic_property_key(&Value::String(key.into())).unwrap_err();
237            assert_eq!(error.kind(), ErrorKind::SyntaxError);
238            assert!(error.to_string().starts_with(
239                "invalid name. A property key name cannot be empty or contain any null-bytes: '"
240            ));
241        }
242    }
243
244    #[test]
245    fn label_names_accept_a_string_and_a_string_list() {
246        assert_eq!(
247            dynamic_label_names(&Value::String("A".into())).unwrap(),
248            vec!["A".to_string()]
249        );
250        let list = Value::List(vec![Value::String("A".into()), Value::String("B".into())].into());
251        assert_eq!(
252            dynamic_label_names(&list).unwrap(),
253            vec!["A".to_string(), "B".to_string()]
254        );
255    }
256
257    #[test]
258    fn label_names_reject_non_string_and_invalid_elements() {
259        let wrong = dynamic_label_names(&Value::Int(1)).unwrap_err();
260        assert_eq!(
261            wrong.to_string(),
262            "Invalid input 'INTEGER' for dynamic label. Expected to be STRING or LIST<STRING>."
263        );
264        let mixed = Value::List(vec![Value::String("A".into()), Value::Int(1)].into());
265        assert_eq!(dynamic_label_names(&mixed).unwrap_err(), wrong);
266        assert!(dynamic_label_names(&Value::String("".into())).is_err());
267    }
268
269    #[test]
270    fn token_check_is_the_shared_validation_entry() {
271        DynamicNameToken::PropertyKey
272            .check(&Value::String("name".into()))
273            .unwrap();
274        DynamicNameToken::Label
275            .check(&Value::List(vec![Value::String("A".into())].into()))
276            .unwrap();
277        assert_eq!(
278            DynamicNameToken::PropertyKey
279                .check(&Value::Int(1))
280                .unwrap_err()
281                .kind(),
282            ErrorKind::InvalidArgumentType
283        );
284        assert_eq!(
285            DynamicNameToken::Label
286                .check(&Value::String("".into()))
287                .unwrap_err()
288                .kind(),
289            ErrorKind::SyntaxError
290        );
291    }
292
293    /// The type half: the accepted class set is the one [`DynamicNameToken::check`]
294    /// enforces per value — a property key takes a `STRING`, a label also a
295    /// `LIST`.
296    #[test]
297    fn accepts_type_is_the_type_half_of_check() {
298        assert!(DynamicNameToken::PropertyKey.accepts_type("STRING"));
299        assert!(!DynamicNameToken::PropertyKey.accepts_type("LIST"));
300        assert!(!DynamicNameToken::PropertyKey.accepts_type("INTEGER"));
301        assert!(DynamicNameToken::Label.accepts_type("STRING"));
302        assert!(DynamicNameToken::Label.accepts_type("LIST"));
303        assert!(!DynamicNameToken::Label.accepts_type("MAP"));
304    }
305
306    /// The core `Error` channel classifies through `kind()`, so a runtime
307    /// `SET n[$k]` with `k = ""` fails as a syntax violation exactly like its
308    /// compile-time constant twin (`SET n[''] = 2`).
309    #[test]
310    fn error_conversion_follows_the_shared_classification() {
311        assert!(matches!(
312            Error::from(dynamic_property_key(&Value::Int(1)).unwrap_err()),
313            Error::InvalidArgumentType(_)
314        ));
315        assert!(matches!(
316            Error::from(dynamic_property_key(&Value::String("".into())).unwrap_err()),
317            Error::Syntax(_)
318        ));
319    }
320
321    /// Lexicographic order would render FLOAT before INTEGER; the CIP-100
322    /// order both consumers share renders INTEGER first in this module's
323    /// 22N27 detail text.
324    #[test]
325    fn wrong_type_detail_orders_numerics_by_cip100_not_lexicographically() {
326        let mixed = Value::List(vec![Value::Float(1.5), Value::Int(1)].into());
327        assert_eq!(
328            dynamic_property_key(&mixed).unwrap_err().to_string(),
329            "Invalid input 'LIST<INTEGER | FLOAT>' for node or relationship property key. \
330             Expected to be STRING."
331        );
332    }
333
334    /// The 22N27/22NB1 detail text renders temporal values with the Cypher
335    /// type spelling this module's type-name source produces.
336    #[test]
337    fn wrong_type_detail_renders_the_temporal_spelling() {
338        let duration = Value::Temporal(Temporal::Duration {
339            months: 0,
340            days: 0,
341            nanos: 0,
342        });
343        assert_eq!(
344            dynamic_property_key(&duration).unwrap_err().to_string(),
345            "Invalid input 'DURATION' for node or relationship property key. \
346             Expected to be STRING."
347        );
348        let date = Value::Temporal(Temporal::CivilDate {
349            year: 2020,
350            month: 1,
351            day: 1,
352        });
353        assert_eq!(
354            dynamic_label_names(&date).unwrap_err().to_string(),
355            "Invalid input 'DATE' for dynamic label. Expected to be STRING or LIST<STRING>."
356        );
357    }
358}