open-cypher 0.5.0

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
//! Contract tests for token-context preprocessing and diagnostic
//! normalization in `src/parser.rs`.
//!
//! These tests pin exact observable behavior of the token-level heuristics
//! (`is_label_predicate_context`, `is_inside_braces`, `is_in_map_entry_value`,
//! `find_top_level_token`), the union splitter (`parse_regular_query`), the
//! contextual keyword retry loop (`parse_tokens_with_contextual_names`), and
//! diagnostic ordering/dedup/truncation (`normalize_diagnostics`). Each test
//! documents the misclassification it guards against.

use open_cypher::ast::{
    ClauseKind, Expr, ExprKind, IsPredicate, ProjectionItemKind, QueryKind, RegularQuery,
    StatementKind, UnionOperator,
};
use open_cypher::{DiagnosticCode, ParsedProgram, parse, parse_recovering};

fn parse_ok(source: &str) -> ParsedProgram {
    match parse(source) {
        Ok(parsed) => parsed,
        Err(errors) => panic!(
            "expected {source:?} to parse, got:\n{}",
            errors.render(source)
        ),
    }
}

fn regular_query(parsed: &ParsedProgram) -> &RegularQuery {
    let StatementKind::Query(statement) = &parsed.program.statements[0].kind else {
        panic!("expected a query statement")
    };
    let QueryKind::Regular(query) = &statement.query.kind else {
        panic!("expected a regular query")
    };
    query
}

fn match_where_clause(parsed: &ParsedProgram) -> &Expr {
    let query = regular_query(parsed);
    let ClauseKind::Match(match_clause) = &query.head.kind.clauses[0].kind else {
        panic!("expected a MATCH clause")
    };
    match_clause.where_clause.as_ref().expect("WHERE clause")
}

fn return_item_expression(parsed: &ParsedProgram, item: usize) -> &Expr {
    let query = regular_query(parsed);
    let ClauseKind::Return(return_clause) = &query.head.kind.clauses.last().unwrap().kind else {
        panic!("expected a final RETURN clause")
    };
    let ProjectionItemKind::Expression { expression, .. } =
        &return_clause.projection.items[item].kind
    else {
        panic!("expected an expression item")
    };
    expression
}

fn assert_is_label_predicate(expression: &Expr, source: &str, text: &str) {
    let ExprKind::Is {
        negated, predicate, ..
    } = &expression.kind
    else {
        panic!("expected an IS/label predicate expression, got {expression:#?}")
    };
    assert!(!negated);
    assert!(
        matches!(predicate, IsPredicate::Label(_)),
        "expected a label predicate, got {predicate:#?}"
    );
    assert_eq!(expression.span.text(source), Some(text));
}

// --- is_label_predicate_context ---------------------------------------------

/// A plain `n:Person` in WHERE must become one label-predicate expression.
/// Guards the `IS AS <name>` exclusion in `is_label_predicate_context`: the
/// token two past the colon (`RETURN`, a symbolic name kind) must not veto
/// the classification on its own.
#[test]
fn where_label_predicate_is_an_is_label_expression() {
    let source = "MATCH (n) WHERE n:Person RETURN n";
    let parsed = parse_ok(source);
    assert_is_label_predicate(match_where_clause(&parsed), source, "n:Person");
}

/// `IS Person` in WHERE is a label predicate too (the `IS AS name` carve-out
/// must not trigger when the token after IS is not AS).
#[test]
fn where_is_keyword_label_predicate_parses() {
    let source = "MATCH (n) WHERE n IS Person RETURN n";
    let parsed = parse_ok(source);
    assert_is_label_predicate(match_where_clause(&parsed), source, "n IS Person");
}

/// A label predicate inside an EXISTS subquery's inner WHERE sits inside
/// braces; being inside braces alone must not disable the classification
/// (only `..., name :` map-key shapes inside braces may).
#[test]
fn label_predicate_inside_exists_subquery_where() {
    let source = "MATCH (m) WHERE EXISTS { MATCH (n) WHERE n:Person } RETURN m";
    let parsed = parse_ok(source);
    let rendered = format!("{:?}", parsed.program);
    assert!(
        rendered.contains("Label("),
        "expected an IsPredicate::Label in {rendered}"
    );
}

/// The `|` of a list comprehension marks expression context even when the
/// nearest clause keyword (SET) would otherwise say "pattern context".
#[test]
fn label_predicate_after_comprehension_pipe_in_set_context() {
    let source = "MATCH (a) SET a.p = [x IN [1] | x:Person] RETURN a";
    let parsed = parse_ok(source);
    let rendered = format!("{:?}", parsed.program);
    assert!(
        rendered.contains("Label("),
        "expected an IsPredicate::Label in {rendered}"
    );
}

/// The backward scan must step over a completed `[...]` (decrementing its
/// bracket counter on the matching `[`) and still find the WHERE keyword.
#[test]
fn label_predicate_after_completed_list_literal() {
    let source = "MATCH (n) WHERE n.p IN [1, 2] AND n:Person RETURN n";
    let parsed = parse_ok(source);
    let where_clause = match_where_clause(&parsed);
    let ExprKind::Binary { right, .. } = &where_clause.kind else {
        panic!("expected AND expression, got {where_clause:#?}")
    };
    assert_is_label_predicate(right, source, "n:Person");
}

/// The backward scan must step over a completed `{...}` in expression
/// position (map literal before AND) and still find the WHERE keyword.
#[test]
fn label_predicate_after_completed_map_literal() {
    let source = "MATCH (n) WHERE {a: 1} = n.p AND n:Person RETURN n";
    let parsed = parse_ok(source);
    let where_clause = match_where_clause(&parsed);
    let ExprKind::Binary { right, .. } = &where_clause.kind else {
        panic!("expected AND expression, got {where_clause:#?}")
    };
    assert_is_label_predicate(right, source, "n:Person");
}

/// A property map containing CASE (whose WHEN/THEN/ELSE are
/// expression-context markers) is skipped as a completed braced construct:
/// the later `(m:Person)` colon must stay a plain node label.
#[test]
fn case_inside_property_map_does_not_leak_expression_context() {
    let source = "MATCH (n {p: CASE WHEN true THEN 1 ELSE 2 END}), (m:Person) RETURN m";
    let parsed = parse_ok(source);
    let rendered = format!("{:?}", parsed.program);
    assert!(
        !rendered.contains("Label("),
        "node label must not become an IsPredicate::Label in {rendered}"
    );
}

/// The scan stops at the nearest MATCH: an earlier WITH/expression context
/// must not reclassify a node-pattern colon in a later MATCH.
#[test]
fn later_match_pattern_colon_stays_a_node_label() {
    let source = "MATCH (a) WITH a MATCH (b:Person) RETURN b";
    let parsed = parse_ok(source);
    let rendered = format!("{:?}", parsed.program);
    assert!(
        !rendered.contains("Label("),
        "node label must not become an IsPredicate::Label in {rendered}"
    );
}

/// A contextual variable named `match` followed by `=` is skipped by the
/// backward scan (lookahead-equals exemption), so the WHERE keyword still
/// wins and `n:Person` stays a label predicate.
#[test]
fn keyword_variable_before_equals_is_skipped_by_the_scan() {
    let source = "WITH 1 AS match WHERE match = 1 AND n:Person RETURN n";
    let parsed = parse_ok(source);
    let rendered = format!("{:?}", parsed.program);
    assert!(
        rendered.contains("Label("),
        "expected an IsPredicate::Label in {rendered}"
    );
}

// --- is_inside_braces --------------------------------------------------------

/// `RETURN n, m:Person` has the `, name :` shape but is not inside braces,
/// so the projection item is a label predicate.
#[test]
fn comma_projection_label_predicate_outside_braces() {
    let source = "MATCH (n), (m) RETURN n, m:Person";
    let parsed = parse_ok(source);
    assert_is_label_predicate(return_item_expression(&parsed, 1), source, "m:Person");
}

/// A completed map literal before the comma must not count as "inside
/// braces": `{a: 1}, m:Person` keeps the label predicate.
#[test]
fn completed_map_before_comma_label_predicate() {
    let source = "MATCH (m) RETURN {a: 1}, m:Person";
    let parsed = parse_ok(source);
    assert_is_label_predicate(return_item_expression(&parsed, 1), source, "m:Person");
}

/// Inside a map with a nested map value, the second key's colon is a map
/// key colon, not a label predicate (`is_inside_braces` must unwind the
/// nested `{...}` pair and still report "inside the outer braces").
#[test]
fn nested_map_second_key_stays_a_map_key() {
    let source = "MATCH (d) RETURN {a: {b: 1}, c: d}";
    let parsed = parse_ok(source);
    let expression = return_item_expression(&parsed, 0);
    assert_eq!(expression.span.text(source), Some("{a: {b: 1}, c: d}"));
    let ExprKind::Map(entries) = &expression.kind else {
        panic!("expected a map literal, got {expression:#?}")
    };
    assert_eq!(entries.len(), 2);
    assert_eq!(entries[1].key.kind.text, "c");
    assert_eq!(entries[1].value.span.text(source), Some("d"));
}

// --- is_in_map_entry_value ---------------------------------------------------

/// A closed property map in an earlier MATCH must be popped from the open
/// brace stack: the later `(m:Person)` is a plain node label, not a
/// map-entry-value label predicate.
#[test]
fn closed_property_map_does_not_capture_later_node_label() {
    let source = "MATCH (n {a: 1}) MATCH (m:Person) RETURN m";
    let parsed = parse_ok(source);
    let rendered = format!("{:?}", parsed.program);
    assert!(
        !rendered.contains("Label("),
        "node label must not become an IsPredicate::Label in {rendered}"
    );
}

/// Inside a map entry value, a comma nested in brackets must not reset the
/// after-separator state: `m:Person` deep in a property-map value is still
/// a label predicate.
#[test]
fn bracketed_comma_inside_map_value_keeps_entry_value_context() {
    let source = "MATCH (m), (n {flag: [1, 2] = $x AND m:Person}) RETURN n";
    let parsed = parse_ok(source);
    let rendered = format!("{:?}", parsed.program);
    assert!(
        rendered.contains("Label("),
        "expected an IsPredicate::Label in {rendered}"
    );
}

/// A map key colon after a completed list value stays a map key: the
/// closing `]` must decrement the nesting depth so the top-level comma
/// resets the entry-value state.
#[test]
fn map_key_after_completed_list_value_stays_a_map_key() {
    let source = "MATCH (c) RETURN {a: [1], b: c}";
    let parsed = parse_ok(source);
    let expression = return_item_expression(&parsed, 0);
    let ExprKind::Map(entries) = &expression.kind else {
        panic!("expected a map literal, got {expression:#?}")
    };
    assert_eq!(entries.len(), 2);
    assert_eq!(entries[1].key.kind.text, "b");
    assert_eq!(entries[1].value.span.text(source), Some("c"));
}

/// A top-level comma resets the entry-value state: the second key's colon
/// in `{a: 1, b: c}` is a map key colon, not a label predicate on `b`.
#[test]
fn map_key_after_top_level_comma_stays_a_map_key() {
    let source = "MATCH (c) RETURN {a: 1, b: c}";
    let parsed = parse_ok(source);
    let expression = return_item_expression(&parsed, 0);
    let ExprKind::Map(entries) = &expression.kind else {
        panic!("expected a map literal, got {expression:#?}")
    };
    assert_eq!(entries.len(), 2);
    assert_eq!(entries[1].key.kind.text, "b");
    assert_eq!(entries[1].value.span.text(source), Some("c"));
}

/// A colon nested inside a property map (`{p: 1}`) inside an EXISTS body
/// must not put the subquery in entry-value state: the later `(b:Person)`
/// colon is a plain node label.
#[test]
fn nested_property_map_colon_in_exists_body_is_not_a_separator() {
    let source = "MATCH (m) WHERE EXISTS { MATCH (a {p: 1}) MATCH (b:Person) } RETURN m";
    let parsed = parse_ok(source);
    let rendered = format!("{:?}", parsed.program);
    assert!(
        !rendered.contains("Label("),
        "node label must not become an IsPredicate::Label in {rendered}"
    );
}

// --- find_top_level_token ----------------------------------------------------

/// A pattern comprehension whose predicate contains a nested list
/// comprehension: the nested `|` sits at bracket depth one and must not be
/// mistaken for the top-level projection pipe.
#[test]
fn nested_list_comprehension_pipe_does_not_split_the_comprehension() {
    let source = "MATCH (a) RETURN [(a)--(b) WHERE a.x IN [z IN [1, 2] | z] | a.name]";
    let parsed = parse_ok(source);
    let expression = return_item_expression(&parsed, 0);
    let ExprKind::PatternComprehension(comprehension) = &expression.kind else {
        panic!("expected a pattern comprehension, got {expression:#?}")
    };
    assert_eq!(comprehension.pattern.span.text(source), Some("(a)--(b)"));
    let predicate = comprehension.predicate.as_ref().expect("predicate");
    assert_eq!(
        predicate.span.text(source),
        Some("a.x IN [z IN [1, 2] | z]")
    );
    assert_eq!(comprehension.projection.span.text(source), Some("a.name"));
}

// --- parse_regular_query -----------------------------------------------------

fn union_parts(source: &str) -> (UnionOperator, String) {
    let parsed = parse_ok(source);
    let query = regular_query(&parsed);
    assert_eq!(query.unions.len(), 1, "expected one union branch");
    let operator = &query.unions[0].operator;
    (
        operator.kind,
        operator
            .span
            .text(source)
            .expect("operator span")
            .to_owned(),
    )
}

#[test]
fn union_all_operator_kind_and_exact_span() {
    let (kind, text) = union_parts("RETURN 1 UNION ALL RETURN 2");
    assert_eq!(kind, UnionOperator::All);
    assert_eq!(text, "UNION ALL");
}

#[test]
fn union_distinct_operator_kind_and_exact_span() {
    let (kind, text) = union_parts("RETURN 1 UNION DISTINCT RETURN 2");
    assert_eq!(kind, UnionOperator::Distinct);
    assert_eq!(text, "UNION DISTINCT");
}

#[test]
fn bare_union_operator_kind_and_exact_span() {
    let (kind, text) = union_parts("RETURN 1 UNION RETURN 2");
    assert_eq!(kind, UnionOperator::Default);
    assert_eq!(text, "UNION");
}

// --- normalize_diagnostics ---------------------------------------------------

/// Two `]` mismatches plus one parser error: three distinct diagnostics.
/// The two MismatchedDelimiter entries share code and message but differ in
/// span, and the two diagnostics at 7..8 share the span but differ in code
/// and message: none of the three may be deduplicated away.
#[test]
fn distinct_delimiter_diagnostics_are_not_deduplicated() {
    let source = "RETURN ] RETURN ]";
    let outcome = parse_recovering(source);
    let observed: Vec<(DiagnosticCode, usize, usize)> = outcome
        .diagnostics
        .iter()
        .map(|diagnostic| {
            (
                diagnostic.code,
                diagnostic.primary_span.start,
                diagnostic.primary_span.end,
            )
        })
        .collect();
    assert_eq!(
        observed,
        vec![
            (DiagnosticCode::UnexpectedToken, 7, 8),
            (DiagnosticCode::MismatchedDelimiter, 7, 8),
            (DiagnosticCode::MismatchedDelimiter, 16, 17),
        ]
    );
}

/// Exactly 32 diagnostics (the cap) must be kept as-is: truncation plus the
/// TooManyErrors marker only kicks in strictly above the cap.
#[test]
fn exactly_max_diagnostics_are_kept_without_truncation() {
    // 31 invalid `~` tokens produce 31 lexer diagnostics plus one parser
    // diagnostic: 32 total, exactly at MAX_DIAGNOSTICS.
    let source = format!("RETURN 1 {}", "~ ".repeat(31));
    let outcome = parse_recovering(&source);
    assert_eq!(outcome.diagnostics.len(), 32);
    assert!(
        outcome
            .diagnostics
            .iter()
            .all(|diagnostic| diagnostic.code != DiagnosticCode::TooManyErrors),
        "no diagnostic may be suppressed at exactly the cap"
    );

    // One more error crosses the cap and appends the marker.
    let source = format!("RETURN 1 {}", "~ ".repeat(32));
    let outcome = parse_recovering(&source);
    assert_eq!(outcome.diagnostics.len(), 32);
    assert_eq!(
        outcome.diagnostics.last().map(|diagnostic| diagnostic.code),
        Some(DiagnosticCode::TooManyErrors)
    );
}

// --- parse_tokens_with_contextual_names --------------------------------------

/// `RETURN count +` — reclassifying `count` moves the error from the `+`
/// to end-of-input; the reported diagnostic must be the farthest error.
#[test]
fn contextual_retry_reports_the_farthest_error() {
    let source = "RETURN count +";
    let outcome = parse_recovering(source);
    let observed: Vec<(DiagnosticCode, usize, usize)> = outcome
        .diagnostics
        .iter()
        .map(|diagnostic| {
            (
                diagnostic.code,
                diagnostic.primary_span.start,
                diagnostic.primary_span.end,
            )
        })
        .collect();
    assert_eq!(observed, vec![(DiagnosticCode::UnexpectedEof, 14, 14)]);
}

/// `RETURN 1 + count filter` — the retry that resolves `count` does not
/// move the error, so the loop stops and reports the original expectation
/// (COUNT still wants `(` or `{`), not the post-retry operator expectation.
#[test]
fn non_improving_retry_keeps_the_original_expectation() {
    let source = "RETURN 1 + count filter";
    let outcome = parse_recovering(source);
    assert_eq!(outcome.diagnostics.len(), 1);
    let diagnostic = &outcome.diagnostics[0];
    assert_eq!(diagnostic.code, DiagnosticCode::UnexpectedToken);
    assert_eq!(
        (diagnostic.primary_span.start, diagnostic.primary_span.end),
        (17, 23)
    );
    assert_eq!(
        diagnostic.message,
        "unexpected token `identifier`; expected `(`, or `{`"
    );
}

/// `RETURN any (x) count` — the nearest candidate is `count`, after the
/// error location; resolving it cannot help, and the error stays at `)`.
#[test]
fn quantifier_without_in_reports_error_at_the_closing_paren() {
    let source = "RETURN any (x) count";
    let outcome = parse_recovering(source);
    assert_eq!(outcome.diagnostics.len(), 1);
    let diagnostic = &outcome.diagnostics[0];
    assert_eq!(diagnostic.code, DiagnosticCode::UnexpectedToken);
    assert_eq!(
        (diagnostic.primary_span.start, diagnostic.primary_span.end),
        (13, 14)
    );
    assert_eq!(diagnostic.message, "unexpected token `)`; expected `IN`");
}

/// `RETURN any(x) + count` — the fix is `any` (before the error); `count`
/// after the error must rank by its real distance, and the second retry
/// round (whose error moved forward) must be allowed to proceed.
#[test]
fn two_round_contextual_resolution_before_and_after_the_error() {
    let source = "RETURN any(x) + count";
    let parsed = parse_ok(source);
    let expression = return_item_expression(&parsed, 0);
    assert_eq!(expression.span.text(source), Some("any(x) + count"));
}

/// `RETURN 1 + detach, 2 + count AS y` — `detach` is accepted natively as a
/// name, and the `count AS` retry (the followed-by-AS candidate) must still
/// resolve on top of it.
#[test]
fn exact_location_candidate_outranks_aliased_candidate() {
    let source = "RETURN 1 + detach, 2 + count AS y";
    let parsed = parse_ok(source);
    assert_eq!(
        return_item_expression(&parsed, 0).span.text(source),
        Some("1 + detach")
    );
    assert_eq!(
        return_item_expression(&parsed, 1).span.text(source),
        Some("2 + count")
    );
}

/// `RETURN 1 + count, 2 + single` — two distinct keyword signatures need
/// two successive retry rounds with strictly advancing error locations.
#[test]
fn two_keyword_signatures_resolve_in_successive_rounds() {
    let source = "RETURN 1 + count, 2 + single";
    let parsed = parse_ok(source);
    assert_eq!(
        return_item_expression(&parsed, 0).span.text(source),
        Some("1 + count")
    );
    assert_eq!(
        return_item_expression(&parsed, 1).span.text(source),
        Some("2 + single")
    );
}

/// `RETURN as` — a bare `as` projection resolves to a variable named "as".
#[test]
fn bare_as_projection_resolves_the_as_token_itself() {
    let source = "RETURN as";
    let parsed = parse_ok(source);
    let expression = return_item_expression(&parsed, 0);
    assert_eq!(expression.span.text(source), Some("as"));
    let ExprKind::Variable(name) = &expression.kind else {
        panic!("expected a variable, got {expression:#?}")
    };
    assert_eq!(name.kind.text, "as");
}

/// `RETURN + count AS as` — the `AS` token sits exactly at the error
/// location and is itself followed by `as`, which gives it top retry
/// priority; the loop then stops without inventing a parse, and the
/// diagnostic keeps COUNT's original expectation. (A candidate-priority
/// change here would instead let the query parse.)
#[test]
fn count_aliased_as_the_word_as_keeps_counts_expectation() {
    let source = "RETURN + count AS as";
    let outcome = parse_recovering(source);
    assert_eq!(outcome.diagnostics.len(), 1);
    let diagnostic = &outcome.diagnostics[0];
    assert_eq!(diagnostic.code, DiagnosticCode::UnexpectedToken);
    assert_eq!(
        (diagnostic.primary_span.start, diagnostic.primary_span.end),
        (15, 17)
    );
    assert_eq!(
        diagnostic.message,
        "unexpected token `AS`; expected `(`, or `{`"
    );
}

// --- is_pattern_expression_context -------------------------------------------

/// The backward scan must step over a completed `[...]` (decrementing its
/// bracket counter on the matching `[`) and still find the WHERE keyword, so
/// the `(` after AND starts a pattern expression.
#[test]
fn pattern_expression_after_completed_list_literal() {
    let source = "MATCH (a) WHERE a.p IN [1, 2] AND (a)-->(b) RETURN a";
    let parsed = parse_ok(source);
    let where_clause = match_where_clause(&parsed);
    let ExprKind::Binary { right, .. } = &where_clause.kind else {
        panic!("expected AND expression, got {where_clause:#?}")
    };
    assert!(
        matches!(right.kind, ExprKind::Pattern(_)),
        "expected a pattern expression, got {right:#?}"
    );
    assert_eq!(right.span.text(source), Some("(a)-->(b)"));
}

/// The backward scan must step over a completed `{...}` (decrementing its
/// brace counter on the matching `{`) and still find the WHERE keyword.
#[test]
fn pattern_expression_after_completed_map_literal() {
    let source = "MATCH (a) WHERE {x: 1} = a.p AND (a)-->(b) RETURN a";
    let parsed = parse_ok(source);
    let where_clause = match_where_clause(&parsed);
    let ExprKind::Binary { right, .. } = &where_clause.kind else {
        panic!("expected AND expression, got {where_clause:#?}")
    };
    assert!(
        matches!(right.kind, ExprKind::Pattern(_)),
        "expected a pattern expression, got {right:#?}"
    );
    assert_eq!(right.span.text(source), Some("(a)-->(b)"));
}

/// A property map containing CASE (whose WHEN/THEN/ELSE are
/// expression-context markers) is skipped as a completed braced construct
/// (its `}` must increment the brace counter): the later `(m)-->(o)` stays a
/// MATCH pattern, not a pattern expression.
#[test]
fn case_inside_property_map_does_not_leak_pattern_expression_context() {
    let source = "MATCH (n {p: CASE WHEN true THEN 1 ELSE 2 END}), (m)-->(o) RETURN n";
    let parsed = parse_ok(source);
    let rendered = format!("{:?}", parsed.program);
    assert!(
        !rendered.contains("Pattern(Pattern"),
        "MATCH path must not become a pattern expression in {rendered}"
    );
}

/// The scan stops at the nearest MATCH: an earlier WITH context must not
/// turn a later MATCH's relationship pattern into a pattern expression.
#[test]
fn later_match_relationship_pattern_is_not_a_pattern_expression() {
    let source = "MATCH (a) WITH a MATCH (b)-->(c) RETURN b";
    let parsed = parse_ok(source);
    let rendered = format!("{:?}", parsed.program);
    assert!(
        !rendered.contains("Pattern(Pattern"),
        "MATCH path must not become a pattern expression in {rendered}"
    );
}

/// The shortestPath carve-out requires `shortestPath(` immediately before
/// the candidate `(`: a shortestPath variable two tokens back (followed by a
/// comma) must not veto the pattern-expression classification.
#[test]
fn shortest_path_variable_two_back_does_not_veto_pattern_expression() {
    let source = "WITH 1 AS shortestPath RETURN shortestPath, (a)-->(b)";
    let parsed = parse_ok(source);
    let expression = return_item_expression(&parsed, 1);
    assert!(
        matches!(expression.kind, ExprKind::Pattern(_)),
        "expected a pattern expression, got {expression:#?}"
    );
    assert_eq!(expression.span.text(source), Some("(a)-->(b)"));
}

// --- relationship_syntax_end / pattern_expression_end ------------------------

/// `<` and `-` split by whitespace lex as two tokens; the `(Less, Minus)`
/// arm of `relationship_syntax_end` must recognize them as a left arrow so
/// the WHERE operand is one pattern expression, not a `<` comparison.
#[test]
fn split_left_arrow_where_operand_is_a_pattern_expression() {
    let source = "MATCH (a) WHERE (a) < -[:R]- (b) RETURN a";
    let parsed = parse_ok(source);
    let where_clause = match_where_clause(&parsed);
    assert!(
        matches!(where_clause.kind, ExprKind::Pattern(_)),
        "expected a pattern expression, got {where_clause:#?}"
    );
    assert_eq!(where_clause.span.text(source), Some("(a) < -[:R]- (b)"));
}

/// A `{m,n}` quantifier after a relationship arrow is consumed by
/// `pattern_expression_end` (cursor lands one past the closing `}`), so the
/// whole `(a)-[:R]->{1,2}(b)` is classified as one pattern expression. The
/// nested pattern parse then rejects the quantifier itself: the diagnostic
/// sits on the `{` and expects the next node's `(`, not a binary operator.
#[test]
fn brace_quantified_pattern_expression_reports_error_at_the_quantifier() {
    let source = "MATCH (a) WHERE (a)-[:R]->{1,2}(b) RETURN a";
    let outcome = parse_recovering(source);
    assert_eq!(outcome.diagnostics.len(), 1, "{:#?}", outcome.diagnostics);
    let diagnostic = &outcome.diagnostics[0];
    assert_eq!(diagnostic.code, DiagnosticCode::UnexpectedToken);
    assert_eq!(
        (diagnostic.primary_span.start, diagnostic.primary_span.end),
        (26, 27)
    );
    assert_eq!(diagnostic.message, "unexpected token `{`; expected `(`");
}

/// A `*` quantifier after a relationship arrow advances the scan by one
/// token before the next node's `(`, with the same observable contract as
/// the braced quantifier above.
#[test]
fn star_quantified_pattern_expression_reports_error_at_the_quantifier() {
    let source = "MATCH (a) WHERE (a)-[:R]->*(b) RETURN a";
    let outcome = parse_recovering(source);
    assert_eq!(outcome.diagnostics.len(), 1, "{:#?}", outcome.diagnostics);
    let diagnostic = &outcome.diagnostics[0];
    assert_eq!(diagnostic.code, DiagnosticCode::UnexpectedToken);
    assert_eq!(
        (diagnostic.primary_span.start, diagnostic.primary_span.end),
        (26, 27)
    );
    assert_eq!(diagnostic.message, "unexpected token `*`; expected `(`");
}

// --- is_relationship_label_start / relationship_label_end --------------------

/// A colon after an integer inside brackets is not a relationship label
/// start (the token before the colon must be symbolic or `[`): `a[1:b]`
/// parses, with the bracket content classified as a label predicate on the
/// literal.
#[test]
fn integer_before_colon_inside_brackets_is_not_a_relationship_label_start() {
    let source = "WITH [1,2,3] AS a, 2 AS b RETURN a[1:b]";
    let parsed = parse_ok(source);
    let expression = return_item_expression(&parsed, 0);
    let ExprKind::Index { index, .. } = &expression.kind else {
        panic!("expected an index expression, got {expression:#?}")
    };
    assert_is_label_predicate(index, source, "1:b");
}

/// `%` after a legacy `|:` separator is not a symbolic name, so
/// `relationship_label_end` refuses the span and no relationship label
/// expression token is formed: the diagnostic points at the first colon
/// with the relationship-detail expectations.
#[test]
fn percent_after_legacy_pipe_colon_is_not_a_relationship_label_expression() {
    let source = "MATCH (a)-[:A|:%]->(b) RETURN a";
    let outcome = parse_recovering(source);
    assert_eq!(outcome.diagnostics.len(), 1, "{:#?}", outcome.diagnostics);
    let diagnostic = &outcome.diagnostics[0];
    assert_eq!(diagnostic.code, DiagnosticCode::UnexpectedToken);
    assert_eq!(
        (diagnostic.primary_span.start, diagnostic.primary_span.end),
        (11, 12)
    );
    assert_eq!(
        diagnostic.message,
        "unexpected token `:`; expected `*`, `IS`, `MATCH`, `PATH`, `RETURN`, `WHERE`, `]`, `escaped identifier`, `identifier`, `parameter`, `relationship label expression`, or `{`"
    );
}

// --- parse_label_expression / legacy_label_tokens_are_consistent -------------

/// A legacy relationship type list whose first name is a contextual keyword
/// (`count`) must pass the legacy-consistency check and parse into the two
/// type names.
#[test]
fn legacy_relationship_type_list_with_keyword_first_name_parses() {
    let source = "MATCH (a)-[:count|:B]->(b) RETURN a";
    let parsed = parse_ok(source);
    let rendered = format!("{:?}", parsed.program);
    assert!(
        rendered.contains("text: \"count\"") && rendered.contains("text: \"B\""),
        "expected both relationship type names in {rendered}"
    );
}

// --- is_procedure_name_start --------------------------------------------------

/// A CALL procedure name with more than three components: the backward walk
/// over `name.name.` pairs must step two tokens at a time all the way to
/// CALL, so no middle segment is misread as a qualified function name.
#[test]
fn deep_call_procedure_name_is_not_a_qualified_function() {
    let source = "CALL a.b.c.d()";
    let parsed = parse_ok(source);
    let query = regular_query(&parsed);
    assert!(
        matches!(query.head.kind.clauses[0].kind, ClauseKind::Call(_)),
        "expected a CALL clause"
    );
}

// --- is_explicit_set_all ------------------------------------------------------

/// `RETURN all(...)` — ALL followed by `(` is a quantifier invocation, never
/// the SET-ALL projection token.
#[test]
fn return_all_with_parenthesis_is_a_quantifier_not_set_all() {
    let source = "RETURN all(x IN [1] WHERE x > 0)";
    let parsed = parse_ok(source);
    let expression = return_item_expression(&parsed, 0);
    assert!(
        matches!(expression.kind, ExprKind::QuantifiedPredicate(_)),
        "expected a quantified predicate, got {expression:#?}"
    );
    assert_eq!(
        expression.span.text(source),
        Some("all(x IN [1] WHERE x > 0)")
    );
}

// --- contextual_name_signature ------------------------------------------------

/// Two `exists` keywords with the same previous token but different next
/// tokens have distinct signatures: resolving the bare `exists` must not
/// also reclassify the `exists {` subquery.
#[test]
fn same_keyword_with_different_next_token_keeps_distinct_signatures() {
    let source = "RETURN 1 + exists, 1 + exists { MATCH (n) }";
    let parsed = parse_ok(source);
    assert_eq!(
        return_item_expression(&parsed, 0).span.text(source),
        Some("1 + exists")
    );
    assert_eq!(
        return_item_expression(&parsed, 1).span.text(source),
        Some("1 + exists { MATCH (n) }")
    );
}

/// `RETURN any ( ) as` — the followed-by-AS candidate (`)` is followed by
/// nothing aliasable, so only `any` qualifies via priority one after its
/// exact/AS checks) drives the retry, and the final diagnostic points at
/// the empty parentheses, not end-of-input. (Promoting plain candidates to
/// priority one would report UnexpectedEof at 17 instead.)
#[test]
fn empty_quantifier_parens_report_error_at_the_close_paren() {
    let source = "RETURN any ( ) as";
    let outcome = parse_recovering(source);
    assert_eq!(outcome.diagnostics.len(), 1);
    let diagnostic = &outcome.diagnostics[0];
    assert_eq!(diagnostic.code, DiagnosticCode::UnexpectedToken);
    assert_eq!(
        (diagnostic.primary_span.start, diagnostic.primary_span.end),
        (13, 14)
    );
    assert_eq!(
        diagnostic.message,
        "unexpected token `)`; expected `MATCH`, `PATH`, `RETURN`, `escaped identifier`, or `identifier`"
    );
}