cyrs-syntax 0.1.0

Lossless CST and recovering parser for Cypher / GQL (spec 0001 §4).
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
//! CST snapshot corpus (spec §17.2).
//!
//! Each test renders the rowan tree for a representative query using
//! [`format_cst`] and asserts it against a committed `insta` snapshot.
//! Snapshots are the review artefact; the textual form is chosen for
//! structural clarity:
//!
//! - nodes print as `NODE_KIND@start..end`
//! - tokens print as `TOKEN_KIND@start..end "text"` with the text
//!   debug-quoted so whitespace / newlines are visible
//! - depth is rendered as two-space indent
//!
//! The corpus is organised by grammar area (clauses → patterns →
//! expressions → errors). Constructs that are deferred in cy-nom scope
//! (see `grammar/clause.rs`, `grammar/pattern.rs`, `grammar/expression.rs`)
//! are marked with `TODO(cy-nom): <bead>` comments so a later bead can
//! flip them on without re-deriving the corpus layout.

use std::fmt::Write as _;

use cyrs_syntax::{SyntaxNode, parse};
use rowan::{NodeOrToken, WalkEvent};

/// Render a rowan CST as an indented textual tree.
///
/// Format:
/// ```text
/// SOURCE_FILE@0..17
///   MATCH_CLAUSE@0..9
///     MATCH_KW@0..5 "MATCH"
///     ...
/// ```
///
/// Trivia and ERROR tokens are included — the tree is lossless, and the
/// snapshot reflects that.
fn format_cst(node: &SyntaxNode) -> String {
    let mut out = String::new();
    let mut depth: usize = 0;
    for ev in node.preorder_with_tokens() {
        match ev {
            WalkEvent::Enter(NodeOrToken::Node(n)) => {
                for _ in 0..depth {
                    out.push_str("  ");
                }
                let r = n.text_range();
                let start: u32 = r.start().into();
                let end: u32 = r.end().into();
                writeln!(out, "{:?}@{start}..{end}", n.kind()).unwrap();
                depth += 1;
            }
            WalkEvent::Leave(NodeOrToken::Node(_)) => {
                depth -= 1;
            }
            WalkEvent::Enter(NodeOrToken::Token(t)) => {
                for _ in 0..depth {
                    out.push_str("  ");
                }
                let r = t.text_range();
                let start: u32 = r.start().into();
                let end: u32 = r.end().into();
                writeln!(out, "{:?}@{start}..{end} {:?}", t.kind(), t.text()).unwrap();
            }
            WalkEvent::Leave(NodeOrToken::Token(_)) => {}
        }
    }
    out
}

/// Append any parse errors to the snapshot after a `---errors---` divider so
/// diagnostic emission is reviewed together with tree shape.
fn format_with_errors(src: &str) -> String {
    let parse = parse(src);
    let mut out = format_cst(&parse.syntax());
    let errs = parse.errors();
    if !errs.is_empty() {
        out.push_str("---errors---\n");
        for e in errs {
            let off: u32 = e.offset.into();
            writeln!(out, "@{off}: {}", e.message).unwrap();
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Clauses
// ---------------------------------------------------------------------------

#[test]
fn clause_match_basic() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN n"));
}

#[test]
fn clause_match_labeled_node() {
    insta::assert_snapshot!(format_with_errors("MATCH (p:Person) RETURN p"));
}

#[test]
fn clause_match_multiple_patterns() {
    insta::assert_snapshot!(format_with_errors("MATCH (a), (b), (c) RETURN a, b, c"));
}

#[test]
fn clause_optional_match() {
    insta::assert_snapshot!(format_with_errors(
        "OPTIONAL MATCH (a:Person {name: 'Alice'}) RETURN a"
    ));
}

#[test]
fn clause_match_where() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) WHERE n.age > 18 RETURN n"));
}

#[test]
fn clause_return_basic() {
    insta::assert_snapshot!(format_with_errors("RETURN 1"));
}

#[test]
fn clause_return_distinct() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN DISTINCT n.name"));
}

#[test]
fn clause_return_star() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN *"));
}

#[test]
fn clause_return_order_by_skip_limit() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (n) RETURN n.name ORDER BY n.age DESC SKIP 1 LIMIT 5"
    ));
}

#[test]
fn clause_return_alias() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN n.name AS name"));
}

#[test]
fn clause_with_simple_projection() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (n:Person) WITH n.name AS name RETURN name"
    ));
}

#[test]
fn clause_with_where_filter() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (n) WITH n WHERE n.age > 21 RETURN n"
    ));
}

#[test]
fn clause_with_order_by_limit() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (n) WITH n ORDER BY n.name LIMIT 5 RETURN n"
    ));
}

#[test]
fn clause_unwind_list() {
    insta::assert_snapshot!(format_with_errors("UNWIND [1, 2, 3] AS x RETURN x"));
}

#[test]
fn clause_create_node() {
    insta::assert_snapshot!(format_with_errors("CREATE (n:Person {name: 'Alice'})"));
}

#[test]
fn clause_merge_node_on_create() {
    insta::assert_snapshot!(format_with_errors(
        "MERGE (n:Person {name: 'A'}) ON CREATE SET n.created = 1 ON MATCH SET n.seen = 1 RETURN n"
    ));
}

#[test]
fn clause_set_property() {
    insta::assert_snapshot!(format_with_errors("MATCH (n:Person) SET n.active = true"));
}

#[test]
fn clause_set_label() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) SET n:Admin"));
}

#[test]
fn clause_remove_property() {
    insta::assert_snapshot!(format_with_errors("MATCH (n:Person) REMOVE n.age"));
}

#[test]
fn clause_remove_label() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) REMOVE n:Admin"));
}

#[test]
fn clause_delete() {
    insta::assert_snapshot!(format_with_errors("MATCH (n:Person) DELETE n"));
}

#[test]
fn clause_detach_delete() {
    insta::assert_snapshot!(format_with_errors("MATCH (n:Person) DETACH DELETE n"));
}

// TODO(cy-nom): CREATE clause (deferred_clause_stub).
// TODO(cy-nom): MERGE with ON CREATE / ON MATCH (deferred_clause_stub).
// TODO(cy-nom): SET (property / labels / map) (deferred_clause_stub).
// TODO(cy-nom): REMOVE (property / labels) (deferred_clause_stub).
// TODO(cy-nom): DELETE / DETACH DELETE (deferred_clause_stub).
// TODO(cy-nom): CALL / CALL YIELD (deferred_clause_stub).
//
// Each of the deferred clauses *does* produce a tree today — a stub
// ERROR node wrapping the keyword — but the shape will change when the
// production lands; snapshotting now would just be churn.

// ---------------------------------------------------------------------------
// Patterns
// ---------------------------------------------------------------------------

#[test]
fn pattern_anonymous_node() {
    insta::assert_snapshot!(format_with_errors("MATCH () RETURN 1"));
}

#[test]
fn pattern_bound_node() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN n"));
}

#[test]
fn pattern_multi_label_node() {
    insta::assert_snapshot!(format_with_errors("MATCH (n:Person:Employee) RETURN n"));
}

#[test]
fn pattern_node_with_properties() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (n:Person {name: 'Alice', age: 30}) RETURN n"
    ));
}

#[test]
fn pattern_rel_undirected() {
    insta::assert_snapshot!(format_with_errors("MATCH (a)-[r]-(b) RETURN a, b"));
}

#[test]
fn pattern_rel_directed_right() {
    insta::assert_snapshot!(format_with_errors("MATCH (a)-[:KNOWS]->(b) RETURN a, b"));
}

#[test]
fn pattern_rel_directed_left() {
    insta::assert_snapshot!(format_with_errors("MATCH (a)<-[:KNOWS]-(b) RETURN a, b"));
}

#[test]
fn pattern_rel_with_props() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (a)-[r:KNOWS {since: 2020}]->(b) RETURN r"
    ));
}

#[test]
fn pattern_chain_three_nodes() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (a)-[:R1]->(b)-[:R2]->(c) RETURN a, b, c"
    ));
}

#[test]
fn pattern_var_length_range() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (a)-[:KNOWS*1..3]->(b) RETURN a, b"
    ));
}

#[test]
fn pattern_var_length_unbounded() {
    insta::assert_snapshot!(format_with_errors("MATCH (a)-[r:KNOWS*]->(b) RETURN a"));
}

#[test]
fn pattern_named_path() {
    insta::assert_snapshot!(format_with_errors("MATCH p = (a)-[:KNOWS]->(b) RETURN p"));
}

// cy-b5b: shortestPath / allShortestPaths pattern functions (spec §6.4 /
// §19 row "shortest-path"). The keyword wraps an inner path pattern in a
// SHORTEST_PATH_PATTERN CST node; the path-binder form (`p = ...`) is
// the canonical use site (acceptance criterion in the bead).
#[test]
fn pattern_shortest_path_named() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH p = shortestPath((a)-[:KNOWS*]->(b)) RETURN p"
    ));
}

#[test]
fn pattern_all_shortest_paths_named() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH p = allShortestPaths((a)-[:KNOWS*1..5]->(b)) RETURN p"
    ));
}

#[test]
fn pattern_shortest_path_anonymous() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH shortestPath((a)-[*]->(b)) RETURN a, b"
    ));
}

// ---------------------------------------------------------------------------
// Expressions — atoms
// ---------------------------------------------------------------------------

#[test]
fn expr_literal_int() {
    insta::assert_snapshot!(format_with_errors("RETURN 42"));
}

#[test]
fn expr_literal_float() {
    insta::assert_snapshot!(format_with_errors("RETURN 3.14"));
}

#[test]
fn expr_literal_string() {
    insta::assert_snapshot!(format_with_errors("RETURN 'hello'"));
}

#[test]
fn expr_literal_bool() {
    insta::assert_snapshot!(format_with_errors("RETURN TRUE, FALSE"));
}

#[test]
fn expr_literal_null() {
    insta::assert_snapshot!(format_with_errors("RETURN NULL"));
}

#[test]
fn expr_parameter() {
    insta::assert_snapshot!(format_with_errors("RETURN $name"));
}

#[test]
fn expr_list_literal_ints() {
    insta::assert_snapshot!(format_with_errors("RETURN [1, 2, 3]"));
}

#[test]
fn expr_list_literal_empty() {
    insta::assert_snapshot!(format_with_errors("RETURN []"));
}

#[test]
fn expr_map_literal_basic() {
    insta::assert_snapshot!(format_with_errors("RETURN {a: 1, b: 'two'}"));
}

// --- Map projection (cy-01q, spec §6.1 / §19) -----------------------------
//
// The four projection-item shapes:
//   .name          property selector
//   key: expr      literal item
//   .*             all-properties spread
//   *              all-bound-vars spread
//
// Disambiguation from `MapLiteral`: a projection's `{` is a *postfix
// trailer* on the subject expression. A bare `{ k: v }` in atom position
// (no preceding expression) still parses as `MapLiteral`. The
// `expr_map_literal_basic` snapshot above pins that contract.

#[test]
fn expr_map_projection_property_selectors() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN n { .name, .age }"));
}

#[test]
fn expr_map_projection_literal_item() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (n) RETURN n { full_name: n.name, .age }"
    ));
}

#[test]
fn expr_map_projection_all_properties_spread() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN n { .* }"));
}

#[test]
fn expr_map_projection_all_bound_vars_spread() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN n { * }"));
}

#[test]
fn expr_map_projection_mixed_all_four_kinds() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (n) RETURN n { .name, age: 30, .*, * }"
    ));
}

#[test]
fn expr_map_projection_empty() {
    // Spec is silent on `n { }` — accept it; lowering produces an empty map.
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN n { }"));
}

// Bare `{ k: v }` in atom position must still parse as a MAP_LITERAL,
// not a projection — a projection requires a subject in trailer position.
#[test]
fn expr_map_literal_remains_literal_without_subject() {
    insta::assert_snapshot!(format_with_errors("RETURN { a: 1, b: 2 }"));
}

// Recovery: missing `}` closer.
#[test]
fn err_map_projection_unclosed() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN n { .name"));
}

// Recovery: missing `:` in literal item.
#[test]
fn err_map_projection_missing_colon() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN n { age 30 }"));
}

// Recovery: stray token after `.` (neither identifier nor `*`).
#[test]
fn err_map_projection_dot_then_garbage() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN n { . , .age }"));
}

#[test]
fn expr_variable() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN n"));
}

#[test]
fn expr_property_access() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN n.name"));
}

#[test]
fn expr_subscript() {
    insta::assert_snapshot!(format_with_errors("RETURN a[0]"));
}

// ---------------------------------------------------------------------------
// Expressions — list indexing and slicing (cy-7s6.1)
// ---------------------------------------------------------------------------
//
// openCypher / GQL postfix indexing:
//   xs[0]        — integer index, zero-based
//   xs[-1]       — negative index, from-end
//   xs[0..3]     — slice with inclusive start, exclusive end
//   xs[..3]      — elided start (defaults to 0)
//   xs[0..]      — elided end (defaults to len)
//   xs[0..3][0]  — postfix chain: slice then index

#[test]
fn expr_index_literal() {
    insta::assert_snapshot!(format_with_errors("RETURN xs[0]"));
}

#[test]
fn expr_index_negative() {
    insta::assert_snapshot!(format_with_errors("RETURN xs[-1]"));
}

#[test]
fn expr_slice_bounded() {
    insta::assert_snapshot!(format_with_errors("RETURN xs[0..3]"));
}

#[test]
fn expr_slice_elided_start() {
    insta::assert_snapshot!(format_with_errors("RETURN xs[..3]"));
}

#[test]
fn expr_slice_elided_end() {
    insta::assert_snapshot!(format_with_errors("RETURN xs[0..]"));
}

#[test]
fn expr_slice_then_index_chain() {
    insta::assert_snapshot!(format_with_errors("RETURN xs[0..3][0]"));
}

// ---------------------------------------------------------------------------
// Expressions — list comprehensions (cy-5gh)
// ---------------------------------------------------------------------------
//
// openCypher §3.3 list comprehension — four legal shapes:
//   [x IN xs]                         — identity collect
//   [x IN xs WHERE p(x)]              — filter only (implicit identity map)
//   [x IN xs | f(x)]                  — map only
//   [x IN xs WHERE p(x) | f(x)]       — filter and map

#[test]
fn expr_list_comprehension_identity() {
    insta::assert_snapshot!(format_with_errors("RETURN [x IN [1, 2, 3]]"));
}

#[test]
fn expr_list_comprehension_filter_only() {
    insta::assert_snapshot!(format_with_errors("RETURN [x IN [1, 2, 3] WHERE x > 1]"));
}

#[test]
fn expr_list_comprehension_map_only() {
    insta::assert_snapshot!(format_with_errors("RETURN [x IN [1, 2, 3] | x + 1]"));
}

#[test]
fn expr_list_comprehension_filter_and_map() {
    insta::assert_snapshot!(format_with_errors(
        "RETURN [x IN [1, 2, 3] WHERE x > 1 | x + 1]"
    ));
}

#[test]
fn err_list_comprehension_unterminated_where() {
    // Missing closing `]` after a WHERE predicate — exercises the
    // E0069 recovery (expected `|` or `]`).
    insta::assert_snapshot!(format_with_errors("RETURN [x IN xs WHERE x > 1"));
}

#[test]
fn expr_function_call() {
    insta::assert_snapshot!(format_with_errors("RETURN count(n)"));
}

#[test]
fn expr_function_call_distinct() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN count(DISTINCT n)"));
}

#[test]
fn expr_paren() {
    insta::assert_snapshot!(format_with_errors("RETURN (1 + 2) * 3"));
}

// TODO(cy-nom): list literals `[a, b]`, map literals `{k: v}`, list /
// pattern comprehensions, CASE (simple + searched), pattern predicates,
// EXISTS(...), standalone COUNT(*) — deferred per grammar/expression.rs.

// ---------------------------------------------------------------------------
// Expressions — list predicates (cy-8x5)
// ---------------------------------------------------------------------------
//
// openCypher list predicates: ANY / ALL / NONE / SINGLE share one grammar
// shape — `KW '(' IDENT 'IN' Expr ('WHERE' Expr)? ')'`. The discriminant
// keyword survives as the first child token of the LIST_PREDICATE_EXPR
// node so HIR lowering can pick the variant.

#[test]
fn expr_list_predicate_any_with_where() {
    insta::assert_snapshot!(format_with_errors("RETURN ANY(x IN xs WHERE x > 0)"));
}

#[test]
fn expr_list_predicate_all_bare() {
    insta::assert_snapshot!(format_with_errors("RETURN ALL(x IN xs)"));
}

#[test]
fn expr_list_predicate_none_prop_filter() {
    insta::assert_snapshot!(format_with_errors(
        "RETURN NONE(x IN xs WHERE x.foo = 'bar')"
    ));
}

#[test]
fn expr_list_predicate_single_with_where() {
    insta::assert_snapshot!(format_with_errors("RETURN SINGLE(x IN xs WHERE x < 10)"));
}

#[test]
fn err_list_predicate_unterminated_where() {
    // Unterminated WHERE arm — the parser should emit `expected predicate
    // expression after WHERE` plus `expected )` recovery diagnostics.
    insta::assert_snapshot!(format_with_errors("RETURN ANY(x IN xs WHERE"));
}

// ---------------------------------------------------------------------------
// Expressions — EXISTS pattern predicate (cy-lve, spec §6.1 / §19)
// ---------------------------------------------------------------------------
//
// `EXISTS ( <pattern> )` is a pattern predicate — sugar for the bare path
// form in WHERE position (`WHERE (a)-->(b)`). Disambiguation from the
// `exists(expr)` function call: two-token lookahead on `EXISTS ( (`. The
// block-subquery form `EXISTS { ... }` is deferred (spec §19 / §20 D1)
// and rejected with E4017.

#[test]
fn expr_exists_pattern_simple() {
    insta::assert_snapshot!(format_with_errors("RETURN EXISTS((a)-->(b))"));
}

#[test]
fn expr_exists_pattern_with_labels() {
    insta::assert_snapshot!(format_with_errors(
        "RETURN EXISTS((a:Person)-[:KNOWS]->(b:Person))"
    ));
}

#[test]
fn expr_exists_pattern_in_where() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (a) WHERE EXISTS((a)-->(:Movie)) RETURN a"
    ));
}

#[test]
fn expr_exists_function_call_form() {
    // `exists(n.prop)` — expression arg, not a pattern. Must still parse
    // as a plain function call (`FUNCTION_CALL`).
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN exists(n.prop)"));
}

#[test]
fn err_exists_block_deferred() {
    // `EXISTS { ... }` block-subquery form — deferred per spec §19 /
    // §20 D1. The parser emits E4017 via the `exists_subquery`
    // dialect-gate slot and recovers by swallowing the braced body.
    insta::assert_snapshot!(format_with_errors(
        "MATCH (a) WHERE EXISTS { MATCH (a) RETURN a } RETURN a"
    ));
}

// ---------------------------------------------------------------------------
// Expressions — bare pattern predicates (cy-7lf, spec §6.1 / §19)
// ---------------------------------------------------------------------------
//
// `(a)-->(b)` in expression position is sugar for the `EXISTS` wrapping
// form — spec §6.1 desugars both to `Expr::PatternPredicate`. Two-token
// lookahead past `(` disambiguates from parenthesised expressions; see
// `grammar::expression::at_bare_pattern_predicate` for the table.

#[test]
fn expr_bare_pattern_predicate_in_where() {
    // Classic bare form in WHERE position with a labelled target node.
    insta::assert_snapshot!(format_with_errors(
        "MATCH (a) WHERE (a)-->(:Movie) RETURN a"
    ));
}

#[test]
fn expr_bare_pattern_predicate_not_negation() {
    // `NOT (a)-->(b)` — the pattern predicate binds tighter than unary
    // NOT, so the whole predicate becomes the operand.
    insta::assert_snapshot!(format_with_errors(
        "MATCH (a) WHERE NOT (a)-->(:Villain) RETURN a"
    ));
}

#[test]
fn expr_bare_pattern_predicate_single_var_ambiguous() {
    // `(n)` — per cy-7lf, resolved as a pattern predicate (the empty
    // path `(n)`). Users who want the expression can write `n` without
    // the parens.
    insta::assert_snapshot!(format_with_errors("MATCH (n) WHERE (n) RETURN n"));
}

#[test]
fn expr_bare_pattern_predicate_empty_node() {
    // `()-->()` — anonymous nodes on both sides. Trivially exercises
    // the `nth(1) == R_PAREN` branch of the disambiguator.
    insta::assert_snapshot!(format_with_errors("MATCH (a) WHERE ()-->() RETURN a"));
}

#[test]
fn expr_bare_pattern_predicate_reverse_direction() {
    // `(n)<-[]-()` — reverse-direction rel. Covers the inbound-arrow
    // branch of the pattern parser via bare pattern predicate position.
    insta::assert_snapshot!(format_with_errors("MATCH (n) WHERE (n)<-[]-() RETURN n"));
}

#[test]
fn expr_paren_still_parens_arithmetic() {
    // Regression guard: `(1 + 2)` must still be a PAREN_EXPR. The
    // disambiguator bails to paren-expr because `nth(1)` is an
    // INT_LITERAL.
    insta::assert_snapshot!(format_with_errors("RETURN (1 + 2)"));
}

#[test]
fn expr_paren_still_parens_property_access() {
    // Regression guard: `(a.name)` is a parenthesised property access,
    // not a pattern predicate. `nth(2)` is `.` which forces the
    // expression branch.
    insta::assert_snapshot!(format_with_errors("MATCH (a) RETURN (a.name)"));
}

// ---------------------------------------------------------------------------
// Expressions — operators
// ---------------------------------------------------------------------------

#[test]
fn expr_binary_arithmetic() {
    insta::assert_snapshot!(format_with_errors("RETURN 1 + 2 * 3"));
}

#[test]
fn expr_binary_power_right_assoc() {
    insta::assert_snapshot!(format_with_errors("RETURN 2 ^ 3 ^ 2"));
}

#[test]
fn expr_binary_comparison() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) WHERE n.age >= 18 RETURN n"));
}

#[test]
fn expr_binary_boolean() {
    insta::assert_snapshot!(format_with_errors("RETURN NOT a OR b AND c"));
}

#[test]
fn expr_starts_with() {
    insta::assert_snapshot!(format_with_errors("RETURN a STARTS WITH 'foo'"));
}

#[test]
fn expr_ends_with() {
    insta::assert_snapshot!(format_with_errors("RETURN a ENDS WITH 'foo'"));
}

#[test]
fn expr_contains() {
    insta::assert_snapshot!(format_with_errors("RETURN a CONTAINS 'foo'"));
}

#[test]
fn expr_regex_match() {
    insta::assert_snapshot!(format_with_errors("RETURN a =~ 'r.*'"));
}

#[test]
fn expr_unary_minus() {
    insta::assert_snapshot!(format_with_errors("RETURN -1"));
}

#[test]
fn expr_unary_not() {
    insta::assert_snapshot!(format_with_errors("RETURN NOT a"));
}

#[test]
fn expr_is_null() {
    insta::assert_snapshot!(format_with_errors("RETURN a IS NULL"));
}

#[test]
fn expr_is_not_null() {
    insta::assert_snapshot!(format_with_errors("RETURN a IS NOT NULL"));
}

#[test]
fn expr_in_operator() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (n) WHERE n.age IN n.ages RETURN n"
    ));
}

// TODO(cy-nom): IN with list literal RHS (`x IN [1, 2, 3]`) — requires
// list-literal support in the expression grammar.

// ---------------------------------------------------------------------------
// Multi-statement files (spec §4.6)
// ---------------------------------------------------------------------------

#[test]
fn multi_stmt_empty_file() {
    insta::assert_snapshot!(format_with_errors(""));
}

#[test]
fn multi_stmt_single_no_semi() {
    insta::assert_snapshot!(format_with_errors("RETURN 1"));
}

#[test]
fn multi_stmt_single_trailing_semi() {
    insta::assert_snapshot!(format_with_errors("RETURN 1;"));
}

#[test]
fn multi_stmt_two_statements() {
    insta::assert_snapshot!(format_with_errors("RETURN 1; RETURN 2"));
}

#[test]
fn multi_stmt_two_with_trailing_semi() {
    insta::assert_snapshot!(format_with_errors(
        "MATCH (n) RETURN n; MATCH (m) RETURN m;"
    ));
}

// ---------------------------------------------------------------------------
// Error cases — tree + diagnostics both snapshotted
// ---------------------------------------------------------------------------

#[test]
fn err_unclosed_paren_in_pattern() {
    insta::assert_snapshot!(format_with_errors("MATCH (n RETURN n"));
}

#[test]
fn err_missing_return_target() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) RETURN"));
}

#[test]
fn err_stray_keyword_after_where() {
    insta::assert_snapshot!(format_with_errors("MATCH (n) WHERE RETURN n"));
}

#[test]
fn err_leading_garbage() {
    insta::assert_snapshot!(format_with_errors("garbage MATCH (n) RETURN n"));
}

#[test]
fn err_unclosed_property_map() {
    insta::assert_snapshot!(format_with_errors("MATCH (n {x: 1 RETURN n"));
}

#[test]
fn err_missing_label_after_colon() {
    insta::assert_snapshot!(format_with_errors("MATCH (n:) RETURN n"));
}

#[test]
fn err_unterminated_string() {
    insta::assert_snapshot!(format_with_errors("RETURN 'oops"));
}

#[test]
fn err_missing_closing_bracket_in_rel() {
    insta::assert_snapshot!(format_with_errors("MATCH (a)-[r (b) RETURN a"));
}