-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathformattingv2.ts
1312 lines (1216 loc) · 37.8 KB
/
formattingv2.ts
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
/*
* This file is a WIP of the second iteration of the Cypher formatter.
* It's being kept as a separate file to enable having two separate version at once
* since it would be difficult to consolidate the new and the old version
*/
import { CommonTokenStream, ParserRuleContext, TerminalNode } from 'antlr4';
import { default as CypherCmdLexer } from '../generated-parser/CypherCmdLexer';
import {
ArrowLineContext,
BooleanLiteralContext,
CallClauseContext,
CaseAlternativeContext,
CaseExpressionContext,
ClauseContext,
CountStarContext,
CreateClauseContext,
ExistsExpressionContext,
Expression10Context,
Expression2Context,
ExpressionContext,
ExtendedCaseExpressionContext,
ForeachClauseContext,
FunctionInvocationContext,
KeywordLiteralContext,
LabelExpression2Context,
LabelExpression3Context,
LabelExpression4Context,
LabelExpressionContext,
LimitContext,
ListItemsPredicateContext,
ListLiteralContext,
MapContext,
MapProjectionContext,
MapProjectionElementContext,
MatchClauseContext,
MergeActionContext,
MergeClauseContext,
NamespaceContext,
NodePatternContext,
NumberLiteralContext,
ParameterContext,
ParenthesizedExpressionContext,
PathLengthContext,
PatternContext,
PatternListContext,
ProcedureNameContext,
PropertyContext,
QuantifierContext,
ReduceExpressionContext,
RegularQueryContext,
RelationshipPatternContext,
ReturnBodyContext,
ReturnClauseContext,
ReturnItemContext,
ReturnItemsContext,
SetClauseContext,
StatementsOrCommandsContext,
SubqueryClauseContext,
UnwindClauseContext,
WhereClauseContext,
WithClauseContext,
} from '../generated-parser/CypherCmdParser';
import CypherCmdParserVisitor from '../generated-parser/CypherCmdParserVisitor';
import {
Chunk,
CommentChunk,
findTargetToken,
getParseTreeAndTokens,
handleMergeClause,
isComment,
RegularChunk,
wantsToBeConcatenated,
wantsToBeUpperCase,
} from './formattingHelpersv2';
import { buffersToFormattedString } from './formattingSolutionSearchv2';
interface RawTerminalOptions {
lowerCase?: boolean;
upperCase?: boolean;
spacingChoice?: SpacingChoice;
}
type SpacingChoice = 'SPACE_AFTER' | 'EXTRA_SPACE';
export class TreePrintVisitor extends CypherCmdParserVisitor<void> {
buffers: Chunk[][] = [];
indentation = 0;
indentationSpaces = 2;
targetToken?: number;
cursorPos = 0;
groupID = 0;
groupStack: number[] = [];
startGroupCounter = 0;
constructor(private tokenStream: CommonTokenStream) {
super();
this.buffers.push([]);
}
format = (root: StatementsOrCommandsContext) => {
this.visit(root);
const result = buffersToFormattedString(this.buffers);
this.cursorPos += result.cursorPos;
return result.formattedString;
};
currentBuffer = () => this.buffers.at(-1);
breakLine = () => {
if (this.currentBuffer().length > 0) {
this.buffers.push([]);
}
};
// If two tokens should never be split, concatenate them into one chunk
concatenate = () => {
// Loop since we might have multiple comments or special chunks anywhere, e.g. [b, C, C, a, C]
// but we should still be able to concatenate a, b to ba
const indices: number[] = [];
for (let i = this.currentBuffer().length - 1; i >= 0; i--) {
if (!(this.currentBuffer()[i].type === 'COMMENT')) {
indices.push(i);
if (indices.length === 2) {
break;
}
}
}
if (indices.length < 2) {
return;
}
const suffix = this.currentBuffer().splice(indices[0], 1)[0];
const prefix = this.currentBuffer()[indices[1]];
if (prefix.type !== 'REGULAR' || suffix.type !== 'REGULAR') {
throw new Error('Internal formatter bug in concatenate');
}
const hasCursor = prefix.isCursor || suffix.isCursor;
if (suffix.isCursor) {
this.cursorPos += prefix.text.length;
}
const chunk: RegularChunk = {
type: 'REGULAR',
text: prefix.text + suffix.text,
doubleBreak: suffix.doubleBreak,
groupsStarting: prefix.groupsStarting + suffix.groupsStarting,
groupsEnding: prefix.groupsEnding + suffix.groupsEnding,
modifyIndentation: prefix.modifyIndentation + suffix.modifyIndentation,
...(hasCursor && { isCursor: true }),
};
this.currentBuffer()[indices[1]] = chunk;
};
/**
* Sets that if the previous token should not choose between the argument ('noSpace' or 'noBreak')
* Skips any preceding comments or special chunks we did not expect.
*/
setAvoidProperty = (propertyName: 'noSpace' | 'noBreak'): void => {
let idx = this.currentBuffer().length - 1;
while (idx >= 0 && this.currentBuffer()[idx].type === 'COMMENT') {
idx--;
}
if (idx < 0) {
return;
}
const chunk = this.currentBuffer()[idx];
if (chunk.type !== 'REGULAR') {
throw new Error(`Internal formatter bug in setting ${propertyName}`);
}
chunk[propertyName] = true;
};
avoidSpaceBetween = (): void => {
this.setAvoidProperty('noSpace');
};
avoidBreakBetween = (): void => {
this.setAvoidProperty('noBreak');
};
doubleBreakBetween = (): void => {
if (this.currentBuffer().length > 0) {
this.currentBuffer().at(-1).doubleBreak = true;
}
};
doubleBreakBetweenNonComment = (): void => {
if (
this.currentBuffer().length > 0 &&
this.currentBuffer().at(-1).type !== 'COMMENT'
) {
this.currentBuffer().at(-1).doubleBreak = true;
}
};
getFirstNonCommentIdx = (): number => {
let idx = this.currentBuffer().length - 1;
while (idx >= 0 && this.currentBuffer()[idx].type === 'COMMENT') {
idx--;
}
return idx;
};
endGroup = (id: number) => {
if (this.groupStack.at(-1) !== id) {
return;
}
const idx = this.getFirstNonCommentIdx();
this.currentBuffer().at(idx).groupsEnding += 1;
this.groupStack.pop();
};
startGroup = (): number => {
this.startGroupCounter += 1;
this.groupStack.push(this.groupID);
this.groupID++;
return this.groupID - 1;
};
addIndentation = () => {
this.currentBuffer().at(-1).modifyIndentation += 1;
};
removeIndentation = () => {
const idx = this.getFirstNonCommentIdx();
this.currentBuffer().at(idx).modifyIndentation -= 1;
};
findBottomChild = (
ctx: ParserRuleContext | TerminalNode,
side: 'before' | 'after',
): TerminalNode => {
if (ctx instanceof TerminalNode) {
return ctx;
}
const idx = side === 'before' ? 0 : ctx.getChildCount() - 1;
const child = ctx.getChild(idx);
if (child instanceof TerminalNode) {
return child;
} else if (child instanceof ParserRuleContext) {
return this.findBottomChild(child, side);
}
throw new Error('Internal formatting error in findBottomChild');
};
preserveExplicitNewlineAfter = (ctx: ParserRuleContext) => {
this.preserveExplicitNewline(ctx, 'after');
};
preserveExplicitNewlineBefore = (ctx: ParserRuleContext) => {
this.preserveExplicitNewline(ctx, 'before');
};
preserveExplicitNewline = (
ctx: ParserRuleContext,
side: 'before' | 'after',
) => {
const bottomChild = this.findBottomChild(ctx, side);
const token = bottomChild.symbol;
const hiddenTokens =
side === 'before'
? this.tokenStream.getHiddenTokensToLeft(token.tokenIndex)
: this.tokenStream.getHiddenTokensToRight(token.tokenIndex);
const hiddenNewlines = hiddenTokens?.filter(
(token) => token.text === '\n',
).length;
const commentCount = hiddenTokens?.filter((token) =>
isComment(token),
).length;
// If there are comments, they take responsibility of the explicit newlines.
if (hiddenNewlines > 1 && commentCount === 0) {
this.doubleBreakBetweenNonComment();
}
};
// Comments are in the hidden channel, so grab them manually
addCommentsBefore = (node: TerminalNode) => {
const token = node.symbol;
const hiddenTokens = this.tokenStream.getHiddenTokensToLeft(
token.tokenIndex,
);
const commentTokens = (hiddenTokens || []).filter((token) =>
isComment(token),
);
for (const commentToken of commentTokens) {
const text = commentToken.text.trim();
const chunk: CommentChunk = {
type: 'COMMENT',
breakBefore: false,
text,
groupsStarting: this.startGroupCounter,
groupsEnding: 0,
modifyIndentation: 0,
};
this.startGroupCounter = 0;
this.currentBuffer().push(chunk);
this.breakLine();
}
};
addCommentsAfter = (node: TerminalNode) => {
const token = node.symbol;
const hiddenTokens = this.tokenStream.getHiddenTokensToRight(
token.tokenIndex,
);
const nodeLine = node.symbol.line;
let breakCount = 0;
let includesComment = false;
for (const hiddenToken of hiddenTokens || []) {
if (hiddenToken.text === '\n') {
breakCount++;
}
if (!isComment(hiddenToken)) {
continue;
}
if (breakCount > 1) {
this.doubleBreakBetween();
}
breakCount = 0;
const commentToken = hiddenToken;
includesComment = true;
const text = commentToken.text.trim();
const commentLine = commentToken.line;
const chunk: CommentChunk = {
type: 'COMMENT',
breakBefore: nodeLine !== commentLine,
text,
groupsStarting: this.startGroupCounter,
groupsEnding: 0,
modifyIndentation: 0,
};
this.startGroupCounter = 0;
// If we have a "hard-break" comment, i.e. one that has a newline before it,
// we end all currently active groups. Otherwise, that comment becomes part of the group,
// which makes it very hard for the search to find a good solution.
if (nodeLine !== commentLine) {
while (this.groupStack.length > 1) {
this.endGroup(this.groupStack.at(-1));
}
}
this.currentBuffer().push(chunk);
}
// Account for the last comment having multiple newline after it, to remember explicit
// newlines when we have e.g. [C, \n, \n]
if (breakCount > 1 && includesComment) {
this.doubleBreakBetween();
}
};
visitIfNotNull = (ctx: ParserRuleContext | TerminalNode) => {
if (ctx) {
this.visit(ctx);
}
};
visitRawIfNotNull = (ctx: TerminalNode, options?: RawTerminalOptions) => {
if (ctx) {
this.visitTerminalRaw(ctx, options);
}
};
visitStatementsOrCommands = (ctx: StatementsOrCommandsContext) => {
const n = ctx.statementOrCommand_list().length;
for (let i = 0; i < n; i++) {
this.visit(ctx.statementOrCommand(i));
if (i < n - 1 || ctx.SEMICOLON(i)) {
if (this.currentBuffer().at(-1).text === '\n') {
this.currentBuffer().pop();
}
this.visit(ctx.SEMICOLON(i));
}
}
};
// Handled separately because clauses should start on new lines, see
// https://neo4j.com/docs/cypher-manual/current/styleguide/#cypher-styleguide-indentation-and-line-breaks
visitClause = (ctx: ClauseContext) => {
this.breakLine();
this.visitChildren(ctx);
this.preserveExplicitNewlineAfter(ctx);
};
visitWithClause = (ctx: WithClauseContext) => {
this.visit(ctx.WITH());
this.avoidBreakBetween();
const withClauseGrp = this.startGroup();
this.visit(ctx.returnBody());
this.visitIfNotNull(ctx.whereClause());
this.endGroup(withClauseGrp);
};
visitMatchClause = (ctx: MatchClauseContext) => {
this.visitIfNotNull(ctx.OPTIONAL());
this.visit(ctx.MATCH());
this.avoidBreakBetween();
const matchClauseGrp = this.startGroup();
this.visitIfNotNull(ctx.matchMode());
this.visit(ctx.patternList());
this.endGroup(matchClauseGrp);
const n = ctx.hint_list().length;
for (let i = 0; i < n; i++) {
this.visit(ctx.hint(i));
}
this.visitIfNotNull(ctx.whereClause());
};
visitCreateClause = (ctx: CreateClauseContext) => {
this.visit(ctx.CREATE());
this.avoidBreakBetween();
const createClauseGrp = this.startGroup();
this.visit(ctx.patternList());
this.endGroup(createClauseGrp);
};
visitReturnClause = (ctx: ReturnClauseContext) => {
this.visit(ctx.RETURN());
this.avoidBreakBetween();
this.visit(ctx.returnBody());
};
visitReturnBody = (ctx: ReturnBodyContext) => {
this.visitIfNotNull(ctx.DISTINCT());
const returnItemsGrp = this.startGroup();
this.visit(ctx.returnItems());
if (ctx.orderBy() || ctx.skip()) {
const orderSkipGrp = this.startGroup();
this.visitIfNotNull(ctx.orderBy());
this.visitIfNotNull(ctx.skip());
this.endGroup(orderSkipGrp);
}
this.endGroup(returnItemsGrp);
this.visitIfNotNull(ctx.limit());
};
visitUnwindClause = (ctx: UnwindClauseContext) => {
this.visit(ctx.UNWIND());
this.avoidBreakBetween();
const unwindClauseGrp = this.startGroup();
this.visit(ctx.expression());
const asGrp = this.startGroup();
this.visit(ctx.AS());
this.visit(ctx.variable());
this.endGroup(asGrp);
this.endGroup(unwindClauseGrp);
};
visitLimit = (ctx: LimitContext) => {
this.preserveExplicitNewlineBefore(ctx);
this.breakLine();
this.visitChildren(ctx);
};
visitReturnItem = (ctx: ReturnItemContext) => {
this.visit(ctx.expression());
if (ctx.AS() || ctx.variable()) {
const asGrp = this.startGroup();
this.visitIfNotNull(ctx.AS());
this.visitIfNotNull(ctx.variable());
this.endGroup(asGrp);
}
};
visitReturnItems = (ctx: ReturnItemsContext) => {
if (ctx.TIMES()) {
this.visit(ctx.TIMES());
}
const n = ctx.returnItem_list().length;
let commaIdx = 0;
if (ctx.TIMES() && n > 0) {
this.visit(ctx.COMMA(commaIdx));
commaIdx++;
}
for (let i = 0; i < n; i++) {
const returnItemGrp = this.startGroup();
this.visit(ctx.returnItem(i));
if (i < n - 1) {
this.visit(ctx.COMMA(commaIdx));
commaIdx++;
}
this.endGroup(returnItemGrp);
}
};
// Handled separately because count star is its own thing
visitCountStar = (ctx: CountStarContext) => {
this.visitTerminalRaw(ctx.COUNT());
this.visit(ctx.LPAREN());
this.visitTerminalRaw(ctx.TIMES());
this.visit(ctx.RPAREN());
};
visitReduceExpression = (ctx: ReduceExpressionContext) => {
const reduceExprGrp = this.startGroup();
this.visitTerminalRaw(ctx.REDUCE());
this.visit(ctx.LPAREN());
this.visit(ctx.variable(0));
this.visit(ctx.EQ());
this.visit(ctx.expression(0));
this.visitTerminalRaw(ctx.COMMA());
this.visit(ctx.variable(1));
this.visit(ctx.IN());
this.visit(ctx.expression(1));
this.visit(ctx.BAR());
this.visit(ctx.expression(2));
this.visit(ctx.RPAREN());
this.endGroup(reduceExprGrp);
};
// Handled separately to avoid spaces between a minus and a number
visitNumberLiteral = (ctx: NumberLiteralContext) => {
this.visitRawIfNotNull(ctx.MINUS());
this.visitIfNotNull(ctx.DECIMAL_DOUBLE());
this.visitIfNotNull(ctx.UNSIGNED_DECIMAL_INTEGER());
this.visitIfNotNull(ctx.UNSIGNED_HEX_INTEGER());
this.visitIfNotNull(ctx.UNSIGNED_OCTAL_INTEGER());
};
// Handled separately since otherwise they will get weird spacing
visitLabelExpression = (ctx: LabelExpressionContext) => {
this.visitRawIfNotNull(ctx.COLON());
if (ctx.IS()) {
this.visitIfNotNull(ctx.IS());
} else {
this.avoidSpaceBetween();
}
this.visit(ctx.labelExpression4());
};
visitLabelExpression4 = (ctx: LabelExpression4Context) => {
// There is no great way to know which labels have colons before them,
// so we have to resort to manually checking the types of the children.
const n = ctx.getChildCount();
for (let i = 0; i < n; i++) {
const child = ctx.getChild(i);
if (child instanceof LabelExpression3Context) {
this.visit(child);
if (i > 0) {
this.concatenate();
}
} else if (child instanceof TerminalNode) {
this.avoidSpaceBetween();
this.visitTerminal(child);
}
}
};
visitLabelExpression3 = (ctx: LabelExpression3Context) => {
const n = ctx.getChildCount();
for (let i = 0; i < n; i++) {
const child = ctx.getChild(i);
if (child instanceof LabelExpression2Context) {
this.visit(child);
if (i > 0) {
this.concatenate();
}
} else if (child instanceof TerminalNode) {
this.avoidSpaceBetween();
this.visitTerminal(child);
}
}
};
visitLabelExpression2 = (ctx: LabelExpression2Context) => {
const n = ctx.EXCLAMATION_MARK_list().length;
for (let i = 0; i < n; i++) {
this.visitTerminalRaw(ctx.EXCLAMATION_MARK(i));
this.concatenate();
if (i == n - 1) {
this.avoidSpaceBetween();
}
}
this.visit(ctx.labelExpression1());
};
visitTerminal = (node: TerminalNode) => {
if (this.buffers.length === 1 && this.currentBuffer().length === 0) {
this.addCommentsBefore(node);
}
if (node.symbol.type === CypherCmdLexer.EOF) {
return;
}
let text = node.getText();
if (wantsToBeUpperCase(node)) {
text = text.toUpperCase();
}
const chunk: RegularChunk = {
type: 'REGULAR',
text,
node,
groupsStarting: this.startGroupCounter,
groupsEnding: 0,
modifyIndentation: 0,
};
this.startGroupCounter = 0;
if (node.symbol.tokenIndex === this.targetToken) {
chunk.isCursor = true;
}
this.currentBuffer().push(chunk);
if (wantsToBeConcatenated(node)) {
this.concatenate();
}
this.addCommentsAfter(node);
};
// Some terminals don't want to have the regular rules applied to them,
// for instance the . in properties should be handled in a "raw" manner to
// avoid getting spaces around it (since it is an operator and operators want spaces)
// But we still need to get the comments, to ensure that in e.g. the query
// node. // comment
// prop
// the comment doesn't disappear
visitTerminalRaw = (node: TerminalNode, options?: RawTerminalOptions) => {
if (this.buffers.length === 1 && this.currentBuffer().length === 0) {
this.addCommentsBefore(node);
}
let text = node.getText();
if (options?.lowerCase) {
text = text.toLowerCase();
}
if (options?.upperCase) {
text = text.toUpperCase();
}
if (options?.spacingChoice === 'EXTRA_SPACE') {
text += ' ';
}
const chunk: RegularChunk = {
type: 'REGULAR',
text,
node,
groupsStarting: this.startGroupCounter,
groupsEnding: 0,
modifyIndentation: 0,
};
this.startGroupCounter = 0;
if (node.symbol.tokenIndex === this.targetToken) {
chunk.isCursor = true;
}
this.currentBuffer().push(chunk);
if (!options?.spacingChoice) {
this.avoidSpaceBetween();
}
if (wantsToBeConcatenated(node)) {
this.concatenate();
}
this.addCommentsAfter(node);
};
// Handled separately because the dollar should not be treated
// as an operator
visitParameter = (ctx: ParameterContext) => {
this.visitTerminalRaw(ctx.DOLLAR());
this.visit(ctx.parameterName());
this.concatenate();
};
// Literals have casing rules, see
// https://neo4j.com/docs/cypher-manual/current/styleguide/#cypher-styleguide-casing
visitBooleanLiteral = (ctx: BooleanLiteralContext) => {
this.visitRawIfNotNull(ctx.TRUE(), {
lowerCase: true,
spacingChoice: 'SPACE_AFTER',
});
this.visitRawIfNotNull(ctx.FALSE(), {
lowerCase: true,
spacingChoice: 'SPACE_AFTER',
});
};
visitKeywordLiteral = (ctx: KeywordLiteralContext) => {
if (ctx.NULL()) {
this.visitTerminalRaw(ctx.NULL(), {
lowerCase: true,
spacingChoice: 'SPACE_AFTER',
});
} else {
this.visitChildren(ctx);
}
};
// The patterns are handled separately because we need spaces
// between labels and property predicates in patterns
handleInnerPatternContext = (
ctx: NodePatternContext | RelationshipPatternContext,
) => {
this.visitIfNotNull(ctx.variable());
this.visitIfNotNull(ctx.labelExpression());
if (ctx instanceof RelationshipPatternContext) {
this.visitIfNotNull(ctx.pathLength());
this.concatenate();
}
this.visitIfNotNull(ctx.properties());
if (ctx.WHERE()) {
this.visit(ctx.WHERE());
this.visit(ctx.expression());
}
};
visitPathLength = (ctx: PathLengthContext) => {
this.visitTerminalRaw(ctx.TIMES());
if (ctx._single) {
this.visitTerminalRaw(ctx.UNSIGNED_DECIMAL_INTEGER(0));
this.concatenate();
} else if (ctx.DOTDOT()) {
let idx = 0;
if (ctx._from_) {
this.visitTerminalRaw(ctx.UNSIGNED_DECIMAL_INTEGER(idx));
this.concatenate();
idx++;
}
this.visitTerminalRaw(ctx.DOTDOT());
this.concatenate();
if (ctx._to) {
this.visitTerminalRaw(ctx.UNSIGNED_DECIMAL_INTEGER(idx));
this.concatenate();
}
}
};
visitArrowLine = (ctx: ArrowLineContext) => {
this.visitRawIfNotNull(ctx.MINUS());
this.visitRawIfNotNull(ctx.ARROW_LINE());
};
visitRelationshipPattern = (ctx: RelationshipPatternContext) => {
if (ctx.leftArrow()) {
this.avoidSpaceBetween();
this.visitIfNotNull(ctx.leftArrow());
}
const arrowLineList = ctx.arrowLine_list();
// Concatenations are to ensure the (left) arrow remains
// on the previous line (styleguide rule) if we need to break within the pattern
this.visit(arrowLineList[0]);
this.concatenate();
this.avoidSpaceBetween();
if (ctx.leftArrow()) {
this.concatenate();
this.avoidSpaceBetween();
}
if (ctx.LBRACKET()) {
const bracketPatternGrp = this.startGroup();
this.visit(ctx.LBRACKET());
this.handleInnerPatternContext(ctx);
this.visit(ctx.RBRACKET());
this.endGroup(bracketPatternGrp);
}
// Same idea with concatenation as above
this.avoidSpaceBetween();
this.visit(arrowLineList[1]);
this.concatenate();
if (ctx.rightArrow()) {
this.visit(ctx.rightArrow());
this.concatenate();
}
this.avoidSpaceBetween();
};
visitNodePattern = (ctx: NodePatternContext) => {
this.visit(ctx.LPAREN());
this.avoidBreakBetween();
const nodePatternGrp = this.startGroup();
if (ctx.variable() || ctx.labelExpression() || ctx.properties()) {
this.visitIfNotNull(ctx.variable());
this.visitIfNotNull(ctx.labelExpression());
this.visitIfNotNull(ctx.properties());
if (ctx.WHERE()) {
this.visit(ctx.WHERE());
this.visit(ctx.expression());
}
} else {
this.visitIfNotNull(ctx.WHERE());
this.visitIfNotNull(ctx.expression());
}
this.endGroup(nodePatternGrp);
this.visit(ctx.RPAREN());
};
visitPattern = (ctx: PatternContext) => {
// Don't create an unnecessary group if we don't also have a path
if (!ctx.variable() && !ctx.selector()) {
this.visitChildren(ctx);
return;
}
if (ctx.variable()) {
this.visit(ctx.variable());
this.avoidBreakBetween();
this.visit(ctx.EQ());
this.avoidBreakBetween();
}
this.visitIfNotNull(ctx.selector());
const anonymousPatternGrp = this.startGroup();
this.visit(ctx.anonymousPattern());
this.endGroup(anonymousPatternGrp);
};
visitPatternList = (ctx: PatternListContext) => {
const n = ctx.pattern_list().length;
if (n === 1) {
this.visitChildren(ctx);
return;
}
for (let i = 0; i < n; i++) {
const patternListItemGrp = this.startGroup();
this.visit(ctx.pattern(i));
if (i < n - 1) {
this.visit(ctx.COMMA(i));
}
this.endGroup(patternListItemGrp);
}
};
// Handled separately because we never want to split within the quantifier.
// So we fully concatenate it to ensure it's part of the same chunk.
visitQuantifier = (ctx: QuantifierContext) => {
if (ctx.PLUS() || ctx.TIMES()) {
this.visitChildren(ctx);
this.concatenate();
this.avoidSpaceBetween();
return;
}
if (!ctx._from_) {
this.visitTerminalRaw(ctx.LCURLY(), { spacingChoice: 'EXTRA_SPACE' });
} else {
this.visit(ctx.LCURLY());
}
this.concatenate();
let idx = 0;
if (ctx._from_) {
this.visit(ctx.UNSIGNED_DECIMAL_INTEGER(idx));
this.concatenate();
idx++;
}
if (ctx._to) {
this.visit(ctx.COMMA());
this.concatenate();
this.visit(ctx.UNSIGNED_DECIMAL_INTEGER(idx));
this.concatenate();
} else {
this.visitTerminalRaw(ctx.COMMA(), { spacingChoice: 'EXTRA_SPACE' });
this.concatenate();
}
this.visit(ctx.RCURLY());
this.concatenate();
this.avoidSpaceBetween();
};
// Handled separately because the dots aren't operators
visitNamespace = (ctx: NamespaceContext) => {
const n = ctx.DOT_list().length;
for (let i = 0; i < n; i++) {
this.visit(ctx.symbolicNameString(i));
this.avoidSpaceBetween();
this.visitTerminalRaw(ctx.DOT(i));
}
};
// Handled separately because the dot is not an operator
visitProperty = (ctx: PropertyContext) => {
this.visitTerminalRaw(ctx.DOT());
if (!(ctx.parentCtx instanceof MapProjectionElementContext)) {
this.concatenate();
}
this.visit(ctx.propertyKeyName());
this.concatenate();
};
// Handled separately because where is not a clause (it is a subclause)
visitWhereClause = (ctx: WhereClauseContext) => {
this.preserveExplicitNewlineBefore(ctx);
this.breakLine();
this.visit(ctx.WHERE());
this.avoidBreakBetween();
const whereClauseGrp = this.startGroup();
this.visit(ctx.expression());
this.endGroup(whereClauseGrp);
};
visitParenthesizedExpression = (ctx: ParenthesizedExpressionContext) => {
this.visit(ctx.LPAREN());
this.avoidBreakBetween();
const parenthesizedExprGrp = this.startGroup();
this.visit(ctx.expression());
this.endGroup(parenthesizedExprGrp);
this.visit(ctx.RPAREN());
};
visitExpression = (ctx: ExpressionContext) => {
const n = ctx.expression11_list().length;
if (n === 1) {
this.visit(ctx.expression11(0));
return;
}
for (let i = 0; i < n; i++) {
const orExprGrp = this.startGroup();
this.visit(ctx.expression11(i));
if (i < n - 1) {
this.visit(ctx.OR(i));
}
this.endGroup(orExprGrp);
}
};
visitExpression10 = (ctx: Expression10Context) => {
const n = ctx.expression9_list().length;
if (n === 1) {
this.visit(ctx.expression9(0));
return;
}
for (let i = 0; i < n; i++) {
const andExprGrp = this.startGroup();
this.visit(ctx.expression9(i));
if (i < n - 1) {
this.visit(ctx.AND(i));
}
this.endGroup(andExprGrp);
}
};
// Handled separately because it contains subclauses (and thus indentation rules)
visitExistsExpression = (ctx: ExistsExpressionContext) => {
this.visit(ctx.EXISTS());
this.avoidBreakBetween();
this.visit(ctx.LCURLY());
if (ctx.regularQuery()) {
this.addIndentation();
this.visit(ctx.regularQuery());
this.removeIndentation();
this.breakLine();
} else {
this.visitIfNotNull(ctx.matchMode());
this.visit(ctx.patternList());
this.visitIfNotNull(ctx.whereClause());
}
this.visit(ctx.RCURLY());
};
visitCaseAlternative = (ctx: CaseAlternativeContext) => {
const caseAlternativeGrp = this.startGroup();
this.visit(ctx.WHEN());
this.visit(ctx.expression(0));
this.visit(ctx.THEN());
this.visit(ctx.expression(1));
this.endGroup(caseAlternativeGrp);
};
// Handled separately since cases want newlines
visitCaseExpression = (ctx: CaseExpressionContext) => {
this.breakLine();
this.visit(ctx.CASE());
const caseGrp = this.startGroup();
const n = ctx.caseAlternative_list().length;
for (let i = 0; i < n; i++) {
this.addIndentation();
this.breakLine();
this.visit(ctx.caseAlternative(i));
this.removeIndentation();
}
if (ctx.ELSE()) {
this.addIndentation();
this.breakLine();
this.visit(ctx.ELSE());
this.visit(ctx.expression());
this.removeIndentation();
}
this.endGroup(caseGrp);
this.breakLine();
this.visit(ctx.END());
};
visitExtendedCaseExpression = (ctx: ExtendedCaseExpressionContext) => {
this.breakLine();
this.visit(ctx.CASE());
this.visit(ctx.expression(0));
this.startGroup();
const extendedCaseGrp = this.startGroup();
const n = ctx.extendedCaseAlternative_list().length;
for (let i = 0; i < n; i++) {
this.addIndentation();
this.breakLine();
this.visit(ctx.extendedCaseAlternative(i));
this.removeIndentation();
}
if (ctx.ELSE()) {
this.addIndentation();
this.breakLine();
this.visit(ctx.ELSE());
this.visit(ctx.expression(1));
this.removeIndentation();
}
this.endGroup(extendedCaseGrp);
this.breakLine();
this.visit(ctx.END());
};
// Handled separately because it wants indentation and line breaks
visitSubqueryClause = (ctx: SubqueryClauseContext) => {