| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package parser |
| 18 |
|
| 19 |
import ( |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"regexp" |
| 23 |
"strconv" |
| 24 |
"strings" |
| 25 |
|
| 26 |
antlr "github.com/antlr4-go/antlr/v4" |
| 27 |
|
| 28 |
"github.com/google/cel-go/common" |
| 29 |
"github.com/google/cel-go/common/ast" |
| 30 |
"github.com/google/cel-go/common/operators" |
| 31 |
"github.com/google/cel-go/common/runes" |
| 32 |
"github.com/google/cel-go/common/types" |
| 33 |
"github.com/google/cel-go/parser/gen" |
| 34 |
) |
| 35 |
|
| 36 |
|
| 37 |
type Parser struct { |
| 38 |
options |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
func NewParser(opts ...Option) (*Parser, error) { |
| 43 |
p := &Parser{} |
| 44 |
p.enableHiddenAccumulatorName = true |
| 45 |
for _, opt := range opts { |
| 46 |
if err := opt(&p.options); err != nil { |
| 47 |
return nil, err |
| 48 |
} |
| 49 |
} |
| 50 |
if p.errorReportingLimit == 0 { |
| 51 |
p.errorReportingLimit = 100 |
| 52 |
} |
| 53 |
if p.maxRecursionDepth == 0 { |
| 54 |
p.maxRecursionDepth = 250 |
| 55 |
} |
| 56 |
if p.maxRecursionDepth == -1 { |
| 57 |
p.maxRecursionDepth = int((^uint(0)) >> 1) |
| 58 |
} |
| 59 |
if p.errorRecoveryTokenLookaheadLimit == 0 { |
| 60 |
p.errorRecoveryTokenLookaheadLimit = 256 |
| 61 |
} |
| 62 |
if p.errorRecoveryLimit == 0 { |
| 63 |
p.errorRecoveryLimit = 30 |
| 64 |
} |
| 65 |
if p.errorRecoveryLimit == -1 { |
| 66 |
p.errorRecoveryLimit = int((^uint(0)) >> 1) |
| 67 |
} |
| 68 |
if p.expressionSizeCodePointLimit == 0 { |
| 69 |
p.expressionSizeCodePointLimit = 100_000 |
| 70 |
} |
| 71 |
if p.expressionSizeCodePointLimit == -1 { |
| 72 |
p.expressionSizeCodePointLimit = int((^uint(0)) >> 1) |
| 73 |
} |
| 74 |
|
| 75 |
return p, nil |
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
func mustNewParser(opts ...Option) *Parser { |
| 83 |
p, err := NewParser(opts...) |
| 84 |
if err != nil { |
| 85 |
panic(err) |
| 86 |
} |
| 87 |
return p |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
func (p *Parser) Parse(source common.Source) (*ast.AST, *common.Errors) { |
| 92 |
errs := common.NewErrors(source) |
| 93 |
accu := AccumulatorName |
| 94 |
if p.enableHiddenAccumulatorName { |
| 95 |
accu = HiddenAccumulatorName |
| 96 |
} |
| 97 |
fac := ast.NewExprFactoryWithAccumulator(accu) |
| 98 |
impl := parser{ |
| 99 |
errors: &parseErrors{errs}, |
| 100 |
exprFactory: fac, |
| 101 |
helper: newParserHelper(source, fac), |
| 102 |
macros: p.macros, |
| 103 |
maxRecursionDepth: p.maxRecursionDepth, |
| 104 |
errorReportingLimit: p.errorReportingLimit, |
| 105 |
errorRecoveryLimit: p.errorRecoveryLimit, |
| 106 |
errorRecoveryLookaheadTokenLimit: p.errorRecoveryTokenLookaheadLimit, |
| 107 |
populateMacroCalls: p.populateMacroCalls, |
| 108 |
enableOptionalSyntax: p.enableOptionalSyntax, |
| 109 |
enableVariadicOperatorASTs: p.enableVariadicOperatorASTs, |
| 110 |
enableIdentEscapeSyntax: p.enableIdentEscapeSyntax, |
| 111 |
} |
| 112 |
buf, ok := source.(runes.Buffer) |
| 113 |
if !ok { |
| 114 |
buf = runes.NewBuffer(source.Content()) |
| 115 |
} |
| 116 |
var out ast.Expr |
| 117 |
if buf.Len() > p.expressionSizeCodePointLimit { |
| 118 |
out = impl.reportError(common.NoLocation, |
| 119 |
"expression code point size exceeds limit: size: %d, limit %d", |
| 120 |
buf.Len(), p.expressionSizeCodePointLimit) |
| 121 |
} else { |
| 122 |
out = impl.parse(buf, source.Description()) |
| 123 |
} |
| 124 |
return ast.NewAST(out, impl.helper.getSourceInfo()), errs |
| 125 |
} |
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
var reservedIds = map[string]struct{}{ |
| 130 |
"as": {}, |
| 131 |
"break": {}, |
| 132 |
"const": {}, |
| 133 |
"continue": {}, |
| 134 |
"else": {}, |
| 135 |
"false": {}, |
| 136 |
"for": {}, |
| 137 |
"function": {}, |
| 138 |
"if": {}, |
| 139 |
"import": {}, |
| 140 |
"in": {}, |
| 141 |
"let": {}, |
| 142 |
"loop": {}, |
| 143 |
"package": {}, |
| 144 |
"namespace": {}, |
| 145 |
"null": {}, |
| 146 |
"return": {}, |
| 147 |
"true": {}, |
| 148 |
"var": {}, |
| 149 |
"void": {}, |
| 150 |
"while": {}, |
| 151 |
} |
| 152 |
|
| 153 |
func unescapeIdent(in string) (string, error) { |
| 154 |
if len(in) <= 2 { |
| 155 |
return "", errors.New("invalid escaped identifier: underflow") |
| 156 |
} |
| 157 |
return in[1 : len(in)-1], nil |
| 158 |
} |
| 159 |
|
| 160 |
|
| 161 |
func (p *parser) normalizeIdent(ctx gen.IEscapeIdentContext) (string, error) { |
| 162 |
switch ident := ctx.(type) { |
| 163 |
case *gen.SimpleIdentifierContext: |
| 164 |
return ident.GetId().GetText(), nil |
| 165 |
case *gen.EscapedIdentifierContext: |
| 166 |
if !p.enableIdentEscapeSyntax { |
| 167 |
return "", errors.New("unsupported syntax: '`'") |
| 168 |
} |
| 169 |
return unescapeIdent(ident.GetId().GetText()) |
| 170 |
} |
| 171 |
return "", errors.New("unsupported ident kind") |
| 172 |
} |
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
func Parse(source common.Source) (*ast.AST, *common.Errors) { |
| 179 |
return mustNewParser(Macros(AllMacros...)).Parse(source) |
| 180 |
} |
| 181 |
|
| 182 |
type recursionError struct { |
| 183 |
message string |
| 184 |
} |
| 185 |
|
| 186 |
|
| 187 |
func (re *recursionError) Error() string { |
| 188 |
return re.message |
| 189 |
} |
| 190 |
|
| 191 |
var _ error = &recursionError{} |
| 192 |
|
| 193 |
type recursionListener struct { |
| 194 |
maxDepth int |
| 195 |
ruleTypeDepth map[int]*int |
| 196 |
} |
| 197 |
|
| 198 |
func (rl *recursionListener) VisitTerminal(node antlr.TerminalNode) {} |
| 199 |
|
| 200 |
func (rl *recursionListener) VisitErrorNode(node antlr.ErrorNode) {} |
| 201 |
|
| 202 |
func (rl *recursionListener) EnterEveryRule(ctx antlr.ParserRuleContext) { |
| 203 |
if ctx == nil { |
| 204 |
return |
| 205 |
} |
| 206 |
ruleIndex := ctx.GetRuleIndex() |
| 207 |
depth, found := rl.ruleTypeDepth[ruleIndex] |
| 208 |
if !found { |
| 209 |
var counter = 1 |
| 210 |
rl.ruleTypeDepth[ruleIndex] = &counter |
| 211 |
depth = &counter |
| 212 |
} else { |
| 213 |
*depth++ |
| 214 |
} |
| 215 |
if *depth > rl.maxDepth { |
| 216 |
panic(&recursionError{ |
| 217 |
message: fmt.Sprintf("expression recursion limit exceeded: %d", rl.maxDepth), |
| 218 |
}) |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
func (rl *recursionListener) ExitEveryRule(ctx antlr.ParserRuleContext) { |
| 223 |
if ctx == nil { |
| 224 |
return |
| 225 |
} |
| 226 |
ruleIndex := ctx.GetRuleIndex() |
| 227 |
if depth, found := rl.ruleTypeDepth[ruleIndex]; found && *depth > 0 { |
| 228 |
*depth-- |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
var _ antlr.ParseTreeListener = &recursionListener{} |
| 233 |
|
| 234 |
type tooManyErrors struct { |
| 235 |
errorReportingLimit int |
| 236 |
} |
| 237 |
|
| 238 |
func (t *tooManyErrors) Error() string { |
| 239 |
return fmt.Sprintf("More than %d syntax errors", t.errorReportingLimit) |
| 240 |
} |
| 241 |
|
| 242 |
var _ error = &tooManyErrors{} |
| 243 |
|
| 244 |
type recoveryLimitError struct { |
| 245 |
message string |
| 246 |
} |
| 247 |
|
| 248 |
|
| 249 |
func (rl *recoveryLimitError) Error() string { |
| 250 |
return rl.message |
| 251 |
} |
| 252 |
|
| 253 |
type lookaheadLimitError struct { |
| 254 |
message string |
| 255 |
} |
| 256 |
|
| 257 |
func (ll *lookaheadLimitError) Error() string { |
| 258 |
return ll.message |
| 259 |
} |
| 260 |
|
| 261 |
var _ error = &recoveryLimitError{} |
| 262 |
|
| 263 |
type recoveryLimitErrorStrategy struct { |
| 264 |
*antlr.DefaultErrorStrategy |
| 265 |
errorRecoveryLimit int |
| 266 |
errorRecoveryTokenLookaheadLimit int |
| 267 |
recoveryAttempts int |
| 268 |
} |
| 269 |
|
| 270 |
type lookaheadConsumer struct { |
| 271 |
antlr.Parser |
| 272 |
errorRecoveryTokenLookaheadLimit int |
| 273 |
lookaheadAttempts int |
| 274 |
} |
| 275 |
|
| 276 |
func (lc *lookaheadConsumer) Consume() antlr.Token { |
| 277 |
if lc.lookaheadAttempts >= lc.errorRecoveryTokenLookaheadLimit { |
| 278 |
panic(&lookaheadLimitError{ |
| 279 |
message: fmt.Sprintf("error recovery token lookahead limit exceeded: %d", lc.errorRecoveryTokenLookaheadLimit), |
| 280 |
}) |
| 281 |
} |
| 282 |
lc.lookaheadAttempts++ |
| 283 |
return lc.Parser.Consume() |
| 284 |
} |
| 285 |
|
| 286 |
func (rl *recoveryLimitErrorStrategy) Recover(recognizer antlr.Parser, e antlr.RecognitionException) { |
| 287 |
rl.checkAttempts(recognizer) |
| 288 |
lc := &lookaheadConsumer{Parser: recognizer, errorRecoveryTokenLookaheadLimit: rl.errorRecoveryTokenLookaheadLimit} |
| 289 |
rl.DefaultErrorStrategy.Recover(lc, e) |
| 290 |
} |
| 291 |
|
| 292 |
func (rl *recoveryLimitErrorStrategy) RecoverInline(recognizer antlr.Parser) antlr.Token { |
| 293 |
rl.checkAttempts(recognizer) |
| 294 |
lc := &lookaheadConsumer{Parser: recognizer, errorRecoveryTokenLookaheadLimit: rl.errorRecoveryTokenLookaheadLimit} |
| 295 |
return rl.DefaultErrorStrategy.RecoverInline(lc) |
| 296 |
} |
| 297 |
|
| 298 |
func (rl *recoveryLimitErrorStrategy) checkAttempts(recognizer antlr.Parser) { |
| 299 |
if rl.recoveryAttempts == rl.errorRecoveryLimit { |
| 300 |
rl.recoveryAttempts++ |
| 301 |
msg := fmt.Sprintf("error recovery attempt limit exceeded: %d", rl.errorRecoveryLimit) |
| 302 |
recognizer.NotifyErrorListeners(msg, nil, nil) |
| 303 |
panic(&recoveryLimitError{ |
| 304 |
message: msg, |
| 305 |
}) |
| 306 |
} |
| 307 |
rl.recoveryAttempts++ |
| 308 |
} |
| 309 |
|
| 310 |
var _ antlr.ErrorStrategy = &recoveryLimitErrorStrategy{} |
| 311 |
|
| 312 |
type parser struct { |
| 313 |
gen.BaseCELVisitor |
| 314 |
errors *parseErrors |
| 315 |
exprFactory ast.ExprFactory |
| 316 |
helper *parserHelper |
| 317 |
macros map[string]Macro |
| 318 |
recursionDepth int |
| 319 |
errorReports int |
| 320 |
maxRecursionDepth int |
| 321 |
errorReportingLimit int |
| 322 |
errorRecoveryLimit int |
| 323 |
errorRecoveryLookaheadTokenLimit int |
| 324 |
populateMacroCalls bool |
| 325 |
enableOptionalSyntax bool |
| 326 |
enableVariadicOperatorASTs bool |
| 327 |
enableIdentEscapeSyntax bool |
| 328 |
} |
| 329 |
|
| 330 |
var _ gen.CELVisitor = (*parser)(nil) |
| 331 |
|
| 332 |
func (p *parser) parse(expr runes.Buffer, desc string) ast.Expr { |
| 333 |
lexer := gen.NewCELLexer(newCharStream(expr, desc)) |
| 334 |
lexer.RemoveErrorListeners() |
| 335 |
lexer.AddErrorListener(p) |
| 336 |
|
| 337 |
prsr := gen.NewCELParser(antlr.NewCommonTokenStream(lexer, 0)) |
| 338 |
prsr.RemoveErrorListeners() |
| 339 |
|
| 340 |
prsrListener := &recursionListener{ |
| 341 |
maxDepth: p.maxRecursionDepth, |
| 342 |
ruleTypeDepth: map[int]*int{}, |
| 343 |
} |
| 344 |
|
| 345 |
prsr.AddErrorListener(p) |
| 346 |
prsr.AddParseListener(prsrListener) |
| 347 |
|
| 348 |
prsr.SetErrorHandler(&recoveryLimitErrorStrategy{ |
| 349 |
DefaultErrorStrategy: antlr.NewDefaultErrorStrategy(), |
| 350 |
errorRecoveryLimit: p.errorRecoveryLimit, |
| 351 |
errorRecoveryTokenLookaheadLimit: p.errorRecoveryLookaheadTokenLimit, |
| 352 |
}) |
| 353 |
|
| 354 |
defer func() { |
| 355 |
if val := recover(); val != nil { |
| 356 |
switch err := val.(type) { |
| 357 |
case *lookaheadLimitError: |
| 358 |
p.errors.internalError(err.Error()) |
| 359 |
case *recursionError: |
| 360 |
p.errors.internalError(err.Error()) |
| 361 |
case *tooManyErrors: |
| 362 |
|
| 363 |
case *recoveryLimitError: |
| 364 |
|
| 365 |
default: |
| 366 |
panic(val) |
| 367 |
} |
| 368 |
} |
| 369 |
}() |
| 370 |
|
| 371 |
return p.Visit(prsr.Start_()).(ast.Expr) |
| 372 |
} |
| 373 |
|
| 374 |
|
| 375 |
func (p *parser) Visit(tree antlr.ParseTree) any { |
| 376 |
t := unnest(tree) |
| 377 |
switch tree := t.(type) { |
| 378 |
case *gen.StartContext: |
| 379 |
return p.VisitStart(tree) |
| 380 |
case *gen.ExprContext: |
| 381 |
p.checkAndIncrementRecursionDepth() |
| 382 |
out := p.VisitExpr(tree) |
| 383 |
p.decrementRecursionDepth() |
| 384 |
return out |
| 385 |
case *gen.ConditionalAndContext: |
| 386 |
return p.VisitConditionalAnd(tree) |
| 387 |
case *gen.ConditionalOrContext: |
| 388 |
return p.VisitConditionalOr(tree) |
| 389 |
case *gen.RelationContext: |
| 390 |
p.checkAndIncrementRecursionDepth() |
| 391 |
out := p.VisitRelation(tree) |
| 392 |
p.decrementRecursionDepth() |
| 393 |
return out |
| 394 |
case *gen.CalcContext: |
| 395 |
p.checkAndIncrementRecursionDepth() |
| 396 |
out := p.VisitCalc(tree) |
| 397 |
p.decrementRecursionDepth() |
| 398 |
return out |
| 399 |
case *gen.LogicalNotContext: |
| 400 |
return p.VisitLogicalNot(tree) |
| 401 |
case *gen.IdentContext: |
| 402 |
return p.VisitIdent(tree) |
| 403 |
case *gen.GlobalCallContext: |
| 404 |
return p.VisitGlobalCall(tree) |
| 405 |
case *gen.SelectContext: |
| 406 |
p.checkAndIncrementRecursionDepth() |
| 407 |
out := p.VisitSelect(tree) |
| 408 |
p.decrementRecursionDepth() |
| 409 |
return out |
| 410 |
case *gen.MemberCallContext: |
| 411 |
p.checkAndIncrementRecursionDepth() |
| 412 |
out := p.VisitMemberCall(tree) |
| 413 |
p.decrementRecursionDepth() |
| 414 |
return out |
| 415 |
case *gen.MapInitializerListContext: |
| 416 |
return p.VisitMapInitializerList(tree) |
| 417 |
case *gen.NegateContext: |
| 418 |
return p.VisitNegate(tree) |
| 419 |
case *gen.IndexContext: |
| 420 |
p.checkAndIncrementRecursionDepth() |
| 421 |
out := p.VisitIndex(tree) |
| 422 |
p.decrementRecursionDepth() |
| 423 |
return out |
| 424 |
case *gen.UnaryContext: |
| 425 |
return p.VisitUnary(tree) |
| 426 |
case *gen.CreateListContext: |
| 427 |
return p.VisitCreateList(tree) |
| 428 |
case *gen.CreateMessageContext: |
| 429 |
return p.VisitCreateMessage(tree) |
| 430 |
case *gen.CreateStructContext: |
| 431 |
return p.VisitCreateStruct(tree) |
| 432 |
case *gen.IntContext: |
| 433 |
return p.VisitInt(tree) |
| 434 |
case *gen.UintContext: |
| 435 |
return p.VisitUint(tree) |
| 436 |
case *gen.DoubleContext: |
| 437 |
return p.VisitDouble(tree) |
| 438 |
case *gen.StringContext: |
| 439 |
return p.VisitString(tree) |
| 440 |
case *gen.BytesContext: |
| 441 |
return p.VisitBytes(tree) |
| 442 |
case *gen.BoolFalseContext: |
| 443 |
return p.VisitBoolFalse(tree) |
| 444 |
case *gen.BoolTrueContext: |
| 445 |
return p.VisitBoolTrue(tree) |
| 446 |
case *gen.NullContext: |
| 447 |
return p.VisitNull(tree) |
| 448 |
} |
| 449 |
|
| 450 |
|
| 451 |
|
| 452 |
if p.errors.errorCount() == 0 { |
| 453 |
txt := "<<nil>>" |
| 454 |
if t != nil { |
| 455 |
txt = fmt.Sprintf("<<%T>>", t) |
| 456 |
} |
| 457 |
return p.reportError(common.NoLocation, "unknown parse element encountered: %s", txt) |
| 458 |
} |
| 459 |
return p.helper.newExpr(common.NoLocation) |
| 460 |
|
| 461 |
} |
| 462 |
|
| 463 |
|
| 464 |
func (p *parser) VisitStart(ctx *gen.StartContext) any { |
| 465 |
return p.Visit(ctx.Expr()) |
| 466 |
} |
| 467 |
|
| 468 |
|
| 469 |
func (p *parser) VisitExpr(ctx *gen.ExprContext) any { |
| 470 |
result := p.Visit(ctx.GetE()).(ast.Expr) |
| 471 |
if ctx.GetOp() == nil { |
| 472 |
return result |
| 473 |
} |
| 474 |
opID := p.helper.id(ctx.GetOp()) |
| 475 |
ifTrue := p.Visit(ctx.GetE1()).(ast.Expr) |
| 476 |
ifFalse := p.Visit(ctx.GetE2()).(ast.Expr) |
| 477 |
return p.globalCallOrMacro(opID, operators.Conditional, result, ifTrue, ifFalse) |
| 478 |
} |
| 479 |
|
| 480 |
|
| 481 |
func (p *parser) VisitConditionalOr(ctx *gen.ConditionalOrContext) any { |
| 482 |
result := p.Visit(ctx.GetE()).(ast.Expr) |
| 483 |
l := p.newLogicManager(operators.LogicalOr, result) |
| 484 |
rest := ctx.GetE1() |
| 485 |
for i, op := range ctx.GetOps() { |
| 486 |
if i >= len(rest) { |
| 487 |
return p.reportError(ctx, "unexpected character, wanted '||'") |
| 488 |
} |
| 489 |
next := p.Visit(rest[i]).(ast.Expr) |
| 490 |
opID := p.helper.id(op) |
| 491 |
l.addTerm(opID, next) |
| 492 |
} |
| 493 |
return l.toExpr() |
| 494 |
} |
| 495 |
|
| 496 |
|
| 497 |
func (p *parser) VisitConditionalAnd(ctx *gen.ConditionalAndContext) any { |
| 498 |
result := p.Visit(ctx.GetE()).(ast.Expr) |
| 499 |
l := p.newLogicManager(operators.LogicalAnd, result) |
| 500 |
rest := ctx.GetE1() |
| 501 |
for i, op := range ctx.GetOps() { |
| 502 |
if i >= len(rest) { |
| 503 |
return p.reportError(ctx, "unexpected character, wanted '&&'") |
| 504 |
} |
| 505 |
next := p.Visit(rest[i]).(ast.Expr) |
| 506 |
opID := p.helper.id(op) |
| 507 |
l.addTerm(opID, next) |
| 508 |
} |
| 509 |
return l.toExpr() |
| 510 |
} |
| 511 |
|
| 512 |
|
| 513 |
func (p *parser) VisitRelation(ctx *gen.RelationContext) any { |
| 514 |
opText := "" |
| 515 |
if ctx.GetOp() != nil { |
| 516 |
opText = ctx.GetOp().GetText() |
| 517 |
} |
| 518 |
if op, found := operators.Find(opText); found { |
| 519 |
lhs := p.Visit(ctx.Relation(0)).(ast.Expr) |
| 520 |
opID := p.helper.id(ctx.GetOp()) |
| 521 |
rhs := p.Visit(ctx.Relation(1)).(ast.Expr) |
| 522 |
return p.globalCallOrMacro(opID, op, lhs, rhs) |
| 523 |
} |
| 524 |
return p.reportError(ctx, "operator not found") |
| 525 |
} |
| 526 |
|
| 527 |
|
| 528 |
func (p *parser) VisitCalc(ctx *gen.CalcContext) any { |
| 529 |
opText := "" |
| 530 |
if ctx.GetOp() != nil { |
| 531 |
opText = ctx.GetOp().GetText() |
| 532 |
} |
| 533 |
if op, found := operators.Find(opText); found { |
| 534 |
lhs := p.Visit(ctx.Calc(0)).(ast.Expr) |
| 535 |
opID := p.helper.id(ctx.GetOp()) |
| 536 |
rhs := p.Visit(ctx.Calc(1)).(ast.Expr) |
| 537 |
return p.globalCallOrMacro(opID, op, lhs, rhs) |
| 538 |
} |
| 539 |
return p.reportError(ctx, "operator not found") |
| 540 |
} |
| 541 |
|
| 542 |
func (p *parser) VisitUnary(ctx *gen.UnaryContext) any { |
| 543 |
return p.helper.newLiteralString(ctx, "<<error>>") |
| 544 |
} |
| 545 |
|
| 546 |
|
| 547 |
func (p *parser) VisitLogicalNot(ctx *gen.LogicalNotContext) any { |
| 548 |
if len(ctx.GetOps())%2 == 0 { |
| 549 |
return p.Visit(ctx.Member()) |
| 550 |
} |
| 551 |
opID := p.helper.id(ctx.GetOps()[0]) |
| 552 |
target := p.Visit(ctx.Member()).(ast.Expr) |
| 553 |
return p.globalCallOrMacro(opID, operators.LogicalNot, target) |
| 554 |
} |
| 555 |
|
| 556 |
func (p *parser) VisitNegate(ctx *gen.NegateContext) any { |
| 557 |
if len(ctx.GetOps())%2 == 0 { |
| 558 |
return p.Visit(ctx.Member()) |
| 559 |
} |
| 560 |
opID := p.helper.id(ctx.GetOps()[0]) |
| 561 |
target := p.Visit(ctx.Member()).(ast.Expr) |
| 562 |
return p.globalCallOrMacro(opID, operators.Negate, target) |
| 563 |
} |
| 564 |
|
| 565 |
|
| 566 |
func (p *parser) VisitSelect(ctx *gen.SelectContext) any { |
| 567 |
operand := p.Visit(ctx.Member()).(ast.Expr) |
| 568 |
|
| 569 |
if ctx.GetId() == nil || ctx.GetOp() == nil { |
| 570 |
return p.helper.newExpr(ctx) |
| 571 |
} |
| 572 |
id, err := p.normalizeIdent(ctx.GetId()) |
| 573 |
if err != nil { |
| 574 |
p.reportError(ctx.GetId(), "%v", err) |
| 575 |
} |
| 576 |
if ctx.GetOpt() != nil { |
| 577 |
if !p.enableOptionalSyntax { |
| 578 |
return p.reportError(ctx.GetOp(), "unsupported syntax '.?'") |
| 579 |
} |
| 580 |
return p.helper.newGlobalCall( |
| 581 |
ctx.GetOp(), |
| 582 |
operators.OptSelect, |
| 583 |
operand, |
| 584 |
p.helper.newLiteralString(ctx.GetId(), id)) |
| 585 |
} |
| 586 |
return p.helper.newSelect(ctx.GetOp(), operand, id) |
| 587 |
} |
| 588 |
|
| 589 |
|
| 590 |
func (p *parser) VisitMemberCall(ctx *gen.MemberCallContext) any { |
| 591 |
operand := p.Visit(ctx.Member()).(ast.Expr) |
| 592 |
|
| 593 |
if ctx.GetId() == nil { |
| 594 |
return p.helper.newExpr(ctx) |
| 595 |
} |
| 596 |
id := ctx.GetId().GetText() |
| 597 |
opID := p.helper.id(ctx.GetOpen()) |
| 598 |
return p.receiverCallOrMacro(opID, id, operand, p.visitExprList(ctx.GetArgs())...) |
| 599 |
} |
| 600 |
|
| 601 |
|
| 602 |
func (p *parser) VisitIndex(ctx *gen.IndexContext) any { |
| 603 |
target := p.Visit(ctx.Member()).(ast.Expr) |
| 604 |
|
| 605 |
if ctx.GetOp() == nil { |
| 606 |
return p.helper.newExpr(ctx) |
| 607 |
} |
| 608 |
opID := p.helper.id(ctx.GetOp()) |
| 609 |
index := p.Visit(ctx.GetIndex()).(ast.Expr) |
| 610 |
operator := operators.Index |
| 611 |
if ctx.GetOpt() != nil { |
| 612 |
if !p.enableOptionalSyntax { |
| 613 |
return p.reportError(ctx.GetOp(), "unsupported syntax '[?'") |
| 614 |
} |
| 615 |
operator = operators.OptIndex |
| 616 |
} |
| 617 |
return p.globalCallOrMacro(opID, operator, target, index) |
| 618 |
} |
| 619 |
|
| 620 |
|
| 621 |
func (p *parser) VisitCreateMessage(ctx *gen.CreateMessageContext) any { |
| 622 |
messageName := "" |
| 623 |
for _, id := range ctx.GetIds() { |
| 624 |
if len(messageName) != 0 { |
| 625 |
messageName += "." |
| 626 |
} |
| 627 |
messageName += id.GetText() |
| 628 |
} |
| 629 |
if ctx.GetLeadingDot() != nil { |
| 630 |
messageName = "." + messageName |
| 631 |
} |
| 632 |
objID := p.helper.id(ctx.GetOp()) |
| 633 |
entries := p.VisitIFieldInitializerList(ctx.GetEntries()).([]ast.EntryExpr) |
| 634 |
return p.helper.newObject(objID, messageName, entries...) |
| 635 |
} |
| 636 |
|
| 637 |
|
| 638 |
func (p *parser) VisitIFieldInitializerList(ctx gen.IFieldInitializerListContext) any { |
| 639 |
if ctx == nil || ctx.GetFields() == nil { |
| 640 |
|
| 641 |
return []ast.EntryExpr{} |
| 642 |
} |
| 643 |
|
| 644 |
result := make([]ast.EntryExpr, len(ctx.GetFields())) |
| 645 |
cols := ctx.GetCols() |
| 646 |
vals := ctx.GetValues() |
| 647 |
for i, f := range ctx.GetFields() { |
| 648 |
if i >= len(cols) || i >= len(vals) { |
| 649 |
|
| 650 |
return []ast.EntryExpr{} |
| 651 |
} |
| 652 |
initID := p.helper.id(cols[i]) |
| 653 |
optField := f.(*gen.OptFieldContext) |
| 654 |
optional := optField.GetOpt() != nil |
| 655 |
if !p.enableOptionalSyntax && optional { |
| 656 |
p.reportError(optField, "unsupported syntax '?'") |
| 657 |
continue |
| 658 |
} |
| 659 |
|
| 660 |
|
| 661 |
fieldName, err := p.normalizeIdent(optField.EscapeIdent()) |
| 662 |
if err != nil { |
| 663 |
p.reportError(ctx, "%v", err) |
| 664 |
continue |
| 665 |
} |
| 666 |
|
| 667 |
value := p.Visit(vals[i]).(ast.Expr) |
| 668 |
field := p.helper.newObjectField(initID, fieldName, value, optional) |
| 669 |
result[i] = field |
| 670 |
} |
| 671 |
return result |
| 672 |
} |
| 673 |
|
| 674 |
|
| 675 |
func (p *parser) VisitIdent(ctx *gen.IdentContext) any { |
| 676 |
identName := "" |
| 677 |
if ctx.GetLeadingDot() != nil { |
| 678 |
identName = "." |
| 679 |
} |
| 680 |
|
| 681 |
if ctx.GetId() == nil { |
| 682 |
return p.helper.newExpr(ctx) |
| 683 |
} |
| 684 |
|
| 685 |
id := ctx.GetId().GetText() |
| 686 |
if _, ok := reservedIds[id]; ok { |
| 687 |
return p.reportError(ctx, "reserved identifier: %s", id) |
| 688 |
} |
| 689 |
identName += id |
| 690 |
return p.helper.newIdent(ctx.GetId(), identName) |
| 691 |
} |
| 692 |
|
| 693 |
|
| 694 |
func (p *parser) VisitGlobalCall(ctx *gen.GlobalCallContext) any { |
| 695 |
identName := "" |
| 696 |
if ctx.GetLeadingDot() != nil { |
| 697 |
identName = "." |
| 698 |
} |
| 699 |
|
| 700 |
if ctx.GetId() == nil { |
| 701 |
return p.helper.newExpr(ctx) |
| 702 |
} |
| 703 |
|
| 704 |
id := ctx.GetId().GetText() |
| 705 |
if _, ok := reservedIds[id]; ok { |
| 706 |
return p.reportError(ctx, "reserved identifier: %s", id) |
| 707 |
} |
| 708 |
identName += id |
| 709 |
opID := p.helper.id(ctx.GetOp()) |
| 710 |
return p.globalCallOrMacro(opID, identName, p.visitExprList(ctx.GetArgs())...) |
| 711 |
|
| 712 |
} |
| 713 |
|
| 714 |
|
| 715 |
func (p *parser) VisitCreateList(ctx *gen.CreateListContext) any { |
| 716 |
listID := p.helper.id(ctx.GetOp()) |
| 717 |
elems, optionals := p.visitListInit(ctx.GetElems()) |
| 718 |
return p.helper.newList(listID, elems, optionals...) |
| 719 |
} |
| 720 |
|
| 721 |
|
| 722 |
func (p *parser) VisitCreateStruct(ctx *gen.CreateStructContext) any { |
| 723 |
structID := p.helper.id(ctx.GetOp()) |
| 724 |
entries := []ast.EntryExpr{} |
| 725 |
if ctx.GetEntries() != nil { |
| 726 |
entries = p.Visit(ctx.GetEntries()).([]ast.EntryExpr) |
| 727 |
} |
| 728 |
return p.helper.newMap(structID, entries...) |
| 729 |
} |
| 730 |
|
| 731 |
|
| 732 |
func (p *parser) VisitMapInitializerList(ctx *gen.MapInitializerListContext) any { |
| 733 |
if ctx == nil || ctx.GetKeys() == nil { |
| 734 |
|
| 735 |
return []ast.EntryExpr{} |
| 736 |
} |
| 737 |
|
| 738 |
result := make([]ast.EntryExpr, len(ctx.GetCols())) |
| 739 |
keys := ctx.GetKeys() |
| 740 |
vals := ctx.GetValues() |
| 741 |
for i, col := range ctx.GetCols() { |
| 742 |
colID := p.helper.id(col) |
| 743 |
if i >= len(keys) || i >= len(vals) { |
| 744 |
|
| 745 |
return []ast.EntryExpr{} |
| 746 |
} |
| 747 |
optKey := keys[i] |
| 748 |
optional := optKey.GetOpt() != nil |
| 749 |
if !p.enableOptionalSyntax && optional { |
| 750 |
p.reportError(optKey, "unsupported syntax '?'") |
| 751 |
continue |
| 752 |
} |
| 753 |
key := p.Visit(optKey.GetE()).(ast.Expr) |
| 754 |
value := p.Visit(vals[i]).(ast.Expr) |
| 755 |
entry := p.helper.newMapEntry(colID, key, value, optional) |
| 756 |
result[i] = entry |
| 757 |
} |
| 758 |
return result |
| 759 |
} |
| 760 |
|
| 761 |
|
| 762 |
func (p *parser) VisitInt(ctx *gen.IntContext) any { |
| 763 |
text := ctx.GetTok().GetText() |
| 764 |
base := 10 |
| 765 |
if strings.HasPrefix(text, "0x") { |
| 766 |
base = 16 |
| 767 |
text = text[2:] |
| 768 |
} |
| 769 |
if ctx.GetSign() != nil { |
| 770 |
text = ctx.GetSign().GetText() + text |
| 771 |
} |
| 772 |
i, err := strconv.ParseInt(text, base, 64) |
| 773 |
if err != nil { |
| 774 |
return p.reportError(ctx, "invalid int literal") |
| 775 |
} |
| 776 |
return p.helper.newLiteralInt(ctx, i) |
| 777 |
} |
| 778 |
|
| 779 |
|
| 780 |
func (p *parser) VisitUint(ctx *gen.UintContext) any { |
| 781 |
text := ctx.GetTok().GetText() |
| 782 |
|
| 783 |
text = text[:len(text)-1] |
| 784 |
base := 10 |
| 785 |
if strings.HasPrefix(text, "0x") { |
| 786 |
base = 16 |
| 787 |
text = text[2:] |
| 788 |
} |
| 789 |
i, err := strconv.ParseUint(text, base, 64) |
| 790 |
if err != nil { |
| 791 |
return p.reportError(ctx, "invalid uint literal") |
| 792 |
} |
| 793 |
return p.helper.newLiteralUint(ctx, i) |
| 794 |
} |
| 795 |
|
| 796 |
|
| 797 |
func (p *parser) VisitDouble(ctx *gen.DoubleContext) any { |
| 798 |
txt := ctx.GetTok().GetText() |
| 799 |
if ctx.GetSign() != nil { |
| 800 |
txt = ctx.GetSign().GetText() + txt |
| 801 |
} |
| 802 |
f, err := strconv.ParseFloat(txt, 64) |
| 803 |
if err != nil { |
| 804 |
return p.reportError(ctx, "invalid double literal") |
| 805 |
} |
| 806 |
return p.helper.newLiteralDouble(ctx, f) |
| 807 |
|
| 808 |
} |
| 809 |
|
| 810 |
|
| 811 |
func (p *parser) VisitString(ctx *gen.StringContext) any { |
| 812 |
s := p.unquote(ctx, ctx.GetTok().GetText(), false) |
| 813 |
return p.helper.newLiteralString(ctx, s) |
| 814 |
} |
| 815 |
|
| 816 |
|
| 817 |
func (p *parser) VisitBytes(ctx *gen.BytesContext) any { |
| 818 |
b := []byte(p.unquote(ctx, ctx.GetTok().GetText()[1:], true)) |
| 819 |
return p.helper.newLiteralBytes(ctx, b) |
| 820 |
} |
| 821 |
|
| 822 |
|
| 823 |
func (p *parser) VisitBoolTrue(ctx *gen.BoolTrueContext) any { |
| 824 |
return p.helper.newLiteralBool(ctx, true) |
| 825 |
} |
| 826 |
|
| 827 |
|
| 828 |
func (p *parser) VisitBoolFalse(ctx *gen.BoolFalseContext) any { |
| 829 |
return p.helper.newLiteralBool(ctx, false) |
| 830 |
} |
| 831 |
|
| 832 |
|
| 833 |
func (p *parser) VisitNull(ctx *gen.NullContext) any { |
| 834 |
return p.helper.exprFactory.NewLiteral(p.helper.newID(ctx), types.NullValue) |
| 835 |
} |
| 836 |
|
| 837 |
func (p *parser) visitExprList(ctx gen.IExprListContext) []ast.Expr { |
| 838 |
if ctx == nil { |
| 839 |
return []ast.Expr{} |
| 840 |
} |
| 841 |
return p.visitSlice(ctx.GetE()) |
| 842 |
} |
| 843 |
|
| 844 |
func (p *parser) visitListInit(ctx gen.IListInitContext) ([]ast.Expr, []int32) { |
| 845 |
if ctx == nil { |
| 846 |
return []ast.Expr{}, []int32{} |
| 847 |
} |
| 848 |
elements := ctx.GetElems() |
| 849 |
result := make([]ast.Expr, len(elements)) |
| 850 |
optionals := []int32{} |
| 851 |
for i, e := range elements { |
| 852 |
ex := p.Visit(e.GetE()).(ast.Expr) |
| 853 |
if ex == nil { |
| 854 |
return []ast.Expr{}, []int32{} |
| 855 |
} |
| 856 |
result[i] = ex |
| 857 |
if e.GetOpt() != nil { |
| 858 |
if !p.enableOptionalSyntax { |
| 859 |
p.reportError(e.GetOpt(), "unsupported syntax '?'") |
| 860 |
continue |
| 861 |
} |
| 862 |
optionals = append(optionals, int32(i)) |
| 863 |
} |
| 864 |
} |
| 865 |
return result, optionals |
| 866 |
} |
| 867 |
|
| 868 |
func (p *parser) visitSlice(expressions []gen.IExprContext) []ast.Expr { |
| 869 |
if expressions == nil { |
| 870 |
return []ast.Expr{} |
| 871 |
} |
| 872 |
result := make([]ast.Expr, len(expressions)) |
| 873 |
for i, e := range expressions { |
| 874 |
ex := p.Visit(e).(ast.Expr) |
| 875 |
result[i] = ex |
| 876 |
} |
| 877 |
return result |
| 878 |
} |
| 879 |
|
| 880 |
func (p *parser) unquote(ctx any, value string, isBytes bool) string { |
| 881 |
text, err := unescape(value, isBytes) |
| 882 |
if err != nil { |
| 883 |
p.reportError(ctx, "%s", err.Error()) |
| 884 |
return value |
| 885 |
} |
| 886 |
return text |
| 887 |
} |
| 888 |
|
| 889 |
func (p *parser) newLogicManager(function string, term ast.Expr) *logicManager { |
| 890 |
if p.enableVariadicOperatorASTs { |
| 891 |
return newVariadicLogicManager(p.exprFactory, function, term) |
| 892 |
} |
| 893 |
return newBalancingLogicManager(p.exprFactory, function, term) |
| 894 |
} |
| 895 |
|
| 896 |
func (p *parser) reportError(ctx any, format string, args ...any) ast.Expr { |
| 897 |
var location common.Location |
| 898 |
err := p.helper.newExpr(ctx) |
| 899 |
switch c := ctx.(type) { |
| 900 |
case common.Location: |
| 901 |
location = c |
| 902 |
case antlr.Token, antlr.ParserRuleContext: |
| 903 |
location = p.helper.getLocation(err.ID()) |
| 904 |
} |
| 905 |
|
| 906 |
p.errors.reportErrorAtID(err.ID(), location, format, args...) |
| 907 |
return err |
| 908 |
} |
| 909 |
|
| 910 |
|
| 911 |
func (p *parser) SyntaxError(recognizer antlr.Recognizer, offendingSymbol any, line, column int, msg string, e antlr.RecognitionException) { |
| 912 |
offset := p.helper.sourceInfo.ComputeOffset(int32(line), int32(column)) |
| 913 |
l := p.helper.getLocationByOffset(offset) |
| 914 |
|
| 915 |
|
| 916 |
|
| 917 |
if strings.Contains(msg, "no viable alternative") { |
| 918 |
msg = reservedIdentifier.ReplaceAllString(msg, mismatchedReservedIdentifier) |
| 919 |
} |
| 920 |
|
| 921 |
|
| 922 |
if p.errorReports < p.errorReportingLimit { |
| 923 |
p.errorReports++ |
| 924 |
p.errors.syntaxError(l, msg) |
| 925 |
} else { |
| 926 |
tme := &tooManyErrors{errorReportingLimit: p.errorReportingLimit} |
| 927 |
p.errors.syntaxError(l, tme.Error()) |
| 928 |
panic(tme) |
| 929 |
} |
| 930 |
} |
| 931 |
|
| 932 |
func (p *parser) ReportAmbiguity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr.BitSet, configs *antlr.ATNConfigSet) { |
| 933 |
|
| 934 |
} |
| 935 |
|
| 936 |
func (p *parser) ReportAttemptingFullContext(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex int, conflictingAlts *antlr.BitSet, configs *antlr.ATNConfigSet) { |
| 937 |
|
| 938 |
} |
| 939 |
|
| 940 |
func (p *parser) ReportContextSensitivity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex, prediction int, configs *antlr.ATNConfigSet) { |
| 941 |
|
| 942 |
} |
| 943 |
|
| 944 |
func (p *parser) globalCallOrMacro(exprID int64, function string, args ...ast.Expr) ast.Expr { |
| 945 |
if expr, found := p.expandMacro(exprID, function, nil, args...); found { |
| 946 |
return expr |
| 947 |
} |
| 948 |
return p.helper.newGlobalCall(exprID, function, args...) |
| 949 |
} |
| 950 |
|
| 951 |
func (p *parser) receiverCallOrMacro(exprID int64, function string, target ast.Expr, args ...ast.Expr) ast.Expr { |
| 952 |
if expr, found := p.expandMacro(exprID, function, target, args...); found { |
| 953 |
return expr |
| 954 |
} |
| 955 |
return p.helper.newReceiverCall(exprID, function, target, args...) |
| 956 |
} |
| 957 |
|
| 958 |
func (p *parser) expandMacro(exprID int64, function string, target ast.Expr, args ...ast.Expr) (ast.Expr, bool) { |
| 959 |
macro, found := p.macros[makeMacroKey(function, len(args), target != nil)] |
| 960 |
if !found { |
| 961 |
macro, found = p.macros[makeVarArgMacroKey(function, target != nil)] |
| 962 |
if !found { |
| 963 |
return nil, false |
| 964 |
} |
| 965 |
} |
| 966 |
eh := exprHelperPool.Get().(*exprHelper) |
| 967 |
defer exprHelperPool.Put(eh) |
| 968 |
eh.parserHelper = p.helper |
| 969 |
eh.id = exprID |
| 970 |
expr, err := macro.Expander()(eh, target, args) |
| 971 |
|
| 972 |
if err != nil { |
| 973 |
loc := err.Location |
| 974 |
if loc == nil { |
| 975 |
loc = p.helper.getLocation(exprID) |
| 976 |
} |
| 977 |
p.helper.deleteID(exprID) |
| 978 |
return p.reportError(loc, "%s", err.Message), true |
| 979 |
} |
| 980 |
|
| 981 |
|
| 982 |
if expr == nil { |
| 983 |
return nil, false |
| 984 |
} |
| 985 |
if p.populateMacroCalls { |
| 986 |
p.helper.addMacroCall(expr.ID(), function, target, args...) |
| 987 |
} |
| 988 |
p.helper.deleteID(exprID) |
| 989 |
return expr, true |
| 990 |
} |
| 991 |
|
| 992 |
func (p *parser) checkAndIncrementRecursionDepth() { |
| 993 |
p.recursionDepth++ |
| 994 |
if p.recursionDepth > p.maxRecursionDepth { |
| 995 |
panic(&recursionError{message: "max recursion depth exceeded"}) |
| 996 |
} |
| 997 |
} |
| 998 |
|
| 999 |
func (p *parser) decrementRecursionDepth() { |
| 1000 |
p.recursionDepth-- |
| 1001 |
} |
| 1002 |
|
| 1003 |
|
| 1004 |
|
| 1005 |
func unnest(tree antlr.ParseTree) antlr.ParseTree { |
| 1006 |
for tree != nil { |
| 1007 |
switch t := tree.(type) { |
| 1008 |
case *gen.ExprContext: |
| 1009 |
|
| 1010 |
if t.GetOp() != nil { |
| 1011 |
return t |
| 1012 |
} |
| 1013 |
|
| 1014 |
tree = t.GetE() |
| 1015 |
case *gen.ConditionalOrContext: |
| 1016 |
|
| 1017 |
if t.GetOps() != nil && len(t.GetOps()) > 0 { |
| 1018 |
return t |
| 1019 |
} |
| 1020 |
|
| 1021 |
tree = t.GetE() |
| 1022 |
case *gen.ConditionalAndContext: |
| 1023 |
|
| 1024 |
if t.GetOps() != nil && len(t.GetOps()) > 0 { |
| 1025 |
return t |
| 1026 |
} |
| 1027 |
|
| 1028 |
tree = t.GetE() |
| 1029 |
case *gen.RelationContext: |
| 1030 |
|
| 1031 |
if t.GetOp() != nil { |
| 1032 |
return t |
| 1033 |
} |
| 1034 |
|
| 1035 |
tree = t.Calc() |
| 1036 |
case *gen.CalcContext: |
| 1037 |
|
| 1038 |
if t.GetOp() != nil { |
| 1039 |
return t |
| 1040 |
} |
| 1041 |
|
| 1042 |
tree = t.Unary() |
| 1043 |
case *gen.MemberExprContext: |
| 1044 |
|
| 1045 |
tree = t.Member() |
| 1046 |
case *gen.PrimaryExprContext: |
| 1047 |
|
| 1048 |
tree = t.Primary() |
| 1049 |
case *gen.NestedContext: |
| 1050 |
|
| 1051 |
tree = t.GetE() |
| 1052 |
case *gen.ConstantLiteralContext: |
| 1053 |
|
| 1054 |
tree = t.Literal() |
| 1055 |
default: |
| 1056 |
return t |
| 1057 |
} |
| 1058 |
} |
| 1059 |
return tree |
| 1060 |
} |
| 1061 |
|
| 1062 |
var ( |
| 1063 |
reservedIdentifier = regexp.MustCompile("no viable alternative at input '.(true|false|null)'") |
| 1064 |
mismatchedReservedIdentifier = "mismatched input '$1' expecting IDENTIFIER" |
| 1065 |
) |