1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! The `<value type>` grammar (CIP-86/CIP-102): component type lists,
//! type terms and leaves, predefined types, vector and time-zone
//! suffixes, and the ANY<...> bracket forms — split out of
//! `expressions.rs` so the expression grammar file stops accreting past
//! every other parser module's size.
use super::*;
impl<'a> Parser<'a> {
/// Parses a `<value type>` (CIP-86 grammar): a `<component type list>`,
/// i.e. one or more `|`-separated type terms. A single term is returned
/// as-is; two or more become a closed dynamic union (CIP-86 "bare
/// component list", equivalent to `ANY<A | B | ...>`). This is the
/// entry point used everywhere a `<value type>` production appears: the
/// top-level type predicate right-hand side, and (recursively) inside
/// `LIST<...>`/`ANY<...>` brackets.
pub(super) fn parse_value_type(&mut self) -> ParseResult<TypeExpr> {
// ADR-0257: `LIST<...>`/`ARRAY<...>` and `ANY<...>` type brackets
// recurse back into this function through `parse_type_term` ->
// `parse_type_leaf` (and `parse_any_type`) without passing through
// `parse_expression`, so deeply nested value types
// (`1::LIST<LIST<...>>`) would otherwise overflow the stack
// (LABS-69). Count each level, same balanced guard as the
// label/subpath sites.
self.with_expr_depth(Self::parse_value_type_at_current_depth)
}
fn parse_value_type_at_current_depth(&mut self) -> ParseResult<TypeExpr> {
let first = self.parse_type_term()?;
if self.peek_type() != TokenType::Pipe {
return Ok(first);
}
let mut components = vec![first];
while self.peek_type() == TokenType::Pipe {
self.next_token();
components.push(self.parse_type_term()?);
}
self.validate_union_nullability(&components)?;
Ok(TypeExpr::Union(components))
}
/// Per CIP-86's "Not Null Uses" section: within a closed dynamic
/// union's component list, either every component must be `NOT NULL`
/// or none may be -- mixed nullability is a compile-time syntax error.
fn validate_union_nullability(&self, components: &[TypeExpr]) -> ParseResult<()> {
let not_null = components[0].direct_not_null();
if components.iter().all(|c| c.direct_not_null() == not_null) {
Ok(())
} else {
Err(self.error(
"invalid type: mixed nullability among union components (either all \
components of a closed union must be NOT NULL or none may be)",
))
}
}
/// Parses a single type term: a `<predefined type>` / `<constructed
/// type>` / `<dynamic union type>` leaf, followed by zero or more
/// trailing `LIST`/`ARRAY` postfixes (`T LIST`, `T LIST LIST`, ...).
/// The trailing-list postfix binds to this single term only, tighter
/// than the `|` handled by `parse_value_type` -- per CIP-86's "List
/// Syntax Additions", `BOOLEAN | STRING LIST` means `BOOLEAN |
/// LIST<STRING>`, not `LIST<BOOLEAN | STRING>`.
fn parse_type_term(&mut self) -> ParseResult<TypeExpr> {
let mut term = self.parse_type_leaf()?;
while self.peek_is_list_or_array_keyword() {
self.next_token();
let not_null = self.maybe_consume_not_null();
term = TypeExpr::List {
element: Box::new(term),
not_null,
};
}
Ok(term)
}
fn peek_is_list_or_array_keyword(&self) -> bool {
self.peek_is_ident("LIST") || self.peek_is_ident("ARRAY")
}
/// Consumes a trailing `NOT NULL` or its `!` shorthand (CIP-102) if
/// present (with backtracking, since `NOT` alone does not commit to it);
/// returns whether it was found. Whitespace (including newlines) before
/// `!` is permitted since the lexer already discards it between tokens
/// — matching observed Neo4j behavior rather than the CIP text, which
/// says whitespace should be disallowed (see CIP-102 NOTES.md Deviations).
fn maybe_consume_not_null(&mut self) -> bool {
if self.peek_type() == TokenType::Bang {
self.next_token();
return true;
}
if self.peek_type() == TokenType::NOT {
let saved = self.save_pos();
self.next_token();
if self.peek_type() == TokenType::NULL {
self.next_token();
true
} else {
self.restore_pos(saved);
false
}
} else {
false
}
}
/// Parses a single leaf `<value type>` production (everything except
/// the trailing-`LIST`/`ARRAY` postfix, which `parse_type_term` layers
/// on top): predefined scalar/temporal/reference/point/map/nothing/null
/// types, the `LIST<T>`/`ARRAY<T>` bracket form, `[ANY] PROPERTY
/// VALUE`, and the `ANY [...]` family (open union, closed union,
/// `ANY MAP`/`ANY NODE`/etc).
fn parse_type_leaf(&mut self) -> ParseResult<TypeExpr> {
let tok = self.peek().clone();
match tok.ty {
TokenType::NULL => self.parse_leaf_predefined(PredefinedKind::Null),
TokenType::NODE => self.parse_leaf_predefined(PredefinedKind::Node),
TokenType::POINT => self.parse_leaf_predefined(PredefinedKind::Point),
TokenType::VECTOR => self.parse_vector_type(),
TokenType::Identifier => {
let upper = tok.literal.to_ascii_uppercase();
match upper.as_str() {
"ANY" => self.parse_any_type(),
"NOTHING" => self.parse_leaf_predefined(PredefinedKind::Nothing),
"BOOL" | "BOOLEAN" => self.parse_leaf_predefined(PredefinedKind::Boolean),
"STRING" | "VARCHAR" => self.parse_leaf_predefined(PredefinedKind::String),
"INT" | "INTEGER" | "INT64" | "INTEGER64" => {
self.parse_leaf_predefined(PredefinedKind::Integer)
}
"SIGNED" => {
self.next_token();
self.expect_keyword_ident("INTEGER")?;
let not_null = self.maybe_consume_not_null();
Ok(TypeExpr::Predefined {
kind: PredefinedKind::Integer,
not_null,
})
}
"FLOAT" | "FLOAT64" => self.parse_leaf_predefined(PredefinedKind::Float),
"DATE" => self.parse_leaf_predefined(PredefinedKind::Date),
"DURATION" => self.parse_leaf_predefined(PredefinedKind::Duration),
"VERTEX" => self.parse_leaf_predefined(PredefinedKind::Node),
"EDGE" | "RELATIONSHIP" => {
self.parse_leaf_predefined(PredefinedKind::Relationship)
}
"PATH" => self.parse_leaf_predefined(PredefinedKind::Path),
"MAP" => self.parse_leaf_predefined(PredefinedKind::Map),
// CIP-246
"UUID" => self.parse_leaf_predefined(PredefinedKind::Uuid),
"PROPERTY" => {
self.next_token();
self.parse_property_value_tail()
}
"LIST" | "ARRAY" => {
self.next_token();
self.expect(TokenType::LessThan)?;
let element = self.parse_value_type()?;
self.expect(TokenType::GreaterThan)?;
let not_null = self.maybe_consume_not_null();
Ok(TypeExpr::List {
element: Box::new(element),
not_null,
})
}
"TIME" => {
self.next_token();
self.parse_time_zone_suffix(
PredefinedKind::ZonedTime,
PredefinedKind::LocalTime,
)
}
"DATETIME" => {
self.next_token();
self.parse_time_zone_suffix(
PredefinedKind::ZonedDateTime,
PredefinedKind::LocalDateTime,
)
}
"TIMESTAMP" => {
self.next_token();
// Unlike bare TIME/DATETIME (whose no-suffix case
// means the zoned variant), TIMESTAMP has no
// suffix-less form: WITH or WITHOUT is required.
if self.peek_type() == TokenType::WITH || self.peek_is_ident("WITHOUT") {
self.parse_time_zone_suffix(
PredefinedKind::ZonedDateTime,
PredefinedKind::LocalDateTime,
)
} else {
let bad = self.peek().clone();
Err(self.error_at_token(
&bad,
format!("expected WITH or WITHOUT, got {:?}", bad.literal),
))
}
}
"LOCAL" => self.parse_time_or_datetime_prefixed(
PredefinedKind::LocalTime,
PredefinedKind::LocalDateTime,
),
"ZONED" => self.parse_time_or_datetime_prefixed(
PredefinedKind::ZonedTime,
PredefinedKind::ZonedDateTime,
),
_ => {
// CIP-216: every alias the CIP-200 table knows that
// the plain INTEGER/FLOAT arms above did not claim
// is a vector-only coordinate type, valid inside
// `VECTOR<...>`/`VECTOR(...)` but not as a
// standalone property type. One table decides, so a
// newly added alias cannot drift between the two
// grammars.
if VectorCoordKind::from_alias(&upper).is_some() {
return Err(self.error_at_token(
&tok,
format!(
"Invalid input '{}', vector-only numeric coordinate types \
are not property value types on their own and cannot be \
used outside VECTOR<...>",
tok.literal
),
));
}
Err(self.error_at_token(
&tok,
format!("expected a type name, got {:?}", tok.literal),
))
}
}
}
_ => {
Err(self
.error_at_token(&tok, format!("expected a type name, got {:?}", tok.literal)))
}
}
}
/// Parses the two-word `LOCAL`/`ZONED` prefixed temporal forms: the
/// already-matched prefix word (consumed here) selects the kind pair,
/// the second word (`TIME`/`DATETIME`) selects the kind within it.
fn parse_time_or_datetime_prefixed(
&mut self,
time: PredefinedKind,
datetime: PredefinedKind,
) -> ParseResult<TypeExpr> {
self.next_token();
if self.peek_is_ident("TIME") {
return self.parse_leaf_predefined(time);
}
if self.peek_is_ident("DATETIME") {
return self.parse_leaf_predefined(datetime);
}
let bad = self.peek().clone();
Err(self.error_at_token(
&bad,
format!("expected TIME or DATETIME, got {:?}", bad.literal),
))
}
/// Parses a `VECTOR` type leaf (CIP-216), already having peeked the
/// `VECTOR` keyword: Cypher style `VECTOR<TYPE [NOT NULL]>(DIM)`, GQL
/// style `VECTOR(DIM, TYPE [NOT NULL])`, and both forms' partial
/// variants (`VECTOR<TYPE>` with no dimension, `VECTOR(DIM)` with no
/// coordinate type) -- grammatically valid, rejected only later at
/// constraint-creation time (CIP-216 Negative 1/2, "need to define
/// both coordinate type and dimension").
fn parse_vector_type(&mut self) -> ParseResult<TypeExpr> {
self.next_token(); // consume VECTOR
let mut coord = None;
if self.peek_type() == TokenType::LessThan {
self.next_token();
coord = Some(self.parse_vector_coord_type()?);
self.expect(TokenType::GreaterThan)?;
}
let mut dimension = None;
if self.peek_type() == TokenType::LeftParen {
self.next_token();
dimension = Some(self.parse_vector_dimension()?);
// The GQL form's `, TYPE` only applies when the Cypher-style
// `<...>` above didn't already supply a coordinate type.
if coord.is_none() && self.peek_type() == TokenType::Comma {
self.next_token();
coord = Some(self.parse_vector_coord_type()?);
}
self.expect(TokenType::RightParen)?;
}
let not_null = self.maybe_consume_not_null();
Ok(TypeExpr::Vector {
coord,
dimension,
not_null,
})
}
/// Parses a single vector coordinate type keyword (CIP-216's
/// restricted numeric vocabulary, not the general `<value type>`
/// grammar) plus its always-implicit-but-optional trailing `NOT NULL`.
///
/// The keyword resolves through [`VectorCoordKind::from_alias`] — the
/// CIP-200 alias table the `vector()` constructor and the canonical
/// type rendering already read — so every alias it accepts parses here
/// too, including the two-word `SIGNED INTEGER` spelling.
fn parse_vector_coord_type(&mut self) -> ParseResult<VectorCoordKind> {
let tok = self.peek().clone();
if tok.ty != TokenType::Identifier {
return Err(self.error_at_token(
&tok,
format!("{} is not a valid vector coordinate type", tok.literal),
));
}
// `SIGNED INTEGER` is one alias in two tokens: join the pair before
// consulting the table.
let name = if tok.literal.eq_ignore_ascii_case("SIGNED") {
self.next_token();
self.expect_keyword_ident("INTEGER")?;
"SIGNED INTEGER".to_string()
} else {
self.next_token();
tok.literal.to_ascii_uppercase()
};
let kind = VectorCoordKind::from_alias(&name).ok_or_else(|| {
self.error_at_token(
&tok,
format!("{} is not a valid vector coordinate type", tok.literal),
)
})?;
self.maybe_consume_not_null();
Ok(kind)
}
/// Parses a vector's `(DIMENSION)` integer literal, validating the
/// CIP-216 range (1 to 4096 inclusive) immediately.
fn parse_vector_dimension(&mut self) -> ParseResult<i64> {
let neg = if self.peek_type() == TokenType::Dash {
self.next_token();
true
} else {
false
};
let tok = self.peek().clone();
if tok.ty != TokenType::Integer {
return Err(self.error_at_token(
&tok,
format!(
"expected an integer vector dimension, got {:?}",
tok.literal
),
));
}
self.next_token();
let mut val = parse_int_literal(&tok.literal)
.map_err(|e| self.int_literal_error(&tok, e, IntLiteralSite::Expression))?;
if neg {
val = -val;
}
if !relate_model::VECTOR_DIMENSION_RANGE.contains(&val) {
return Err(self.error_at_token(
&tok,
format!(
"Expected 'DIMENSION' to be INTEGER in the range {} but found {val}.",
relate_model::dimension_range_text()
),
));
}
Ok(val)
}
/// Consumes the current (already-peeked) leaf type keyword and an
/// optional trailing `NOT NULL`.
fn parse_leaf_predefined(&mut self, kind: PredefinedKind) -> ParseResult<TypeExpr> {
self.next_token();
let not_null = self.maybe_consume_not_null();
Ok(TypeExpr::Predefined { kind, not_null })
}
/// Parses the `WITH TIME ZONE` / `WITHOUT TIME ZONE` suffix that may
/// follow a bare `TIME` or `DATETIME` leaf (`<time type>`/`<datetime
/// type>`'s second alternative). Without a suffix, the bare leaf is
/// treated as the zoned variant.
fn parse_time_zone_suffix(
&mut self,
zoned: PredefinedKind,
local: PredefinedKind,
) -> ParseResult<TypeExpr> {
// The kind is the only per-branch difference; the suffix words
// and the NOT NULL tail are shared.
let kind = if self.peek_type() == TokenType::WITH {
self.next_token();
self.expect_time_zone_words()?;
zoned
} else if self.peek_is_ident("WITHOUT") {
self.next_token();
self.expect_time_zone_words()?;
local
} else {
zoned
};
let not_null = self.maybe_consume_not_null();
Ok(TypeExpr::Predefined { kind, not_null })
}
/// Consumes the `TIME ZONE` tail of a `WITH[OUT] TIME ZONE` type
/// suffix, accepting both the two-word spelling and the single-word
/// `TIMEZONE` alias (both appear in the wild, e.g. CIP-100's own
/// `TIMESTAMP WITHOUT TIMEZONE`).
fn expect_time_zone_words(&mut self) -> ParseResult<()> {
if self.peek_is_ident("TIMEZONE") {
self.next_token();
return Ok(());
}
self.expect_keyword_ident("TIME")?;
self.expect_keyword_ident("ZONE")?;
Ok(())
}
/// Consumes `VALUE` plus an optional `NOT NULL` after an already-matched
/// `PROPERTY` — the `[ANY] PROPERTY VALUE` production's tail, shared by
/// the bare and the ANY-prefixed spelling.
fn parse_property_value_tail(&mut self) -> ParseResult<TypeExpr> {
self.expect_keyword_ident("VALUE")?;
let not_null = self.maybe_consume_not_null();
Ok(TypeExpr::PropertyValue { not_null })
}
/// Parses everything that can follow the `ANY` keyword: `ANY PROPERTY
/// VALUE`, `ANY NODE`/`ANY VERTEX`, `ANY EDGE`/`ANY RELATIONSHIP`, `ANY
/// MAP`, the open dynamic union `ANY [VALUE] [NOT NULL]`, and the
/// closed dynamic union bracket form `ANY [VALUE] <A | B | ...>` (which
/// grammatically has no `[NOT NULL]` of its own).
fn parse_any_type(&mut self) -> ParseResult<TypeExpr> {
self.next_token(); // consume ANY
if self.peek_is_ident("PROPERTY") {
self.next_token();
return self.parse_property_value_tail();
}
if self.peek_type() == TokenType::NODE || self.peek_is_ident("VERTEX") {
return self.parse_leaf_predefined(PredefinedKind::Node);
}
if self.peek_is_ident("EDGE") || self.peek_is_ident("RELATIONSHIP") {
return self.parse_leaf_predefined(PredefinedKind::Relationship);
}
if self.peek_is_ident("MAP") {
return self.parse_leaf_predefined(PredefinedKind::Map);
}
if self.peek_is_ident("VALUE") {
self.next_token();
}
if self.peek_type() == TokenType::LessThan {
self.next_token();
let inner = self.parse_value_type()?;
self.expect(TokenType::GreaterThan)?;
// No [NOT NULL] production exists for a closed union: a
// trailing NOT NULL is left unconsumed here and becomes a
// syntax error further up (CIP-86 "Not Null Uses" > invalid).
return Ok(match inner {
TypeExpr::Union(components) => TypeExpr::Union(components),
single => TypeExpr::Union(vec![single]),
});
}
let not_null = self.maybe_consume_not_null();
Ok(TypeExpr::Predefined {
kind: PredefinedKind::Any,
not_null,
})
}
}