rebase: update kubernetes to 1.28.0 in main

updating kubernetes to 1.28.0
in the main repo.

Signed-off-by: Madhu Rajanna <madhupr007@gmail.com>
This commit is contained in:
Madhu Rajanna
2023-08-17 07:15:28 +02:00
committed by mergify[bot]
parent b2fdc269c3
commit ff3e84ad67
706 changed files with 45252 additions and 16346 deletions

View File

@ -23,8 +23,8 @@ go_library(
"//common/operators:go_default_library",
"//common/runes:go_default_library",
"//parser/gen:go_default_library",
"@com_github_antlr_antlr4_runtime_go_antlr//:go_default_library",
"@org_golang_google_genproto//googleapis/api/expr/v1alpha1:go_default_library",
"@com_github_antlr_antlr4_runtime_go_antlr_v4//:go_default_library",
"@org_golang_google_genproto_googleapis_api//expr/v1alpha1:go_default_library",
"@org_golang_google_protobuf//proto:go_default_library",
"@org_golang_google_protobuf//types/known/structpb:go_default_library",
],
@ -34,6 +34,7 @@ go_test(
name = "go_default_test",
size = "small",
srcs = [
"helper_test.go",
"parser_test.go",
"unescape_test.go",
"unparser_test.go",
@ -45,7 +46,8 @@ go_test(
"//common/debug:go_default_library",
"//parser/gen:go_default_library",
"//test:go_default_library",
"@com_github_antlr_antlr4_runtime_go_antlr//:go_default_library",
"@com_github_antlr_antlr4_runtime_go_antlr_v4//:go_default_library",
"@org_golang_google_protobuf//proto:go_default_library",
"@org_golang_google_protobuf//testing/protocmp:go_default_library",
],
)

View File

@ -21,6 +21,6 @@ go_library(
],
importpath = "github.com/google/cel-go/parser/gen",
deps = [
"@com_github_antlr_antlr4_runtime_go_antlr//:go_default_library",
"@com_github_antlr_antlr4_runtime_go_antlr_v4//:go_default_library",
],
)

View File

@ -52,16 +52,18 @@ unary
member
: primary # PrimaryExpr
| member op='.' id=IDENTIFIER (open='(' args=exprList? ')')? # SelectOrCall
| member op='[' index=expr ']' # Index
| member op='{' entries=fieldInitializerList? ','? '}' # CreateMessage
| member op='.' (opt='?')? id=IDENTIFIER # Select
| member op='.' id=IDENTIFIER open='(' args=exprList? ')' # MemberCall
| member op='[' (opt='?')? index=expr ']' # Index
;
primary
: leadingDot='.'? id=IDENTIFIER (op='(' args=exprList? ')')? # IdentOrGlobalCall
| '(' e=expr ')' # Nested
| op='[' elems=exprList? ','? ']' # CreateList
| op='[' elems=listInit? ','? ']' # CreateList
| op='{' entries=mapInitializerList? ','? '}' # CreateStruct
| leadingDot='.'? ids+=IDENTIFIER (ops+='.' ids+=IDENTIFIER)*
op='{' entries=fieldInitializerList? ','? '}' # CreateMessage
| literal # ConstantLiteral
;
@ -69,23 +71,35 @@ exprList
: e+=expr (',' e+=expr)*
;
listInit
: elems+=optExpr (',' elems+=optExpr)*
;
fieldInitializerList
: fields+=IDENTIFIER cols+=':' values+=expr (',' fields+=IDENTIFIER cols+=':' values+=expr)*
: fields+=optField cols+=':' values+=expr (',' fields+=optField cols+=':' values+=expr)*
;
optField
: (opt='?')? IDENTIFIER
;
mapInitializerList
: keys+=expr cols+=':' values+=expr (',' keys+=expr cols+=':' values+=expr)*
: keys+=optExpr cols+=':' values+=expr (',' keys+=optExpr cols+=':' values+=expr)*
;
optExpr
: (opt='?')? e=expr
;
literal
: sign=MINUS? tok=NUM_INT # Int
| tok=NUM_UINT # Uint
| tok=NUM_UINT # Uint
| sign=MINUS? tok=NUM_FLOAT # Double
| tok=STRING # String
| tok=BYTES # Bytes
| tok=CEL_TRUE # BoolTrue
| tok=CEL_FALSE # BoolFalse
| tok=NUL # Null
| tok=STRING # String
| tok=BYTES # Bytes
| tok=CEL_TRUE # BoolTrue
| tok=CEL_FALSE # BoolFalse
| tok=NUL # Null
;
// Lexer Rules

File diff suppressed because one or more lines are too long

View File

@ -1,7 +1,7 @@
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.10.1. DO NOT EDIT.
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.12.0. DO NOT EDIT.
package gen // CEL
import "github.com/antlr/antlr4/runtime/Go/antlr"
import "github.com/antlr/antlr4/runtime/Go/antlr/v4"
// BaseCELListener is a complete listener for a parse tree produced by CELParser.
type BaseCELListener struct{}
@ -74,11 +74,17 @@ func (s *BaseCELListener) EnterNegate(ctx *NegateContext) {}
// ExitNegate is called when production Negate is exited.
func (s *BaseCELListener) ExitNegate(ctx *NegateContext) {}
// EnterSelectOrCall is called when production SelectOrCall is entered.
func (s *BaseCELListener) EnterSelectOrCall(ctx *SelectOrCallContext) {}
// EnterMemberCall is called when production MemberCall is entered.
func (s *BaseCELListener) EnterMemberCall(ctx *MemberCallContext) {}
// ExitSelectOrCall is called when production SelectOrCall is exited.
func (s *BaseCELListener) ExitSelectOrCall(ctx *SelectOrCallContext) {}
// ExitMemberCall is called when production MemberCall is exited.
func (s *BaseCELListener) ExitMemberCall(ctx *MemberCallContext) {}
// EnterSelect is called when production Select is entered.
func (s *BaseCELListener) EnterSelect(ctx *SelectContext) {}
// ExitSelect is called when production Select is exited.
func (s *BaseCELListener) ExitSelect(ctx *SelectContext) {}
// EnterPrimaryExpr is called when production PrimaryExpr is entered.
func (s *BaseCELListener) EnterPrimaryExpr(ctx *PrimaryExprContext) {}
@ -92,12 +98,6 @@ func (s *BaseCELListener) EnterIndex(ctx *IndexContext) {}
// ExitIndex is called when production Index is exited.
func (s *BaseCELListener) ExitIndex(ctx *IndexContext) {}
// EnterCreateMessage is called when production CreateMessage is entered.
func (s *BaseCELListener) EnterCreateMessage(ctx *CreateMessageContext) {}
// ExitCreateMessage is called when production CreateMessage is exited.
func (s *BaseCELListener) ExitCreateMessage(ctx *CreateMessageContext) {}
// EnterIdentOrGlobalCall is called when production IdentOrGlobalCall is entered.
func (s *BaseCELListener) EnterIdentOrGlobalCall(ctx *IdentOrGlobalCallContext) {}
@ -122,6 +122,12 @@ func (s *BaseCELListener) EnterCreateStruct(ctx *CreateStructContext) {}
// ExitCreateStruct is called when production CreateStruct is exited.
func (s *BaseCELListener) ExitCreateStruct(ctx *CreateStructContext) {}
// EnterCreateMessage is called when production CreateMessage is entered.
func (s *BaseCELListener) EnterCreateMessage(ctx *CreateMessageContext) {}
// ExitCreateMessage is called when production CreateMessage is exited.
func (s *BaseCELListener) ExitCreateMessage(ctx *CreateMessageContext) {}
// EnterConstantLiteral is called when production ConstantLiteral is entered.
func (s *BaseCELListener) EnterConstantLiteral(ctx *ConstantLiteralContext) {}
@ -134,18 +140,36 @@ func (s *BaseCELListener) EnterExprList(ctx *ExprListContext) {}
// ExitExprList is called when production exprList is exited.
func (s *BaseCELListener) ExitExprList(ctx *ExprListContext) {}
// EnterListInit is called when production listInit is entered.
func (s *BaseCELListener) EnterListInit(ctx *ListInitContext) {}
// ExitListInit is called when production listInit is exited.
func (s *BaseCELListener) ExitListInit(ctx *ListInitContext) {}
// EnterFieldInitializerList is called when production fieldInitializerList is entered.
func (s *BaseCELListener) EnterFieldInitializerList(ctx *FieldInitializerListContext) {}
// ExitFieldInitializerList is called when production fieldInitializerList is exited.
func (s *BaseCELListener) ExitFieldInitializerList(ctx *FieldInitializerListContext) {}
// EnterOptField is called when production optField is entered.
func (s *BaseCELListener) EnterOptField(ctx *OptFieldContext) {}
// ExitOptField is called when production optField is exited.
func (s *BaseCELListener) ExitOptField(ctx *OptFieldContext) {}
// EnterMapInitializerList is called when production mapInitializerList is entered.
func (s *BaseCELListener) EnterMapInitializerList(ctx *MapInitializerListContext) {}
// ExitMapInitializerList is called when production mapInitializerList is exited.
func (s *BaseCELListener) ExitMapInitializerList(ctx *MapInitializerListContext) {}
// EnterOptExpr is called when production optExpr is entered.
func (s *BaseCELListener) EnterOptExpr(ctx *OptExprContext) {}
// ExitOptExpr is called when production optExpr is exited.
func (s *BaseCELListener) ExitOptExpr(ctx *OptExprContext) {}
// EnterInt is called when production Int is entered.
func (s *BaseCELListener) EnterInt(ctx *IntContext) {}

View File

@ -1,7 +1,7 @@
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.10.1. DO NOT EDIT.
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.12.0. DO NOT EDIT.
package gen // CEL
import "github.com/antlr/antlr4/runtime/Go/antlr"
import "github.com/antlr/antlr4/runtime/Go/antlr/v4"
type BaseCELVisitor struct {
*antlr.BaseParseTreeVisitor
@ -43,7 +43,11 @@ func (v *BaseCELVisitor) VisitNegate(ctx *NegateContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitSelectOrCall(ctx *SelectOrCallContext) interface{} {
func (v *BaseCELVisitor) VisitMemberCall(ctx *MemberCallContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitSelect(ctx *SelectContext) interface{} {
return v.VisitChildren(ctx)
}
@ -55,10 +59,6 @@ func (v *BaseCELVisitor) VisitIndex(ctx *IndexContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitCreateMessage(ctx *CreateMessageContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitIdentOrGlobalCall(ctx *IdentOrGlobalCallContext) interface{} {
return v.VisitChildren(ctx)
}
@ -75,6 +75,10 @@ func (v *BaseCELVisitor) VisitCreateStruct(ctx *CreateStructContext) interface{}
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitCreateMessage(ctx *CreateMessageContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitConstantLiteral(ctx *ConstantLiteralContext) interface{} {
return v.VisitChildren(ctx)
}
@ -83,14 +87,26 @@ func (v *BaseCELVisitor) VisitExprList(ctx *ExprListContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitListInit(ctx *ListInitContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitFieldInitializerList(ctx *FieldInitializerListContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitOptField(ctx *OptFieldContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitMapInitializerList(ctx *MapInitializerListContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitOptExpr(ctx *OptExprContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitInt(ctx *IntContext) interface{} {
return v.VisitChildren(ctx)
}

View File

@ -1,4 +1,4 @@
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.10.1. DO NOT EDIT.
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.12.0. DO NOT EDIT.
package gen
@ -7,7 +7,7 @@ import (
"sync"
"unicode"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/antlr/antlr4/runtime/Go/antlr/v4"
)
// Suppress unused import error

View File

@ -1,7 +1,7 @@
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.10.1. DO NOT EDIT.
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.12.0. DO NOT EDIT.
package gen // CEL
import "github.com/antlr/antlr4/runtime/Go/antlr"
import "github.com/antlr/antlr4/runtime/Go/antlr/v4"
// CELListener is a complete listener for a parse tree produced by CELParser.
type CELListener interface {
@ -34,8 +34,11 @@ type CELListener interface {
// EnterNegate is called when entering the Negate production.
EnterNegate(c *NegateContext)
// EnterSelectOrCall is called when entering the SelectOrCall production.
EnterSelectOrCall(c *SelectOrCallContext)
// EnterMemberCall is called when entering the MemberCall production.
EnterMemberCall(c *MemberCallContext)
// EnterSelect is called when entering the Select production.
EnterSelect(c *SelectContext)
// EnterPrimaryExpr is called when entering the PrimaryExpr production.
EnterPrimaryExpr(c *PrimaryExprContext)
@ -43,9 +46,6 @@ type CELListener interface {
// EnterIndex is called when entering the Index production.
EnterIndex(c *IndexContext)
// EnterCreateMessage is called when entering the CreateMessage production.
EnterCreateMessage(c *CreateMessageContext)
// EnterIdentOrGlobalCall is called when entering the IdentOrGlobalCall production.
EnterIdentOrGlobalCall(c *IdentOrGlobalCallContext)
@ -58,18 +58,30 @@ type CELListener interface {
// EnterCreateStruct is called when entering the CreateStruct production.
EnterCreateStruct(c *CreateStructContext)
// EnterCreateMessage is called when entering the CreateMessage production.
EnterCreateMessage(c *CreateMessageContext)
// EnterConstantLiteral is called when entering the ConstantLiteral production.
EnterConstantLiteral(c *ConstantLiteralContext)
// EnterExprList is called when entering the exprList production.
EnterExprList(c *ExprListContext)
// EnterListInit is called when entering the listInit production.
EnterListInit(c *ListInitContext)
// EnterFieldInitializerList is called when entering the fieldInitializerList production.
EnterFieldInitializerList(c *FieldInitializerListContext)
// EnterOptField is called when entering the optField production.
EnterOptField(c *OptFieldContext)
// EnterMapInitializerList is called when entering the mapInitializerList production.
EnterMapInitializerList(c *MapInitializerListContext)
// EnterOptExpr is called when entering the optExpr production.
EnterOptExpr(c *OptExprContext)
// EnterInt is called when entering the Int production.
EnterInt(c *IntContext)
@ -121,8 +133,11 @@ type CELListener interface {
// ExitNegate is called when exiting the Negate production.
ExitNegate(c *NegateContext)
// ExitSelectOrCall is called when exiting the SelectOrCall production.
ExitSelectOrCall(c *SelectOrCallContext)
// ExitMemberCall is called when exiting the MemberCall production.
ExitMemberCall(c *MemberCallContext)
// ExitSelect is called when exiting the Select production.
ExitSelect(c *SelectContext)
// ExitPrimaryExpr is called when exiting the PrimaryExpr production.
ExitPrimaryExpr(c *PrimaryExprContext)
@ -130,9 +145,6 @@ type CELListener interface {
// ExitIndex is called when exiting the Index production.
ExitIndex(c *IndexContext)
// ExitCreateMessage is called when exiting the CreateMessage production.
ExitCreateMessage(c *CreateMessageContext)
// ExitIdentOrGlobalCall is called when exiting the IdentOrGlobalCall production.
ExitIdentOrGlobalCall(c *IdentOrGlobalCallContext)
@ -145,18 +157,30 @@ type CELListener interface {
// ExitCreateStruct is called when exiting the CreateStruct production.
ExitCreateStruct(c *CreateStructContext)
// ExitCreateMessage is called when exiting the CreateMessage production.
ExitCreateMessage(c *CreateMessageContext)
// ExitConstantLiteral is called when exiting the ConstantLiteral production.
ExitConstantLiteral(c *ConstantLiteralContext)
// ExitExprList is called when exiting the exprList production.
ExitExprList(c *ExprListContext)
// ExitListInit is called when exiting the listInit production.
ExitListInit(c *ListInitContext)
// ExitFieldInitializerList is called when exiting the fieldInitializerList production.
ExitFieldInitializerList(c *FieldInitializerListContext)
// ExitOptField is called when exiting the optField production.
ExitOptField(c *OptFieldContext)
// ExitMapInitializerList is called when exiting the mapInitializerList production.
ExitMapInitializerList(c *MapInitializerListContext)
// ExitOptExpr is called when exiting the optExpr production.
ExitOptExpr(c *OptExprContext)
// ExitInt is called when exiting the Int production.
ExitInt(c *IntContext)

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.10.1. DO NOT EDIT.
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.12.0. DO NOT EDIT.
package gen // CEL
import "github.com/antlr/antlr4/runtime/Go/antlr"
import "github.com/antlr/antlr4/runtime/Go/antlr/v4"
// A complete Visitor for a parse tree produced by CELParser.
type CELVisitor interface {
@ -34,8 +34,11 @@ type CELVisitor interface {
// Visit a parse tree produced by CELParser#Negate.
VisitNegate(ctx *NegateContext) interface{}
// Visit a parse tree produced by CELParser#SelectOrCall.
VisitSelectOrCall(ctx *SelectOrCallContext) interface{}
// Visit a parse tree produced by CELParser#MemberCall.
VisitMemberCall(ctx *MemberCallContext) interface{}
// Visit a parse tree produced by CELParser#Select.
VisitSelect(ctx *SelectContext) interface{}
// Visit a parse tree produced by CELParser#PrimaryExpr.
VisitPrimaryExpr(ctx *PrimaryExprContext) interface{}
@ -43,9 +46,6 @@ type CELVisitor interface {
// Visit a parse tree produced by CELParser#Index.
VisitIndex(ctx *IndexContext) interface{}
// Visit a parse tree produced by CELParser#CreateMessage.
VisitCreateMessage(ctx *CreateMessageContext) interface{}
// Visit a parse tree produced by CELParser#IdentOrGlobalCall.
VisitIdentOrGlobalCall(ctx *IdentOrGlobalCallContext) interface{}
@ -58,18 +58,30 @@ type CELVisitor interface {
// Visit a parse tree produced by CELParser#CreateStruct.
VisitCreateStruct(ctx *CreateStructContext) interface{}
// Visit a parse tree produced by CELParser#CreateMessage.
VisitCreateMessage(ctx *CreateMessageContext) interface{}
// Visit a parse tree produced by CELParser#ConstantLiteral.
VisitConstantLiteral(ctx *ConstantLiteralContext) interface{}
// Visit a parse tree produced by CELParser#exprList.
VisitExprList(ctx *ExprListContext) interface{}
// Visit a parse tree produced by CELParser#listInit.
VisitListInit(ctx *ListInitContext) interface{}
// Visit a parse tree produced by CELParser#fieldInitializerList.
VisitFieldInitializerList(ctx *FieldInitializerListContext) interface{}
// Visit a parse tree produced by CELParser#optField.
VisitOptField(ctx *OptFieldContext) interface{}
// Visit a parse tree produced by CELParser#mapInitializerList.
VisitMapInitializerList(ctx *MapInitializerListContext) interface{}
// Visit a parse tree produced by CELParser#optExpr.
VisitOptExpr(ctx *OptExprContext) interface{}
// Visit a parse tree produced by CELParser#Int.
VisitInt(ctx *IntContext) interface{}

View File

@ -27,7 +27,7 @@
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Generate AntLR artifacts.
java -Xmx500M -cp ${DIR}/antlr-4.10.1-complete.jar org.antlr.v4.Tool \
java -Xmx500M -cp ${DIR}/antlr-4.12.0-complete.jar org.antlr.v4.Tool \
-Dlanguage=Go \
-package gen \
-o ${DIR} \

View File

@ -17,7 +17,8 @@ package parser
import (
"sync"
"github.com/antlr/antlr4/runtime/Go/antlr"
antlr "github.com/antlr/antlr4/runtime/Go/antlr/v4"
"github.com/google/cel-go/common"
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
@ -47,115 +48,122 @@ func (p *parserHelper) getSourceInfo() *exprpb.SourceInfo {
MacroCalls: p.macroCalls}
}
func (p *parserHelper) newLiteral(ctx interface{}, value *exprpb.Constant) *exprpb.Expr {
func (p *parserHelper) newLiteral(ctx any, value *exprpb.Constant) *exprpb.Expr {
exprNode := p.newExpr(ctx)
exprNode.ExprKind = &exprpb.Expr_ConstExpr{ConstExpr: value}
return exprNode
}
func (p *parserHelper) newLiteralBool(ctx interface{}, value bool) *exprpb.Expr {
func (p *parserHelper) newLiteralBool(ctx any, value bool) *exprpb.Expr {
return p.newLiteral(ctx,
&exprpb.Constant{ConstantKind: &exprpb.Constant_BoolValue{BoolValue: value}})
}
func (p *parserHelper) newLiteralString(ctx interface{}, value string) *exprpb.Expr {
func (p *parserHelper) newLiteralString(ctx any, value string) *exprpb.Expr {
return p.newLiteral(ctx,
&exprpb.Constant{ConstantKind: &exprpb.Constant_StringValue{StringValue: value}})
}
func (p *parserHelper) newLiteralBytes(ctx interface{}, value []byte) *exprpb.Expr {
func (p *parserHelper) newLiteralBytes(ctx any, value []byte) *exprpb.Expr {
return p.newLiteral(ctx,
&exprpb.Constant{ConstantKind: &exprpb.Constant_BytesValue{BytesValue: value}})
}
func (p *parserHelper) newLiteralInt(ctx interface{}, value int64) *exprpb.Expr {
func (p *parserHelper) newLiteralInt(ctx any, value int64) *exprpb.Expr {
return p.newLiteral(ctx,
&exprpb.Constant{ConstantKind: &exprpb.Constant_Int64Value{Int64Value: value}})
}
func (p *parserHelper) newLiteralUint(ctx interface{}, value uint64) *exprpb.Expr {
func (p *parserHelper) newLiteralUint(ctx any, value uint64) *exprpb.Expr {
return p.newLiteral(ctx, &exprpb.Constant{ConstantKind: &exprpb.Constant_Uint64Value{Uint64Value: value}})
}
func (p *parserHelper) newLiteralDouble(ctx interface{}, value float64) *exprpb.Expr {
func (p *parserHelper) newLiteralDouble(ctx any, value float64) *exprpb.Expr {
return p.newLiteral(ctx,
&exprpb.Constant{ConstantKind: &exprpb.Constant_DoubleValue{DoubleValue: value}})
}
func (p *parserHelper) newIdent(ctx interface{}, name string) *exprpb.Expr {
func (p *parserHelper) newIdent(ctx any, name string) *exprpb.Expr {
exprNode := p.newExpr(ctx)
exprNode.ExprKind = &exprpb.Expr_IdentExpr{IdentExpr: &exprpb.Expr_Ident{Name: name}}
return exprNode
}
func (p *parserHelper) newSelect(ctx interface{}, operand *exprpb.Expr, field string) *exprpb.Expr {
func (p *parserHelper) newSelect(ctx any, operand *exprpb.Expr, field string) *exprpb.Expr {
exprNode := p.newExpr(ctx)
exprNode.ExprKind = &exprpb.Expr_SelectExpr{
SelectExpr: &exprpb.Expr_Select{Operand: operand, Field: field}}
return exprNode
}
func (p *parserHelper) newPresenceTest(ctx interface{}, operand *exprpb.Expr, field string) *exprpb.Expr {
func (p *parserHelper) newPresenceTest(ctx any, operand *exprpb.Expr, field string) *exprpb.Expr {
exprNode := p.newExpr(ctx)
exprNode.ExprKind = &exprpb.Expr_SelectExpr{
SelectExpr: &exprpb.Expr_Select{Operand: operand, Field: field, TestOnly: true}}
return exprNode
}
func (p *parserHelper) newGlobalCall(ctx interface{}, function string, args ...*exprpb.Expr) *exprpb.Expr {
func (p *parserHelper) newGlobalCall(ctx any, function string, args ...*exprpb.Expr) *exprpb.Expr {
exprNode := p.newExpr(ctx)
exprNode.ExprKind = &exprpb.Expr_CallExpr{
CallExpr: &exprpb.Expr_Call{Function: function, Args: args}}
return exprNode
}
func (p *parserHelper) newReceiverCall(ctx interface{}, function string, target *exprpb.Expr, args ...*exprpb.Expr) *exprpb.Expr {
func (p *parserHelper) newReceiverCall(ctx any, function string, target *exprpb.Expr, args ...*exprpb.Expr) *exprpb.Expr {
exprNode := p.newExpr(ctx)
exprNode.ExprKind = &exprpb.Expr_CallExpr{
CallExpr: &exprpb.Expr_Call{Function: function, Target: target, Args: args}}
return exprNode
}
func (p *parserHelper) newList(ctx interface{}, elements ...*exprpb.Expr) *exprpb.Expr {
func (p *parserHelper) newList(ctx any, elements []*exprpb.Expr, optionals ...int32) *exprpb.Expr {
exprNode := p.newExpr(ctx)
exprNode.ExprKind = &exprpb.Expr_ListExpr{
ListExpr: &exprpb.Expr_CreateList{Elements: elements}}
ListExpr: &exprpb.Expr_CreateList{
Elements: elements,
OptionalIndices: optionals,
}}
return exprNode
}
func (p *parserHelper) newMap(ctx interface{}, entries ...*exprpb.Expr_CreateStruct_Entry) *exprpb.Expr {
func (p *parserHelper) newMap(ctx any, entries ...*exprpb.Expr_CreateStruct_Entry) *exprpb.Expr {
exprNode := p.newExpr(ctx)
exprNode.ExprKind = &exprpb.Expr_StructExpr{
StructExpr: &exprpb.Expr_CreateStruct{Entries: entries}}
return exprNode
}
func (p *parserHelper) newMapEntry(entryID int64, key *exprpb.Expr, value *exprpb.Expr) *exprpb.Expr_CreateStruct_Entry {
func (p *parserHelper) newMapEntry(entryID int64, key *exprpb.Expr, value *exprpb.Expr, optional bool) *exprpb.Expr_CreateStruct_Entry {
return &exprpb.Expr_CreateStruct_Entry{
Id: entryID,
KeyKind: &exprpb.Expr_CreateStruct_Entry_MapKey{MapKey: key},
Value: value}
Id: entryID,
KeyKind: &exprpb.Expr_CreateStruct_Entry_MapKey{MapKey: key},
Value: value,
OptionalEntry: optional,
}
}
func (p *parserHelper) newObject(ctx interface{},
typeName string,
entries ...*exprpb.Expr_CreateStruct_Entry) *exprpb.Expr {
func (p *parserHelper) newObject(ctx any, typeName string, entries ...*exprpb.Expr_CreateStruct_Entry) *exprpb.Expr {
exprNode := p.newExpr(ctx)
exprNode.ExprKind = &exprpb.Expr_StructExpr{
StructExpr: &exprpb.Expr_CreateStruct{
MessageName: typeName,
Entries: entries}}
Entries: entries,
},
}
return exprNode
}
func (p *parserHelper) newObjectField(fieldID int64, field string, value *exprpb.Expr) *exprpb.Expr_CreateStruct_Entry {
func (p *parserHelper) newObjectField(fieldID int64, field string, value *exprpb.Expr, optional bool) *exprpb.Expr_CreateStruct_Entry {
return &exprpb.Expr_CreateStruct_Entry{
Id: fieldID,
KeyKind: &exprpb.Expr_CreateStruct_Entry_FieldKey{FieldKey: field},
Value: value}
Id: fieldID,
KeyKind: &exprpb.Expr_CreateStruct_Entry_FieldKey{FieldKey: field},
Value: value,
OptionalEntry: optional,
}
}
func (p *parserHelper) newComprehension(ctx interface{}, iterVar string,
func (p *parserHelper) newComprehension(ctx any, iterVar string,
iterRange *exprpb.Expr,
accuVar string,
accuInit *exprpb.Expr,
@ -175,7 +183,7 @@ func (p *parserHelper) newComprehension(ctx interface{}, iterVar string,
return exprNode
}
func (p *parserHelper) newExpr(ctx interface{}) *exprpb.Expr {
func (p *parserHelper) newExpr(ctx any) *exprpb.Expr {
id, isID := ctx.(int64)
if isID {
return &exprpb.Expr{Id: id}
@ -183,7 +191,7 @@ func (p *parserHelper) newExpr(ctx interface{}) *exprpb.Expr {
return &exprpb.Expr{Id: p.id(ctx)}
}
func (p *parserHelper) id(ctx interface{}) int64 {
func (p *parserHelper) id(ctx any) int64 {
var location common.Location
switch ctx.(type) {
case antlr.ParserRuleContext:
@ -251,7 +259,8 @@ func (p *parserHelper) buildMacroCallArg(expr *exprpb.Expr) *exprpb.Expr {
Id: expr.GetId(),
ExprKind: &exprpb.Expr_ListExpr{
ListExpr: &exprpb.Expr_CreateList{
Elements: macroListArgs,
Elements: macroListArgs,
OptionalIndices: listExpr.GetOptionalIndices(),
},
},
}
@ -360,6 +369,95 @@ func (e *exprHelper) nextMacroID() int64 {
return e.parserHelper.id(e.parserHelper.getLocation(e.id))
}
// Copy implements the ExprHelper interface method by producing a copy of the input Expr value
// with a fresh set of numeric identifiers the Expr and all its descendents.
func (e *exprHelper) Copy(expr *exprpb.Expr) *exprpb.Expr {
copy := e.parserHelper.newExpr(e.parserHelper.getLocation(expr.GetId()))
switch expr.GetExprKind().(type) {
case *exprpb.Expr_ConstExpr:
copy.ExprKind = &exprpb.Expr_ConstExpr{ConstExpr: expr.GetConstExpr()}
case *exprpb.Expr_IdentExpr:
copy.ExprKind = &exprpb.Expr_IdentExpr{IdentExpr: expr.GetIdentExpr()}
case *exprpb.Expr_SelectExpr:
op := expr.GetSelectExpr().GetOperand()
copy.ExprKind = &exprpb.Expr_SelectExpr{SelectExpr: &exprpb.Expr_Select{
Operand: e.Copy(op),
Field: expr.GetSelectExpr().GetField(),
TestOnly: expr.GetSelectExpr().GetTestOnly(),
}}
case *exprpb.Expr_CallExpr:
call := expr.GetCallExpr()
target := call.GetTarget()
if target != nil {
target = e.Copy(target)
}
args := call.GetArgs()
argsCopy := make([]*exprpb.Expr, len(args))
for i, arg := range args {
argsCopy[i] = e.Copy(arg)
}
copy.ExprKind = &exprpb.Expr_CallExpr{
CallExpr: &exprpb.Expr_Call{
Function: call.GetFunction(),
Target: target,
Args: argsCopy,
},
}
case *exprpb.Expr_ListExpr:
elems := expr.GetListExpr().GetElements()
elemsCopy := make([]*exprpb.Expr, len(elems))
for i, elem := range elems {
elemsCopy[i] = e.Copy(elem)
}
copy.ExprKind = &exprpb.Expr_ListExpr{
ListExpr: &exprpb.Expr_CreateList{Elements: elemsCopy},
}
case *exprpb.Expr_StructExpr:
entries := expr.GetStructExpr().GetEntries()
entriesCopy := make([]*exprpb.Expr_CreateStruct_Entry, len(entries))
for i, entry := range entries {
entryCopy := &exprpb.Expr_CreateStruct_Entry{}
entryCopy.Id = e.nextMacroID()
switch entry.GetKeyKind().(type) {
case *exprpb.Expr_CreateStruct_Entry_FieldKey:
entryCopy.KeyKind = &exprpb.Expr_CreateStruct_Entry_FieldKey{
FieldKey: entry.GetFieldKey(),
}
case *exprpb.Expr_CreateStruct_Entry_MapKey:
entryCopy.KeyKind = &exprpb.Expr_CreateStruct_Entry_MapKey{
MapKey: e.Copy(entry.GetMapKey()),
}
}
entryCopy.Value = e.Copy(entry.GetValue())
entriesCopy[i] = entryCopy
}
copy.ExprKind = &exprpb.Expr_StructExpr{
StructExpr: &exprpb.Expr_CreateStruct{
MessageName: expr.GetStructExpr().GetMessageName(),
Entries: entriesCopy,
},
}
case *exprpb.Expr_ComprehensionExpr:
iterRange := e.Copy(expr.GetComprehensionExpr().GetIterRange())
accuInit := e.Copy(expr.GetComprehensionExpr().GetAccuInit())
cond := e.Copy(expr.GetComprehensionExpr().GetLoopCondition())
step := e.Copy(expr.GetComprehensionExpr().GetLoopStep())
result := e.Copy(expr.GetComprehensionExpr().GetResult())
copy.ExprKind = &exprpb.Expr_ComprehensionExpr{
ComprehensionExpr: &exprpb.Expr_Comprehension{
IterRange: iterRange,
IterVar: expr.GetComprehensionExpr().GetIterVar(),
AccuInit: accuInit,
AccuVar: expr.GetComprehensionExpr().GetAccuVar(),
LoopCondition: cond,
LoopStep: step,
Result: result,
},
}
}
return copy
}
// LiteralBool implements the ExprHelper interface method.
func (e *exprHelper) LiteralBool(value bool) *exprpb.Expr {
return e.parserHelper.newLiteralBool(e.nextMacroID(), value)
@ -392,7 +490,7 @@ func (e *exprHelper) LiteralUint(value uint64) *exprpb.Expr {
// NewList implements the ExprHelper interface method.
func (e *exprHelper) NewList(elems ...*exprpb.Expr) *exprpb.Expr {
return e.parserHelper.newList(e.nextMacroID(), elems...)
return e.parserHelper.newList(e.nextMacroID(), elems)
}
// NewMap implements the ExprHelper interface method.
@ -401,21 +499,18 @@ func (e *exprHelper) NewMap(entries ...*exprpb.Expr_CreateStruct_Entry) *exprpb.
}
// NewMapEntry implements the ExprHelper interface method.
func (e *exprHelper) NewMapEntry(key *exprpb.Expr,
val *exprpb.Expr) *exprpb.Expr_CreateStruct_Entry {
return e.parserHelper.newMapEntry(e.nextMacroID(), key, val)
func (e *exprHelper) NewMapEntry(key *exprpb.Expr, val *exprpb.Expr, optional bool) *exprpb.Expr_CreateStruct_Entry {
return e.parserHelper.newMapEntry(e.nextMacroID(), key, val, optional)
}
// NewObject implements the ExprHelper interface method.
func (e *exprHelper) NewObject(typeName string,
fieldInits ...*exprpb.Expr_CreateStruct_Entry) *exprpb.Expr {
func (e *exprHelper) NewObject(typeName string, fieldInits ...*exprpb.Expr_CreateStruct_Entry) *exprpb.Expr {
return e.parserHelper.newObject(e.nextMacroID(), typeName, fieldInits...)
}
// NewObjectFieldInit implements the ExprHelper interface method.
func (e *exprHelper) NewObjectFieldInit(field string,
init *exprpb.Expr) *exprpb.Expr_CreateStruct_Entry {
return e.parserHelper.newObjectField(e.nextMacroID(), field, init)
func (e *exprHelper) NewObjectFieldInit(field string, init *exprpb.Expr, optional bool) *exprpb.Expr_CreateStruct_Entry {
return e.parserHelper.newObjectField(e.nextMacroID(), field, init, optional)
}
// Fold implements the ExprHelper interface method.
@ -471,7 +566,7 @@ func (e *exprHelper) OffsetLocation(exprID int64) common.Location {
var (
// Thread-safe pool of ExprHelper values to minimize alloc overhead of ExprHelper creations.
exprHelperPool = &sync.Pool{
New: func() interface{} {
New: func() any {
return &exprHelper{}
},
}

View File

@ -15,7 +15,8 @@
package parser
import (
"github.com/antlr/antlr4/runtime/Go/antlr"
antlr "github.com/antlr/antlr4/runtime/Go/antlr/v4"
"github.com/google/cel-go/common/runes"
)

View File

@ -132,8 +132,11 @@ func makeVarArgMacroKey(name string, receiverStyle bool) string {
return fmt.Sprintf("%s:*:%v", name, receiverStyle)
}
// MacroExpander converts a call and its associated arguments into a new CEL abstract syntax tree, or an error
// if the input arguments are not suitable for the expansion requirements for the macro in question.
// MacroExpander converts a call and its associated arguments into a new CEL abstract syntax tree.
//
// If the MacroExpander determines within the implementation that an expansion is not needed it may return
// a nil Expr value to indicate a non-match. However, if an expansion is to be performed, but the arguments
// are not well-formed, the result of the expansion will be an error.
//
// The MacroExpander accepts as arguments a MacroExprHelper as well as the arguments used in the function call
// and produces as output an Expr ast node.
@ -147,6 +150,9 @@ type MacroExpander func(eh ExprHelper,
// consistent with the source position and expression id generation code leveraged by both
// the parser and type-checker.
type ExprHelper interface {
// Copy the input expression with a brand new set of identifiers.
Copy(*exprpb.Expr) *exprpb.Expr
// LiteralBool creates an Expr value for a bool literal.
LiteralBool(value bool) *exprpb.Expr
@ -174,14 +180,14 @@ type ExprHelper interface {
NewMap(entries ...*exprpb.Expr_CreateStruct_Entry) *exprpb.Expr
// NewMapEntry creates a Map Entry for the key, value pair.
NewMapEntry(key *exprpb.Expr, val *exprpb.Expr) *exprpb.Expr_CreateStruct_Entry
NewMapEntry(key *exprpb.Expr, val *exprpb.Expr, optional bool) *exprpb.Expr_CreateStruct_Entry
// NewObject creates a CreateStruct instruction for an object with a given type name and
// optional set of field initializers.
NewObject(typeName string, fieldInits ...*exprpb.Expr_CreateStruct_Entry) *exprpb.Expr
// NewObjectFieldInit creates a new Object field initializer from the field name and value.
NewObjectFieldInit(field string, init *exprpb.Expr) *exprpb.Expr_CreateStruct_Entry
NewObjectFieldInit(field string, init *exprpb.Expr, optional bool) *exprpb.Expr_CreateStruct_Entry
// Fold creates a fold comprehension instruction.
//
@ -309,8 +315,10 @@ func MakeExistsOne(eh ExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*ex
// input to produce an output list.
//
// There are two call patterns supported by map:
// <iterRange>.map(<iterVar>, <transform>)
// <iterRange>.map(<iterVar>, <predicate>, <transform>)
//
// <iterRange>.map(<iterVar>, <transform>)
// <iterRange>.map(<iterVar>, <predicate>, <transform>)
//
// In the second form only iterVar values which return true when provided to the predicate expression
// are transformed.
func MakeMap(eh ExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *common.Error) {

View File

@ -18,11 +18,13 @@ import "fmt"
type options struct {
maxRecursionDepth int
errorReportingLimit int
errorRecoveryTokenLookaheadLimit int
errorRecoveryLimit int
expressionSizeCodePointLimit int
macros map[string]Macro
populateMacroCalls bool
enableOptionalSyntax bool
}
// Option configures the behavior of the parser.
@ -45,7 +47,7 @@ func MaxRecursionDepth(limit int) Option {
// successfully resume. In some pathological cases, the parser can look through quite a large set of input which
// in turn generates a lot of back-tracking and performance degredation.
//
// The limit must be > 1, and is recommended to be less than the default of 256.
// The limit must be >= 1, and is recommended to be less than the default of 256.
func ErrorRecoveryLookaheadTokenLimit(limit int) Option {
return func(opts *options) error {
if limit < 1 {
@ -67,6 +69,19 @@ func ErrorRecoveryLimit(limit int) Option {
}
}
// ErrorReportingLimit limits the number of syntax error reports before terminating parsing.
//
// The limit must be at least 1. If unset, the limit will be 100.
func ErrorReportingLimit(limit int) Option {
return func(opts *options) error {
if limit < 1 {
return fmt.Errorf("error reporting limit must be at least 1: %d", limit)
}
opts.errorReportingLimit = limit
return nil
}
}
// ExpressionSizeCodePointLimit is an option which limits the maximum code point count of an
// expression.
func ExpressionSizeCodePointLimit(expressionSizeCodePointLimit int) Option {
@ -102,3 +117,11 @@ func PopulateMacroCalls(populateMacroCalls bool) Option {
return nil
}
}
// EnableOptionalSyntax enables syntax for optional field and index selection.
func EnableOptionalSyntax(optionalSyntax bool) Option {
return func(opts *options) error {
opts.enableOptionalSyntax = optionalSyntax
return nil
}
}

View File

@ -18,11 +18,13 @@ package parser
import (
"fmt"
"regexp"
"strconv"
"strings"
"sync"
"github.com/antlr/antlr4/runtime/Go/antlr"
antlr "github.com/antlr/antlr4/runtime/Go/antlr/v4"
"github.com/google/cel-go/common"
"github.com/google/cel-go/common/operators"
"github.com/google/cel-go/common/runes"
@ -45,6 +47,9 @@ func NewParser(opts ...Option) (*Parser, error) {
return nil, err
}
}
if p.errorReportingLimit == 0 {
p.errorReportingLimit = 100
}
if p.maxRecursionDepth == 0 {
p.maxRecursionDepth = 250
}
@ -89,9 +94,11 @@ func (p *Parser) Parse(source common.Source) (*exprpb.ParsedExpr, *common.Errors
helper: newParserHelper(source),
macros: p.macros,
maxRecursionDepth: p.maxRecursionDepth,
errorReportingLimit: p.errorReportingLimit,
errorRecoveryLimit: p.errorRecoveryLimit,
errorRecoveryLookaheadTokenLimit: p.errorRecoveryTokenLookaheadLimit,
populateMacroCalls: p.populateMacroCalls,
enableOptionalSyntax: p.enableOptionalSyntax,
}
buf, ok := source.(runes.Buffer)
if !ok {
@ -178,7 +185,7 @@ func (rl *recursionListener) EnterEveryRule(ctx antlr.ParserRuleContext) {
} else {
*depth++
}
if *depth >= rl.maxDepth {
if *depth > rl.maxDepth {
panic(&recursionError{
message: fmt.Sprintf("expression recursion limit exceeded: %d", rl.maxDepth),
})
@ -197,6 +204,16 @@ func (rl *recursionListener) ExitEveryRule(ctx antlr.ParserRuleContext) {
var _ antlr.ParseTreeListener = &recursionListener{}
type tooManyErrors struct {
errorReportingLimit int
}
func (t *tooManyErrors) Error() string {
return fmt.Sprintf("More than %d syntax errors", t.errorReportingLimit)
}
var _ error = &tooManyErrors{}
type recoveryLimitError struct {
message string
}
@ -271,17 +288,20 @@ type parser struct {
helper *parserHelper
macros map[string]Macro
recursionDepth int
errorReports int
maxRecursionDepth int
errorReportingLimit int
errorRecoveryLimit int
errorRecoveryLookaheadTokenLimit int
populateMacroCalls bool
enableOptionalSyntax bool
}
var (
_ gen.CELVisitor = (*parser)(nil)
lexerPool *sync.Pool = &sync.Pool{
New: func() interface{} {
New: func() any {
l := gen.NewCELLexer(nil)
l.RemoveErrorListeners()
return l
@ -289,7 +309,7 @@ var (
}
parserPool *sync.Pool = &sync.Pool{
New: func() interface{} {
New: func() any {
p := gen.NewCELParser(nil)
p.RemoveErrorListeners()
return p
@ -302,14 +322,14 @@ func (p *parser) parse(expr runes.Buffer, desc string) *exprpb.Expr {
lexer := lexerPool.Get().(*gen.CELLexer)
prsr := parserPool.Get().(*gen.CELParser)
// Unfortunately ANTLR Go runtime is missing (*antlr.BaseParser).RemoveParseListeners, so this is
// good enough until that is exported.
prsrListener := &recursionListener{
maxDepth: p.maxRecursionDepth,
ruleTypeDepth: map[int]*int{},
}
defer func() {
// Unfortunately ANTLR Go runtime is missing (*antlr.BaseParser).RemoveParseListeners,
// so this is good enough until that is exported.
// Reset the lexer and parser before putting them back in the pool.
lexer.RemoveErrorListeners()
prsr.RemoveParseListener(prsrListener)
@ -340,6 +360,8 @@ func (p *parser) parse(expr runes.Buffer, desc string) *exprpb.Expr {
p.errors.ReportError(common.NoLocation, err.Error())
case *recursionError:
p.errors.ReportError(common.NoLocation, err.Error())
case *tooManyErrors:
// do nothing
case *recoveryLimitError:
// do nothing, listeners already notified and error reported.
default:
@ -352,57 +374,85 @@ func (p *parser) parse(expr runes.Buffer, desc string) *exprpb.Expr {
}
// Visitor implementations.
func (p *parser) Visit(tree antlr.ParseTree) interface{} {
p.recursionDepth++
if p.recursionDepth > p.maxRecursionDepth {
panic(&recursionError{message: "max recursion depth exceeded"})
}
defer func() {
p.recursionDepth--
}()
switch tree.(type) {
func (p *parser) Visit(tree antlr.ParseTree) any {
t := unnest(tree)
switch tree := t.(type) {
case *gen.StartContext:
return p.VisitStart(tree.(*gen.StartContext))
return p.VisitStart(tree)
case *gen.ExprContext:
return p.VisitExpr(tree.(*gen.ExprContext))
p.checkAndIncrementRecursionDepth()
out := p.VisitExpr(tree)
p.decrementRecursionDepth()
return out
case *gen.ConditionalAndContext:
return p.VisitConditionalAnd(tree.(*gen.ConditionalAndContext))
return p.VisitConditionalAnd(tree)
case *gen.ConditionalOrContext:
return p.VisitConditionalOr(tree.(*gen.ConditionalOrContext))
return p.VisitConditionalOr(tree)
case *gen.RelationContext:
return p.VisitRelation(tree.(*gen.RelationContext))
p.checkAndIncrementRecursionDepth()
out := p.VisitRelation(tree)
p.decrementRecursionDepth()
return out
case *gen.CalcContext:
return p.VisitCalc(tree.(*gen.CalcContext))
p.checkAndIncrementRecursionDepth()
out := p.VisitCalc(tree)
p.decrementRecursionDepth()
return out
case *gen.LogicalNotContext:
return p.VisitLogicalNot(tree.(*gen.LogicalNotContext))
case *gen.MemberExprContext:
return p.VisitMemberExpr(tree.(*gen.MemberExprContext))
case *gen.PrimaryExprContext:
return p.VisitPrimaryExpr(tree.(*gen.PrimaryExprContext))
case *gen.SelectOrCallContext:
return p.VisitSelectOrCall(tree.(*gen.SelectOrCallContext))
return p.VisitLogicalNot(tree)
case *gen.IdentOrGlobalCallContext:
return p.VisitIdentOrGlobalCall(tree)
case *gen.SelectContext:
p.checkAndIncrementRecursionDepth()
out := p.VisitSelect(tree)
p.decrementRecursionDepth()
return out
case *gen.MemberCallContext:
p.checkAndIncrementRecursionDepth()
out := p.VisitMemberCall(tree)
p.decrementRecursionDepth()
return out
case *gen.MapInitializerListContext:
return p.VisitMapInitializerList(tree.(*gen.MapInitializerListContext))
return p.VisitMapInitializerList(tree)
case *gen.NegateContext:
return p.VisitNegate(tree.(*gen.NegateContext))
return p.VisitNegate(tree)
case *gen.IndexContext:
return p.VisitIndex(tree.(*gen.IndexContext))
p.checkAndIncrementRecursionDepth()
out := p.VisitIndex(tree)
p.decrementRecursionDepth()
return out
case *gen.UnaryContext:
return p.VisitUnary(tree.(*gen.UnaryContext))
return p.VisitUnary(tree)
case *gen.CreateListContext:
return p.VisitCreateList(tree.(*gen.CreateListContext))
return p.VisitCreateList(tree)
case *gen.CreateMessageContext:
return p.VisitCreateMessage(tree.(*gen.CreateMessageContext))
return p.VisitCreateMessage(tree)
case *gen.CreateStructContext:
return p.VisitCreateStruct(tree.(*gen.CreateStructContext))
return p.VisitCreateStruct(tree)
case *gen.IntContext:
return p.VisitInt(tree)
case *gen.UintContext:
return p.VisitUint(tree)
case *gen.DoubleContext:
return p.VisitDouble(tree)
case *gen.StringContext:
return p.VisitString(tree)
case *gen.BytesContext:
return p.VisitBytes(tree)
case *gen.BoolFalseContext:
return p.VisitBoolFalse(tree)
case *gen.BoolTrueContext:
return p.VisitBoolTrue(tree)
case *gen.NullContext:
return p.VisitNull(tree)
}
// Report at least one error if the parser reaches an unknown parse element.
// Typically, this happens if the parser has already encountered a syntax error elsewhere.
if len(p.errors.GetErrors()) == 0 {
txt := "<<nil>>"
if tree != nil {
txt = fmt.Sprintf("<<%T>>", tree)
if t != nil {
txt = fmt.Sprintf("<<%T>>", t)
}
return p.reportError(common.NoLocation, "unknown parse element encountered: %s", txt)
}
@ -411,12 +461,12 @@ func (p *parser) Visit(tree antlr.ParseTree) interface{} {
}
// Visit a parse tree produced by CELParser#start.
func (p *parser) VisitStart(ctx *gen.StartContext) interface{} {
func (p *parser) VisitStart(ctx *gen.StartContext) any {
return p.Visit(ctx.Expr())
}
// Visit a parse tree produced by CELParser#expr.
func (p *parser) VisitExpr(ctx *gen.ExprContext) interface{} {
func (p *parser) VisitExpr(ctx *gen.ExprContext) any {
result := p.Visit(ctx.GetE()).(*exprpb.Expr)
if ctx.GetOp() == nil {
return result
@ -428,11 +478,8 @@ func (p *parser) VisitExpr(ctx *gen.ExprContext) interface{} {
}
// Visit a parse tree produced by CELParser#conditionalOr.
func (p *parser) VisitConditionalOr(ctx *gen.ConditionalOrContext) interface{} {
func (p *parser) VisitConditionalOr(ctx *gen.ConditionalOrContext) any {
result := p.Visit(ctx.GetE()).(*exprpb.Expr)
if ctx.GetOps() == nil {
return result
}
b := newBalancer(p.helper, operators.LogicalOr, result)
rest := ctx.GetE1()
for i, op := range ctx.GetOps() {
@ -447,11 +494,8 @@ func (p *parser) VisitConditionalOr(ctx *gen.ConditionalOrContext) interface{} {
}
// Visit a parse tree produced by CELParser#conditionalAnd.
func (p *parser) VisitConditionalAnd(ctx *gen.ConditionalAndContext) interface{} {
func (p *parser) VisitConditionalAnd(ctx *gen.ConditionalAndContext) any {
result := p.Visit(ctx.GetE()).(*exprpb.Expr)
if ctx.GetOps() == nil {
return result
}
b := newBalancer(p.helper, operators.LogicalAnd, result)
rest := ctx.GetE1()
for i, op := range ctx.GetOps() {
@ -466,10 +510,7 @@ func (p *parser) VisitConditionalAnd(ctx *gen.ConditionalAndContext) interface{}
}
// Visit a parse tree produced by CELParser#relation.
func (p *parser) VisitRelation(ctx *gen.RelationContext) interface{} {
if ctx.Calc() != nil {
return p.Visit(ctx.Calc())
}
func (p *parser) VisitRelation(ctx *gen.RelationContext) any {
opText := ""
if ctx.GetOp() != nil {
opText = ctx.GetOp().GetText()
@ -484,10 +525,7 @@ func (p *parser) VisitRelation(ctx *gen.RelationContext) interface{} {
}
// Visit a parse tree produced by CELParser#calc.
func (p *parser) VisitCalc(ctx *gen.CalcContext) interface{} {
if ctx.Unary() != nil {
return p.Visit(ctx.Unary())
}
func (p *parser) VisitCalc(ctx *gen.CalcContext) any {
opText := ""
if ctx.GetOp() != nil {
opText = ctx.GetOp().GetText()
@ -501,27 +539,12 @@ func (p *parser) VisitCalc(ctx *gen.CalcContext) interface{} {
return p.reportError(ctx, "operator not found")
}
func (p *parser) VisitUnary(ctx *gen.UnaryContext) interface{} {
func (p *parser) VisitUnary(ctx *gen.UnaryContext) any {
return p.helper.newLiteralString(ctx, "<<error>>")
}
// Visit a parse tree produced by CELParser#MemberExpr.
func (p *parser) VisitMemberExpr(ctx *gen.MemberExprContext) interface{} {
switch ctx.Member().(type) {
case *gen.PrimaryExprContext:
return p.VisitPrimaryExpr(ctx.Member().(*gen.PrimaryExprContext))
case *gen.SelectOrCallContext:
return p.VisitSelectOrCall(ctx.Member().(*gen.SelectOrCallContext))
case *gen.IndexContext:
return p.VisitIndex(ctx.Member().(*gen.IndexContext))
case *gen.CreateMessageContext:
return p.VisitCreateMessage(ctx.Member().(*gen.CreateMessageContext))
}
return p.reportError(ctx, "unsupported simple expression")
}
// Visit a parse tree produced by CELParser#LogicalNot.
func (p *parser) VisitLogicalNot(ctx *gen.LogicalNotContext) interface{} {
func (p *parser) VisitLogicalNot(ctx *gen.LogicalNotContext) any {
if len(ctx.GetOps())%2 == 0 {
return p.Visit(ctx.Member())
}
@ -530,7 +553,7 @@ func (p *parser) VisitLogicalNot(ctx *gen.LogicalNotContext) interface{} {
return p.globalCallOrMacro(opID, operators.LogicalNot, target)
}
func (p *parser) VisitNegate(ctx *gen.NegateContext) interface{} {
func (p *parser) VisitNegate(ctx *gen.NegateContext) any {
if len(ctx.GetOps())%2 == 0 {
return p.Visit(ctx.Member())
}
@ -539,60 +562,77 @@ func (p *parser) VisitNegate(ctx *gen.NegateContext) interface{} {
return p.globalCallOrMacro(opID, operators.Negate, target)
}
// Visit a parse tree produced by CELParser#SelectOrCall.
func (p *parser) VisitSelectOrCall(ctx *gen.SelectOrCallContext) interface{} {
// VisitSelect visits a parse tree produced by CELParser#Select.
func (p *parser) VisitSelect(ctx *gen.SelectContext) any {
operand := p.Visit(ctx.Member()).(*exprpb.Expr)
// Handle the error case where no valid identifier is specified.
if ctx.GetId() == nil || ctx.GetOp() == nil {
return p.helper.newExpr(ctx)
}
id := ctx.GetId().GetText()
if ctx.GetOpt() != nil {
if !p.enableOptionalSyntax {
return p.reportError(ctx.GetOp(), "unsupported syntax '.?'")
}
return p.helper.newGlobalCall(
ctx.GetOp(),
operators.OptSelect,
operand,
p.helper.newLiteralString(ctx.GetId(), id))
}
return p.helper.newSelect(ctx.GetOp(), operand, id)
}
// VisitMemberCall visits a parse tree produced by CELParser#MemberCall.
func (p *parser) VisitMemberCall(ctx *gen.MemberCallContext) any {
operand := p.Visit(ctx.Member()).(*exprpb.Expr)
// Handle the error case where no valid identifier is specified.
if ctx.GetId() == nil {
return p.helper.newExpr(ctx)
}
id := ctx.GetId().GetText()
if ctx.GetOpen() != nil {
opID := p.helper.id(ctx.GetOpen())
return p.receiverCallOrMacro(opID, id, operand, p.visitList(ctx.GetArgs())...)
}
return p.helper.newSelect(ctx.GetOp(), operand, id)
}
// Visit a parse tree produced by CELParser#PrimaryExpr.
func (p *parser) VisitPrimaryExpr(ctx *gen.PrimaryExprContext) interface{} {
switch ctx.Primary().(type) {
case *gen.NestedContext:
return p.VisitNested(ctx.Primary().(*gen.NestedContext))
case *gen.IdentOrGlobalCallContext:
return p.VisitIdentOrGlobalCall(ctx.Primary().(*gen.IdentOrGlobalCallContext))
case *gen.CreateListContext:
return p.VisitCreateList(ctx.Primary().(*gen.CreateListContext))
case *gen.CreateStructContext:
return p.VisitCreateStruct(ctx.Primary().(*gen.CreateStructContext))
case *gen.ConstantLiteralContext:
return p.VisitConstantLiteral(ctx.Primary().(*gen.ConstantLiteralContext))
}
return p.reportError(ctx, "invalid primary expression")
opID := p.helper.id(ctx.GetOpen())
return p.receiverCallOrMacro(opID, id, operand, p.visitExprList(ctx.GetArgs())...)
}
// Visit a parse tree produced by CELParser#Index.
func (p *parser) VisitIndex(ctx *gen.IndexContext) interface{} {
func (p *parser) VisitIndex(ctx *gen.IndexContext) any {
target := p.Visit(ctx.Member()).(*exprpb.Expr)
// Handle the error case where no valid identifier is specified.
if ctx.GetOp() == nil {
return p.helper.newExpr(ctx)
}
opID := p.helper.id(ctx.GetOp())
index := p.Visit(ctx.GetIndex()).(*exprpb.Expr)
return p.globalCallOrMacro(opID, operators.Index, target, index)
operator := operators.Index
if ctx.GetOpt() != nil {
if !p.enableOptionalSyntax {
return p.reportError(ctx.GetOp(), "unsupported syntax '[?'")
}
operator = operators.OptIndex
}
return p.globalCallOrMacro(opID, operator, target, index)
}
// Visit a parse tree produced by CELParser#CreateMessage.
func (p *parser) VisitCreateMessage(ctx *gen.CreateMessageContext) interface{} {
target := p.Visit(ctx.Member()).(*exprpb.Expr)
objID := p.helper.id(ctx.GetOp())
if messageName, found := p.extractQualifiedName(target); found {
entries := p.VisitIFieldInitializerList(ctx.GetEntries()).([]*exprpb.Expr_CreateStruct_Entry)
return p.helper.newObject(objID, messageName, entries...)
func (p *parser) VisitCreateMessage(ctx *gen.CreateMessageContext) any {
messageName := ""
for _, id := range ctx.GetIds() {
if len(messageName) != 0 {
messageName += "."
}
messageName += id.GetText()
}
return p.helper.newExpr(objID)
if ctx.GetLeadingDot() != nil {
messageName = "." + messageName
}
objID := p.helper.id(ctx.GetOp())
entries := p.VisitIFieldInitializerList(ctx.GetEntries()).([]*exprpb.Expr_CreateStruct_Entry)
return p.helper.newObject(objID, messageName, entries...)
}
// Visit a parse tree of field initializers.
func (p *parser) VisitIFieldInitializerList(ctx gen.IFieldInitializerListContext) interface{} {
func (p *parser) VisitIFieldInitializerList(ctx gen.IFieldInitializerListContext) any {
if ctx == nil || ctx.GetFields() == nil {
// This is the result of a syntax error handled elswhere, return empty.
return []*exprpb.Expr_CreateStruct_Entry{}
@ -607,15 +647,27 @@ func (p *parser) VisitIFieldInitializerList(ctx gen.IFieldInitializerListContext
return []*exprpb.Expr_CreateStruct_Entry{}
}
initID := p.helper.id(cols[i])
optField := f.(*gen.OptFieldContext)
optional := optField.GetOpt() != nil
if !p.enableOptionalSyntax && optional {
p.reportError(optField, "unsupported syntax '?'")
continue
}
// The field may be empty due to a prior error.
id := optField.IDENTIFIER()
if id == nil {
return []*exprpb.Expr_CreateStruct_Entry{}
}
fieldName := id.GetText()
value := p.Visit(vals[i]).(*exprpb.Expr)
field := p.helper.newObjectField(initID, f.GetText(), value)
field := p.helper.newObjectField(initID, fieldName, value, optional)
result[i] = field
}
return result
}
// Visit a parse tree produced by CELParser#IdentOrGlobalCall.
func (p *parser) VisitIdentOrGlobalCall(ctx *gen.IdentOrGlobalCallContext) interface{} {
func (p *parser) VisitIdentOrGlobalCall(ctx *gen.IdentOrGlobalCallContext) any {
identName := ""
if ctx.GetLeadingDot() != nil {
identName = "."
@ -632,24 +684,20 @@ func (p *parser) VisitIdentOrGlobalCall(ctx *gen.IdentOrGlobalCallContext) inter
identName += id
if ctx.GetOp() != nil {
opID := p.helper.id(ctx.GetOp())
return p.globalCallOrMacro(opID, identName, p.visitList(ctx.GetArgs())...)
return p.globalCallOrMacro(opID, identName, p.visitExprList(ctx.GetArgs())...)
}
return p.helper.newIdent(ctx.GetId(), identName)
}
// Visit a parse tree produced by CELParser#Nested.
func (p *parser) VisitNested(ctx *gen.NestedContext) interface{} {
return p.Visit(ctx.GetE())
}
// Visit a parse tree produced by CELParser#CreateList.
func (p *parser) VisitCreateList(ctx *gen.CreateListContext) interface{} {
func (p *parser) VisitCreateList(ctx *gen.CreateListContext) any {
listID := p.helper.id(ctx.GetOp())
return p.helper.newList(listID, p.visitList(ctx.GetElems())...)
elems, optionals := p.visitListInit(ctx.GetElems())
return p.helper.newList(listID, elems, optionals...)
}
// Visit a parse tree produced by CELParser#CreateStruct.
func (p *parser) VisitCreateStruct(ctx *gen.CreateStructContext) interface{} {
func (p *parser) VisitCreateStruct(ctx *gen.CreateStructContext) any {
structID := p.helper.id(ctx.GetOp())
entries := []*exprpb.Expr_CreateStruct_Entry{}
if ctx.GetEntries() != nil {
@ -658,31 +706,8 @@ func (p *parser) VisitCreateStruct(ctx *gen.CreateStructContext) interface{} {
return p.helper.newMap(structID, entries...)
}
// Visit a parse tree produced by CELParser#ConstantLiteral.
func (p *parser) VisitConstantLiteral(ctx *gen.ConstantLiteralContext) interface{} {
switch ctx.Literal().(type) {
case *gen.IntContext:
return p.VisitInt(ctx.Literal().(*gen.IntContext))
case *gen.UintContext:
return p.VisitUint(ctx.Literal().(*gen.UintContext))
case *gen.DoubleContext:
return p.VisitDouble(ctx.Literal().(*gen.DoubleContext))
case *gen.StringContext:
return p.VisitString(ctx.Literal().(*gen.StringContext))
case *gen.BytesContext:
return p.VisitBytes(ctx.Literal().(*gen.BytesContext))
case *gen.BoolFalseContext:
return p.VisitBoolFalse(ctx.Literal().(*gen.BoolFalseContext))
case *gen.BoolTrueContext:
return p.VisitBoolTrue(ctx.Literal().(*gen.BoolTrueContext))
case *gen.NullContext:
return p.VisitNull(ctx.Literal().(*gen.NullContext))
}
return p.reportError(ctx, "invalid literal")
}
// Visit a parse tree produced by CELParser#mapInitializerList.
func (p *parser) VisitMapInitializerList(ctx *gen.MapInitializerListContext) interface{} {
func (p *parser) VisitMapInitializerList(ctx *gen.MapInitializerListContext) any {
if ctx == nil || ctx.GetKeys() == nil {
// This is the result of a syntax error handled elswhere, return empty.
return []*exprpb.Expr_CreateStruct_Entry{}
@ -697,16 +722,22 @@ func (p *parser) VisitMapInitializerList(ctx *gen.MapInitializerListContext) int
// This is the result of a syntax error detected elsewhere.
return []*exprpb.Expr_CreateStruct_Entry{}
}
key := p.Visit(keys[i]).(*exprpb.Expr)
optKey := keys[i]
optional := optKey.GetOpt() != nil
if !p.enableOptionalSyntax && optional {
p.reportError(optKey, "unsupported syntax '?'")
continue
}
key := p.Visit(optKey.GetE()).(*exprpb.Expr)
value := p.Visit(vals[i]).(*exprpb.Expr)
entry := p.helper.newMapEntry(colID, key, value)
entry := p.helper.newMapEntry(colID, key, value, optional)
result[i] = entry
}
return result
}
// Visit a parse tree produced by CELParser#Int.
func (p *parser) VisitInt(ctx *gen.IntContext) interface{} {
func (p *parser) VisitInt(ctx *gen.IntContext) any {
text := ctx.GetTok().GetText()
base := 10
if strings.HasPrefix(text, "0x") {
@ -724,7 +755,7 @@ func (p *parser) VisitInt(ctx *gen.IntContext) interface{} {
}
// Visit a parse tree produced by CELParser#Uint.
func (p *parser) VisitUint(ctx *gen.UintContext) interface{} {
func (p *parser) VisitUint(ctx *gen.UintContext) any {
text := ctx.GetTok().GetText()
// trim the 'u' designator included in the uint literal.
text = text[:len(text)-1]
@ -741,7 +772,7 @@ func (p *parser) VisitUint(ctx *gen.UintContext) interface{} {
}
// Visit a parse tree produced by CELParser#Double.
func (p *parser) VisitDouble(ctx *gen.DoubleContext) interface{} {
func (p *parser) VisitDouble(ctx *gen.DoubleContext) any {
txt := ctx.GetTok().GetText()
if ctx.GetSign() != nil {
txt = ctx.GetSign().GetText() + txt
@ -755,42 +786,66 @@ func (p *parser) VisitDouble(ctx *gen.DoubleContext) interface{} {
}
// Visit a parse tree produced by CELParser#String.
func (p *parser) VisitString(ctx *gen.StringContext) interface{} {
func (p *parser) VisitString(ctx *gen.StringContext) any {
s := p.unquote(ctx, ctx.GetText(), false)
return p.helper.newLiteralString(ctx, s)
}
// Visit a parse tree produced by CELParser#Bytes.
func (p *parser) VisitBytes(ctx *gen.BytesContext) interface{} {
func (p *parser) VisitBytes(ctx *gen.BytesContext) any {
b := []byte(p.unquote(ctx, ctx.GetTok().GetText()[1:], true))
return p.helper.newLiteralBytes(ctx, b)
}
// Visit a parse tree produced by CELParser#BoolTrue.
func (p *parser) VisitBoolTrue(ctx *gen.BoolTrueContext) interface{} {
func (p *parser) VisitBoolTrue(ctx *gen.BoolTrueContext) any {
return p.helper.newLiteralBool(ctx, true)
}
// Visit a parse tree produced by CELParser#BoolFalse.
func (p *parser) VisitBoolFalse(ctx *gen.BoolFalseContext) interface{} {
func (p *parser) VisitBoolFalse(ctx *gen.BoolFalseContext) any {
return p.helper.newLiteralBool(ctx, false)
}
// Visit a parse tree produced by CELParser#Null.
func (p *parser) VisitNull(ctx *gen.NullContext) interface{} {
func (p *parser) VisitNull(ctx *gen.NullContext) any {
return p.helper.newLiteral(ctx,
&exprpb.Constant{
ConstantKind: &exprpb.Constant_NullValue{
NullValue: structpb.NullValue_NULL_VALUE}})
}
func (p *parser) visitList(ctx gen.IExprListContext) []*exprpb.Expr {
func (p *parser) visitExprList(ctx gen.IExprListContext) []*exprpb.Expr {
if ctx == nil {
return []*exprpb.Expr{}
}
return p.visitSlice(ctx.GetE())
}
func (p *parser) visitListInit(ctx gen.IListInitContext) ([]*exprpb.Expr, []int32) {
if ctx == nil {
return []*exprpb.Expr{}, []int32{}
}
elements := ctx.GetElems()
result := make([]*exprpb.Expr, len(elements))
optionals := []int32{}
for i, e := range elements {
ex := p.Visit(e.GetE()).(*exprpb.Expr)
if ex == nil {
return []*exprpb.Expr{}, []int32{}
}
result[i] = ex
if e.GetOpt() != nil {
if !p.enableOptionalSyntax {
p.reportError(e.GetOpt(), "unsupported syntax '?'")
continue
}
optionals = append(optionals, int32(i))
}
}
return result, optionals
}
func (p *parser) visitSlice(expressions []gen.IExprContext) []*exprpb.Expr {
if expressions == nil {
return []*exprpb.Expr{}
@ -803,26 +858,7 @@ func (p *parser) visitSlice(expressions []gen.IExprContext) []*exprpb.Expr {
return result
}
func (p *parser) extractQualifiedName(e *exprpb.Expr) (string, bool) {
if e == nil {
return "", false
}
switch e.GetExprKind().(type) {
case *exprpb.Expr_IdentExpr:
return e.GetIdentExpr().GetName(), true
case *exprpb.Expr_SelectExpr:
s := e.GetSelectExpr()
if prefix, found := p.extractQualifiedName(s.GetOperand()); found {
return prefix + "." + s.GetField(), true
}
}
// TODO: Add a method to Source to get location from character offset.
location := p.helper.getLocation(e.GetId())
p.reportError(location, "expected a qualified name")
return "", false
}
func (p *parser) unquote(ctx interface{}, value string, isBytes bool) string {
func (p *parser) unquote(ctx any, value string, isBytes bool) string {
text, err := unescape(value, isBytes)
if err != nil {
p.reportError(ctx, "%s", err.Error())
@ -831,7 +867,7 @@ func (p *parser) unquote(ctx interface{}, value string, isBytes bool) string {
return text
}
func (p *parser) reportError(ctx interface{}, format string, args ...interface{}) *exprpb.Expr {
func (p *parser) reportError(ctx any, format string, args ...any) *exprpb.Expr {
var location common.Location
switch ctx.(type) {
case common.Location:
@ -847,10 +883,24 @@ func (p *parser) reportError(ctx interface{}, format string, args ...interface{}
}
// ANTLR Parse listener implementations
func (p *parser) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line, column int, msg string, e antlr.RecognitionException) {
// TODO: Snippet
func (p *parser) SyntaxError(recognizer antlr.Recognizer, offendingSymbol any, line, column int, msg string, e antlr.RecognitionException) {
l := p.helper.source.NewLocation(line, column)
p.errors.syntaxError(l, msg)
// Hack to keep existing error messages consistent with previous versions of CEL when a reserved word
// is used as an identifier. This behavior needs to be overhauled to provide consistent, normalized error
// messages out of ANTLR to prevent future breaking changes related to error message content.
if strings.Contains(msg, "no viable alternative") {
msg = reservedIdentifier.ReplaceAllString(msg, mismatchedReservedIdentifier)
}
// Ensure that no more than 100 syntax errors are reported as this will halt attempts to recover from a
// seriously broken expression.
if p.errorReports < p.errorReportingLimit {
p.errorReports++
p.errors.syntaxError(l, msg)
} else {
tme := &tooManyErrors{errorReportingLimit: p.errorReportingLimit}
p.errors.syntaxError(l, tme.Error())
panic(tme)
}
}
func (p *parser) ReportAmbiguity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr.BitSet, configs antlr.ATNConfigSet) {
@ -892,14 +942,95 @@ func (p *parser) expandMacro(exprID int64, function string, target *exprpb.Expr,
eh.parserHelper = p.helper
eh.id = exprID
expr, err := macro.Expander()(eh, target, args)
// An error indicates that the macro was matched, but the arguments were not well-formed.
if err != nil {
if err.Location != nil {
return p.reportError(err.Location, err.Message), true
}
return p.reportError(p.helper.getLocation(exprID), err.Message), true
}
// A nil value from the macro indicates that the macro implementation decided that
// an expansion should not be performed.
if expr == nil {
return nil, false
}
if p.populateMacroCalls {
p.helper.addMacroCall(expr.GetId(), function, target, args...)
}
return expr, true
}
func (p *parser) checkAndIncrementRecursionDepth() {
p.recursionDepth++
if p.recursionDepth > p.maxRecursionDepth {
panic(&recursionError{message: "max recursion depth exceeded"})
}
}
func (p *parser) decrementRecursionDepth() {
p.recursionDepth--
}
// unnest traverses down the left-hand side of the parse graph until it encounters the first compound
// parse node or the first leaf in the parse graph.
func unnest(tree antlr.ParseTree) antlr.ParseTree {
for tree != nil {
switch t := tree.(type) {
case *gen.ExprContext:
// conditionalOr op='?' conditionalOr : expr
if t.GetOp() != nil {
return t
}
// conditionalOr
tree = t.GetE()
case *gen.ConditionalOrContext:
// conditionalAnd (ops=|| conditionalAnd)*
if t.GetOps() != nil && len(t.GetOps()) > 0 {
return t
}
// conditionalAnd
tree = t.GetE()
case *gen.ConditionalAndContext:
// relation (ops=&& relation)*
if t.GetOps() != nil && len(t.GetOps()) > 0 {
return t
}
// relation
tree = t.GetE()
case *gen.RelationContext:
// relation op relation
if t.GetOp() != nil {
return t
}
// calc
tree = t.Calc()
case *gen.CalcContext:
// calc op calc
if t.GetOp() != nil {
return t
}
// unary
tree = t.Unary()
case *gen.MemberExprContext:
// member expands to one of: primary, select, index, or create message
tree = t.Member()
case *gen.PrimaryExprContext:
// primary expands to one of identifier, nested, create list, create struct, literal
tree = t.Primary()
case *gen.NestedContext:
// contains a nested 'expr'
tree = t.GetE()
case *gen.ConstantLiteralContext:
// expands to a primitive literal
tree = t.Literal()
default:
return t
}
}
return tree
}
var (
reservedIdentifier = regexp.MustCompile("no viable alternative at input '.(true|false|null)'")
mismatchedReservedIdentifier = "mismatched input '$1' expecting IDENTIFIER"
)

View File

@ -106,9 +106,15 @@ func (un *unparser) visitCall(expr *exprpb.Expr) error {
// ternary operator
case operators.Conditional:
return un.visitCallConditional(expr)
// optional select operator
case operators.OptSelect:
return un.visitOptSelect(expr)
// index operator
case operators.Index:
return un.visitCallIndex(expr)
// optional index operator
case operators.OptIndex:
return un.visitCallOptIndex(expr)
// unary operators
case operators.LogicalNot, operators.Negate:
return un.visitCallUnary(expr)
@ -218,6 +224,14 @@ func (un *unparser) visitCallFunc(expr *exprpb.Expr) error {
}
func (un *unparser) visitCallIndex(expr *exprpb.Expr) error {
return un.visitCallIndexInternal(expr, "[")
}
func (un *unparser) visitCallOptIndex(expr *exprpb.Expr) error {
return un.visitCallIndexInternal(expr, "[?")
}
func (un *unparser) visitCallIndexInternal(expr *exprpb.Expr, op string) error {
c := expr.GetCallExpr()
args := c.GetArgs()
nested := isBinaryOrTernaryOperator(args[0])
@ -225,7 +239,7 @@ func (un *unparser) visitCallIndex(expr *exprpb.Expr) error {
if err != nil {
return err
}
un.str.WriteString("[")
un.str.WriteString(op)
err = un.visit(args[1])
if err != nil {
return err
@ -262,6 +276,9 @@ func (un *unparser) visitConst(expr *exprpb.Expr) error {
// represent the float using the minimum required digits
d := strconv.FormatFloat(c.GetDoubleValue(), 'g', -1, 64)
un.str.WriteString(d)
if !strings.Contains(d, ".") {
un.str.WriteString(".0")
}
case *exprpb.Constant_Int64Value:
i := strconv.FormatInt(c.GetInt64Value(), 10)
un.str.WriteString(i)
@ -289,8 +306,15 @@ func (un *unparser) visitIdent(expr *exprpb.Expr) error {
func (un *unparser) visitList(expr *exprpb.Expr) error {
l := expr.GetListExpr()
elems := l.GetElements()
optIndices := make(map[int]bool, len(elems))
for _, idx := range l.GetOptionalIndices() {
optIndices[int(idx)] = true
}
un.str.WriteString("[")
for i, elem := range elems {
if optIndices[i] {
un.str.WriteString("?")
}
err := un.visit(elem)
if err != nil {
return err
@ -303,20 +327,32 @@ func (un *unparser) visitList(expr *exprpb.Expr) error {
return nil
}
func (un *unparser) visitOptSelect(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
args := c.GetArgs()
operand := args[0]
field := args[1].GetConstExpr().GetStringValue()
return un.visitSelectInternal(operand, false, ".?", field)
}
func (un *unparser) visitSelect(expr *exprpb.Expr) error {
sel := expr.GetSelectExpr()
return un.visitSelectInternal(sel.GetOperand(), sel.GetTestOnly(), ".", sel.GetField())
}
func (un *unparser) visitSelectInternal(operand *exprpb.Expr, testOnly bool, op string, field string) error {
// handle the case when the select expression was generated by the has() macro.
if sel.GetTestOnly() {
if testOnly {
un.str.WriteString("has(")
}
nested := !sel.GetTestOnly() && isBinaryOrTernaryOperator(sel.GetOperand())
err := un.visitMaybeNested(sel.GetOperand(), nested)
nested := !testOnly && isBinaryOrTernaryOperator(operand)
err := un.visitMaybeNested(operand, nested)
if err != nil {
return err
}
un.str.WriteString(".")
un.str.WriteString(sel.GetField())
if sel.GetTestOnly() {
un.str.WriteString(op)
un.str.WriteString(field)
if testOnly {
un.str.WriteString(")")
}
return nil
@ -339,6 +375,9 @@ func (un *unparser) visitStructMsg(expr *exprpb.Expr) error {
un.str.WriteString("{")
for i, entry := range entries {
f := entry.GetFieldKey()
if entry.GetOptionalEntry() {
un.str.WriteString("?")
}
un.str.WriteString(f)
un.str.WriteString(": ")
v := entry.GetValue()
@ -360,6 +399,9 @@ func (un *unparser) visitStructMap(expr *exprpb.Expr) error {
un.str.WriteString("{")
for i, entry := range entries {
k := entry.GetMapKey()
if entry.GetOptionalEntry() {
un.str.WriteString("?")
}
err := un.visit(k)
if err != nil {
return err
@ -492,11 +534,10 @@ func (un *unparser) writeOperatorWithWrapping(fun string, unmangled string) bool
un.str.WriteString(" ")
}
return true
} else {
un.str.WriteString(" ")
un.str.WriteString(unmangled)
un.str.WriteString(" ")
}
un.str.WriteString(" ")
un.str.WriteString(unmangled)
un.str.WriteString(" ")
return false
}