This repository was archived by the owner on Aug 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathtrivadis_custom_format.arbori
4485 lines (4045 loc) · 151 KB
/
trivadis_custom_format.arbori
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
/*
* Copyright 2021 Philipp Salvisberg <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
include "std.arbori"
/**
* Lightweight Formatter for SQL Developer and SQLcl, version 23.4.1-SNAPSHOT
* The idea is to keep the code formatted "as is" and apply chosen formatting rules only.
*
* The Arbori program is processed from top to bottom.
*
* To structure the Arbori program the concept of "phases" and "sections" are used.
* A phase consists of one ore more sections.
* A section consists of one or more Arbori queries.
*
* The following phases are defined:
*
* - Phase 0 - Main program with minimal configuration.
* - Phase 1 - Initialization and preprocessing.
* - Phase 2 - Apply rules.
*
* The start of a phase is visualized by a comment series like this
*
* -- ================================
* -- Phase <PhaseNumber> - <Comment>.
* -- ================================
*
* The sections have the following format <Category><SectionNumber>.
* The next table explains the meaning of a category:
*
* Cat. Meaning Description Phases Tests?
* ---- ---------------------- ------------------------------------------------------ ------ ------
* D Debug Initialize or produce debugging output. 1, 2 No
* I Initialization Section Identifies a section in an initialization phase. 1 No
* O SQLDev Option Implements a SQL Developer option (Advanced Format). 2 Yes
* R Trivadis Rule Implements a Trivadis PL/SQL & SQL Guideline. 2 Yes
* A Add-on Section/Rule Additional formatting rule, that is not based on 2 Yes
* the Trivadis PL/SQL & SQL Guidelines. Nonetheless it's
* considered important to improve the formatting result.
*
* The SectionNumber identifies a section within a category.
*
* The start of a section is visualized by a comment series like this
*
* -- -------------------------------------
* -- <Category><SectionNumber>: <Comment>.
* -- -------------------------------------
*
* The lightweight formatter honors most of the SQLDev options. However, the following options
* are ignored, have limitations or are considered only partially:
*
* - Indentation: indent with. Options: Tab; Spaces. (useTab).
* The formatter supports only indentation with spaces. Spaces are used even if "Tab" is configured.
* Using tab would lead to various issues in combination with other settings (e.g. leading commas).
*
* - Line Breaks: Commas per line in procedures. Options: Integer value. (breaksProcArgs).
* The formatter ignores this configuration.
* The idea of the lightweight formatter is to leave this decision to the developer.
*
* - Line Breaks: For compound_condition parenthesis. Options: true; false. (breakParenCondition).
* The formatter ignores this configuration.
* The idea of the lightweight formatter is to leave this decision to the developer.
*
* - Line Breaks: After statements. Options: Double break; Single break; Preserve original. (extraLinesAfterSignificantStatements).
* The formatter ignores this configuration.
* The idea of the lightweight formatter is to leave this decision to the developer.
*
* The following SQL options are honored, but not implemented by this Arbori program.
* They are implemented by SQLDev's oracle.dbtools.app.Format class. As a result the behavior cannot be overridden.
*
* - Format:
* - Convert Case Only. Options: true, false. (adjustCaseOnly).
* - Advanced Format:
* - General: Keywords case. Options: UPPER; lower; Init cap; Keep unchanged. (kwCase).
* - General: Identifiers case. Options: UPPER; lower; Init cap; Keep unchanged. (idCase).
* - General: 1-line long comments. Options: Keep unchanged; Wrap multiline; Wrap singleline. (singleLineComments).
* - Line Breaks: Before line comments. Options: true; false. (forceLinebreaksBeforeComment).
*/
-- ====================================================================================================================
-- Phase 0: Main Configuration.
-- ====================================================================================================================
-- Sections:
-- - I2: Minimal Arbori program (expected by the formatter).
-- --------------------------------------------------------------------------------------------------------------------
-- I2: Minimal Arbori program (expected by the formatter).
-- --------------------------------------------------------------------------------------------------------------------
-- ":indentCondtions" must be used,
-- otherwise the Arbori program will be considered invalid and the default is used.
-- The Arbori query "i2_dummy" is never called, hence it does not matter what node is selected.
-- However, I chose to use "identifier" to avoid an Arbori warning.
i2_dummy:
:indentConditions & [node) identifier
;
-- "skipWhitespaceBeforeNode" must be defined,
-- otherwise the Arbori program will be considered invalid and the default is used.
skipWhiteSpaceBeforeNode:
runOnce
-> {
var doNotCallCallbackFunction;
}
-- In SQLDev 22.2.0 the formatter introduced a check that looks for "order_by_clause___0" in the Arbori program.
-- There is no need to define a query that uses it. Using it in the comment is good enough.
-- ====================================================================================================================
-- Phase 1 - Initialization and pre-processing.
-- ====================================================================================================================
-- Sections:
-- - D1: Initialize timer.
-- - I3: Do not format nodes.
-- - I5: Define global variables and functions.
-- - I10: Determine and normalize line separators.
-- - I11: Enforce nonquoted identifiers.
-- - I6: Remove duplicate empty lines.
-- - I4: Define identifiers.
-- - I7: Keep existing whitespace.
-- - I8: Save indentations of parser node positions in first selection directive.
-- - I9: Remove duplicate spaces in scope.
-- --------------------------------------------------------------------------------------------------------------------
-- D1: Initialize timer.
-- --------------------------------------------------------------------------------------------------------------------
d1_initialize_timer:
runOnce
-> {
var startTime = (new Date()).getTime();
}
-- --------------------------------------------------------------------------------------------------------------------
-- I3: Do not format node
-- --------------------------------------------------------------------------------------------------------------------
-- This is considered pre-processing because the provided callback function is used
-- and we do not write tests for this.
-- Callback function to ensure numeric literals are formatted correctly (without whitespaces)
dontFormatNode:
[node) numeric_literal
| [node) path -- expected in SQL*Plus, SQLcl commands only
| [node) "create_java"
->
;
enableKeepQutoedIdentifiersForCall:
runOnce
-> {
var keepQuotedIdentifiersForCall = false;
}
enforceKeepQuotedIdentifiersForCall:
[node) "create_java"
-> {
keepQuotedIdentifiersForCall = true;
}
-- --------------------------------------------------------------------------------------------------------------------
-- I5: Define global variables and functions.
-- --------------------------------------------------------------------------------------------------------------------
-- Global variables, which are likely to be used in more than one Arbori query/action
i5_define_global_variables:
runOnce
-> {
// java.lang classes
var Integer = Java.type('java.lang.Integer');
var StringBuilder = Java.type('java.lang.StringBuilder');
var System = Java.type('java.lang.System');
// java.util classes
var ArrayList = Java.type('java.util.ArrayList');
var Arrays = Java.type('java.util.Arrays');
var HashMap = Java.type('java.util.HashMap');
var HashSet = Java.type('java.util.HashSet');
var Pattern = Java.type("java.util.regex.Pattern");
var Collectors = Java.type('java.util.stream.Collectors');
// oracle.dbtools.app classes
var Format = Java.type('oracle.dbtools.app.Format');
var Format$Breaks = Java.type("oracle.dbtools.app.Format$Breaks");
var Format$Space = Java.type("oracle.dbtools.app.Format$Space");
// oracle.dbtools.parser classes
var LexerToken = Java.type('oracle.dbtools.parser.LexerToken');
var Substitutions = Java.type('oracle.dbtools.parser.Substitutions');
var Token = Java.type('oracle.dbtools.parser.Token');
// oracle.dbtools.util classes
var logger = Java.type('oracle.dbtools.util.Logger');
// use reflection to access hidden field newlinePositions
var newlinePositionsField = Format.class.getDeclaredField("newlinePositions");
newlinePositionsField.setAccessible(true);
var newlinePositions = newlinePositionsField.get(struct);
// get option for "Alignment: Column and Table aliases"
var alignTabColAliases = struct.options.get("alignTabColAliases");
// get option for "Alignment: Type Declarations"
var alignTypeDecl = struct.options.get("alignTypeDecl");
// get option for "Alignment: Named Argument Separator =>"
var alignNamedArgs = struct.options.get("alignNamedArgs");
// get option for "Alignment: Assignment Operator :="
var alignAssignments = struct.options.get("alignAssignments");
// get option for "Alignment: Equality Predicate ="
var alignEquality = struct.options.get("alignEquality");
// get option for "Alignment: Right-align query keywords"
var alignRight = struct.options.get("alignRight");
// get option for "Indentation: Indent spaces" (number of spaces for a single indentation)
var indentSpaces = struct.options.get("identSpaces");
// get option for "Line breaks: On Concatenation"
var breaksConcat = struct.options.get("breaksConcat");
// get option for "Line Breaks: On Boolean connectors"
var breaksAroundLogicalConjunctions = struct.options.get("breaksAroundLogicalConjunctions");
// get option for "Line Breaks: On ANSI joins"
var breakAnsiiJoin = struct.options.get("breakAnsiiJoin");
// get option for "Line Breaks: On subqueries"
var breakOnSubqueries = struct.options.get("breakOnSubqueries");
// get option for "Line Breaks: Max char line width"
var maxCharLineSize = struct.options.get("maxCharLineSize");
// get option for "Line Breaks: SELECT/FROM/WHERE"
var breaksAfterSelect = struct.options.get("breaksAfterSelect");
// get option for "White Space: Around operators"
var spaceAroundOperators = struct.options.get("spaceAroundOperators");
// get option for "White Space: After commas"
var spaceAfterCommas = struct.options.get("spaceAfterCommas");
// get option for "Whitespace: Around parenthesis"
var spaceAroundBrackets = struct.options.get("spaceAroundBrackets");
// lexer tokens including hidden tokens (LINE_COMMENT, COMMENT, WS, MACRO_SKIP, SQLPLUSLINECONTINUE_SKIP)
// are relevant to find comments between tokens. These variables are populated in
// keepSignificantWhitespaceBeforeLeafNodes
var tokens = null;
var mapParserPosToLexerPos = new HashMap();
// parser tokens in first conditional compilation branch with original indent - populated in I8
var indentInConditionalBranch = new HashMap();
}
-- Global functions, which are likely to be used in more than one Arbory action
i5_define_global_functions:
runOnce
-> {
// Return a string with the requested number of spaces.
var getSpaces = function(numberOfSpaces) {
var result = "";
for (var i=0; i<numberOfSpaces; i++) {
result += " ";
}
return result;
}
// Return the indentation at a node position. Converts the default null to a single space
var getIndent = function(nodeFrom) {
// map is based on Integer; therefore nodeFrom must be converted to an Integer
var indent = newlinePositions.get(Integer.valueOf(nodeFrom));
if (indent == null) {
return " ";
}
return indent;
}
// Returns the indentation without leading new lines from a string.
var getNumCharsAfterNewLine = function(indent) {
if (indent.indexOf("\n") != -1) {
return indent.length - indent.lastIndexOf("\n") - 1;
}
return indent.length;
}
// Returns the leading new lines from a node position (without trailing spaces).
var getLeadingNewLines = function(nodeFrom) {
var startPos=nodeFrom;
var indent = getIndent(startPos);
if (indent.indexOf("\n") != -1) {
return indent.substring(0, indent.lastIndexOf("\n") + 1);
}
return "";
}
// Returns the column of a node position. Considers all preceding nodes.
var getColumn = function(nodeFrom) {
var startPos=nodeFrom;
var col=getNumCharsAfterNewLine(getIndent(startPos));
var indent = getIndent(startPos);
for (var i=startPos-1; i>=0 && indent.indexOf("\n") == -1; i=i-1) {
col += target.src.get(i).content.length;
var indent = getIndent(i);
col += getNumCharsAfterNewLine(indent);
}
return col;
}
// Same as getColumn but does not contain the very first indentation.
var getColumnWithoutFirstIndent = function(nodeFrom) {
var startPos=nodeFrom;
var col=getNumCharsAfterNewLine(getIndent(startPos));
var indent = getIndent(startPos);
for (var i=startPos-1; i>=0 && indent.indexOf("\n") == -1; i=i-1) {
col += target.src.get(i).content.length;
var indent = getIndent(i);
if (indent.indexOf("\n") == -1) {
col += getNumCharsAfterNewLine(indent);
}
}
return col;
}
// Returns true if a node or one of its children contains an indentation with a new line character.
var containsLineBreak = function(node) {
return containsLineBreakBetweenPos(node.from, node.to);
}
// Returns true if a new line character is found in the provided position range
var containsLineBreakBetweenPos = function(from, to) {
for (var i = from; i < to; i++) {
var value = getIndent(i);
if (value.indexOf("\n") != -1) {
return true;
}
}
}
// Returns true if single-line or multi-line comments exists between two node positions.
var hasCommentsBetweenPos = function(startPos, endPos) {
// maps are based on Integers; therefore startPost and endPos must be converted to Integers
tokenStartPos = mapParserPosToLexerPos.get(Integer.valueOf(startPos));
tokenEndPos = mapParserPosToLexerPos.get(Integer.valueOf(endPos));
for (var i = tokenStartPos; i < tokenEndPos; i++) {
var type = tokens[i].type;
if (type == Token.LINE_COMMENT || type == Token.COMMENT) {
return true;
}
}
return false;
}
// Returns the the last comment (sl or ml) between two node positions.
var getLastCommentBetweenPos = function(startPos, endPos) {
var comment = "";
// maps are based on Integers; therefore startPost and endPos must be converted to Integers
tokenStartPos = mapParserPosToLexerPos.get(Integer.valueOf(startPos));
tokenEndPos = mapParserPosToLexerPos.get(Integer.valueOf(endPos));
for (var i = tokenStartPos; i < tokenEndPos; i++) {
var type = tokens[i].type;
if (type == Token.LINE_COMMENT || type == Token.COMMENT) {
comment = tokens[i].content;
}
}
return comment;
}
// Returns the maximum column of nodes in an array list of tuples.
var getMaxColumn = function(list, nodeName) {
var maxCol = 0;
for (var i=0; i < list.length; i++) {
var node = list.get(i).get(nodeName)
var col = getColumn(node.from);
if (col > maxCol) {
maxCol = col;
}
}
return maxCol;
}
// Adds a tuple to a map indexed by scope.
var addTupleToMap = function(tuple, scopeNodeName, map) {
var scope = tuple.get(scopeNodeName);
var list = map.get(scope);
if (list == null) {
list = new ArrayList();
}
list.add(tuple);
map.put(scope, list);
}
// Increase the indent for a parent and all its descendants; but only for leaf nodes to avoid duplicate indentation.
var addIndent = function(parent, increaseBy) {
if (parent != null) {
var descendants = parent.descendants();
for (var i = 0, len = descendants.length; i < len; i++) {
var node = descendants.get(i);
var indent = getIndent(node.from);
if (indent.indexOf("\n") != -1) {
if (node.children().size() == 0) {
struct.putNewline(node.from, indent + getSpaces(increaseBy));
}
}
}
}
}
// Aligns all nodes per scope.
var align = function(map, alignNodeName, indentNodeName, logText) {
var keys = map.keySet().stream().collect(Collectors.toList()).toArray();
for (var i in keys) {
var scope = keys[i];
var list = map.get(scope);
var maxCol = getMaxColumn(list, alignNodeName);
alignAtPos(maxCol, list, alignNodeName, indentNodeName, logText);
}
}
// Aligns all nodes at a target position.
var alignAtPos = function(targetPos, list, alignNodeName, indentNodeName, logText) {
for (var i=0; i<list.length; i++) {
var alignNode = list.get(i).get(alignNodeName);
var indent = getIndent(alignNode.from);
var col = getColumn(alignNode.from);
if (targetPos != col) {
if (targetPos > col) {
indent += getSpaces(targetPos - col);
} else {
indent = indent.substring(0, targetPos + 1);
}
struct.putNewline(alignNode.from, indent);
logger.fine(struct.getClass(), logText + ": at " + alignNode.from + ".");
if (indentNodeName != null) {
var indentNode = list.get(i).get(indentNodeName);
if (indentNode != null) {
addIndent(indentNode, targetPos - col);
logger.fine(struct.getClass(), logText + ": add indent for " + indentNode.from + ".");
}
}
}
}
}
// Returns the content of the token position range.
var getContent = function(fromPos, toPos) {
var content = "";
for (var i=fromPos; i<toPos; i++) {
content += target.src.get(i).content;
content += getIndent(i+1);
}
return content;
}
// Returns the content of the last line in a text.
var getLastLine = function(text) {
if (text != null) {
var index = text.lastIndexOf("\n");
if (index > 0) {
return text.substring(text, index);
}
}
return text;
}
// Returns true if there is no other parameter defined on the same line.
var firstParameterOnLine = function(nodeFrom, scopeFrom) {
if (getIndent(nodeFrom).indexOf("\n") == -1) {
for (var i=nodeFrom-1; i>=scopeFrom; i=i-1) {
var prevNode = target.root.leafAtPos(i);
if (prevNode.contains("decl_id")) {
return false;
}
if (getIndent(prevNode.from).indexOf("\n") != -1) {
break;
}
}
}
return true;
}
// Returns true if there is a a new line in the node range; search backwards.
var hasNewline = function(from, to) {
for (var i=from; i>=to; i=i-1) {
if (getIndent(i).indexOf("\n") != -1) {
return true;
}
}
return false;
}
// Reduce indentation for nodes with leading commas.
var fixIndentOfLeadingCommas = function(map, nodeName, logText) {
if (struct.breaksBeforeComma()) {
var comma = 1;
if (spaceAfterCommas) {
comma += 1;
}
var keys = map.keySet().stream().collect(Collectors.toList()).toArray();
for (var i in keys) {
var scope = keys[i];
var list = map.get(scope);
for (var i=0; i<list.length; i++) {
var node = list.get(i).get(nodeName);
var indent = getIndent(node.from);
if (indent.indexOf("\n") != -1) {
var content = target.src.get(node.from).content;
if (content == ",") {
struct.putNewline(node.from, indent.substring(0, indent.length - comma));
logger.fine(struct.getClass(), logText + ": reduced intent at " + node.from + ".");
}
}
}
}
}
}
// Returns true if the node is part of a statement that should be fully formatted.
var overrideIndents = function(nodeFrom) {
// "subquery" could be added to handle select statements that do not end on semicolon.
// But this will have an impact on other statements using "subquery".
return hasParentOfType(nodeFrom, [
"select",
"create_view",
"create_materialized_view",
"insert",
"update",
"delete",
"merge",
"block_stmt",
"pkg_body",
"create_plsql",
"stmt"
]);
}
// Returns true if a the node or an ancestors has one of the provided symbols.
var hasParentOfType = function(nodeFrom, symbols) {
var node = target.root.leafAtPos(nodeFrom);
while (node != null) {
for (var i=0; i < symbols.length; i++) {
if (node.contains(symbols[i])) {
return true;
}
}
node = node.parent();
}
return false;
}
//-- Alternative implementation of Java String's replaceAll method due to
//-- https://github.com/oracle/graaljs/issues/460 .
//-- We cannot influence the JS engine initialization in an Arbori program,
//-- and therefore cannot delete the String.prototype.replaceAll.
//-- However, it would be possible to pass a JS regex, e.g.
//-- someString.replaceAll(/old/g, "new");
//-- This works, but when a backslash (e.g. \n for newline) is used in the regex an error is thrown.
//-- As soon as the issue 460 is fixed in the GraalVM JS script engine and this new version is used
//-- in SQLcl and SQLDev this workaround can be eliminated.
var replaceAll = function(input, pattern, replacement) {
var p = Pattern.compile(pattern);
var m = p.matcher(input);
var result = "";
var pos = 0;
while (m.find()) {
result += input.substring(pos, m.start());
result += replacement;
pos = m.end();
}
if (input.length > pos) {
result += input.substring(pos);
}
return result;
}
}
-- --------------------------------------------------------------------------------------------------------------------
-- I10: Determine and normalize line separators.
-- --------------------------------------------------------------------------------------------------------------------
-- Determine global variable theLineSeparator based on input as follows:
-- - if a CRLF is found, then use CRLF
-- - if a LF is found then use LF
-- - if neither a CRLF nor a LF is used (single line) then use the default, OS specific System.lineSeparator()
-- Ensure that only theLineSeparator is used in the input.
-- This section might change the target.input and requires a reparse.
-- However, the reparse is done in the section I6, which can handle an amended target.input.
-- This way the overhead of determining and normalizing line separators can be minimized.
i10_determine_and_normalize_line_separators:
runOnce
-> {
var getLineSeparator = function() {
var lineSep;
if (target.input.indexOf("\r\n") != -1) {
lineSep = "\r\n";
logger.fine(struct.getClass(), "i10_determine_and_normalize_line_separators: using CRLF.");
} else if (target.input.indexOf("\n") != -1) {
lineSep = "\n";
logger.fine(struct.getClass(), "i10_determine_and_normalize_line_separators: using LF.");
} else {
lineSep = System.lineSeparator();
logger.fine(struct.getClass(), "i10_determine_and_normalize_line_separators: using the OS default.");
}
return lineSep;
}
var normalizeLineSeparators = function() {
target.input = replaceAll(target.input, "\r", "");
if (theLineSeparator == "\r\n") {
target.input = replaceAll(target.input, "\n", "\r\n");
}
logger.fine(struct.getClass(), "i10_determine_and_normalize_line_separators: normalized.");
}
var theLineSeparator = getLineSeparator();
normalizeLineSeparators();
}
-- --------------------------------------------------------------------------------------------------------------------
-- I11: Enforce nonquoted identifiers.
-- --------------------------------------------------------------------------------------------------------------------
-- Removes the quotes in quoted identifiers, if the following is true:
-- - The option keepQuotedIdentifiers is not set or set to false
-- - The identifier starts and ends with a double quote.
-- - The first character after the initial double quote is a letter (A-Z) in upper case.
-- - The subsequent characters are one of the following:
-- - A-Z (upper case only)
-- - 0-9
-- - _ (underscore)
-- - # (hash)
-- - $ (dollar)
-- - The identifier is not part of a code section for which the formatter is disabled.
-- - The identifier is not part of a conditional compilation block.
-- - The identifier is not a reserved keyword
-- - The variable keepQuotedIdentifiersForCall is true (set at the beginning, disabled for Java)
--
-- Quoted identifiers look like strings in Java and other languages. The parser in SQLDev 22.2.0 does not
-- understand Java stored procedures. Trying to format a Java stored procedure leads to a syntax error.
-- However, the formatter tries nonetheless to format the code with a best effort approach. This will lead
-- to a broken formatter result. To avoid that, the undocumented formatter option "formatWhenSyntaxError"
-- must be set to "false".
--
-- This section changes the target.input and requires a reparse.
-- However, the reparse is done in the section I6, which can handle an amended target.input.
i11_enforce_nonquoted_identifiers:
runOnce
-> {
var offOnRanges = [];
var populateOffOnRanges = function(tokens) {
var off = -1;
offOnRanges = [];
for (var i in tokens) {
var type = tokens[i].type;
if (type == Token.LINE_COMMENT || type == Token.COMMENT) {
if (tokens[i].content.toLowerCase().indexOf("@formatter:off") != -1 || tokens[i].content.toLowerCase().indexOf("noformat start") != -1) {
off = tokens[i].begin;
}
if (off != -1) {
if (tokens[i].content.toLowerCase().indexOf("@formatter:on") != -1 || tokens[i].content.toLowerCase().indexOf("noformat end") != -1) {
offOnRanges.push([off, tokens[i].end]);
off = -1;
}
}
}
}
}
var inOffOnRange = function(pos) {
for (var x in offOnRanges) {
if (pos >= offOnRanges[x][0] && pos < offOnRanges[x][1]) {
return true;
}
}
return false;
}
var reservedKeywords = new HashSet(Arrays.asList("ACCESS","ADD","AFTER","ALL","ALLOW","ALTER","ANALYTIC","AND",
"ANY","ANYSCHEMA","AS","ASC","ASSOCIATE","AUDIT","AUTHID","AUTOMATIC","AUTONOMOUS_TRANSACTION","BEFORE",
"BEGIN","BETWEEN","BULK","BY","BYTE","CANONICAL","CASE","CASE-SENSITIVE","CHAR","CHECK","CLUSTER","COLUMN",
"COLUMN_VALUE","COMMENT","COMPOUND","COMPRESS","CONNECT","CONNECT_BY_ROOT","CONSTANT","CONSTRAINT",
"CONSTRUCTOR","CORRUPT_XID","CORRUPT_XID_ALL","CREATE","CROSSEDITION","CURRENT","CUSTOMDATUM","CYCLE",
"DATE","DB_ROLE_CHANGE","DECIMAL","DECLARE","DECREMENT","DEFAULT","DEFAULTS","DEFINE","DEFINER","DELETE",
"DESC","DETERMINISTIC","DIMENSION","DISALLOW","DISASSOCIATE","DISTINCT","DROP","EACH","EDITIONING","ELSE",
"ELSIF","END","EVALNAME","EXCEPT","EXCEPTION","EXCEPTIONS","EXCEPTION_INIT","EXCLUSIVE","EXISTS","EXTERNAL",
"FETCH","FILE","FLOAT","FOLLOWING","FOLLOWS","FOR","FORALL","FROM","GOTO","GRANT","GROUP","HAVING","HIDE",
"HIER_ANCESTOR","HIER_LAG","HIER_LEAD","HIER_PARENT","IDENTIFIED","IF","IGNORE","IMMEDIATE","IMMUTABLE",
"IN","INCREMENT","INDEX","INDICATOR","INDICES","INITIAL","INITIALLY","INLINE","INSERT","INSTEAD","INTEGER",
"INTERSECT","INTO","INVISIBLE","IS","ISOLATION","JAVA","JSON_EXISTS","JSON_TABLE","LATERAL","LEVEL","LIBRARY",
"LIKE","LIKE2","LIKE4","LIKEC","LOCK","LOGON","LONG","MAXEXTENTS","MAXVALUE","MEASURES","MERGE","MINUS",
"MINVALUE","MLSLABEL","MODE","MODIFY","MULTISET","MUTABLE","NAN","NAV","NCHAR_CS","NESTED_TABLE_ID","NOAUDIT",
"NOCOMPRESS","NOCOPY","NOCYCLE","NONSCHEMA","NORELY","NOT","NOVALIDATE","NOWAIT","NULL","NUMBER","OF",
"OFFLINE","ON","ONLINE","ONLY","OPTION","OR","ORADATA","ORDER","ORDINALITY","OVER","OVERRIDING",
"PARALLEL_ENABLE","PARTITION","PASSING","PAST","PCTFREE","PIPELINED","PIVOT","PRAGMA","PRECEDES",
"PRECEDING","PRESENT","PRIOR","PROCEDURE","PUBLIC","RAW","REFERENCES","REFERENCING","REJECT","RELY",
"RENAME","REPEAT","RESOURCE","RESPECT","RESTRICT_REFERENCES","RESULT_CACHE","RETURNING","REVOKE","ROW",
"ROWID","ROWNUM","ROWS","SELECT","SEQUENTIAL","SERIALIZABLE","SERIALLY_REUSABLE","SERVERERROR","SESSION",
"SET","SETS","SHARE","SIBLINGS","SINGLE","SIZE","SMALLINT","SOME","SQLDATA","SQL_MACRO","STANDALONE",
"START","SUBMULTISET","SUBPARTITION","SUCCESSFUL","SUPPRESSES_WARNING_6009","SYNONYM","SYSDATE","TABLE",
"THE","THEN","TO","TRIGGER","UDF","UID","UNBOUNDED","UNDER","UNION","UNIQUE","UNLIMITED","UNPIVOT","UNTIL",
"UPDATE","UPSERT","USER","USING","VALIDATE","VALUES","VARCHAR","VARCHAR2","VARRAY","VARYING","VIEW",
"WHEN","WHENEVER","WHERE","WHILE","WINDOW","WITH","XMLATTRIBUTES","XMLEXISTS","XMLFOREST","XMLNAMESPACES",
"XMLQUERY","XMLROOT","XMLSCHEMA","XMLSERIALIZE","XMLTABLE"));
var isKeyword = function(token) {
return reservedKeywords.contains(replaceAll(token.content,'"', ""));
}
var isUnquotingAllowed = function(token) {
if (!Pattern.matches('^"[A-Z][A-Z0-9_$#]*"$', token.content)) {
return false;
}
if (isKeyword(token)) {
return false;
}
return true;
}
var findAndConvertQuotedIdentifiers = function() {
var tokens = LexerToken.parse(target.input,true); // parse with WS symbols
populateOffOnRanges(tokens);
var newInput = new StringBuilder(target.input);
var delpos = [];
var hiddenTokenCount = 0;
var conditionalBlock = false;
for (var i in tokens) {
var type = tokens[i].type;
if (type == Token.MACRO_SKIP) {
var content = tokens[i].content.toLowerCase();
if (content.indexOf("$if ") == 0) {
conditionalBlock = true;
} else if (content.indexOf("$end") == 0) {
conditionalBlock = false;
}
}
if (type == Token.DQUOTED_STRING && isUnquotingAllowed(tokens[i]) && !inOffOnRange(tokens[i].begin) && !conditionalBlock) {
delpos.push(tokens[i].begin);
delpos.push(tokens[i].end-1);
logger.fine(struct.getClass(), "i11_enforce_nonquoted_identifiers: at " + (i-hiddenTokenCount) + ".");
} else if (type == Token.LINE_COMMENT || type == Token.COMMENT || type == Token.WS ||
type == Token.MACRO_SKIP || type == Token.SQLPLUSLINECONTINUE_SKIP)
{
hiddenTokenCount++;
}
}
var i = delpos.length - 1;
while (i >= 0) {
newInput.deleteCharAt(delpos[i]);
i--;
}
target.input = newInput.toString();
}
// get custom option keepQuotedIdentifiers (might not exist)
var keepQuotedIdentifiers = struct.options.get("keepQuotedIdentifiers");
if ((keepQuotedIdentifiers == null || !keepQuotedIdentifiers) && !keepQuotedIdentifiersForCall) {
findAndConvertQuotedIdentifiers();
}
}
-- --------------------------------------------------------------------------------------------------------------------
-- I6: Remove duplicate empty lines.
-- --------------------------------------------------------------------------------------------------------------------
-- Replace multiple, consecutive empty lines with one empty line.
-- This code changes the input (target.input) and the lexer tokens (target.src).
-- Therefore this code must run at the beginning of the Arbori program.
-- The functions populateOffOnRanges and inOffOnRange are defined in I11.
i6_remove_duplicate_empty_lines:
runOnce
-> {
var removeDuplicateEmptyLines = function() {
var tokens = LexerToken.parse(target.input,true); // parse with WS symbols
populateOffOnRanges(tokens);
var substitutions = new Substitutions(target.input);
var firstEOLToken = 0;
var secondEOLToken = 0;
var lastEOLToken = 0;
for (i = 0; i < tokens.length; i++) {
var type = tokens[i].type;
if (tokens[i].content == "\n") {
if (firstEOLToken == 0) {
firstEOLToken = tokens[i];
} else if (secondEOLToken == 0) {
secondEOLToken = tokens[i];
} else {
lastEOLToken = tokens[i];
}
continue;
}
if (type != Token.WS) {
if (lastEOLToken != 0) {
if (!inOffOnRange(secondEOLToken.begin)) {
substitutions.put(secondEOLToken.begin,lastEOLToken.begin,"");
}
}
firstEOLToken = 0;
secondEOLToken = 0;
lastEOLToken = 0;
}
}
// update source code
target.input = substitutions.transformInput();
}
// replacements
removeDuplicateEmptyLines();
// tokens without WS and comments (mimicking default behaviour)
var Lexer = Java.type('oracle.dbtools.parser.Lexer');
var defaultTokens = Lexer.parse(target.input);
// produce a new parse tree based on the updated lexer tokens
var Parsed = Java.type('oracle.dbtools.parser.Parsed');
var SqlEarley = Java.type('oracle.dbtools.parser.plsql.SqlEarley')
var newTarget = new Parsed(target.input, defaultTokens, SqlEarley.getInstance(), Java.to(["sql_statements"], "java.lang.String[]"));
// update token list based on fixed source code (without WS tokens)
target.src.clear();
target.src.addAll(newTarget.src);
// enable next line to print all node names on the console (e.g. when SQLDev UI shows unnamed nodes)
// target.root.printTree();
}
-- --------------------------------------------------------------------------------------------------------------------
-- I4: Define identifiers
-- --------------------------------------------------------------------------------------------------------------------
-- analytic functions, to be treated as keywords
i4_analytics:
[identifier) identifier
& [call) analytic_function
& [call = [identifier
;
-- all identifiers
i4_ids:
[identifier) identifier
;
-- Callback function to reduce the list of keywords by the identifiers provided here
-- This is relevant for general options "Keyword case" and "Indentifier case".
identifiers:
i4_ids - i4_analytics
->
;
-- --------------------------------------------------------------------------------------------------------------------
-- I7: Keep existing whitespace.
-- --------------------------------------------------------------------------------------------------------------------
-- add explicit whitespace before each leaf node, if the whitespace before is not a single space (default)
i7_keep_significant_whitespace:
runOnce
-> {
tokens = LexerToken.parse(target.input, true); // include hidden tokens not relevant to build a parse tree
var hiddenTokenCount = 0;
var wsBefore = "";
for (var i in tokens) {
var type = tokens[i].type;
// count hidden tokens
if (type == Token.LINE_COMMENT || type == Token.COMMENT || type == Token.WS ||
type == Token.MACRO_SKIP || type == Token.SQLPLUSLINECONTINUE_SKIP)
{
hiddenTokenCount++;
// concatenate whitespace before a node
if (type == Token.WS) {
wsBefore += tokens[i].content;
} else {
// ensure that other hidden token are not counted as whitespace
wsBefore = "";
}
} else {
// enforce uniform datatype in map; therefore convert values to Integer
mapParserPosToLexerPos.put(Integer.valueOf(i-hiddenTokenCount), i);
if (i-hiddenTokenCount == 0 && hiddenTokenCount == wsBefore.length) {
// first parser token with leading whitespace only (no other hidden tokens like comments)
struct.putNewline(0, "");
logger.fine(struct.getClass(), "i7_keep_significant_whitespace: remove all whitespace at 0.");
} else if (wsBefore != " ") {
// add collected whitespace before leaf node (actually at the position of the leaf node)
// add also empty strings to ensure that not a space is added between tokens
struct.putNewline(i-hiddenTokenCount, wsBefore);
logger.fine(struct.getClass(), "i7_keep_significant_whitespace: add "
+ wsBefore.length + " whitespace at " + (i-hiddenTokenCount) + ".");
}
wsBefore = "";
}
}
}
-- --------------------------------------------------------------------------------------------------------------------
-- I8: Save indentations of parser node positions in first selection directive.
-- --------------------------------------------------------------------------------------------------------------------
-- Only tokens of the first branch in a condition compilation block are visible as parser tokens.
-- The parser expects valid code within this branch. If the branch contains something
-- else (e.g. code templates as used in FTLDB or tePLSQLPL) an incomplete
-- parse tree is produced and therefore also an unsatisfactory formatting result.
-- We populate a hash map containing parser token positions in the first conditional compilation block
-- with their initial indent. At the end of the Arbori program we reset the indentation to the
-- original values. This way we don't have to deal with conditional compilation in other sections.
-- We cannot use dontFormatNode because the indent of the first position in a consecutive list
-- of positions is ignored. However, depending on the configuration the case of keywords and
-- identifiers is changed.
i8_save_indent_in_conditional_branch:
runOnce
-> {
var pos = 0;
var withinFirstBranch = false;
for (var i in tokens) {
var type = tokens[i].type
var content = tokens[i].content.toLowerCase()
if (type == Token.MACRO_SKIP && content.indexOf("$if ") == 0) {
withinFirstBranch = true;
continue;
}
if (withinFirstBranch && type == Token.MACRO_SKIP && content.indexOf("$") == 0) {
withinFirstBranch = false;
continue;
}
if (type != Token.LINE_COMMENT && type != Token.COMMENT && type != Token.WS &&
type != Token.MACRO_SKIP && type != Token.SQLPLUSLINECONTINUE_SKIP)
{
if (withinFirstBranch) {
// enforce uniform datatype in map; therefore convert values to Integer
indentInConditionalBranch.put(Integer.valueOf(pos), getIndent(pos));
logger.fine(struct.getClass(), "i8_save_indent_in_conditional_branch: at " + pos + ".");
}
pos++;
}
}
}
-- --------------------------------------------------------------------------------------------------------------------
-- I9: Remove duplicate spaces in scope.
-- --------------------------------------------------------------------------------------------------------------------
-- In scope are statements for that are formatted fully (see overrideIndents).
-- Only spaces after the last new line character are considered. So, all line breaks are kept.
i9_remove_duplicate_spaces_in_scope:
runOnce
-> {
var keys = newlinePositions.keySet().stream().collect(Collectors.toList()).toArray();
for (var i in keys) {
var pos = keys[i];
if (overrideIndents(pos)) {
var indent = getIndent(pos);
var nlpos = indent.lastIndexOf("\n");
if (nlpos == -1) {
if (indent.length > 1) {
struct.putNewline(pos, " ");
logger.fine(struct.getClass(), "i9_remove_duplicate_spaces_in_scope: single space at " + pos + ".");
}
} else {
var spaces = indent.length - nlpos - 1;
if (spaces > 0) {
struct.putNewline(pos, indent.substring(0, nlpos+1));
logger.fine(struct.getClass(), "i9_remove_duplicate_spaces_in_scope: keeping line breaks only at "
+ pos + ".");
}
}
}
}
}
-- ====================================================================================================================
-- Phase 2 - Apply rules.
-- ====================================================================================================================
-- Sections:
-- - A1: Do not use tabs.
-- - A2: Remove trailing spaces.
-- - A3: Do not format code between @formatter:off and @formatter:on comments.
-- - O2: White Space: Around operators. Options: true; false. (spaceAroundOperators).
-- - A22: No space between sign and digits.