forked from JSQLParser/JSqlParser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSqlParserCC.jjt
More file actions
14025 lines (12999 loc) · 449 KB
/
Copy pathJSqlParserCC.jjt
File metadata and controls
14025 lines (12999 loc) · 449 KB
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
/*
* #%L
* JSQLParser library
* %%
* Copyright (C) 2004 - 2021 JSQLParser
* %%
* Dual licensed under GNU LGPL 2.1 or Apache License 2.0
* #L%
*/
options {
IGNORE_CASE = true;
STATIC = false;
DEBUG_PARSER = false;
DEBUG_LOOKAHEAD = false;
DEBUG_TOKEN_MANAGER = false;
CACHE_TOKENS = false;
// FORCE_LA_CHECK = true;
UNICODE_INPUT = true;
JAVA_TEMPLATE_TYPE = "modern";
// JDK_VERSION = "1.8";
TOKEN_EXTENDS = "BaseToken";
COMMON_TOKEN_ACTION = true;
NODE_DEFAULT_VOID = true;
TRACK_TOKENS = true;
VISITOR = true;
GRAMMAR_ENCODING = "UTF-8";
KEEP_LINE_COLUMN = true;
// USER_CHAR_STREAM = false;
}
PARSER_BEGIN(CCJSqlParser)
package net.sf.jsqlparser.parser;
import java.lang.reflect.Field;
import java.lang.Integer;
import net.sf.jsqlparser.parser.feature.*;
import net.sf.jsqlparser.expression.*;
import net.sf.jsqlparser.expression.operators.arithmetic.*;
import net.sf.jsqlparser.expression.operators.conditional.*;
import net.sf.jsqlparser.expression.operators.relational.*;
import net.sf.jsqlparser.schema.*;
import net.sf.jsqlparser.statement.*;
import net.sf.jsqlparser.statement.analyze.*;
import net.sf.jsqlparser.statement.alter.*;
import net.sf.jsqlparser.statement.alter.sequence.*;
import net.sf.jsqlparser.statement.comment.*;
import net.sf.jsqlparser.statement.create.database.*;
import net.sf.jsqlparser.statement.create.function.*;
import net.sf.jsqlparser.statement.create.index.*;
import net.sf.jsqlparser.statement.create.policy.*;
import net.sf.jsqlparser.statement.create.procedure.*;
import net.sf.jsqlparser.statement.create.schema.*;
import net.sf.jsqlparser.statement.create.synonym.*;
import net.sf.jsqlparser.statement.create.sequence.*;
import net.sf.jsqlparser.statement.create.table.*;
import net.sf.jsqlparser.statement.create.view.*;
import net.sf.jsqlparser.statement.delete.*;
import net.sf.jsqlparser.statement.drop.*;
import net.sf.jsqlparser.statement.insert.*;
import net.sf.jsqlparser.statement.execute.*;
import net.sf.jsqlparser.statement.piped.*;
import net.sf.jsqlparser.statement.select.*;
import net.sf.jsqlparser.statement.refresh.*;
import net.sf.jsqlparser.statement.show.*;
import net.sf.jsqlparser.statement.truncate.*;
import net.sf.jsqlparser.statement.update.*;
import net.sf.jsqlparser.statement.upsert.*;
import net.sf.jsqlparser.statement.merge.*;
import net.sf.jsqlparser.statement.grant.*;
import net.sf.jsqlparser.statement.imprt.*;
import net.sf.jsqlparser.statement.export.*;
import net.sf.jsqlparser.statement.lock.*;
import java.util.*;
import java.util.AbstractMap.SimpleEntry;
import net.sf.jsqlparser.statement.select.SetOperationList.SetOperationType;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The parser generated by JavaCC
*/
public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
public final static Logger LOGGER = Logger.getLogger(CCJSqlParser.class.getName());
public int bracketsCounter = 0;
public int caseCounter = 0;
public boolean interrupted = false;
public CCJSqlParser withConfiguration(FeatureConfiguration configuration) {
token_source.configuration = configuration;
return this;
}
public FeatureConfiguration getConfiguration() {
return token_source.configuration;
}
public CCJSqlParser me () {
return this;
}
// depth of open ClickHouse-style ternary then-branches: a ":" directly after the
// then-branch closes the ternary and must not be taken as the JSON path operator
private int ternaryThenBranchDepth = 0;
private void linkAST(ASTNodeAccess access, Node node) {
access.setASTNode(node);
node.jjtSetValue(access);
}
public Node getASTRoot() {
return jjtree.rootNode();
}
private static class ObjectNames {
private final List<String> names;
private final List<String> delimiters;
public ObjectNames(List<String> names, List<String> delimiters) {
this.names = names;
this.delimiters = delimiters;
}
public List<String> getNames() {
return names;
}
public List<String> getDelimiters() {
return delimiters;
}
}
private static void appendWhitespaceFromTokenGap(StringBuilder buffer, Token prev, Token curr) {
if (prev == null) return;
int lineDiff = curr.beginLine - prev.endLine;
if (lineDiff > 0) {
for (int i = 0; i < lineDiff; i++) buffer.append('\n');
for (int i = 1; i < curr.beginColumn; i++) buffer.append(' ');
} else {
int spaceCount = curr.beginColumn - prev.endColumn - 1;
for (int i = 0; i < spaceCount; i++) buffer.append(' ');
}
}
private static void appendTokenImageAndTrackDelimiter(StringBuilder buffer, Deque<Character> windowQueue,
int delimiterLength, String image, String tag) {
for (char ch : image.toCharArray()) {
buffer.append(ch);
windowQueue.addLast(ch);
if (windowQueue.size() > delimiterLength) {
windowQueue.removeFirst();
}
}
}
private static boolean endsWithDelimiter(Deque<Character> windowQueue, String delimiter) {
if (windowQueue.size() != delimiter.length()) return false;
int i = 0;
for (char ch : windowQueue) {
if (ch != delimiter.charAt(i++)) return false;
}
return true;
}
/**
* Checks whether the given token can start the operator in a RegularCondition
* (comparison operators, JSON operators, regex operators, geometry distance, etc.)
*
* Used to avoid expensive syntactic lookaheads like LOOKAHEAD(RegularCondition()).
* By the time this is called, lower-precedence operators like "-" (subtraction)
* and "||" (concatenation) have already been consumed by SimpleExpression,
* so seeing them here means they are comparison-level operators.
*/
protected boolean isComparisonOperatorAhead() {
try {
Token token = getToken(1);
if (token.image.equals("(") && getToken(2).image.equals("+")) {
// Oracle (+) — only route to RegularConditionRHS if a real
// comparison operator follows after "(" "+" ")"
return isComparisonOperator(getToken(4));
}
if ("?".equals(token.image) && isTernaryAhead()) {
// ClickHouse ternary `cond ? then : else` — the `?` must not be taken
// as the PostgreSQL JSON operator here, it is consumed by prattExpressionRest
return false;
}
return isComparisonOperator(token);
} catch (Exception e) {
return false;
}
}
protected static boolean isComparisonOperator(Token token) {
if (token.image == null || token.image.isEmpty()) {
return false;
}
switch (token.image.charAt(0)) {
case '>': // >, >=
case '=': // =, =* but not => Oracle/PostgreSQL named parameter syntax
return !token.image.equals("=>");
case '~': // ~, ~*
return true;
case '<': // <, <=, <>, <@, <->, <#>, <=>, <&
return true;
case '*': return token.image.equals("*=");
case '!': return token.image.startsWith("!~") || token.image.startsWith("!=");
case '@': return token.image.equals("@@") || token.image.equals("@>");
case '?': return true; // ?, ?|, ?&
case '-': return true; // -, -#
case '|': return token.image.equals("||");
case '^': return token.image.startsWith("^=");
case '&': return token.image.equals("&&") || token.image.equals("&>");
default: return false;
}
}
/**
* True when the pending "?" starts a ClickHouse-style ternary conditional
* {@code cond ? then : else} rather than the PostgreSQL JSON operator:
* a standalone ":" closes the then-branch at the same nesting depth before
* any expression boundary (",", ";", EOF, an unbalanced closing bracket or a
* clause keyword such as FROM/WHERE). A ":" in operand position (directly
* after an operator) starts a JDBC named parameter instead and cannot close
* the then-branch.
*/
protected boolean isTernaryAhead() {
try {
int depth = 0;
Token prev = null;
for (int i = 2; ; i++) {
Token t = getToken(i);
if (t == null || t.kind == EOF) {
return false;
}
String image = t.image;
if ("(".equals(image) || "[".equals(image)) {
depth++;
} else if (")".equals(image) || "]".equals(image)) {
if (depth == 0) {
return false;
}
depth--;
} else if (depth == 0) {
if (":".equals(image) && canEndExpression(prev)) {
return true;
}
if (",".equals(image) || ";".equals(image)) {
return false;
}
switch (t.kind) {
case K_SELECT: case K_FROM: case K_WHERE: case K_GROUP:
case K_HAVING: case K_ORDER: case K_LIMIT: case K_UNION:
case K_INTERSECT: case K_EXCEPT: case K_MINUS: case K_INTO:
case K_VALUES: case K_FETCH: case K_OFFSET:
return false;
default:
break;
}
}
prev = t;
}
} catch (Exception e) {
return false;
}
}
/**
* True when the token can be the LAST token of an expression: an
* identifier, a literal, a JDBC parameter, or a balanced closing bracket.
* Only such a token may directly precede the ":" closing the ternary
* then-branch, since the then-branch must be a complete expression. A ":"
* in operand position instead (directly after an operator, e.g. `x = :name`
* or directly after the leading "?") starts a JDBC named parameter.
* DATA_TYPE tokens end expressions as well, because a cast's target type
* (`b :: int`) or a bare type keyword closes the then-branch. The bare "?"
* positional parameter has no token-kind constant (anonymous token), so it
* is recognized by its image, like the closing brackets.
*/
private boolean canEndExpression(Token t) {
if (t == null) {
return false;
}
switch (t.kind) {
case S_IDENTIFIER: case S_QUOTED_IDENTIFIER: case S_PARAMETER:
case S_LONG: case S_DOUBLE: case S_HEX: case S_CHAR_LITERAL:
case K_DATE_LITERAL: case K_DATETIMELITERAL: case DATA_TYPE:
case K_NULL: case K_TRUE: case K_FALSE:
return true;
default:
return (t.kind >= MIN_NON_RESERVED_WORD && t.kind <= MAX_NON_RESERVED_WORD)
|| ")".equals(t.image) || "]".equals(t.image)
|| "?".equals(t.image);
}
}
/**
* Tokens that have dedicated branches in PrimaryExpression AFTER the Function branch.
* If isFunctionAhead() returns true for these, Function() would consume them and fail.
*/
private boolean isNonFunctionKeyword(Token t) {
switch (t.kind) {
case K_CONNECT_BY_ROOT: // CONNECT_BY_ROOT (expr)
case K_PRIOR: // PRIOR expr
case K_STRUCT: // STRUCT(...)
return true;
default:
return false;
}
}
/**
* Scans ahead through a dotted identifier chain and checks if '(' follows.
* Distinguishes function calls like func(), schema.func(), a.b.c.func()
* from column references like col, schema.col, a.b.c.col.
*
* Replaces LOOKAHEAD(16) on Function() with a targeted O(chain-length) check.
*/
protected boolean isFunctionAhead() {
try {
int i = 1;
Token t = getToken(i);
// JDBC escape function: {fn ...} — must check for FN keyword
if (t.image.equals("{")) {
return getToken(2).kind == K_FN;
}
// Optional APPROXIMATE keyword
if (t.kind == K_APPROXIMATE) {
i++;
t = getToken(i);
}
// Exclude tokens that have their own dedicated branches
// after Function() in PrimaryExpression
if (isNonFunctionKeyword(t)) {
return false;
}
// First token must not be a literal, bracket, or EOF
if (t.kind == S_LONG || t.kind == S_DOUBLE || t.kind == S_HEX
|| t.kind == S_CHAR_LITERAL || t.kind == OPENING_BRACKET
|| t.kind == CLOSING_BRACKET || t.kind == EOF) {
return false;
}
i++;
// Walk through dotted name chain
while (true) {
t = getToken(i);
if (t.image.equals(".") || t.image.equals("..")
|| t.image.equals("...") || t.image.equals(":")) {
i++; // skip delimiter
i++; // skip next name part
} else {
break;
}
}
// Must be followed by (
if (getToken(i).kind != OPENING_BRACKET) {
return false;
}
// Exclude Oracle join syntax: column(+)
if (getToken(i + 1).image.equals("+")
&& getToken(i + 2).kind == CLOSING_BRACKET) {
return false;
}
return true;
} catch (TokenMgrException e) {
return false;
}
}
/**
* True when the next token can only start a bare (unparenthesized) sub-select.
*
* Used where the alternative to Select() is an ExpressionList: the Pratt
* arithmetic loop runs inside a Java action (prattArithRest) and JavaCC does
* not execute actions while evaluating syntactic lookahead, so a jj_3R probe
* cannot see through any infix operator. A syntactic LOOKAHEAD(n) over an
* expression therefore fails as soon as an operator appears within the first
* n tokens - e.g. "( 1 + a ) / ( 1 + b )" - and control wrongly falls through
* to the Select() branch. This O(1) token check replaces that probe.
*/
protected boolean isUnparenthesizedSelectAhead() {
try {
int kind = getToken(1).kind;
return kind == K_SELECT || kind == K_WITH || kind == K_VALUES;
} catch (TokenMgrException e) {
return false;
}
}
/**
* Pratt arithmetic operator precedence loop.
* Handles: *, /, %, ^, DIV (prec=6) and +, -, ||, |, &, <<, >> (prec=5)
* Called only in real-parse mode (not syntactic-LOOKAHEAD mode) so action
* blocks execute correctly. Safe now that no syntactic production LOOKAHEADs
* scan through arithmetic expressions.
*/
/**
* Pratt boolean operator precedence loop.
* Handles OR (prec=2), XOR (prec=3), AND/&& (prec=4).
* Safe to use now that no syntactic production LOOKAHEADs scan through expressions.
*/
protected Expression prattExpressionRest(Expression left, int minPrec) throws ParseException {
while (!interrupted) {
Token t = getToken(1);
int op = t.kind;
boolean ternary = "?".equals(t.image) && isTernaryAhead();
int prec;
if (op == K_AND || op == OP_DOUBLEAND) prec = 4;
else if (op == K_XOR || op == K_OR) prec = 2;
else if (ternary) prec = 2;
else break;
if (prec < minPrec) break;
if (ternary) {
// ClickHouse-style ternary conditional: cond ? then : else
// Right-associative: both branches parse at the full expression
// level (prec 2), nested ternaries are absorbed by the else-branch.
jj_consume_token(op, t.image);
Expression thenExpression;
ternaryThenBranchDepth++;
try {
thenExpression = prattExpressionRest(Condition(), 2);
} finally {
ternaryThenBranchDepth--;
}
if (!":".equals(getToken(1).image)) {
throw new ParseException("Expected ':' closing the ternary conditional operator");
}
jj_consume_token(getToken(1).kind, getToken(1).image);
Expression elseExpression = prattExpressionRest(Condition(), 2);
left = new TernaryExpression(left, thenExpression, elseExpression);
continue;
}
jj_consume_token(op, getToken(1).image);
// +1 makes OR/AND/XOR left-associative
Expression right = prattExpressionRest(Condition(), prec + 1);
if (op == K_AND) {
left = new AndExpression(left, right);
} else if (op == OP_DOUBLEAND) {
AndExpression a = new AndExpression(left, right);
a.setUseOperator(true); left = a;
} else if (op == K_XOR) {
left = new XorExpression(left, right);
} else {
left = new OrExpression(left, right);
}
}
return left;
}
protected Expression prattArithRest(Expression left, int minPrec) throws ParseException {
while (!interrupted) {
Token t = getToken(1);
int op = t.kind;
int prec;
// Named tokens: OP_SLASH(/), OP_CARET(^), K_DIV, OP_CONCAT(||),
// OP_PIPE(|), OP_LSHIFT(<<), OP_RSHIFT(>>)
// String-literal tokens: *, +, -, %, & (unnamed in JavaCC grammar)
if (op == OP_SLASH || op == OP_CARET || op == K_DIV) prec = 6;
else if (op == OP_CONCAT || op == OP_PIPE
|| op == OP_LSHIFT || op == OP_RSHIFT) prec = 5;
else {
// Handle unnamed tokens by image
String img = t.image;
if ("*".equals(img) || "%".equals(img)) prec = 6;
else if ("+".equals(img) || "-".equals(img) || "&".equals(img)) prec = 5;
else break; // not an arithmetic operator
}
if (prec < minPrec) break;
// OP_PIPE: distinguish " | | " (space-sep concat) from single " | " (bitwise OR)
if (op == OP_PIPE && getToken(2).kind == OP_PIPE) {
jj_consume_token(OP_PIPE, getToken(1).image);
jj_consume_token(OP_PIPE, getToken(1).image);
Expression right = prattArithRest(PrimaryExpression(), prec + 1);
Concat r = new Concat(); r.setLeftExpression(left); r.setRightExpression(right); left = r;
continue;
}
jj_consume_token(op, getToken(1).image);
Expression right = prattArithRest(PrimaryExpression(), prec + 1);
if (op == OP_SLASH) { Division r = new Division(); r.setLeftExpression(left); r.setRightExpression(right); left = r; }
else if (op == OP_CARET) { net.sf.jsqlparser.expression.operators.arithmetic.BitwiseXor r = new net.sf.jsqlparser.expression.operators.arithmetic.BitwiseXor(); r.setLeftExpression(left); r.setRightExpression(right); left = r; }
else if (op == K_DIV) { IntegerDivision r = new IntegerDivision(); r.setLeftExpression(left); r.setRightExpression(right); left = r; }
else if (op == OP_CONCAT) { Concat r = new Concat(); r.setLeftExpression(left); r.setRightExpression(right); left = r; }
else if (op == OP_PIPE) { BitwiseOr r = new BitwiseOr(); r.setLeftExpression(left); r.setRightExpression(right); left = r; }
else if (op == OP_LSHIFT) { BitwiseLeftShift r = new BitwiseLeftShift(); r.setLeftExpression(left); r.setRightExpression(right); left = r; }
else if (op == OP_RSHIFT) { BitwiseRightShift r = new BitwiseRightShift(); r.setLeftExpression(left); r.setRightExpression(right); left = r; }
else {
String img = t.image;
if ("*".equals(img)) { Multiplication r = new Multiplication(); r.setLeftExpression(left); r.setRightExpression(right); left = r; }
else if ("+".equals(img)) { Addition r = new Addition(); r.setLeftExpression(left); r.setRightExpression(right); left = r; }
else if ("-".equals(img)) { Subtraction r = new Subtraction(); r.setLeftExpression(left); r.setRightExpression(right); left = r; }
else if ("%".equals(img)) { Modulo r = new Modulo(); r.setLeftExpression(left); r.setRightExpression(right); left = r; }
else if ("&".equals(img)) { BitwiseAnd r = new BitwiseAnd(); r.setLeftExpression(left); r.setRightExpression(right); left = r; }
}
}
return left;
}
// True when "(" opens a parenthesised FROM item (table/function/lateral/join)
// rather than a SELECT subquery. Cheap 2-token check replaces expensive
// syntactic LOOKAHEAD(ParenthesedFromItem()).
protected boolean isParenthesedFromItemAhead() {
try {
if (getToken(1).kind != OPENING_BRACKET) return false;
int k2 = getToken(2).kind;
// Direct subquery: ( SELECT/WITH ) → ParenthesedSelect handles it
// ( VALUES ) can be ParenthesedFromItem(Values) or ParenthesedSelect;
// ParenthesedFromItem is checked first so Values-as-FROM-item works
if (k2 == K_SELECT || k2 == K_WITH) return false;
// ( ( SELECT ) UNION ( SELECT ) ) → isNestedSetOperationAhead handles it
// Other (( patterns: ( (SELECT...) JOIN ... ) or ( (table) ) → ParenthesedFromItem
if (k2 == K_LATERAL) return false; // handled by LateralSubSelect
if (k2 == CLOSING_BRACKET) return false; // empty "()" is not valid
// EXASOL: ( IMPORT ... ) is a SubImport; handled at the outer FromItem level
// by LOOKAHEAD(2, Dialect.EXASOL...) SubImport() - must NOT go into ParenthesedFromItem
if (k2 == K_IMPORT) return false;
return true;
} catch (TokenMgrException e) { return false; }
}
// True when ( (SELECT ...) UNION/INTERSECT/EXCEPT (SELECT ...) ) — a set-operation
// subquery used as IN RHS. Bracket-scans past the inner select to verify a set
// operator follows, distinguishing from comma-separated ((SELECT...), (SELECT...)).
protected boolean isNestedSetOperationAhead() {
try {
if (getToken(1).kind != OPENING_BRACKET) return false;
if (getToken(2).kind != OPENING_BRACKET) return false;
// Skip any run of opening brackets: ( ( ( ... ( SELECT
int i = 3;
while (getToken(i).kind == OPENING_BRACKET) i++;
int k = getToken(i).kind;
if (k != K_SELECT && k != K_WITH && k != K_VALUES) return false;
// Scan forward counting brackets to find the matching ) for token(2)
// We are now inside all the opening brackets; depth = number of brackets skipped - 1
// (token(1) is the outer one, token(2..i-1) are the inner ones we scanned)
int depth = i - 2; // brackets from position 2 to i-1 inclusive
i++;
while (i <= 500) {
Token t; try { t = getToken(i); } catch (TokenMgrException e) { return false; }
if (t == null || t.kind == 0) return false;
if (t.kind == OPENING_BRACKET) depth++;
else if (t.kind == CLOSING_BRACKET) {
if (--depth == 0) break;
}
i++;
}
if (i > 500) return false;
// Token at position i+1 follows the innermost closing )
Token next; try { next = getToken(i + 1); } catch (TokenMgrException e) { return false; }
if (next == null) return false;
return next.kind == K_UNION || next.kind == K_INTERSECT ||
next.kind == K_EXCEPT || next.kind == K_MINUS;
} catch (TokenMgrException e) { return false; }
}
protected boolean isParenthesedSelectAhead() {
try {
if (getToken(1).kind != OPENING_BRACKET) return false;
int k = getToken(2).kind;
return k == K_SELECT || k == K_WITH || k == K_VALUES;
} catch (TokenMgrException e) {
return false;
}
}
protected boolean isImplicitCastAhead() {
try {
int k1 = getToken(1).kind;
// DT_ZONE (TIMESTAMP WITH TIME ZONE / WITHOUT TIME ZONE) is also a valid
// implicit cast type prefix handled by DataType(), but distinct from DATA_TYPE.
if (k1 == DT_ZONE) return true;
if (k1 != DATA_TYPE) return false;
int k2 = getToken(2).kind;
if (k2 != OPENING_BRACKET) return true; // DATA_TYPE literal - simple cast
// DATA_TYPE( ... ) - precision cast if content is only S_LONG literals
// function call otherwise (e.g. UUID(), VARCHAR(col))
int k3 = getToken(3).kind;
if (k3 == CLOSING_BRACKET) return false; // DATA_TYPE() - empty call
if (k3 != S_LONG) return false; // DATA_TYPE(expr) - function call
int k4 = getToken(4).kind;
if (k4 == CLOSING_BRACKET) return true; // DATA_TYPE(N) - precision cast
if (k4 != K_COMMA) return false; // DATA_TYPE(N expr) - function call
int k5 = getToken(5).kind;
if (k5 != S_LONG) return false; // DATA_TYPE(N, expr) - function call
return getToken(6).kind == CLOSING_BRACKET; // DATA_TYPE(N,M) - precision cast
} catch (TokenMgrException e) {
return false;
}
}
protected boolean isCaseExpressionAhead() {
try {
if (getToken(1).kind != K_CASE) return false;
int k2 = getToken(2).kind;
// CASE WHEN ... is unambiguously a CASE expression
if (k2 == K_WHEN) return true;
// CASE followed by tokens that only appear after an expression means
// CASE is being used as a column/table name identifier
if (k2 == K_FROM || k2 == K_WHERE || k2 == K_AS ||
k2 == K_AND || k2 == K_OR ||
k2 == K_IS || k2 == K_IN || k2 == K_LIKE || k2 == K_BETWEEN ||
k2 == K_THEN || k2 == K_ELSE || k2 == K_END ||
k2 == K_GROUP || k2 == K_ORDER || k2 == K_HAVING || k2 == K_LIMIT ||
k2 == K_UNION || k2 == K_INTERSECT || k2 == K_EXCEPT ||
k2 == K_OVER || k2 == CLOSING_BRACKET || k2 == 0) return false;
// Also check single-char operator tokens by image
Token t2 = getToken(2);
if (t2 != null && t2.image != null) {
String img = t2.image;
if (img.length() == 1) {
char c = img.charAt(0);
if (c == '=' || c == '>' || c == '<' || c == '+' || c == '-' ||
c == '*' || c == ',' || c == '.' || c == ';') return false;
}
}
// Otherwise assume it is a CASE expression with a switch value
return true;
} catch (TokenMgrException e) {
return false;
}
}
private boolean isKeywordArgumentAhead() {
Token t = getToken(1);
if (t.kind == EOF || t.image.equals(")")) return false;
if (t.image.isEmpty() || !Character.isLetter(t.image.charAt(0))) return false;
// S_QUOTED_IDENTIFIER is not a valid keyword arg name.
// S_IDENTIFIER and DATA_TYPE ARE allowed — after ExpressionList has
// consumed all comma-separated arguments, a remaining identifier or
// type keyword before ')' is a keyword argument name (e.g.
// PREDICTION(expr COST MODEL USING cols),
// XMLTABLE(... COLUMNS "col" VARCHAR2(6) PATH '...')).
if (t.kind == S_QUOTED_IDENTIFIER) return false;
switch (t.kind) {
case S_LONG: case S_DOUBLE: case S_HEX: case S_CHAR_LITERAL:
case K_DISTINCT: case K_ALL: case K_UNIQUE: case K_TABLE:
case K_ORDER: case K_ON: case K_HAVING: case K_IGNORE: case K_RESPECT:
case K_SELECT: case K_FROM: case K_WHERE: case K_GROUP: case K_LIMIT:
case K_UNION: case K_EXCEPT: case K_INTERSECT: case K_MINUS:
case K_JOIN: case K_INNER: case K_LEFT: case K_RIGHT: case K_FULL: case K_CROSS:
case K_INTO: case K_SET: case K_FETCH: case K_OFFSET:
case K_OVER: case K_WITHIN: case K_FILTER: case K_WITH: case K_WITHOUT:
case K_AND: case K_OR: case K_NOT: case K_IN: case K_BETWEEN: case K_LIKE:
case K_IS: case K_EXISTS: case K_AS:
case K_CASE: case K_WHEN: case K_THEN: case K_ELSE: case K_END:
case K_NULL: case K_TRUE: case K_FALSE:
case K_RETURNING:
return false;
}
Token t2 = getToken(2);
if (t2.kind == EOF || t2.image.equals(")")) return false;
return true;
}
/**
* Scans ahead through a dotted identifier chain and checks if '*' follows.
* Identifies table.* patterns for AllTableColumns.
*/
protected boolean isAllTableColumnsAhead() {
int i = 1;
Token t = getToken(i);
// Must start with a name-like token
if (t.kind == S_LONG || t.kind == S_DOUBLE || t.kind == S_HEX
|| t.kind == S_CHAR_LITERAL || t.kind == OPENING_BRACKET
|| t.kind == CLOSING_BRACKET || t.kind == EOF) {
return false;
}
i++;
// Walk through dotted name chain
while (true) {
t = getToken(i);
if (t.image.equals(".") || t.image.equals("..")
|| t.image.equals("...")) {
i++; // skip delimiter
i++; // skip next part (could be "*")
} else {
break;
}
}
// It's AllTableColumns if the chain ended on "*"
// i.e., the last name part we skipped over was "*"
// Back up: the last token consumed was at (i-1)
return getToken(i - 1).image.equals("*");
}
/**
* Detects PostgreSQL composite row expansion {@code (function()).*} (and any
* number of surrounding parentheses), where a parenthesised expression wrapping
* a single {@link Function} is immediately followed by {@code .*}.
*
* <p>This is a constant-time follower check (unwraps the already-parsed
* {@code retval} and peeks the next two tokens). It deliberately avoids the
* speculative syntactic lookahead that previously degraded performance, see
* issue #2207.
*
* @param retval the expression parsed so far within the
* {@code ParenthesedExpressionList} branch of {@code PrimaryExpression}
*/
protected boolean isFunctionAllColumnsAhead(Expression retval) {
// Fast follower gate: the overwhelming majority of parenthesised
// expressions are not followed by ".*", so reject on the token stream
// before ever touching the already-parsed expression.
if (!getToken(1).image.equals(".") || !getToken(2).image.equals("*")) {
return false;
}
if (retval == null) {
return false;
}
Expression inner = retval;
while (inner instanceof ParenthesedExpressionList) {
ParenthesedExpressionList<?> parenthesed = (ParenthesedExpressionList<?>) inner;
if (parenthesed.size() != 1) {
return false;
}
inner = parenthesed.get(0);
}
return inner instanceof Function;
}
/**
* Unwraps any number of surrounding parentheses from a parenthesised
* {@link Function} and returns the inner function. Only call this after
* {@link #isFunctionAllColumnsAhead(Expression)} has confirmed the shape.
*/
protected Function unwrapParenthesedFunction(Expression retval) {
Expression inner = retval;
while (inner instanceof ParenthesedExpressionList) {
inner = ((ParenthesedExpressionList<?>) inner).get(0);
}
return (Function) inner;
}
/**
* Whether the next token can continue the (possibly multi-word) keyword of
* an OPTION query hint, e.g. any word of {@code HASH JOIN}, {@code KEEP PLAN},
* {@code OPTIMIZE FOR UNKNOWN} or {@code IGNORE_NONCLUSTERED_COLUMNSTORE_INDEX}.
*
* Reserved words usable inside hint keywords are enumerated here because
* they cannot be matched by {@code RelObjectName()}.
*/
private boolean isOptionHintWordAhead() {
int kind = getToken(1).kind;
if (kind == S_IDENTIFIER
|| (kind >= MIN_NON_RESERVED_WORD && kind <= MAX_NON_RESERVED_WORD)) {
return true;
}
switch (kind) {
case K_JOIN: case K_FOR: case K_ORDER:
case K_UNION: case K_EXCEPT: case K_INTERSECT:
case K_USE: case K_OPTIMIZE: case K_FORCE: case K_UNKNOWN:
return true;
default:
return false;
}
}
/**
* Whether the next token can start the single value argument of an OPTION
* query hint, e.g. the {@code 100} of {@code FAST 100} or the {@code 25}
* of {@code MAX_GRANT_PERCENT = 25}.
*/
private boolean isOptionHintValueAhead() {
switch (getToken(1).kind) {
case S_LONG: case S_DOUBLE: case S_CHAR_LITERAL:
case S_PARAMETER:
return true;
default:
return false;
}
}
/**
* Follower-based disambiguation for reserved keywords in ambiguous
* positions (implicit alias, clause boundary, after parenthesised
* expression, etc.).
*
* Checks the candidate keyword ({@code getToken(1)}) and its follower
* ({@code getToken(2)}) to decide whether the keyword is being used as
* an identifier or as SQL syntax. Returns {@code true} only for
* keywords that provably don't collide with clause syntax in the
* current follower context.
*/
private boolean isReservedKeywordSafeByFollower() {
Token next2 = getToken(2);
// If followed by . or = the keyword is a name part / property key
if (next2.image != null
&& (next2.image.equals(".") || next2.image.equals("="))) {
return true;
}
int kind = getToken(1).kind;
int nextKind = next2.kind;
switch (kind) {
// Safe as implicit identifiers (no clause collision)
case K_TABLES: case K_OPTIMIZE: case K_PUBLIC:
case K_CASEWHEN: case K_IIF:
return true;
// Safe when the follower doesn't form a clause
case K_PROCEDURE: return nextKind != K_ANALYSE;
case K_GROUP: return nextKind != K_BY;
case K_ORDER: return nextKind != K_BY && nextKind != K_SIBLINGS;
case K_CONNECT: return nextKind != K_BY;
case K_START: return nextKind != K_WITH;
case K_LEFT: return nextKind != K_JOIN && nextKind != K_OUTER
&& nextKind != K_SEMI && nextKind != K_ARRAY_LITERAL;
case K_RIGHT: return nextKind != K_JOIN && nextKind != K_OUTER
&& nextKind != K_SEMI && nextKind != K_ARRAY_LITERAL;
case K_ARRAY_LITERAL:
return nextKind != K_JOIN;
case K_ALL: return nextKind != K_JOIN;
case K_ANY: return nextKind != OPENING_BRACKET;
case K_SOME: return nextKind != OPENING_BRACKET;
case K_IN: return nextKind != OPENING_BRACKET;
case K_IF: return nextKind != OPENING_BRACKET;
case K_GROUPING: return nextKind != OPENING_BRACKET;
case K_DEFAULT: return nextKind != K_VALUES;
case K_CREATE: return nextKind != K_TABLE && nextKind != K_VIEW
&& nextKind != K_INDEX;
case K_INTERVAL: return nextKind != S_LONG && nextKind != S_DOUBLE
&& nextKind != S_CHAR_LITERAL;
case K_TOP: return nextKind != S_LONG && nextKind != S_DOUBLE
&& nextKind != OPENING_BRACKET;
case K_NEXTVAL: return nextKind != K_VALUE;
// IGNORE: blocks NULLS (IGNORE NULLS), FROM (DELETE IGNORE FROM),
// INDEX (IGNORE INDEX hint)
case K_IGNORE: return nextKind != K_NULLS && nextKind != K_FROM
&& nextKind != K_INDEX;
// GLOBAL: blocks IN (GLOBAL IN), TEMPORARY, JOIN (GLOBAL JOIN)
case K_GLOBAL: return nextKind != K_IN && nextKind != K_TEMPORARY
&& nextKind != K_JOIN;
// Structural keywords — never safe as implicit identifiers
case K_SET: case K_ON: case K_QUALIFY:
case K_LIMIT: case K_OFFSET:
return false;
// VALUE/VALUES: safe as alias when not starting VALUES(...)
case K_VALUE: case K_VALUES:
return nextKind != OPENING_BRACKET && nextKind != S_IDENTIFIER
&& nextKind != S_QUOTED_IDENTIFIER && nextKind != S_CHAR_LITERAL;
default:
return false;
}
}
/**
* Determines whether a reserved keyword token can be treated as an unquoted
* identifier in the current parser position.
*
* Called from the semantic LOOKAHEAD inside {@code RelObjectName()}.
* Uses the previous token to detect name positions (after structural
* keywords, delimiters, AS), the follower token (after . or =), and
* falls back to conservative follower-based disambiguation.
*/
private boolean isReservedKeywordAsIdentifier() {
Token prev = getToken(0);
// Guard: at the very start of parsing (e.g. parseExpression()),
// prev may be null or have null image. This is always a name /
// expression position, so accept any keyword.
if (prev == null || prev.image == null) {
return true;
}
// ── 1. After AS: explicit alias — accept any keyword ──────────
if (prev.kind == K_AS) {
return true;
}
// ── 2. After delimiters and operators: expression position ─────
// With K_FROM/K_SELECT/K_CURRENT removed from RelObjectName's
// token list, accepting all remaining keywords after these
// delimiters and operators is safe.
if (!prev.image.isEmpty()) {
switch (prev.image.charAt(0)) {
// Structural delimiters
case '.': case ',': case ':': case '(': case '=':
// Comparison and arithmetic operators
case '>': case '<': case '!': case '^':
case '+': case '-': case '*': case '/': case '%':
case '~': case '|': case '&': case '?':
return true;
}
}
// ── 3. If followed by . or = the keyword is a name/property key ──
Token next2 = getToken(2);
if (next2.image != null
&& (next2.image.equals(".") || next2.image.equals("="))) {
return true;
}
// ── 4. After TRULY STRUCTURAL keywords that can NEVER be ──────
// consumed as identifiers (i.e. they are never in our own
// keyword-as-identifier set). After these, any keyword is
// safe as an identifier.
//
// Keywords that CAN be identifiers (LEFT, LIMIT, IGNORE,
// etc.) are NOT listed here because they may appear as
// getToken(0) after being consumed as identifiers or
// modifiers, which is NOT a name position.
switch (prev.kind) {
// Boolean / conditional operators
case K_AND: case K_OR: case K_NOT: case K_XOR:
// Clause keywords
case K_SELECT: case K_FROM: case K_WHERE: case K_HAVING:
case K_INTO: case K_USING: case K_SET: case K_ON:
case K_FETCH: case K_FOR: case K_WITH:
// Comparison / expression operators
case K_BETWEEN: case K_LIKE: case K_ILIKE: case K_IS:
// Join keywords
case K_JOIN: case K_INNER: case K_OUTER: case K_FULL:
case K_CROSS: case K_NATURAL: case K_STRAIGHT: case K_SEMI:
case K_LATERAL:
// CASE/WHEN expression structure
case K_WHEN: case K_ELSE:
// Non-reserved keywords that structurally introduce expression
// positions (GROUP BY expr, ORDER BY expr, CASE WHEN x THEN expr)
case K_BY: case K_THEN:
// Modifiers
case K_DISTINCT: case K_DISTINCTROW:
// Set operators
case K_UNION: case K_EXCEPT: case K_INTERSECT: case K_MINUS:
// DDL / utility keywords (never identifiers)
case K_FOREIGN: case K_CONSTRAINT: case K_UNIQUE: case K_CHECK:
case K_FORCE:
case K_RETURNING: case K_OUTPUT: case K_IMPORT:
case K_PIVOT: case K_UNPIVOT:
case K_PRIOR: case K_WINDOW: case K_ONLY:
case K_PREFERRING: case K_PREWHERE:
case K_RETURNS: case K_EXISTS:
case K_QUALIFY: case K_CURRENT:
return true;
}
// ── 5. Conservative default: fall back to follower check ──────
return isReservedKeywordSafeByFollower();
}
/**
* Checks whether the next token(s) can plausibly start an {@code Alias}.
*
* Used as a semantic LOOKAHEAD guard at alias call-sites. Unlike
* {@link #isReservedKeywordAsIdentifier()}, this method does NOT use
* the structural-keyword whitelist (step 4), because an alias always
* follows an expression — never a structural keyword in isolation.
* Instead it goes directly to follower-based disambiguation for
* reserved keywords.
*/
private boolean isAliasAhead() {
Token t = getToken(1);
int kind = t.kind;
// AS always starts an alias
if (kind == K_AS) return true;
// String-literal alias: SELECT col 'myAlias'
if (kind == S_CHAR_LITERAL) return true;
// OPTION (...) introduces a query hint clause, not an alias
if (kind == K_OPTION && getToken(2).kind == OPENING_BRACKET) {