-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathPrattParser.java
More file actions
1315 lines (1203 loc) · 43.7 KB
/
Copy pathPrattParser.java
File metadata and controls
1315 lines (1203 loc) · 43.7 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
// Copyright 2026 Google LLC
//
// 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
//
// https://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.
package dev.cel.parser;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import dev.cel.common.CelAbstractSyntaxTree;
import dev.cel.common.CelIssue;
import dev.cel.common.CelOptions;
import dev.cel.common.CelSource;
import dev.cel.common.CelSourceLocation;
import dev.cel.common.CelValidationResult;
import dev.cel.common.Operator;
import dev.cel.common.ast.CelConstant;
import dev.cel.common.ast.CelExpr;
import dev.cel.common.internal.CelCodePointArray;
import dev.cel.common.internal.Constants;
import java.text.ParseException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import org.jspecify.annotations.Nullable;
/** Pratt parser implementation for CEL. */
final class PrattParser {
private static final Locale LOCALE = Locale.US;
/** Sentinel stored in {@link #positions} for expression ids that have no source position. */
private static final int NO_POSITION = -1;
private static final String ACCUMULATOR_NAME = "@result";
private static final CelExpr ERROR = CelExpr.newBuilder().setConstant(Constants.ERROR).build();
private static final Lexer.Token END_TOKEN =
new Lexer.Token(Lexer.TokenType.END, NO_POSITION, NO_POSITION);
/** Most logical chains are short; 8 avoids resizing for the overwhelming majority. */
private static final int INITIAL_CHAIN_CAPACITY = 8;
private static final class BinaryOpInfo {
final int precedence;
final String name;
final boolean isLogical;
final Lexer.TokenType type;
BinaryOpInfo(int precedence, String name, boolean isLogical, Lexer.TokenType type) {
this.precedence = precedence;
this.name = name;
this.isLogical = isLogical;
this.type = type;
}
}
private static final BinaryOpInfo[] binaryOps = initBinaryOps();
// Safe and desirable to use .ordinal() here:
// 1. Safe: This lookup table is strictly private and internal to PrattParser, never serialized or
// persisted. The array is sized to TokenType.values().length, so indexing by ordinal is
// guaranteed to be within bounds even if enum members change.
// 2. Desirable: Expression parsing checks binary operator info on every token in the input;
// direct array indexing by ordinal provides O(1) lookup with zero hashing, indirection,
// or boxing overhead on this critical hot path.
@SuppressWarnings("EnumOrdinal")
private static BinaryOpInfo[] initBinaryOps() {
BinaryOpInfo[] ops = new BinaryOpInfo[Lexer.TokenType.values().length];
ops[Lexer.TokenType.LOGICAL_OR.ordinal()] =
new BinaryOpInfo(1, Operator.LOGICAL_OR.getFunction(), true, Lexer.TokenType.LOGICAL_OR);
ops[Lexer.TokenType.LOGICAL_AND.ordinal()] =
new BinaryOpInfo(2, Operator.LOGICAL_AND.getFunction(), true, Lexer.TokenType.LOGICAL_AND);
ops[Lexer.TokenType.LESS.ordinal()] =
new BinaryOpInfo(3, Operator.LESS.getFunction(), false, Lexer.TokenType.LESS);
ops[Lexer.TokenType.LESS_EQUAL.ordinal()] =
new BinaryOpInfo(3, Operator.LESS_EQUALS.getFunction(), false, Lexer.TokenType.LESS_EQUAL);
ops[Lexer.TokenType.GREATER.ordinal()] =
new BinaryOpInfo(3, Operator.GREATER.getFunction(), false, Lexer.TokenType.GREATER);
ops[Lexer.TokenType.GREATER_EQUAL.ordinal()] =
new BinaryOpInfo(
3, Operator.GREATER_EQUALS.getFunction(), false, Lexer.TokenType.GREATER_EQUAL);
ops[Lexer.TokenType.EQUAL_EQUAL.ordinal()] =
new BinaryOpInfo(3, Operator.EQUALS.getFunction(), false, Lexer.TokenType.EQUAL_EQUAL);
ops[Lexer.TokenType.EXCLAMATION_EQUAL.ordinal()] =
new BinaryOpInfo(
3, Operator.NOT_EQUALS.getFunction(), false, Lexer.TokenType.EXCLAMATION_EQUAL);
ops[Lexer.TokenType.IN.ordinal()] =
new BinaryOpInfo(3, Operator.IN.getFunction(), false, Lexer.TokenType.IN);
ops[Lexer.TokenType.PLUS.ordinal()] =
new BinaryOpInfo(4, Operator.ADD.getFunction(), false, Lexer.TokenType.PLUS);
ops[Lexer.TokenType.MINUS.ordinal()] =
new BinaryOpInfo(4, Operator.SUBTRACT.getFunction(), false, Lexer.TokenType.MINUS);
ops[Lexer.TokenType.ASTERISK.ordinal()] =
new BinaryOpInfo(5, Operator.MULTIPLY.getFunction(), false, Lexer.TokenType.ASTERISK);
ops[Lexer.TokenType.SLASH.ordinal()] =
new BinaryOpInfo(5, Operator.DIVIDE.getFunction(), false, Lexer.TokenType.SLASH);
ops[Lexer.TokenType.PERCENT.ordinal()] =
new BinaryOpInfo(5, Operator.MODULO.getFunction(), false, Lexer.TokenType.PERCENT);
return ops;
}
private static final class UnaryOp {
final Lexer.Token token;
long id;
UnaryOp(Lexer.Token token) {
this.token = token;
}
}
private final CelSource source;
private final CelCodePointArray content;
private final CelOptions options;
private final ImmutableMap<String, CelMacro> macros;
private final Lexer lexer;
/**
* Code point offset of each expression node, indexed by expression id, with {@link #NO_POSITION}
* for nodes that have none. Ids are dense and handed out sequentially by {@link #nextId}, so an
* array avoids the boxing and hashing a {@code Map<Long, Integer>} would cost on every node.
*/
private int[] positions;
private Map<Long, CelExpr> macroCalls = ImmutableMap.of();
private PrattMacroExprFactory macroExprFactory;
private final List<CelIssue> issues;
private Lexer.Token currentToken;
private Lexer.Token peekToken;
private int recursionDepth;
private int currentLhsDepth;
private long nextId;
private boolean nodeLimitExceeded;
private boolean recursionLimitExceeded;
private int errorCount;
static CelValidationResult parse(
CelSource source, CelOptions options, Map<String, CelMacro> macros) {
if (source.getContent().size() > options.maxExpressionCodePointSize()) {
return new CelValidationResult(
source,
ImmutableList.of(
CelIssue.formatError(
CelSourceLocation.NONE,
String.format(
LOCALE,
"expression code point size exceeds limit: size: %d, limit %d",
source.getContent().size(),
options.maxExpressionCodePointSize()))));
}
PrattParser prattParser = new PrattParser(source, options, macros);
CelExpr expr = prattParser.run();
if (prattParser.recursionLimitExceeded || prattParser.errorCount > 0) {
return new CelValidationResult(source, ImmutableList.copyOf(prattParser.issues));
}
CelSource.Builder sourceBuilder = source.toBuilder();
prattParser.copyPositionsTo(sourceBuilder);
sourceBuilder.addAllMacroCalls(prattParser.macroCalls);
return new CelValidationResult(
CelAbstractSyntaxTree.newParsedAst(expr, sourceBuilder.build()),
ImmutableList.copyOf(prattParser.issues));
}
private PrattParser(CelSource source, CelOptions options, Map<String, CelMacro> macros) {
this.source = source;
this.content = source.getContent();
this.options = options;
this.macros = ImmutableMap.copyOf(macros);
this.lexer = new Lexer(content);
this.positions = new int[Math.max(16, Math.min(content.size() + 1, 1024))];
Arrays.fill(this.positions, NO_POSITION);
this.issues = new ArrayList<>();
this.nextId = 1;
peekToken = nextSignificantToken(true);
}
CelExpr run() {
CelExpr expr = parseExpr();
if (recursionLimitExceeded || isRecoveryLimitExceeded()) {
return expr;
}
while (peekToken.type != Lexer.TokenType.END && peekToken.type != Lexer.TokenType.ERROR) {
if (options.enableReservedIds()
&& (peekToken.type == Lexer.TokenType.RESERVED_WORD
|| peekToken.type == Lexer.TokenType.IN)) {
Lexer.Token resTok = nextToken();
String resText = normalizeIdent(resTok, /* allowQuoted= */ false);
reportError(resTok.start, String.format("reserved identifier: %s", resText));
continue;
}
reportSyntaxError(peekToken, "unexpected token after expression");
break;
}
return expr;
}
private boolean isRecoveryLimitExceeded() {
return errorCount > options.maxParseErrorRecoveryLimit();
}
private String getTokenText(Lexer.Token tok) {
if (tok.text != null) {
return tok.text;
}
if (tok.start >= 0 && tok.end >= tok.start && tok.end <= content.size()) {
return content.substring(tok.start, tok.end);
}
return "";
}
private Lexer.Token nextSignificantToken(boolean reportError) {
// The lexer skips whitespace and comments itself, so every token it returns is significant.
Lexer.Token tok = lexer.lex();
if (tok.type == Lexer.TokenType.ERROR && reportError) {
reportSyntaxError(tok, lexer.getError().message);
if (isRecoveryLimitExceeded()) {
return END_TOKEN;
}
}
return tok;
}
private Lexer.Token nextToken() {
currentToken = peekToken;
if (isRecoveryLimitExceeded()) {
peekToken = END_TOKEN;
return currentToken;
}
if (peekToken.type != Lexer.TokenType.END) {
peekToken = nextSignificantToken(true);
}
return currentToken;
}
private boolean expect(Lexer.TokenType type, String msg) {
if (peekToken.type == type) {
nextToken();
return true;
}
if (isRecoveryLimitExceeded()) {
return false;
}
if (peekToken.type != Lexer.TokenType.ERROR) {
String errMsg;
if (msg == null || msg.isEmpty()) {
String tokText = getTokenText(peekToken);
String formattedTok =
(peekToken.type == Lexer.TokenType.END) ? "<EOF>" : "'" + tokText + "'";
errMsg = "mismatched input " + formattedTok + " expecting '" + type.getSymbol() + "'";
} else {
errMsg = msg;
}
reportSyntaxError(peekToken, errMsg);
}
synchronizeOnDelimiter();
return false;
}
// Find the next delimiter to prevent a cascade of spurious secondary errors.
private void synchronizeOnDelimiter() {
if (isRecoveryLimitExceeded()) {
peekToken = END_TOKEN;
return;
}
while (peekToken.type != Lexer.TokenType.END) {
if (peekToken.type == Lexer.TokenType.COMMA
|| peekToken.type == Lexer.TokenType.RIGHT_PAREN
|| peekToken.type == Lexer.TokenType.RIGHT_BRACKET
|| peekToken.type == Lexer.TokenType.RIGHT_BRACE) {
break;
}
nextToken();
}
}
private long nextId(int position) {
long id = nextId++;
if (id > options.maxParseExpressionNodeCount() && !nodeLimitExceeded) {
reportError(
position,
String.format(
LOCALE,
"expression node limit (%d) exceeded",
options.maxParseExpressionNodeCount()));
nodeLimitExceeded = true;
}
if (!nodeLimitExceeded && position >= 0) {
setPosition(id, position);
}
return id;
}
private long nextId(Lexer.Token token) {
return nextId(token.start);
}
private long nextId() {
return nextId(NO_POSITION);
}
private void setPosition(long id, Lexer.Token token) {
if (token.start >= 0) {
setPosition(id, token.start);
}
}
private void setPosition(long id, int position) {
int index = (int) id;
if (index >= positions.length) {
int oldLength = positions.length;
positions = Arrays.copyOf(positions, Math.max(index + 1, oldLength * 2));
Arrays.fill(positions, oldLength, positions.length, NO_POSITION);
}
positions[index] = position;
}
/** Returns the recorded position of {@code id}, or {@link #NO_POSITION} if it has none. */
private int getPosition(long id) {
int index = (int) id;
return index >= 0 && index < positions.length ? positions[index] : NO_POSITION;
}
private void copyPositionsTo(CelSource.Builder sourceBuilder) {
ImmutableMap.Builder<Long, Integer> positionsMap =
ImmutableMap.builderWithExpectedSize((int) nextId);
for (long id = 1; id < nextId; id++) {
int position = getPosition(id);
if (position != NO_POSITION) {
positionsMap.put(id, position);
}
}
sourceBuilder.addPositionsMap(positionsMap.buildOrThrow());
}
private long copyId(long id) {
if (id == 0) {
return 0;
}
return nextId(getPosition(id));
}
private void eraseId(long id) {
int index = (int) id;
if (index >= 0 && index < positions.length) {
positions[index] = NO_POSITION;
}
if (nextId == id + 1) {
--nextId;
}
}
private void reportError(int position, String msg) {
CelSourceLocation loc =
position >= 0
? source.getOffsetLocation(position).orElse(CelSourceLocation.NONE)
: CelSourceLocation.NONE;
reportError(loc, msg);
}
private void reportError(CelSourceLocation loc, String msg) {
if (errorCount > options.maxParseErrorRecoveryLimit()) {
return;
}
errorCount++;
if (errorCount == options.maxParseErrorRecoveryLimit() + 1) {
issues.add(
CelIssue.formatError(
CelSourceLocation.NONE,
String.format(
LOCALE, "More than %d parse errors.", options.maxParseErrorRecoveryLimit())));
peekToken = END_TOKEN;
}
if (errorCount <= options.maxParseErrorRecoveryLimit()) {
issues.add(CelIssue.formatError(loc, msg));
}
}
private void reportSyntaxError(Lexer.Token token, String msg) {
reportError(token.start, "Syntax error: " + msg);
}
private boolean checkRecursion(int chainDepth, Lexer.Token token) {
if (recursionDepth + chainDepth > options.maxParseRecursionDepth()) {
reportRecursionLimit(token.start);
return true;
}
return false;
}
private void reportRecursionLimit(int position) {
if (!recursionLimitExceeded) {
recursionLimitExceeded = true;
reportError(
position,
String.format(
LOCALE,
"Expression recursion limit exceeded. limit: %d",
options.maxParseRecursionDepth()));
}
}
private CelExpr parseExpr() {
if (recursionLimitExceeded || errorCount > options.maxParseErrorRecoveryLimit()) {
return ERROR;
}
if (recursionDepth >= options.maxParseRecursionDepth()) {
reportRecursionLimit(peekToken.start);
return ERROR;
}
recursionDepth++;
CelExpr expr = parseBinaryAndTernary(0);
recursionDepth--;
return expr;
}
@SuppressWarnings("EnumOrdinal") // Using ordinal for O(1) binary operator lookup table
private CelExpr parseBinaryAndTernary(int minPrec) {
CelExpr lhs = parseSelectorChain();
int chainDepth = currentLhsDepth;
while (true) {
Lexer.TokenType tok = peekToken.type;
if (tok == Lexer.TokenType.QUESTION && minPrec <= 0) {
lhs = parseTernary(lhs);
continue;
}
BinaryOpInfo opInfo = binaryOps[tok.ordinal()];
if (opInfo == null || opInfo.precedence < minPrec) {
break;
}
if (opInfo.isLogical) {
lhs = parseBalancedLogicalChain(lhs, opInfo);
continue;
}
Lexer.Token opTok = nextToken();
if (recursionDepth + chainDepth > options.maxParseRecursionDepth()) {
reportRecursionLimit(opTok.start);
return ERROR;
}
chainDepth++;
long opId = nextId(opTok);
CelExpr rhs = parseBinaryAndTernary(opInfo.precedence + 1);
lhs = buildBinaryCall(opId, opInfo.name, lhs, rhs);
currentLhsDepth = chainDepth;
}
return lhs;
}
private CelExpr parseTernary(CelExpr lhs) {
Lexer.Token opTok = nextToken();
long opId = nextId(opTok);
CelExpr trueExpr = parseBinaryAndTernary(1);
if (!expect(Lexer.TokenType.COLON, "expected ':' in conditional expression")) {
return lhs;
}
CelExpr falseExpr = parseExpr();
return CelExpr.ofCall(
opId, Operator.CONDITIONAL.getFunction(), ImmutableList.of(lhs, trueExpr, falseExpr));
}
private CelExpr parseBalancedLogicalChain(CelExpr lhs, BinaryOpInfo opInfo) {
Lexer.Token opTok = nextToken();
long opId = nextId(opTok.start);
CelExpr rhs = parseBinaryAndTernary(opInfo.precedence + 1);
if (peekToken.type != opInfo.type) {
return buildBinaryCall(opId, opInfo.name, lhs, rhs);
}
CelExpr[] terms = new CelExpr[INITIAL_CHAIN_CAPACITY];
long[] ops = new long[INITIAL_CHAIN_CAPACITY];
terms[0] = lhs;
terms[1] = rhs;
ops[0] = opId;
int opsCount = 1;
int termsCount = 2;
while (peekToken.type == opInfo.type) {
opTok = nextToken();
opId = nextId(opTok.start);
rhs = parseBinaryAndTernary(opInfo.precedence + 1);
if (termsCount == terms.length) {
int newCapacity = terms.length * 2;
ops = Arrays.copyOf(ops, newCapacity);
terms = Arrays.copyOf(terms, newCapacity);
}
ops[opsCount++] = opId;
terms[termsCount++] = rhs;
}
return balancedTree(opInfo.name, terms, ops, 0, opsCount - 1);
}
private CelExpr balancedTree(String op, CelExpr[] terms, long[] ops, int lo, int hi) {
int mid = (lo + hi + 1) / 2;
CelExpr left = (mid == lo) ? terms[mid] : balancedTree(op, terms, ops, lo, mid - 1);
CelExpr right = (mid == hi) ? terms[mid + 1] : balancedTree(op, terms, ops, mid + 1, hi);
return buildBinaryCall(ops[mid], op, left, right);
}
private static CelExpr buildBinaryCall(long id, String function, CelExpr lhs, CelExpr rhs) {
return CelExpr.ofCall(id, function, ImmutableList.of(lhs, rhs));
}
private static CelExpr buildUnaryCall(long id, String function, CelExpr operand) {
return CelExpr.ofCall(id, function, ImmutableList.of(operand));
}
private CelExpr parseSelectorChain() {
Lexer.TokenType tok = peekToken.type;
CelExpr lhs =
(tok == Lexer.TokenType.EXCLAMATION || tok == Lexer.TokenType.MINUS)
? parseUnaryOps()
: parsePrimary();
currentLhsDepth = 0;
tok = peekToken.type;
if (tok == Lexer.TokenType.DOT
|| tok == Lexer.TokenType.LEFT_BRACKET
|| tok == Lexer.TokenType.LEFT_BRACE) {
lhs = parseSelectorChainTail(lhs);
}
return lhs;
}
private CelExpr parseSelectorChainTail(CelExpr initialLhs) {
CelExpr lhs = initialLhs;
int chainDepth = 0;
while (true) {
Lexer.TokenType tok = peekToken.type;
if (tok == Lexer.TokenType.DOT) {
if (checkRecursion(chainDepth, peekToken)) {
return ERROR;
}
chainDepth++;
Lexer.Token dotTok = nextToken();
boolean optional = false;
if (peekToken.type == Lexer.TokenType.QUESTION) {
nextToken();
optional = true;
if (!options.enableOptionalSyntax()) {
reportError(dotTok.start, "unsupported syntax '.?'");
}
}
Lexer.Token idTok = nextToken();
if (idTok.type != Lexer.TokenType.IDENT
&& idTok.type != Lexer.TokenType.RESERVED_WORD
&& idTok.type != Lexer.TokenType.IN) {
if (idTok.type != Lexer.TokenType.ERROR) {
reportSyntaxError(idTok, "expected identifier after '.'");
}
synchronizeOnDelimiter();
currentLhsDepth = chainDepth;
return lhs;
}
boolean isMemberCall = (peekToken.type == Lexer.TokenType.LEFT_PAREN);
String idText = normalizeIdent(idTok, /* allowQuoted= */ !isMemberCall);
if (optional) {
long opId = nextId(dotTok);
CelExpr field =
CelExpr.ofConstant(nextId(getLeftmostPosition(lhs)), CelConstant.ofValue(idText));
lhs = buildBinaryCall(opId, Operator.OPTIONAL_SELECT.getFunction(), lhs, field);
} else if (peekToken.type == Lexer.TokenType.LEFT_PAREN) {
Lexer.Token lparen = nextToken();
long callId = nextId(lparen);
ImmutableList<CelExpr> args = parseArguments(Lexer.TokenType.RIGHT_PAREN);
Optional<CelExpr> expanded = tryExpandMacro(callId, idText, lhs, args);
lhs =
expanded.isPresent()
? expanded.get()
: CelExpr.ofCall(callId, Optional.of(lhs), idText, args);
} else {
lhs = CelExpr.ofSelect(nextId(dotTok), lhs, idText, /* isTestOnly= */ false);
}
} else if (tok == Lexer.TokenType.LEFT_BRACKET) {
if (checkRecursion(chainDepth, peekToken)) {
return ERROR;
}
chainDepth++;
Lexer.Token bracketTok = nextToken();
long opId = nextId(bracketTok);
boolean optional = false;
if (peekToken.type == Lexer.TokenType.QUESTION) {
nextToken();
optional = true;
if (!options.enableOptionalSyntax()) {
reportError(bracketTok.start, "unsupported syntax '?'");
}
}
CelExpr index = parseExpr();
expect(Lexer.TokenType.RIGHT_BRACKET, "expected ']'");
String opName =
optional ? Operator.OPTIONAL_INDEX.getFunction() : Operator.INDEX.getFunction();
lhs = buildBinaryCall(opId, opName, lhs, index);
} else if (tok == Lexer.TokenType.LEFT_BRACE) {
String structName = extractStructName(lhs);
if (structName == null) {
break;
}
lhs = parseStruct(nextId(peekToken.start), structName);
} else {
break;
}
}
currentLhsDepth = chainDepth;
return lhs;
}
private CelExpr parseUnaryOps() {
Lexer.Token op = nextToken();
Lexer.TokenType opType = op.type;
if (peekToken.type == Lexer.TokenType.EXCLAMATION || peekToken.type == Lexer.TokenType.MINUS) {
return parseUnaryOpsChain(op);
}
if (opType == Lexer.TokenType.MINUS) {
if (peekToken.type == Lexer.TokenType.INT) {
return parseIntLiteral(nextId(peekToken), /* isNegative= */ true);
}
if (peekToken.type == Lexer.TokenType.FLOAT) {
return parseDoubleLiteral(nextId(peekToken), /* isNegative= */ true);
}
}
if (checkRecursion(0, op)) {
return ERROR;
}
long opId = nextId(op);
recursionDepth++;
CelExpr operand = parseSelectorChain();
recursionDepth--;
if (recursionLimitExceeded) {
return ERROR;
}
String opName =
(opType == Lexer.TokenType.EXCLAMATION)
? Operator.LOGICAL_NOT.getFunction()
: Operator.NEGATE.getFunction();
return buildUnaryCall(opId, opName, operand);
}
private CelExpr parseUnaryOpsChain(Lexer.Token firstOp) {
List<UnaryOp> ops = new ArrayList<>();
ops.add(new UnaryOp(firstOp));
while (peekToken.type == Lexer.TokenType.EXCLAMATION
|| peekToken.type == Lexer.TokenType.MINUS) {
ops.add(new UnaryOp(nextToken()));
}
boolean hasSolitaryTrailingMinus =
!ops.isEmpty()
&& Iterables.getLast(ops).token.type == Lexer.TokenType.MINUS
&& (ops.size() == 1 || ops.get(ops.size() - 2).token.type != Lexer.TokenType.MINUS);
if (!options.retainRepeatedUnaryOperators()) {
int write = 0;
for (int read = 0; read < ops.size(); ) {
int next = read;
while (next < ops.size() && ops.get(next).token.type == ops.get(read).token.type) {
next++;
}
if ((next - read) % 2 != 0) {
ops.set(write++, ops.get(read));
}
read = next;
}
ops = new ArrayList<>(ops.subList(0, write));
}
for (UnaryOp op : ops) {
op.id = nextId(op.token);
}
boolean isNegativeNumericLiteral =
hasSolitaryTrailingMinus
&& (peekToken.type == Lexer.TokenType.INT || peekToken.type == Lexer.TokenType.FLOAT);
long negativeLiteralOpId = 0;
if (isNegativeNumericLiteral) {
negativeLiteralOpId = Iterables.getLast(ops).id;
ops.remove(ops.size() - 1);
}
int chainDepth = 0;
for (UnaryOp op : ops) {
if (checkRecursion(chainDepth, op.token)) {
return ERROR;
}
chainDepth++;
}
recursionDepth += ops.size();
CelExpr operand;
if (isNegativeNumericLiteral) {
operand =
(peekToken.type == Lexer.TokenType.INT)
? parseIntLiteral(negativeLiteralOpId, /* isNegative= */ true)
: parseDoubleLiteral(negativeLiteralOpId, /* isNegative= */ true);
operand = parseSelectorChainTail(operand);
} else {
operand = parseSelectorChain();
}
recursionDepth -= ops.size();
if (recursionLimitExceeded) {
return ERROR;
}
for (int i = ops.size() - 1; i >= 0; --i) {
String opName =
(ops.get(i).token.type == Lexer.TokenType.EXCLAMATION)
? Operator.LOGICAL_NOT.getFunction()
: Operator.NEGATE.getFunction();
operand = buildUnaryCall(ops.get(i).id, opName, operand);
}
return operand;
}
private CelExpr parseIdentOrCall() {
Lexer.TokenType tokType = peekToken.type;
boolean leadingDot = false;
Lexer.Token firstTok = peekToken;
if (tokType == Lexer.TokenType.DOT) {
nextToken();
leadingDot = true;
}
Lexer.Token idTok = nextToken();
if (idTok.type != Lexer.TokenType.IDENT && idTok.type != Lexer.TokenType.RESERVED_WORD) {
if (idTok.type != Lexer.TokenType.ERROR) {
reportSyntaxError(idTok, "expected identifier");
}
return CelExpr.newBuilder().setId(nextId(idTok)).build();
}
String idText = normalizeIdent(idTok, /* allowQuoted= */ false);
if (idTok.type == Lexer.TokenType.RESERVED_WORD && options.enableReservedIds()) {
reportError(idTok.start, String.format("reserved identifier: %s", idText));
}
String name = leadingDot ? "." + idText : idText;
if (peekToken.type == Lexer.TokenType.LEFT_PAREN) {
Lexer.Token lparen = nextToken();
long callId = nextId(lparen);
ImmutableList<CelExpr> args = parseArguments(Lexer.TokenType.RIGHT_PAREN);
Optional<CelExpr> expanded = tryExpandMacro(callId, name, null, args);
if (expanded.isPresent()) {
return expanded.get();
}
return CelExpr.ofCall(callId, name, args);
}
long id = nextId(leadingDot ? firstTok : idTok);
return CelExpr.ofIdent(id, name);
}
private CelExpr parsePrimary() {
switch (peekToken.type) {
case LEFT_PAREN:
{
int groupingParenCount = countGroupingParentheses();
if (checkRecursion(groupingParenCount, peekToken)) {
return ERROR;
}
for (int i = 0; i < groupingParenCount; ++i) {
nextToken();
}
CelExpr expr = parseExpr();
for (int i = 0; i < groupingParenCount; ++i) {
expect(Lexer.TokenType.RIGHT_PAREN, "");
}
return expr;
}
case NULL:
return CelExpr.ofConstant(nextId(nextToken()), Constants.NULL);
case TRUE:
case FALSE:
{
Lexer.Token tok = nextToken();
return CelExpr.ofConstant(
nextId(tok), tok.type == Lexer.TokenType.TRUE ? Constants.TRUE : Constants.FALSE);
}
case INT:
return parseIntLiteral(/* nodeId= */ -1, /* isNegative= */ false);
case UINT:
return parseUintLiteral();
case FLOAT:
return parseDoubleLiteral(/* nodeId= */ -1, /* isNegative= */ false);
case STRING:
return parseStringLiteral();
case BYTES:
return parseBytesLiteral();
case LEFT_BRACKET:
return parseList();
case LEFT_BRACE:
return parseMap();
case DOT:
case IDENT:
case RESERVED_WORD:
return parseIdentOrCall();
default:
{
Lexer.Token badTok = nextToken();
if (badTok.type != Lexer.TokenType.ERROR) {
if (badTok.type == Lexer.TokenType.END) {
reportSyntaxError(badTok, "mismatched input '<EOF>' expecting expression");
} else {
reportSyntaxError(badTok, "unexpected token");
}
}
return CelExpr.newBuilder().setId(nextId(badTok)).build();
}
}
}
private CelExpr parseList() {
Lexer.Token openTok = nextToken();
long listId = nextId(openTok);
ImmutableList.Builder<CelExpr> elements = ImmutableList.builder();
ImmutableList.Builder<Integer> optionalIndices = ImmutableList.builder();
int elemIndex = 0;
while (peekToken.type != Lexer.TokenType.RIGHT_BRACKET
&& peekToken.type != Lexer.TokenType.END) {
boolean optional = false;
if (peekToken.type == Lexer.TokenType.QUESTION) {
Lexer.Token q = nextToken();
optional = true;
if (!options.enableOptionalSyntax()) {
reportError(q.start, "unsupported syntax '?'");
}
}
elements.add(parseExpr());
if (optional) {
optionalIndices.add(elemIndex);
}
elemIndex++;
if (peekToken.type == Lexer.TokenType.COMMA) {
nextToken();
} else {
break;
}
}
expect(Lexer.TokenType.RIGHT_BRACKET, "expected ']'");
return CelExpr.ofList(listId, elements.build(), optionalIndices.build());
}
private CelExpr parseMap() {
Lexer.Token openTok = nextToken();
long mapId = nextId(openTok);
ImmutableList.Builder<CelExpr.CelMap.Entry> entries = ImmutableList.builder();
while (peekToken.type != Lexer.TokenType.RIGHT_BRACE && peekToken.type != Lexer.TokenType.END) {
boolean optional = false;
Lexer.Token keyStart = peekToken;
if (keyStart.type == Lexer.TokenType.QUESTION) {
Lexer.Token q = nextToken();
optional = true;
if (!options.enableOptionalSyntax()) {
reportError(q.start, "unsupported syntax '?'");
}
keyStart = peekToken;
}
long entryId = nextId();
CelExpr key = parseExpr();
Lexer.Token colon = peekToken;
if (!expect(Lexer.TokenType.COLON, "expected ':' in map entry")) {
break;
}
setPosition(entryId, colon);
CelExpr value = parseExpr();
entries.add(CelExpr.ofMapEntry(entryId, key, value, optional));
if (peekToken.type == Lexer.TokenType.COMMA) {
nextToken();
} else {
break;
}
}
expect(Lexer.TokenType.RIGHT_BRACE, "expected '}'");
return CelExpr.ofMap(mapId, entries.build());
}
private CelExpr parseStruct(long objId, String structName) {
nextToken();
ImmutableList.Builder<CelExpr.CelStruct.Entry> entries = ImmutableList.builder();
while (peekToken.type != Lexer.TokenType.RIGHT_BRACE && peekToken.type != Lexer.TokenType.END) {
boolean optional = false;
if (peekToken.type == Lexer.TokenType.QUESTION) {
Lexer.Token q = nextToken();
optional = true;
if (!options.enableOptionalSyntax()) {
reportError(q.start, "unsupported syntax '?'");
}
}
Lexer.Token fieldTok = nextToken();
if (fieldTok.type != Lexer.TokenType.IDENT
&& fieldTok.type != Lexer.TokenType.RESERVED_WORD) {
reportSyntaxError(fieldTok, "expected struct field name");
synchronizeOnDelimiter();
break;
}
String fieldName = normalizeIdent(fieldTok, /* allowQuoted= */ true);
Lexer.Token colon = peekToken;
if (!expect(Lexer.TokenType.COLON, "expected ':' in struct field")) {
break;
}
long fieldId = nextId(colon);
CelExpr value = parseExpr();
entries.add(CelExpr.ofStructEntry(fieldId, fieldName, value, optional));
if (peekToken.type == Lexer.TokenType.COMMA) {
nextToken();
} else {
break;
}
}
expect(Lexer.TokenType.RIGHT_BRACE, "expected '}'");
return CelExpr.ofStruct(objId, structName, entries.build());
}
private ImmutableList<CelExpr> parseArguments(Lexer.TokenType closeToken) {
ImmutableList.Builder<CelExpr> args = ImmutableList.builder();
if (peekToken.type != closeToken && peekToken.type != Lexer.TokenType.END) {
while (true) {
args.add(parseExpr());
if (peekToken.type == Lexer.TokenType.COMMA) {
nextToken();
if (peekToken.type == closeToken) {
reportError(peekToken.start, "unexpected token");
break;
}
continue;
}
break;
}
}
expect(closeToken, "");
return args.build();
}
private CelExpr parseIntLiteral(long nodeId, boolean isNegative) {
Lexer.Token tok = nextToken();
String text = isNegative ? "-" + getTokenText(tok) : getTokenText(tok);
long id = nodeId == -1 ? nextId(tok) : nodeId;
try {
CelConstant constExpr = Constants.parseInt(text);
return CelExpr.ofConstant(id, constExpr);
} catch (ParseException e) {
reportSyntaxError(tok, "invalid int literal: " + text);
return CelExpr.newBuilder().setId(nextId(tok)).build();
}
}
private CelExpr parseUintLiteral() {
Lexer.Token tok = nextToken();
String value = getTokenText(tok);
try {
CelConstant constExpr = Constants.parseUint(value);
return CelExpr.ofConstant(nextId(tok), constExpr);
} catch (ParseException e) {
reportSyntaxError(tok, "invalid uint literal: " + value);
return CelExpr.newBuilder().setId(nextId(tok)).build();
}
}
private CelExpr parseDoubleLiteral(long nodeId, boolean isNegative) {
Lexer.Token tok = nextToken();
String text = isNegative ? "-" + getTokenText(tok) : getTokenText(tok);
long id = nodeId == -1 ? nextId(tok) : nodeId;
try {
CelConstant constExpr = Constants.parseDouble(text);
return CelExpr.ofConstant(id, constExpr);
} catch (ParseException e) {
reportSyntaxError(tok, "invalid double literal: " + text);
return CelExpr.newBuilder().setId(nextId(tok)).build();
}
}
private CelExpr parseStringLiteral() {
Lexer.Token tok = nextToken();
String value = getTokenText(tok);
try {
CelConstant constExpr = Constants.parseString(value);
return CelExpr.ofConstant(nextId(tok), constExpr);
} catch (ParseException e) {
reportError(tok.start, e.getMessage());
return CelExpr.newBuilder().setId(nextId(tok)).build();
}
}