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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
// Parser — tokenizes and parses Cypher-like pattern strings into a Pattern AST.
use crate::datatypes::values::Value;
use std::collections::HashMap;
use std::iter::Peekable;
use std::str::Chars;
use super::pattern::{
EdgeDirection, EdgePattern, NodePattern, ParamLabel, Pattern, PatternElement, PropertyMatcher,
};
// ============================================================================
// Tokenizer
// ============================================================================
#[derive(Debug, Clone, PartialEq)]
pub enum Token {
LParen, // (
RParen, // )
LBracket, // [
RBracket, // ]
LBrace, // {
RBrace, // }
Colon, // :
Comma, // ,
Dash, // -
GreaterThan, // >
LessThan, // <
Star, // * (for variable-length paths)
DotDot, // .. (for range in variable-length)
Dot, // . (property access in an inline-map value: {id: prior.id})
Pipe, // | (for multi-type edges: [:A|B])
Identifier(String),
StringLit(String),
IntLit(i64),
FloatLit(f64),
BoolLit(bool),
Parameter(String), // $param_name
}
/// Lex one numeric literal, with the sign (if any) already consumed by the
/// caller and reported through `negative`.
///
/// Accepts `12`, `1.5` and the leading-dot form `.5` (normalised to `0.5`),
/// and stops before a `..` range operator so `*1..3` still lexes as
/// `IntLit(1) DotDot IntLit(3)`.
///
/// The sign is folded into the string that is parsed, never applied
/// afterwards: `-9223372036854775808` is `i64::MIN`, but its magnitude alone
/// does not fit in an `i64`, so a parse-then-negate lexer would reject it.
fn lex_number(chars: &mut Peekable<Chars<'_>>, negative: bool) -> Result<Token, String> {
let mut num_str = String::new();
if negative {
num_str.push('-');
}
let mut has_dot = false;
if chars.peek() == Some(&'.') {
// Leading-dot float: `.5` → `0.5`
chars.next();
num_str.push_str("0.");
has_dot = true;
}
while let Some(&c) = chars.peek() {
if c.is_ascii_digit() {
num_str.push(c);
chars.next();
} else if c == '.' && !has_dot {
// Peek ahead to check if this is '..' (range operator).
// Clone the iterator to peek ahead without consuming.
let mut peek_chars = chars.clone();
peek_chars.next(); // skip the first '.'
if peek_chars.peek() == Some(&'.') {
// This is '..', stop here and don't include the dot
break;
}
// It's a decimal point for a float
has_dot = true;
num_str.push(c);
chars.next();
} else {
break;
}
}
if has_dot {
Ok(Token::FloatLit(
num_str
.parse()
.map_err(|_| format!("Invalid float: {}", num_str))?,
))
} else {
Ok(Token::IntLit(
num_str
.parse()
.map_err(|_| format!("Invalid integer: {}", num_str))?,
))
}
}
/// Does a `-` at the current position open a signed numeric literal?
/// True only when a digit, or a `.` followed by a digit, comes next —
/// structural dashes in a pattern are always followed by `[`, `>`, `(`,
/// `<` or another `-`, so an edge is never mistaken for a number.
fn opens_signed_number(chars: &Peekable<Chars<'_>>) -> bool {
let mut ahead = chars.clone();
match ahead.next() {
Some(c) if c.is_ascii_digit() => true,
Some('.') => ahead.next().is_some_and(|c| c.is_ascii_digit()),
_ => false,
}
}
/// Would `word`, written bare into a pattern string, lex as something other
/// than an [`Token::Identifier`]?
///
/// **This is the emitter's obligation, and it belongs here** — next to the
/// lexer that creates the hazard. Pattern strings are not written by users;
/// they are *re-serialized* from an already-tokenized Cypher query by
/// `languages::cypher::parser::match_pattern`, which has to reproduce every
/// name it received. An identifier that this tokenizer would read back as a
/// literal has to be emitted backtick-quoted, or the name silently changes
/// meaning in transit — which is exactly how a backticked `` `TRUE` `` label
/// could be created and never matched: the escape was dropped and the
/// secondary lexer re-read a boolean.
///
/// Keep this in step with the identifier arm of [`tokenize`]; the agreement is
/// pinned by `quoting_predicate_agrees_with_the_tokenizer`.
pub fn bare_word_needs_quoting(word: &str) -> bool {
// A leading `$` lexes as a parameter reference here, which is how a
// *dynamic* label is written (`(n:$label)`). A name that happens to start
// with `$` — only reachable as `` `$label` `` in the source, since the
// primary tokenizer would otherwise have made it a parameter — must
// therefore be re-emitted quoted, or the re-serializer turns a literal
// label into a parameter reference and the query silently changes meaning.
word.starts_with('$') || word.eq_ignore_ascii_case("true") || word.eq_ignore_ascii_case("false")
}
pub fn tokenize(input: &str) -> Result<Vec<Token>, String> {
let mut tokens = Vec::new();
let mut chars = input.chars().peekable();
while let Some(&ch) = chars.peek() {
match ch {
' ' | '\t' | '\n' | '\r' => {
chars.next();
}
'(' => {
tokens.push(Token::LParen);
chars.next();
}
')' => {
tokens.push(Token::RParen);
chars.next();
}
'[' => {
tokens.push(Token::LBracket);
chars.next();
}
']' => {
tokens.push(Token::RBracket);
chars.next();
}
'{' => {
tokens.push(Token::LBrace);
chars.next();
}
'}' => {
tokens.push(Token::RBrace);
chars.next();
}
':' => {
tokens.push(Token::Colon);
chars.next();
}
',' => {
tokens.push(Token::Comma);
chars.next();
}
'-' => {
chars.next();
if opens_signed_number(&chars) {
// Negative inline-map literal, e.g. `{temp: -1}`. The
// sign belongs to the number, not to a structural dash.
tokens.push(lex_number(&mut chars, true)?);
} else {
tokens.push(Token::Dash);
}
}
'>' => {
tokens.push(Token::GreaterThan);
chars.next();
}
'<' => {
tokens.push(Token::LessThan);
chars.next();
}
'*' => {
tokens.push(Token::Star);
chars.next();
}
'|' => {
tokens.push(Token::Pipe);
chars.next();
}
'.' => {
// Check for '..' (range operator)
let mut ahead = chars.clone();
ahead.next();
if ahead.peek() == Some(&'.') {
chars.next();
chars.next();
tokens.push(Token::DotDot);
} else if ahead.peek().is_some_and(|c| c.is_ascii_digit()) {
// It's a float starting with '.'
tokens.push(lex_number(&mut chars, false)?);
} else {
chars.next();
// Lone '.' — property access in an inline-map value,
// e.g. `MATCH (b {id: prior.id})`. `parse_properties`
// consumes the `ident . ident` sequence as a correlated
// node-property reference (EqualsNodeProp).
tokens.push(Token::Dot);
}
}
'"' | '\'' => {
let quote = ch;
chars.next(); // consume opening quote
let mut s = String::new();
while let Some(&c) = chars.peek() {
if c == quote {
chars.next(); // consume closing quote
break;
}
if c == '\\' {
chars.next();
if let Some(&escaped) = chars.peek() {
s.push(match escaped {
'n' => '\n',
't' => '\t',
'r' => '\r',
_ => escaped,
});
chars.next();
}
} else {
s.push(c);
chars.next();
}
}
tokens.push(Token::StringLit(s));
}
c if c.is_ascii_digit() => {
tokens.push(lex_number(&mut chars, false)?);
}
'`' => {
// Backtick-quoted identifier: `programming language`.
// A doubled backtick is an escaped one, matching the Cypher
// tokenizer — this lexer reads patterns *re-serialized* by
// `parser::match_pattern`, so the two escape rules have to be
// the same or a round-tripped identifier changes meaning.
chars.next(); // consume opening backtick
let mut ident = String::new();
while let Some(&c) = chars.peek() {
if c == '`' {
chars.next(); // consume the backtick
if chars.peek() == Some(&'`') {
chars.next(); // …the second of a doubled pair
ident.push('`');
continue;
}
break; // it closed the identifier
}
ident.push(c);
chars.next();
}
if ident.is_empty() {
return Err("Empty backtick identifier".to_string());
}
tokens.push(Token::Identifier(ident));
}
c if c.is_ascii_alphabetic() || c == '_' => {
let mut ident = String::new();
while let Some(&c) = chars.peek() {
if c.is_ascii_alphanumeric() || c == '_' {
ident.push(c);
chars.next();
} else {
break;
}
}
// Check for boolean literals
match ident.to_lowercase().as_str() {
"true" => tokens.push(Token::BoolLit(true)),
"false" => tokens.push(Token::BoolLit(false)),
_ => tokens.push(Token::Identifier(ident)),
}
}
'$' => {
chars.next(); // consume $
let mut name = String::new();
while let Some(&c) = chars.peek() {
if c.is_ascii_alphanumeric() || c == '_' {
name.push(c);
chars.next();
} else {
break;
}
}
if name.is_empty() {
return Err("Expected parameter name after '$'".to_string());
}
tokens.push(Token::Parameter(name));
}
_ => return Err(format!(
"Unexpected character '{}' in pattern. Valid pattern syntax: (node)-[:EDGE]->(node). \
Use () for nodes, [] for edges, : for types, {{}} for properties.",
ch
)),
}
}
Ok(tokens)
}
// ============================================================================
// Parser
// ============================================================================
/// Parses Cypher-like pattern strings into a `Pattern` AST.
///
/// Tokenizes the input, then builds a sequence of `PatternElement`
/// nodes and edges: `(a:Type {key: val})-[:REL]->(b:Type)`.
pub struct Parser {
tokens: Vec<Token>,
pos: usize,
}
impl Parser {
pub fn new(tokens: Vec<Token>) -> Self {
Parser { tokens, pos: 0 }
}
fn peek(&self) -> Option<&Token> {
self.tokens.get(self.pos)
}
fn advance(&mut self) -> Option<&Token> {
let token = self.tokens.get(self.pos);
self.pos += 1;
token
}
fn expect(&mut self, expected: &Token) -> Result<(), String> {
match self.advance() {
Some(token) if token == expected => Ok(()),
Some(token) => Err(format!(
"Syntax error: expected '{}', but found '{}'. Check your pattern syntax.",
Self::token_to_display(expected),
Self::token_to_display(token)
)),
None => Err(format!(
"Syntax error: expected '{}', but reached end of pattern. Pattern may be incomplete.",
Self::token_to_display(expected)
)),
}
}
fn token_to_display(token: &Token) -> &'static str {
match token {
Token::LParen => "(",
Token::RParen => ")",
Token::LBracket => "[",
Token::RBracket => "]",
Token::LBrace => "{",
Token::RBrace => "}",
Token::Colon => ":",
Token::Comma => ",",
Token::Dash => "-",
Token::GreaterThan => ">",
Token::LessThan => "<",
Token::Star => "*",
Token::DotDot => "..",
Token::Dot => ".",
Token::Identifier(_) => "identifier",
Token::StringLit(_) => "string",
Token::IntLit(_) => "number",
Token::FloatLit(_) => "decimal",
Token::BoolLit(_) => "boolean",
Token::Parameter(_) => "parameter",
Token::Pipe => "|",
}
}
/// Parse a complete pattern: node (edge node)*
pub fn parse_pattern(&mut self) -> Result<Pattern, String> {
let mut elements = Vec::new();
// Must start with a node pattern
elements.push(PatternElement::Node(self.parse_node_pattern()?));
// Parse edge-node pairs
while self.peek().is_some() {
// Check for edge pattern (starts with - or <)
match self.peek() {
Some(Token::Dash) | Some(Token::LessThan) => {
elements.push(PatternElement::Edge(self.parse_edge_pattern()?));
elements.push(PatternElement::Node(self.parse_node_pattern()?));
}
_ => break,
}
}
Ok(Pattern { elements })
}
/// Consume a name in a label / relationship-type position, which may be
/// written literally or as a parameter reference (`$label`).
///
/// Returns the text to park in the string slot — the name itself, or the
/// `$name` placeholder — plus the parameter name when it *was* a
/// reference. The caller records that reference in the pattern's
/// `label_params` / `type_params`, which is what the resolver reads; see
/// [`ParamLabel`] for why the marker is out of band rather than a
/// spelling inside the string.
fn expect_label_name(&mut self, context: &str) -> Result<(String, Option<String>), String> {
match self.advance().cloned() {
Some(Token::Identifier(name)) => Ok((name, None)),
Some(Token::Parameter(param)) => Ok((ParamLabel::placeholder(¶m), Some(param))),
_ => Err(context.to_string()),
}
}
/// Parse node pattern: (var:Type {props})
fn parse_node_pattern(&mut self) -> Result<NodePattern, String> {
self.expect(&Token::LParen)?;
let mut variable = None;
let mut node_type = None;
let mut extra_labels: Vec<String> = Vec::new();
let mut properties = None;
let mut label_params: Vec<ParamLabel> = Vec::new();
const TYPE_ERR: &str =
"Expected node type name after ':'. Example: (:Person), (n:Person) or (n:$label)";
// Check what comes next
match self.peek() {
Some(Token::RParen) => {
// Empty node pattern: ()
}
Some(Token::Colon) => {
// No variable, just type: (:Type) or (:A:B:...)
self.advance(); // consume :
let (name, param) = self.expect_label_name(TYPE_ERR)?;
node_type = Some(name);
if let Some(param) = param {
label_params.push(ParamLabel { slot: 0, param });
}
}
Some(Token::Identifier(_)) => {
// Variable name
if let Some(Token::Identifier(name)) = self.advance().cloned() {
variable = Some(name);
}
// Check for type
if let Some(Token::Colon) = self.peek() {
self.advance(); // consume :
let (name, param) = self.expect_label_name(TYPE_ERR)?;
node_type = Some(name);
if let Some(param) = param {
label_params.push(ParamLabel { slot: 0, param });
}
}
}
Some(Token::LBrace) => {
// Properties only: ({prop: value})
}
_ => {}
}
// Multi-label suffix: `:A:B:C` collects any extras after the
// first label. The executor AND-intersects across all labels.
while let Some(Token::Colon) = self.peek() {
self.advance(); // consume :
let (name, param) = self.expect_label_name(
"Expected node label name after ':'. Example: (n:Person:Manager)",
)?;
extra_labels.push(name);
if let Some(param) = param {
label_params.push(ParamLabel {
slot: extra_labels.len(),
param,
});
}
}
// Check for properties
if let Some(Token::LBrace) = self.peek() {
properties = Some(self.parse_properties()?);
}
self.expect(&Token::RParen)?;
Ok(NodePattern {
variable,
node_type,
extra_labels,
properties,
label_params,
})
}
/// Parse edge pattern: -[:TYPE]-> or <-[:TYPE]- or -[:TYPE]-
/// Also supports variable-length: -[:TYPE*1..3]-> and the openCypher
/// abbreviated forms without a bracket part: `-->`, `<--`, `--`
/// (equivalent to -[]->, <-[]-, -[]-).
fn parse_edge_pattern(&mut self) -> Result<EdgePattern, String> {
let mut direction = EdgeDirection::Both;
let mut incoming_start = false;
// Check for incoming arrow start: <-
if let Some(Token::LessThan) = self.peek() {
self.advance(); // consume <
incoming_start = true;
direction = EdgeDirection::Incoming;
}
self.expect(&Token::Dash)?;
// Abbreviated edge (no bracket part): a second dash immediately
// follows — `-->` (Dash Dash GreaterThan), `--` (Dash Dash) or
// `<--` (LessThan Dash Dash, incoming_start already consumed).
if let Some(Token::Dash) = self.peek() {
self.advance(); // consume the second -
if let Some(Token::GreaterThan) = self.peek() {
self.advance(); // consume >
if incoming_start {
// <--> is invalid
return Err("Invalid edge pattern: cannot have both '<' and '>' arrows. Use --> for outgoing, <-- for incoming, or -- for both directions.".to_string());
}
direction = EdgeDirection::Outgoing;
}
return Ok(EdgePattern {
variable: None,
connection_type: None,
connection_types: None,
direction,
properties: None,
var_length: None,
needs_path_info: true,
skip_target_type_check: false,
edge_filter: None,
type_params: Vec::new(),
});
}
// Parse the bracket part: [:TYPE {props}]
self.expect(&Token::LBracket)?;
let mut variable = None;
let mut connection_type = None;
let mut connection_types: Option<Vec<String>> = None;
let mut properties = None;
let mut var_length = None;
let mut type_params: Vec<ParamLabel> = Vec::new();
const TYPE_ERR: &str = "Expected connection/edge type after ':'. \
Example: -[:KNOWS]->, -[e:WORKS_AT]-> or -[:$type]->";
// Check what comes next
match self.peek() {
Some(Token::RBracket) => {
// Empty edge pattern: []
}
Some(Token::Colon) => {
// No variable, just type: [:TYPE] or [:TYPE1|TYPE2]
self.advance(); // consume :
let (name, param) = self.expect_label_name(TYPE_ERR)?;
connection_type = Some(name);
if let Some(param) = param {
type_params.push(ParamLabel { slot: 0, param });
}
}
Some(Token::Identifier(_)) => {
// Variable name
if let Some(Token::Identifier(name)) = self.advance().cloned() {
variable = Some(name);
}
// Check for type
if let Some(Token::Colon) = self.peek() {
self.advance(); // consume :
let (name, param) = self.expect_label_name(TYPE_ERR)?;
connection_type = Some(name);
if let Some(param) = param {
type_params.push(ParamLabel { slot: 0, param });
}
}
}
Some(Token::Star) => {
// Variable-length without type: [*1..3]
}
Some(Token::LBrace) => {
// Properties only
}
_ => {}
}
// Handle pipe-separated types: [:A|B|C]
// After parsing the first type, consume any |TYPE continuations
if connection_type.is_some() {
if let Some(Token::Pipe) = self.peek() {
let mut types = vec![connection_type.clone().unwrap()];
while let Some(Token::Pipe) = self.peek() {
self.advance(); // consume |
let (name, param) = self.expect_label_name(
"Expected connection/edge type after '|'. Example: -[:KNOWS|LIKES]->",
)?;
types.push(name);
if let Some(param) = param {
type_params.push(ParamLabel {
slot: types.len() - 1,
param,
});
}
}
connection_types = Some(types);
}
}
// Check for variable-length marker: *
if let Some(Token::Star) = self.peek() {
var_length = Some(self.parse_var_length()?);
}
// Check for properties
if let Some(Token::LBrace) = self.peek() {
properties = Some(self.parse_properties()?);
}
self.expect(&Token::RBracket)?;
self.expect(&Token::Dash)?;
// Check for outgoing arrow end: ->
if let Some(Token::GreaterThan) = self.peek() {
self.advance(); // consume >
if incoming_start {
// <-[]-> is invalid
return Err("Invalid edge pattern: cannot have both '<' and '>' arrows. Use -[]-> for outgoing, <-[]- for incoming, or -[]- for both directions.".to_string());
}
direction = EdgeDirection::Outgoing;
} else if !incoming_start {
// -[]- without direction is bidirectional
direction = EdgeDirection::Both;
}
Ok(EdgePattern {
variable,
connection_type,
connection_types,
direction,
properties,
var_length,
needs_path_info: true,
skip_target_type_check: false,
edge_filter: None,
type_params,
})
}
/// Parse variable-length specification: *, *2, *1..3, *..5, *2..
/// Returns (min_hops, max_hops)
///
/// Open-ended forms (`*`, `*N..`) default the upper bound to
/// `DEFAULT_MAX_HOPS` as a runaway-query guard — a deliberate,
/// documented divergence from openCypher's unbounded `*` (recorded in
/// `tests/api-baselines/cypher-dialect.json` as
/// `pattern.var_length_default_cap`). An explicit lower bound above the
/// default (`*11..`) raises the ceiling to that bound so the range is
/// never silently empty.
fn parse_var_length(&mut self) -> Result<(usize, usize), String> {
self.expect(&Token::Star)?;
// The tokenizer folds a sign into the number it precedes, so `*-1`
// arrives here as `IntLit(-1)`. An `as usize` cast would turn that
// into a near-`usize::MAX` hop bound; reject it instead.
fn hop_count(n: i64) -> Result<usize, String> {
usize::try_from(n).map_err(|_| {
format!(
"Invalid hop count {} in variable-length path: hop counts must not be \
negative. Examples: *2, *1..3, *..5, *1..",
n
)
})
}
const DEFAULT_MAX_HOPS: usize = 10; // Reasonable limit to prevent runaway queries
// Check what follows the *
match self.peek() {
Some(Token::IntLit(_)) => {
// *N or *N..M or *N..
let min = if let Some(Token::IntLit(n)) = self.advance().cloned() {
hop_count(n)?
} else {
return Err("Expected integer after '*' for variable-length path. Examples: *2, *1..3, *..5, *1..".to_string());
};
// Check for range
if let Some(Token::DotDot) = self.peek() {
self.advance(); // consume ..
// Check for max
if let Some(Token::IntLit(_)) = self.peek() {
let max = if let Some(Token::IntLit(n)) = self.advance().cloned() {
hop_count(n)?
} else {
return Err("Expected max hop count after '..'. Examples: *1..3 (1 to 3 hops), *2.. (2 or more hops)".to_string());
};
if min > max {
return Err(format!(
"Invalid variable-length range *{}..{}: minimum hop count ({}) \
exceeds maximum ({}). Use *{}..{} instead.",
min, max, min, max, max, min
));
}
Ok((min, max))
} else {
// *N.. means "N or more", capped at the engine's
// default ceiling — but never an empty range: an
// explicit minimum above the default raises the cap.
Ok((min, min.max(DEFAULT_MAX_HOPS)))
}
} else {
// *N means exactly N hops
Ok((min, min))
}
}
Some(Token::DotDot) => {
// *..M means 1 to M
self.advance(); // consume ..
let max = if let Some(Token::IntLit(n)) = self.advance().cloned() {
hop_count(n)?
} else {
return Err(
"Expected max hop count after '*..'. Example: *..3 means up to 3 hops"
.to_string(),
);
};
Ok((1, max))
}
_ => {
// * alone means 1 or more (up to default max)
Ok((1, DEFAULT_MAX_HOPS))
}
}
}
/// Parse properties: {key: value, key2: value2}
fn parse_properties(&mut self) -> Result<HashMap<String, PropertyMatcher>, String> {
self.expect(&Token::LBrace)?;
let mut props = HashMap::new();
loop {
match self.peek() {
Some(Token::RBrace) => {
self.advance();
break;
}
Some(Token::Identifier(_)) => {
// Parse key: value
let key = if let Some(Token::Identifier(k)) = self.advance().cloned() {
k
} else {
return Err("Expected property key in properties block. Example: {name: 'Alice', age: 30}".to_string());
};
self.expect(&Token::Colon)?;
// Check if next token is a parameter reference
if let Some(Token::Parameter(_)) = self.peek() {
if let Some(Token::Parameter(name)) = self.advance().cloned() {
props.insert(key, PropertyMatcher::EqualsParam(name));
}
} else if let Some(Token::Identifier(_)) = self.peek() {
if let Some(Token::Identifier(name)) = self.advance().cloned() {
if let Some(Token::Dot) = self.peek() {
// `var.prop` → correlated node-property reference,
// e.g. WITH collect(x)[0] AS first
// MATCH (b {id: first.id})
self.advance(); // consume '.'
if let Some(Token::Identifier(prop)) = self.advance().cloned() {
props.insert(
key,
PropertyMatcher::EqualsNodeProp { var: name, prop },
);
} else {
return Err(
"Expected a property name after '.' in inline map value \
(e.g. {id: other.id})"
.to_string(),
);
}
} else {
// Bare identifier → variable reference from outer
// scope, e.g. WITH 'Oslo' AS city MATCH (n {city: city})
props.insert(key, PropertyMatcher::EqualsVar(name));
}
}
} else {
let value = self.parse_value()?;
props.insert(key, PropertyMatcher::Equals(value));
}
// Check for comma or end
if let Some(Token::Comma) = self.peek() {
self.advance();
}
}
_ => return Err("Expected property key or '}' to close properties block. Example: {name: 'Alice'}".to_string()),
}
}
Ok(props)
}
/// Parse a value (string, int, float, bool)
///
/// The tokenizer folds a sign that is adjacent to its digits into the
/// literal (`{x: -1}` → `IntLit(-1)`). A separated sign only reaches
/// here from the EXISTS-subquery pattern re-serializer, which joins
/// tokens with a space (`{x: - 1}`), so the `Dash` arm negates the
/// following literal. A literal that is *already* negative there means
/// a doubled sign (`--1`, `- -1`) and stays an error.
fn parse_value(&mut self) -> Result<Value, String> {
match self.advance().cloned() {
Some(Token::StringLit(s)) => Ok(Value::String(s)),
Some(Token::IntLit(i)) => Ok(Value::Int64(i)),
Some(Token::FloatLit(f)) => Ok(Value::Float64(f)),
Some(Token::BoolLit(b)) => Ok(Value::Boolean(b)),
Some(Token::Dash) => match self.advance().cloned() {
Some(Token::IntLit(i)) if i >= 0 => Ok(Value::Int64(-i)),
Some(Token::FloatLit(f)) if !f.is_sign_negative() => Ok(Value::Float64(-f)),
Some(token) => Err(format!(
"Expected a numeric literal after '-' in an inline map value \
(e.g. {{temp: -1}}), got {:?}",
token
)),
None => Err(
"Expected a numeric literal after '-' in an inline map value \
(e.g. {temp: -1}), got end of input"
.to_string(),
),
},
Some(token) => Err(format!("Expected value, got {:?}", token)),
None => Err("Expected value, got end of input".to_string()),
}
}
}
pub fn parse_pattern(input: &str) -> Result<Pattern, String> {
let tokens = tokenize(input)?;
let mut parser = Parser::new(tokens);
let pattern = parser.parse_pattern()?;
// The whole input must be one pattern. Pre-fix, trailing tokens were
// silently discarded, so `MATCH (n) bogus tokens` — including a typo'd
// keyword (`RETRUN n`) — executed as `MATCH (n)` with no error and a
// different meaning than the user wrote.
if let Some(tok) = parser.peek() {
return Err(format!(
"unexpected trailing input after pattern: {tok:?} (in {input:?})"
));
}
Ok(pattern)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tokenize_simple() {
let tokens = tokenize("(a:Person)").unwrap();
assert_eq!(
tokens,
vec![
Token::LParen,
Token::Identifier("a".to_string()),
Token::Colon,
Token::Identifier("Person".to_string()),
Token::RParen,
]
);
}
#[test]
fn quoting_predicate_agrees_with_the_tokenizer() {
// `bare_word_needs_quoting` tells the pattern re-serializer which
// names it may write bare. If it ever disagrees with this tokenizer,
// a name changes meaning in transit — the create-then-match asymmetry
// that made a backticked `TRUE` label unmatchable. Both directions
// are checked, so the predicate can neither under- nor over-claim.
for word in [
"true", "TRUE", "True", "false", "FALSE", "fAlSe", "null", "NULL", "Person", "order",
"contains", "x", "_x", "t1", "$label", "$", "$1",
] {
// A word the tokenizer *rejects* outright (a bare `$`) also fails
// to lex as itself, so the predicate must demand quoting for it.
let lexes_as_itself = matches!(
tokenize(word).as_deref(),
Ok([Token::Identifier(s)]) if s == word
);
assert_eq!(
bare_word_needs_quoting(word),
!lexes_as_itself,
"{word:?}: the quoting predicate and the tokenizer disagree"
);
// And the escape always works, whatever the verdict.
assert_eq!(
tokenize(&format!("`{word}`")).unwrap(),
vec![Token::Identifier(word.to_string())]
);
}
}
#[test]
fn test_tokenize_edge() {
let tokens = tokenize("-[:KNOWS]->").unwrap();
assert_eq!(
tokens,
vec![
Token::Dash,
Token::LBracket,
Token::Colon,
Token::Identifier("KNOWS".to_string()),
Token::RBracket,
Token::Dash,
Token::GreaterThan,
]
);
}
#[test]
fn test_tokenize_properties() {
let tokens = tokenize("{name: \"Alice\", age: 30}").unwrap();
assert_eq!(
tokens,
vec![
Token::LBrace,
Token::Identifier("name".to_string()),
Token::Colon,
Token::StringLit("Alice".to_string()),
Token::Comma,
Token::Identifier("age".to_string()),
Token::Colon,
Token::IntLit(30),
Token::RBrace,
]
);
}
#[test]
fn test_parse_simple_node() {
let pattern = parse_pattern("(p:Person)").unwrap();
assert_eq!(pattern.elements.len(), 1);
if let PatternElement::Node(np) = &pattern.elements[0] {
assert_eq!(np.variable, Some("p".to_string()));
assert_eq!(np.node_type, Some("Person".to_string()));
} else {
panic!("Expected node pattern");
}
}
#[test]
fn test_parse_multi_label_node() {
let pattern = parse_pattern("(a:Person:Director)").unwrap();
if let PatternElement::Node(np) = &pattern.elements[0] {
assert_eq!(np.node_type, Some("Person".to_string()));
assert_eq!(np.extra_labels, vec!["Director".to_string()]);
} else {
panic!("Expected node pattern");
}
}
#[test]
fn test_parse_three_labels() {
let pattern = parse_pattern("(n:Animal:Pet:Dog)").unwrap();
if let PatternElement::Node(np) = &pattern.elements[0] {
assert_eq!(np.node_type, Some("Animal".to_string()));
assert_eq!(np.extra_labels, vec!["Pet".to_string(), "Dog".to_string()]);
} else {
panic!("Expected node pattern");
}
}
#[test]
fn test_parse_single_label_has_empty_extras() {
let pattern = parse_pattern("(p:Person)").unwrap();
if let PatternElement::Node(np) = &pattern.elements[0] {
assert!(np.extra_labels.is_empty());
} else {
panic!("Expected node pattern");
}
}
#[test]
fn test_parse_node_with_properties() {
let pattern = parse_pattern("(p:Person {name: \"Alice\"})").unwrap();
if let PatternElement::Node(np) = &pattern.elements[0] {
assert!(np.properties.is_some());
let props = np.properties.as_ref().unwrap();
assert!(props.contains_key("name"));
} else {
panic!("Expected node pattern");
}
}
#[test]
fn test_parse_single_hop() {
let pattern = parse_pattern("(a:Person)-[:KNOWS]->(b:Person)").unwrap();
assert_eq!(pattern.elements.len(), 3);
if let PatternElement::Edge(ep) = &pattern.elements[1] {
assert_eq!(ep.connection_type, Some("KNOWS".to_string()));
assert_eq!(ep.direction, EdgeDirection::Outgoing);
} else {
panic!("Expected edge pattern");
}
}
#[test]
fn test_parse_incoming_edge() {
let pattern = parse_pattern("(a:Person)<-[:KNOWS]-(b:Person)").unwrap();
if let PatternElement::Edge(ep) = &pattern.elements[1] {
assert_eq!(ep.direction, EdgeDirection::Incoming);
} else {
panic!("Expected edge pattern");
}
}
#[test]
fn test_parse_bidirectional_edge() {
let pattern = parse_pattern("(a:Person)-[:KNOWS]-(b:Person)").unwrap();
if let PatternElement::Edge(ep) = &pattern.elements[1] {
assert_eq!(ep.direction, EdgeDirection::Both);
} else {
panic!("Expected edge pattern");
}
}
#[test]
fn test_parse_multi_hop() {
let pattern =
parse_pattern("(a:Person)-[:KNOWS]->(b:Person)-[:WORKS_AT]->(c:Company)").unwrap();
assert_eq!(pattern.elements.len(), 5);
}
#[test]
fn test_parse_anonymous_node() {
let pattern = parse_pattern("(:Person)").unwrap();
if let PatternElement::Node(np) = &pattern.elements[0] {
assert_eq!(np.variable, None);
assert_eq!(np.node_type, Some("Person".to_string()));
} else {
panic!("Expected node pattern");
}
}
#[test]
fn test_parse_empty_node() {
let pattern = parse_pattern("()").unwrap();
if let PatternElement::Node(np) = &pattern.elements[0] {
assert_eq!(np.variable, None);
assert_eq!(np.node_type, None);
} else {
panic!("Expected node pattern");
}
}
// Variable-length path tests
#[test]
fn test_tokenize_var_length() {
let tokens = tokenize("-[:KNOWS*1..3]->").unwrap();
assert!(tokens.contains(&Token::Star));
assert!(tokens.contains(&Token::DotDot));
assert!(tokens.contains(&Token::IntLit(1)));
assert!(tokens.contains(&Token::IntLit(3)));
}
#[test]
fn test_parse_var_length_exact() {
let pattern = parse_pattern("(a:Person)-[:KNOWS*2]->(b:Person)").unwrap();
if let PatternElement::Edge(ep) = &pattern.elements[1] {
assert_eq!(ep.var_length, Some((2, 2)));
} else {
panic!("Expected edge pattern");
}
}
#[test]
fn test_parse_var_length_range() {
let pattern = parse_pattern("(a:Person)-[:KNOWS*1..3]->(b:Person)").unwrap();
if let PatternElement::Edge(ep) = &pattern.elements[1] {
assert_eq!(ep.var_length, Some((1, 3)));
} else {
panic!("Expected edge pattern");
}
}
#[test]
fn test_parse_var_length_min_only() {
let pattern = parse_pattern("(a:Person)-[:KNOWS*2..]->(b:Person)").unwrap();
if let PatternElement::Edge(ep) = &pattern.elements[1] {
// *2.. means 2 to default max (10)
assert_eq!(ep.var_length, Some((2, 10)));
} else {
panic!("Expected edge pattern");
}
}
#[test]
fn test_parse_var_length_max_only() {
let pattern = parse_pattern("(a:Person)-[:KNOWS*..5]->(b:Person)").unwrap();
if let PatternElement::Edge(ep) = &pattern.elements[1] {
assert_eq!(ep.var_length, Some((1, 5)));
} else {
panic!("Expected edge pattern");
}
}
#[test]
fn test_parse_var_length_star_only() {
let pattern = parse_pattern("(a:Person)-[:KNOWS*]->(b:Person)").unwrap();
if let PatternElement::Edge(ep) = &pattern.elements[1] {
// * alone means 1 to default max (10)
assert_eq!(ep.var_length, Some((1, 10)));
} else {
panic!("Expected edge pattern");
}
}
#[test]
fn test_parse_normal_edge_no_var_length() {
let pattern = parse_pattern("(a:Person)-[:KNOWS]->(b:Person)").unwrap();
if let PatternElement::Edge(ep) = &pattern.elements[1] {
assert_eq!(ep.var_length, None);
} else {
panic!("Expected edge pattern");
}
}
// Abbreviated (bracketless) edge forms: -->, --, <--
fn abbreviated_edge(pattern_str: &str) -> EdgePattern {
let pattern = parse_pattern(pattern_str).unwrap();
assert_eq!(pattern.elements.len(), 3);
match &pattern.elements[1] {
PatternElement::Edge(ep) => ep.clone(),
_ => panic!("Expected edge pattern"),
}
}
#[test]
fn test_parse_abbreviated_outgoing() {
let ep = abbreviated_edge("(a)-->(b)");
assert_eq!(ep.direction, EdgeDirection::Outgoing);
assert_eq!(ep.connection_type, None);
assert_eq!(ep.variable, None);
assert_eq!(ep.var_length, None);
}
#[test]
fn test_parse_abbreviated_undirected() {
let ep = abbreviated_edge("(a)--(b)");
assert_eq!(ep.direction, EdgeDirection::Both);
assert_eq!(ep.connection_type, None);
}
#[test]
fn test_parse_abbreviated_incoming() {
let ep = abbreviated_edge("(a)<--(b)");
assert_eq!(ep.direction, EdgeDirection::Incoming);
assert_eq!(ep.connection_type, None);
}
#[test]
fn test_parse_abbreviated_multi_hop() {
let pattern = parse_pattern("(a)-->(b)--(c)<--(d)").unwrap();
assert_eq!(pattern.elements.len(), 7);
}
#[test]
fn test_parse_abbreviated_double_arrow_rejected() {
// <--> is invalid — both arrowheads.
assert!(parse_pattern("(a)<-->(b)").is_err());
}
#[test]
fn test_parse_single_dash_still_rejected() {
// `(a)-(b)` is not a pattern edge (a lone dash is subtraction in
// expression positions and invalid in patterns).
assert!(parse_pattern("(a)-(b)").is_err());
}
// Negative inline-map literals: `MATCH (n {x: -1})`.
fn node_props(pattern_str: &str) -> HashMap<String, PropertyMatcher> {
let pattern = parse_pattern(pattern_str).unwrap();
match &pattern.elements[0] {
PatternElement::Node(np) => np.properties.clone().expect("node properties"),
_ => panic!("Expected node pattern"),
}
}
fn edge_props(pattern_str: &str) -> HashMap<String, PropertyMatcher> {
let pattern = parse_pattern(pattern_str).unwrap();
match &pattern.elements[1] {
PatternElement::Edge(ep) => ep.properties.clone().expect("edge properties"),
_ => panic!("Expected edge pattern"),
}
}
fn equals(props: &HashMap<String, PropertyMatcher>, key: &str) -> Value {
match props.get(key) {
Some(PropertyMatcher::Equals(v)) => v.clone(),
other => panic!("Expected an Equals matcher for {}, got {:?}", key, other),
}
}
#[test]
fn test_parse_negative_int_in_node_map() {
let props = node_props("(n:Reading {temp: -1})");
assert_eq!(equals(&props, "temp"), Value::Int64(-1));
}
#[test]
fn test_parse_negative_float_in_node_map() {
let props = node_props("(n:Reading {delta: -1.5})");
assert_eq!(equals(&props, "delta"), Value::Float64(-1.5));
}
#[test]
fn test_parse_negative_literals_in_edge_map() {
let props = edge_props("(a:P)-[r:DELTA {temp: -1, change: -1.5}]->(b:P)");
assert_eq!(equals(&props, "temp"), Value::Int64(-1));
assert_eq!(equals(&props, "change"), Value::Float64(-1.5));
}
#[test]
fn test_tokenize_signed_int_is_one_literal() {
// The sign must be consumed as part of the literal. Lexing the
// magnitude first and negating afterwards cannot represent
// i64::MIN — 9223372036854775808 does not fit in an i64 — so this
// is the test that catches a parse-positive-then-negate fix.
let tokens = tokenize("{x: -9223372036854775808}").unwrap();
assert!(
tokens.contains(&Token::IntLit(i64::MIN)),
"expected a single IntLit(i64::MIN) token, got {:?}",
tokens
);
assert!(
!tokens.contains(&Token::Dash),
"sign left unconsumed: {:?}",
tokens
);
}
#[test]
fn test_parse_i64_min_in_node_map() {
let props = node_props("(n:Reading {temp: -9223372036854775808})");
assert_eq!(equals(&props, "temp"), Value::Int64(i64::MIN));
}
#[test]
fn test_parse_negative_literal_with_space_after_dash() {
// The EXISTS-subquery pattern re-serializer joins tokens with a
// space, so a negative literal reaches this parser as `- 1`.
let props = node_props("( n:Reading { temp : - 1 , delta : - 1.5 } )");
assert_eq!(equals(&props, "temp"), Value::Int64(-1));
assert_eq!(equals(&props, "delta"), Value::Float64(-1.5));
}
#[test]
fn test_parse_malformed_dash_values_still_rejected() {
for bad in [
"(n:Reading {temp: -})",
"(n:Reading {temp: --1})",
"(n:Reading {temp: - -1})",
"(n:Reading {temp: -'x'})",
] {
assert!(
parse_pattern(bad).is_err(),
"expected {} to stay a parse error",
bad
);
}
}
#[test]
fn test_negative_hop_counts_rejected() {
// The tokenizer folds the sign into the literal, so the hop-count
// parser must reject it rather than cast it to a huge usize.
for bad in [
"(a)-[:K*-1]->(b)",
"(a)-[:K*1..-3]->(b)",
"(a)-[:K*..-3]->(b)",
] {
let err = parse_pattern(bad).unwrap_err();
assert!(
err.contains("hop count"),
"expected a hop-count error for {}, got: {}",
bad,
err
);
}
}
#[test]
fn test_structural_dash_unaffected_by_negative_literals() {
// A relationship whose dashes are structural still parses, including
// when both endpoints and the edge carry negative inline literals.
let pattern =
parse_pattern("(a:P {temp: -1})-[r:DELTA {change: -1.5}]->(b:P {temp: -2})").unwrap();
assert_eq!(pattern.elements.len(), 3);
match &pattern.elements[1] {
PatternElement::Edge(ep) => {
assert_eq!(ep.direction, EdgeDirection::Outgoing);
assert_eq!(ep.connection_type, Some("DELTA".to_string()));
assert_eq!(ep.var_length, None);
}
_ => panic!("Expected edge pattern"),
}
// Bare and incoming forms keep their structural dashes.
assert_eq!(parse_pattern("(a)-->(b)").unwrap().elements.len(), 3);
assert_eq!(parse_pattern("(a)<-[:K]-(b)").unwrap().elements.len(), 3);
}
}