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