relate-parser 1.0.2

Cypher lexer, parser, and AST for the Relate graph database
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
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
use super::*;

/// What the `ON` target of a `CREATE … INDEX … FOR …` clause must be,
/// decided once from the index kind, the entity type and whether `EACH` was
/// written ([`Parser::classify_on_target`]).
enum OnTargetForm {
    /// `ON EACH [prop, …]` — FULLTEXT's list.
    EachBracketList,
    /// `ON EACH labels(n)` / `ON EACH type(r)`, or a relationship LOOKUP
    /// index's EACH-less `ON type(r)`.
    LookupTarget,
    /// `ON (n.prop, …)` / `ON n.prop` — the property-list kinds.
    PropertyList,
}

impl<'a> Parser<'a> {
    /// Parses the `FOR (n:Label)` / `FOR (n:A|B|...)` / `FOR (n)` /
    /// `FOR ()-[r:TYPE]-()` (all four direction spellings) / `FOR ()-[r]-()`
    /// DDL target shared by `CREATE INDEX` and `CREATE CONSTRAINT`
    /// (CIP-11's relationship-pattern generalization). Returns the entity
    /// kind, the flat label/relationship-type list (empty for a label-less
    /// LOOKUP target), and the pattern's own variable name (the property
    /// list that follows, e.g. `ON (n.prop)`, is written in terms of it).
    pub(super) fn parse_schema_for_target(
        &mut self,
    ) -> ParseResult<(SchemaEntityType, Vec<SmallName>, SmallName)> {
        self.expect(TokenType::FOR)?;
        if self.peek_type() != TokenType::LeftParen {
            let tok = self.peek().clone();
            return Err(self.error_at_token(
                &tok,
                format!("expected '(' after FOR, got {:?}", tok.literal),
            ));
        }
        // A relationship pattern always has empty parens on both sides in
        // this DDL grammar (`FOR ()-[r:TYPE]-()`, `FOR ()<-[r:TYPE]-()`, ...)
        // -- distinguished from the node form by a `)` immediately followed
        // by a dash/left-arrow. Unlike `parse_constraint_for_target_ext`
        // (a more permissive `FOR (m)-[...]->()` grammar), this stays
        // strict: `CREATE INDEX`/`CREATE VECTOR INDEX` reject a
        // labelled or aliased endpoint on either side (CIP-116 create-
        // index-errors[18]/[19]).
        if self.peek_at(1).ty == TokenType::RightParen
            && matches!(self.peek_at(2).ty, TokenType::Dash | TokenType::ArrowLeft)
        {
            self.parse_node_pattern()?; // consume the empty left `()`
            let rel = self.parse_rel_pattern()?;
            self.parse_node_pattern()?; // consume the (also empty) right `()`
            let labels = match &rel.type_expr {
                Some(le) => le.as_ddl_list().ok_or_else(|| {
                    self.error(
                        "expected a plain relationship type or A|B|... list in the FOR pattern",
                    )
                })?,
                None => Vec::new(),
            };
            let var = rel.variable.clone().unwrap_or_default();
            return Ok((SchemaEntityType::Relationship, labels, var));
        }

        let node = self.parse_node_pattern()?;
        let labels = match &node.label_expr {
            Some(le) => le.as_ddl_list().ok_or_else(|| {
                self.error("expected a plain label or A|B|... list in the FOR pattern")
            })?,
            None => Vec::new(),
        };
        let var = node.variable.clone().unwrap_or_default();
        Ok((SchemaEntityType::Node, labels, var))
    }

    /// Like `parse_schema_for_target`, but for `CREATE CONSTRAINT` only:
    /// also returns the relationship pattern's own source/destination
    /// endpoint aliases, and permits a labelled/aliased endpoint on either
    /// side (CIP-177's `FOR (m)-[:TYPE]->()` / `FOR ()-[:TYPE]->(m)`
    /// label-existence constraints need to know which endpoint `m`
    /// names). `None`/`None` for a node target. Deliberately not shared
    /// with `parse_schema_for_target` -- `CREATE INDEX` must keep
    /// rejecting a labelled/aliased relationship-pattern endpoint (CIP-116
    /// create-index-errors[18]/[19]).
    pub(super) fn parse_constraint_for_target_ext(&mut self) -> ParseResult<ConstraintForTarget> {
        self.expect(TokenType::FOR)?;
        if self.peek_type() != TokenType::LeftParen {
            let tok = self.peek().clone();
            return Err(self.error_at_token(
                &tok,
                format!("expected '(' after FOR, got {:?}", tok.literal),
            ));
        }
        // Try the source endpoint as a general node pattern (empty `()`,
        // or one carrying just an alias like `(m)` -- CIP-177's
        // source/destination label-existence constraints) -- distinguished
        // from a plain node FOR-target by the closing `)` being immediately
        // followed by a dash/left-arrow.
        let saved = self.save_pos();
        let source = self.parse_node_pattern()?;
        if matches!(self.peek_type(), TokenType::Dash | TokenType::ArrowLeft) {
            let rel = self.parse_rel_pattern()?;
            let target = self.parse_node_pattern()?;
            let labels = match &rel.type_expr {
                Some(le) => le.as_ddl_list().ok_or_else(|| {
                    self.error(
                        "expected a plain relationship type or A|B|... list in the FOR pattern",
                    )
                })?,
                None => Vec::new(),
            };
            return Ok(ConstraintForTarget {
                entity_type: SchemaEntityType::Relationship,
                labels,
                variable: rel.variable.unwrap_or_default(),
                source_alias: source.variable,
                target_alias: target.variable,
            });
        }
        self.restore_pos(saved);

        let node = self.parse_node_pattern()?;
        let labels = match &node.label_expr {
            Some(le) => le.as_ddl_list().ok_or_else(|| {
                self.error("expected a plain label or A|B|... list in the FOR pattern")
            })?,
            None => Vec::new(),
        };
        Ok(ConstraintForTarget {
            entity_type: SchemaEntityType::Node,
            labels,
            variable: node.variable.unwrap_or_default(),
            source_alias: None,
            target_alias: None,
        })
    }

    /// `ON (n.prop1, n.prop2, ...)` / paren-less single-property `ON
    /// n.prop`.
    pub(super) fn parse_on_property_list(&mut self) -> ParseResult<Vec<SmallName>> {
        let paren = self.peek_type() == TokenType::LeftParen;
        if paren {
            self.next_token();
        }
        let mut properties = Vec::new();
        loop {
            self.next_token(); // variable name (skip)
            self.expect(TokenType::Dot)?;
            properties.push(self.parse_bare_name("property name")?);
            if !paren || self.peek_type() != TokenType::Comma {
                break;
            }
            self.next_token();
        }
        if paren {
            self.expect(TokenType::RightParen)?;
        }
        Ok(properties)
    }

    /// `ON EACH [n.prop1, n.prop2, ...]` (CIP-38 FULLTEXT): a bracketed list
    /// of plain property references -- Neo4j's actual grammar is narrower
    /// than the proposal's own `EACH <expression>` text (Deviation: no general
    /// expressions, e.g. `p.title + p.abstract`, are accepted), and the
    /// list may never be empty.
    pub(super) fn parse_on_each_bracket_list(&mut self) -> ParseResult<Vec<SmallName>> {
        self.expect(TokenType::LeftBracket)?;
        if self.peek_type() == TokenType::RightBracket {
            return Err(self.error("InvalidSyntax: ON EACH requires at least one property"));
        }
        let mut properties = Vec::new();
        loop {
            self.next_token(); // variable name (skip)
            self.expect(TokenType::Dot)?;
            properties.push(self.parse_bare_name("property name")?);
            if self.peek_type() != TokenType::Comma {
                break;
            }
            self.next_token();
        }
        self.expect(TokenType::RightBracket)?;
        let mut seen = std::collections::HashSet::new();
        for p in &properties {
            if !seen.insert(p.clone()) {
                return Err(self.error(format!(
                    "IndexWithDuplicatedTokens: duplicate property '{p}' in ON EACH list"
                )));
            }
        }
        Ok(properties)
    }

    /// `ON EACH labels(n)` / `ON EACH type(r)`: the LOOKUP token-index
    /// target. The argument is the FOR-pattern's own
    /// variable; a LOOKUP index has no fixed property/label list, so
    /// nothing beyond syntax is captured here.
    pub(super) fn parse_lookup_each_target(
        &mut self,
        entity_type: SchemaEntityType,
        pattern_variable: &SmallName,
    ) -> ParseResult<()> {
        let fn_tok = self.next_token();
        let want = match entity_type {
            SchemaEntityType::Node => "labels",
            SchemaEntityType::Relationship => "type",
        };
        if !fn_tok.literal.eq_ignore_ascii_case(want) {
            return Err(self.error_at_token(
                &fn_tok,
                format!("expected {}(...), got {:?}", want, fn_tok.literal),
            ));
        }
        self.expect(TokenType::LeftParen)?;
        let var_tok = self.next_token();
        // The function argument must be the lookup target's own pattern
        // variable (`FOR (n) ... labels(n)`); any other name is undefined
        // in this scope (Neo4j 42N62). The detail tag names that condition,
        // so `EngineError::kind()` surfaces `UndefinedVariable` like every
        // other undefined-variable site rather than the generic parse
        // fallback.
        if pattern_variable.with_str(|expected| var_tok.literal != expected) {
            return Err(self
                .error_at_token(
                    &var_tok,
                    format!("Variable `{}` not defined.", var_tok.literal),
                )
                .with_detail(crate::parser::UNDEFINED_VARIABLE_DETAIL));
        }
        self.expect(TokenType::RightParen)?;
        Ok(())
    }

    /// The optional `<name>` in `CREATE INDEX`/`CREATE CONSTRAINT`: a plain
    /// identifier (including the schema keywords `INDEX`/`CONSTRAINT` used
    /// bare, which Neo4j allows as a name here) or a `$param` reference
    /// (CIP-134). Deliberately narrower than `TokenType::is_ident_like`:
    /// that set also contains `IF`/`FOR`/`NOT`/`EXISTS`/etc., the very
    /// tokens expected to immediately follow a name position, so accepting
    /// them here would misparse `CREATE INDEX IF NOT EXISTS ...` (no name)
    /// as naming the index `IF`. Absent (`None`) whenever the next token
    /// isn't one of the safe cases, matching the un-named form.
    pub(super) fn parse_optional_schema_name(&mut self) -> Option<SchemaName> {
        match self.peek_type() {
            TokenType::Parameter => {
                let tok = self.next_token();
                Some(SchemaName::Parameter(tok.literal.into_owned()))
            }
            TokenType::Identifier | TokenType::INDEX | TokenType::CONSTRAINT => {
                let tok = self.next_token();
                Some(SchemaName::Literal(tok.literal.into_owned()))
            }
            _ => None,
        }
    }

    /// The mandatory `<name>` in `DROP INDEX`/`DROP CONSTRAINT` (CIP-134
    /// adds the `$param` form; unlike CREATE, DROP always requires a name
    /// token here).
    pub(super) fn parse_required_schema_name(&mut self, context: &str) -> ParseResult<SchemaName> {
        match self.peek_type() {
            TokenType::Parameter => {
                let tok = self.next_token();
                Ok(SchemaName::Parameter(tok.literal.into_owned()))
            }
            TokenType::Identifier | TokenType::INDEX | TokenType::CONSTRAINT => {
                let tok = self.next_token();
                Ok(SchemaName::Literal(tok.literal.into_owned()))
            }
            _ => {
                let tok = self.peek().clone();
                Err(self.error_at_token(
                    &tok,
                    format!("expected a name after {}, got {:?}", context, tok.literal),
                ))
            }
        }
    }

    /// Consumes an `IF EXISTS` if one comes next; returns whether it did.
    pub(super) fn parse_optional_if_exists(&mut self) -> ParseResult<bool> {
        if self.peek_type() != TokenType::IF {
            return Ok(false);
        }
        self.next_token();
        self.expect(TokenType::EXISTS)?;
        Ok(true)
    }

    /// The `<name>? IF NOT EXISTS? <name>?` prefix both `CREATE INDEX` and
    /// `CREATE CONSTRAINT` accept, in that order: an optional schema name,
    /// an optional `IF NOT EXISTS`, then a second name attempt when the
    /// first one did not parse (so `IF NOT EXISTS` may precede or follow the
    /// name). One spelling of the ordering rule, shared by both parsers.
    pub(super) fn parse_optional_name_and_if_not_exists(
        &mut self,
    ) -> ParseResult<(Option<SchemaName>, bool)> {
        let mut name = self.parse_optional_schema_name();
        let if_not_exists = if self.peek_type() == TokenType::IF {
            self.next_token();
            self.expect(TokenType::NOT)?;
            self.expect(TokenType::EXISTS)?;
            true
        } else {
            false
        };
        if name.is_none() {
            name = self.parse_optional_schema_name();
        }
        Ok((name, if_not_exists))
    }

    /// `<language name> ::= CYPHER <digit>...` -- the version digits are
    /// *not* range-checked here (an unsupported value inside
    /// `DEFAULT LANGUAGE` is a runtime data
    /// exception, not a compile-time syntax error, unlike CIP-150's
    /// statement-preamble `CYPHER <version>` prefix -- the value is
    /// checked where the command executes, the executor's
    /// `catalog_alter_database`, against the one admitted version,
    /// ADR-0584). Only the token shape (`CYPHER` followed by an
    /// integer) is a hard grammar requirement.
    pub(super) fn parse_cypher_language_name(&mut self) -> ParseResult<u32> {
        if !self.peek_is_ident("cypher") {
            let tok = self.peek().clone();
            return Err(self.error_at_token(
                &tok,
                format!("expected CYPHER in <language name>, got {:?}", tok.literal),
            ));
        }
        self.next_token(); // CYPHER
        let tok = self.next_token();
        if tok.ty != TokenType::Integer {
            return Err(self.error_at_token(
                &tok,
                format!(
                    "expected a version number after CYPHER, got {:?}",
                    tok.literal
                ),
            ));
        }
        tok.literal.parse::<u32>().map_err(|_| {
            self.error_at_token(
                &tok,
                format!("invalid cypher version number: {:?}", tok.literal),
            )
        })
    }

    /// `ALTER DATABASE <name> [IF EXISTS] SET DEFAULT LANGUAGE CYPHER
    /// <n>` (CIP-170) -- under ADR-0116 §2's fixed namespaces this is the
    /// *only* supported `ALTER DATABASE` form: a sole `SET DEFAULT
    /// LANGUAGE` item with no `WAIT` clause. Every other form (`SET
    /// ACCESS`, `SET OPTION`, `REMOVE OPTION`, `SET TOPOLOGY`, any
    /// additional `SET` item, or a trailing `WAIT`/`NOWAIT`) is
    /// recognized and rejected with CE's
    /// `UnsupportedAdministrationCommand`.
    pub(super) fn parse_alter_database(&mut self) -> ParseResult<Clause> {
        let start = self.pos;
        self.next_token(); // consume ALTER
        self.next_token(); // consume DATABASE
        let name = self.parse_required_schema_name("ALTER DATABASE")?;
        let if_exists = self.parse_optional_if_exists()?;
        if self.peek_type() == TokenType::SET && self.peek_at_is_ident(1, "default") {
            self.next_token(); // SET
            let default_language = self.parse_alter_database_default_language()?;
            if matches!(self.peek_type(), TokenType::EOF | TokenType::Semicolon) {
                return Ok(Clause::AlterDatabase(AlterDatabaseClause {
                    name,
                    if_exists,
                    default_language,
                }));
            }
            // A second SET item or a WAIT/NOWAIT clause: recognized but
            // unsupported on fixed namespaces (ADR-0116 §2).
            return self.unsupported_admin_clause(start);
        }
        if self.peek_type() == TokenType::SET || self.peek_type() == TokenType::REMOVE {
            return self.unsupported_admin_clause(start);
        }
        let tok = self.peek().clone();
        Err(self.error_at_token(
            &tok,
            format!(
                "expected SET after ALTER DATABASE ... [IF EXISTS], got {:?}",
                tok.literal
            ),
        ))
    }

    /// The one supported `<alter database set item>`: `DEFAULT LANGUAGE
    /// CYPHER <n>` (ADR-0116 §2). The digits are unvalidated at parse time
    /// -- an out-of-range version is a *runtime* data exception (`22N04`).
    pub(super) fn parse_alter_database_default_language(&mut self) -> ParseResult<u32> {
        self.next_token(); // DEFAULT
        self.expect_keyword_ident("LANGUAGE")?;
        self.parse_cypher_language_name()
    }

    /// The one classification of a `CREATE INDEX`'s `ON` target, owning both
    /// `ON EACH` diagnostics: an `EACH` on a kind that does not take it, and
    /// the missing-`EACH` rejection for FULLTEXT and node LOOKUP indexes. A
    /// relationship LOOKUP index is the one shape that may omit `EACH` (live
    /// Neo4j 2026.09; the node form `ON labels(n)` is rejected there with
    /// 42I06, expected "EACH").
    fn classify_on_target(
        &self,
        kind: IndexKind,
        entity_type: SchemaEntityType,
        each_next: bool,
    ) -> ParseResult<OnTargetForm> {
        match (kind, each_next) {
            (IndexKind::Fulltext, true) => Ok(OnTargetForm::EachBracketList),
            (IndexKind::Lookup, true) => Ok(OnTargetForm::LookupTarget),
            (IndexKind::Lookup, false) if entity_type == SchemaEntityType::Relationship => {
                Ok(OnTargetForm::LookupTarget)
            }
            (IndexKind::Fulltext | IndexKind::Lookup, false) => Err(self.error(
                "InvalidSyntax: FULLTEXT/LOOKUP indexes require ON EACH [...] / ON EACH labels(n)/type(r)",
            )),
            (_, true) => Err(self.error_at_token(
                self.peek(),
                "InvalidSyntax: ON EACH is only supported for FULLTEXT and LOOKUP indexes"
                    .to_string(),
            )),
            (_, false) => Ok(OnTargetForm::PropertyList),
        }
    }

    pub(super) fn parse_create_index(&mut self, kind: IndexKind) -> ParseResult<CreateIndexClause> {
        self.next_token(); // consume INDEX

        let (name, if_not_exists) = self.parse_optional_name_and_if_not_exists()?;

        if self.peek_type() == TokenType::ON {
            let (label, properties) = self.parse_legacy_index_target()?;
            return Ok(CreateIndexClause {
                name,
                entity_type: SchemaEntityType::Node,
                labels: vec![label],
                properties,
                if_not_exists,
                kind,
                on_each: false,
                with_properties: Vec::new(),
                options: OptionsForm::Absent,
            });
        }

        let (entity_type, labels, variable) = self.parse_schema_for_target()?;

        self.expect(TokenType::ON)?;

        let each_next = self.peek_is_ident("each");
        let (properties, on_each) = match self.classify_on_target(kind, entity_type, each_next)? {
            OnTargetForm::LookupTarget => {
                if each_next {
                    self.next_token(); // consume EACH
                }
                self.parse_lookup_each_target(entity_type, &variable)?;
                (Vec::new(), each_next)
            }
            OnTargetForm::EachBracketList => {
                self.next_token(); // consume EACH
                (self.parse_on_each_bracket_list()?, true)
            }
            OnTargetForm::PropertyList => (self.parse_on_property_list()?, false),
        };

        // CIP-235: `WITH [var.prop1, var.prop2, ...]` -- a VECTOR-only
        // clause listing additional filtering properties, positioned
        // between `ON` and `OPTIONS`. Reuses the `ON EACH [...]`
        // bracket-list parser, which already rejects an empty list (CF3)
        // and duplicate properties within the list (CF8) with exactly the
        // shape this clause needs.
        let with_properties = if kind == IndexKind::Vector && self.peek_type() == TokenType::WITH {
            self.next_token(); // consume WITH
            self.parse_on_each_bracket_list()?
        } else {
            Vec::new()
        };

        let options = self.parse_options_tail()?;

        Ok(CreateIndexClause {
            name,
            entity_type,
            labels,
            properties,
            if_not_exists,
            kind,
            on_each,
            with_properties,
            options,
        })
    }

    /// The optional `OPTIONS` tail shared by every schema DDL command:
    /// `OPTIONS { ... }` (a literal map), `OPTIONS $param` (resolved
    /// against the query's parameter map at execution time), or no clause
    /// at all.
    pub(super) fn parse_options_tail(&mut self) -> ParseResult<OptionsForm> {
        if self.peek_type() != TokenType::OPTIONS {
            return Ok(OptionsForm::Absent);
        }
        self.next_token();
        if self.peek_type() == TokenType::Parameter {
            let tok = self.next_token();
            return Ok(OptionsForm::Parameter(tok.literal.into_owned()));
        }
        let pairs = self.parse_map_literal()?;
        // Map-bridge: OPTIONS keys are value-domain map keys (evaluated into
        // a runtime `Value::Map`), not scope names — the one MapPair→value
        // feed; SmallName scope maps (ADR-0509 stage 2) do not change it.
        Ok(OptionsForm::Literal(
            pairs
                .into_iter()
                .map(|p| (p.key.to_string(), p.value))
                .collect(),
        ))
    }

    /// Parses the legacy openCypher index target retained by Relate,
    /// `ON :Label(property[, ...])`, starting at `ON`, for `CREATE INDEX`
    /// and `DROP INDEX`. Returns the label (a keyword included, ADR-0169)
    /// and at least one property name; `parse_drop` rejects a legacy
    /// `DROP INDEX` target with more than one.
    pub(super) fn parse_legacy_index_target(&mut self) -> ParseResult<(SmallName, Vec<SmallName>)> {
        self.expect(TokenType::ON)?;
        self.expect(TokenType::Colon)?;
        let label = self.parse_label_name()?;
        self.expect(TokenType::LeftParen)?;
        let mut properties = vec![self.parse_bare_name("property name")?];
        while self.peek_type() == TokenType::Comma {
            self.next_token();
            properties.push(self.parse_bare_name("property name")?);
        }
        self.expect(TokenType::RightParen)?;
        Ok((label, properties))
    }

    /// One `variable.property` term of a constraint's `REQUIRE` schema. The
    /// variable must be the `FOR` clause's own variable: Neo4j rejects any
    /// other name with 42N62 (`Variable `n` not defined`), before the
    /// constraint reaches validation. The detail tag names that condition so
    /// `EngineError::kind()` surfaces `UndefinedVariable` here too, and the
    /// property name goes through the canonical symbolic-name reader
    /// (ADR-0191: an identifier or a keyword, so `n.order` stays legal) so a
    /// non-name token (`n.$p`) is a parse error, not a property literally
    /// named by it.
    fn parse_constraint_property(
        &mut self,
        variable: &SmallName,
        properties: &mut Vec<SmallName>,
    ) -> ParseResult<()> {
        let var_tok = self.next_token();
        // Text compare against the borrowed token (the one place the
        // FOR-pattern variable is matched); the pushed property names are
        // SmallNames from the shared name readers.
        if variable.with_str(|expected| var_tok.literal != expected) {
            return Err(self
                .error_at_token(
                    &var_tok,
                    format!("Variable `{}` not defined", var_tok.literal),
                )
                .with_detail(crate::parser::UNDEFINED_VARIABLE_DETAIL));
        }
        self.expect(TokenType::Dot)?;
        properties.push(self.parse_schema_name("property name")?);
        Ok(())
    }

    pub(super) fn parse_create_constraint(&mut self) -> ParseResult<CreateConstraintClause> {
        self.next_token(); // consume CONSTRAINT

        let (name, if_not_exists) = self.parse_optional_name_and_if_not_exists()?;

        let ConstraintForTarget {
            entity_type,
            labels,
            variable,
            source_alias,
            target_alias,
        } = self.parse_constraint_for_target_ext()?;
        if labels.len() > 1 {
            return Err(self.error(
                "constraints support only a single label or relationship type, not an A|B|... list",
            ));
        }
        let label = labels.into_iter().next().unwrap_or_default();

        self.expect(TokenType::REQUIRE)?;

        // `REQUIRE <alias>:<Label>` -- a label existence
        // constraint (NLABELEXIST / ESRCLABELEXIST / EDESTLABELEXIST),
        // distinct from every other REQUIRE form (all of which continue
        // with `.` into a property path). Neo4j has no runtime for this
        // (the DDL sketch is explicitly illustrative, not normative),
        // so this is Relate's implementation target derived from the
        // CIP's notation: a node-entity `alias:Label` requires the FOR
        // target's own label to co-occur with `Label`; a relationship
        // entity's `alias` must name one of the pattern's own source/
        // destination endpoint aliases, selecting which endpoint the
        // constraint applies to.
        if self.peek_type().is_ident_like() && self.peek_at(1).ty == TokenType::Colon {
            let alias_tok = self.next_token();
            self.expect(TokenType::Colon)?;
            let target_label = self.parse_label_name()?;
            let constraint_type = match entity_type {
                // Distinct from `"labelExistence"` (only ever created by
                // `ALTER CURRENT GRAPH TYPE`, CIP-187): both render the
                // same `NODE_LABEL_EXISTENCE` SHOW CONSTRAINTS type, but
                // this standalone `CREATE CONSTRAINT` form is an
                // independent constraint, not one the current graph type
                // manages -- see `classification` in `clause::show`.
                SchemaEntityType::Node => "nodeLabelExistence".to_string(),
                SchemaEntityType::Relationship => {
                    if source_alias.as_ref() == Some(&SmallName::from_name(&alias_tok.literal)) {
                        "sourceLabelExistence".to_string()
                    } else if target_alias.as_ref()
                        == Some(&SmallName::from_name(&alias_tok.literal))
                    {
                        "targetLabelExistence".to_string()
                    } else {
                        return Err(self.error_at_token(
                            &alias_tok,
                            format!(
                                "expected the source or destination endpoint alias, got {:?}",
                                alias_tok.literal
                            ),
                        ));
                    }
                }
            };
            return Ok(CreateConstraintClause {
                name,
                entity_type,
                label,
                variable,
                properties: Vec::new(),
                constraint_type,
                if_not_exists,
                property_type: None,
                options: OptionsForm::Absent,
                enforced_label: Some(target_label),
            });
        }

        let mut properties = Vec::new();
        if self.peek_type() == TokenType::LeftParen {
            self.next_token();
            loop {
                self.parse_constraint_property(&variable, &mut properties)?;
                if self.peek_type() != TokenType::Comma {
                    break;
                }
                self.next_token();
            }
            self.expect(TokenType::RightParen)?;
        } else {
            self.parse_constraint_property(&variable, &mut properties)?;
        }
        // 22N75: a composite constraint may not repeat a property.
        let mut seen = std::collections::HashSet::new();
        if properties.iter().any(|property| !seen.insert(property)) {
            return Err(self.error("constraint contains duplicated tokens"));
        }

        // CIP-216 01#2/#4: the bare `x :: <value type>` surface form (CIP-86)
        // is equivalent to `x IS :: <value type>` and skips the `IS` keyword
        // entirely -- checked before the mandatory `expect(IS)` below, which
        // covers every other constraint-verb spelling (all of which require
        // `IS`).
        if self.peek_type() == TokenType::DoubleColon {
            self.next_token();
            let te = self.parse_value_type()?;
            let options = self.parse_options_tail()?;
            return Ok(CreateConstraintClause {
                name,
                entity_type,
                label,
                variable,
                properties,
                constraint_type: "propertyType".to_string(),
                if_not_exists,
                property_type: Some(te),
                options,
                enforced_label: None,
            });
        }

        self.expect(TokenType::IS)?;
        let tok = self.peek().clone();
        let (constraint_type, property_type) = match tok.ty {
            TokenType::UNIQUE => {
                self.next_token();
                ("unique".to_string(), None)
            }
            TokenType::NOT => {
                self.next_token();
                self.expect(TokenType::NULL)?;
                ("exists".to_string(), None)
            }
            // CIP-62: the entity keyword (NODE / REL / RELATIONSHIP) before
            // UNIQUE/KEY is optional and purely documentary -- the real
            // entity comes from the FOR-clause target, already captured in
            // `entity_type` above -- so it's just consumed and discarded
            // here. `IS KEY` with no entity keyword at all is also
            // accepted (bare KEY, matched below).
            TokenType::NODE | TokenType::REL => {
                self.next_token(); // consume NODE/REL
                self.parse_constraint_verb()?
            }
            TokenType::Identifier if tok.literal.eq_ignore_ascii_case("relationship") => {
                self.next_token(); // consume RELATIONSHIP
                self.parse_constraint_verb()?
            }
            TokenType::Identifier if tok.literal.eq_ignore_ascii_case("key") => {
                self.next_token();
                ("key".to_string(), None)
            }
            TokenType::DoubleColon => {
                // REQUIRE (n.prop) IS :: <value type>  (CIP-85 property
                // type constraint, reusing the CIP-86 <value type> parser).
                self.next_token();
                let te = self.parse_value_type()?;
                ("propertyType".to_string(), Some(te))
            }
            _ if self.peek_is_typed_keyword() => {
                // REQUIRE (n.prop) IS TYPED <value type>
                self.next_token();
                let te = self.parse_value_type()?;
                ("propertyType".to_string(), Some(te))
            }
            _ => {
                return Err(self.error_at_token(
                    &tok,
                    format!(
                        "expected UNIQUE, NOT NULL, KEY, NODE/REL[ATIONSHIP] UNIQUE, \
                         NODE/REL[ATIONSHIP] KEY, ::, or TYPED, got {:?}",
                        tok.literal
                    ),
                ));
            }
        };

        let options = self.parse_options_tail()?;

        Ok(CreateConstraintClause {
            name,
            entity_type,
            label,
            variable,
            properties,
            constraint_type,
            if_not_exists,
            property_type,
            options,
            enforced_label: None,
        })
    }

    /// The `UNIQUE`/`KEY` verb following an optional `NODE`/`REL`/
    /// `RELATIONSHIP` entity keyword in `REQUIRE (...) IS [entity] <verb>`
    /// (CIP-62). The entity keyword itself was already consumed by the
    /// caller and discarded -- see the comment at the call site.
    pub(super) fn parse_constraint_verb(&mut self) -> ParseResult<(String, Option<TypeExpr>)> {
        let tok = self.next_token();
        if tok.ty == TokenType::UNIQUE {
            Ok(("unique".to_string(), None))
        } else if tok.literal.eq_ignore_ascii_case("key") {
            Ok(("key".to_string(), None))
        } else {
            Err(self.error_at_token(
                &tok,
                format!("expected UNIQUE or KEY, got {:?}", tok.literal),
            ))
        }
    }

    /// `ALTER CURRENT GRAPH TYPE (SET|ADD|ALTER|DROP) '{' <graph type
    /// specification body> '}'` (CIP-176/182). `SET`/`DROP` are reserved
    /// keywords (`TokenType::SET`/`TokenType::DROP`) everywhere else, so
    /// they're matched directly; `ADD`/`ALTER` are not reserved and are
    /// recognized by spelling like `SHOW`/`USE` elsewhere in this parser.
    pub(super) fn parse_alter_current_graph_type(&mut self) -> ParseResult<Clause> {
        self.next_token(); // consume ALTER
        self.expect_keyword_ident("CURRENT")?;
        self.expect_keyword_ident("GRAPH")?;
        self.expect_keyword_ident("TYPE")?;
        let verb = if self.peek_type() == TokenType::SET {
            self.next_token();
            // ADR-0211: `ALTER CURRENT GRAPH TYPE SET GRAPH TYPE <name>`
            // promotes a `CREATE GRAPH TYPE`-declared named type to current,
            // instead of taking a `{ <body> }`.
            if self.peek_is_ident("graph") && self.peek_at_is_ident(1, "type") {
                self.next_token(); // GRAPH
                self.next_token(); // TYPE
                let name = self.parse_bare_name("identifier")?;
                return Ok(Clause::AlterCurrentGraphType(AlterCurrentGraphTypeClause {
                    verb: AlterGraphTypeVerb::Set,
                    target: AlterCurrentGraphTypeTarget::Named(name),
                }));
            }
            AlterGraphTypeVerb::Set
        } else if self.peek_type() == TokenType::DROP {
            self.next_token();
            AlterGraphTypeVerb::Drop
        } else if self.peek_is_ident("add") {
            self.next_token();
            AlterGraphTypeVerb::Add
        } else if self.peek_is_ident("alter") {
            self.next_token();
            AlterGraphTypeVerb::Alter
        } else {
            let tok = self.peek().clone();
            return Err(self.error_at_token(
                &tok,
                format!("expected SET, ADD, ALTER, or DROP, got {:?}", tok.literal),
            ));
        };
        // CIP-182: only a `DROP` body's grammar allows the bare `CONSTRAINT
        // <name>` (no `FOR ...`) drop-by-name element, and a `DROP` body
        // drops a constraint by name only.
        let (open, body) = self.parse_graph_type_spec_body()?;
        if verb == AlterGraphTypeVerb::Drop {
            self.reject_undesignated_constraint_drops(&open, &body)?;
        } else {
            self.reject_bare_constraint_drops(&open, &body)?;
        }
        Ok(Clause::AlterCurrentGraphType(AlterCurrentGraphTypeClause {
            verb,
            target: AlterCurrentGraphTypeTarget::Body(body),
        }))
    }

    /// `CREATE GRAPH TYPE <name> [AS] '{' <graph type specification body>
    /// '}'` (CIP-178 grammar; the optional `AS` is CIP-180's spelling of
    /// the same body-introducing form). Not a reserved keyword sequence --
    /// `parse_create`'s dispatch recognizes `GRAPH TYPE` by spelling before
    /// calling this.
    pub(super) fn parse_create_graph_type(&mut self) -> ParseResult<Clause> {
        self.expect_keyword_ident("GRAPH")?;
        self.expect_keyword_ident("TYPE")?;
        let name = self.parse_bare_name("identifier")?;
        let via_as = self.peek_type() == TokenType::AS;
        if via_as {
            self.next_token();
        }
        let (open, body) = self.parse_graph_type_spec_body()?;
        self.reject_bare_constraint_drops(&open, &body)?;
        Ok(Clause::CreateGraphType(CreateGraphTypeClause {
            name,
            body,
            via_as,
        }))
    }

    /// `'{' [ <graph type spec element> (',' <graph type spec element>)*
    /// ] '}'` (`<graph type specification body>`). Grammar-only:
    /// see `GraphTypeBody`'s doc comment for why the CIP-178 semantic
    /// rules live elsewhere. Returns the consumed opening `{` with the body,
    /// the token `reject_bare_constraint_drops` and
    /// `reject_undesignated_constraint_drops` errors point at.
    pub(super) fn parse_graph_type_spec_body(&mut self) -> ParseResult<(Token<'a>, GraphTypeBody)> {
        let open = self.expect(TokenType::LeftBrace)?;
        let mut body = GraphTypeBody::default();
        if self.peek_type() != TokenType::RightBrace {
            loop {
                self.parse_graph_type_element(&mut body)?;
                if self.peek_type() == TokenType::Comma {
                    self.next_token();
                    continue;
                }
                break;
            }
        }
        self.expect(TokenType::RightBrace)?;
        Ok((open, body))
    }

    /// Rejects a parsed `body` holding a bare `CONSTRAINT <name>`
    /// drop-by-name element: only an `ALTER CURRENT GRAPH TYPE DROP` body's
    /// grammar has one, every other body's `CONSTRAINT` needs its `FOR ...`
    /// specification. The error points at `open`, the body's `{`.
    pub(super) fn reject_bare_constraint_drops(
        &self,
        open: &Token,
        body: &GraphTypeBody,
    ) -> ParseResult<()> {
        match body.drop_constraint_names.first() {
            None => Ok(()),
            Some(name) => Err(self.error_at_token(
                open,
                format!(
                    "constraint {name:?} has no FOR specification; only ALTER CURRENT GRAPH TYPE DROP names a constraint without one"
                ),
            )),
        }
    }

    /// Rejects an `ALTER CURRENT GRAPH TYPE DROP` `body` holding an
    /// undesignated (unnamed) `CONSTRAINT FOR ...` specification: such a
    /// constraint can only be dropped by name. A
    /// standalone specification's reference always has an alias
    /// (`parse_graph_type_constraint_spec` enforces this), which tells it apart from the
    /// unnamed constraints a node/edge type specification owns
    /// (`parse_graph_type_owned_constraints`). The error points at `open`,
    /// the body's `{`.
    pub(super) fn reject_undesignated_constraint_drops(
        &self,
        open: &Token,
        body: &GraphTypeBody,
    ) -> ParseResult<()> {
        let undesignated = body.constraints.iter().any(|c| {
            c.name.is_none() && !matches!(c.target, GraphTypeElementRef::InSitu { alias: None, .. })
        });
        if undesignated {
            return Err(self.error_at_token(
                open,
                "undesignated constraints cannot be dropped by specification",
            ));
        }
        Ok(())
    }

    /// One comma-separated top-level element of a `<graph type
    /// specification body>`: a `CONSTRAINT` specification, or a node type
    /// specification `(...)` -- the source endpoint reference of an edge
    /// type specification when a `-` follows it. Either type specification
    /// may end in an inline `REQUIRE ...` constraint list (see
    /// `parse_graph_type_owned_constraints`).
    pub(super) fn parse_graph_type_element(&mut self, body: &mut GraphTypeBody) -> ParseResult<()> {
        if self.peek_type() == TokenType::CONSTRAINT {
            return self.parse_graph_type_constraint_element(body);
        }

        self.expect(TokenType::LeftParen)?;
        let (alias, label, implies) = self.parse_graph_type_ref()?;
        let mut implied_labels = Vec::new();
        if implies && matches!(self.peek_type(), TokenType::Colon | TokenType::IS) {
            self.next_token();
            implied_labels.push(self.parse_label_name()?);
            while self.peek_type() == TokenType::Ampersand {
                self.next_token();
                // Each subsequent `&`-joined label may repeat its own
                // `:`/IS introducer (`:Zebra&:Mango`), or omit it
                // (`:Happy&Employed`) -- both spellings denote the same
                // implied label set.
                if matches!(self.peek_type(), TokenType::Colon | TokenType::IS) {
                    self.next_token();
                }
                implied_labels.push(self.parse_label_name()?);
            }
        }
        let properties = self.parse_graph_type_property_block(implies, "Node")?;
        self.expect(TokenType::RightParen)?;

        if self.peek_type() == TokenType::Dash {
            // Edge type specification: the just-parsed `(...)` was its
            // source endpoint reference (`implies` is significant here --
            // an implies reference must name a declared node type -- so
            // it's threaded through rather than discarded).
            let source = Self::build_graph_type_ref_implies(alias, label, implies);
            return self.parse_graph_type_edge_tail(body, source);
        }
        let node = GraphTypeNodeTypeSpec {
            alias,
            identifying_label: label.unwrap_or_default(),
            implied_labels,
            properties,
        };
        self.parse_graph_type_node_tail(body, node)
    }

    /// A `CONSTRAINT` element of a `<graph type specification body>`,
    /// starting at `CONSTRAINT`: a CIP-182 bare drop-by-name, else a full
    /// constraint specification.
    pub(super) fn parse_graph_type_constraint_element(
        &mut self,
        body: &mut GraphTypeBody,
    ) -> ParseResult<()> {
        // `<constraint drop specification>` ::= `CONSTRAINT
        // <name>` -- a bare name with no `FOR ...`, so the element ends
        // right after the name. It is read in every body; the callers of
        // every verb but `DROP` reject it (`reject_bare_constraint_drops`).
        // Ending the lookahead at `,`/`}` rather than "anything but `FOR`"
        // keeps an unnamed `CONSTRAINT FOR ...` specification from reading
        // `FOR` as the constraint name (a `DROP` caller rejects that
        // specification instead -- `reject_undesignated_constraint_drops`).
        if self.peek_at(1).ty.is_ident_like()
            && matches!(self.peek_at(2).ty, TokenType::Comma | TokenType::RightBrace)
        {
            self.next_token(); // consume CONSTRAINT
            let name = self.parse_bare_name("identifier")?;
            body.drop_constraint_names.push(name);
            return Ok(());
        }
        let c = self.parse_graph_type_constraint_spec()?;
        body.constraints.push(c);
        Ok(())
    }

    /// The rest of a node type specification once its `(...)` is parsed:
    /// the trailing inline `REQUIRE ...` list. Records `node` and every
    /// constraint it owns in `body`.
    pub(super) fn parse_graph_type_node_tail(
        &mut self,
        body: &mut GraphTypeBody,
        node: GraphTypeNodeTypeSpec,
    ) -> ParseResult<()> {
        let constraints = self.parse_graph_type_owned_constraints(
            &node.properties,
            &node.identifying_label,
            false,
            node.alias.as_ref(),
        )?;
        body.constraints.extend(constraints);
        body.node_types.push(node);
        Ok(())
    }

    /// The rest of an edge type specification once its `source` endpoint
    /// reference is parsed: `'-' '[' <edge type head> ']' '->' <destination
    /// endpoint>` and the trailing inline `REQUIRE ...` list. Records the
    /// edge type and every constraint it owns in `body`.
    pub(super) fn parse_graph_type_edge_tail(
        &mut self,
        body: &mut GraphTypeBody,
        source: GraphTypeElementRef,
    ) -> ParseResult<()> {
        self.next_token(); // consume '-'
        self.expect(TokenType::LeftBracket)?;
        let (alias, label, implies) = self.parse_graph_type_ref()?;
        let identifying_label = label.unwrap_or_default();
        let properties = self.parse_graph_type_property_block(implies, "Edge")?;
        self.expect(TokenType::RightBracket)?;
        self.expect(TokenType::ArrowRight)?;
        self.expect(TokenType::LeftParen)?;
        let (t_alias, t_label, t_implies) = self.parse_graph_type_ref()?;
        self.expect(TokenType::RightParen)?;
        let target = Self::build_graph_type_ref_implies(t_alias, t_label, t_implies);

        let constraints = self.parse_graph_type_owned_constraints(
            &properties,
            &identifying_label,
            true,
            alias.as_ref(),
        )?;
        body.constraints.extend(constraints);
        body.edge_types.push(GraphTypeEdgeTypeSpec {
            alias,
            identifying_label,
            properties,
            source,
            target,
        });
        Ok(())
    }

    /// The constraints a node/edge type specification owns, all targeting
    /// its own identifying label (CIP-178 Rules 10-12): one per property
    /// carrying an inline constraint, then one per trailing inline
    /// `REQUIRE ...`. `owner_alias` is the specification's own alias.
    pub(super) fn parse_graph_type_owned_constraints(
        &mut self,
        properties: &[GraphTypePropertyType],
        identifying_label: &SmallName,
        is_edge: bool,
        owner_alias: Option<&SmallName>,
    ) -> ParseResult<Vec<GraphTypeConstraintSpec>> {
        let mut constraints =
            Self::take_property_inline_constraints(properties, identifying_label, is_edge);
        let own_ref = GraphTypeElementRef::InSitu {
            alias: None,
            label: identifying_label.clone(),
            implies: true,
        };
        while self.peek_type() == TokenType::REQUIRE {
            constraints.push(self.parse_graph_type_inline_require(
                own_ref.clone(),
                is_edge,
                owner_alias,
            )?);
        }
        Ok(constraints)
    }

    /// `[alias] [(':'|IS) <label>]` -- the alias/label pair shared by every
    /// `<node type reference>`/`<edge type reference>`/`<node type
    /// specification>`/`<edge type specification>` head. `IS` is a
    /// reserved token (never itself a legal alias in this grammar), so
    /// checking for it before the ident-like alias check disambiguates
    /// `(p IS Person => ...)` (alias `p`) from a hypothetical alias-less
    /// `IS`-introduced label. The label may be a keyword (ADR-0169); the
    /// alias may not.
    pub(super) fn parse_graph_type_ref_inner(
        &mut self,
    ) -> ParseResult<(Option<SmallName>, Option<SmallName>)> {
        let mut alias = None;
        if self.peek_type().is_ident_like() && self.peek_type() != TokenType::IS {
            alias = Some(self.parse_bare_name("identifier")?);
        }
        let mut label = None;
        if self.peek_type() == TokenType::Colon || self.peek_type() == TokenType::IS {
            self.next_token();
            label = Some(self.parse_label_name()?);
        }
        Ok((alias, label))
    }

    /// Consumes a `=>` or `IMPLIES` token if present; returns whether one
    /// was found.
    pub(super) fn consume_graph_type_implies(&mut self) -> bool {
        if self.peek_type() == TokenType::FatArrow || self.peek_is_ident("implies") {
            self.next_token();
            true
        } else {
            false
        }
    }

    /// `'{' [ <property type> (',' <property type>)* ] '}'` (CIP-178
    /// `<property types specification>`). `<property type> ::= <name>
    /// [('::'|TYPED)] <value type> [DEFAULT ON COMMIT <value expression>]
    /// [<inline constraint>]` (with the `DEFAULT ON COMMIT` clause;
    /// grammar-only here, the shape and the preview gate live in the
    /// semantic layer and statement admission).
    pub(super) fn parse_graph_type_property_types(
        &mut self,
    ) -> ParseResult<Vec<GraphTypePropertyType>> {
        self.expect(TokenType::LeftBrace)?;
        let mut props = Vec::new();
        if self.peek_type() != TokenType::RightBrace {
            loop {
                let name = self.parse_bare_name("identifier")?;
                // ADR-0211: `<name> IS [::] <value type>` is the GQL
                // spelling of `<name> :: <value type>`. The optional `IS`
                // introducer is consumed once, guarded by the inline-
                // constraint lookahead (`IS KEY`/`IS UNIQUE` belong to the
                // constraint parsed below); the `::`/TYPED introducer then
                // has a single branch.
                if self.peek_type() == TokenType::IS
                    && !self.peek_starts_graph_type_inline_constraint()
                {
                    self.next_token(); // consume IS
                }
                if self.peek_type() == TokenType::DoubleColon || self.peek_is_typed_keyword() {
                    self.next_token();
                }
                let value_type = self.parse_value_type()?;
                let default_value = self.parse_graph_type_property_default()?;
                let inline_constraint = if self.peek_type() == TokenType::IS {
                    Some(self.parse_graph_type_inline_property_constraint()?)
                } else {
                    None
                };
                props.push(GraphTypePropertyType {
                    name,
                    value_type,
                    default_value,
                    inline_constraint,
                });
                if self.peek_type() != TokenType::Comma {
                    break;
                }
                self.next_token();
            }
        }
        self.expect(TokenType::RightBrace)?;
        Ok(props)
    }

    /// The optional `DEFAULT ON COMMIT <value expression>` clause of a
    /// graph-type `<property type>` (CIP-262): `DEFAULT` and `COMMIT` are
    /// non-reserved words, so both match as bare identifiers; `ON` is the
    /// keyword token. The value is the ordinary expression parser's -- its
    /// existing nesting-depth limit (ADR-0079) covers the clause, so no
    /// new recursion family is introduced. Shape (literal or type
    /// constructor, never `null`) is the semantic layer's to enforce.
    fn parse_graph_type_property_default(&mut self) -> ParseResult<Option<Expr>> {
        if !self.peek_is_ident("default") {
            return Ok(None);
        }
        self.next_token(); // consume DEFAULT
        self.expect(TokenType::ON)?;
        if !self.peek_is_ident("commit") {
            return Err(self.error_at_token(
                self.peek(),
                "expected COMMIT after DEFAULT ON in a property type".to_string(),
            ));
        }
        self.next_token(); // consume COMMIT
        Ok(Some(self.parse_expression()?))
    }

    /// The `{ <property types> }` block of a node/edge type specification.
    /// The `=>`/`IMPLIES` marker (the `implies` flag, consumed by the
    /// caller) is what makes the preceding label the *explicitly denoted
    /// identifying label*, so a bare `{` without it is a compile-time
    /// syntax error (CIP-178/181/183; current Neo4j rejects the bare
    /// `(:Label {…})` form); no block at all is an empty property list.
    /// One policy for both the node and the edge type-spec parsers.
    fn parse_graph_type_property_block(
        &mut self,
        implies: bool,
        entity: &str,
    ) -> ParseResult<Vec<GraphTypePropertyType>> {
        if self.peek_type() != TokenType::LeftBrace {
            return Ok(Vec::new());
        }
        if !implies {
            return Err(self.error_at_token(
                self.peek(),
                format!(
                    "{entity} type does not have an explicitly denoted identifying label \
                     (use `=>` or `IMPLIES` after the label before the property block)"
                ),
            ));
        }
        self.parse_graph_type_property_types()
    }

    /// A KEY/UNIQUE token mapped to its inline-constraint verb (UNIQUE is a
    /// keyword token, KEY a non-reserved identifier) — the single definition
    /// of the verb token set both the inline-constraint lookahead and its
    /// parser use.
    fn inline_verb_from_token(tok: &Token) -> Option<GraphTypeInlineVerb> {
        match tok.ty {
            TokenType::UNIQUE => Some(GraphTypeInlineVerb::Unique),
            TokenType::Identifier if Self::token_is_ident(tok, "key") => {
                Some(GraphTypeInlineVerb::Key)
            }
            _ => None,
        }
    }

    /// An entity qualifier token (NODE / REL / identifier `relationship`)
    /// mapped to its qualifier — the single definition of the qualifier
    /// token set both the lookahead and the parser use.
    fn entity_qualifier_from_token(tok: &Token) -> Option<GraphTypeEntityQualifier> {
        match tok.ty {
            TokenType::NODE => Some(GraphTypeEntityQualifier::Node),
            TokenType::REL => Some(GraphTypeEntityQualifier::Rel),
            TokenType::Identifier if Self::token_is_ident(tok, "relationship") => {
                Some(GraphTypeEntityQualifier::Rel)
            }
            _ => None,
        }
    }

    /// Whether the tokens after a property declaration's `IS` (not yet
    /// consumed) start an inline constraint -- `IS KEY`, `IS UNIQUE`, or
    /// `IS NODE/REL/RELATIONSHIP KEY|UNIQUE` -- rather than an ADR-0211
    /// `IS [::] <value type>` type declaration.
    pub(super) fn peek_starts_graph_type_inline_constraint(&self) -> bool {
        if Self::inline_verb_from_token(self.peek_at(1)).is_some() {
            return true;
        }
        Self::entity_qualifier_from_token(self.peek_at(1)).is_some()
            && Self::inline_verb_from_token(self.peek_at(2)).is_some()
    }

    /// `IS [NODE|REL|RELATIONSHIP] (KEY|UNIQUE)` -- an inline property-type
    /// constraint.
    pub(super) fn parse_graph_type_inline_property_constraint(
        &mut self,
    ) -> ParseResult<GraphTypeInlineConstraint> {
        self.expect(TokenType::IS)?;
        let qualifier = Self::entity_qualifier_from_token(self.peek());
        if qualifier.is_some() {
            self.next_token();
        }
        let tok = self.next_token();
        match Self::inline_verb_from_token(&tok) {
            Some(verb) => Ok(GraphTypeInlineConstraint { verb, qualifier }),
            None => Err(self.error_at_token(
                &tok,
                format!("expected KEY or UNIQUE, got {:?}", tok.literal),
            )),
        }
    }

    /// Rewrites every property in `properties` carrying an inline
    /// constraint into a standalone `GraphTypeConstraintSpec` targeting the
    /// owning node/edge type's own identifying label (CIP-178 Rules 10,
    /// 12).
    pub(super) fn take_property_inline_constraints(
        properties: &[GraphTypePropertyType],
        identifying_label: &SmallName,
        is_edge: bool,
    ) -> Vec<GraphTypeConstraintSpec> {
        properties
            .iter()
            .filter_map(|p| {
                p.inline_constraint.map(|ic| GraphTypeConstraintSpec {
                    name: None,
                    target: GraphTypeElementRef::InSitu {
                        alias: None,
                        label: identifying_label.clone(),
                        implies: true,
                    },
                    is_edge,
                    properties: vec![p.name.clone()],
                    kind: match ic.verb {
                        GraphTypeInlineVerb::Key => GraphTypeConstraintVerb::Key,
                        GraphTypeInlineVerb::Unique => GraphTypeConstraintVerb::Unique,
                    },
                    property_type: None,
                    options: OptionsForm::Absent,
                })
            })
            .collect()
    }

    /// A node/edge type specification's trailing inline `REQUIRE
    /// <property name spec> <verb> [OPTIONS <map>]` (no `CONSTRAINT`
    /// keyword, no name -- CIP-178 Rules 11/12). `target` is always the
    /// owning element's own identifying label, in-situ-identified form (see
    /// `parse_graph_type_owned_constraints`). `owner_alias` is the owning
    /// node/edge type specification's own declared element type alias, if
    /// any -- every alias used in the REQUIRE list must match it exactly.
    pub(super) fn parse_graph_type_inline_require(
        &mut self,
        target: GraphTypeElementRef,
        is_edge: bool,
        owner_alias: Option<&SmallName>,
    ) -> ParseResult<GraphTypeConstraintSpec> {
        self.next_token(); // consume REQUIRE
        let properties =
            self.parse_graph_type_property_name_spec_for_owner(owner_alias, is_edge)?;
        let GraphTypeConstraintVerbSpec {
            kind,
            property_type,
            options,
        } = self.parse_graph_type_constraint_verb()?;
        // In the grammar, `<node/edge type inline constraint require>` is
        // only ever a KEY or UNIQUE constraint require -- existence
        // (`IS NOT NULL`) and property type (`:: T`) constraints are not
        // grammatically reachable when attached directly to a node/edge
        // type specification's trailing `REQUIRE` (only via the standalone
        // `CONSTRAINT FOR` form or an inline property constraint).
        if matches!(
            kind,
            GraphTypeConstraintVerb::Exists | GraphTypeConstraintVerb::PropertyType
        ) {
            let kind_word = if is_edge { "edge" } else { "node" };
            let verb_word = if matches!(kind, GraphTypeConstraintVerb::Exists) {
                "existence"
            } else {
                "type"
            };
            return Err(self.error(format!(
                "Unsupported syntax — {kind_word} type property {verb_word} constraints cannot be specified inline of a {kind_word} type"
            )));
        }
        Ok(GraphTypeConstraintSpec {
            name: None,
            target,
            is_edge,
            properties,
            kind,
            property_type,
            options,
        })
    }

    /// `CONSTRAINT [<name>] FOR <node/edge type reference> REQUIRE
    /// <property name spec> <verb> [OPTIONS <map>]` (CIP-178 `<constraint
    /// specification>`). Enforces the purely-local rules that don't need
    /// cross-element context: the any type is forbidden, a labelled
    /// reference requires an element type alias, the property name spec's
    /// own alias must match the reference's, no duplicate property name in
    /// the spec, and the "existence/property-type constraints are not
    /// allowed on a structurally-identified reference" rule. Rules needing
    /// the *whole* body (5-9, 14, 15/16, reference resolution) are checked
    /// by the engine's graph-type validator.
    pub(super) fn parse_graph_type_constraint_spec(
        &mut self,
    ) -> ParseResult<GraphTypeConstraintSpec> {
        self.expect(TokenType::CONSTRAINT)?;
        let name = if self.peek_type() == TokenType::FOR {
            None
        } else {
            Some(self.parse_bare_name("identifier")?)
        };
        self.expect(TokenType::FOR)?;
        let (is_edge, target) = self.parse_graph_type_constraint_target()?;

        let expected_alias = match &target {
            GraphTypeElementRef::Any => {
                return Err(self.error("constraint may not reference the any node type"));
            }
            GraphTypeElementRef::AliasRef(a) => Some(a.clone()),
            GraphTypeElementRef::InSitu { alias: Some(a), .. } => Some(a.clone()),
            GraphTypeElementRef::InSitu { alias: None, .. } => {
                return Err(self.error(if is_edge {
                    "edge type constraint reference requires an element type alias"
                } else {
                    "node type constraint reference requires an element type alias"
                }));
            }
        };

        self.expect(TokenType::REQUIRE)?;
        let properties = self.parse_graph_type_property_name_spec(expected_alias.as_ref())?;
        let GraphTypeConstraintVerbSpec {
            kind,
            property_type,
            options,
        } = self.parse_graph_type_constraint_verb()?;

        // Rules 22/23: existence/property-type constraints are not allowed
        // on a structurally-identified reference (an alias reference always
        // resolves to a declared type; an in-situ reference with `=>` must
        // resolve to one).
        let locally_identified = matches!(target, GraphTypeElementRef::AliasRef(_))
            || matches!(target, GraphTypeElementRef::InSitu { implies: true, .. });
        if locally_identified
            && matches!(
                kind,
                GraphTypeConstraintVerb::Exists | GraphTypeConstraintVerb::PropertyType
            )
        {
            return Err(self.error(
                "existence/property type constraints are not allowed on a designated node type",
            ));
        }

        Ok(GraphTypeConstraintSpec {
            name,
            target,
            is_edge,
            properties,
            kind,
            property_type,
            options,
        })
    }

    /// Parses a `<constraint specification>`'s `FOR` target: `'(' ...  ')'`
    /// for a node type reference, or `'(' ')' '-' '[' ... ']' '->' '(' ')'`
    /// for an edge type reference (both node-parens empty). Returns
    /// `(is_edge, reference)`.
    pub(super) fn parse_graph_type_constraint_target(
        &mut self,
    ) -> ParseResult<(bool, GraphTypeElementRef)> {
        self.expect(TokenType::LeftParen)?;
        if self.peek_type() == TokenType::RightParen && self.peek_at(1).ty == TokenType::Dash {
            self.next_token(); // consume ')'
            self.expect(TokenType::Dash)?;
            self.expect(TokenType::LeftBracket)?;
            let (alias, label, implies) = self.parse_graph_type_ref()?;
            self.expect(TokenType::RightBracket)?;
            self.expect(TokenType::ArrowRight)?;
            self.expect(TokenType::LeftParen)?;
            self.expect(TokenType::RightParen)?;
            return Ok((
                true,
                Self::build_graph_type_ref_implies(alias, label, implies),
            ));
        }
        let (alias, label, implies) = self.parse_graph_type_ref()?;
        self.expect(TokenType::RightParen)?;
        Ok((
            false,
            Self::build_graph_type_ref_implies(alias, label, implies),
        ))
    }

    /// A `<graph type reference>` head plus its `=>`/`IMPLIES` marker: the
    /// alias/label pair of [`Parser::parse_graph_type_ref_inner`] with the
    /// implies marker consumed behind it — the marker only counts, and is
    /// only consumed, behind a label; `[: => {...}]` has no identifying
    /// label to denote. The five reference positions (a node/edge type
    /// specification's own head, an edge's destination endpoint, and the
    /// two shapes of a constraint `FOR`-target) all spell exactly this.
    pub(super) fn parse_graph_type_ref(
        &mut self,
    ) -> ParseResult<(Option<SmallName>, Option<SmallName>, bool)> {
        let (alias, label) = self.parse_graph_type_ref_inner()?;
        let implies = label.is_some() && self.consume_graph_type_implies();
        Ok((alias, label, implies))
    }

    /// Builds a `GraphTypeElementRef` from a parsed alias/label/implies
    /// triple -- shared by node/edge type spec endpoints and constraint
    /// `FOR`-targets, where `=>` presence is semantically meaningful
    /// (an implies reference must name a declared identifying label;
    /// existence/property-type constraints are not allowed on a
    /// structurally-identified reference). CIP-178's edge-endpoint rule
    /// (an edge type's own in-situ
    /// endpoint reference may not carry an alias) and the constraint
    /// `FOR`-target rules (the any type is forbidden, a labelled
    /// reference requires an alias) are cross-referential/context-dependent
    /// and are checked by the engine's graph-type validator, not here.
    pub(super) fn build_graph_type_ref_implies(
        alias: Option<SmallName>,
        label: Option<SmallName>,
        implies: bool,
    ) -> GraphTypeElementRef {
        match (alias, label) {
            (None, None) => GraphTypeElementRef::Any,
            (Some(a), None) => GraphTypeElementRef::AliasRef(a),
            (alias, Some(l)) => GraphTypeElementRef::InSitu {
                alias,
                label: l,
                implies,
            },
        }
    }

    /// `<alias>.<prop>` / `'(' <alias>.<prop> (',' <alias>.<prop>)* ')'`
    /// (`<property name specification>`), returning the raw
    /// `(alias, property)` pairs in source order without any alias
    /// validation -- shared by `parse_graph_type_property_name_spec` (the
    /// standalone `CONSTRAINT FOR` form, which already knows a single
    /// `expected_alias`) and `parse_graph_type_inline_require`'s owner-alias
    /// check (which needs to report every *distinct* offending alias, not
    /// just detect a mismatch).
    pub(super) fn parse_graph_type_property_name_entries(
        &mut self,
    ) -> ParseResult<Vec<(SmallName, SmallName)>> {
        let mut entries: Vec<(SmallName, SmallName)> = Vec::new();
        if self.peek_type() == TokenType::LeftParen {
            self.next_token();
            loop {
                let alias = self.parse_bare_name("identifier")?;
                self.expect(TokenType::Dot)?;
                let prop = self.parse_bare_name("identifier")?;
                entries.push((alias, prop));
                if self.peek_type() != TokenType::Comma {
                    break;
                }
                self.next_token();
            }
            self.expect(TokenType::RightParen)?;
        } else {
            let alias = self.parse_bare_name("identifier")?;
            self.expect(TokenType::Dot)?;
            let prop = self.parse_bare_name("identifier")?;
            entries.push((alias, prop));
        }
        Ok(entries)
    }

    /// `<alias>.<prop>` / `'(' <alias>.<prop> (',' <alias>.<prop>)* ')'`
    /// (`<property name specification>`). When `expected_alias` is
    /// given, every entry's alias must match it; duplicate
    /// property names within the spec are always rejected.
    pub(super) fn parse_graph_type_property_name_spec(
        &mut self,
        expected_alias: Option<&SmallName>,
    ) -> ParseResult<Vec<SmallName>> {
        let entries = self.parse_graph_type_property_name_entries()?;
        if let Some(expected) = expected_alias {
            if entries.iter().any(|(a, _)| a != expected) {
                return Err(self.error("property name alias must match the reference alias"));
            }
        }
        let mut props = Vec::new();
        for (_, p) in entries {
            if props.contains(&p) {
                return Err(self.error("duplicate property name in property names specification"));
            }
            props.push(p);
        }
        Ok(props)
    }

    /// The `<property names specification>` of a node/edge type
    /// specification's trailing inline `REQUIRE` list (CIP-178 `<node/edge
    /// type inline constraint require>`). Unlike the standalone `CONSTRAINT
    /// FOR` form (`parse_graph_type_property_name_spec`, which always has a
    /// declared reference alias to compare against), the owning node/edge
    /// type specification may not have declared an alias at all
    /// (`owner_alias: None`) -- in which case *any* alias used in the
    /// REQUIRE list is undefined, not just a non-matching one.
    pub(super) fn parse_graph_type_property_name_spec_for_owner(
        &mut self,
        owner_alias: Option<&SmallName>,
        is_edge: bool,
    ) -> ParseResult<Vec<SmallName>> {
        let entries = self.parse_graph_type_property_name_entries()?;
        let mut undefined: Vec<SmallName> = Vec::new();
        for (a, _) in &entries {
            if Some(a) != owner_alias && !undefined.contains(a) {
                undefined.push(a.clone());
            }
        }
        if !undefined.is_empty() {
            let kind = if is_edge { "Edge" } else { "Node" };
            let (noun, list) = if undefined.len() == 1 {
                ("alias", undefined[0].to_string())
            } else {
                (
                    "aliases",
                    undefined
                        .iter()
                        .map(SmallName::to_string)
                        .collect::<Vec<_>>()
                        .join(" and "),
                )
            };
            return Err(self.error(format!(
                "{kind} type constraint uses undefined type {noun} {list}"
            )));
        }
        let mut props = Vec::new();
        for (_, p) in entries {
            if props.contains(&p) {
                return Err(self.error("duplicate property name in property names specification"));
            }
            props.push(p);
        }
        Ok(props)
    }

    /// The constraint verb tail of a `<constraint specification>` (CIP-178
    /// CS grammar), starting right after the `<property name spec>`:
    /// either a bare `:: <value type>` or `IS (KEY | [NODE|REL|
    /// RELATIONSHIP] KEY | UNIQUE | [NODE|REL|RELATIONSHIP] UNIQUE | NOT
    /// NULL | (::|TYPED) <value type>)`, followed by an optional `OPTIONS
    /// <map>`. Mirrors (but does not share code with) the top-level
    /// `CREATE CONSTRAINT` verb grammar in `parse_create_constraint` --
    /// unlike that grammar, the entity qualifier here is never restricted
    /// by context (CIP-178 doesn't test a mismatch).
    pub(super) fn parse_graph_type_constraint_verb(
        &mut self,
    ) -> ParseResult<GraphTypeConstraintVerbSpec> {
        if self.peek_type() == TokenType::DoubleColon {
            self.next_token();
            let te = self.parse_value_type()?;
            let options = self.parse_options_tail()?;
            return Ok(GraphTypeConstraintVerbSpec {
                kind: GraphTypeConstraintVerb::PropertyType,
                property_type: Some(te),
                options,
            });
        }
        self.expect(TokenType::IS)?;
        let tok = self.peek().clone();
        let (verb, property_type) = match tok.ty {
            TokenType::UNIQUE => {
                self.next_token();
                (GraphTypeConstraintVerb::Unique, None)
            }
            TokenType::NOT => {
                self.next_token();
                self.expect(TokenType::NULL)?;
                (GraphTypeConstraintVerb::Exists, None)
            }
            TokenType::NODE | TokenType::REL => {
                self.next_token();
                self.parse_graph_type_constraint_kw_verb()?
            }
            TokenType::Identifier if tok.literal.eq_ignore_ascii_case("relationship") => {
                self.next_token();
                self.parse_graph_type_constraint_kw_verb()?
            }
            TokenType::Identifier if tok.literal.eq_ignore_ascii_case("key") => {
                self.next_token();
                (GraphTypeConstraintVerb::Key, None)
            }
            TokenType::DoubleColon => {
                self.next_token();
                let te = self.parse_value_type()?;
                (GraphTypeConstraintVerb::PropertyType, Some(te))
            }
            _ if self.peek_is_typed_keyword() => {
                self.next_token();
                let te = self.parse_value_type()?;
                (GraphTypeConstraintVerb::PropertyType, Some(te))
            }
            _ => {
                return Err(self.error_at_token(
                    &tok,
                    format!(
                        "expected UNIQUE, NOT NULL, KEY, ::, or TYPED, got {:?}",
                        tok.literal
                    ),
                ));
            }
        };
        let options = self.parse_options_tail()?;
        Ok(GraphTypeConstraintVerbSpec {
            kind: verb,
            property_type,
            options,
        })
    }

    pub(super) fn parse_graph_type_constraint_kw_verb(
        &mut self,
    ) -> ParseResult<(GraphTypeConstraintVerb, Option<TypeExpr>)> {
        let tok = self.next_token();
        if tok.ty == TokenType::UNIQUE {
            Ok((GraphTypeConstraintVerb::Unique, None))
        } else if tok.literal.eq_ignore_ascii_case("key") {
            Ok((GraphTypeConstraintVerb::Key, None))
        } else {
            Err(self.error_at_token(
                &tok,
                format!("expected UNIQUE or KEY, got {:?}", tok.literal),
            ))
        }
    }

    /// `TERMINATE TRANSACTION[S] <id-list> [YIELD ...]` (CIP-68 grammar
    /// foundation). Not a `SHOW` spelling -- a separate top-level
    /// context-sensitive keyword, same recognition technique.
    pub(super) fn parse_terminate_transactions(&mut self) -> ParseResult<Clause> {
        self.next_token(); // consume TERMINATE

        // TRANSACTION has no reserved token of its own, so the
        // identifier-spelling check is the whole gate (same technique as
        // FUNCTION(S)/DEFINED).
        self.expect_kind_word(
            TokenType::Identifier,
            "transaction",
            Some("transactions"),
            "TRANSACTION(S) after TERMINATE",
        )?;

        let ids = self.parse_comma_separated_exprs()?;

        let yields = self.parse_show_yield_list()?;

        Ok(Clause::TerminateTransactions(TerminateTransactionsClause {
            ids,
            yields,
        }))
    }
}