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    string_name(DynamicNameToken::PropertyKey, value)
161}
162
163/// The one dynamic label/type rule: the operand must be a `STRING` or a
164/// `LIST<STRING>`, and every name must be non-empty and NUL-free.
165pub fn dynamic_label_names(value: &Value) -> Result<Vec<String>, DynamicAccessError> {
166    match value {
167        Value::List(items) => items.iter().map(label_name).collect(),
168        other => label_name(other).map(|name| vec![name]),
169    }
170}
171
172/// The per-name rule a dynamic label/type operand applies at every position:
173/// a scalar operand is one name, a list operand applies it per element, so a
174/// wrong element and a wrong scalar report the identical 22NB1 detail.
175fn label_name(item: &Value) -> Result<String, DynamicAccessError> {
176    string_name(DynamicNameToken::Label, item)
177}
178
179/// The one string-or-wrong-type rule both dynamic name positions share: a
180/// `STRING` is validated as a name for `token`; any other value is the
181/// wrong-type rejection naming `token`.
182fn string_name(token: DynamicNameToken, value: &Value) -> Result<String, DynamicAccessError> {
183    match value {
184        Value::String(name) => validated_name(token, name),
185        other => Err(DynamicAccessError::wrong_type(token, bare_type_name(other))),
186    }
187}
188
189/// The one token-name check: rejects an empty name or one carrying a NUL
190/// byte (42I11), and returns the owned spelling of a valid name.
191fn validated_name(token: DynamicNameToken, name: &str) -> Result<String, DynamicAccessError> {
192    if name.is_empty() || name.contains('\0') {
193        Err(DynamicAccessError::InvalidName {
194            token,
195            input: name.to_string(),
196        })
197    } else {
198        Ok(name.to_string())
199    }
200}
201
202/// The input as it can sit inside a single-quoted detail message: a NUL byte
203/// renders as `\0` instead of breaking the line.
204fn escape_for_message(input: &str) -> String {
205    input.chars().flat_map(char::escape_default).collect()
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211    use crate::temporal::Temporal;
212
213    #[test]
214    fn string_property_key_is_accepted_by_reference() {
215        assert_eq!(
216            dynamic_property_key(&Value::String("name".into())).unwrap(),
217            "name"
218        );
219    }
220
221    #[test]
222    fn wrong_property_key_type_names_the_input_and_the_expected_type() {
223        let error = dynamic_property_key(&Value::Int(1)).unwrap_err();
224        assert_eq!(error.kind(), ErrorKind::InvalidArgumentType);
225        assert_eq!(
226            error.to_string(),
227            "Invalid input 'INTEGER' for node or relationship property key. Expected to be STRING."
228        );
229    }
230
231    #[test]
232    fn empty_and_nul_property_keys_are_invalid_names() {
233        for key in ["", "a\0b"] {
234            let error = dynamic_property_key(&Value::String(key.into())).unwrap_err();
235            assert_eq!(error.kind(), ErrorKind::SyntaxError);
236            assert!(error.to_string().starts_with(
237                "invalid name. A property key name cannot be empty or contain any null-bytes: '"
238            ));
239        }
240    }
241
242    #[test]
243    fn label_names_accept_a_string_and_a_string_list() {
244        assert_eq!(
245            dynamic_label_names(&Value::String("A".into())).unwrap(),
246            vec!["A".to_string()]
247        );
248        let list = Value::List(vec![Value::String("A".into()), Value::String("B".into())].into());
249        assert_eq!(
250            dynamic_label_names(&list).unwrap(),
251            vec!["A".to_string(), "B".to_string()]
252        );
253    }
254
255    #[test]
256    fn label_names_reject_non_string_and_invalid_elements() {
257        let wrong = dynamic_label_names(&Value::Int(1)).unwrap_err();
258        assert_eq!(
259            wrong.to_string(),
260            "Invalid input 'INTEGER' for dynamic label. Expected to be STRING or LIST<STRING>."
261        );
262        let mixed = Value::List(vec![Value::String("A".into()), Value::Int(1)].into());
263        assert_eq!(dynamic_label_names(&mixed).unwrap_err(), wrong);
264        assert!(dynamic_label_names(&Value::String("".into())).is_err());
265    }
266
267    #[test]
268    fn token_check_is_the_shared_validation_entry() {
269        DynamicNameToken::PropertyKey
270            .check(&Value::String("name".into()))
271            .unwrap();
272        DynamicNameToken::Label
273            .check(&Value::List(vec![Value::String("A".into())].into()))
274            .unwrap();
275        assert_eq!(
276            DynamicNameToken::PropertyKey
277                .check(&Value::Int(1))
278                .unwrap_err()
279                .kind(),
280            ErrorKind::InvalidArgumentType
281        );
282        assert_eq!(
283            DynamicNameToken::Label
284                .check(&Value::String("".into()))
285                .unwrap_err()
286                .kind(),
287            ErrorKind::SyntaxError
288        );
289    }
290
291    /// The type half: the accepted class set is the one [`DynamicNameToken::check`]
292    /// enforces per value — a property key takes a `STRING`, a label also a
293    /// `LIST`.
294    #[test]
295    fn accepts_type_is_the_type_half_of_check() {
296        assert!(DynamicNameToken::PropertyKey.accepts_type("STRING"));
297        assert!(!DynamicNameToken::PropertyKey.accepts_type("LIST"));
298        assert!(!DynamicNameToken::PropertyKey.accepts_type("INTEGER"));
299        assert!(DynamicNameToken::Label.accepts_type("STRING"));
300        assert!(DynamicNameToken::Label.accepts_type("LIST"));
301        assert!(!DynamicNameToken::Label.accepts_type("MAP"));
302    }
303
304    /// The core `Error` channel classifies through `kind()`, so a runtime
305    /// `SET n[$k]` with `k = ""` fails as a syntax violation exactly like its
306    /// compile-time constant twin (`SET n[''] = 2`).
307    #[test]
308    fn error_conversion_follows_the_shared_classification() {
309        assert!(matches!(
310            Error::from(dynamic_property_key(&Value::Int(1)).unwrap_err()),
311            Error::InvalidArgumentType(_)
312        ));
313        assert!(matches!(
314            Error::from(dynamic_property_key(&Value::String("".into())).unwrap_err()),
315            Error::Syntax(_)
316        ));
317    }
318
319    /// Lexicographic order would render FLOAT before INTEGER; the CIP-100
320    /// order both consumers share renders INTEGER first in this module's
321    /// 22N27 detail text.
322    #[test]
323    fn wrong_type_detail_orders_numerics_by_cip100_not_lexicographically() {
324        let mixed = Value::List(vec![Value::Float(1.5), Value::Int(1)].into());
325        assert_eq!(
326            dynamic_property_key(&mixed).unwrap_err().to_string(),
327            "Invalid input 'LIST<INTEGER | FLOAT>' for node or relationship property key. \
328             Expected to be STRING."
329        );
330    }
331
332    /// The 22N27/22NB1 detail text renders temporal values with the Cypher
333    /// type spelling this module's type-name source produces.
334    #[test]
335    fn wrong_type_detail_renders_the_temporal_spelling() {
336        let duration = Value::Temporal(Temporal::Duration {
337            months: 0,
338            days: 0,
339            nanos: 0,
340        });
341        assert_eq!(
342            dynamic_property_key(&duration).unwrap_err().to_string(),
343            "Invalid input 'DURATION' for node or relationship property key. \
344             Expected to be STRING."
345        );
346        let date = Value::Temporal(Temporal::CivilDate {
347            year: 2020,
348            month: 1,
349            day: 1,
350        });
351        assert_eq!(
352            dynamic_label_names(&date).unwrap_err().to_string(),
353            "Invalid input 'DATE' for dynamic label. Expected to be STRING or LIST<STRING>."
354        );
355    }
356}