open-cypher 0.2.0-alpha.1

An unofficial Rust parser for the openCypher query language.
Documentation
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
//! A fully owned, syntax-oriented openCypher abstract syntax tree.
//!
//! The tree describes what was written; it does not perform name resolution,
//! type checking, query planning, or execution. Every syntactic node carries a
//! half-open UTF-8 byte [`Span`]. Trivia remains available from the lossless
//! token stream and is not attached to AST nodes.

use crate::span::Span;

/// A syntax value and its source extent.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Node<T> {
    /// The syntax represented by this node.
    pub kind: T,
    /// The full source extent, excluding surrounding trivia.
    pub span: Span,
}

impl<T> Node<T> {
    /// Creates a spanned syntax node.
    #[must_use]
    pub const fn new(kind: T, span: Span) -> Self {
        Self { kind, span }
    }

    /// Converts the contained value while preserving its span.
    #[must_use]
    pub fn map<U>(self, map: impl FnOnce(T) -> U) -> Node<U> {
        Node::new(map(self.kind), self.span)
    }

    /// Borrows the contained value while preserving its span.
    #[must_use]
    pub const fn as_ref(&self) -> Node<&T> {
        Node::new(&self.kind, self.span)
    }
}

/// A complete source input containing zero or one query statement.
///
/// The parser accepts an optional trailing semicolon. The statement vector is
/// empty for empty or trivia-only input and otherwise contains one statement.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Program {
    /// Statements in source order.
    pub statements: Vec<Statement>,
    /// The complete non-trivia source extent.
    pub span: Span,
}

impl Program {
    /// Creates a program.
    #[must_use]
    pub const fn new(statements: Vec<Statement>, span: Span) -> Self {
        Self { statements, span }
    }

    /// Returns `true` when the input contains no statements.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.statements.is_empty()
    }
}

/// A top-level statement.
pub type Statement = Node<StatementKind>;

/// The syntactic form of a top-level statement.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum StatementKind {
    /// A regular query, optionally prefixed by an execution mode.
    Query(QueryStatement),
    /// A placeholder emitted by recovery.
    Error(ErrorNode),
}

/// A query statement and its optional execution prefix.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryStatement {
    /// `EXPLAIN` or `PROFILE`, when present.
    pub mode: Option<Node<ExecutionMode>>,
    /// The query body.
    pub query: Query,
    /// A trailing semicolon, when one was written.
    pub terminator: Option<Span>,
}

/// A query execution prefix.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ExecutionMode {
    Explain,
    Profile,
}

/// A regular query.
pub type Query = Node<QueryKind>;

/// The syntactic form of a query.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum QueryKind {
    /// One single query followed by zero or more `UNION` branches.
    Regular(RegularQuery),
    /// A placeholder emitted by recovery.
    Error(ErrorNode),
}

/// A query connected by zero or more set unions.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RegularQuery {
    /// The first single query.
    pub head: SingleQuery,
    /// Subsequent union branches.
    pub unions: Vec<UnionBranch>,
}

/// A `UNION` operator and the query to its right.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UnionBranch {
    /// Union duplicate policy.
    pub operator: Node<UnionOperator>,
    /// Query on the right-hand side.
    pub query: SingleQuery,
}

/// Duplicate handling for a query union.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum UnionOperator {
    /// Bare `UNION`, whose duplicate behavior is the openCypher default.
    Default,
    /// `UNION ALL`.
    All,
    /// `UNION DISTINCT`.
    Distinct,
}

/// Duplicate handling explicitly written for a projection or function call.
///
/// The absence of this node represents the grammar's default behavior. Keeping
/// `ALL` distinct from absence preserves the source-level syntax for tools that
/// inspect or rewrite queries.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SetQuantifier {
    All,
    Distinct,
}

/// A sequence of query clauses evaluated from left to right.
pub type SingleQuery = Node<SingleQueryKind>;

/// The contents of a single query.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SingleQueryKind {
    /// Clauses in source order.
    pub clauses: Vec<Clause>,
}

/// A query clause.
pub type Clause = Node<ClauseKind>;

/// Any clause in an openCypher query.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ClauseKind {
    Use(UseClause),
    Match(MatchClause),
    Unwind(UnwindClause),
    Let(LetClause),
    Create(CreateClause),
    Insert(InsertClause),
    Merge(MergeClause),
    Delete(DeleteClause),
    Set(SetClause),
    Remove(RemoveClause),
    Foreach(ForeachClause),
    LoadCsv(LoadCsvClause),
    Call(CallClause),
    With(WithClause),
    Return(ReturnClause),
    Select(ProjectionClause),
    Next(ProjectionClause),
    Filter(FilterClause),
    Finish,
    /// A placeholder emitted after synchronizing at a clause boundary.
    Error(ErrorNode),
}

/// Selects the graph against which the following query runs.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UseClause {
    pub graph: Expr,
}

/// A `MATCH` clause.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MatchClause {
    pub optional: bool,
    pub mode: Option<Node<PathMode>>,
    pub pattern: Pattern,
    pub hints: Vec<MatchHint>,
    pub where_clause: Option<Expr>,
}

/// A planner hint attached to `MATCH`.
pub type MatchHint = Node<MatchHintKind>;

/// The form of a planner hint.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum MatchHintKind {
    Index {
        variable: Name,
        label: Name,
        properties: Vec<Name>,
        seek: bool,
    },
    Scan {
        variable: Name,
        label: Name,
    },
    Join {
        variables: Vec<Name>,
    },
}

/// Expands a list expression into rows.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UnwindClause {
    pub expression: Expr,
    pub variable: Name,
}

/// Introduces one or more variable bindings.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LetClause {
    pub bindings: Vec<Binding>,
}

/// An expression bound to a variable.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Binding {
    pub variable: Name,
    pub expression: Expr,
    pub span: Span,
}

/// Creates graph elements described by a pattern.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CreateClause {
    pub pattern: Pattern,
}

/// Inserts graph elements using GQL-aligned pattern syntax.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct InsertClause {
    pub pattern: Pattern,
}

/// Matches or creates a single pattern and applies conditional updates.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MergeClause {
    pub pattern: PatternPart,
    pub actions: Vec<MergeAction>,
}

/// An `ON MATCH` or `ON CREATE` action.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MergeAction {
    pub trigger: Node<MergeTrigger>,
    pub set: SetClause,
    pub span: Span,
}

/// The event that triggers a merge action.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum MergeTrigger {
    Match,
    Create,
}

/// Deletes values or graph elements.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DeleteClause {
    pub mode: Node<DeleteMode>,
    pub expressions: Vec<Expr>,
}

/// Relationship handling for a delete operation.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DeleteMode {
    Normal,
    Detach,
    Nodetach,
}

/// A collection of assignments following `SET`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SetClause {
    pub items: Vec<SetItem>,
}

/// A single `SET` assignment.
pub type SetItem = Node<SetItemKind>;

/// The form of an assignment.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SetItemKind {
    Property {
        target: Expr,
        value: Expr,
    },
    ReplaceProperties {
        target: Name,
        value: Expr,
    },
    MergeProperties {
        target: Name,
        value: Expr,
    },
    Labels {
        target: Name,
        labels: LabelExpression,
    },
}

/// A collection of removals following `REMOVE`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RemoveClause {
    pub items: Vec<RemoveItem>,
}

/// A single `REMOVE` operation.
pub type RemoveItem = Node<RemoveItemKind>;

/// The form of a removal.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum RemoveItemKind {
    Property(Expr),
    Labels {
        target: Name,
        labels: LabelExpression,
    },
}

/// Applies updating clauses for each item in a list.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ForeachClause {
    pub variable: Name,
    pub list: Expr,
    pub clauses: Vec<Clause>,
}

/// Loads delimited records from a URL expression.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LoadCsvClause {
    pub with_headers: bool,
    pub source: Expr,
    pub variable: Name,
    pub field_terminator: Option<Node<StringLiteral>>,
}

/// Invokes a procedure or a subquery.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CallClause {
    pub optional: bool,
    pub target: CallTarget,
    pub yield_clause: Option<YieldClause>,
}

/// The target of a `CALL` clause.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CallTarget {
    Procedure {
        name: QualifiedName,
        arguments: Option<Vec<Expr>>,
    },
    Subquery {
        scope: Option<SubqueryScope>,
        query: Box<Query>,
        in_transactions: Option<Box<InTransactions>>,
    },
}

/// Variables imported into a `CALL { ... }` subquery.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SubqueryScope {
    pub import_all: bool,
    pub variables: Vec<Name>,
    pub span: Span,
}

/// Batched transaction behavior for a subquery call.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct InTransactions {
    pub rows: Option<Expr>,
    pub on_error: Option<Node<TransactionErrorBehavior>>,
    pub report_status_as: Option<Name>,
    pub span: Span,
}

/// Error handling for `CALL { ... } IN TRANSACTIONS`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TransactionErrorBehavior {
    Continue,
    Break,
    Fail,
}

/// Selects values produced by a procedure call.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct YieldClause {
    pub all: bool,
    pub items: Vec<ProjectionItem>,
    pub where_clause: Option<Expr>,
    pub span: Span,
}

/// Projects intermediate values and continues a query.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct WithClause {
    pub projection: ProjectionClause,
    pub where_clause: Option<Expr>,
}

/// Produces the final rows from a query.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ReturnClause {
    pub projection: ProjectionClause,
}

/// A projection body shared by `RETURN`, `WITH`, and GQL-aligned `SELECT`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ProjectionClause {
    /// An explicitly written `ALL` or `DISTINCT` modifier.
    pub quantifier: Option<Node<SetQuantifier>>,
    pub items: Vec<ProjectionItem>,
    pub order_by: Option<OrderBy>,
    pub offset: Option<Expr>,
    pub skip: Option<Expr>,
    pub limit: Option<Expr>,
    pub span: Span,
}

/// One expression or wildcard in a projection.
pub type ProjectionItem = Node<ProjectionItemKind>;

/// The form of a projection item.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ProjectionItemKind {
    Wildcard,
    Expression {
        expression: Expr,
        alias: Option<Name>,
    },
}

/// Sort specifications following `ORDER BY`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OrderBy {
    pub items: Vec<SortItem>,
    pub span: Span,
}

/// One expression and its requested ordering.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SortItem {
    pub expression: Expr,
    pub direction: Option<Node<SortDirection>>,
    pub nulls: Option<Node<NullOrder>>,
    pub span: Span,
}

/// Sort direction.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SortDirection {
    Ascending,
    Descending,
}

/// Placement of null values in sorted output.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum NullOrder {
    First,
    Last,
}

/// Keeps rows satisfying an expression.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FilterClause {
    pub predicate: Expr,
}

/// A graph pattern.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Pattern {
    pub parts: Vec<PatternPart>,
    pub span: Span,
}

/// A selected path pattern and optional path-variable binding.
pub type PatternPart = Node<PatternPartKind>;

/// The contents of a pattern part.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PatternPartKind {
    pub binding: Option<Name>,
    pub selector: Option<Node<PathSelector>>,
    pub path: PathPattern,
}

/// A path pattern composed from node, relationship, and grouped factors.
pub type PathPattern = Node<PathPatternKind>;

/// Ordered factors in a path pattern.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PathPatternKind {
    pub factors: Vec<PathFactor>,
}

/// One factor in a path pattern.
pub type PathFactor = Node<PathFactorKind>;

/// The form of a path factor.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PathFactorKind {
    Node(NodePattern),
    /// A node pattern followed by a graph-pattern quantifier.
    QuantifiedNode {
        pattern: NodePattern,
        quantifier: Quantifier,
    },
    Relationship(RelationshipPattern),
    Parenthesized {
        pattern: Box<PathPattern>,
        where_clause: Option<Box<Expr>>,
        quantifier: Option<Quantifier>,
    },
    /// A parenthesized path factor with a subpath-variable binding.
    Subpath {
        binding: Name,
        pattern: Box<PathPattern>,
        where_clause: Option<Box<Expr>>,
        quantifier: Option<Quantifier>,
    },
    /// A legacy `shortestPath(...)` or `allShortestPaths(...)` path factor.
    LegacyShortest {
        all: bool,
        pattern: Box<PathPattern>,
    },
    Error(ErrorNode),
}

/// A node pattern `(variable:Label {properties})`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NodePattern {
    pub variable: Option<Name>,
    pub labels: Option<LabelExpression>,
    pub properties: Option<Box<Expr>>,
    pub where_clause: Option<Box<Expr>>,
}

/// A relationship pattern between two nodes.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RelationshipPattern {
    pub direction: Node<RelationshipDirection>,
    pub variable: Option<Name>,
    pub labels: Option<LabelExpression>,
    /// A legacy variable-length relationship quantifier written inside `[]`.
    pub legacy_quantifier: Option<Quantifier>,
    /// A graph-pattern quantifier written after the relationship pattern.
    pub graph_quantifier: Option<Quantifier>,
    pub properties: Option<Box<Expr>>,
    pub where_clause: Option<Box<Expr>>,
}

/// Direction indicated by a relationship pattern's arrows.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum RelationshipDirection {
    Left,
    Right,
    Undirected,
    Both,
}

/// Repetition applied to a node, relationship, or parenthesized path.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Quantifier {
    pub kind: QuantifierKind,
    pub span: Span,
}

/// A path repetition form. Bounds retain their original decimal spelling.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum QuantifierKind {
    ZeroOrMore,
    OneOrMore,
    Optional,
    Fixed(String),
    Range {
        lower: Option<String>,
        upper: Option<String>,
    },
}

/// Restrictions on repeated elements in a path.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PathMode {
    Walk,
    Trail,
    Simple,
    Acyclic,
}

/// Selection applied to matching paths.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PathSelector {
    All,
    Any { count: Option<String> },
    AnyShortest,
    AllShortest,
    Shortest { count: Option<String>, groups: bool },
}

/// A label/type boolean expression.
pub type LabelExpression = Node<LabelExpressionKind>;

/// The form of a label/type boolean expression.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LabelExpressionKind {
    Name(Name),
    Wildcard,
    Not(Box<LabelExpression>),
    And(Vec<LabelExpression>),
    Or(Vec<LabelExpression>),
    Parenthesized(Box<LabelExpression>),
    Error(ErrorNode),
}

/// An expression.
pub type Expr = Node<ExprKind>;

/// Any expression in openCypher 2024.3.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ExprKind {
    Literal(Literal),
    Variable(Name),
    Parameter(Parameter),
    Wildcard,
    List(Vec<Expr>),
    Map(Vec<MapEntry>),
    MapProjection(MapProjection),
    Unary {
        operator: Node<UnaryOperator>,
        operand: Box<Expr>,
    },
    Binary {
        left: Box<Expr>,
        operator: Node<BinaryOperator>,
        right: Box<Expr>,
    },
    Is {
        expression: Box<Expr>,
        negated: bool,
        predicate: IsPredicate,
    },
    Property {
        expression: Box<Expr>,
        key: Name,
    },
    DynamicProperty {
        expression: Box<Expr>,
        key: Box<Expr>,
    },
    Index {
        expression: Box<Expr>,
        index: Box<Expr>,
    },
    Slice {
        expression: Box<Expr>,
        lower: Option<Box<Expr>>,
        upper: Option<Box<Expr>>,
    },
    Function(FunctionInvocation),
    Case(CaseExpression),
    ListComprehension(ListComprehension),
    PatternComprehension(PatternComprehension),
    Reduce(ReduceExpression),
    QuantifiedPredicate(QuantifiedPredicate),
    Subquery(SubqueryExpression),
    Pattern(Pattern),
    Parenthesized(Box<Expr>),
    Error(ErrorNode),
}

/// A prefix operator.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum UnaryOperator {
    Plus,
    Minus,
    Not,
}

/// An infix operator, ordered by the grammar's precedence rules.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BinaryOperator {
    Or,
    Xor,
    And,
    Equal,
    NotEqual,
    Less,
    LessEqual,
    Greater,
    GreaterEqual,
    RegexMatch,
    In,
    StartsWith,
    EndsWith,
    Contains,
    Add,
    Subtract,
    Multiply,
    Divide,
    Remainder,
    Power,
    Concat,
}

/// A predicate following `IS` or `IS NOT`.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum IsPredicate {
    Null,
    Typed(TypeRef),
    Normalized(Option<Node<NormalizationForm>>),
    Label(LabelExpression),
}

/// Unicode normalization requested by an expression predicate.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum NormalizationForm {
    Nfc,
    Nfd,
    Nfkc,
    Nfkd,
}

/// A function call.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FunctionInvocation {
    pub name: QualifiedName,
    /// An explicitly written `ALL` or `DISTINCT` modifier.
    pub quantifier: Option<Node<SetQuantifier>>,
    pub arguments: Vec<Expr>,
}

/// A searched or simple `CASE` expression.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CaseExpression {
    pub operand: Option<Box<Expr>>,
    pub alternatives: Vec<CaseAlternative>,
    pub else_expression: Option<Box<Expr>>,
}

/// One `WHEN ... THEN ...` arm.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CaseAlternative {
    /// One or more operands following `WHEN`.
    pub when: Vec<Expr>,
    pub then: Expr,
    pub span: Span,
}

/// A list comprehension.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ListComprehension {
    pub variable: Name,
    pub list: Box<Expr>,
    pub predicate: Option<Box<Expr>>,
    pub projection: Option<Box<Expr>>,
}

/// A pattern comprehension.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PatternComprehension {
    pub binding: Option<Name>,
    pub pattern: Pattern,
    pub predicate: Option<Box<Expr>>,
    pub projection: Box<Expr>,
}

/// A left fold over a list.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ReduceExpression {
    pub accumulator: Name,
    pub initial: Box<Expr>,
    pub variable: Name,
    pub list: Box<Expr>,
    pub expression: Box<Expr>,
}

/// An `ALL`, `ANY`, `NONE`, or `SINGLE` predicate over a list.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QuantifiedPredicate {
    pub kind: Node<QuantifiedPredicateKind>,
    pub variable: Name,
    pub list: Box<Expr>,
    pub predicate: Box<Expr>,
}

/// Quantification applied to a list predicate.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum QuantifiedPredicateKind {
    All,
    Any,
    None,
    Single,
}

/// A query nested inside an expression.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SubqueryExpression {
    pub kind: Node<SubqueryExpressionKind>,
    pub query: Box<Query>,
}

/// The value produced by a subquery expression.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SubqueryExpressionKind {
    Exists,
    Count,
    Collect,
}

/// A map entry.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MapEntry {
    pub key: Name,
    pub value: Expr,
    pub span: Span,
}

/// A projection derived from an existing map or graph element.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MapProjection {
    pub base: Box<Expr>,
    pub items: Vec<MapProjectionItem>,
}

/// One item in a map projection.
pub type MapProjectionItem = Node<MapProjectionItemKind>;

/// The form of a map projection item.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum MapProjectionItemKind {
    Property(Name),
    AllProperties,
    Variable(Name),
    Entry(MapEntry),
}

/// A literal expression.
pub type Literal = Node<LiteralKind>;

/// A literal value as represented in source.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LiteralKind {
    Null,
    Boolean(bool),
    Integer(IntegerLiteral),
    Float(FloatLiteral),
    String(StringLiteral),
}

/// An integer spelling and its radix.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IntegerLiteral {
    /// Digits exactly as written, including any radix prefix.
    pub text: String,
    pub radix: IntegerRadix,
}

/// The radix of an integer literal.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum IntegerRadix {
    Decimal,
    Hexadecimal,
    Octal,
}

/// A floating-point spelling preserved without rounding.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FloatLiteral {
    pub text: String,
}

/// A decoded string value and its delimiter style.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StringLiteral {
    pub value: String,
    pub quote: QuoteStyle,
}

/// Quote style used for a string literal.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum QuoteStyle {
    Single,
    Double,
}

/// A parameter reference without its leading `$`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Parameter {
    pub name: ParameterName,
}

/// The form of a parameter name.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ParameterName {
    Named(String),
    Positional(String),
}

/// An identifier and whether it was backtick escaped.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Identifier {
    /// Decoded, case-preserving identifier text.
    pub text: String,
    /// Whether the source used backtick delimiters.
    pub escaped: bool,
}

impl Identifier {
    /// Creates an identifier.
    #[must_use]
    pub fn new(text: impl Into<String>, escaped: bool) -> Self {
        Self {
            text: text.into(),
            escaped,
        }
    }
}

/// A spanned identifier.
pub type Name = Node<Identifier>;

/// A dot-separated name such as a procedure or function name.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QualifiedName {
    pub parts: Vec<Name>,
    pub span: Span,
}

/// A value type used by typed predicates.
pub type TypeRef = Node<TypeRefKind>;

/// A type expression and its nullability marker.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TypeRefKind {
    pub value: ValueType,
    pub nullable: Option<bool>,
}

/// A value type named by the grammar.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ValueType {
    Nothing,
    Null,
    Boolean,
    String,
    Integer,
    Float,
    Decimal,
    Number,
    Date,
    LocalTime,
    ZonedTime,
    LocalDateTime,
    ZonedDateTime,
    Duration,
    Point,
    Node,
    Relationship,
    Map,
    Path,
    List(Box<TypeRef>),
    Any,
    Named(QualifiedName),
}

/// A marker inserted where error recovery skipped malformed syntax.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ErrorNode;